From 8dd08d5cb13c9feb4b5a7a5a22009e3eb3eb7079 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Mon, 16 Jan 2023 19:01:10 +0100 Subject: [PATCH 001/233] refactor access to context data --- .../java/carpet/script/CarpetContext.java | 43 ++++++- .../java/carpet/script/CarpetEventServer.java | 4 +- .../java/carpet/script/CarpetScriptHost.java | 4 +- .../java/carpet/script/api/Auxiliary.java | 82 ++++++------- .../carpet/script/api/BlockIterators.java | 2 +- src/main/java/carpet/script/api/Entities.java | 32 ++--- .../java/carpet/script/api/Inventories.java | 24 ++-- .../java/carpet/script/api/Monitoring.java | 2 +- .../java/carpet/script/api/Scoreboards.java | 30 ++--- .../java/carpet/script/api/Threading.java | 6 +- .../java/carpet/script/api/WorldAccess.java | 111 +++++++++--------- .../carpet/script/argument/BlockArgument.java | 12 +- .../java/carpet/script/utils/SystemInfo.java | 66 +++++------ .../java/carpet/script/value/BlockValue.java | 5 +- .../script/value/NBTSerializableValue.java | 10 +- 15 files changed, 239 insertions(+), 194 deletions(-) diff --git a/src/main/java/carpet/script/CarpetContext.java b/src/main/java/carpet/script/CarpetContext.java index 44bbfb4a74..d10ed2ed53 100644 --- a/src/main/java/carpet/script/CarpetContext.java +++ b/src/main/java/carpet/script/CarpetContext.java @@ -3,11 +3,16 @@ import carpet.script.value.Value; import net.minecraft.commands.CommandSourceStack; import net.minecraft.core.BlockPos; +import net.minecraft.core.Registry; +import net.minecraft.core.RegistryAccess; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; public class CarpetContext extends Context { - public CommandSourceStack s; - public final BlockPos origin; + private CommandSourceStack s; + private final BlockPos origin; public CarpetContext(CarpetScriptHost host, CommandSourceStack source) { this(host, source, BlockPos.ZERO); @@ -34,4 +39,38 @@ protected void initialize() variables.put("_y", (c, t) -> Value.ZERO); variables.put("_z", (c, t) -> Value.ZERO); } + + public MinecraftServer server() + { + return s.getServer(); + } + + public ServerLevel level() + { + return s.getLevel(); + } + + public RegistryAccess registryAccess() + { + return s.getLevel().registryAccess(); + } + + public Registry registry(ResourceKey> resourceKey) { + return registryAccess().registryOrThrow(resourceKey); + } + + public CommandSourceStack source() + { + return s; + } + + public BlockPos origin() + { + return origin; + } + + public void swapSource(CommandSourceStack source) + { + s = source; + } } diff --git a/src/main/java/carpet/script/CarpetEventServer.java b/src/main/java/carpet/script/CarpetEventServer.java index 88460509b4..920d84e6dd 100644 --- a/src/main/java/carpet/script/CarpetEventServer.java +++ b/src/main/java/carpet/script/CarpetEventServer.java @@ -167,7 +167,7 @@ public ScheduledCall(CarpetContext context, FunctionValue function, List */ public void execute() { - CarpetServer.scriptServer.events.runScheduledCall(ctx.origin, ctx.s, host, (CarpetScriptHost) ctx.host, function, parametrizedArgs); + CarpetServer.scriptServer.events.runScheduledCall(ctx.origin(), ctx.source(), host, (CarpetScriptHost) ctx.host, function, parametrizedArgs); } } @@ -1315,7 +1315,7 @@ public int signalEvent(String event, CarpetContext cc, ServerPlayer optionalTarg { Event ev = Event.getEvent(event, ((CarpetScriptHost)cc.host).scriptServer()); if (ev == null) return -1; - return ev.handler.signal(cc.s, optionalTarget, callArgs); + return ev.handler.signal(cc.source(), optionalTarget, callArgs); } private void onEventAddedToHost(Event event, ScriptHost host) diff --git a/src/main/java/carpet/script/CarpetScriptHost.java b/src/main/java/carpet/script/CarpetScriptHost.java index 76c394cfc8..4ce39f4467 100644 --- a/src/main/java/carpet/script/CarpetScriptHost.java +++ b/src/main/java/carpet/script/CarpetScriptHost.java @@ -579,9 +579,9 @@ protected Module getModuleOrLibraryByName(String name) protected void runModuleCode(Context c, Module module) { CarpetContext cc = (CarpetContext)c; - CarpetExpression ex = new CarpetExpression(module, module.code(), cc.s, cc.origin); + CarpetExpression ex = new CarpetExpression(module, module.code(), cc.source(), cc.origin()); ex.getExpr().asATextSource(); - ex.scriptRunCommand(this, cc.origin); + ex.scriptRunCommand(this, cc.origin()); } @Override diff --git a/src/main/java/carpet/script/api/Auxiliary.java b/src/main/java/carpet/script/api/Auxiliary.java index 7741cf8627..de9b76e206 100644 --- a/src/main/java/carpet/script/api/Auxiliary.java +++ b/src/main/java/carpet/script/api/Auxiliary.java @@ -167,8 +167,9 @@ public static void apply(Expression expression) Vec3 vec = locator.vec; double d0 = Math.pow(volume > 1.0F ? (double)(volume * 16.0F) : 16.0D, 2.0D); int count = 0; - long seed = cc.s.getLevel().getRandom().nextLong(); - for (ServerPlayer player : cc.s.getLevel().getPlayers( (p) -> p.distanceToSqr(vec) < d0)) + final ServerLevel level = cc.level(); + long seed = level.getRandom().nextLong(); + for (ServerPlayer player : level.getPlayers( (p) -> p.distanceToSqr(vec) < d0)) { count++; player.connection.send(new ClientboundSoundPacket(soundHolder, mixer, vec.x, vec.y, vec.z, volume, pitch, seed)); @@ -180,8 +181,8 @@ public static void apply(Expression expression) { CarpetContext cc = (CarpetContext)c; if (lv.size() == 0) return ListValue.wrap(BuiltInRegistries.PARTICLE_TYPE.keySet().stream().map(ValueConversions::of)); - MinecraftServer ms = cc.s.getServer(); - ServerLevel world = cc.s.getLevel(); + MinecraftServer ms = cc.server(); + ServerLevel world = cc.level(); Vector3Argument locator = Vector3Argument.findIn(lv, 1); String particleName = lv.get(0).getString(); int count = 10; @@ -227,7 +228,7 @@ public static void apply(Expression expression) expression.addContextFunction("particle_line", -1, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; - ServerLevel world = cc.s.getLevel(); + ServerLevel world = cc.level(); String particleName = lv.get(0).getString(); ParticleOptions particle = ShapeDispatcher.getParticleData(particleName, world.registryAccess()); Vector3Argument pos1 = Vector3Argument.findIn(lv, 1); @@ -252,7 +253,7 @@ public static void apply(Expression expression) } else { - player = cc.s.getServer().getPlayerList().getPlayerByName(playerValue.getString()); + player = cc.server().getPlayerList().getPlayerByName(playerValue.getString()); } } } @@ -263,12 +264,12 @@ public static void apply(Expression expression) )); }); - expression.addContextFunction("item_display_name", 1, (c, t, lv) -> new FormattedTextValue(ValueConversions.getItemStackFromValue(lv.get(0), false, ((CarpetContext)c).s.registryAccess() ).getHoverName())); + expression.addContextFunction("item_display_name", 1, (c, t, lv) -> new FormattedTextValue(ValueConversions.getItemStackFromValue(lv.get(0), false, ((CarpetContext)c).registryAccess()).getHoverName())); expression.addContextFunction("particle_box", -1, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; - ServerLevel world = cc.s.getLevel(); + ServerLevel world = cc.level(); String particleName = lv.get(0).getString(); ParticleOptions particle = ShapeDispatcher.getParticleData(particleName, world.registryAccess() ); Vector3Argument pos1 = Vector3Argument.findIn(lv, 1); @@ -294,7 +295,7 @@ public static void apply(Expression expression) } else { - player = cc.s.getServer().getPlayerList().getPlayerByName(playerValue.getString()); + player = cc.server().getPlayerList().getPlayerByName(playerValue.getString()); } } } @@ -315,7 +316,7 @@ public static void apply(Expression expression) expression.addContextFunction("draw_shape", -1, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; - ServerLevel world = cc.s.getLevel(); + ServerLevel world = cc.level(); MinecraftServer server = world.getServer(); Set playerTargets = new HashSet<>(); List shapes = new ArrayList<>(); @@ -335,7 +336,7 @@ public static void apply(Expression expression) } ShapeDispatcher.sendShape( - (playerTargets.isEmpty())?cc.s.getLevel().players():playerTargets, + (playerTargets.isEmpty())?cc.level().players():playerTargets, shapes ); return Value.TRUE; @@ -366,8 +367,8 @@ public static void apply(Expression expression) { throw new InternalExpressionException("'create_marker' requires a name and three coordinates, with optional direction, and optional block on its head"); } - - ArmorStand armorstand = new ArmorStand(EntityType.ARMOR_STAND, cc.s.getLevel()); + Level level = cc.level(); + ArmorStand armorstand = new ArmorStand(EntityType.ARMOR_STAND, level); double yoffset; if (targetBlock == null && name == null) { @@ -410,7 +411,7 @@ else if (!interactable && targetBlock == null) armorstand.setInvisible(true); armorstand.setInvulnerable(true); armorstand.getEntityData().set(ArmorStand.DATA_CLIENT_FLAGS, (byte)(interactable?8 : 16|8)); - cc.s.getLevel().addFreshEntity(armorstand); + level.addFreshEntity(armorstand); return new EntityValue(armorstand); }); @@ -418,7 +419,7 @@ else if (!interactable && targetBlock == null) CarpetContext cc = (CarpetContext)c; int total = 0; String markerName = MARKER_STRING+"_"+((cc.host.getName()==null)?"":cc.host.getName()); - for (Entity e : cc.s.getLevel().getEntities(EntityType.ARMOR_STAND, (as) -> as.getTags().contains(markerName))) + for (Entity e : cc.level().getEntities(EntityType.ARMOR_STAND, (as) -> as.getTags().contains(markerName))) { total ++; e.discard(); // discard // remove(); @@ -468,7 +469,7 @@ else if (!interactable && targetBlock == null) expression.addContextFunction("print", -1, (c, t, lv) -> { if (lv.size() == 0 || lv.size() > 2) throw new InternalExpressionException("'print' takes one or two arguments"); - CommandSourceStack s = ((CarpetContext)c).s; + CommandSourceStack s = ((CarpetContext)c).source(); MinecraftServer server = s.getServer(); Value res = lv.get(0); List targets = null; @@ -500,7 +501,7 @@ else if (!interactable && targetBlock == null) if (lv.size() < 2) throw new InternalExpressionException("'display_title' needs at least a target, type and message, and optionally times"); Value pVal = lv.get(0); if (!(pVal instanceof ListValue)) pVal = ListValue.of(pVal); - MinecraftServer server = ((CarpetContext)c).s.getServer(); + MinecraftServer server = ((CarpetContext)c).server(); Stream targets = ((ListValue) pVal).getItems().stream().map(v -> { ServerPlayer player = EntityValue.getPlayerByValue(server, v); @@ -574,7 +575,7 @@ else if (!interactable && targetBlock == null) map.put(target.getScoreboardName(), (MutableComponent) title); total.getAndIncrement(); }); - HUDController.update_hud(((CarpetContext)c).s.getServer(), targetList); + HUDController.update_hud(((CarpetContext)c).server(), targetList); return NumericValue.of(total.get()); } ClientboundSetTitlesAnimationPacket timesPacket; // TimesPacket @@ -609,7 +610,7 @@ else if (!interactable && targetBlock == null) expression.addContextFunction("run", 1, (c, t, lv) -> { - CommandSourceStack s = ((CarpetContext)c).s; + CommandSourceStack s = ((CarpetContext)c).source(); try { Component[] error = {null}; @@ -632,7 +633,7 @@ else if (!interactable && targetBlock == null) expression.addContextFunction("save", 0, (c, t, lv) -> { - CommandSourceStack s = ((CarpetContext)c).s; + CommandSourceStack s = ((CarpetContext)c).source(); s.getServer().getPlayerList().saveAll(); s.getServer().saveAllChunks(true,true,true); for (ServerLevel world : s.getServer().getAllLevels()) @@ -644,21 +645,21 @@ else if (!interactable && targetBlock == null) }); expression.addContextFunction("tick_time", 0, (c, t, lv) -> - new NumericValue(((CarpetContext) c).s.getServer().getTickCount())); + new NumericValue(((CarpetContext) c).server().getTickCount())); expression.addContextFunction("world_time", 0, (c, t, lv) -> { c.host.issueDeprecation("world_time()"); - return new NumericValue(((CarpetContext) c).s.getLevel().getGameTime()); + return new NumericValue(((CarpetContext) c).level().getGameTime()); }); expression.addContextFunction("day_time", -1, (c, t, lv) -> { - Value time = new NumericValue(((CarpetContext) c).s.getLevel().getDayTime()); + Value time = new NumericValue(((CarpetContext) c).level().getDayTime()); if (lv.size() > 0) { long newTime = NumericValue.asNumber(lv.get(0)).getLong(); if (newTime < 0) newTime = 0; - ((CarpetContext) c).s.getLevel().setDayTime(newTime);// setTimeOfDay(newTime); + ((CarpetContext) c).level().setDayTime(newTime); } return time; }); @@ -672,14 +673,15 @@ else if (!interactable && targetBlock == null) expression.addContextFunction("game_tick", -1, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; - CommandSourceStack s = cc.s; + //CommandSourceStack s = cc.source(); + MinecraftServer server = cc.server(); if (CarpetServer.scriptServer == null) return Value.NULL; - if (!s.getServer().isSameThread()) throw new InternalExpressionException("Unable to run ticks from threads"); + if (!server.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 { CarpetServer.scriptServer.tickDepth ++; - ((MinecraftServerInterface) s.getServer()).forceTick(() -> System.nanoTime() - CarpetServer.scriptServer.tickStart < 50000000L); + ((MinecraftServerInterface) server).forceTick(() -> System.nanoTime() - CarpetServer.scriptServer.tickStart < 50000000L); if (lv.size() > 0) { long ms_total = NumericValue.asNumber(lv.get(0)).getLong(); @@ -710,7 +712,7 @@ else if (!interactable && targetBlock == null) }); expression.addContextFunction("seed", -1, (c, t, lv) -> { - CommandSourceStack s = ((CarpetContext)c).s; + CommandSourceStack s = ((CarpetContext)c).source(); c.host.issueDeprecation("seed()"); return new NumericValue(s.getLevel().getSeed()); }); @@ -720,7 +722,7 @@ else if (!interactable && targetBlock == null) CarpetContext cc = (CarpetContext) c; BlockArgument locator = BlockArgument.findIn(cc, lv, 0); BlockPos pos = locator.block.getPos(); - ServerLevel world = cc.s.getLevel(); + ServerLevel world = cc.level(); ((ThreadedAnvilChunkStorageInterface) world.getChunkSource().chunkMap).relightChunk(new ChunkPos(pos)); WorldTools.forceChunkUpdate(pos, world); return Value.TRUE; @@ -728,22 +730,22 @@ else if (!interactable && targetBlock == null) // Should this be deprecated for system_info('source_dimension')? expression.addContextFunction("current_dimension", 0, (c, t, lv) -> - ValueConversions.of( ((CarpetContext)c).s.getLevel())); + ValueConversions.of( ((CarpetContext)c).level())); expression.addContextFunction("view_distance", 0, (c, t, lv) -> { c.host.issueDeprecation("view_distance()"); - return new NumericValue(((CarpetContext)c).s.getServer().getPlayerList().getViewDistance()); + return new NumericValue(((CarpetContext)c).server().getPlayerList().getViewDistance()); }); // lazy due to passthrough and context changing ability expression.addLazyFunction("in_dimension", 2, (c, t, lv) -> { - CommandSourceStack outerSource = ((CarpetContext)c).s; + CommandSourceStack outerSource = ((CarpetContext)c).source(); Value dimensionValue = lv.get(0).evalValue(c); 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; + ((CarpetContext) newCtx).swapSource(innerSource); newCtx.variables = c.variables; Value retval = lv.get(1).evalValue(newCtx); return (cc, tt) -> retval; @@ -754,7 +756,7 @@ else if (!interactable && targetBlock == null) { Map plopData = new HashMap<>(); CarpetContext cc = (CarpetContext)c; - RegistryAccess registryManager = cc.s.getLevel().registryAccess(); + RegistryAccess registryManager = cc.registryAccess(); plopData.put(StringValue.of("scarpet_custom"), ListValue.wrap(FeatureGenerator.featureMap.keySet().stream().sorted().map(StringValue::of).collect(Collectors.toList())) ); @@ -777,14 +779,14 @@ else if (!interactable && targetBlock == null) 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().executeBlocking( () -> + ((CarpetContext)c).server().executeBlocking( () -> { - Boolean res = FeatureGenerator.plop(what, ((CarpetContext) c).s.getLevel(), locator.block.getPos()); + Boolean res = FeatureGenerator.plop(what, ((CarpetContext) c).level(), locator.block.getPos()); if (res == null) return; if (what.equalsIgnoreCase("forest_rock")) // there might be more of those - WorldTools.forceChunkUpdate(locator.block.getPos(), ((CarpetContext) c).s.getLevel()); + WorldTools.forceChunkUpdate(locator.block.getPos(), ((CarpetContext) c).level()); result[0] = BooleanValue.of(res); }); return result[0]; @@ -958,7 +960,7 @@ else if (fdesc.type == FileArgument.Type.JSON) expression.addContextFunction("statistic", 3, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; - ServerPlayer player = EntityValue.getPlayerByValue(cc.s.getServer(), lv.get(0)); + ServerPlayer player = EntityValue.getPlayerByValue(cc.server(), lv.get(0)); if (player == null) return Value.NULL; ResourceLocation category; ResourceLocation statName; @@ -1012,7 +1014,7 @@ else if (fdesc.type == FileArgument.Type.JSON) 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; - CommandStorage storage = cc.s.getServer().getCommandStorage(); + CommandStorage storage = cc.server().getCommandStorage(); if (lv.size() == 0) return ListValue.wrap(storage.keys().map(i -> new StringValue(nameFromRegistryId(i))).collect(Collectors.toList())); String key = lv.get(0).getString(); @@ -1031,7 +1033,7 @@ else if (fdesc.type == FileArgument.Type.JSON) CarpetContext cc = (CarpetContext)c; String origName = lv.get(0).getString(); String name = InputValidator.validateSimpleString(origName, true); - MinecraftServer server = cc.s.getServer(); + MinecraftServer server = cc.server(); for (String dpName : server.getPackRepository().getAvailableIds()) { if (dpName.equalsIgnoreCase("file/"+name+".zip") || diff --git a/src/main/java/carpet/script/api/BlockIterators.java b/src/main/java/carpet/script/api/BlockIterators.java index 05f0956531..d5ee8ac6b7 100644 --- a/src/main/java/carpet/script/api/BlockIterators.java +++ b/src/main/java/carpet/script/api/BlockIterators.java @@ -216,7 +216,7 @@ public static void apply(Expression expression) expression.addContextFunction("neighbours", -1, (c, t, lv)-> { BlockPos center = BlockArgument.findIn((CarpetContext) c, lv,0).block.getPos(); - ServerLevel world = ((CarpetContext) c).s.getLevel(); + ServerLevel world = ((CarpetContext) c).level(); List neighbours = new ArrayList<>(); neighbours.add(new BlockValue(null, world, center.above())); diff --git a/src/main/java/carpet/script/api/Entities.java b/src/main/java/carpet/script/api/Entities.java index ac44a500ef..70f9eb3952 100644 --- a/src/main/java/carpet/script/api/Entities.java +++ b/src/main/java/carpet/script/api/Entities.java @@ -42,7 +42,7 @@ public class Entities { private static ListValue getPlayersFromWorldMatching(Context c, Predicate condition) { List ret = new ArrayList<>(); - for (ServerPlayer player: ((CarpetContext) c).s.getLevel().players()) { + for (ServerPlayer player: ((CarpetContext) c).level().players()) { if (condition.test(player)) { ret.add(new EntityValue(player)); } @@ -59,20 +59,20 @@ public static void apply(Expression expression) CarpetContext cc = (CarpetContext)c; if (cc.host.user != null) { - ServerPlayer player = cc.s.getServer().getPlayerList().getPlayerByName(cc.host.user); + ServerPlayer player = cc.server().getPlayerList().getPlayerByName(cc.host.user); return EntityValue.of(player); } - Entity callingEntity = cc.s.getEntity(); + Entity callingEntity = cc.source().getEntity(); 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); + Vec3 pos = ((CarpetContext)c).source().getPosition(); + Player closestPlayer = ((CarpetContext)c).level().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 ret = new ArrayList<>(); - for (ServerPlayer player: ((CarpetContext)c).s.getServer().getPlayerList().getPlayers()) + for (ServerPlayer player: ((CarpetContext)c).server().getPlayerList().getPlayers()) ret.add(new EntityValue(player)); yield ListValue.wrap(ret); } @@ -82,7 +82,7 @@ public static void apply(Expression expression) case "spectating" -> getPlayersFromWorldMatching(c, ServerPlayer::isSpectator); case "!spectating" -> getPlayersFromWorldMatching(c, p -> !p.isSpectator()); default -> { - ServerPlayer player = ((CarpetContext) c).s.getServer().getPlayerList().getPlayerByName(playerName); + ServerPlayer player = ((CarpetContext) c).server().getPlayerList().getPlayerByName(playerName); if (player != null) { yield new EntityValue(player); } @@ -127,7 +127,7 @@ public static void apply(Expression expression) tag.putString("id", entityId.toString()); Vec3 vec3d = position.vec; - ServerLevel serverWorld = cc.s.getLevel(); + ServerLevel serverWorld = cc.level(); 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; @@ -146,14 +146,14 @@ public static void apply(Expression expression) { Value who = lv.get(0); if (who instanceof NumericValue) - return EntityValue.of(((CarpetContext)c).s.getLevel().getEntity((int)((NumericValue) who).getLong())); - return EntityValue.of(((CarpetContext)c).s.getLevel().getEntity(UUID.fromString(who.getString()))); + return EntityValue.of(((CarpetContext)c).level().getEntity((int)((NumericValue) who).getLong())); + return EntityValue.of(((CarpetContext)c).level().getEntity(UUID.fromString(who.getString()))); }); expression.addContextFunction("entity_list", 1, (c, t, lv) -> { String who = lv.get(0).getString(); - CommandSourceStack source = ((CarpetContext)c).s; + CommandSourceStack source = ((CarpetContext)c).source(); EntityValue.EntityClassDescriptor eDesc = EntityValue.getEntityDescriptor(who, source.getServer()); List entityList = source.getLevel().getEntities(eDesc.directType, eDesc.filteringPredicate); return ListValue.wrap(entityList.stream().map(EntityValue::new).collect(Collectors.toList())); @@ -182,8 +182,8 @@ public static void apply(Expression expression) throw new InternalExpressionException("Range of 'entity_area' cannot come from a block argument"); Vec3 range = rangeLocator.vec; AABB area = centerBox.inflate(range.x, range.y, range.z); - EntityValue.EntityClassDescriptor eDesc = EntityValue.getEntityDescriptor(who, cc.s.getServer()); - List entityList = cc.s.getLevel().getEntities(eDesc.directType, area,eDesc.filteringPredicate); + EntityValue.EntityClassDescriptor eDesc = EntityValue.getEntityDescriptor(who, cc.server()); + List entityList = cc.level().getEntities(eDesc.directType, area,eDesc.filteringPredicate); return ListValue.wrap(entityList.stream().map(EntityValue::new).collect(Collectors.toList())); }); @@ -191,7 +191,7 @@ public static void apply(Expression expression) { String selector = lv.get(0).getString(); List retlist = new ArrayList<>(); - for (Entity e: EntityValue.getEntitiesFromSelector(((CarpetContext)c).s, selector)) + for (Entity e: EntityValue.getEntitiesFromSelector(((CarpetContext)c).source(), selector)) { retlist.add(new EntityValue(e)); } @@ -244,7 +244,7 @@ else if (lv.size()==3) { if (lv.size() > 1) throw new InternalExpressionException("'entity_types' requires one or no arguments"); String desc = (lv.size() == 1)?lv.get(0).getString():"*"; - return EntityValue.getEntityDescriptor(desc, ((CarpetContext) c).s.getServer()).listValue(); + return EntityValue.getEntityDescriptor(desc, ((CarpetContext) c).server()).listValue(); }); expression.addContextFunction("entity_load_handler", -1, (c, t, lv) -> @@ -255,7 +255,7 @@ else if (lv.size()==3) ? ((ListValue) entityValue).getItems().stream().map(Value::getString).collect(Collectors.toList()) : Collections.singletonList(entityValue.getString()); Set> types = new HashSet<>(); - descriptors.forEach(s -> types.addAll(EntityValue.getEntityDescriptor(s, ((CarpetContext) c).s.getServer()).types)); + descriptors.forEach(s -> types.addAll(EntityValue.getEntityDescriptor(s, ((CarpetContext) c).server()).types)); FunctionArgument funArg = FunctionArgument.findIn(c, expression.module, lv, 1, true, false); CarpetEventServer events = ((CarpetScriptHost)c.host).scriptServer().events; if (funArg.function == null) diff --git a/src/main/java/carpet/script/api/Inventories.java b/src/main/java/carpet/script/api/Inventories.java index 1770fad6e0..8175cd221c 100644 --- a/src/main/java/carpet/script/api/Inventories.java +++ b/src/main/java/carpet/script/api/Inventories.java @@ -56,7 +56,7 @@ public class Inventories { public static void apply(Expression expression) { expression.addContextFunction("stack_limit", 1, (c, t, lv) -> - new NumericValue(NBTSerializableValue.parseItem(lv.get(0).getString(), ((CarpetContext) c).s.registryAccess() ).getItem().getMaxStackSize())); + new NumericValue(NBTSerializableValue.parseItem(lv.get(0).getString(), ((CarpetContext) c).registryAccess() ).getItem().getMaxStackSize())); expression.addContextFunction("item_category", -1, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; @@ -69,7 +69,7 @@ public static void apply(Expression expression) if (lv.size() == 0) return ListValue.wrap(BuiltInRegistries.ITEM.keySet().stream().map(ValueConversions::of).collect(Collectors.toList())); CarpetContext cc = (CarpetContext)c; - Registry items = cc.s.getServer().registryAccess().registryOrThrow(Registries.ITEM); + Registry items = cc.registry(Registries.ITEM); String tag = lv.get(0).getString(); Optional> itemTag = items.getTag(TagKey.create(Registries.ITEM, InputValidator.identifierOf(tag))); if (itemTag.isEmpty()) return Value.NULL; @@ -87,10 +87,10 @@ public static void apply(Expression expression) { CarpetContext cc = (CarpetContext)c; - Registry blocks = cc.s.getServer().registryAccess().registryOrThrow(Registries.ITEM); + Registry blocks = cc.registry(Registries.ITEM); if (lv.size() == 0) return ListValue.wrap(blocks.getTagNames().map(ValueConversions::of).collect(Collectors.toList())); - Item item = NBTSerializableValue.parseItem(lv.get(0).getString(), cc.s.registryAccess()).getItem(); + Item item = NBTSerializableValue.parseItem(lv.get(0).getString(), cc.registryAccess()).getItem(); if (lv.size() == 1) { return ListValue.wrap( blocks.getTags().filter(e -> e.getSecond().stream().anyMatch(h -> (h.value() == item))).map(e -> ValueConversions.of(e.getFirst())).collect(Collectors.toList())); @@ -128,7 +128,7 @@ public static void apply(Expression expression) type = BuiltInRegistries.RECIPE_TYPE.get(InputValidator.identifierOf(recipeType)); } List> recipes; - recipes = ((RecipeManagerInterface) cc.s.getServer().getRecipeManager()).getAllMatching(type, InputValidator.identifierOf(recipeName)); + recipes = ((RecipeManagerInterface) cc.server().getRecipeManager()).getAllMatching(type, InputValidator.identifierOf(recipeName)); if (recipes.isEmpty()) return Value.NULL; List recipesOutput = new ArrayList<>(); @@ -279,7 +279,7 @@ else if (nbtValue.isNull()) else nbt = new NBTSerializableValue(nbtValue.getString()).getCompoundTag(); } - ItemInput newitem = NBTSerializableValue.parseItem(lv.get(inventoryLocator.offset()+2).getString(), nbt, cc.s.registryAccess()); + ItemInput newitem = NBTSerializableValue.parseItem(lv.get(inventoryLocator.offset()+2).getString(), nbt, cc.registryAccess()); ItemStack previousStack = inventoryLocator.inventory().getItem(slot); try { @@ -304,7 +304,7 @@ else if (nbtValue.isNull()) { Value secondArg = lv.get(inventoryLocator.offset()+0); if (!secondArg.isNull()) - itemArg = NBTSerializableValue.parseItem(secondArg.getString(), cc.s.registryAccess()); + itemArg = NBTSerializableValue.parseItem(secondArg.getString(), cc.registryAccess()); } int startIndex = 0; if (lv.size() > inventoryLocator.offset()+1) @@ -329,7 +329,7 @@ else if (nbtValue.isNull()) if (inventoryLocator == null) return Value.NULL; if (lv.size() <= inventoryLocator.offset()) throw new InternalExpressionException("'inventory_remove' requires at least an item to be removed"); - ItemInput searchItem = NBTSerializableValue.parseItem(lv.get(inventoryLocator.offset()).getString(), cc.s.registryAccess()); + ItemInput searchItem = NBTSerializableValue.parseItem(lv.get(inventoryLocator.offset()).getString(), cc.registryAccess()); int amount = 1; if (lv.size() > inventoryLocator.offset()+1) amount = (int)NumericValue.asNumber(lv.get(inventoryLocator.offset()+1)).getLong(); @@ -398,14 +398,14 @@ else if (owner instanceof LivingEntity villager) 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); + cc.level().addFreshEntity(item); } else { Vec3 point = Vec3.atCenterOf(inventoryLocator.position()); //pos+0.5v - item = new ItemEntity(cc.s.getLevel(), point.x, point.y, point.z, droppedStack); + item = new ItemEntity(cc.level(), point.x, point.y, point.z, droppedStack); item.setDefaultPickUpDelay(); - cc.s.getLevel().addFreshEntity(item); + cc.level().addFreshEntity(item); } return new NumericValue(item.getItem().getCount()); }); @@ -414,7 +414,7 @@ else if (owner instanceof LivingEntity villager) { if(lv.size() < 3) throw new InternalExpressionException("'create_screen' requires at least three arguments"); Value playerValue = lv.get(0); - ServerPlayer player = EntityValue.getPlayerByValue(((CarpetContext) c).s.getServer(), playerValue); + ServerPlayer player = EntityValue.getPlayerByValue(((CarpetContext) c).server(), playerValue); if(player == null) throw new InternalExpressionException("'create_screen' requires a valid online player as the first argument."); String type = lv.get(1).getString(); Component name = FormattedTextValue.getTextByValue(lv.get(2)); diff --git a/src/main/java/carpet/script/api/Monitoring.java b/src/main/java/carpet/script/api/Monitoring.java index d32347346f..bf8344d874 100644 --- a/src/main/java/carpet/script/api/Monitoring.java +++ b/src/main/java/carpet/script/api/Monitoring.java @@ -47,7 +47,7 @@ public static void apply(Expression expression) expression.addContextFunction("get_mob_counts", -1, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; - ServerLevel world = cc.s.getLevel(); + ServerLevel world = cc.level(); NaturalSpawner.SpawnState info = world.getChunkSource().getLastSpawnState(); if (info == null) return Value.NULL; Object2IntMap mobcounts = info.getMobCategoryCounts(); diff --git a/src/main/java/carpet/script/api/Scoreboards.java b/src/main/java/carpet/script/api/Scoreboards.java index 4dfb2384d5..1d5cf31011 100644 --- a/src/main/java/carpet/script/api/Scoreboards.java +++ b/src/main/java/carpet/script/api/Scoreboards.java @@ -65,7 +65,7 @@ public static void apply(Expression expression) expression.addContextFunction("scoreboard", -1, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; - Scoreboard scoreboard = cc.s.getServer().getScoreboard(); + Scoreboard scoreboard = cc.server().getScoreboard(); if (lv.size()==0) return ListValue.wrap(scoreboard.getObjectiveNames().stream().map(StringValue::new).collect(Collectors.toList())); String objectiveName = lv.get(0).getString(); @@ -98,7 +98,7 @@ public static void apply(Expression expression) { if (lv.size()==0) throw new InternalExpressionException("'scoreboard_remove' requires at least one parameter"); CarpetContext cc = (CarpetContext)c; - Scoreboard scoreboard = cc.s.getServer().getScoreboard(); + Scoreboard scoreboard = cc.server().getScoreboard(); String objectiveName = lv.get(0).getString(); Objective objective = scoreboard.getOrCreateObjective(objectiveName); if (objective == null) return Value.FALSE; @@ -121,7 +121,7 @@ public static void apply(Expression expression) expression.addContextFunction("scoreboard_add", -1, (c, t, lv)-> { CarpetContext cc = (CarpetContext)c; - Scoreboard scoreboard = cc.s.getServer().getScoreboard(); + Scoreboard scoreboard = cc.server().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(); ObjectiveCriteria criterion; @@ -159,7 +159,7 @@ public static void apply(Expression expression) { if(lv.size() < 2) throw new InternalExpressionException("'scoreboard_property' requires at least two parameters"); CarpetContext cc = (CarpetContext)c; - Scoreboard scoreboard = cc.s.getServer().getScoreboard(); + Scoreboard scoreboard = cc.server().getScoreboard(); Objective objective = scoreboard.getOrCreateObjective(lv.get(0).getString()); if(objective == null) return Value.NULL; @@ -224,7 +224,7 @@ public static void apply(Expression expression) expression.addContextFunction("scoreboard_display", 2, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; - Scoreboard scoreboard = cc.s.getServer().getScoreboard(); + Scoreboard scoreboard = cc.server().getScoreboard(); String location = lv.get(0).getString(); int slot = Scoreboard.getDisplaySlotByName(location); if (slot < 0) throw new InternalExpressionException("Invalid objective slot: "+location); @@ -245,7 +245,7 @@ public static void apply(Expression expression) { if(lv.size() > 1) throw new InternalExpressionException("'team_list' requires zero or one parameters"); CarpetContext cc = (CarpetContext)c; - ServerScoreboard scoreboard = cc.s.getServer().getScoreboard(); + ServerScoreboard scoreboard = cc.server().getScoreboard(); if(lv.size() == 0) return ListValue.wrap(scoreboard.getTeamNames().stream().map(StringValue::of).collect(Collectors.toList())); if (lv.size() != 1) return Value.NULL; @@ -260,7 +260,7 @@ public static void apply(Expression expression) if(!(lv.size() < 3 && lv.size() > 0)) throw new InternalExpressionException("'team_add' requires one or two parameters"); CarpetContext cc = (CarpetContext)c; - ServerScoreboard scoreboard = cc.s.getServer().getScoreboard(); + ServerScoreboard scoreboard = cc.server().getScoreboard(); String teamName = lv.get(0).getString(); if(lv.size() == 1) @@ -283,7 +283,7 @@ public static void apply(Expression expression) expression.addContextFunction("team_remove", 1, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; - ServerScoreboard scoreboard = cc.s.getServer().getScoreboard(); + ServerScoreboard scoreboard = cc.server().getScoreboard(); Value teamVal = lv.get(0); String team = teamVal.getString(); if(scoreboard.getPlayerTeam(team) == null) return Value.NULL; @@ -295,7 +295,7 @@ public static void apply(Expression expression) expression.addContextFunction("team_leave", 1, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; - ServerScoreboard scoreboard = cc.s.getServer().getScoreboard(); + ServerScoreboard scoreboard = cc.server().getScoreboard(); Value playerVal = lv.get(0); String player = EntityValue.getPlayerNameByValue(playerVal); if(player == null) return Value.NULL; @@ -305,7 +305,7 @@ public static void apply(Expression expression) expression.addContextFunction("team_property", -1, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; - ServerScoreboard scoreboard = cc.s.getServer().getScoreboard(); + ServerScoreboard scoreboard = cc.server().getScoreboard(); if(lv.size() < 2 || lv.size() > 3) throw new InternalExpressionException("'team_property' requires two or three arguments"); @@ -396,7 +396,7 @@ public static void apply(Expression expression) expression.addContextFunction("bossbar", -1, (c, t, lv) -> { - CustomBossEvents bossBarManager = ((CarpetContext)c).s.getServer().getCustomBossEvents(); + CustomBossEvents bossBarManager = ((CarpetContext)c).server().getCustomBossEvents(); if(lv.size() > 3) throw new InternalExpressionException("'bossbar' accepts max three arguments"); if(lv.size() == 0) return ListValue.wrap(bossBarManager.getEvents().stream().map(CustomBossEvent::getTextId).map(ResourceLocation::toString).map(StringValue::of).collect(Collectors.toList())); @@ -446,13 +446,13 @@ public static void apply(Expression expression) if(propertyValue instanceof ListValue) { ((ListValue) propertyValue).getItems().forEach((v)->{ - ServerPlayer player = EntityValue.getPlayerByValue(((CarpetContext)c).s.getServer(),propertyValue); + ServerPlayer player = EntityValue.getPlayerByValue(((CarpetContext)c).server(), propertyValue); if(player != null) bossBar.addPlayer(player); }); return Value.TRUE; } - ServerPlayer player = EntityValue.getPlayerByValue(((CarpetContext) c).s.getServer(), propertyValue); + ServerPlayer player = EntityValue.getPlayerByValue(((CarpetContext) c).server(), propertyValue); if(player != null) { bossBar.addPlayer(player); return Value.TRUE; @@ -464,14 +464,14 @@ public static void apply(Expression expression) { bossBar.removeAllPlayers(); ((ListValue) propertyValue).getItems().forEach((v) -> { - ServerPlayer p = EntityValue.getPlayerByValue(((CarpetContext) c).s.getServer(), v); + ServerPlayer p = EntityValue.getPlayerByValue(((CarpetContext) c).server(), v); if (p != null) bossBar.addPlayer(p); }); return Value.TRUE; } - ServerPlayer p = EntityValue.getPlayerByValue(((CarpetContext) c).s.getServer(), propertyValue); + ServerPlayer p = EntityValue.getPlayerByValue(((CarpetContext) c).server(), propertyValue); bossBar.removeAllPlayers(); if (p != null) { bossBar.addPlayer(p); diff --git a/src/main/java/carpet/script/api/Threading.java b/src/main/java/carpet/script/api/Threading.java index e62c504ea4..54f55c5622 100644 --- a/src/main/java/carpet/script/api/Threading.java +++ b/src/main/java/carpet/script/api/Threading.java @@ -16,7 +16,7 @@ public static void apply(Expression expression) { //"overidden" native call to cancel if on main thread expression.addContextFunction("task_join", 1, (c, t, lv) -> { - if (((CarpetContext)c).s.getServer().isSameThread()) + if (((CarpetContext)c).server().isSameThread()) throw new InternalExpressionException("'task_join' cannot be called from main thread to avoid deadlocks"); Value v = lv.get(0); if (!(v instanceof ThreadValue)) @@ -27,13 +27,13 @@ public static void apply(Expression expression) // has to be lazy due to deferred execution of the expression expression.addLazyFunctionWithDelegation("task_dock", 1, false,true, (c, t, expr, tok, lv) -> { CarpetContext cc = (CarpetContext)c; - MinecraftServer server = cc.s.getServer(); + MinecraftServer server = cc.server(); 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().executeBlocking(() -> + ((CarpetContext) c).server().executeBlocking(() -> { try { diff --git a/src/main/java/carpet/script/api/WorldAccess.java b/src/main/java/carpet/script/api/WorldAccess.java index a1fe0e74cb..b56add393b 100644 --- a/src/main/java/carpet/script/api/WorldAccess.java +++ b/src/main/java/carpet/script/api/WorldAccess.java @@ -198,7 +198,7 @@ private static Value genericStateTest( { try { - return test.apply(((BlockValue) v0).getBlockState(), ((BlockValue) v0).getPos(), cc.s.getLevel()); + return test.apply(((BlockValue) v0).getBlockState(), ((BlockValue) v0).getPos(), cc.level()); } catch (NullPointerException ignored) { @@ -206,7 +206,7 @@ private static Value genericStateTest( } } BlockValue block = BlockArgument.findIn(cc, params, 0).block; - return test.apply(block.getBlockState(), block.getPos(), cc.s.getLevel()); + return test.apply(block.getBlockState(), block.getPos(), cc.level()); } private static > BlockState setProperty(Property property, String name, String value, @@ -278,7 +278,7 @@ public static void apply(Expression expression) if (lv.size() == 0) throw new InternalExpressionException("'poi' requires at least one parameter"); BlockArgument locator = BlockArgument.findIn(cc, lv, 0, false); BlockPos pos = locator.block.getPos(); - PoiManager store = cc.s.getLevel().getPoiManager(); + PoiManager store = cc.level().getPoiManager(); if (lv.size() == locator.offset) { Optional> foo = store.getType(pos); @@ -353,7 +353,7 @@ else if (!("any".equals(statusString))) BlockPos pos = locator.block.getPos(); if (lv.size() < locator.offset) throw new InternalExpressionException("'set_poi' requires the new poi type or null, after position argument"); Value poi = lv.get(locator.offset+0); - PoiManager store = cc.s.getLevel().getPoiManager(); + PoiManager store = cc.level().getPoiManager(); if (poi.isNull()) { // clear poi information if (!store.getType(pos).isPresent()) return Value.FALSE; @@ -389,7 +389,7 @@ else if (!("any".equals(statusString))) expression.addContextFunction("weather",-1,(c, t, lv) -> { - ServerLevel world = ((CarpetContext) c).s.getLevel(); + ServerLevel world = ((CarpetContext) c).level(); if(lv.size()==0)//cos it can thunder when raining or when clear. return new StringValue(world.isThundering() ? "thunder" : (world.isRaining() ? "rain" : "clear")); @@ -537,7 +537,7 @@ else if (v instanceof EntityValue) ChunkPos chunkPos = new ChunkPos(pos); return BooleanValue.of(WorldgenRandom.seedSlimeChunk( chunkPos.x, chunkPos.z, - ((CarpetContext)c).s.getLevel().getSeed(), + ((CarpetContext)c).level().getSeed(), 987234911L ).nextInt(10) == 0); }); @@ -559,24 +559,24 @@ else if (v instanceof EntityValue) BlockPos pos = locator.block.getPos(); int x = pos.getX(); int z = pos.getZ(); - return new NumericValue(((CarpetContext)c).s.getLevel().getChunk(x >> 4, z >> 4).getHeight(htype, x & 15, z & 15) + 1); + return new NumericValue(((CarpetContext)c).level().getChunk(x >> 4, z >> 4).getHeight(htype, x & 15, z & 15) + 1); }); expression.addContextFunction("loaded", -1, (c, t, lv) -> - BooleanValue.of((((CarpetContext) c).s.getLevel().hasChunkAt(BlockArgument.findIn((CarpetContext) c, lv, 0).block.getPos())))); + BooleanValue.of((((CarpetContext) c).level().hasChunkAt(BlockArgument.findIn((CarpetContext) c, lv, 0).block.getPos())))); // Deprecated, use loaded_status as more indicative expression.addContextFunction("loaded_ep", -1, (c, t, lv) -> { c.host.issueDeprecation("loaded_ep(...)"); BlockPos pos = BlockArgument.findIn((CarpetContext)c, lv, 0).block.getPos(); - return BooleanValue.of(((CarpetContext)c).s.getLevel().isPositionEntityTicking(pos));// 1.17pre1 getChunkManager().shouldTickChunk(new ChunkPos(pos))); + return BooleanValue.of(((CarpetContext)c).level().isPositionEntityTicking(pos));// 1.17pre1 getChunkManager().shouldTickChunk(new ChunkPos(pos))); }); expression.addContextFunction("loaded_status", -1, (c, t, lv) -> { BlockPos pos = BlockArgument.findIn((CarpetContext)c, lv, 0).block.getPos(); - LevelChunk chunk = ((CarpetContext)c).s.getLevel().getChunkSource().getChunk(pos.getX()>>4, pos.getZ()>>4, false); + LevelChunk chunk = ((CarpetContext)c).level().getChunkSource().getChunk(pos.getX()>>4, pos.getZ()>>4, false); if (chunk == null) return Value.ZERO; return new NumericValue(chunk.getFullStatus().ordinal()); }); @@ -588,7 +588,7 @@ else if (v instanceof EntityValue) boolean force = false; if (lv.size() > locator.offset) force = lv.get(locator.offset).getBoolean(); - return BooleanValue.of(canHasChunk(((CarpetContext)c).s.getLevel(), new ChunkPos(pos), null, force)); + return BooleanValue.of(canHasChunk(((CarpetContext)c).level(), new ChunkPos(pos), null, force)); }); expression.addContextFunction("generation_status", -1, (c, t, lv) -> @@ -598,14 +598,14 @@ else if (v instanceof EntityValue) boolean forceLoad = false; if (lv.size() > blockArgument.offset) forceLoad = lv.get(blockArgument.offset).getBoolean(); - ChunkAccess chunk = ((CarpetContext)c).s.getLevel().getChunk(pos.getX()>>4, pos.getZ()>>4, ChunkStatus.EMPTY, forceLoad); + ChunkAccess chunk = ((CarpetContext)c).level().getChunk(pos.getX()>>4, pos.getZ()>>4, ChunkStatus.EMPTY, forceLoad); if (chunk == null) return Value.NULL; return new StringValue(chunk.getStatus().getName()); }); expression.addContextFunction("chunk_tickets", -1, (c, t, lv) -> { - ServerLevel world = ((CarpetContext) c).s.getLevel(); + ServerLevel world = ((CarpetContext) c).level(); Long2ObjectOpenHashMap>> levelTickets = ( (ChunkTicketManagerInterface) ((ServerChunkManagerInterface) world.getChunkSource()) .getCMTicketManager() @@ -659,14 +659,14 @@ else if (v instanceof EntityValue) expression.addContextFunction("update", -1, (c, t, lv) -> booleanStateTest(c, "update", lv, (s, p) -> { - ((CarpetContext) c).s.getLevel().neighborChanged(p, s.getBlock(), p); + ((CarpetContext) c).level().neighborChanged(p, s.getBlock(), p); return true; })); expression.addContextFunction("block_tick", -1, (c, t, lv) -> booleanStateTest(c, "block_tick", lv, (s, p) -> { - ServerLevel w = ((CarpetContext)c).s.getLevel(); + ServerLevel w = ((CarpetContext)c).level(); s.randomTick(w, p, w.random); return true; })); @@ -674,7 +674,7 @@ else if (v instanceof EntityValue) expression.addContextFunction("random_tick", -1, (c, t, lv) -> booleanStateTest(c, "random_tick", lv, (s, p) -> { - ServerLevel w = ((CarpetContext)c).s.getLevel(); + ServerLevel w = ((CarpetContext)c).level(); if (s.isRandomlyTicking() || s.getFluidState().isRandomlyTicking()) s.randomTick(w, p, w.random); return true; @@ -686,7 +686,7 @@ else if (v instanceof EntityValue) boolean previous = CarpetSettings.impendingFillSkipUpdates.get(); if (previous) return lv.get(0); Value [] result = new Value[]{Value.NULL}; - ((CarpetContext)c).s.getServer().executeBlocking( () -> + ((CarpetContext)c).server().executeBlocking( () -> { try { @@ -704,7 +704,7 @@ else if (v instanceof EntityValue) expression.addContextFunction("set", -1, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; - ServerLevel world = cc.s.getLevel(); + ServerLevel world = cc.level(); BlockArgument targetLocator = BlockArgument.findIn(cc, lv, 0); BlockArgument sourceLocator = BlockArgument.findIn(cc, lv, targetLocator.offset, true); BlockState sourceBlockState = sourceLocator.block.getBlockState(); @@ -775,7 +775,7 @@ else if (args.get(0) instanceof MapValue) BlockState finalSourceBlockState = sourceBlockState; BlockPos targetPos = targetLocator.block.getPos(); Boolean[] result = new Boolean[]{true}; - cc.s.getServer().executeBlocking( () -> + cc.server().executeBlocking( () -> { Clearable.tryClear(world.getBlockEntity(targetPos)); boolean success = world.setBlock(targetPos, finalSourceBlockState, 2); @@ -802,7 +802,7 @@ else if (args.get(0) instanceof MapValue) expression.addContextFunction("destroy", -1, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; - ServerLevel world = cc.s.getLevel(); + ServerLevel world = cc.level(); BlockArgument locator = BlockArgument.findIn(cc, lv, 0); BlockState state = locator.block.getBlockState(); if (state.isAir()) return Value.FALSE; @@ -901,7 +901,7 @@ else if (item instanceof TridentItem || item instanceof SwordItem) if (lv.size()<2) throw new InternalExpressionException("'harvest' takes at least 2 parameters: entity and block, or position, to harvest"); CarpetContext cc = (CarpetContext)c; - Level world = cc.s.getLevel(); + Level world = cc.level(); Value entityValue = lv.get(0); if (!(entityValue instanceof EntityValue)) return Value.FALSE; @@ -987,7 +987,7 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin float thePowah = powah; // copy of ServerWorld.createExplosion #TRACK# - Explosion explosion = new Explosion(cc.s.getLevel(), source, null, null, pos.x, pos.y, pos.z, powah, createFire, mode){ + Explosion explosion = new Explosion(cc.level(), source, null, null, pos.x, pos.y, pos.z, powah, createFire, mode){ @Override public @Nullable LivingEntity getIndirectSourceEntity() { return theAttacker; @@ -996,7 +996,7 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin explosion.explode(); explosion.finalizeExplosion(false); if (mode == Explosion.BlockInteraction.KEEP) explosion.clearToBlow(); - cc.s.getLevel().players().forEach(spe -> { + cc.level().players().forEach(spe -> { if (spe.distanceToSqr(pos) < 4096.0D) spe.connection.send(new ClientboundExplodePacket(pos.x, pos.y, pos.z, thePowah, explosion.getToBlow(), explosion.getHitPlayers().get(spe))); }); @@ -1011,7 +1011,7 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin CarpetContext cc = (CarpetContext) c; String itemString = lv.get(0).getString(); Vector3Argument locator = Vector3Argument.findIn(lv, 1); - ItemInput stackArg = NBTSerializableValue.parseItem(itemString, cc.s.registryAccess()); + ItemInput stackArg = NBTSerializableValue.parseItem(itemString, cc.registryAccess()); BlockPos where = new BlockPos(locator.vec); String facing; if (lv.size() > locator.offset) { @@ -1027,7 +1027,7 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin BlockValue.PlacementContext ctx; try { - ctx = BlockValue.PlacementContext.from(cc.s.getLevel(), where, facing, sneakPlace, stackArg.createItemStack(1, false)); + ctx = BlockValue.PlacementContext.from(cc.level(), where, facing, sneakPlace, stackArg.createItemStack(1, false)); } catch (CommandSyntaxException e) { @@ -1049,11 +1049,12 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin BlockState placementState = blockItem.getBlock().getStateForPlacement(ctx); if (placementState != null) { - if (placementState.canSurvive(cc.s.getLevel(), where)) + final Level level = ctx.getLevel(); + if (placementState.canSurvive(level, where)) { - cc.s.getLevel().setBlock(where, placementState, 2); + level.setBlock(where, placementState, 2); SoundType blockSoundGroup = placementState.getSoundType(); - cc.s.getLevel().playSound(null, where, blockSoundGroup.getPlaceSound(), SoundSource.BLOCKS, (blockSoundGroup.getVolume() + 1.0F) / 2.0F, blockSoundGroup.getPitch() * 0.8F); + level.playSound(null, where, blockSoundGroup.getPlaceSound(), SoundSource.BLOCKS, (blockSoundGroup.getVolume() + 1.0F) / 2.0F, blockSoundGroup.getPitch() * 0.8F); return Value.TRUE; } } @@ -1063,7 +1064,7 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin expression.addContextFunction("blocks_movement", -1, (c, t, lv) -> booleanStateTest(c, "blocks_movement", lv, (s, p) -> - !s.isPathfindable(((CarpetContext) c).s.getLevel(), p, PathComputationType.LAND))); + !s.isPathfindable(((CarpetContext) c).level(), p, PathComputationType.LAND))); expression.addContextFunction("block_sound", -1, (c, t, lv) -> stateStringQuery(c, "block_sound", lv, (s, p) -> @@ -1075,7 +1076,7 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin expression.addContextFunction("map_colour", -1, (c, t, lv) -> stateStringQuery(c, "map_colour", lv, (s, p) -> - BlockInfo.mapColourName.get(s.getMapColor(((CarpetContext)c).s.getLevel(), p)))); + BlockInfo.mapColourName.get(s.getMapColor(((CarpetContext)c).level(), p)))); // Deprecated for block_state() @@ -1135,7 +1136,7 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin CarpetContext cc = (CarpetContext)c; ResourceLocation tag = InputValidator.identifierOf(lv.get(0).getString()); - Registry blocks = cc.s.getServer().registryAccess().registryOrThrow(Registries.BLOCK); + Registry blocks = cc.registry(Registries.BLOCK); Optional> tagset = blocks.getTag(TagKey.create(Registries.BLOCK, tag)); if (tagset.isEmpty()) return Value.NULL; return ListValue.wrap(tagset.get().stream().map(b -> ValueConversions.of(blocks.getKey(b.value()))).collect(Collectors.toList())); @@ -1144,7 +1145,7 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin expression.addContextFunction("block_tags", -1, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; - Registry blocks = cc.s.getServer().registryAccess().registryOrThrow(Registries.BLOCK); + Registry blocks = cc.registry(Registries.BLOCK); if (lv.size() == 0) return ListValue.wrap(blocks.getTagNames().map(ValueConversions::of).collect(Collectors.toList())); BlockArgument blockLocator = BlockArgument.findIn(cc, lv, 0, true); @@ -1178,7 +1179,7 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin expression.addContextFunction("biome", -1, (c, t, lv) -> { CarpetContext cc = (CarpetContext) c; - ServerLevel world = cc.s.getLevel(); + ServerLevel world = cc.level(); if (lv.size() == 0) return ListValue.wrap(world.registryAccess().registryOrThrow(Registries.BIOME).keySet().stream().map(ValueConversions::of)); @@ -1215,7 +1216,7 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin Climate.quantizeCoord(numberGetOrThrow(weirdness)) ); biome = mnbs.getNoiseBiome(point).value(); - ResourceLocation biomeId = cc.s.getServer().registryAccess().registryOrThrow(Registries.BIOME).getKey(biome); + ResourceLocation biomeId = cc.registry(Registries.BIOME).getKey(biome); return new StringValue(NBTSerializableValue.nameFromRegistryId(biomeId)); } @@ -1234,7 +1235,7 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin // in locatebiome if (locator.offset == lv.size()) { - ResourceLocation biomeId = cc.s.getServer().registryAccess().registryOrThrow(Registries.BIOME).getKey(biome); + ResourceLocation biomeId = cc.registry(Registries.BIOME).getKey(biome); return new StringValue(NBTSerializableValue.nameFromRegistryId(biomeId)); } String biomeFeature = lv.get(locator.offset).getString(); @@ -1252,7 +1253,7 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin throw new InternalExpressionException("'set_biome' needs a biome name as an argument"); String biomeName = lv.get(locator.offset+0).getString(); // from locatebiome command code - Holder biome = cc.s.getServer().registryAccess().registryOrThrow(Registries.BIOME).getHolder(ResourceKey.create(Registries.BIOME, InputValidator.identifierOf(biomeName))) + Holder biome = cc.registry(Registries.BIOME).getHolder(ResourceKey.create(Registries.BIOME, InputValidator.identifierOf(biomeName))) .orElseThrow(() -> new ThrowStatement(biomeName, Throwables.UNKNOWN_BIOME)); @@ -1261,7 +1262,7 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin { doImmediateUpdate = lv.get(locator.offset+1).getBoolean(); } - ServerLevel world = cc.s.getLevel(); + ServerLevel world = cc.level(); BlockPos pos = locator.block.getPos(); ChunkAccess chunk = world.getChunk(pos); // getting level chunk instead of protochunk with biomes int biomeX = QuartPos.fromBlock(pos.getX()); @@ -1285,18 +1286,18 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin expression.addContextFunction("reload_chunk", -1, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; BlockPos pos = BlockArgument.findIn(cc, lv, 0).block.getPos(); - ServerLevel world = cc.s.getLevel(); - cc.s.getServer().executeBlocking( () -> WorldTools.forceChunkUpdate(pos, world)); + ServerLevel world = cc.level(); + cc.server().executeBlocking( () -> WorldTools.forceChunkUpdate(pos, world)); return Value.TRUE; }); expression.addContextFunction("structure_references", -1, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; BlockArgument locator = BlockArgument.findIn(cc, lv, 0); - ServerLevel world = cc.s.getLevel(); + ServerLevel world = cc.level(); BlockPos pos = locator.block.getPos(); Map references = world.getChunk(pos.getX() >> 4, pos.getZ() >> 4, ChunkStatus.STRUCTURE_REFERENCES).getAllReferences(); - Registry reg = cc.s.getServer().registryAccess().registryOrThrow(Registries.STRUCTURE); + Registry reg = cc.registry(Registries.STRUCTURE); if (lv.size() == locator.offset) return ListValue.wrap(references.entrySet().stream(). filter(e -> e.getValue()!= null && !e.getValue().isEmpty()). @@ -1318,7 +1319,7 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin CarpetContext cc = (CarpetContext)c; BlockArgument locator = BlockArgument.findIn(cc, lv, 0); - ServerLevel world = cc.s.getLevel(); + ServerLevel world = cc.level(); // well, because BooYah(world); @@ -1327,7 +1328,7 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin final List structure = new ArrayList<>(); boolean needSize = false; boolean singleOutput = false; - Registry reg = cc.s.getServer().registryAccess().registryOrThrow(Registries.STRUCTURE); + Registry reg = cc.registry(Registries.STRUCTURE); if (lv.size() > locator.offset) { Value requested = lv.get(locator.offset+0); @@ -1398,10 +1399,10 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin CarpetContext cc = (CarpetContext)c; BlockArgument locator = BlockArgument.findIn(cc, lv, 0); - ServerLevel world = cc.s.getLevel(); + ServerLevel world = cc.level(); BlockPos pos = locator.block.getPos(); Map structures = world.getChunk(pos.getX() >> 4, pos.getZ() >> 4, ChunkStatus.STRUCTURE_STARTS).getAllStarts(); - Registry reg = cc.s.getServer().registryAccess().registryOrThrow(Registries.STRUCTURE); + Registry reg = cc.registry(Registries.STRUCTURE); if (lv.size() == locator.offset) { Map structureList = new HashMap<>(); @@ -1427,7 +1428,7 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin CarpetContext cc = (CarpetContext)c; BlockArgument locator = BlockArgument.findIn(cc, lv, 0); - ServerLevel world = cc.s.getLevel(); + ServerLevel world = cc.level(); BlockPos pos = locator.block.getPos(); if (lv.size() == locator.offset) @@ -1438,12 +1439,12 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin // good 'ol pointer Value[] result = new Value[]{Value.NULL}; // technically a world modification. Even if we could let it slide, we will still park it - ((CarpetContext) c).s.getServer().executeBlocking(() -> + ((CarpetContext) c).server().executeBlocking(() -> { Map structures = world.getChunk(pos).getAllStarts(); if (lv.size() == locator.offset + 1) { - Boolean res = FeatureGenerator.plopGrid(configuredStructure, ((CarpetContext) c).s.getLevel(), locator.block.getPos()); + Boolean res = FeatureGenerator.plopGrid(configuredStructure, ((CarpetContext) c).level(), locator.block.getPos()); if (res == null) return; result[0] = res?Value.TRUE:Value.FALSE; return; @@ -1553,11 +1554,11 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin } - ServerLevel world = cc.s.getLevel(); + ServerLevel world = cc.level(); Value [] result = new Value[]{Value.NULL}; - ((CarpetContext)c).s.getServer().executeBlocking( () -> + ((CarpetContext)c).server().executeBlocking( () -> { Map report = ((ThreadedAnvilChunkStorageInterface) world.getChunkSource().chunkMap).regenerateChunkRegion(requestedChunks); /*for (ChunkPos chpos: requestedChunks) // needed in 1.16 only @@ -1580,7 +1581,7 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin CarpetContext cc = (CarpetContext)c; BlockArgument locator = BlockArgument.findIn(cc, lv, 0); BlockPos pos = locator.block.getPos(); - return new NumericValue(cc.s.getLevel().getChunk(pos).getInhabitedTime()); + return new NumericValue(cc.level().getChunk(pos).getInhabitedTime()); }); expression.addContextFunction("spawn_potential", -1, (c, t, lv) -> @@ -1591,7 +1592,7 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin double required_charge = 1; if (lv.size() > locator.offset) required_charge = NumericValue.asNumber(lv.get(locator.offset)).getDouble(); - NaturalSpawner.SpawnState charger = cc.s.getLevel().getChunkSource().getLastSpawnState(); + NaturalSpawner.SpawnState charger = cc.level().getChunkSource().getLastSpawnState(); if (charger == null) return Value.NULL; return new NumericValue( ((SpawnHelperInnerInterface)charger).getPotentialCalculator(). @@ -1613,11 +1614,11 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin // due to types we will wing it: ChunkPos target = new ChunkPos(pos); if (ticket == TicketType.PORTAL) // portal - cc.s.getLevel().getChunkSource().addRegionTicket(TicketType.PORTAL, target, radius, pos); + cc.level().getChunkSource().addRegionTicket(TicketType.PORTAL, target, radius, pos); else if (ticket == TicketType.POST_TELEPORT) // post teleport - cc.s.getLevel().getChunkSource().addRegionTicket(TicketType.POST_TELEPORT, target, radius, 1); + cc.level().getChunkSource().addRegionTicket(TicketType.POST_TELEPORT, target, radius, 1); else - cc.s.getLevel().getChunkSource().addRegionTicket(TicketType.UNKNOWN, target, radius, target); + cc.level().getChunkSource().addRegionTicket(TicketType.UNKNOWN, target, radius, target); return new NumericValue(ticket.timeout()); }); diff --git a/src/main/java/carpet/script/argument/BlockArgument.java b/src/main/java/carpet/script/argument/BlockArgument.java index b32556d2e4..e29d28a31c 100644 --- a/src/main/java/carpet/script/argument/BlockArgument.java +++ b/src/main/java/carpet/script/argument/BlockArgument.java @@ -60,23 +60,25 @@ public static BlockArgument findIn(CarpetContext c, Iterator params, int } if (acceptString && v1 instanceof StringValue) { - return new BlockArgument(BlockValue.fromString(v1.getString(), c.s.registryAccess()), 1 + offset); + return new BlockArgument(BlockValue.fromString(v1.getString(), c.registryAccess()), 1 + offset); } if (v1 instanceof BlockValue) { return new BlockArgument(((BlockValue) v1), 1 + offset); } + final BlockPos pos = c.origin(); if (v1 instanceof ListValue) { List args = ((ListValue) v1).getItems(); int xpos = (int) NumericValue.asNumber(args.get(0)).getLong(); int ypos = (int) NumericValue.asNumber(args.get(1)).getLong(); int zpos = (int) NumericValue.asNumber(args.get(2)).getLong(); + return new BlockArgument( new BlockValue( null, - c.s.getLevel(), - new BlockPos(c.origin.getX() + xpos, c.origin.getY() + ypos, c.origin.getZ() + zpos) + c.level(), + new BlockPos(pos.getX() + xpos, pos.getY() + ypos, pos.getZ() + zpos) ), 1 + offset); } @@ -86,8 +88,8 @@ public static BlockArgument findIn(CarpetContext c, Iterator params, int return new BlockArgument( new BlockValue( null, - c.s.getLevel(), - new BlockPos(c.origin.getX() + xpos, c.origin.getY() + ypos, c.origin.getZ() + zpos) + c.level(), + new BlockPos(pos.getX() + xpos, pos.getY() + ypos, pos.getZ() + zpos) ), 3 + offset ); diff --git a/src/main/java/carpet/script/utils/SystemInfo.java b/src/main/java/carpet/script/utils/SystemInfo.java index abe60e15cc..514d085d55 100644 --- a/src/main/java/carpet/script/utils/SystemInfo.java +++ b/src/main/java/carpet/script/utils/SystemInfo.java @@ -48,46 +48,46 @@ 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().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_name", c -> new StringValue(c.server().getWorldData().getLevelName())); + put("world_seed", c -> new NumericValue(c.level().getSeed())); + put("server_motd", c -> StringValue.of(c.server().getMotd())); + put("world_path", c -> StringValue.of(c.server().getWorldPath(LevelResource.ROOT).toString())); put("world_folder", c -> { - Path serverPath = c.s.getServer().getWorldPath(LevelResource.ROOT); + Path serverPath = c.server().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().levelKeys().stream().map(k -> ValueConversions.of(k.location())).collect(Collectors.toList()))); + put("world_dimensions", c -> ListValue.wrap(c.server().levelKeys().stream().map(k -> ValueConversions.of(k.location())).collect(Collectors.toList()))); put("world_spawn_point", c -> { - LevelData prop = c.s.getServer().overworld().getLevelData(); + LevelData prop = c.server().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.getLevel().getMinBuildHeight())); + put("world_bottom", c-> new NumericValue(c.level().getMinBuildHeight())); - put("world_top", c-> new NumericValue(c.s.getLevel().getMaxBuildHeight())); + put("world_top", c-> new NumericValue(c.level().getMaxBuildHeight())); put("world_center", c-> { - WorldBorder worldBorder = c.s.getLevel().getWorldBorder(); + WorldBorder worldBorder = c.level().getWorldBorder(); return ListValue.fromTriple(worldBorder.getCenterX(), 0, worldBorder.getCenterZ()); }); - put("world_size", c -> new NumericValue(c.s.getLevel().getWorldBorder().getSize() / 2)); + put("world_size", c -> new NumericValue(c.level().getWorldBorder().getSize() / 2)); - put("world_max_size", c-> new NumericValue( c.s.getLevel().getWorldBorder().getAbsoluteMaxSize())); + put("world_max_size", c-> new NumericValue( c.level().getWorldBorder().getAbsoluteMaxSize())); - put("world_time", c -> new NumericValue(c.s.getLevel().getGameTime())); + put("world_time", c -> new NumericValue(c.level().getGameTime())); - 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().getServerVersion())); + put("game_difficulty", c -> StringValue.of(c.server().getWorldData().getDifficulty().getKey())); + put("game_hardcore", c -> BooleanValue.of(c.server().getWorldData().isHardcore())); + put("game_storage_format", c -> StringValue.of(c.server().getWorldData().getStorageVersionName(c.server().getWorldData().getVersion()))); + put("game_default_gamemode", c -> StringValue.of(c.server().getDefaultGameType().getName())); + put("game_max_players", c -> new NumericValue(c.server().getMaxPlayers())); + put("game_view_distance", c -> new NumericValue(c.server().getPlayerList().getViewDistance())); + put("game_mod_name", c -> StringValue.of(c.server().getServerModName())); + put("game_version", c -> StringValue.of(c.server().getServerVersion())); put("game_target", c -> StringValue.of(CarpetSettings.releaseTarget)); put("game_protocol", c -> NumericValue.of(SharedConstants.getProtocolVersion())); put("game_major_target", c -> { @@ -102,11 +102,11 @@ public class SystemInfo { put("game_data_version", c->NumericValue.of(SharedConstants.getCurrentVersion().getWorldVersion())); put("game_pack_version", c->NumericValue.of(SharedConstants.getCurrentVersion().getPackVersion(PackType.DATA))); - put("server_ip", c -> StringValue.of(c.s.getServer().getLocalIp())); - put("server_whitelisted", c -> BooleanValue.of(c.s.getServer().isEnforceWhitelist())); + put("server_ip", c -> StringValue.of(c.server().getLocalIp())); + put("server_whitelisted", c -> BooleanValue.of(c.server().isEnforceWhitelist())); put("server_whitelist", c -> { MapValue whitelist = new MapValue(Collections.emptyList()); - for (String s: c.s.getServer().getPlayerList().getWhiteListNames()) + for (String s: c.server().getPlayerList().getWhiteListNames()) { whitelist.append(StringValue.of(s)); } @@ -114,7 +114,7 @@ public class SystemInfo { }); put("server_banned_players", c -> { MapValue whitelist = new MapValue(Collections.emptyList()); - for (String s: c.s.getServer().getPlayerList().getBans().getUserList()) + for (String s: c.server().getPlayerList().getBans().getUserList()) { whitelist.append(StringValue.of(s)); } @@ -122,7 +122,7 @@ public class SystemInfo { }); put("server_banned_ips", c -> { MapValue whitelist = new MapValue(Collections.emptyList()); - for (String s: c.s.getServer().getPlayerList().getIpBans().getUserList()) + for (String s: c.server().getPlayerList().getIpBans().getUserList()) { whitelist.append(StringValue.of(s)); } @@ -138,9 +138,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().getTickCount()-1; + int currentReportedTick = c.server().getTickCount()-1; List ticks = new ArrayList<>(100); - final long[] tickArray = c.s.getServer().tickTimes; + final long[] tickArray = c.server().tickTimes; for (int i=currentReportedTick+100; i > currentReportedTick; i--) { ticks.add(new NumericValue(((double)tickArray[i % 100])/1000000.0)); @@ -192,7 +192,7 @@ public class SystemInfo { }); put("world_gamerules", c->{ Map rules = new HashMap<>(); - final GameRules gameRules = c.s.getLevel().getGameRules(); + final GameRules gameRules = c.level().getGameRules(); GameRules.visitGameRuleTypes(new GameRules.GameRuleTypeVisitor() { @Override public > void visit(GameRules.Key key, GameRules.Type type) { @@ -202,11 +202,11 @@ public > void visit(GameRules.Key key, GameRules return MapValue.wrap(rules); }); - 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.getLevel())); + put("source_entity", c -> EntityValue.of(c.source().getEntity())); + put("source_position", c -> ValueConversions.of(c.source().getPosition())); + put("source_dimension", c -> ValueConversions.of(c.level())); put("source_rotation", c -> { - Vec2 rotation = c.s.getRotation(); + Vec2 rotation = c.source().getRotation(); return ListValue.of(new NumericValue(rotation.x), new NumericValue(rotation.y)); }); diff --git a/src/main/java/carpet/script/value/BlockValue.java b/src/main/java/carpet/script/value/BlockValue.java index 4fe34e6b95..c22f43a3be 100644 --- a/src/main/java/carpet/script/value/BlockValue.java +++ b/src/main/java/carpet/script/value/BlockValue.java @@ -51,7 +51,7 @@ public class BlockValue extends Value public static BlockValue fromCoords(CarpetContext c, int x, int y, int z) { BlockPos pos = locateBlockPos(c, x,y,z); - return new BlockValue(null, c.s.getLevel(), pos); + return new BlockValue(null, c.level(), pos); } private static final Map bvCache= new HashMap<>(); @@ -82,7 +82,8 @@ public static BlockValue fromString(String str, RegistryAccess regs) public static BlockPos locateBlockPos(CarpetContext c, int xpos, int ypos, int zpos) { - return new BlockPos(c.origin.getX() + xpos, c.origin.getY() + ypos, c.origin.getZ() + zpos); + final BlockPos pos = c.origin(); + return new BlockPos(pos.getX() + xpos, pos.getY() + ypos, pos.getZ() + zpos); } public BlockState getBlockState() diff --git a/src/main/java/carpet/script/value/NBTSerializableValue.java b/src/main/java/carpet/script/value/NBTSerializableValue.java index 1ca0eaf4d9..d48721a8da 100644 --- a/src/main/java/carpet/script/value/NBTSerializableValue.java +++ b/src/main/java/carpet/script/value/NBTSerializableValue.java @@ -208,7 +208,7 @@ else if (v1 instanceof StringValue) if (strVal.equals("enderchest")) { Value v2 = params.get(1 + offset); - ServerPlayer player = EntityValue.getPlayerByValue(c.s.getServer(), v2); + ServerPlayer player = EntityValue.getPlayerByValue(c.server(), v2); if (player == null) throw new InternalExpressionException("enderchest inventory requires player argument"); return new InventoryLocator(player, player.blockPosition(), player.getEnderChestInventory(), offset + 2, true); } @@ -222,7 +222,7 @@ else if (v1 instanceof StringValue) } boolean isEnder = strVal.startsWith("enderchest_"); if (isEnder) strVal = strVal.substring(11); // len("enderchest_") - ServerPlayer player = c.s.getServer().getPlayerList().getPlayerByName(strVal); + ServerPlayer player = c.server().getPlayerList().getPlayerByName(strVal); if (player == null) throw new InternalExpressionException("String description of an inventory should either denote a player or player's enderchest"); return new InventoryLocator( player, @@ -251,7 +251,7 @@ else if (v1 instanceof StringValue) BlockPos pos = ((BlockValue) v1).getPos(); if (pos == null) throw new InternalExpressionException("Block to access inventory needs to be positioned in the world"); - Container inv = getInventoryAt(c.s.getLevel(), pos); + Container inv = getInventoryAt(c.level(), pos); if (inv == null) return null; return new InventoryLocator(pos, pos, inv, offset+1); @@ -263,7 +263,7 @@ else if (v1 instanceof StringValue) NumericValue.asNumber(args.get(0)).getDouble(), NumericValue.asNumber(args.get(1)).getDouble(), NumericValue.asNumber(args.get(2)).getDouble()); - Container inv = getInventoryAt(c.s.getLevel(), pos); + Container inv = getInventoryAt(c.level(), pos); if (inv == null) return null; return new InventoryLocator(pos, pos, inv, offset+1); @@ -277,7 +277,7 @@ else if (v1 instanceof StringValue) NumericValue.asNumber(v1).getDouble(), NumericValue.asNumber(params.get(1 + offset)).getDouble(), NumericValue.asNumber(params.get(2 + offset)).getDouble()); - Container inv = getInventoryAt(c.s.getLevel(), pos); + Container inv = getInventoryAt(c.level(), pos); if (inv == null) return null; return new InventoryLocator(pos, pos, inv, offset + 3); From bd5dfdbf9fecb1d48495f5dc73c24870aeb20366 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 18 Jan 2023 04:07:55 +0100 Subject: [PATCH 002/233] refactor limit access to built-in registries --- src/main/java/carpet/CarpetSettings.java | 3 +- .../java/carpet/commands/MobAICommand.java | 2 +- .../carpet/fakes/RecipeManagerInterface.java | 4 +- .../java/carpet/helpers/FeatureGenerator.java | 6 +- .../java/carpet/helpers/HopperCounter.java | 36 ++++--- .../logHelpers/ExplosionLogHelper.java | 9 +- .../mixins/Explosion_optimizedTntMixin.java | 2 +- .../mixins/RecipeManager_scarpetMixin.java | 9 +- .../java/carpet/script/CarpetEventServer.java | 28 +++--- .../script/annotation/OutputConverter.java | 1 + .../java/carpet/script/api/Auxiliary.java | 17 ++-- src/main/java/carpet/script/api/Entities.java | 5 +- .../java/carpet/script/api/Inventories.java | 35 ++++--- .../java/carpet/script/api/WorldAccess.java | 30 +++--- .../carpet/script/argument/BlockArgument.java | 2 +- .../script/command/CommandArgument.java | 7 +- .../carpet/script/utils/ShapeDispatcher.java | 97 ++++++++++--------- .../carpet/script/utils/ShapesRenderer.java | 8 +- .../java/carpet/script/value/BlockValue.java | 47 ++++----- .../java/carpet/script/value/EntityValue.java | 27 +++--- .../java/carpet/script/value/ScreenValue.java | 2 +- .../carpet/script/value/ValueConversions.java | 23 ++++- src/main/java/carpet/utils/BlockInfo.java | 5 +- .../java/carpet/utils/CarpetProfiler.java | 7 +- src/main/java/carpet/utils/MobAI.java | 7 +- 25 files changed, 243 insertions(+), 176 deletions(-) diff --git a/src/main/java/carpet/CarpetSettings.java b/src/main/java/carpet/CarpetSettings.java index 863a84a256..ded6c7f96b 100644 --- a/src/main/java/carpet/CarpetSettings.java +++ b/src/main/java/carpet/CarpetSettings.java @@ -14,6 +14,7 @@ import net.minecraft.commands.CommandSourceStack; import net.minecraft.core.BlockPos; import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; import net.minecraft.server.ServerInterface; @@ -1007,7 +1008,7 @@ public static class StructureBlockIgnoredValidator extends Validator { @Override public String validate(CommandSourceStack source, CarpetRule currentRule, String newValue, String string) { - Optional ignoredBlock = BuiltInRegistries.BLOCK.getOptional(ResourceLocation.tryParse(newValue)); + Optional ignoredBlock = source.registryAccess().registryOrThrow(Registries.BLOCK).getOptional(ResourceLocation.tryParse(newValue)); if (!ignoredBlock.isPresent()) { Messenger.m(source, "r Unknown block '" + newValue + "'."); return null; diff --git a/src/main/java/carpet/commands/MobAICommand.java b/src/main/java/carpet/commands/MobAICommand.java index 26b1e031cc..f905ebda0c 100644 --- a/src/main/java/carpet/commands/MobAICommand.java +++ b/src/main/java/carpet/commands/MobAICommand.java @@ -24,7 +24,7 @@ public static void register(CommandDispatcher dispatcher, fi requires((player) -> CommandHelper.canUseCommand(player, CarpetSettings.commandTrackAI)). then(argument("entity type", resource(commandBuildContext, Registries.ENTITY_TYPE)). - suggests( (c, b) -> suggest(MobAI.availbleTypes(), b)). + suggests( (c, b) -> suggest(MobAI.availbleTypes(c.getSource()), b)). then(literal("clear").executes( (c) -> { MobAI.clearTracking(getSummonableEntityType(c, "entity type").value()); diff --git a/src/main/java/carpet/fakes/RecipeManagerInterface.java b/src/main/java/carpet/fakes/RecipeManagerInterface.java index 6e618389c0..ff130d003e 100644 --- a/src/main/java/carpet/fakes/RecipeManagerInterface.java +++ b/src/main/java/carpet/fakes/RecipeManagerInterface.java @@ -1,6 +1,8 @@ package carpet.fakes; import java.util.List; + +import net.minecraft.core.RegistryAccess; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.crafting.Recipe; import net.minecraft.world.item.crafting.RecipeType; @@ -11,5 +13,5 @@ public interface RecipeManagerInterface * Gets all the recipes for a given item. Also used for {@link carpet.helpers.HopperCounter#guessColor} to guess the * colour of an item to display it prettily */ - List> getAllMatching(RecipeType type, ResourceLocation output); + List> getAllMatching(final RecipeType type, final ResourceLocation output, final RegistryAccess registryAccess); } diff --git a/src/main/java/carpet/helpers/FeatureGenerator.java b/src/main/java/carpet/helpers/FeatureGenerator.java index c6f00687be..8ba56c4092 100644 --- a/src/main/java/carpet/helpers/FeatureGenerator.java +++ b/src/main/java/carpet/helpers/FeatureGenerator.java @@ -92,14 +92,14 @@ synchronized public static Boolean plop(String featureName, ServerLevel world, B CarpetSettings.skipGenerationChecks.set(false); } } - Optional> structureType = BuiltInRegistries.STRUCTURE_TYPE.getOptional(id); + Optional> structureType = world.registryAccess().registryOrThrow(Registries.STRUCTURE_TYPE).getOptional(id); if (structureType.isPresent()) { Structure configuredStandard = getDefaultFeature(structureType.get(), world, pos); if (configuredStandard != null) return plopAnywhere(configuredStandard, world, pos, world.getChunkSource().getGenerator(), false); } - Feature feature = BuiltInRegistries.FEATURE.get(id); + Feature feature = world.registryAccess().registryOrThrow(Registries.FEATURE).get(id); if (feature != null) { ConfiguredFeature configuredStandard = getDefaultFeature(feature, world, pos, true); @@ -124,7 +124,7 @@ public static Structure resolveConfiguredStructure(String name, ServerLevel worl ResourceLocation id = new ResourceLocation(name); Structure configuredStructureFeature = world.registryAccess().registryOrThrow(Registries.STRUCTURE).get(id); if (configuredStructureFeature != null) return configuredStructureFeature; - StructureType structureFeature = BuiltInRegistries.STRUCTURE_TYPE.get(id); + StructureType structureFeature = world.registryAccess().registryOrThrow(Registries.STRUCTURE_TYPE).get(id); if (structureFeature == null) return null; return getDefaultFeature(structureFeature, world, pos); } diff --git a/src/main/java/carpet/helpers/HopperCounter.java b/src/main/java/carpet/helpers/HopperCounter.java index d0340ef4a5..f7f5159791 100644 --- a/src/main/java/carpet/helpers/HopperCounter.java +++ b/src/main/java/carpet/helpers/HopperCounter.java @@ -8,7 +8,10 @@ import it.unimi.dsi.fastutil.objects.Object2LongLinkedOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2LongMap; import net.minecraft.ChatFormatting; +import net.minecraft.core.Registry; +import net.minecraft.core.RegistryAccess; import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; import net.minecraft.network.chat.Style; @@ -211,7 +214,7 @@ public List format(MinecraftServer server, boolean realTime, boolean Item item = e.getKey(); MutableComponent itemName = Component.translatable(item.getDescriptionId()); Style itemStyle = itemName.getStyle(); - TextColor color = guessColor(item); + TextColor color = guessColor(item, server.registryAccess()); itemName.setStyle((color != null) ? itemStyle.withColor(color) : itemStyle.withItalic(true)); long count = e.getLongValue(); return Messenger.c("g - ", itemName, @@ -240,7 +243,7 @@ public static int appropriateColor(int color) /** * Maps items that don't get a good block to reference for colour, or those that colour is wrong to a number of blocks, so we can get their colours easily with the - * {@link Block#getDefaultMaterialColor()} method as these items have those same colours. + * {@link Block#defaultMaterialColor()} method as these items have those same colours. */ private static final Map DEFAULTS = Map.ofEntries( entry(Items.DANDELION, Blocks.YELLOW_WOOL), @@ -331,19 +334,21 @@ public static int appropriateColor(int color) /** * Gets the colour to print an item in when printing its count in a hopper counter. */ - public static TextColor fromItem(Item item) + public static TextColor fromItem(Item item, RegistryAccess registryAccess) { if (DEFAULTS.containsKey(item)) return TextColor.fromRgb(appropriateColor(DEFAULTS.get(item).defaultMaterialColor().col)); - if (item instanceof DyeItem) return TextColor.fromRgb(appropriateColor(((DyeItem) item).getDyeColor().getMaterialColor().col)); + if (item instanceof DyeItem dye) return TextColor.fromRgb(appropriateColor(dye.getDyeColor().getMaterialColor().col)); Block block = null; - ResourceLocation id = BuiltInRegistries.ITEM.getKey(item); - if (item instanceof BlockItem) + final Registry itemRegistry = registryAccess.registryOrThrow(Registries.ITEM); + final Registry blockRegistry = registryAccess.registryOrThrow(Registries.BLOCK); + ResourceLocation id = itemRegistry.getKey(item); + if (item instanceof BlockItem blockItem) { - block = ((BlockItem) item).getBlock(); + block = blockItem.getBlock(); } - else if (BuiltInRegistries.BLOCK.getOptional(id).isPresent()) + else if (blockRegistry.getOptional(id).isPresent()) { - block = BuiltInRegistries.BLOCK.get(id); + block = blockRegistry.get(id); } if (block != null) { @@ -358,15 +363,16 @@ else if (BuiltInRegistries.BLOCK.getOptional(id).isPresent()) * Guesses the item's colour from the item itself. It first calls {@link HopperCounter#fromItem} to see if it has a * valid colour there, if not just makes a guess, and if that fails just returns null */ - public static TextColor guessColor(Item item) + public static TextColor guessColor(Item item, RegistryAccess registryAccess) { - TextColor direct = fromItem(item); + TextColor direct = fromItem(item, registryAccess); if (direct != null) return direct; if (CarpetServer.minecraft_server == null) return WHITE; - ResourceLocation id = BuiltInRegistries.ITEM.getKey(item); - for (RecipeType type: BuiltInRegistries.RECIPE_TYPE) + + ResourceLocation id = registryAccess.registryOrThrow(Registries.ITEM).getKey(item); + for (RecipeType type: registryAccess.registryOrThrow(Registries.RECIPE_TYPE)) { - for (Recipe r: ((RecipeManagerInterface) CarpetServer.minecraft_server.getRecipeManager()).getAllMatching(type, id)) + for (Recipe r: ((RecipeManagerInterface) CarpetServer.minecraft_server.getRecipeManager()).getAllMatching(type, id, registryAccess)) { for (Ingredient ingredient: r.getIngredients()) { @@ -374,7 +380,7 @@ public static TextColor guessColor(Item item) { for (ItemStack iStak : stacks) { - TextColor cand = fromItem(iStak.getItem()); + TextColor cand = fromItem(iStak.getItem(), registryAccess); if (cand != null) return cand; } diff --git a/src/main/java/carpet/logging/logHelpers/ExplosionLogHelper.java b/src/main/java/carpet/logging/logHelpers/ExplosionLogHelper.java index 300b4b8d16..3b9fba762b 100644 --- a/src/main/java/carpet/logging/logHelpers/ExplosionLogHelper.java +++ b/src/main/java/carpet/logging/logHelpers/ExplosionLogHelper.java @@ -6,7 +6,10 @@ import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; import java.util.ArrayList; import java.util.List; + +import net.minecraft.core.RegistryAccess; import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; import net.minecraft.network.chat.Component; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; @@ -19,6 +22,7 @@ public class ExplosionLogHelper { private final boolean createFire; private final Explosion.BlockInteraction blockDestructionType; + private final RegistryAccess regs; public final Vec3 pos; private final float power; private boolean affectBlocks = false; @@ -28,11 +32,12 @@ public class ExplosionLogHelper private static int explosionCountInCurretGT = 0; private static boolean newTick; - public ExplosionLogHelper(double x, double y, double z, float power, boolean createFire, Explosion.BlockInteraction blockDestructionType) { + public ExplosionLogHelper(double x, double y, double z, float power, boolean createFire, Explosion.BlockInteraction blockDestructionType, RegistryAccess regs) { this.power = power; this.pos = new Vec3(x,y,z); this.createFire = createFire; this.blockDestructionType = blockDestructionType; + this.regs = regs; } public void setAffectBlocks(boolean b) @@ -76,7 +81,7 @@ public void onExplosionDone(long gametime) messages.add(c((k.pos.equals(pos))?"r - TNT":"w - ", Messenger.dblt((k.pos.equals(pos))?"r":"y", k.pos.x, k.pos.y, k.pos.z), "w dV", Messenger.dblt("d", k.accel.x, k.accel.y, k.accel.z), - "w "+ BuiltInRegistries.ENTITY_TYPE.getKey(k.type).getPath(), (v>1)?"l ("+v+")":"" + "w "+ regs.registryOrThrow(Registries.ENTITY_TYPE).getKey(k.type).getPath(), (v>1)?"l ("+v+")":"" )); }); } diff --git a/src/main/java/carpet/mixins/Explosion_optimizedTntMixin.java b/src/main/java/carpet/mixins/Explosion_optimizedTntMixin.java index 984f3f3107..52e0dc34ef 100644 --- a/src/main/java/carpet/mixins/Explosion_optimizedTntMixin.java +++ b/src/main/java/carpet/mixins/Explosion_optimizedTntMixin.java @@ -80,7 +80,7 @@ private void onExplosionCreated(Level world, Entity entity, DamageSource damageS { if (LoggerRegistry.__explosions && ! world.isClientSide) { - eLogger = new ExplosionLogHelper(x, y, z, power, createFire, destructionType); + eLogger = new ExplosionLogHelper(x, y, z, power, createFire, destructionType, level.registryAccess()); } } diff --git a/src/main/java/carpet/mixins/RecipeManager_scarpetMixin.java b/src/main/java/carpet/mixins/RecipeManager_scarpetMixin.java index e2c18b87a3..39ae15912a 100644 --- a/src/main/java/carpet/mixins/RecipeManager_scarpetMixin.java +++ b/src/main/java/carpet/mixins/RecipeManager_scarpetMixin.java @@ -2,7 +2,11 @@ import carpet.fakes.RecipeManagerInterface; import com.google.common.collect.Lists; +import net.minecraft.core.Registry; +import net.minecraft.core.RegistryAccess; import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.world.item.Item; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -22,13 +26,14 @@ public class RecipeManager_scarpetMixin implements RecipeManagerInterface @Shadow private Map, Map>> recipes; @Override - public List> getAllMatching(RecipeType type, ResourceLocation output) + public List> getAllMatching(RecipeType type, ResourceLocation output, final RegistryAccess registryAccess) { Map> typeRecipes = recipes.get(type); // happens when mods add recipe to the registry without updating recipe manager if (typeRecipes == null) return Collections.emptyList(); if (typeRecipes.containsKey(output)) return Collections.singletonList(typeRecipes.get(output)); + final Registry regs = registryAccess.registryOrThrow(Registries.ITEM); return Lists.newArrayList(typeRecipes.values().stream().filter( - r -> BuiltInRegistries.ITEM.getKey(r.getResultItem().getItem()).equals(output)).collect(Collectors.toList())); + r -> regs.getKey(r.getResultItem().getItem()).equals(output)).collect(Collectors.toList())); } } diff --git a/src/main/java/carpet/script/CarpetEventServer.java b/src/main/java/carpet/script/CarpetEventServer.java index 920d84e6dd..01ebfe990e 100644 --- a/src/main/java/carpet/script/CarpetEventServer.java +++ b/src/main/java/carpet/script/CarpetEventServer.java @@ -43,12 +43,16 @@ import net.minecraft.commands.CommandSourceStack; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.Registry; +import net.minecraft.core.RegistryAccess; import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.stats.Stat; +import net.minecraft.stats.StatType; import net.minecraft.stats.Stats; import net.minecraft.world.InteractionHand; import net.minecraft.world.damagesource.DamageSource; @@ -551,7 +555,7 @@ public boolean onItemAction(ServerPlayer player, InteractionHand enumhand, ItemS //ItemStack itemstack = player.getStackInHand(enumhand); return Arrays.asList( new EntityValue(player), - ValueConversions.of(itemstack), + ValueConversions.of(itemstack, player.getLevel().registryAccess()), StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand") ); }, player::createCommandSourceStack); @@ -585,7 +589,7 @@ public boolean onBlockHit(ServerPlayer player, InteractionHand enumhand, BlockHi Vec3 vec3d = hitRes.getLocation().subtract(blockpos.getX(), blockpos.getY(), blockpos.getZ()); return Arrays.asList( new EntityValue(player), - ValueConversions.of(itemstack), + ValueConversions.of(itemstack, player.getLevel().registryAccess()), StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand"), new BlockValue(null, player.getLevel(), blockpos), StringValue.of(enumfacing.getName()), @@ -630,7 +634,7 @@ public boolean onBlockPlaced(ServerPlayer player, BlockPos pos, InteractionHand { return handler.call( () -> Arrays.asList( new EntityValue(player), - ValueConversions.of(itemstack), + ValueConversions.of(itemstack, player.getLevel().registryAccess()), StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand"), new BlockValue(null, player.getLevel(), pos) ), player::createCommandSourceStack); @@ -643,7 +647,7 @@ public boolean onBlockPlaced(ServerPlayer player, BlockPos pos, InteractionHand { handler.call( () -> Arrays.asList( new EntityValue(player), - ValueConversions.of(itemstack), + ValueConversions.of(itemstack, player.getLevel().registryAccess()), StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand"), new BlockValue(null, player.getLevel(), pos) ), player::createCommandSourceStack); @@ -676,12 +680,13 @@ public boolean onEntityHandAction(ServerPlayer player, Entity entity, Interactio @Override public void onTrade(ServerPlayer player, Merchant merchant, MerchantOffer tradeOffer) { + final RegistryAccess regs = player.getLevel().registryAccess(); handler.call( () -> Arrays.asList( new EntityValue(player), merchant instanceof AbstractVillager ? new EntityValue((AbstractVillager) merchant) : Value.NULL, - ValueConversions.of(tradeOffer.getBaseCostA()), - ValueConversions.of(tradeOffer.getCostB()), - ValueConversions.of(tradeOffer.getResult()) + ValueConversions.of(tradeOffer.getBaseCostA(), regs), + ValueConversions.of(tradeOffer.getCostB(), regs), + ValueConversions.of(tradeOffer.getResult(), regs) ), player::createCommandSourceStack); } }; @@ -689,7 +694,7 @@ public void onTrade(ServerPlayer player, Merchant merchant, MerchantOffer tradeO { @Override public boolean onItemAction(ServerPlayer player, InteractionHand enumhand, ItemStack itemstack) { - handler.call( () -> Arrays.asList(new EntityValue(player), ValueConversions.of(itemstack)), player::createCommandSourceStack); + handler.call( () -> Arrays.asList(new EntityValue(player), ValueConversions.of(itemstack, player.getLevel().registryAccess())), player::createCommandSourceStack); return false; } }; @@ -748,7 +753,7 @@ public boolean onItemAction(ServerPlayer player, InteractionHand enumhand, ItemS handler.call( () -> Arrays.asList( new EntityValue(player), - ValueConversions.of(itemstack), + ValueConversions.of(itemstack, player.getLevel().registryAccess()), StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand") ), player::createCommandSourceStack); return false; @@ -763,7 +768,7 @@ public boolean onItemAction(ServerPlayer player, InteractionHand enumhand, ItemS return handler.call( () -> Arrays.asList( new EntityValue(player), - ValueConversions.of(itemstack), + ValueConversions.of(itemstack, player.getLevel().registryAccess()), new StringValue(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand") ), player::createCommandSourceStack); } @@ -946,9 +951,10 @@ public void onPlayerStatistic(ServerPlayer player, Stat stat, int amount) { ResourceLocation id = getStatId(stat); if (skippedStats.contains(id)) return; + final Registry> registry = player.getLevel().registryAccess().registryOrThrow(Registries.STAT_TYPE); handler.call( () -> Arrays.asList( new EntityValue(player), - StringValue.of(NBTSerializableValue.nameFromRegistryId(BuiltInRegistries.STAT_TYPE.getKey(stat.getType()))), + StringValue.of(NBTSerializableValue.nameFromRegistryId(registry.getKey(stat.getType()))), StringValue.of(NBTSerializableValue.nameFromRegistryId(id)), new NumericValue(amount) ), player::createCommandSourceStack); diff --git a/src/main/java/carpet/script/annotation/OutputConverter.java b/src/main/java/carpet/script/annotation/OutputConverter.java index c9de72ca86..59f9923355 100644 --- a/src/main/java/carpet/script/annotation/OutputConverter.java +++ b/src/main/java/carpet/script/annotation/OutputConverter.java @@ -6,6 +6,7 @@ import java.util.function.Function; import net.minecraft.core.BlockPos; import net.minecraft.core.GlobalPos; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.nbt.Tag; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; diff --git a/src/main/java/carpet/script/api/Auxiliary.java b/src/main/java/carpet/script/api/Auxiliary.java index de9b76e206..c5611e0a26 100644 --- a/src/main/java/carpet/script/api/Auxiliary.java +++ b/src/main/java/carpet/script/api/Auxiliary.java @@ -139,12 +139,12 @@ public static void apply(Expression expression) CarpetContext cc = (CarpetContext)c; if (lv.size() == 0) { - return ListValue.wrap(BuiltInRegistries.SOUND_EVENT.keySet().stream().map(ValueConversions::of)); + return ListValue.wrap(cc.registry(Registries.SOUND_EVENT).keySet().stream().map(ValueConversions::of)); } String rawString = lv.get(0).getString(); ResourceLocation soundName = InputValidator.identifierOf(rawString); Vector3Argument locator = Vector3Argument.findIn(lv, 1); - if (BuiltInRegistries.SOUND_EVENT.get(soundName) == null) + if (cc.registry(Registries.SOUND_EVENT).get(soundName) == null) throw new ThrowStatement(rawString, Throwables.UNKNOWN_SOUND); final Holder soundHolder = Holder.direct(SoundEvent.createVariableRangeEvent(soundName)); float volume = 1.0F; @@ -180,7 +180,7 @@ public static void apply(Expression expression) expression.addContextFunction("particle", -1, (c, t, lv) -> { CarpetContext cc = (CarpetContext)c; - if (lv.size() == 0) return ListValue.wrap(BuiltInRegistries.PARTICLE_TYPE.keySet().stream().map(ValueConversions::of)); + if (lv.size() == 0) return ListValue.wrap(cc.registry(Registries.PARTICLE_TYPE).keySet().stream().map(ValueConversions::of)); MinecraftServer ms = cc.server(); ServerLevel world = cc.level(); Vector3Argument locator = Vector3Argument.findIn(lv, 1); @@ -756,21 +756,20 @@ else if (!interactable && targetBlock == null) { Map plopData = new HashMap<>(); CarpetContext cc = (CarpetContext)c; - RegistryAccess registryManager = cc.registryAccess(); plopData.put(StringValue.of("scarpet_custom"), ListValue.wrap(FeatureGenerator.featureMap.keySet().stream().sorted().map(StringValue::of).collect(Collectors.toList())) ); plopData.put(StringValue.of("features"), - ListValue.wrap(BuiltInRegistries.FEATURE.keySet().stream().sorted().map(ValueConversions::of).collect(Collectors.toList())) + ListValue.wrap(cc.registry(Registries.FEATURE).keySet().stream().sorted().map(ValueConversions::of).collect(Collectors.toList())) ); plopData.put(StringValue.of("configured_features"), - ListValue.wrap(registryManager.registryOrThrow(Registries.CONFIGURED_FEATURE).keySet().stream().sorted().map(ValueConversions::of).collect(Collectors.toList())) + ListValue.wrap(cc.registry(Registries.CONFIGURED_FEATURE).keySet().stream().sorted().map(ValueConversions::of).collect(Collectors.toList())) ); plopData.put(StringValue.of("structure_types"), - ListValue.wrap(BuiltInRegistries.STRUCTURE_TYPE.keySet().stream().sorted().map(ValueConversions::of).collect(Collectors.toList())) + ListValue.wrap(cc.registry(Registries.STRUCTURE_TYPE).keySet().stream().sorted().map(ValueConversions::of).collect(Collectors.toList())) ); plopData.put(StringValue.of("structures"), - ListValue.wrap(registryManager.registryOrThrow(Registries.STRUCTURE).keySet().stream().sorted().map(ValueConversions::of).collect(Collectors.toList())) + ListValue.wrap(cc.registry(Registries.STRUCTURE).keySet().stream().sorted().map(ValueConversions::of).collect(Collectors.toList())) ); return MapValue.wrap(plopData); } @@ -966,7 +965,7 @@ else if (fdesc.type == FileArgument.Type.JSON) ResourceLocation statName; category = InputValidator.identifierOf(lv.get(1).getString()); statName = InputValidator.identifierOf(lv.get(2).getString()); - StatType type = BuiltInRegistries.STAT_TYPE.get(category); + StatType type = cc.registry(Registries.STAT_TYPE).get(category); if (type == null) return Value.NULL; Stat stat = getStat(type, statName); if (stat == null) return Value.NULL; diff --git a/src/main/java/carpet/script/api/Entities.java b/src/main/java/carpet/script/api/Entities.java index 70f9eb3952..be7205ecdf 100644 --- a/src/main/java/carpet/script/api/Entities.java +++ b/src/main/java/carpet/script/api/Entities.java @@ -26,6 +26,7 @@ import java.util.stream.Collectors; import net.minecraft.commands.CommandSourceStack; import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerLevel; @@ -101,7 +102,7 @@ public static void apply(Expression expression) try { entityId = ResourceLocation.read(new StringReader(entityString)); - EntityType type = BuiltInRegistries.ENTITY_TYPE.getOptional(entityId).orElse(null); + EntityType type = cc.registry(Registries.ENTITY_TYPE).getOptional(entityId).orElse(null); if (type == null || !type.canSummon()) return Value.NULL; } @@ -244,7 +245,7 @@ else if (lv.size()==3) { if (lv.size() > 1) throw new InternalExpressionException("'entity_types' requires one or no arguments"); String desc = (lv.size() == 1)?lv.get(0).getString():"*"; - return EntityValue.getEntityDescriptor(desc, ((CarpetContext) c).server()).listValue(); + return EntityValue.getEntityDescriptor(desc, ((CarpetContext) c).server()).listValue(((CarpetContext)c).registryAccess()); }); expression.addContextFunction("entity_load_handler", -1, (c, t, lv) -> diff --git a/src/main/java/carpet/script/api/Inventories.java b/src/main/java/carpet/script/api/Inventories.java index 8175cd221c..2901528794 100644 --- a/src/main/java/carpet/script/api/Inventories.java +++ b/src/main/java/carpet/script/api/Inventories.java @@ -30,6 +30,7 @@ import net.minecraft.commands.arguments.item.ItemInput; import net.minecraft.core.HolderSet; import net.minecraft.core.Registry; +import net.minecraft.core.RegistryAccess; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; @@ -66,10 +67,10 @@ public static void apply(Expression expression) expression.addContextFunction("item_list", -1, (c, t, lv) -> { - if (lv.size() == 0) - return ListValue.wrap(BuiltInRegistries.ITEM.keySet().stream().map(ValueConversions::of).collect(Collectors.toList())); CarpetContext cc = (CarpetContext)c; Registry items = cc.registry(Registries.ITEM); + if (lv.size() == 0) + return ListValue.wrap(items.keySet().stream().map(ValueConversions::of).collect(Collectors.toList())); String tag = lv.get(0).getString(); Optional> itemTag = items.getTag(TagKey.create(Registries.ITEM, InputValidator.identifierOf(tag))); if (itemTag.isEmpty()) return Value.NULL; @@ -125,13 +126,14 @@ public static void apply(Expression expression) if (lv.size() > 1) { String recipeType = lv.get(1).getString(); - type = BuiltInRegistries.RECIPE_TYPE.get(InputValidator.identifierOf(recipeType)); + type = cc.registry(Registries.RECIPE_TYPE).get(InputValidator.identifierOf(recipeType)); } List> recipes; - recipes = ((RecipeManagerInterface) cc.server().getRecipeManager()).getAllMatching(type, InputValidator.identifierOf(recipeName)); + recipes = ((RecipeManagerInterface) cc.server().getRecipeManager()).getAllMatching(type, InputValidator.identifierOf(recipeName), cc.registryAccess()); if (recipes.isEmpty()) return Value.NULL; List recipesOutput = new ArrayList<>(); + RegistryAccess regs = cc.registryAccess(); for (Recipe recipe: recipes) { ItemStack result = recipe.getResultItem(); @@ -150,7 +152,7 @@ public static void apply(Expression expression) else { List alternatives = new ArrayList<>(); - stacks.forEach(col -> col.stream().map(ValueConversions::of).forEach(alternatives::add)); + stacks.forEach(col -> col.stream().map(is -> ValueConversions.of(is, regs)).forEach(alternatives::add)); ingredientValue.add(ListValue.wrap(alternatives)); } } @@ -189,19 +191,20 @@ else if (recipe instanceof CustomRecipe) recipeSpec = ListValue.of(new StringValue("custom")); } - recipesOutput.add(ListValue.of(ValueConversions.of(result), ListValue.wrap(ingredientValue), recipeSpec)); + recipesOutput.add(ListValue.of(ValueConversions.of(result, regs), ListValue.wrap(ingredientValue), recipeSpec)); } return ListValue.wrap(recipesOutput); }); - expression.addUnaryFunction("crafting_remaining_item", v -> + expression.addContextFunction("crafting_remaining_item", 1, (c, t, v) -> { - String itemStr = v.getString(); + String itemStr = v.get(0).getString(); Item item; ResourceLocation id = InputValidator.identifierOf(itemStr); - item = BuiltInRegistries.ITEM.getOptional(id).orElseThrow(() -> new ThrowStatement(itemStr, Throwables.UNKNOWN_ITEM)); + Registry registry = ((CarpetContext)c).registry(Registries.ITEM); + item = registry.getOptional(id).orElseThrow(() -> new ThrowStatement(itemStr, Throwables.UNKNOWN_ITEM)); if (!item.hasCraftingRemainingItem()) return Value.NULL; - return new StringValue(NBTSerializableValue.nameFromRegistryId(BuiltInRegistries.ITEM.getKey(item.getCraftingRemainingItem()))); + return new StringValue(NBTSerializableValue.nameFromRegistryId(registry.getKey(item.getCraftingRemainingItem()))); }); expression.addContextFunction("inventory_size", -1, (c, t, lv) -> @@ -226,17 +229,18 @@ else if (recipe instanceof CustomRecipe) CarpetContext cc = (CarpetContext) c; NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); if (inventoryLocator == null) return Value.NULL; + RegistryAccess regs = cc.registryAccess(); if (lv.size() == inventoryLocator.offset()) { List fullInventory = new ArrayList<>(); for (int i = 0, maxi = inventoryLocator.inventory().getContainerSize(); i < maxi; i++) - fullInventory.add(ValueConversions.of(inventoryLocator.inventory().getItem(i))); + fullInventory.add(ValueConversions.of(inventoryLocator.inventory().getItem(i), regs)); return ListValue.wrap(fullInventory); } int slot = (int)NumericValue.asNumber(lv.get(inventoryLocator.offset())).getLong(); slot = NBTSerializableValue.validateSlot(slot, inventoryLocator.inventory()); if (slot == inventoryLocator.inventory().getContainerSize()) return Value.NULL; - return ValueConversions.of(inventoryLocator.inventory().getItem(slot)); + return ValueConversions.of(inventoryLocator.inventory().getItem(slot), regs); }); //inventory_set(, , , , ) @@ -251,13 +255,14 @@ else if (recipe instanceof CustomRecipe) slot = NBTSerializableValue.validateSlot(slot, inventoryLocator.inventory()); if (slot == inventoryLocator.inventory().getContainerSize()) return Value.NULL; int count = (int) NumericValue.asNumber(lv.get(inventoryLocator.offset()+1)).getLong(); + RegistryAccess regs = cc.registryAccess(); if (count == 0) { // clear slot ItemStack removedStack = inventoryLocator.inventory().removeItemNoUpdate(slot); syncPlayerInventory(inventoryLocator, slot); //Value res = ListValue.fromItemStack(removedStack); // that tuple will be read only but cheaper if noone cares - return ValueConversions.of(removedStack); + return ValueConversions.of(removedStack, regs); } if (lv.size() < inventoryLocator.offset()+3) { @@ -266,7 +271,7 @@ else if (recipe instanceof CustomRecipe) newStack.setCount(count); inventoryLocator.inventory().setItem(slot, newStack); syncPlayerInventory(inventoryLocator, slot); - return ValueConversions.of(previousStack); + return ValueConversions.of(previousStack, regs); } CompoundTag nbt = null; // skipping one argument if (lv.size() > inventoryLocator.offset()+3) @@ -290,7 +295,7 @@ else if (nbtValue.isNull()) { throw new InternalExpressionException(e.getMessage()); } - return ValueConversions.of(previousStack); + return ValueConversions.of(previousStack, regs); }); //inventory_find(, or null (first empty slot), ) -> or null diff --git a/src/main/java/carpet/script/api/WorldAccess.java b/src/main/java/carpet/script/api/WorldAccess.java index b56add393b..cc9a546f3d 100644 --- a/src/main/java/carpet/script/api/WorldAccess.java +++ b/src/main/java/carpet/script/api/WorldAccess.java @@ -279,6 +279,7 @@ public static void apply(Expression expression) BlockArgument locator = BlockArgument.findIn(cc, lv, 0, false); BlockPos pos = locator.block.getPos(); PoiManager store = cc.level().getPoiManager(); + Registry poiReg = cc.registry(Registries.POINT_OF_INTEREST_TYPE); if (lv.size() == locator.offset) { Optional> foo = store.getType(pos); @@ -297,7 +298,7 @@ public static void apply(Expression expression) if (poi == null) return Value.NULL; return ListValue.of( - ValueConversions.of(BuiltInRegistries.POINT_OF_INTEREST_TYPE.getKey(poi.getPoiType().value())), + ValueConversions.of(poiReg.getKey(poi.getPoiType().value())), new NumericValue(poiType.maxTickets() - ((PoiRecord_scarpetMixin)poi).getFreeTickets()) ); } @@ -311,7 +312,7 @@ public static void apply(Expression expression) String poiType = lv.get(locator.offset+1).getString().toLowerCase(Locale.ROOT); if (!"any".equals(poiType)) { - PoiType type = BuiltInRegistries.POINT_OF_INTEREST_TYPE.getOptional(InputValidator.identifierOf(poiType)) + PoiType type = poiReg.getOptional(InputValidator.identifierOf(poiType)) .orElseThrow(() -> new ThrowStatement(poiType, Throwables.UNKNOWN_POI)); condition = (tt) -> tt.value() == type; } @@ -337,7 +338,7 @@ else if (!("any".equals(statusString))) store.getInRange(condition, pos, radius, status); return ListValue.wrap(pois.sorted(Comparator.comparingDouble(p -> p.getPos().distSqr(pos))).map(p -> ListValue.of( - ValueConversions.of(BuiltInRegistries.POINT_OF_INTEREST_TYPE.getKey(p.getPoiType().value())), + ValueConversions.of(poiReg.getKey(p.getPoiType().value())), new NumericValue(p.getPoiType().value().maxTickets() - ((PoiRecord_scarpetMixin)p).getFreeTickets()), ValueConversions.of(p.getPos()) ) @@ -362,9 +363,10 @@ else if (!("any".equals(statusString))) } String poiTypeString = poi.getString().toLowerCase(Locale.ROOT); ResourceLocation resource = InputValidator.identifierOf(poiTypeString); - PoiType type = BuiltInRegistries.POINT_OF_INTEREST_TYPE.getOptional(resource) + Registry poiReg = cc.registry(Registries.POINT_OF_INTEREST_TYPE); + PoiType type = poiReg.getOptional(resource) .orElseThrow(() -> new ThrowStatement(poiTypeString, Throwables.UNKNOWN_POI)); - Holder holder = BuiltInRegistries.POINT_OF_INTEREST_TYPE.getHolderOrThrow(ResourceKey.create(Registries.POINT_OF_INTEREST_TYPE, resource)); + Holder holder = poiReg.getHolderOrThrow(ResourceKey.create(Registries.POINT_OF_INTEREST_TYPE, resource)); int occupancy = 0; if (locator.offset + 1 < lv.size()) @@ -822,7 +824,7 @@ else if (args.get(0) instanceof MapValue) { playerBreak = true; String itemString = val.getString(); - item = BuiltInRegistries.ITEM.getOptional(InputValidator.identifierOf(itemString)) + item = cc.registry(Registries.ITEM).getOptional(InputValidator.identifierOf(itemString)) .orElseThrow(() -> new ThrowStatement(itemString, Throwables.UNKNOWN_ITEM)); } } @@ -971,7 +973,7 @@ else if (enVal instanceof EntityValue) attacker = (LivingEntity) attackingEntity; } else throw new InternalExpressionException("Attacking entity needs to be a living thing, "+ - ValueConversions.of(BuiltInRegistries.ENTITY_TYPE.getKey(attackingEntity.getType())).getString() +" ain't it."); + ValueConversions.of(cc.registry(Registries.ENTITY_TYPE).getKey(attackingEntity.getType())).getString() +" ain't it."); } else @@ -1131,12 +1133,12 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin expression.addContextFunction("block_list", -1, (c, t, lv) -> { - if (lv.size() == 0) - return ListValue.wrap(BuiltInRegistries.BLOCK.keySet().stream().map(ValueConversions::of).collect(Collectors.toList())); CarpetContext cc = (CarpetContext)c; + Registry blocks = cc.registry(Registries.BLOCK); + if (lv.size() == 0) + return ListValue.wrap(blocks.keySet().stream().map(ValueConversions::of).collect(Collectors.toList())); ResourceLocation tag = InputValidator.identifierOf(lv.get(0).getString()); - Registry blocks = cc.registry(Registries.BLOCK); Optional> tagset = blocks.getTag(TagKey.create(Registries.BLOCK, tag)); if (tagset.isEmpty()) return Value.NULL; return ListValue.wrap(tagset.get().stream().map(b -> ValueConversions.of(blocks.getKey(b.value()))).collect(Collectors.toList())); @@ -1344,7 +1346,7 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin } else { - StructureType sss = BuiltInRegistries.STRUCTURE_TYPE.get(id); + StructureType sss = cc.registry(Registries.STRUCTURE_TYPE).get(id); reg.entrySet().stream().filter(e -> e.getValue().type() ==sss).forEach(e -> structure.add(e.getValue())); } if (structure.isEmpty()) @@ -1371,7 +1373,7 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin StructureStart start = FeatureGenerator.shouldStructureStartAt(world, pos, structure.get(0), needSize); if (start == null) return Value.NULL; if (!needSize) return Value.TRUE; - return ValueConversions.of(start); + return ValueConversions.of(start, cc.registryAccess()); } Map ret = new HashMap<>(); for(Structure str: structure) @@ -1390,7 +1392,7 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin if (start == null) continue; Value key = new StringValue(NBTSerializableValue.nameFromRegistryId(reg.getKey(str))); - ret.put(key, (!needSize)?Value.NULL: ValueConversions.of(start)); + ret.put(key, (!needSize)?Value.NULL: ValueConversions.of(start, cc.registryAccess())); } return MapValue.wrap(ret); }); @@ -1420,7 +1422,7 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin return MapValue.wrap(structureList); } String structureName = lv.get(locator.offset).getString().toLowerCase(Locale.ROOT); - return ValueConversions.of(structures.get(reg.get(InputValidator.identifierOf(structureName)))); + return ValueConversions.of(structures.get(reg.get(InputValidator.identifierOf(structureName))), cc.registryAccess()); }); expression.addContextFunction("set_structure", -1, (c, t, lv) -> diff --git a/src/main/java/carpet/script/argument/BlockArgument.java b/src/main/java/carpet/script/argument/BlockArgument.java index e29d28a31c..b2e66c9300 100644 --- a/src/main/java/carpet/script/argument/BlockArgument.java +++ b/src/main/java/carpet/script/argument/BlockArgument.java @@ -60,7 +60,7 @@ public static BlockArgument findIn(CarpetContext c, Iterator params, int } if (acceptString && v1 instanceof StringValue) { - return new BlockArgument(BlockValue.fromString(v1.getString(), c.registryAccess()), 1 + offset); + return new BlockArgument(BlockValue.fromString(v1.getString(), c.level()), 1 + offset); } if (v1 instanceof BlockValue) { diff --git a/src/main/java/carpet/script/command/CommandArgument.java b/src/main/java/carpet/script/command/CommandArgument.java index 67bfb37e96..280e10e93d 100644 --- a/src/main/java/carpet/script/command/CommandArgument.java +++ b/src/main/java/carpet/script/command/CommandArgument.java @@ -2,6 +2,7 @@ import carpet.CarpetServer; import carpet.fakes.BlockStateArgumentInterface; +import carpet.script.CarpetContext; import carpet.script.CarpetScriptHost; import carpet.script.argument.FunctionArgument; import carpet.script.value.BlockValue; @@ -136,7 +137,7 @@ public static CommandSyntaxException error(String text) new VanillaUnconfigurableArgument( "block", BlockStateArgument::block, (c, p) -> { BlockInput result = BlockStateArgument.getBlock(c, p); - return new BlockValue(result.getState(), null, null, ((BlockStateArgumentInterface)result).getCMTag() ); + return new BlockValue(result.getState(), c.getSource().getLevel(), null, ((BlockStateArgumentInterface)result).getCMTag() ); }, param -> (ctx, builder) -> ctx.getArgument(param, BlockStateArgument.class).listSuggestions(ctx, builder) ), @@ -179,7 +180,7 @@ public static CommandSyntaxException error(String text) // item_predicate ?? //same as item but accepts tags, not sure right now new SlotArgument(), new VanillaUnconfigurableArgument("item", ItemArgument::item, - (c, p) -> ValueConversions.of(ItemArgument.getItem(c, p).createItemStack(1, false)), + (c, p) -> ValueConversions.of(ItemArgument.getItem(c, p).createItemStack(1, false), c.getSource().registryAccess()), param -> (ctx, builder) -> ctx.getArgument(param, ItemArgument.class).listSuggestions(ctx, builder) ), new VanillaUnconfigurableArgument("message", MessageArgument::message, @@ -211,7 +212,7 @@ public static CommandSyntaxException error(String text) (c, p) -> ValueConversions.of( ResourceLocationArgument.getAdvancement(c, p).getId()), (ctx, builder) -> SharedSuggestionProvider.suggestResource(ctx.getSource().getServer().getAdvancements().getAllAdvancements().stream().map(Advancement::getId), builder) ), new VanillaUnconfigurableArgument("lootcondition", ResourceLocationArgument::id, - (c, p) -> ValueConversions.of( BuiltInRegistries.LOOT_CONDITION_TYPE.getKey(ResourceLocationArgument.getPredicate(c, p).getType())), (ctx, builder) -> SharedSuggestionProvider.suggestResource(ctx.getSource().getServer().getPredicateManager().getKeys(), builder) + (c, p) -> ValueConversions.of( c.getSource().registryAccess().registryOrThrow(Registries.LOOT_CONDITION_TYPE).getKey(ResourceLocationArgument.getPredicate(c, p).getType())), (ctx, builder) -> SharedSuggestionProvider.suggestResource(ctx.getSource().getServer().getPredicateManager().getKeys(), builder) ), new VanillaUnconfigurableArgument("loottable", ResourceLocationArgument::id, (c, p) -> ValueConversions.of( ResourceLocationArgument.getId(c, p)), (ctx, builder) -> SharedSuggestionProvider.suggestResource(ctx.getSource().getServer().getLootTables().getIds(), builder) diff --git a/src/main/java/carpet/script/utils/ShapeDispatcher.java b/src/main/java/carpet/script/utils/ShapeDispatcher.java index d16fdae6fb..724e963969 100644 --- a/src/main/java/carpet/script/utils/ShapeDispatcher.java +++ b/src/main/java/carpet/script/utils/ShapeDispatcher.java @@ -29,6 +29,7 @@ import net.minecraft.commands.arguments.ParticleArgument; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.Registry; import net.minecraft.core.RegistryAccess; import net.minecraft.core.particles.ParticleOptions; import net.minecraft.core.registries.BuiltInRegistries; @@ -67,6 +68,7 @@ import java.util.Map; import java.util.Random; import java.util.Set; +import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; @@ -214,9 +216,9 @@ public static ExpiringShape create(MinecraftServer server, String shapeType, Map if (param==null) throw new InternalExpressionException("Unknown feature for shape: "+key); userParams.put(key, param.validate(userParams, server, userParams.get(key))); }); - Function,ExpiringShape> factory = ExpiringShape.shapeProviders.get(shapeType); + BiFunction, RegistryAccess, ExpiringShape> factory = ExpiringShape.shapeProviders.get(shapeType); if (factory == null) throw new InternalExpressionException("Unknown shape: "+shapeType); - return factory.apply(userParams); + return factory.apply(userParams, server.registryAccess()); } // client @@ -240,7 +242,7 @@ public static ExpiringShape fromTag(CompoundTag tag, Level level) CarpetSettings.LOG.info("Shape id missing in "+ String.join(", ", tag.getAllKeys())); return null; } - Function,ExpiringShape> factory = ExpiringShape.shapeProviders.get(shapeValue.getString()); + BiFunction, RegistryAccess, ExpiringShape> factory = ExpiringShape.shapeProviders.get(shapeValue.getString()); if (factory == null) { CarpetSettings.LOG.info("Unknown shape: "+shapeValue.getString()); @@ -248,7 +250,7 @@ public static ExpiringShape fromTag(CompoundTag tag, Level level) } try { - return factory.apply(options); + return factory.apply(options, level.registryAccess()); } catch (InternalExpressionException exc) { @@ -259,7 +261,7 @@ public static ExpiringShape fromTag(CompoundTag tag, Level level) public abstract static class ExpiringShape { - public static final Map,ExpiringShape>> shapeProviders = new HashMap, ExpiringShape>>(){{ + public static final Map, RegistryAccess, ExpiringShape>> shapeProviders = new HashMap, RegistryAccess, ExpiringShape>>(){{ put("line", creator(Line::new)); put("box", creator(Box::new)); put("sphere", creator(Sphere::new)); @@ -269,11 +271,11 @@ public abstract static class ExpiringShape put("block",creator(()->new DisplayedSprite(false))); put("item",creator(()->new DisplayedSprite(true))); }}; - private static Function,ExpiringShape> creator(Supplier shapeFactory) + private static BiFunction, RegistryAccess, ExpiringShape> creator(Supplier shapeFactory) { - return o -> { + return (o, regs) -> { ExpiringShape shape = shapeFactory.get(); - shape.fromOptions(o); + shape.fromOptions(o, regs); return shape; }; } @@ -305,7 +307,7 @@ public static CompoundTag toTag(Map params) return tag; } - private void fromOptions(Map options) + private void fromOptions(Map options, RegistryAccess regs) { Set optional = optionalParams(); Set required = requiredParams(); @@ -318,12 +320,12 @@ private void fromOptions(Map options) if (!this.canTake(k)) throw new InternalExpressionException("Parameter "+k+" doesn't apply for shape "+options.get("shape").getString()); }); - init(options); + init(options, regs); } - protected void init(Map options) + protected void init(Map options, RegistryAccess regs) { duration = NumericValue.asNumber(options.get("duration")).getInt(); @@ -399,13 +401,13 @@ protected ParticleOptions replacementParticle(RegistryAccess regs) public abstract Consumer alternative(); - public long key() + public long key(final RegistryAccess regs) { if (key!=0) return key; - key = calcKey(); + key = calcKey(regs); return key; } - protected long calcKey() + protected long calcKey(final RegistryAccess regs) { // using FNV-1a algorithm long hash = -3750763034362895579L; hash ^= shapeDimension.hashCode(); hash *= 1099511628211L; @@ -487,9 +489,9 @@ public DisplayedText() { } boolean doublesided; @Override - protected void init(Map options) + protected void init(Map options, RegistryAccess regs) { - super.init(options); + super.init(options, regs); pos = vecFromValue(options.get("pos")); value = ((FormattedTextValue)options.get("text")).getText(); text = value.getString(); @@ -543,9 +545,9 @@ public Consumer alternative() } @Override - public long calcKey() + public long calcKey(final RegistryAccess regs) { - long hash = super.calcKey(); + long hash = super.calcKey(regs); hash ^= 5; hash *= 1099511628211L; hash ^= vec3dhash(pos); hash *= 1099511628211L; hash ^= text.hashCode(); hash *= 1099511628211L; @@ -607,9 +609,9 @@ public DisplayedSprite(boolean i) String itemTransformType; @Override - protected void init(Map options) + protected void init(Map options, RegistryAccess regs) { - super.init(options); + super.init(options, regs); pos = vecFromValue(options.get("pos")); if (!this.isitem) { @@ -648,14 +650,15 @@ protected void init(Map options) public Consumer alternative() { return p -> { ParticleOptions particle; + final Registry blocks = p.getServer().registryAccess().registryOrThrow(Registries.BLOCK); if(this.isitem) { if (Block.byItem(this.item.getItem()).defaultBlockState().isAir()) return; - particle = getParticleData("block_marker "+ BuiltInRegistries.BLOCK.getKey(Block.byItem(this.item.getItem())), p.level.registryAccess()); + particle = getParticleData("block_marker " + blocks.getKey(Block.byItem(this.item.getItem())), p.level.registryAccess()); } else { - particle = getParticleData("block_marker "+BuiltInRegistries.BLOCK.getKey(this.blockState.getBlock()), p.level.registryAccess()); + particle = getParticleData("block_marker " + blocks.getKey(this.blockState.getBlock()), p.level.registryAccess()); } Vec3 v = relativiseRender(p.level, this.pos, 0); @@ -664,8 +667,8 @@ public Consumer alternative() { } @Override - public long calcKey() { - long hash = super.calcKey(); + public long calcKey(final RegistryAccess regs) { + long hash = super.calcKey(regs); hash ^= 7; hash *= 1099511628211L; hash ^= Boolean.hashCode(isitem); hash *= 1099511628211L; hash ^= vec3dhash(pos); hash *= 1099511628211L; @@ -680,7 +683,7 @@ public long calcKey() { hash ^= Float.hashCode(blockLight); hash *= 1099511628211L; if (blockEntity!= null) hash ^= blockEntity.toString().hashCode(); hash *= 1099511628211L; if (blockState!= null) hash ^= blockState.hashCode(); hash *= 1099511628211L; - hash ^= ValueConversions.of(item).getString().hashCode(); hash *= 1099511628211L; + hash ^= ValueConversions.of(item, regs).getString().hashCode(); hash *= 1099511628211L; hash ^= itemTransformType.hashCode(); hash *= 1099511628211L; return hash; @@ -702,9 +705,9 @@ public Box() { } Vec3 to; @Override - protected void init(Map options) + protected void init(Map options, RegistryAccess regs) { - super.init(options); + super.init(options, regs); from = vecFromValue(options.get("from")); to = vecFromValue(options.get("to")); } @@ -729,9 +732,9 @@ public Consumer alternative() } @Override - public long calcKey() + public long calcKey(final RegistryAccess regs) { - long hash = super.calcKey(); + long hash = super.calcKey(regs); hash ^= 1; hash *= 1099511628211L; hash ^= vec3dhash(from); hash *= 1099511628211L; hash ^= vec3dhash(to); hash *= 1099511628211L; @@ -768,8 +771,8 @@ public static int particleMesh(List playerList, ParticleOptions pa public static class Polyface extends ExpiringShape { @Override - public long calcKey(){ - long hash = super.calcKey(); + public long calcKey(final RegistryAccess regs){ + long hash = super.calcKey(regs); hash ^= 6; hash *= 1099511628211L; hash ^= mode.hashCode(); hash *= 1099511628211L; hash ^= relative.hashCode(); hash *= 1099511628211L; @@ -898,9 +901,9 @@ public Consumer alternative() { ArrayList relative=new ArrayList<>(); boolean inneredges; @Override - protected void init(Map options) + protected void init(Map options, RegistryAccess regs) { - super.init(options); + super.init(options, regs); doublesided=options.getOrDefault("doublesided",optional.get("doublesided")).getBoolean(); @@ -962,9 +965,9 @@ private Line() Vec3 to; @Override - protected void init(Map options) + protected void init(Map options, RegistryAccess regs) { - super.init(options); + super.init(options, regs); from = vecFromValue(options.get("from")); to = vecFromValue(options.get("to")); } @@ -986,9 +989,9 @@ public Consumer alternative() } @Override - public long calcKey() + public long calcKey(final RegistryAccess regs) { - long hash = super.calcKey(); + long hash = super.calcKey(regs); hash ^= 2; hash *= 1099511628211L; hash ^= vec3dhash(from); hash *= 1099511628211L; hash ^= vec3dhash(to); hash *= 1099511628211L; @@ -1016,9 +1019,9 @@ private Sphere() int subdivisions; @Override - protected void init(Map options) + protected void init(Map options, RegistryAccess regs) { - super.init(options); + super.init(options, regs); center = vecFromValue(options.get("center")); radius = NumericValue.asNumber(options.get("radius")).getFloat(); level = NumericValue.asNumber(options.getOrDefault("level", optional.get("level"))).getInt(); @@ -1059,9 +1062,9 @@ public Consumer alternative() { return p -> };} @Override - public long calcKey() + public long calcKey(final RegistryAccess regs) { - long hash = super.calcKey(); + long hash = super.calcKey(regs); hash ^= 3; hash *= 1099511628211L; hash ^= vec3dhash(center); hash *= 1099511628211L; hash ^= Double.hashCode(radius); hash *= 1099511628211L; @@ -1092,9 +1095,9 @@ public static class Cylinder extends ExpiringShape private Cylinder() { super(); } @Override - protected void init(Map options) + protected void init(Map options, RegistryAccess regs) { - super.init(options); + super.init(options, regs); center = vecFromValue(options.get("center")); radius = NumericValue.asNumber(options.get("radius")).getFloat(); level = NumericValue.asNumber(options.getOrDefault("level", optional.get("level"))).getInt(); @@ -1162,9 +1165,9 @@ else if (axis== Direction.Axis.X) };} @Override - public long calcKey() + public long calcKey(final RegistryAccess regs) { - long hash = super.calcKey(); + long hash = super.calcKey(regs); hash ^= 4; hash *= 1099511628211L; hash ^= vec3dhash(center); hash *= 1099511628211L; hash ^= Double.hashCode(radius); hash *= 1099511628211L; @@ -1307,7 +1310,7 @@ public Value validate(Map options, MinecraftServer server, Value if(value instanceof BlockValue blv){ return value; } - return BlockValue.fromString(value.getString(), server.registryAccess()); + return BlockValue.fromString(value.getString(), server.overworld()); } @Override public Tag toTag(Value value) { @@ -1330,7 +1333,7 @@ public Value decode(Tag tag, Level level) { if (((CompoundTag) tag).contains("TileEntityData", 10)) { compoundTag2 = ((CompoundTag) tag).getCompound("TileEntityData"); } - return new BlockValue(bs, null, null, compoundTag2); + return new BlockValue(bs, level, null, compoundTag2); } } public static class ItemParam extends Param diff --git a/src/main/java/carpet/script/utils/ShapesRenderer.java b/src/main/java/carpet/script/utils/ShapesRenderer.java index 9878c568d4..e7e14ec193 100644 --- a/src/main/java/carpet/script/utils/ShapesRenderer.java +++ b/src/main/java/carpet/script/utils/ShapesRenderer.java @@ -217,9 +217,9 @@ public void renderFaces(Tesselator tessellator, BufferBuilder builder, double cx protected RenderedShape(Minecraft client, T shape) { this.shape = shape; - expiryTick = client.level.getGameTime()+shape.getExpiry(); - renderEpsilon = (3+((double)shape.key())/Long.MAX_VALUE)/1000; this.client = client; + expiryTick = client.level.getGameTime()+shape.getExpiry(); + renderEpsilon = (3+((double)key())/Long.MAX_VALUE)/1000; } public boolean isExpired(long currentTick) @@ -228,7 +228,7 @@ public boolean isExpired(long currentTick) } public long key() { - return shape.key(); + return shape.key(client.level.registryAccess()); }; public boolean shouldRender(ResourceKey dim) { @@ -365,7 +365,7 @@ public void renderLines(PoseStack matrices, Tesselator tessellator, BufferBuilde { // draw the item client.getItemRenderer().renderStatic(shape.item, transformType, light, - OverlayTexture.NO_OVERLAY, matrices, immediate, (int) shape.key()); + OverlayTexture.NO_OVERLAY, matrices, immediate, (int) shape.key(client.level.registryAccess())); } } matrices.popPose(); diff --git a/src/main/java/carpet/script/value/BlockValue.java b/src/main/java/carpet/script/value/BlockValue.java index c22f43a3be..f42cee845a 100644 --- a/src/main/java/carpet/script/value/BlockValue.java +++ b/src/main/java/carpet/script/value/BlockValue.java @@ -18,7 +18,7 @@ import net.minecraft.core.Direction; import net.minecraft.core.Direction.Axis; import net.minecraft.core.GlobalPos; -import net.minecraft.core.RegistryAccess; +import net.minecraft.core.Registry; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; @@ -29,23 +29,22 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.Property; import net.minecraft.world.level.chunk.LevelChunk; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.NotNull; import static carpet.script.value.NBTSerializableValue.nameFromRegistryId; public class BlockValue extends Value { - public static final BlockValue AIR = new BlockValue(Blocks.AIR.defaultBlockState(), null, BlockPos.ZERO); - public static final BlockValue NULL = new BlockValue(null, null, null); private BlockState blockState; private final BlockPos pos; - private final ServerLevel world; + @NotNull private final Level world; private CompoundTag data; public static BlockValue fromCoords(CarpetContext c, int x, int y, int z) @@ -55,19 +54,19 @@ public static BlockValue fromCoords(CarpetContext c, int x, int y, int z) } private static final Map bvCache= new HashMap<>(); - public static BlockValue fromString(String str, RegistryAccess regs) + public static BlockValue fromString(String str, Level level) { try { BlockValue bv = bvCache.get(str); // [SCARY SHIT] persistent caches over server reloads if (bv != null) return bv; - BlockStateParser.BlockResult foo = BlockStateParser.parseForBlock(regs.lookupOrThrow(Registries.BLOCK), new StringReader(str), true ); + BlockStateParser.BlockResult foo = BlockStateParser.parseForBlock(level.registryAccess().lookupOrThrow(Registries.BLOCK), new StringReader(str), true ); if (foo.blockState() != null) { CompoundTag bd = foo.nbt(); if (bd == null) bd = new CompoundTag(); - bv = new BlockValue(foo.blockState(), null, null, bd ); + bv = new BlockValue(foo.blockState(), level, null, bd ); if (bvCache.size()>10000) bvCache.clear(); bvCache.put(str, bv); @@ -92,7 +91,7 @@ public BlockState getBlockState() { return blockState; } - if (world != null && pos != null) + if (pos != null) { blockState = world.getBlockState(pos); return blockState; @@ -100,12 +99,15 @@ public BlockState getBlockState() throw new InternalExpressionException("Attempted to fetch block state without world or stored block state"); } - public static BlockEntity getBlockEntity(ServerLevel world, BlockPos pos) + public static BlockEntity getBlockEntity(Level level, BlockPos pos) { - if (world.getServer().isSameThread()) - return world.getBlockEntity(pos); - else - return world.getChunkAt(pos).getBlockEntity(pos, LevelChunk.EntityCreationType.IMMEDIATE); + if (level instanceof ServerLevel serverLevel) { + if (serverLevel.getServer().isSameThread()) + return serverLevel.getBlockEntity(pos); + else + return serverLevel.getChunkAt(pos).getBlockEntity(pos, LevelChunk.EntityCreationType.IMMEDIATE); + } + return null; } @@ -117,7 +119,7 @@ public CompoundTag getData() return null; return data; } - if (world != null && pos != null) + if (pos != null) { BlockEntity be = getBlockEntity(world, pos); if (be == null) @@ -132,7 +134,7 @@ public CompoundTag getData() } - public BlockValue(BlockState state, ServerLevel world, BlockPos position) + public BlockValue(BlockState state, @NotNull Level world, BlockPos position) { this.world = world; blockState = state; @@ -140,7 +142,7 @@ public BlockValue(BlockState state, ServerLevel world, BlockPos position) data = null; } - public BlockValue(BlockState state, ServerLevel world, BlockPos position, CompoundTag nbt) + public BlockValue(BlockState state, @NotNull Level world, BlockPos position, CompoundTag nbt) { this.world = world; blockState = state; @@ -152,13 +154,14 @@ public BlockValue(BlockState state, ServerLevel world, BlockPos position, Compou @Override public String getString() { - return nameFromRegistryId(BuiltInRegistries.BLOCK.getKey(getBlockState().getBlock())); + Registry blockRegistry = world.registryAccess().registryOrThrow(Registries.BLOCK); + return nameFromRegistryId(blockRegistry.getKey(getBlockState().getBlock())); } @Override public boolean getBoolean() { - return this != NULL && !getBlockState().isAir(); + return !getBlockState().isAir(); } @Override @@ -176,7 +179,7 @@ public Value clone() @Override public int hashCode() { - if (world != null && pos != null ) + if (pos != null ) return GlobalPos.of(world.dimension() , pos).hashCode(); //getDimension().getType() return ("b"+getString()).hashCode(); } @@ -186,7 +189,7 @@ public BlockPos getPos() return pos; } - public ServerLevel getWorld() { return world;} + public Level getWorld() { return world;} @Override public Tag toTag(boolean force) @@ -196,7 +199,7 @@ public Tag toTag(boolean force) CompoundTag tag = new CompoundTag(); CompoundTag state = new CompoundTag(); BlockState s = getBlockState(); - state.put("Name", StringTag.valueOf(BuiltInRegistries.BLOCK.getKey(s.getBlock()).toString())); + state.put("Name", StringTag.valueOf(world.registryAccess().registryOrThrow(Registries.BLOCK).getKey(s.getBlock()).toString())); Collection> properties = s.getProperties(); if (!properties.isEmpty()) { diff --git a/src/main/java/carpet/script/value/EntityValue.java b/src/main/java/carpet/script/value/EntityValue.java index 6141e69eb5..cdb314bd9b 100644 --- a/src/main/java/carpet/script/value/EntityValue.java +++ b/src/main/java/carpet/script/value/EntityValue.java @@ -24,6 +24,8 @@ import net.minecraft.core.Direction; import net.minecraft.core.Holder; import net.minecraft.core.HolderSet; +import net.minecraft.core.Registry; +import net.minecraft.core.RegistryAccess; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; @@ -274,7 +276,7 @@ public static EntityClassDescriptor getEntityDescriptor(String who, MinecraftSer } else { - return new EntityClassDescriptor(ANY, e -> !eTag.contains(e.getType()) && e.isAlive(), BuiltInRegistries.ENTITY_TYPE.stream().filter(et -> !eTag.contains(et))); + return new EntityClassDescriptor(ANY, e -> !eTag.contains(e.getType()) && e.isAlive(), server.registryAccess().registryOrThrow(Registries.ENTITY_TYPE).stream().filter(et -> !eTag.contains(et))); } } return eDesc; @@ -300,8 +302,9 @@ public static class EntityClassDescriptor this(type, predicate, types.toList()); } - public Value listValue() { - return ListValue.wrap(types.stream().map(et -> StringValue.of(nameFromRegistryId(BuiltInRegistries.ENTITY_TYPE.getKey(et))))); + public Value listValue(RegistryAccess regs) { + final Registry entityRegs = regs.registryOrThrow(Registries.ENTITY_TYPE); + return ListValue.wrap(types.stream().map(et -> StringValue.of(nameFromRegistryId(entityRegs.getKey(et))))); } public final static Map byName = new HashMap<>() {{ @@ -449,7 +452,7 @@ public Value get(String what, Value arg) put("display_name", (e, a) -> new FormattedTextValue(e.getDisplayName())); put("command_name", (e, a) -> new StringValue(e.getScoreboardName())); put("custom_name", (e, a) -> e.hasCustomName()?new StringValue(e.getCustomName().getString()):Value.NULL); - put("type", (e, a) -> new StringValue(nameFromRegistryId(BuiltInRegistries.ENTITY_TYPE.getKey(e.getType())))); + put("type", (e, a) -> new StringValue(nameFromRegistryId(e.getLevel().registryAccess().registryOrThrow(Registries.ENTITY_TYPE).getKey(e.getType())))); put("is_riding", (e, a) -> BooleanValue.of(e.isPassenger())); put("is_ridden", (e, a) -> BooleanValue.of(e.isVehicle())); put("passengers", (e, a) -> ListValue.wrap(e.getPassengers().stream().map(EntityValue::new).collect(Collectors.toList()))); @@ -529,9 +532,9 @@ public Value get(String what, Value arg) }); put("item", (e, a) -> { if(e instanceof ItemEntity) - return ValueConversions.of(((ItemEntity) e).getItem()); + return ValueConversions.of(((ItemEntity) e).getItem(), e.getServer().registryAccess()); if(e instanceof ItemFrame) - return ValueConversions.of(((ItemFrame) e).getItem()); + return ValueConversions.of(((ItemFrame) e).getItem(), e.getServer().registryAccess()); return Value.NULL; }); put("count", (e, a) -> (e instanceof ItemEntity)?new NumericValue(((ItemEntity) e).getItem().getCount()):Value.NULL); @@ -657,7 +660,7 @@ public Value get(String what, Value arg) put("brain", (e, a) -> { String module = a.getString(); - MemoryModuleType moduleType = BuiltInRegistries.MEMORY_MODULE_TYPE.get(InputValidator.identifierOf(module)); + MemoryModuleType moduleType = e.getLevel().registryAccess().registryOrThrow(Registries.MEMORY_MODULE_TYPE).get(InputValidator.identifierOf(module)); if (moduleType == MemoryModuleType.DUMMY) return Value.NULL; if (e instanceof LivingEntity livingEntity) { @@ -820,7 +823,7 @@ public Value get(String what, Value arg) if (where == null) throw new InternalExpressionException("Unknown inventory slot: "+a.getString()); if (e instanceof LivingEntity) - return ValueConversions.of(((LivingEntity)e).getItemBySlot(where)); + return ValueConversions.of(((LivingEntity)e).getItemBySlot(where), e.getServer().registryAccess()); return Value.NULL; }); @@ -931,13 +934,14 @@ else if (entities) put("attribute", (e, a) ->{ if (!(e instanceof LivingEntity)) return Value.NULL; LivingEntity el = (LivingEntity)e; + final Registry attributes = e.getLevel().registryAccess().registryOrThrow(Registries.ATTRIBUTE); if (a == null) { AttributeMap container = el.getAttributes(); - return MapValue.wrap(BuiltInRegistries.ATTRIBUTE.stream().filter(container::hasAttribute).collect(Collectors.toMap(aa -> ValueConversions.of(BuiltInRegistries.ATTRIBUTE.getKey(aa)), aa -> NumericValue.of(container.getValue(aa))))); + return MapValue.wrap(attributes.stream().filter(container::hasAttribute).collect(Collectors.toMap(aa -> ValueConversions.of(attributes.getKey(aa)), aa -> NumericValue.of(container.getValue(aa))))); } ResourceLocation id = InputValidator.identifierOf(a.getString()); - Attribute attrib = BuiltInRegistries.ATTRIBUTE.getOptional(id).orElseThrow( + Attribute attrib = attributes.getOptional(id).orElseThrow( () -> new InternalExpressionException("Unknown attribute: "+a.getString()) ); if (!el.getAttributes().hasAttribute(attrib)) return Value.NULL; @@ -1717,7 +1721,8 @@ public net.minecraft.nbt.Tag toTag(boolean force) if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this); CompoundTag tag = new CompoundTag(); tag.put("Data", getEntity().saveWithoutId( new CompoundTag())); - tag.put("Name", StringTag.valueOf(BuiltInRegistries.ENTITY_TYPE.getKey(getEntity().getType()).toString())); + final Registry> reg = getEntity().level.registryAccess().registryOrThrow(Registries.ENTITY_TYPE); + tag.put("Name", StringTag.valueOf(reg.getKey(getEntity().getType()).toString())); return tag; } } diff --git a/src/main/java/carpet/script/value/ScreenValue.java b/src/main/java/carpet/script/value/ScreenValue.java index 80139a9da1..8ab0ab7885 100644 --- a/src/main/java/carpet/script/value/ScreenValue.java +++ b/src/main/java/carpet/script/value/ScreenValue.java @@ -228,7 +228,7 @@ public boolean onSelectRecipe(ServerPlayer player, Recipe recipe, boolean cra public void slotChanged(AbstractContainerMenu handler, int slotId, ItemStack stack) { Map data = new HashMap<>(); data.put(StringValue.of("slot"),NumericValue.of(slotId)); - data.put(StringValue.of("stack"),ValueConversions.of(stack)); + data.put(StringValue.of("stack"),ValueConversions.of(stack, player.level.registryAccess())); ScreenValue.this.callListener(ScreenValue.this.player,"slot_update",data); } @Override diff --git a/src/main/java/carpet/script/value/ValueConversions.java b/src/main/java/carpet/script/value/ValueConversions.java index 05c4f44c1f..6b28bfd034 100644 --- a/src/main/java/carpet/script/value/ValueConversions.java +++ b/src/main/java/carpet/script/value/ValueConversions.java @@ -11,6 +11,7 @@ import net.minecraft.commands.arguments.item.ItemInput; import net.minecraft.core.BlockPos; import net.minecraft.core.GlobalPos; +import net.minecraft.core.Registry; import net.minecraft.core.RegistryAccess; import net.minecraft.core.Vec3i; import net.minecraft.core.particles.ParticleOptions; @@ -31,6 +32,7 @@ import net.minecraft.world.entity.ai.memory.WalkTarget; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.pattern.BlockInWorld; import net.minecraft.world.level.block.state.properties.Property; @@ -80,6 +82,7 @@ public static Value of(ServerLevel world) public static Value of(MinMaxBounds range) { return ListValue.of(NumericValue.of(range.getMin()), NumericValue.of(range.getMax()));} + @Deprecated public static Value of(ItemStack stack) { if (stack == null || stack.isEmpty()) @@ -90,6 +93,15 @@ public static Value of(ItemStack stack) NBTSerializableValue.fromStack(stack) ); } + public static Value of(ItemStack stack, RegistryAccess regs) { + if (stack == null || stack.isEmpty()) + return Value.NULL; + return ListValue.of( + of(regs.registryOrThrow(Registries.ITEM).getKey(stack.getItem())), + new NumericValue(stack.getCount()), + NBTSerializableValue.fromStack(stack) + ); + } public static Value of(Objective objective) { @@ -318,7 +330,7 @@ public static Value of(BoundingBox box) ); } - public static Value of(StructureStart structure) + public static Value of(StructureStart structure, final RegistryAccess regs) { if (structure == null || structure == StructureStart.INVALID_START) return Value.NULL; BoundingBox boundingBox = structure.getBoundingBox(); @@ -332,7 +344,7 @@ public static Value of(StructureStart structure) if (box.maxX() >= box.minX() && box.maxY() >= box.minY() && box.maxZ() >= box.minZ()) { pieces.add(ListValue.of( - new StringValue(NBTSerializableValue.nameFromRegistryId(BuiltInRegistries.STRUCTURE_PIECE.getKey(piece.getType()))), + new StringValue(NBTSerializableValue.nameFromRegistryId(regs.registryOrThrow(Registries.STRUCTURE_PIECE).getKey(piece.getType()))), (piece.getOrientation() == null) ? Value.NULL : new StringValue(piece.getOrientation().getName()), ListValue.fromTriple(box.minX(), box.minY(), box.minZ()), ListValue.fromTriple(box.maxX(), box.maxY(), box.maxZ()) @@ -406,9 +418,10 @@ public static Value ofVanillaSlotResult(int itemSlot) public static Value ofBlockPredicate(RegistryAccess registryAccess, Predicate blockPredicate) { BlockPredicateInterface predicateData = (BlockPredicateInterface) blockPredicate; + final Registry blocks = registryAccess.registryOrThrow(Registries.BLOCK); return ListValue.of( - predicateData.getCMBlockState()==null?Value.NULL:of(BuiltInRegistries.BLOCK.getKey(predicateData.getCMBlockState().getBlock())), - predicateData.getCMBlockTagKey()==null?Value.NULL:of(registryAccess.registryOrThrow(Registries.BLOCK).getTag(predicateData.getCMBlockTagKey()).get().key()), + predicateData.getCMBlockState()==null?Value.NULL:of(blocks.getKey(predicateData.getCMBlockState().getBlock())), + predicateData.getCMBlockTagKey()==null?Value.NULL:of(blocks.getTag(predicateData.getCMBlockTagKey()).get().key()), MapValue.wrap(predicateData.getCMProperties()), predicateData.getCMDataTag() == null?Value.NULL:new NBTSerializableValue(predicateData.getCMDataTag()) ); @@ -481,7 +494,7 @@ public static Value guess(ServerLevel serverWorld, Object o) { if (o instanceof BoundingBox) return of((BoundingBox) o); if (o instanceof ItemStack) - return of((ItemStack)o); + return of((ItemStack)o, serverWorld.registryAccess()); if (o instanceof Boolean) return BooleanValue.of((Boolean) o); if (o instanceof Number) diff --git a/src/main/java/carpet/utils/BlockInfo.java b/src/main/java/carpet/utils/BlockInfo.java index a9431fd8a9..e1c01773c4 100644 --- a/src/main/java/carpet/utils/BlockInfo.java +++ b/src/main/java/carpet/utils/BlockInfo.java @@ -4,7 +4,9 @@ import java.util.List; import java.util.Map; import net.minecraft.core.BlockPos; +import net.minecraft.core.Registry; import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.EntityType; @@ -227,6 +229,7 @@ public static List blockInfo(BlockPos pos, ServerLevel world) Material material = state.getMaterial(); Block block = state.getBlock(); String metastring = ""; + final Registry blocks = world.registryAccess().registryOrThrow(Registries.BLOCK); for (net.minecraft.world.level.block.state.properties.Property iproperty : state.getProperties()) { metastring += ", "+iproperty.getName() + '='+state.getValue(iproperty); @@ -234,7 +237,7 @@ public static List blockInfo(BlockPos pos, ServerLevel world) List lst = new ArrayList<>(); lst.add(Messenger.s("")); lst.add(Messenger.s("=====================================")); - lst.add(Messenger.s(String.format("Block info for %s%s (id %d%s):", BuiltInRegistries.BLOCK.getKey(block),metastring, BuiltInRegistries.BLOCK.getId(block), metastring ))); + lst.add(Messenger.s(String.format("Block info for %s%s (id %d%s):", blocks.getKey(block),metastring, blocks.getId(block), metastring ))); lst.add(Messenger.s(String.format(" - Material: %s", materialName.get(material)))); lst.add(Messenger.s(String.format(" - Map colour: %s", mapColourName.get(state.getMapColor(world, pos))))); lst.add(Messenger.s(String.format(" - Sound type: %s", soundName.get(block.getSoundType(state))))); diff --git a/src/main/java/carpet/utils/CarpetProfiler.java b/src/main/java/carpet/utils/CarpetProfiler.java index 7218db74e7..a4a0206719 100644 --- a/src/main/java/carpet/utils/CarpetProfiler.java +++ b/src/main/java/carpet/utils/CarpetProfiler.java @@ -3,7 +3,9 @@ import it.unimi.dsi.fastutil.objects.Object2LongMap; import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; import net.minecraft.commands.CommandSourceStack; +import net.minecraft.core.RegistryAccess; import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; @@ -274,13 +276,14 @@ public static void finalize_tick_report_for_time(MinecraftServer server) private static String sectionName(Pair section) { ResourceLocation id; + final RegistryAccess regs = section.getKey().registryAccess(); if (section.getValue() instanceof EntityType) { - id = BuiltInRegistries.ENTITY_TYPE.getKey((EntityType) section.getValue()); + id = regs.registryOrThrow(Registries.ENTITY_TYPE).getKey((EntityType) section.getValue()); } else { - id = BuiltInRegistries.BLOCK_ENTITY_TYPE.getKey((BlockEntityType) section.getValue()); + id = regs.registryOrThrow(Registries.BLOCK_ENTITY_TYPE).getKey((BlockEntityType) section.getValue()); } String name = "minecraft".equals(id.getNamespace())?id.getPath():id.toString(); if (section.getKey().isClientSide) diff --git a/src/main/java/carpet/utils/MobAI.java b/src/main/java/carpet/utils/MobAI.java index fd49f467e7..c13fd5946f 100644 --- a/src/main/java/carpet/utils/MobAI.java +++ b/src/main/java/carpet/utils/MobAI.java @@ -8,8 +8,11 @@ import java.util.Map; import java.util.Set; import java.util.stream.Collectors; + +import net.minecraft.commands.CommandSourceStack; import net.minecraft.core.BlockPos; import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; import net.minecraft.server.level.ServerLevel; import net.minecraft.util.Mth; import net.minecraft.world.entity.Entity; @@ -54,14 +57,14 @@ public static void startTracking(EntityType e, TrackingType type) aiTrackers.get(e).add(type); } - public static List availbleTypes() + public static List availbleTypes(CommandSourceStack source) { Set> types = new HashSet<>(); for (TrackingType type: TrackingType.values()) { types.addAll(type.types); } - return types.stream().map(t -> BuiltInRegistries.ENTITY_TYPE.getKey(t).getPath()).collect(Collectors.toList()); + return types.stream().map(t -> source.registryAccess().registryOrThrow(Registries.ENTITY_TYPE).getKey(t).getPath()).collect(Collectors.toList()); } public static List availableFor(EntityType entityType) From 0e8b53c8d3a1f22609ba61ff86f8fb2a2e664fa5 Mon Sep 17 00:00:00 2001 From: altrisi Date: Wed, 18 Jan 2023 13:47:22 +0100 Subject: [PATCH 003/233] Add `CarpetContext.s` back temporarily as Deprecated for compatibility --- src/main/java/carpet/script/CarpetContext.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/carpet/script/CarpetContext.java b/src/main/java/carpet/script/CarpetContext.java index d10ed2ed53..cfb21effd5 100644 --- a/src/main/java/carpet/script/CarpetContext.java +++ b/src/main/java/carpet/script/CarpetContext.java @@ -11,7 +11,11 @@ public class CarpetContext extends Context { - private CommandSourceStack s; + /** + * @deprecated Use {@link #source()} or the new methods to access stuff in it instead + */ + @Deprecated(forRemoval = true) + public CommandSourceStack s; private final BlockPos origin; public CarpetContext(CarpetScriptHost host, CommandSourceStack source) { From 005368c3d9cba1288ce2dce2d3584256a13f2457 Mon Sep 17 00:00:00 2001 From: altrisi Date: Wed, 18 Jan 2023 14:14:36 +0100 Subject: [PATCH 004/233] Typo fixing round Light check over all scarpet docs Resolves #1626, resolves #1613, resolves #1597, some of the fixes are from these --- docs/scarpet/api/Auxiliary.md | 8 ++++---- docs/scarpet/api/BlocksAndWorldAccess.md | 8 ++++---- docs/scarpet/api/Entities.md | 8 ++++---- docs/scarpet/api/Events.md | 14 +++++++------- docs/scarpet/api/Inventories.md | 2 +- docs/scarpet/api/ScriptCommand.md | 4 ++-- .../language/LoopsAndHigherOrderFunctions.md | 2 +- docs/scarpet/language/Math.md | 2 +- docs/scarpet/language/Operators.md | 4 ++-- docs/scarpet/language/SystemFunctions.md | 4 ++-- src/main/java/carpet/CarpetExtension.java | 4 +--- .../logging/logHelpers/ExplosionLogHelper.java | 11 +++++------ 12 files changed, 34 insertions(+), 37 deletions(-) diff --git a/docs/scarpet/api/Auxiliary.md b/docs/scarpet/api/Auxiliary.md index 361ec7ded0..1b05a90b26 100644 --- a/docs/scarpet/api/Auxiliary.md +++ b/docs/scarpet/api/Auxiliary.md @@ -9,7 +9,7 @@ Collection of other methods that control smaller, yet still important aspects of Plays a specific sound `name`, at block or position `pos`, with optional `volume` and modified `pitch`, and under optional `mixer`. Default values for `volume`, `pitch` and `mixer` are `1.0`, `1.0`, and `master`. Valid mixer options are `master`, `music`, `record`, `weather`, `block`, `hostile`,`neutral`, `player`, `ambient` -and `voice`. `pos` can be either a block, triple of coords, or a list of thee numbers. Uses the same options as a +and `voice`. `pos` can be either a block, triple of coords, or a list of three numbers. Uses the same options as a corresponding `playsound` command. Used with no arguments, return the list of available sound names. @@ -244,7 +244,7 @@ produce an exception. ### `print(expr)`, `print(player/player_list, expr)` -Displays the result of the expression to the chat. Overrides default `scarpet` behaviour of sending everyting to stderr. +Displays the result of the expression to the chat. Overrides default `scarpet` behaviour of sending everything to stderr. Can optionally define player or list of players to send the message to. ### `format(components, ...)`, `format([components, ...])` @@ -634,7 +634,7 @@ to that value. Daytime clocks are shared between all dimensions. _**Deprecated**. Use `system_info('server_last_tick_times')` instead._ Returns a 100-long array of recent tick times, in milliseconds. First item on the list is the most recent tick -If called outside of the main tick (either throgh scheduled tasks, or async execution), then the first item on the +If called outside of the main tick (either through scheduled tasks, or async execution), then the first item on the list may refer to the previous tick performance. In this case the last entry (tick 100) would refer to the most current tick. For all intent and purpose, `last_tick_times():0` should be used as last tick execution time, but individual tick times may vary greatly, and these need to be taken with the little grain of @@ -655,7 +655,7 @@ If you need to break up your execution into chunks, you could queue the rest of the work into the next task using `schedule`, or perform your actions defining `__on_tick()` event handler, but in case you need to take a full control over the game loop and run some simulations using `game_tick()` as the way to advance the game progress, that might be the simplest way to do it, -and triggering the script in a 'proper' way (there is not 'proper' way, but via commmand line, or server chat is the most 'proper'), +and triggering the script in a 'proper' way (there is not 'proper' way, but via command line, or server chat is the most 'proper'), would be the safest way to do it. For instance, running `game_tick()` from a command block triggered with a button, or in an entity event triggered in an entity tick, may technically cause the game to run and encounter that call again, causing stack to overflow. Thankfully it doesn't happen in vanilla running diff --git a/docs/scarpet/api/BlocksAndWorldAccess.md b/docs/scarpet/api/BlocksAndWorldAccess.md index 012e6c3b1a..1eb3074770 100644 --- a/docs/scarpet/api/BlocksAndWorldAccess.md +++ b/docs/scarpet/api/BlocksAndWorldAccess.md @@ -502,8 +502,8 @@ Returns the map colour of a block at position. One of: `'air'`, `'grass'`, `'sand'`, `'wool'`, `'tnt'`, `'ice'`, `'iron'`, `'foliage'`, `'snow'`, `'clay'`, `'dirt'`, `'stone'`, `'water'`, `'wood'`, `'quartz'`, `'adobe'`, `'magenta'`, `'light_blue'`, `'yellow'`, `'lime'`, `'pink'`, -`'gray'`, `'light_gray'`, `'cyan'`, `'purple'`, `'blue'`, `'brown'`, `'green'`, `'red'`, `'black'`, `'gold -'`, `'diamond'`, `'lapis'`, `'emerald'`, `'obsidian'`, `'netherrack'`, `'white_terracotta'`, `'orange_terracotta'`, +`'gray'`, `'light_gray'`, `'cyan'`, `'purple'`, `'blue'`, `'brown'`, `'green'`, `'red'`, `'black'`, `'gold'`, +`'diamond'`, `'lapis'`, `'emerald'`, `'obsidian'`, `'netherrack'`, `'white_terracotta'`, `'orange_terracotta'`, `'magenta_terracotta'`, `'light_blue_terracotta'`, `'yellow_terracotta'`, `'lime_terracotta'`, `'pink_terracotta'`, `'gray_terracotta'`, `'light_gray_terracotta'`, `'cyan_terracotta'`, `'purple_terracotta'`, `'blue_terracotta'`, `'brown_terracotta'`, `'green_terracotta'`, `'red_terracotta'`, `'black_terracotta'`, @@ -740,12 +740,12 @@ These contain some popular features and structures that are impossible or diffic * `'coral_mushroom'` - mushroom coral feature * `'coral_tree'` - tree coral feature * `'fancy_oak_bees'` - large oak tree variant with a mandatory beehive unlike standard that generate with probability -* `'oak_bees'` - normal oak tree with a manatory beehive unlike standard that generate with probability +* `'oak_bees'` - normal oak tree with a mandatory beehive unlike standard that generate with probability ### `structure_eligibility(pos, ?structure, ?size_needed)` -Checks wordgen eligibility for a structure in a given chunk. Requires a `Structure Variant` name (see above), +Checks worldgen eligibility for a structure in a given chunk. Requires a `Structure Variant` name (see above), or `Standard Structure` to check structures of this type. If no structure is given, or `null`, then it will check for all structures. If bounding box of the structures is also requested, it will compute size of potential diff --git a/docs/scarpet/api/Entities.md b/docs/scarpet/api/Entities.md index 1be8af087f..713573526e 100644 --- a/docs/scarpet/api/Entities.md +++ b/docs/scarpet/api/Entities.md @@ -80,7 +80,7 @@ cuboid search area. ### `entity_selector(selector)` -Returns entities satisifying given vanilla entity selector. Most complex among all the methods of selecting entities, +Returns entities satisfying given vanilla entity selector. Most complex among all the methods of selecting entities, but the most capable. Selectors are cached so it should be as fast as other methods of selecting entities. Unlike other entities fetching / filtering method, this one doesn't guarantee to return entities from current dimension, since selectors can return any loaded entity in the world. @@ -111,7 +111,7 @@ Boolean. True if the entity is removed. ### `query(e, 'id')` -Returns numerical id of the entity. Most efficient way to keep track of entites in a script. +Returns numerical id of the entity. Most efficient way to keep track of entities in a script. Ids are only unique within current game session (ids are not preserved between restarts), and dimension (each dimension has its own ids which can overlap). @@ -161,7 +161,7 @@ Respective component of the entity's motion vector ### `query(e, 'on_ground')` -Returns `true` if en entity is standing on firm ground and falling down due to that. +Returns `true` if an entity is standing on firm ground and falling down due to that. ### `query(e, 'name'), query(e, 'display_name'), query(e, 'custom_name'), query(e, 'type')` @@ -394,7 +394,7 @@ Returns `null` if the argument is not a player, otherwise: * `multiplayer`: for players on a dedicated server * `lan_host`: for singleplayer owner that opened the game to LAN * `lan_player`: for all other players that connected to a LAN host -* `fake`: any carpet-spanwed fake player +* `fake`: any carpet-spawned fake player * `shadow`: any carpet-shadowed real player * `realms`: ? diff --git a/docs/scarpet/api/Events.md b/docs/scarpet/api/Events.md index 83771e8646..59378f9bd6 100644 --- a/docs/scarpet/api/Events.md +++ b/docs/scarpet/api/Events.md @@ -38,7 +38,7 @@ Events triggered in an app can result in zero, one, or multiple executions, depe * player targeted events (like `player_breaks_block`) target each app once: * for global scoped apps - targets a single app instance and provides `player` as the first argument. * for player scoped apps - targets only a given player instance, providing player argument for API consistency, - since active player in player scoped apps can always be retrived using `player()`. + since active player in player scoped apps can always be retrieved using `player()`. * global events could be handled by multiple players multiple times (like `explosion`, or `tick`): * for global scoped apps - triggered once for the single app instance. * for player scoped apps - triggered N times for each player separately, so they can do something with that information @@ -80,7 +80,7 @@ the system is closing down exceptionally. ## Built-in global events Global events will be handled once per app that is with `'global'` scope. With `player` scoped apps, each player instance - will be triggerd once for each player, so a global event may be executed multiple times for such apps. + will be triggered once for each player, so a global event may be executed multiple times for such apps. ### `__on_server_starts()` Event triggers after world is loaded and after all startup apps have started. It won't be triggered with `/reload`. @@ -242,14 +242,14 @@ Triggered when a player attacks entity, right before it happens server side. This event can be cancelled by returning `'cancel'`, which prevents the player from attacking the entity. ### `__on_player_takes_damage(player, amount, source, source_entity)` -Triggered when a player is taking damage. Event is executed right after potential absorbtion was applied and before +Triggered when a player is taking damage. Event is executed right after potential absorption was applied and before the actual damage is applied to the player. This event can be cancelled by returning `'cancel'`, which prevents the player from taking damage. ### `__on_player_deals_damage(player, amount, entity)` Triggered when a player deals damage to another entity. Its applied in the same moment as `player_takes_damage` if both -sides of the event are players, and similar for all other entities, just their absorbtion is taken twice, just noone ever +sides of the event are players, and similar for all other entities, just their absorption is taken twice, just noone ever notices that ¯\_(ツ)_/¯ This event can be cancelled by returning `'cancel'`, which prevents the damage from being dealt. @@ -332,7 +332,7 @@ is handled before scoreboard values for these statistics are changed. App programmers can define and trigger their own custom events. Unlike built-in events, all custom events pass a single value as an argument, but this doesn't mean that they cannot pass a complex list, map, or nbt tag as a message. Each event signal is -either targetting all apps instances for all players, including global apps, if no target player has been identified, +either targeting all apps instances for all players, including global apps, if no target player has been identified, or only player scoped apps, if the target player is specified, running once for that player app. You cannot target global apps with player-targeted signals. Built-in events do target global apps, since their first argument is clearly defined and passed. That may change in the future in case there is @@ -376,7 +376,7 @@ to it when the event is triggered. All custom events expect a function that take If extra arguments are provided, they will be appended to the argument list of the callback function. Returns `true` if subscription to the event was successful, or `false` if it failed (for instance wrong scope for built-in event, -or incorect number of parameters for the event). +or incorrect number of parameters for the event). If a callback is specified as `null`, the given app (or player app instance )stops handling that event. @@ -400,7 +400,7 @@ In case you want to pass an event handler that is not defined in your module, pl Fires a specific event. If the event does not exist (only `handle_event` creates missing new events), or provided argument list was not matching the callee expected arguments, returns `null`, -otherwise returns number of apps notified. If `target_player` is specified and not `null` triggers a player specific event, targetting +otherwise returns number of apps notified. If `target_player` is specified and not `null` triggers a player specific event, targeting only `player` scoped apps for that player. Apps with globals scope will not be notified even if they handle this event. If the `target_player` is omitted or `null`, it will target `global` scoped apps and all instances of `player` scoped apps. Note that all built-in player events have a player as a first argument, so to trigger these events, you need to diff --git a/docs/scarpet/api/Inventories.md b/docs/scarpet/api/Inventories.md index d8c66e31d1..c95f38ad8f 100644 --- a/docs/scarpet/api/Inventories.md +++ b/docs/scarpet/api/Inventories.md @@ -34,7 +34,7 @@ With no arguments, returns a list of all items in the game. With an item tag pro ### `item_tags(item, tag?)` -Returns list of tags the item belongs to, or, if tag is provided, `true` if an item maches the tag, `false` if it doesn't and `null` if that's not a valid tag +Returns list of tags the item belongs to, or, if tag is provided, `true` if an item matches the tag, `false` if it doesn't and `null` if that's not a valid tag Throws `unknown_item` if item doesn't exist. diff --git a/docs/scarpet/api/ScriptCommand.md b/docs/scarpet/api/ScriptCommand.md index 326c3f69ed..fb4a8b9fab 100644 --- a/docs/scarpet/api/ScriptCommand.md +++ b/docs/scarpet/api/ScriptCommand.md @@ -41,7 +41,7 @@ check `load_app_data` and `store_app_data` functions. Unloading the app will only mask their command tree, not remove it. This has the same effect than not having that command -at all, with the exception that if you load a diffrent app with the same name, this may cause commands to reappear. +at all, with the exception that if you load a different app with the same name, this may cause commands to reappear. To remove the commands fully, use `/reload`. @@ -88,7 +88,7 @@ at the end ### `/script invokearea ...` -It is equivalent to `invoke` except it assumes that the first three arguments are one set of ccordinates, +It is equivalent to `invoke` except it assumes that the first three arguments are one set of coordinates, followed by the second set of coordinates, providing tab completion, with `looking at...` mechanics for convenience, followed by any other required arguments diff --git a/docs/scarpet/language/LoopsAndHigherOrderFunctions.md b/docs/scarpet/language/LoopsAndHigherOrderFunctions.md index d0e31ba54a..41a1c5aa2d 100644 --- a/docs/scarpet/language/LoopsAndHigherOrderFunctions.md +++ b/docs/scarpet/language/LoopsAndHigherOrderFunctions.md @@ -53,7 +53,7 @@ From which we can learn that there is 7216 primes between 1M and 1.1M Evaluates expression `expr` repeatedly until condition `cond` becomes false, but not more than `limit` times. Returns the result of the last `expr` evaluation, or `null` if nothing was successful. Both `expr` and `cond` will -recveived a bound variable `_` indicating current iteration, so its a number. +received a bound variable `_` indicating current iteration, so its a number.
 while(a<100,10,a=_*_)  => 81 // loop exhausted via limit
diff --git a/docs/scarpet/language/Math.md b/docs/scarpet/language/Math.md
index afb89987da..3bb65eec00 100644
--- a/docs/scarpet/language/Math.md
+++ b/docs/scarpet/language/Math.md
@@ -27,7 +27,7 @@ Highest integer that is still no larger then `n`. Insert a floor pun here.
 
 ### `ceil(n)`
 
-First lucky integer that is not smalller than `n`. As you would expect, ceiling is typically right above the floor.
+First lucky integer that is not smaller than `n`. As you would expect, ceiling is typically right above the floor.
 
 ### `ln(n)`
 
diff --git a/docs/scarpet/language/Operators.md b/docs/scarpet/language/Operators.md
index c0e8dd5a16..ea18211bd1 100644
--- a/docs/scarpet/language/Operators.md
+++ b/docs/scarpet/language/Operators.md
@@ -222,7 +222,7 @@ A set of assignment operators. All require bounded variable on the LHS, `<>` req
 right hand side as well (bounded, meaning being variables). Additionally they can also handle list constructors 
 with all bounded variables, and work then as list assignment operators. When `+=` is used on a list, it extends 
 that list of that element, and returns the list (old == new). `scarpet` doesn't support currently removal of items. 
-Removal of items can be obtaine via `filter` command, and reassigning it fo the same variable. Both operations would 
+Removal of items can be obtained via `filter` command, and reassigning it fo the same variable. Both operations would 
 require rewriting of the array anyways.
 
 
@@ -276,7 +276,7 @@ args() -> ... [1, 2, 3]; sum(a, b, c) -> a+b+c; sum(args())   => 6
 a = ... [1, 2, 3]; sum(a, b, c) -> a+b+c; sum(a)   => 6
 
-Unpacking mechanics can be used for list and map constriction, not just for function calls. +Unpacking mechanics can be used for list and map construction, not just for function calls.
 [...range(5), pi, ...range(5,-1,-1)]   => [0, 1, 2, 3, 4, 3.14159265359, 5, 4, 3, 2, 1, 0]
diff --git a/docs/scarpet/language/SystemFunctions.md b/docs/scarpet/language/SystemFunctions.md
index d158f4e073..42caf30b9f 100644
--- a/docs/scarpet/language/SystemFunctions.md
+++ b/docs/scarpet/language/SystemFunctions.md
@@ -76,7 +76,7 @@ str('foo') => 'foo'
 str('3bar') => '3bar'
 str(2)+str(2) => '22'
 str('pi: %.2f',pi) => 'pi: 3.14'
-str('player at: %d %d %d',pos(player())) => 'player at: 567, -2423, 124'
+str('player at: %d, %d, %d',pos(player())) => 'player at: 567, -2423, 124'
 
* * * @@ -204,7 +204,7 @@ title('aBc') => 'Abc' ### `replace(string, regex, repl?); replace_first(string, regex, repl?)` -Replaces all, or first occurence of a regular expression in the string with `repl` expression, +Replaces all, or first occurrence of a regular expression in the string with `repl` expression, or nothing, if not specified. To use escape characters (`\(`,`\+`,...), metacharacters (`\d`,`\w`,...), or position anchors (`\b`,`\z`,...) in your regular expression, use two backslashes.
diff --git a/src/main/java/carpet/CarpetExtension.java b/src/main/java/carpet/CarpetExtension.java
index 1918a166ae..e7a742cdf6 100644
--- a/src/main/java/carpet/CarpetExtension.java
+++ b/src/main/java/carpet/CarpetExtension.java
@@ -128,8 +128,6 @@ default void onServerClosed(MinecraftServer server) {}
     default void onReload(MinecraftServer server) {}
 
     /**
-     * Event that gets called when a player logs in
-     * 
      * @return A {@link String} usually being the extension's id
      * 
      */
@@ -146,7 +144,7 @@ default void registerLoggers() {}
      * rules.
      * 
      * @param lang A {@link String} being the language id selected by the user
-     * @return A {@link Map} containing the string key with it's 
+     * @return A {@link Map} containing the string key with its 
      *         respective translation {@link String} or an empty map if not available
      * 
      */
diff --git a/src/main/java/carpet/logging/logHelpers/ExplosionLogHelper.java b/src/main/java/carpet/logging/logHelpers/ExplosionLogHelper.java
index 3b9fba762b..972ec1a5c0 100644
--- a/src/main/java/carpet/logging/logHelpers/ExplosionLogHelper.java
+++ b/src/main/java/carpet/logging/logHelpers/ExplosionLogHelper.java
@@ -8,7 +8,6 @@
 import java.util.List;
 
 import net.minecraft.core.RegistryAccess;
-import net.minecraft.core.registries.BuiltInRegistries;
 import net.minecraft.core.registries.Registries;
 import net.minecraft.network.chat.Component;
 import net.minecraft.world.entity.Entity;
@@ -29,7 +28,7 @@ public class ExplosionLogHelper
     private final Object2IntMap impactedEntities = new Object2IntOpenHashMap<>();
 
     private static long lastGametime = 0;
-    private static int explosionCountInCurretGT = 0;
+    private static int explosionCountInCurrentGT = 0;
     private static boolean newTick;
 
     public ExplosionLogHelper(double x, double y, double z, float power, boolean createFire, Explosion.BlockInteraction blockDestructionType, RegistryAccess regs) {
@@ -49,22 +48,22 @@ public void onExplosionDone(long gametime)
     {
         newTick = false;
         if (!(lastGametime == gametime)){
-            explosionCountInCurretGT = 0;
+            explosionCountInCurrentGT = 0;
             lastGametime = gametime;
             newTick = true;
         }
-        explosionCountInCurretGT++;
+        explosionCountInCurrentGT++;
         LoggerRegistry.getLogger("explosions").log( (option) -> {
             List messages = new ArrayList<>();
             if(newTick) messages.add(c("wb tick : ", "d " + gametime));
             if ("brief".equals(option))
             {
-                messages.add( c("d #" + explosionCountInCurretGT,"gb ->",
+                messages.add( c("d #" + explosionCountInCurrentGT,"gb ->",
                         Messenger.dblt("l", pos.x, pos.y, pos.z), (affectBlocks)?"m  (affects blocks)":"m  (doesn't affect blocks)" ));
             }
             if ("full".equals(option))
             {
-                messages.add( c("d #" + explosionCountInCurretGT,"gb ->", Messenger.dblt("l", pos.x, pos.y, pos.z) ));
+                messages.add( c("d #" + explosionCountInCurrentGT,"gb ->", Messenger.dblt("l", pos.x, pos.y, pos.z) ));
                 messages.add(c("w   affects blocks: ", "m " + this.affectBlocks));
                 messages.add(c("w   creates fire: ", "m " + this.createFire));
                 messages.add(c("w   power: ", "c " + this.power));

From 2b95a878ad0d995b72c2839eac94284142b19dba Mon Sep 17 00:00:00 2001
From: altrisi 
Date: Wed, 18 Jan 2023 14:41:46 +0100
Subject: [PATCH 005/233] Remove now fixed `flatWorldStructureSpawning` rule
 and cleanup some unused mixins

---
 src/main/java/carpet/CarpetSettings.java      |  7 --
 .../carpet/fakes/PlacedFeatureInterface.java  |  7 --
 .../FlatLevelSource_structuresMixin.java      | 82 -------------------
 .../mixins/PlacedFeature_scarpetMixin.java    | 15 ----
 .../java/carpet/script/utils/BiomeInfo.java   |  2 -
 src/main/resources/carpet.mixins.json         |  2 -
 6 files changed, 115 deletions(-)
 delete mode 100644 src/main/java/carpet/fakes/PlacedFeatureInterface.java
 delete mode 100644 src/main/java/carpet/mixins/FlatLevelSource_structuresMixin.java
 delete mode 100644 src/main/java/carpet/mixins/PlacedFeature_scarpetMixin.java

diff --git a/src/main/java/carpet/CarpetSettings.java b/src/main/java/carpet/CarpetSettings.java
index ded6c7f96b..5c20d3d823 100644
--- a/src/main/java/carpet/CarpetSettings.java
+++ b/src/main/java/carpet/CarpetSettings.java
@@ -13,7 +13,6 @@
 import net.fabricmc.loader.api.FabricLoader;
 import net.minecraft.commands.CommandSourceStack;
 import net.minecraft.core.BlockPos;
-import net.minecraft.core.registries.BuiltInRegistries;
 import net.minecraft.core.registries.Registries;
 import net.minecraft.resources.ResourceLocation;
 import net.minecraft.server.MinecraftServer;
@@ -898,12 +897,6 @@ public enum RenewableCoralMode {
 
     @Rule(desc = "Spawning requires much less CPU and Memory", category = OPTIMIZATION)
     public static boolean lagFreeSpawning = false;
-    
-    @Rule(
-            desc = "Allows structure mobs to spawn in flat worlds",
-            category = {EXPERIMENTAL, CREATIVE}
-    )
-    public static boolean flatWorldStructureSpawning = false;
 
     @Rule(
             desc = "Increases for testing purposes number of blue skulls shot by the wither",
diff --git a/src/main/java/carpet/fakes/PlacedFeatureInterface.java b/src/main/java/carpet/fakes/PlacedFeatureInterface.java
deleted file mode 100644
index 392dda04f7..0000000000
--- a/src/main/java/carpet/fakes/PlacedFeatureInterface.java
+++ /dev/null
@@ -1,7 +0,0 @@
-package carpet.fakes;
-
-import net.minecraft.world.level.levelgen.feature.ConfiguredFeature;
-
-public interface PlacedFeatureInterface {
-    //ConfiguredFeature getRawFeature();
-}
diff --git a/src/main/java/carpet/mixins/FlatLevelSource_structuresMixin.java b/src/main/java/carpet/mixins/FlatLevelSource_structuresMixin.java
deleted file mode 100644
index 1fe31c7d6c..0000000000
--- a/src/main/java/carpet/mixins/FlatLevelSource_structuresMixin.java
+++ /dev/null
@@ -1,82 +0,0 @@
-package carpet.mixins;
-
-import net.minecraft.core.HolderSet;
-import net.minecraft.core.Registry;
-import net.minecraft.world.level.levelgen.structure.StructureSet;
-import org.spongepowered.asm.mixin.Mixin;
-
-import net.minecraft.world.level.biome.BiomeSource;
-import net.minecraft.world.level.chunk.ChunkGenerator;
-import net.minecraft.world.level.levelgen.FlatLevelSource;
-
-@Mixin(FlatLevelSource.class) // YEET
-public abstract class FlatLevelSource_structuresMixin extends ChunkGenerator
-{
-    public FlatLevelSource_structuresMixin(BiomeSource biomeSource) {
-        super(biomeSource);
-    }
-
-/*
-    @Override
-    public WeightedRandomList getMobsAt(Holder biome, StructureFeatureManager accessor, MobCategory group, BlockPos pos)
-    {
-        if (!CarpetSettings.flatWorldStructureSpawning) return super.getMobsAt(biome, accessor, group, pos);
-
-        // vanila noise one
-        if (accessor.getStructureAt(pos, StructureFeature.SWAMP_HUT).isValid()) {
-            if (group == MobCategory.MONSTER) {
-                return SwamplandHutFeature.SWAMPHUT_ENEMIES;
-            }
-
-            if (group == MobCategory.CREATURE) {
-                return SwamplandHutFeature.SWAMPHUT_ANIMALS;
-            }
-        }
-
-        if (group == MobCategory.MONSTER) {
-            if (accessor.getStructureAt(pos, StructureFeature.PILLAGER_OUTPOST).isValid()) {
-                return PillagerOutpostFeature.OUTPOST_ENEMIES;
-            }
-
-            if (accessor.getStructureAt(pos, StructureFeature.OCEAN_MONUMENT).isValid()) {
-                return OceanMonumentFeature.MONUMENT_ENEMIES;
-            }
-
-            if (accessor.getStructureAt(pos, StructureFeature.NETHER_BRIDGE).isValid()) {
-                return NetherFortressFeature.FORTRESS_ENEMIES;
-            }
-        }
-
-
-        // carpet spawns
-        if (group == MobCategory.MONSTER)
-        {
-            if (CarpetSettings.huskSpawningInTemples)
-            {
-                if (accessor.getStructureAt(pos, StructureFeature.DESERT_PYRAMID).isValid())
-                {
-                    return CustomSpawnLists.PYRAMID_SPAWNS;
-                }
-            }
-            if (CarpetSettings.shulkerSpawningInEndCities)
-            {
-                if (accessor.getStructureAt(pos, StructureFeature.END_CITY).isValid())
-                {
-                    return CustomSpawnLists.SHULKER_SPAWNS;
-                }
-            }
-            if (CarpetSettings.piglinsSpawningInBastions)
-            {
-                if (accessor.getStructureAt(pos, StructureFeature.BASTION_REMNANT).isValid())
-                {
-                    return CustomSpawnLists.BASTION_SPAWNS;
-                }
-            }
-        }
-        return (group == MobCategory.UNDERGROUND_WATER_CREATURE || group == MobCategory.AXOLOTLS) && accessor.getStructureAt(pos, StructureFeature.OCEAN_MONUMENT).isValid() ? MobSpawnSettings.EMPTY_MOB_LIST : super.getMobsAt(biome, accessor, group, pos);
-
-
-    }
-    
- */
-}
diff --git a/src/main/java/carpet/mixins/PlacedFeature_scarpetMixin.java b/src/main/java/carpet/mixins/PlacedFeature_scarpetMixin.java
deleted file mode 100644
index 2e4f149d75..0000000000
--- a/src/main/java/carpet/mixins/PlacedFeature_scarpetMixin.java
+++ /dev/null
@@ -1,15 +0,0 @@
-package carpet.mixins;
-
-import carpet.fakes.PlacedFeatureInterface;
-import org.spongepowered.asm.mixin.Final;
-import org.spongepowered.asm.mixin.Mixin;
-import org.spongepowered.asm.mixin.Shadow;
-
-import java.util.function.Supplier;
-import net.minecraft.world.level.levelgen.feature.ConfiguredFeature;
-import net.minecraft.world.level.levelgen.placement.PlacedFeature;
-
-@Mixin(PlacedFeature.class)
-public class PlacedFeature_scarpetMixin implements PlacedFeatureInterface {
-
-}
diff --git a/src/main/java/carpet/script/utils/BiomeInfo.java b/src/main/java/carpet/script/utils/BiomeInfo.java
index 12cac5a7a8..cfc36c7409 100644
--- a/src/main/java/carpet/script/utils/BiomeInfo.java
+++ b/src/main/java/carpet/script/utils/BiomeInfo.java
@@ -1,7 +1,5 @@
 package carpet.script.utils;
 
-import carpet.fakes.PlacedFeatureInterface;
-import carpet.script.value.BlockValue;
 import carpet.script.value.ListValue;
 import carpet.script.value.NumericValue;
 import carpet.script.value.StringValue;
diff --git a/src/main/resources/carpet.mixins.json b/src/main/resources/carpet.mixins.json
index eb99e5968b..e5c7fd6624 100644
--- a/src/main/resources/carpet.mixins.json
+++ b/src/main/resources/carpet.mixins.json
@@ -81,14 +81,12 @@
     "Level_scarpetPlopMixin",
     "WorldGenRegion_scarpetPlopMixin",
     "StructurePiece_scarpetPlopMixin",
-    "PlacedFeature_scarpetMixin",
     "PieceGeneratorSupplier_plopMixin",
     "ServerGamePacketListenerImpl_scarpetEventsMixin",
     "ServerPlayerGameMode_scarpetEventsMixin",
     "Player_parrotMixin",
     "SaplingBlock_desertShrubsMixin",
     "EntityMixin",
-    "FlatLevelSource_structuresMixin",
     "ChunkGenerator_scarpetMixin",
     "Guardian_renewableSpongesMixin",
     "Husk_templesMixin",

From c7d506675ef65aff1f2557ec57abae8f4c8d837c Mon Sep 17 00:00:00 2001
From: gnembon <41132274+gnembon@users.noreply.github.com>
Date: Wed, 18 Jan 2023 22:11:19 +0100
Subject: [PATCH 006/233] 23w03a

---
 gradle.properties                               | 10 +++++-----
 src/main/java/carpet/CarpetSettings.java        |  7 +++----
 .../java/carpet/commands/ScriptCommand.java     |  5 +++--
 src/main/java/carpet/fakes/BiomeInterface.java  |  7 +++++++
 .../ServerGamePacketListenerImplInterface.java  |  7 +++++++
 src/main/java/carpet/logging/HUDController.java |  9 +++++++--
 .../java/carpet/mixins/Biome_scarpetMixin.java  | 17 +++++++++++++++++
 .../mixins/CloneCommands_fillUpdatesMixin.java  | 14 +++++++++-----
 .../carpet/mixins/FillBiomeCommandMixin.java    | 15 ++++++++++-----
 .../java/carpet/mixins/FillCommandMixin.java    | 14 +++++++++-----
 .../ServerGamePacketListenerImpl_coreMixin.java | 12 +++++++++++-
 .../carpet/network/ServerNetworkHandler.java    |  5 +++--
 src/main/java/carpet/script/api/Auxiliary.java  |  4 ++--
 .../java/carpet/script/utils/BiomeInfo.java     |  7 +++++--
 .../carpet/script/utils/ShapesRenderer.java     |  2 --
 .../java/carpet/script/utils/SystemInfo.java    |  6 +++---
 .../java/carpet/script/value/EntityValue.java   |  7 ++++---
 src/main/resources/carpet.accesswidener         |  1 +
 src/main/resources/carpet.mixins.json           |  1 +
 19 files changed, 107 insertions(+), 43 deletions(-)
 create mode 100644 src/main/java/carpet/fakes/BiomeInterface.java
 create mode 100644 src/main/java/carpet/fakes/ServerGamePacketListenerImplInterface.java
 create mode 100644 src/main/java/carpet/mixins/Biome_scarpetMixin.java

diff --git a/gradle.properties b/gradle.properties
index 5ce2774cbb..4d21ef2998 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -4,9 +4,9 @@ org.gradle.jvmargs=-Xmx1G
 # Fabric Properties
 	# check these on https://fabricmc.net/use
     # or better: https://modmuss50.me/fabric.html
-	minecraft_version=1.19.3
-	loader_version=0.14.11
-	fabric_version=0.67.1+1.19.3
+	minecraft_version=23w03a
+	loader_version=0.14.13
+	fabric_version=0.72.0+1.19.3
 
 # Mod Properties
 	mod_version = 1.4.93
@@ -17,7 +17,7 @@ org.gradle.jvmargs=-Xmx1G
 	# The Curseforge versions "names" or ids for the main branch (comma separated: 1.16.4,1.16.5)
 	# This is needed because CF uses too vague names for prereleases and release candidates
 	# Can also be the version ID directly coming from https://minecraft.curseforge.com/api/game/versions?token=[API_TOKEN]
-	release-curse-versions = Minecraft 1.19:1.19.3
+	release-curse-versions = Minecraft 1.19:1.19.4
 	# Whether or not to build another branch on release
 	release-extra-branch = false
 	# The name of the second branch to release
@@ -25,4 +25,4 @@ org.gradle.jvmargs=-Xmx1G
 	# The "name" or id of the Curseforge version for the secondary branch
 	# This is needed because CF uses too vague names for snapshots
 	# Can also be the version ID directly coming from https://minecraft.curseforge.com/api/game/versions?token=[API_TOKEN]
-	release-extra-curse-version = Minecraft 1.19:1.19.3
\ No newline at end of file
+	release-extra-curse-version = Minecraft 1.19:1.19.4
\ No newline at end of file
diff --git a/src/main/java/carpet/CarpetSettings.java b/src/main/java/carpet/CarpetSettings.java
index 5c20d3d823..ca6e62ba33 100644
--- a/src/main/java/carpet/CarpetSettings.java
+++ b/src/main/java/carpet/CarpetSettings.java
@@ -55,7 +55,6 @@ public class CarpetSettings
     public static final Logger LOG = LoggerFactory.getLogger("carpet");
     public static final ThreadLocal skipGenerationChecks = ThreadLocal.withInitial(() -> false);
     public static final ThreadLocal impendingFillSkipUpdates = ThreadLocal.withInitial(() -> false);
-    public static final int VANILLA_FILL_LIMIT = 32768;
     public static int runPermissionLevel = 2;
     public static boolean doChainStone = false;
     public static boolean chainStoneStickToAll = false;
@@ -632,14 +631,14 @@ private static class FillLimitLimits extends Validator {
         public String description() { return "You must choose a value from 1 to 20M";}
     }
     @Rule(
-            desc = "Customizable fill/fillbiome/clone volume limit",
+            desc = "[Deprecated] Customizable fill/fillbiome/clone volume limit",
+            extra = "Use vanilla gamerule instead. This setting will be removed in 1.20.0",
             options = {"32768", "250000", "1000000"},
             category = CREATIVE,
             strict = false,
             validate = FillLimitLimits.class
     )
-    public static int fillLimit = VANILLA_FILL_LIMIT;
-
+    public static int fillLimit = 32768;
 
     @Rule(
             desc = "Customizable forceload chunk limit",
diff --git a/src/main/java/carpet/commands/ScriptCommand.java b/src/main/java/carpet/commands/ScriptCommand.java
index 5921d5a55c..8251f051f3 100644
--- a/src/main/java/carpet/commands/ScriptCommand.java
+++ b/src/main/java/carpet/commands/ScriptCommand.java
@@ -24,6 +24,7 @@
 import com.mojang.brigadier.suggestion.Suggestions;
 import com.mojang.brigadier.suggestion.SuggestionsBuilder;
 import net.minecraft.commands.CommandBuildContext;
+import net.minecraft.world.level.GameRules;
 import org.apache.commons.lang3.StringUtils;
 
 import java.io.IOException;
@@ -516,7 +517,7 @@ private static int scriptScan(CommandContext context, BlockP
         BoundingBox area = BoundingBox.fromCorners(a, b);
         CarpetExpression cexpr = new CarpetExpression(host.main, expr, source, origin);
         int int_1 = area.getXSpan() * area.getYSpan() * area.getZSpan(); // X Y Z
-        if (int_1 > CarpetSettings.fillLimit)
+        if (int_1 > Math.max(source.getServer().getGameRules().getInt(GameRules.RULE_COMMAND_MODIFICATION_BLOCK_LIMIT), CarpetSettings.fillLimit))
         {
             Messenger.m(source, "r too many blocks to evaluate: " + int_1);
             return 1;
@@ -565,7 +566,7 @@ private static int scriptFill(CommandContext context, BlockP
         BoundingBox area = BoundingBox.fromCorners(a, b);
         CarpetExpression cexpr = new CarpetExpression(host.main, expr, source, origin);
         int int_1 = area.getXSpan() * area.getYSpan() * area.getZSpan();
-        if (int_1 > CarpetSettings.fillLimit)
+        if (int_1 > Math.max(source.getServer().getGameRules().getInt(GameRules.RULE_COMMAND_MODIFICATION_BLOCK_LIMIT), CarpetSettings.fillLimit))
         {
             Messenger.m(source, "r too many blocks to evaluate: "+ int_1);
             return 1;
diff --git a/src/main/java/carpet/fakes/BiomeInterface.java b/src/main/java/carpet/fakes/BiomeInterface.java
new file mode 100644
index 0000000000..3279150a93
--- /dev/null
+++ b/src/main/java/carpet/fakes/BiomeInterface.java
@@ -0,0 +1,7 @@
+package carpet.fakes;
+
+import net.minecraft.world.level.biome.Biome;
+
+public interface BiomeInterface {
+    Biome.ClimateSettings getClimateSettings();
+}
diff --git a/src/main/java/carpet/fakes/ServerGamePacketListenerImplInterface.java b/src/main/java/carpet/fakes/ServerGamePacketListenerImplInterface.java
new file mode 100644
index 0000000000..fbd0f834e6
--- /dev/null
+++ b/src/main/java/carpet/fakes/ServerGamePacketListenerImplInterface.java
@@ -0,0 +1,7 @@
+package carpet.fakes;
+
+import net.minecraft.network.Connection;
+
+public interface ServerGamePacketListenerImplInterface {
+    Connection getConnection();
+}
diff --git a/src/main/java/carpet/logging/HUDController.java b/src/main/java/carpet/logging/HUDController.java
index 2fb4d03cd8..d941ab6404 100644
--- a/src/main/java/carpet/logging/HUDController.java
+++ b/src/main/java/carpet/logging/HUDController.java
@@ -11,7 +11,6 @@
 import net.minecraft.resources.ResourceKey;
 import net.minecraft.server.MinecraftServer;
 import net.minecraft.server.level.ServerPlayer;
-import net.minecraft.util.Mth;
 import net.minecraft.world.level.Level;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -20,6 +19,7 @@
 import java.util.List;
 import java.util.Locale;
 import java.util.Map;
+import java.util.OptionalDouble;
 import java.util.Set;
 import java.util.function.Consumer;
 
@@ -116,7 +116,12 @@ public static void update_hud(MinecraftServer server, List force)
     }
     private static Component [] send_tps_display(MinecraftServer server)
     {
-        double MSPT = Mth.average(server.tickTimes) * 1.0E-6D;
+        final OptionalDouble averageTPS = Arrays.stream(server.tickTimes).average();
+        if (averageTPS.isEmpty())
+        {
+            return new Component[]{Component.literal("No TPS data available")};
+        }
+        double MSPT = Arrays.stream(server.tickTimes).average().getAsDouble() * 1.0E-6D;
         double TPS = 1000.0D / Math.max((TickSpeed.time_warp_start_time != 0)?0.0:TickSpeed.mspt, MSPT);
         if (TickSpeed.isPaused()) {
             TPS = 0;
diff --git a/src/main/java/carpet/mixins/Biome_scarpetMixin.java b/src/main/java/carpet/mixins/Biome_scarpetMixin.java
new file mode 100644
index 0000000000..496c2bd487
--- /dev/null
+++ b/src/main/java/carpet/mixins/Biome_scarpetMixin.java
@@ -0,0 +1,17 @@
+package carpet.mixins;
+
+import carpet.fakes.BiomeInterface;
+import net.minecraft.world.level.biome.Biome;
+import org.spongepowered.asm.mixin.Mixin;
+import org.spongepowered.asm.mixin.Shadow;
+
+@Mixin(Biome.class)
+public class Biome_scarpetMixin implements BiomeInterface {
+    @Shadow
+    private Biome.ClimateSettings climateSettings;
+
+    @Override
+    public Biome.ClimateSettings getClimateSettings() {
+        return climateSettings;
+    }
+}
diff --git a/src/main/java/carpet/mixins/CloneCommands_fillUpdatesMixin.java b/src/main/java/carpet/mixins/CloneCommands_fillUpdatesMixin.java
index 1617f3741a..3f9ba1dff5 100644
--- a/src/main/java/carpet/mixins/CloneCommands_fillUpdatesMixin.java
+++ b/src/main/java/carpet/mixins/CloneCommands_fillUpdatesMixin.java
@@ -4,20 +4,24 @@
 import net.minecraft.core.BlockPos;
 import net.minecraft.server.commands.CloneCommands;
 import net.minecraft.server.level.ServerLevel;
+import net.minecraft.world.level.GameRules;
 import net.minecraft.world.level.block.Block;
 import org.spongepowered.asm.mixin.Mixin;
 import org.spongepowered.asm.mixin.injection.At;
-import org.spongepowered.asm.mixin.injection.Constant;
-import org.spongepowered.asm.mixin.injection.ModifyConstant;
 import org.spongepowered.asm.mixin.injection.Redirect;
 
 
 @Mixin(CloneCommands.class)
 public abstract class CloneCommands_fillUpdatesMixin
 {
-    @ModifyConstant(method = "clone", constant = @Constant(intValue = CarpetSettings.VANILLA_FILL_LIMIT))
-    private static int fillLimit(int original) {
-        return CarpetSettings.fillLimit;
+    @Redirect(method = "clone", at = @At(
+                    value = "INVOKE",
+                    target = "Lnet/minecraft/world/level/GameRules;getInt(Lnet/minecraft/world/level/GameRules$Key;)I"
+    ))
+    private static int redirectCloneGameRuleInt(GameRules instance, GameRules.Key key)
+    {
+        int vanilla = instance.getInt(key);
+        return Math.max(vanilla, CarpetSettings.fillLimit);
     }
 
     @Redirect(method = "clone", at = @At(
diff --git a/src/main/java/carpet/mixins/FillBiomeCommandMixin.java b/src/main/java/carpet/mixins/FillBiomeCommandMixin.java
index 029a143200..cd4402a771 100644
--- a/src/main/java/carpet/mixins/FillBiomeCommandMixin.java
+++ b/src/main/java/carpet/mixins/FillBiomeCommandMixin.java
@@ -2,16 +2,21 @@
 
 import carpet.CarpetSettings;
 import net.minecraft.server.commands.FillBiomeCommand;
+import net.minecraft.world.level.GameRules;
 import org.spongepowered.asm.mixin.Mixin;
-import org.spongepowered.asm.mixin.injection.Constant;
-import org.spongepowered.asm.mixin.injection.ModifyConstant;
+import org.spongepowered.asm.mixin.injection.At;
+import org.spongepowered.asm.mixin.injection.Redirect;
 
 @Mixin(FillBiomeCommand.class)
 public class FillBiomeCommandMixin
 {
-	@ModifyConstant(method = "fill", constant = @Constant(intValue = CarpetSettings.VANILLA_FILL_LIMIT))
-	private static int fillLimit(int original)
+	@Redirect(method = "fill", at = @At(
+			value = "INVOKE",
+			target = "Lnet/minecraft/world/level/GameRules;getInt(Lnet/minecraft/world/level/GameRules$Key;)I"
+	))
+	private static int redirectCloneGameRuleInt(GameRules instance, GameRules.Key key)
 	{
-		return CarpetSettings.fillLimit;
+		int vanilla = instance.getInt(key);
+		return Math.max(vanilla, CarpetSettings.fillLimit);
 	}
 }
diff --git a/src/main/java/carpet/mixins/FillCommandMixin.java b/src/main/java/carpet/mixins/FillCommandMixin.java
index 4efedc5196..ab1e0a40e9 100644
--- a/src/main/java/carpet/mixins/FillCommandMixin.java
+++ b/src/main/java/carpet/mixins/FillCommandMixin.java
@@ -4,20 +4,24 @@
 import net.minecraft.core.BlockPos;
 import net.minecraft.server.commands.FillCommand;
 import net.minecraft.server.level.ServerLevel;
+import net.minecraft.world.level.GameRules;
 import net.minecraft.world.level.block.Block;
 import org.spongepowered.asm.mixin.Mixin;
 import org.spongepowered.asm.mixin.injection.At;
-import org.spongepowered.asm.mixin.injection.Constant;
-import org.spongepowered.asm.mixin.injection.ModifyConstant;
 import org.spongepowered.asm.mixin.injection.Redirect;
 
 @Mixin(FillCommand.class)
 public abstract class FillCommandMixin
 {
-    @ModifyConstant(method = "fillBlocks", constant = @Constant(intValue = CarpetSettings.VANILLA_FILL_LIMIT))
-    private static int fillLimit(int original)
+
+    @Redirect(method = "fillBlocks", at = @At(
+            value = "INVOKE",
+            target = "Lnet/minecraft/world/level/GameRules;getInt(Lnet/minecraft/world/level/GameRules$Key;)I"
+    ))
+    private static int redirectCloneGameRuleInt(GameRules instance, GameRules.Key key)
     {
-        return CarpetSettings.fillLimit;
+        int vanilla = instance.getInt(key);
+        return Math.max(vanilla, CarpetSettings.fillLimit);
     }
 
     @Redirect(method = "fillBlocks", at = @At(
diff --git a/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_coreMixin.java b/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_coreMixin.java
index 930b3eaeb6..b7278c60ef 100644
--- a/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_coreMixin.java
+++ b/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_coreMixin.java
@@ -1,9 +1,12 @@
 package carpet.mixins;
 
 import carpet.CarpetServer;
+import carpet.fakes.ServerGamePacketListenerImplInterface;
+import net.minecraft.network.Connection;
 import net.minecraft.network.chat.Component;
 import net.minecraft.server.level.ServerPlayer;
 import net.minecraft.server.network.ServerGamePacketListenerImpl;
+import org.spongepowered.asm.mixin.Final;
 import org.spongepowered.asm.mixin.Mixin;
 import org.spongepowered.asm.mixin.Shadow;
 import org.spongepowered.asm.mixin.injection.At;
@@ -13,13 +16,20 @@
 import static carpet.script.CarpetEventServer.Event.PLAYER_DISCONNECTS;
 
 @Mixin(ServerGamePacketListenerImpl.class)
-public class ServerGamePacketListenerImpl_coreMixin {
+public class ServerGamePacketListenerImpl_coreMixin implements ServerGamePacketListenerImplInterface {
     @Shadow
     public ServerPlayer player;
 
+    @Shadow @Final private Connection connection;
+
     @Inject(method = "onDisconnect", at = @At("HEAD"))
     private void onPlayerDisconnect(Component reason, CallbackInfo ci) {
         CarpetServer.onPlayerLoggedOut(this.player);
         if (PLAYER_DISCONNECTS.isNeeded()) PLAYER_DISCONNECTS.onPlayerMessage(player, reason.getContents().toString());
     }
+
+    @Override
+    public Connection getConnection() {
+        return connection;
+    }
 }
diff --git a/src/main/java/carpet/network/ServerNetworkHandler.java b/src/main/java/carpet/network/ServerNetworkHandler.java
index f8713a6d73..7d0fd0f65a 100644
--- a/src/main/java/carpet/network/ServerNetworkHandler.java
+++ b/src/main/java/carpet/network/ServerNetworkHandler.java
@@ -4,6 +4,7 @@
 import carpet.CarpetSettings;
 import carpet.api.settings.CarpetRule;
 import carpet.api.settings.RuleHelper;
+import carpet.fakes.ServerGamePacketListenerImplInterface;
 import carpet.helpers.TickSpeed;
 import carpet.script.utils.SnoopyCommandSource;
 import carpet.api.settings.SettingsManager;
@@ -51,7 +52,7 @@ public static void handleData(FriendlyByteBuf data, ServerPlayer player)
 
     public static void onPlayerJoin(ServerPlayer playerEntity)
     {
-        if (!playerEntity.connection.connection.isMemoryConnection())
+        if (!((ServerGamePacketListenerImplInterface)playerEntity.connection).getConnection().isMemoryConnection())
         {
             playerEntity.connection.send(new ClientboundCustomPayloadPacket(
                     CarpetClient.CARPET_CHANNEL,
@@ -218,7 +219,7 @@ public static void sendCustomCommand(ServerPlayer player, String command, Tag da
     public static void onPlayerLoggedOut(ServerPlayer player)
     {
         validCarpetPlayers.remove(player);
-        if (!player.connection.connection.isMemoryConnection())
+        if (!((ServerGamePacketListenerImplInterface)player.connection).getConnection().isMemoryConnection())
             remoteCarpetPlayers.remove(player);
     }
 
diff --git a/src/main/java/carpet/script/api/Auxiliary.java b/src/main/java/carpet/script/api/Auxiliary.java
index c5611e0a26..a82786a01a 100644
--- a/src/main/java/carpet/script/api/Auxiliary.java
+++ b/src/main/java/carpet/script/api/Auxiliary.java
@@ -38,7 +38,6 @@
 import carpet.script.value.ValueConversions;
 import carpet.utils.Messenger;
 import com.google.common.collect.Lists;
-import com.mojang.bridge.game.PackType;
 import net.minecraft.SharedConstants;
 import net.minecraft.commands.CommandSourceStack;
 import net.minecraft.core.BlockPos;
@@ -66,6 +65,7 @@
 import net.minecraft.server.MinecraftServer;
 import net.minecraft.server.level.ServerLevel;
 import net.minecraft.server.level.ServerPlayer;
+import net.minecraft.server.packs.PackType;
 import net.minecraft.server.packs.repository.Pack;
 import net.minecraft.server.packs.repository.PackRepository;
 import net.minecraft.sounds.SoundEvent;
@@ -1056,7 +1056,7 @@ else if (fdesc.type == FileArgument.Type.JSON)
                         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.getCurrentVersion().getPackVersion(PackType.DATA)),
+                                        StringValue.of("pack_format"), new NumericValue(SharedConstants.getCurrentVersion().getPackVersion(PackType.SERVER_DATA)),
                                         StringValue.of("description"), StringValue.of(name),
                                         StringValue.of("source"), StringValue.of("scarpet")
                                 )))
diff --git a/src/main/java/carpet/script/utils/BiomeInfo.java b/src/main/java/carpet/script/utils/BiomeInfo.java
index cfc36c7409..69b448893a 100644
--- a/src/main/java/carpet/script/utils/BiomeInfo.java
+++ b/src/main/java/carpet/script/utils/BiomeInfo.java
@@ -1,15 +1,18 @@
 package carpet.script.utils;
 
+import carpet.fakes.BiomeInterface;
 import carpet.script.value.ListValue;
 import carpet.script.value.NumericValue;
 import carpet.script.value.StringValue;
 import carpet.script.value.Value;
 import carpet.script.value.ValueConversions;
 import java.util.HashMap;
+import java.util.Locale;
 import java.util.Map;
 import java.util.function.BiFunction;
 import java.util.stream.Collectors;
 
+import net.minecraft.core.BlockPos;
 import net.minecraft.core.Registry;
 import net.minecraft.core.registries.Registries;
 import net.minecraft.server.level.ServerLevel;
@@ -30,8 +33,8 @@ public class BiomeInfo
         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("humidity", (w, b) -> NumericValue.of(((BiomeInterface) (Object) b).getClimateSettings().downfall()));
+        put("precipitation", (w, b) -> StringValue.of(b.getPrecipitationAt(new BlockPos(0, w.getSeaLevel(), 0)).name().toLowerCase(Locale.ROOT)));
         //put("depth", (w, b) -> NumericValue.of(b.getDepth()));
         //put("scale", (w, b) -> NumericValue.of(b.getScale()));
         put("features", (w, b) -> {
diff --git a/src/main/java/carpet/script/utils/ShapesRenderer.java b/src/main/java/carpet/script/utils/ShapesRenderer.java
index e7e14ec193..33ff5cf3e2 100644
--- a/src/main/java/carpet/script/utils/ShapesRenderer.java
+++ b/src/main/java/carpet/script/utils/ShapesRenderer.java
@@ -87,7 +87,6 @@ public void render(PoseStack matrices, Camera camera, float partialTick)
         if ((shapes.get(dimensionType) == null || shapes.get(dimensionType).isEmpty()) &&
                 (labels.get(dimensionType) == null || labels.get(dimensionType).isEmpty())) return;
         long currentTime = client.level.getGameTime();
-        RenderSystem.disableTexture();
         RenderSystem.enableDepthTest();
         RenderSystem.setShader(GameRenderer::getPositionColorShader);
         RenderSystem.depthFunc(515);
@@ -148,7 +147,6 @@ public void render(PoseStack matrices, Camera camera, float partialTick)
         RenderSystem.depthMask(true);
         RenderSystem.enableBlend();
         RenderSystem.defaultBlendFunc();
-        RenderSystem.enableTexture();
         CarpetProfiler.end_current_section(token);
     }
 
diff --git a/src/main/java/carpet/script/utils/SystemInfo.java b/src/main/java/carpet/script/utils/SystemInfo.java
index 514d085d55..e5112a1c04 100644
--- a/src/main/java/carpet/script/utils/SystemInfo.java
+++ b/src/main/java/carpet/script/utils/SystemInfo.java
@@ -15,11 +15,11 @@
 import carpet.script.value.Value;
 import carpet.script.value.ValueConversions;
 import carpet.api.settings.SettingsManager;
-import com.mojang.bridge.game.PackType;
 import com.sun.management.OperatingSystemMXBean;
 import net.fabricmc.loader.api.FabricLoader;
 import net.fabricmc.loader.api.ModContainer;
 import net.minecraft.SharedConstants;
+import net.minecraft.server.packs.PackType;
 import net.minecraft.world.level.GameRules;
 import net.minecraft.world.level.border.WorldBorder;
 import net.minecraft.world.level.storage.LevelData;
@@ -99,8 +99,8 @@ public class SystemInfo {
             return NumericValue.of((vers.length > 2)?Integer.parseInt(vers[2]):0);
         });
         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(PackType.DATA)));
+        put("game_data_version", c->NumericValue.of(SharedConstants.getCurrentVersion().getDataVersion().getVersion()));
+        put("game_pack_version", c->NumericValue.of(SharedConstants.getCurrentVersion().getPackVersion(PackType.SERVER_DATA)));
 
         put("server_ip", c -> StringValue.of(c.server().getLocalIp()));
         put("server_whitelisted", c -> BooleanValue.of(c.server().isEnforceWhitelist()));
diff --git a/src/main/java/carpet/script/value/EntityValue.java b/src/main/java/carpet/script/value/EntityValue.java
index cdb314bd9b..ffc3d44ad7 100644
--- a/src/main/java/carpet/script/value/EntityValue.java
+++ b/src/main/java/carpet/script/value/EntityValue.java
@@ -55,6 +55,7 @@
 import net.minecraft.world.entity.MobType;
 import net.minecraft.world.entity.PathfinderMob;
 import net.minecraft.world.entity.Pose;
+import net.minecraft.world.entity.RelativeMovement;
 import net.minecraft.world.entity.ai.Brain;
 import net.minecraft.world.entity.ai.attributes.Attribute;
 import net.minecraft.world.entity.ai.attributes.AttributeMap;
@@ -989,9 +990,9 @@ private static void updatePosition(Entity e, double x, double y, double z, float
         if (e instanceof ServerPlayer)
         {
             // this forces position but doesn't angles for some reason. Need both in the API in the future.
-            EnumSet set  = EnumSet.noneOf(ClientboundPlayerPositionPacket.RelativeArgument.class);
-            set.add(ClientboundPlayerPositionPacket.RelativeArgument.X_ROT);
-            set.add(ClientboundPlayerPositionPacket.RelativeArgument.Y_ROT);
+            EnumSet set  = EnumSet.noneOf(RelativeMovement.class);
+            set.add(RelativeMovement.X_ROT);
+            set.add(RelativeMovement.Y_ROT);
             ((ServerPlayer)e).connection.teleport(x, y, z, yaw, pitch, set );
         }
         else
diff --git a/src/main/resources/carpet.accesswidener b/src/main/resources/carpet.accesswidener
index 405db4208c..903db44003 100644
--- a/src/main/resources/carpet.accesswidener
+++ b/src/main/resources/carpet.accesswidener
@@ -5,5 +5,6 @@ accessible class net/minecraft/server/level/ThreadedLevelLightEngine$TaskType
 accessible class net/minecraft/world/item/crafting/Ingredient$Value
 accessible class net/minecraft/world/level/lighting/BlockLightSectionStorage$BlockDataLayerStorageMap
 accessible class net/minecraft/server/MinecraftServer$ReloadableResources
+accessible class net/minecraft/world/level/biome/Biome$ClimateSettings
 
 accessible field net/minecraft/world/level/block/state/BlockBehaviour UPDATE_SHAPE_ORDER [Lnet/minecraft/core/Direction;
diff --git a/src/main/resources/carpet.mixins.json b/src/main/resources/carpet.mixins.json
index e5c7fd6624..a6c87ce10d 100644
--- a/src/main/resources/carpet.mixins.json
+++ b/src/main/resources/carpet.mixins.json
@@ -165,6 +165,7 @@
     "HorseBaseEntity_scarpetMixin",
     "NoiseSampler_scarpetMixin",
     "QuantizedSpaghettiRarityMixin_scarpetMixin",
+    "Biome_scarpetMixin",
 
     "BlockEntity_movableBEMixin",
     "PistonBaseBlock_movableBEMixin",

From 943fa1ed0f5ef79b33c7ac7cd99cd0f71ea28ef7 Mon Sep 17 00:00:00 2001
From: gnembon <41132274+gnembon@users.noreply.github.com>
Date: Wed, 18 Jan 2023 22:12:07 +0100
Subject: [PATCH 007/233] 1.4.94

---
 gradle.properties | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/gradle.properties b/gradle.properties
index 4d21ef2998..ec9b8ddf8d 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -9,7 +9,7 @@ org.gradle.jvmargs=-Xmx1G
 	fabric_version=0.72.0+1.19.3
 
 # Mod Properties
-	mod_version = 1.4.93
+	mod_version = 1.4.94
 	maven_group = carpet
 	archives_base_name = fabric-carpet
 

From 8935764df5e9c1a54058e8471a1be07c02c18ed8 Mon Sep 17 00:00:00 2001
From: gnembon <41132274+gnembon@users.noreply.github.com>
Date: Wed, 18 Jan 2023 22:14:56 +0100
Subject: [PATCH 008/233] 1.4.94

---
 src/main/java/carpet/CarpetSettings.java | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/main/java/carpet/CarpetSettings.java b/src/main/java/carpet/CarpetSettings.java
index ca6e62ba33..13e7995b70 100644
--- a/src/main/java/carpet/CarpetSettings.java
+++ b/src/main/java/carpet/CarpetSettings.java
@@ -51,7 +51,7 @@
 public class CarpetSettings
 {
     public static final String carpetVersion = FabricLoader.getInstance().getModContainer("carpet").orElseThrow().getMetadata().getVersion().toString();
-    public static final String releaseTarget = "1.19.3";
+    public static final String releaseTarget = "1.19.4";
     public static final Logger LOG = LoggerFactory.getLogger("carpet");
     public static final ThreadLocal skipGenerationChecks = ThreadLocal.withInitial(() -> false);
     public static final ThreadLocal impendingFillSkipUpdates = ThreadLocal.withInitial(() -> false);

From b81ce06beb5aaf30368da903289d405cbdbc7be5 Mon Sep 17 00:00:00 2001
From: "github-actions[bot]" 
Date: Wed, 18 Jan 2023 21:21:10 +0000
Subject: [PATCH 009/233] Merge docs for 'Carpet Mod 1.4.94 for 23w03a'

---
 docs/scarpet/Full.md | 56 ++++++++++++++++++++++----------------------
 1 file changed, 28 insertions(+), 28 deletions(-)

diff --git a/docs/scarpet/Full.md b/docs/scarpet/Full.md
index 3b9bb75a18..35cb033866 100644
--- a/docs/scarpet/Full.md
+++ b/docs/scarpet/Full.md
@@ -549,7 +549,7 @@ A set of assignment operators. All require bounded variable on the LHS, `<>` req
 right hand side as well (bounded, meaning being variables). Additionally they can also handle list constructors 
 with all bounded variables, and work then as list assignment operators. When `+=` is used on a list, it extends 
 that list of that element, and returns the list (old == new). `scarpet` doesn't support currently removal of items. 
-Removal of items can be obtaine via `filter` command, and reassigning it fo the same variable. Both operations would 
+Removal of items can be obtained via `filter` command, and reassigning it fo the same variable. Both operations would 
 require rewriting of the array anyways.
 
 
@@ -603,7 +603,7 @@ args() -> ... [1, 2, 3]; sum(a, b, c) -> a+b+c; sum(args())   => 6
 a = ... [1, 2, 3]; sum(a, b, c) -> a+b+c; sum(a)   => 6
 
-Unpacking mechanics can be used for list and map constriction, not just for function calls. +Unpacking mechanics can be used for list and map construction, not just for function calls.
 [...range(5), pi, ...range(5,-1,-1)]   => [0, 1, 2, 3, 4, 3.14159265359, 5, 4, 3, 2, 1, 0]
@@ -677,7 +677,7 @@ Highest integer that is still no larger then `n`. Insert a floor pun here.
 
 ### `ceil(n)`
 
-First lucky integer that is not smalller than `n`. As you would expect, ceiling is typically right above the floor.
+First lucky integer that is not smaller than `n`. As you would expect, ceiling is typically right above the floor.
 
 ### `ln(n)`
 
@@ -847,7 +847,7 @@ str('foo') => 'foo'
 str('3bar') => '3bar'
 str(2)+str(2) => '22'
 str('pi: %.2f',pi) => 'pi: 3.14'
-str('player at: %d %d %d',pos(player())) => 'player at: 567, -2423, 124'
+str('player at: %d, %d, %d',pos(player())) => 'player at: 567, -2423, 124'
 
* * * @@ -975,7 +975,7 @@ title('aBc') => 'Abc' ### `replace(string, regex, repl?); replace_first(string, regex, repl?)` -Replaces all, or first occurence of a regular expression in the string with `repl` expression, +Replaces all, or first occurrence of a regular expression in the string with `repl` expression, or nothing, if not specified. To use escape characters (`\(`,`\+`,...), metacharacters (`\d`,`\w`,...), or position anchors (`\b`,`\z`,...) in your regular expression, use two backslashes.
@@ -1256,7 +1256,7 @@ From which we can learn that there is 7216 primes between 1M and 1.1M
 
 Evaluates expression `expr` repeatedly until condition `cond` becomes false, but not more than `limit` times. 
 Returns the result of the last `expr` evaluation, or `null` if nothing was successful. Both `expr` and `cond` will 
-recveived a bound variable `_` indicating current iteration, so its a number.
+received a bound variable `_` indicating current iteration, so its a number.
 
 
 while(a<100,10,a=_*_)  => 81 // loop exhausted via limit
@@ -2829,8 +2829,8 @@ Returns the map colour of a block at position. One of:
 
 `'air'`, `'grass'`, `'sand'`, `'wool'`, `'tnt'`, `'ice'`, `'iron'`, `'foliage'`, `'snow'`, `'clay'`, `'dirt'`, 
 `'stone'`, `'water'`, `'wood'`, `'quartz'`, `'adobe'`, `'magenta'`, `'light_blue'`, `'yellow'`, `'lime'`, `'pink'`, 
-`'gray'`, `'light_gray'`, `'cyan'`, `'purple'`, `'blue'`, `'brown'`, `'green'`, `'red'`, `'black'`, `'gold
-'`, `'diamond'`, `'lapis'`, `'emerald'`, `'obsidian'`, `'netherrack'`, `'white_terracotta'`, `'orange_terracotta'`, 
+`'gray'`, `'light_gray'`, `'cyan'`, `'purple'`, `'blue'`, `'brown'`, `'green'`, `'red'`, `'black'`, `'gold'`, 
+`'diamond'`, `'lapis'`, `'emerald'`, `'obsidian'`, `'netherrack'`, `'white_terracotta'`, `'orange_terracotta'`, 
 `'magenta_terracotta'`, `'light_blue_terracotta'`, `'yellow_terracotta'`, `'lime_terracotta'`, `'pink_terracotta'`, 
 `'gray_terracotta'`, `'light_gray_terracotta'`, `'cyan_terracotta'`, `'purple_terracotta'`, `'blue_terracotta'`, 
 `'brown_terracotta'`, `'green_terracotta'`, `'red_terracotta'`, `'black_terracotta'`,
@@ -3067,12 +3067,12 @@ These contain some popular features and structures that are impossible or diffic
 * `'coral_mushroom'` - mushroom coral feature
 * `'coral_tree'` - tree coral feature
 * `'fancy_oak_bees'` - large oak tree variant with a mandatory beehive unlike standard that generate with probability
-* `'oak_bees'` - normal oak tree with a manatory beehive unlike standard that generate with probability
+* `'oak_bees'` - normal oak tree with a mandatory beehive unlike standard that generate with probability
 
 
 ### `structure_eligibility(pos, ?structure, ?size_needed)`
 
-Checks wordgen eligibility for a structure in a given chunk. Requires a `Structure Variant` name (see above),
+Checks worldgen eligibility for a structure in a given chunk. Requires a `Structure Variant` name (see above),
 or `Standard Structure` to check structures of this type.
 If no structure is given, or `null`, then it will check
 for all structures. If bounding box of the structures is also requested, it will compute size of potential
@@ -3283,7 +3283,7 @@ cuboid search area.
 
 ### `entity_selector(selector)`
 
-Returns entities satisifying given vanilla entity selector. Most complex among all the methods of selecting entities, 
+Returns entities satisfying given vanilla entity selector. Most complex among all the methods of selecting entities, 
 but the most capable. Selectors are cached so it should be as fast as other methods of selecting entities. Unlike other
 entities fetching / filtering method, this one doesn't guarantee to return entities from current dimension, since
 selectors can return any loaded entity in the world.
@@ -3314,7 +3314,7 @@ Boolean. True if the entity is removed.
 
 ### `query(e, 'id')`
 
-Returns numerical id of the entity. Most efficient way to keep track of entites in a script. 
+Returns numerical id of the entity. Most efficient way to keep track of entities in a script. 
 Ids are only unique within current game session (ids are not preserved between restarts), 
 and dimension (each dimension has its own ids which can overlap).
 
@@ -3364,7 +3364,7 @@ Respective component of the entity's motion vector
 
 ### `query(e, 'on_ground')`
 
-Returns `true` if en entity is standing on firm ground and falling down due to that.
+Returns `true` if an entity is standing on firm ground and falling down due to that.
 
 ### `query(e, 'name'), query(e, 'display_name'), query(e, 'custom_name'), query(e, 'type')`
 
@@ -3597,7 +3597,7 @@ Returns `null` if the argument is not a player, otherwise:
 *   `multiplayer`: for players on a dedicated server
 *   `lan_host`: for singleplayer owner that opened the game to LAN
 *   `lan_player`: for all other players that connected to a LAN host
-*   `fake`: any carpet-spanwed fake player
+*   `fake`: any carpet-spawned fake player
 *   `shadow`: any carpet-shadowed real player
 *   `realms`: ?
 
@@ -4239,7 +4239,7 @@ With no arguments, returns a list of all items in the game. With an item tag pro
 
 ### `item_tags(item, tag?)`
 
-Returns list of tags the item belongs to, or, if tag is provided, `true` if an item maches the tag, `false` if it doesn't and `null` if that's not a valid tag
+Returns list of tags the item belongs to, or, if tag is provided, `true` if an item matches the tag, `false` if it doesn't and `null` if that's not a valid tag
 
 Throws `unknown_item` if item doesn't exist.
 
@@ -4707,7 +4707,7 @@ Events triggered in an app can result in zero, one, or multiple executions, depe
  * player targeted events (like `player_breaks_block`) target each app once:
    * for global scoped apps - targets a single app instance and provides `player` as the first argument.
    * for player scoped apps - targets only a given player instance, providing player argument for API consistency, 
-     since active player in player scoped apps can always be retrived using `player()`. 
+     since active player in player scoped apps can always be retrieved using `player()`. 
  * global events could be handled by multiple players multiple times (like `explosion`, or `tick`):
    * for global scoped apps - triggered once for the single app instance.
    * for player scoped apps - triggered N times for each player separately, so they can do something with that information
@@ -4749,7 +4749,7 @@ the system is closing down exceptionally.
 ## Built-in global events
 
 Global events will be handled once per app that is with `'global'` scope. With `player` scoped apps, each player instance
- will be triggerd once for each player, so a global event may be executed multiple times for such apps.
+ will be triggered once for each player, so a global event may be executed multiple times for such apps.
 
 ### `__on_server_starts()`
 Event triggers after world is loaded and after all startup apps have started. It won't be triggered with `/reload`.
@@ -4911,14 +4911,14 @@ Triggered when a player attacks entity, right before it happens server side.
 This event can be cancelled by returning `'cancel'`, which prevents the player from attacking the entity.
 
 ### `__on_player_takes_damage(player, amount, source, source_entity)`
-Triggered when a player is taking damage. Event is executed right after potential absorbtion was applied and before
+Triggered when a player is taking damage. Event is executed right after potential absorption was applied and before
 the actual damage is applied to the player. 
 
 This event can be cancelled by returning `'cancel'`, which prevents the player from taking damage.
 
 ### `__on_player_deals_damage(player, amount, entity)`
 Triggered when a player deals damage to another entity. Its applied in the same moment as `player_takes_damage` if both
-sides of the event are players, and similar for all other entities, just their absorbtion is taken twice, just noone ever 
+sides of the event are players, and similar for all other entities, just their absorption is taken twice, just noone ever 
 notices that ¯\_(ツ)_/¯
 
 This event can be cancelled by returning `'cancel'`, which prevents the damage from being dealt.
@@ -5001,7 +5001,7 @@ is handled before scoreboard values for these statistics are changed.
 
 App programmers can define and trigger their own custom events. Unlike built-in events, all custom events pass a single value
 as an argument, but this doesn't mean that they cannot pass a complex list, map, or nbt tag as a message. Each event signal is
-either targetting all apps instances for all players, including global apps, if no target player has been identified, 
+either targeting all apps instances for all players, including global apps, if no target player has been identified, 
 or only player scoped apps, if the target player
 is specified, running once for that player app. You cannot target global apps with player-targeted signals. Built-in events
 do target global apps, since their first argument is clearly defined and passed. That may change in the future in case there is 
@@ -5045,7 +5045,7 @@ to it when the event is triggered. All custom events expect a function that take
 If extra arguments are provided, they will be appended to the argument list of the callback function.
 
 Returns `true` if subscription to the event was successful, or `false` if it failed (for instance wrong scope for built-in event,
-or incorect number of parameters for the event).
+or incorrect number of parameters for the event).
 
 If a callback is specified as `null`, the given app (or player app instance )stops handling that event. 
 
@@ -5069,7 +5069,7 @@ In case you want to pass an event handler that is not defined in your module, pl
 
 Fires a specific event. If the event does not exist (only `handle_event` creates missing new events), or provided argument list
 was not matching the callee expected arguments, returns `null`, 
-otherwise returns number of apps notified. If `target_player` is specified and not `null` triggers a player specific event, targetting
+otherwise returns number of apps notified. If `target_player` is specified and not `null` triggers a player specific event, targeting
 only `player` scoped apps for that player. Apps with globals scope will not be notified even if they handle this event.
 If the `target_player` is omitted or `null`, it will target `global` scoped apps and all instances of `player` scoped apps.
 Note that all built-in player events have a player as a first argument, so to trigger these events, you need to 
@@ -5305,7 +5305,7 @@ Collection of other methods that control smaller, yet still important aspects of
 Plays a specific sound `name`, at block or position `pos`, with optional `volume` and modified `pitch`, and under
 optional `mixer`. Default values for `volume`, `pitch` and `mixer` are `1.0`, `1.0`, and `master`. 
 Valid mixer options are `master`, `music`, `record`, `weather`, `block`, `hostile`,`neutral`, `player`, `ambient`
-and `voice`. `pos` can be either a block, triple of coords, or a list of thee numbers. Uses the same options as a
+and `voice`. `pos` can be either a block, triple of coords, or a list of three numbers. Uses the same options as a
  corresponding `playsound` command.
  
 Used with no arguments, return the list of available sound names.
@@ -5540,7 +5540,7 @@ produce an exception.
 
 ### `print(expr)`, `print(player/player_list, expr)`
 
-Displays the result of the expression to the chat. Overrides default `scarpet` behaviour of sending everyting to stderr.
+Displays the result of the expression to the chat. Overrides default `scarpet` behaviour of sending everything to stderr.
 Can optionally define player or list of players to send the message to.
 
 ### `format(components, ...)`, `format([components, ...])`
@@ -5930,7 +5930,7 @@ to that value. Daytime clocks are shared between all dimensions.
 _**Deprecated**. Use `system_info('server_last_tick_times')` instead._
 
 Returns a 100-long array of recent tick times, in milliseconds. First item on the list is the most recent tick
-If called outside of the main tick (either throgh scheduled tasks, or async execution), then the first item on the
+If called outside of the main tick (either through scheduled tasks, or async execution), then the first item on the
 list may refer to the previous tick performance. In this case the last entry (tick 100) would refer to the most current
 tick. For all intent and purpose, `last_tick_times():0` should be used as last tick execution time, but
 individual tick times may vary greatly, and these need to be taken with the little grain of 
@@ -5951,7 +5951,7 @@ If you need to break
 up your execution into chunks, you could queue the rest of the work into the next task using `schedule`, or perform your actions
 defining `__on_tick()` event handler, but in case you need to take a full control over the game loop and run some simulations using 
 `game_tick()` as the way to advance the game progress, that might be the simplest way to do it, 
-and triggering the script in a 'proper' way (there is not 'proper' way, but via commmand line, or server chat is the most 'proper'),
+and triggering the script in a 'proper' way (there is not 'proper' way, but via command line, or server chat is the most 'proper'),
 would be the safest way to do it. For instance, running `game_tick()` from a command block triggered with a button, or in an entity
  event triggered in an entity tick, may technically
 cause the game to run and encounter that call again, causing stack to overflow. Thankfully it doesn't happen in vanilla running 
@@ -6157,7 +6157,7 @@ check `load_app_data` and `store_app_data` functions.
 
 
 Unloading the app will only mask their command tree, not remove it. This has the same effect than not having that command
-at all, with the exception that if you load a diffrent app with the same name, this may cause commands to reappear.
+at all, with the exception that if you load a different app with the same name, this may cause commands to reappear.
 To remove the commands fully, use `/reload`.
 
 
@@ -6204,7 +6204,7 @@ at the end
 
 ### `/script invokearea     ...`
 
-It is equivalent to `invoke` except it assumes that the first three arguments are one set of ccordinates, 
+It is equivalent to `invoke` except it assumes that the first three arguments are one set of coordinates, 
 followed by the second set of coordinates, providing tab completion, with `looking at...` mechanics for convenience, 
 followed by any other required arguments
 

From e9244775582da2bcc1863b36f59d8f1449837cd7 Mon Sep 17 00:00:00 2001
From: altrisi 
Date: Wed, 18 Jan 2023 22:43:01 +0100
Subject: [PATCH 010/233] Use `enum` for `chainstone` setting

And very minor cleanup in `CarpetSettings`
---
 src/main/java/carpet/CarpetSettings.java      | 43 +++++--------------
 .../mixins/ChainBlock_customStickyMixin.java  |  5 ++-
 2 files changed, 13 insertions(+), 35 deletions(-)

diff --git a/src/main/java/carpet/CarpetSettings.java b/src/main/java/carpet/CarpetSettings.java
index 13e7995b70..e8ffeabc38 100644
--- a/src/main/java/carpet/CarpetSettings.java
+++ b/src/main/java/carpet/CarpetSettings.java
@@ -32,7 +32,6 @@
 import org.slf4j.LoggerFactory;
 
 import java.util.Iterator;
-import java.util.Locale;
 import java.util.Optional;
 
 import static carpet.api.settings.RuleCategory.BUGFIX;
@@ -56,8 +55,6 @@ public class CarpetSettings
     public static final ThreadLocal skipGenerationChecks = ThreadLocal.withInitial(() -> false);
     public static final ThreadLocal impendingFillSkipUpdates = ThreadLocal.withInitial(() -> false);
     public static int runPermissionLevel = 2;
-    public static boolean doChainStone = false;
-    public static boolean chainStoneStickToAll = false;
     public static Block structureBlockIgnoredBlock = Blocks.STRUCTURE_VOID;
     private static class LanguageValidator extends Validator {
         @Override public String validate(CommandSourceStack source, CarpetRule currentRule, String newValue, String string) {
@@ -386,13 +383,10 @@ public String description() {
     @Rule( desc = "Pistons can push block entities, like hoppers, chests etc.", category = {EXPERIMENTAL, FEATURE} )
     public static boolean movableBlockEntities = false;
 
-
-    private static class ChainStoneSetting extends Validator {
-        @Override public String validate(CommandSourceStack source, CarpetRule currentRule, String newValue, String string) {
-            CarpetSettings.doChainStone = !newValue.toLowerCase(Locale.ROOT).equals("false");
-            CarpetSettings.chainStoneStickToAll = newValue.toLowerCase(Locale.ROOT).equals("stick_to_all");
-
-            return newValue;
+    public enum ChainStoneMode {
+        TRUE, FALSE, STICK_TO_ALL;
+        public boolean enabled() {
+            return this != FALSE;
         }
     }
 
@@ -402,11 +396,9 @@ private static class ChainStoneSetting extends Validator {
                     "and will stick to other blocks that connect to them directly.",
                     "With stick_to_all: it will stick even if not visually connected"
             },
-            category = {EXPERIMENTAL, FEATURE},
-            options = {"true", "false", "stick_to_all"},
-            validate = ChainStoneSetting.class
+            category = {EXPERIMENTAL, FEATURE}
     )
-    public static String chainStone = "false";
+    public static ChainStoneMode chainStone = ChainStoneMode.FALSE;
 
     @Rule( desc = "Saplings turn into dead shrubs in hot climates and no water access", category = FEATURE )
     public static boolean desertShrubs = false;
@@ -487,18 +479,10 @@ private static class ChainStoneSetting extends Validator {
     private static class ModulePermissionLevel extends Validator {
         @Override public String validate(CommandSourceStack source, CarpetRule currentRule, String newValue, String string) {
             int permissionLevel = switch (newValue) {
-                    case "false":
-                        yield 0;
-                    case "true":
-                    case "ops":
-                        yield 2;
-                    case "0":
-                    case "1":
-                    case "2":
-                    case "3":
-                    case "4":
-                    	yield Integer.parseInt(newValue);
-                    default: throw new IllegalArgumentException();
+                    case "false" -> 0;
+                    case "true", "ops" -> 2;
+                    case "0", "1", "2", "3", "4" -> Integer.parseInt(newValue);
+                    default -> throw new IllegalArgumentException(); // already checked by previous validator
             	};
             if (source != null && !source.hasPermission(permissionLevel))
                 return null;
@@ -591,13 +575,6 @@ private static class ModulePermissionLevel extends Validator {
     )
     public static boolean smoothClientAnimations;
 
-    //@Rule(
-    //        desc="Fixes mining ghost blocks by trusting clients with block breaking",
-    //        extra="Increases player allowed mining distance to 32 blocks",
-    //        category = SURVIVAL
-    //)
-    //public static boolean miningGhostBlockFix = false;
-
     private static class PushLimitLimits extends Validator {
         @Override public Integer validate(CommandSourceStack source, CarpetRule currentRule, Integer newValue, String string) {
             return (newValue>0 && newValue <= 1024) ? newValue : null;
diff --git a/src/main/java/carpet/mixins/ChainBlock_customStickyMixin.java b/src/main/java/carpet/mixins/ChainBlock_customStickyMixin.java
index 2e2d1e014b..9cad0aea61 100644
--- a/src/main/java/carpet/mixins/ChainBlock_customStickyMixin.java
+++ b/src/main/java/carpet/mixins/ChainBlock_customStickyMixin.java
@@ -3,6 +3,7 @@
 import org.spongepowered.asm.mixin.Mixin;
 
 import carpet.CarpetSettings;
+import carpet.CarpetSettings.ChainStoneMode;
 import carpet.fakes.BlockBehaviourInterface;
 
 import net.minecraft.core.BlockPos;
@@ -20,7 +21,7 @@ public class ChainBlock_customStickyMixin implements BlockBehaviourInterface {
 
     @Override
     public boolean isSticky(BlockState state) {
-        return CarpetSettings.doChainStone;
+        return CarpetSettings.chainStone.enabled();
     }
 
     @Override
@@ -31,7 +32,7 @@ public boolean isStickyToNeighbor(Level level, BlockPos pos, BlockState state, B
             return false;
         }
 
-        if (CarpetSettings.chainStoneStickToAll) {
+        if (CarpetSettings.chainStone == ChainStoneMode.STICK_TO_ALL) {
             return true;
         }
         if (neighborState.is((Block)(Object)this)) {

From dd1dc3756a645668fa1d867df57df195e8fd5f48 Mon Sep 17 00:00:00 2001
From: altrisi 
Date: Thu, 19 Jan 2023 00:28:57 +0100
Subject: [PATCH 011/233] Remove a no longer necessary mixin

And tiny cleanup to another one
---
 ...MovingBlockEntity_playerHandlingMixin.java | 24 +++++++------------
 .../mixins/PlayerTeam_scarpetMixin.java       | 13 ----------
 .../java/carpet/script/api/Scoreboards.java   |  3 +--
 src/main/resources/carpet.mixins.json         |  1 -
 4 files changed, 9 insertions(+), 32 deletions(-)
 delete mode 100644 src/main/java/carpet/mixins/PlayerTeam_scarpetMixin.java

diff --git a/src/main/java/carpet/mixins/PistonMovingBlockEntity_playerHandlingMixin.java b/src/main/java/carpet/mixins/PistonMovingBlockEntity_playerHandlingMixin.java
index 983ef2e797..cd5106a111 100644
--- a/src/main/java/carpet/mixins/PistonMovingBlockEntity_playerHandlingMixin.java
+++ b/src/main/java/carpet/mixins/PistonMovingBlockEntity_playerHandlingMixin.java
@@ -9,11 +9,9 @@
 import net.minecraft.world.level.Level;
 import net.minecraft.world.level.block.Blocks;
 import net.minecraft.world.level.block.piston.PistonMovingBlockEntity;
-import net.minecraft.world.level.block.state.BlockState;
 import net.minecraft.world.level.material.PushReaction;
 import net.minecraft.world.phys.Vec3;
 import org.spongepowered.asm.mixin.Mixin;
-import org.spongepowered.asm.mixin.Shadow;
 import org.spongepowered.asm.mixin.injection.At;
 import org.spongepowered.asm.mixin.injection.Inject;
 import org.spongepowered.asm.mixin.injection.Redirect;
@@ -22,7 +20,6 @@
 @Mixin(PistonMovingBlockEntity.class)
 public abstract class PistonMovingBlockEntity_playerHandlingMixin
 {
-
     @Inject(method = "moveEntityByPiston", at = @At("HEAD"), cancellable = true)
     private static void dontPushSpectators(Direction direction, Entity entity, double d, Direction direction2, CallbackInfo ci)
     {
@@ -46,22 +43,17 @@ private static PushReaction moveFakePlayers(Entity entity,
         if (entity instanceof EntityPlayerMPFake && pistonBlockEntity.getMovedState().is(Blocks.SLIME_BLOCK))
         {
             Vec3 vec3d = entity.getDeltaMovement();
-            double e = vec3d.x;
-            double f = vec3d.y;
-            double g = vec3d.z;
+            double x = vec3d.x;
+            double y = vec3d.y;
+            double z = vec3d.z;
             Direction direction = pistonBlockEntity.getMovementDirection();
-            switch(direction.getAxis()) {
-                case X:
-                    e = direction.getStepX();
-                    break;
-                case Y:
-                    f = direction.getStepY();
-                    break;
-                case Z:
-                    g = direction.getStepZ();
+            switch (direction.getAxis()) {
+                case X -> x = direction.getStepX();
+                case Y -> y = direction.getStepY();
+                case Z -> z = direction.getStepZ();
             }
 
-            entity.setDeltaMovement(e, f, g);
+            entity.setDeltaMovement(x, y, z);
         }
         return entity.getPistonPushReaction();
     }
diff --git a/src/main/java/carpet/mixins/PlayerTeam_scarpetMixin.java b/src/main/java/carpet/mixins/PlayerTeam_scarpetMixin.java
deleted file mode 100644
index 779ae8bbbd..0000000000
--- a/src/main/java/carpet/mixins/PlayerTeam_scarpetMixin.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package carpet.mixins;
-
-import net.minecraft.ChatFormatting;
-import net.minecraft.world.scores.PlayerTeam;
-import org.spongepowered.asm.mixin.Mixin;
-import org.spongepowered.asm.mixin.gen.Accessor;
-
-@Mixin(PlayerTeam.class)
-public interface PlayerTeam_scarpetMixin
-{
-    @Accessor("color")
-    ChatFormatting getColor();
-}
diff --git a/src/main/java/carpet/script/api/Scoreboards.java b/src/main/java/carpet/script/api/Scoreboards.java
index 1d5cf31011..8332dcaf15 100644
--- a/src/main/java/carpet/script/api/Scoreboards.java
+++ b/src/main/java/carpet/script/api/Scoreboards.java
@@ -2,7 +2,6 @@
 
 import carpet.mixins.Objective_scarpetMixin;
 import carpet.mixins.Scoreboard_scarpetMixin;
-import carpet.mixins.PlayerTeam_scarpetMixin;
 import carpet.script.CarpetContext;
 import carpet.script.Expression;
 import carpet.script.exception.InternalExpressionException;
@@ -334,7 +333,7 @@ public static void apply(Expression expression)
                     team.setCollisionRule(collisionRule);
                     break;
                 case "color":
-                    if(!modifying) return new StringValue(((PlayerTeam_scarpetMixin) team).getColor().getName());
+                    if(!modifying) return new StringValue(team.getColor().getName());
                     if(!(settingVal instanceof StringValue)) throw new InternalExpressionException("'team_property' requires a string as the third argument for the property " + propertyVal.getString());
                     ChatFormatting color = ChatFormatting.getByName(settingVal.getString().toUpperCase());
                     if(color == null || !color.isColor()) throw new InternalExpressionException("Unknown value for property " + propertyVal.getString() + ": " + settingVal.getString());
diff --git a/src/main/resources/carpet.mixins.json b/src/main/resources/carpet.mixins.json
index a6c87ce10d..ddc27dbb4b 100644
--- a/src/main/resources/carpet.mixins.json
+++ b/src/main/resources/carpet.mixins.json
@@ -143,7 +143,6 @@
     "Inventory_scarpetEventMixin",
     "Objective_scarpetMixin",
     "Scoreboard_scarpetMixin",
-    "PlayerTeam_scarpetMixin",
     "MerchantResultSlot_scarpetEventMixin",
     "AbstractContainerMenu_scarpetMixin",
     "AbstractContainerMenuSubclasses_scarpetMixin",

From 17249c3c77ad5de5319fdcb043abacfabc7b7bf2 Mon Sep 17 00:00:00 2001
From: altrisi 
Date: Thu, 19 Jan 2023 01:40:29 +0100
Subject: [PATCH 012/233] Refactor code to use `ListValue.wrap(Stream)`

Simplifies code (improving readability) and unifies `Stream` to `ListValue` handling
---
 .../java/carpet/script/api/Auxiliary.java     | 23 ++++++++-----------
 src/main/java/carpet/script/api/Entities.java |  8 +++----
 .../java/carpet/script/api/Inventories.java   | 18 +++++++--------
 .../java/carpet/script/api/Scoreboards.java   | 13 +++++------
 .../java/carpet/script/api/WorldAccess.java   | 21 ++++++++---------
 .../script/command/CommandArgument.java       |  8 +++----
 .../carpet/script/language/ControlFlow.java   |  2 +-
 .../script/language/DataStructures.java       |  3 +--
 .../carpet/script/language/Functions.java     |  5 ++--
 .../java/carpet/script/utils/BiomeInfo.java   |  3 +--
 .../java/carpet/script/utils/SystemInfo.java  | 13 +++++------
 .../java/carpet/script/value/EntityValue.java | 14 +++++------
 .../script/value/NBTSerializableValue.java    |  6 ++---
 src/main/java/carpet/script/value/Value.java  |  3 +--
 .../carpet/script/value/ValueConversions.java | 11 ++++-----
 15 files changed, 66 insertions(+), 85 deletions(-)

diff --git a/src/main/java/carpet/script/api/Auxiliary.java b/src/main/java/carpet/script/api/Auxiliary.java
index a82786a01a..3357fb87b8 100644
--- a/src/main/java/carpet/script/api/Auxiliary.java
+++ b/src/main/java/carpet/script/api/Auxiliary.java
@@ -42,17 +42,14 @@
 import net.minecraft.commands.CommandSourceStack;
 import net.minecraft.core.BlockPos;
 import net.minecraft.core.Holder;
-import net.minecraft.core.RegistryAccess;
 import net.minecraft.core.Rotations;
 import net.minecraft.core.particles.ParticleOptions;
-import net.minecraft.core.registries.BuiltInRegistries;
 import net.minecraft.core.registries.Registries;
 import net.minecraft.nbt.CompoundTag;
 import net.minecraft.nbt.NbtIo;
 import net.minecraft.nbt.NbtUtils;
 import net.minecraft.nbt.StringTag;
 import net.minecraft.nbt.Tag;
-import net.minecraft.network.chat.MutableComponent;
 import net.minecraft.network.chat.Component;
 import net.minecraft.network.protocol.Packet;
 import net.minecraft.network.protocol.game.ClientboundClearTitlesPacket;
@@ -572,7 +569,7 @@ else if (!interactable && targetBlock == null)
                     });
                 else
                     targetList.forEach(target -> {
-                        map.put(target.getScoreboardName(), (MutableComponent) title);
+                        map.put(target.getScoreboardName(), title);
                         total.getAndIncrement();
                     });
                 HUDController.update_hud(((CarpetContext)c).server(), targetList);
@@ -621,7 +618,7 @@ else if (!interactable && targetBlock == null)
                 );
                 return ListValue.of(
                         retval,
-                        ListValue.wrap(output.stream().map(FormattedTextValue::new).collect(Collectors.toList())),
+                        ListValue.wrap(output.stream().map(FormattedTextValue::new)),
                         FormattedTextValue.of(error[0])
                 );
             }
@@ -757,19 +754,19 @@ else if (!interactable && targetBlock == null)
                 Map plopData = new HashMap<>();
                 CarpetContext cc = (CarpetContext)c;
                 plopData.put(StringValue.of("scarpet_custom"),
-                        ListValue.wrap(FeatureGenerator.featureMap.keySet().stream().sorted().map(StringValue::of).collect(Collectors.toList()))
+                        ListValue.wrap(FeatureGenerator.featureMap.keySet().stream().sorted().map(StringValue::of))
                 );
                 plopData.put(StringValue.of("features"),
-                        ListValue.wrap(cc.registry(Registries.FEATURE).keySet().stream().sorted().map(ValueConversions::of).collect(Collectors.toList()))
+                        ListValue.wrap(cc.registry(Registries.FEATURE).keySet().stream().sorted().map(ValueConversions::of))
                 );
                 plopData.put(StringValue.of("configured_features"),
-                        ListValue.wrap(cc.registry(Registries.CONFIGURED_FEATURE).keySet().stream().sorted().map(ValueConversions::of).collect(Collectors.toList()))
+                        ListValue.wrap(cc.registry(Registries.CONFIGURED_FEATURE).keySet().stream().sorted().map(ValueConversions::of))
                 );
                 plopData.put(StringValue.of("structure_types"),
-                        ListValue.wrap(cc.registry(Registries.STRUCTURE_TYPE).keySet().stream().sorted().map(ValueConversions::of).collect(Collectors.toList()))
+                        ListValue.wrap(cc.registry(Registries.STRUCTURE_TYPE).keySet().stream().sorted().map(ValueConversions::of))
                 );
                 plopData.put(StringValue.of("structures"),
-                        ListValue.wrap(cc.registry(Registries.STRUCTURE).keySet().stream().sorted().map(ValueConversions::of).collect(Collectors.toList()))
+                        ListValue.wrap(cc.registry(Registries.STRUCTURE).keySet().stream().sorted().map(ValueConversions::of))
                 );
                 return MapValue.wrap(plopData);
             }
@@ -841,7 +838,7 @@ else if(lv.size()==2)
             FileArgument fdesc = FileArgument.from(lv,true, FileArgument.Reason.READ);
             Stream files = ((CarpetScriptHost) c.host).listFolder(fdesc);
             if (files == null) return Value.NULL;
-            return ListValue.wrap(files.map(StringValue::of).collect(Collectors.toList()));
+            return ListValue.wrap(files.map(StringValue::of));
         });
 
         expression.addContextFunction("read_file", 2, (c, t, lv) ->
@@ -868,7 +865,7 @@ else if (fdesc.type == FileArgument.Type.JSON)
             {
                 List content = ((CarpetScriptHost) c.host).readTextResource(fdesc);
                 if (content == null) return Value.NULL;
-                retVal = ListValue.wrap(content.stream().map(StringValue::new).collect(Collectors.toList()));
+                retVal = ListValue.wrap(content.stream().map(StringValue::new));
             }
             return retVal;
         });
@@ -1015,7 +1012,7 @@ else if (fdesc.type == FileArgument.Type.JSON)
             CarpetContext cc = (CarpetContext) c;
             CommandStorage storage = cc.server().getCommandStorage();
             if (lv.size() == 0)
-                return ListValue.wrap(storage.keys().map(i -> new StringValue(nameFromRegistryId(i))).collect(Collectors.toList()));
+                return ListValue.wrap(storage.keys().map(i -> new StringValue(nameFromRegistryId(i))));
             String key = lv.get(0).getString();
             CompoundTag old_nbt = storage.get(InputValidator.identifierOf(key));
             if (lv.size() == 2) {
diff --git a/src/main/java/carpet/script/api/Entities.java b/src/main/java/carpet/script/api/Entities.java
index be7205ecdf..00b6036c25 100644
--- a/src/main/java/carpet/script/api/Entities.java
+++ b/src/main/java/carpet/script/api/Entities.java
@@ -23,9 +23,7 @@
 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.registries.BuiltInRegistries;
 import net.minecraft.core.registries.Registries;
 import net.minecraft.nbt.CompoundTag;
 import net.minecraft.resources.ResourceLocation;
@@ -157,7 +155,7 @@ public static void apply(Expression expression)
             CommandSourceStack source = ((CarpetContext)c).source();
             EntityValue.EntityClassDescriptor eDesc = EntityValue.getEntityDescriptor(who, source.getServer());
             List entityList = source.getLevel().getEntities(eDesc.directType, eDesc.filteringPredicate);
-            return ListValue.wrap(entityList.stream().map(EntityValue::new).collect(Collectors.toList()));
+            return ListValue.wrap(entityList.stream().map(EntityValue::new));
         });
 
         expression.addContextFunction("entity_area", -1, (c, t, lv) ->
@@ -185,7 +183,7 @@ public static void apply(Expression expression)
             AABB area = centerBox.inflate(range.x, range.y, range.z);
             EntityValue.EntityClassDescriptor eDesc = EntityValue.getEntityDescriptor(who, cc.server());
             List entityList = cc.level().getEntities(eDesc.directType, area,eDesc.filteringPredicate);
-            return ListValue.wrap(entityList.stream().map(EntityValue::new).collect(Collectors.toList()));
+            return ListValue.wrap(entityList.stream().map(EntityValue::new));
         });
 
         expression.addContextFunction("entity_selector", -1, (c, t, lv) ->
@@ -253,7 +251,7 @@ else if (lv.size()==3)
             if (lv.size() < 2) throw new InternalExpressionException("'entity_load_handler' required the entity type, and a function to call");
             Value entityValue = lv.get(0);
             List descriptors = (entityValue instanceof ListValue)
-                    ? ((ListValue) entityValue).getItems().stream().map(Value::getString).collect(Collectors.toList())
+                    ? ((ListValue) entityValue).getItems().stream().map(Value::getString).toList()
                     : Collections.singletonList(entityValue.getString());
             Set> types = new HashSet<>();
             descriptors.forEach(s -> types.addAll(EntityValue.getEntityDescriptor(s, ((CarpetContext) c).server()).types));
diff --git a/src/main/java/carpet/script/api/Inventories.java b/src/main/java/carpet/script/api/Inventories.java
index 2901528794..f03bb6e76e 100644
--- a/src/main/java/carpet/script/api/Inventories.java
+++ b/src/main/java/carpet/script/api/Inventories.java
@@ -26,12 +26,10 @@
 import java.util.List;
 import java.util.Optional;
 import java.util.Set;
-import java.util.stream.Collectors;
 import net.minecraft.commands.arguments.item.ItemInput;
 import net.minecraft.core.HolderSet;
 import net.minecraft.core.Registry;
 import net.minecraft.core.RegistryAccess;
-import net.minecraft.core.registries.BuiltInRegistries;
 import net.minecraft.core.registries.Registries;
 import net.minecraft.nbt.CompoundTag;
 import net.minecraft.network.chat.Component;
@@ -70,17 +68,17 @@ public static void apply(Expression expression)
             CarpetContext cc = (CarpetContext)c;
             Registry items = cc.registry(Registries.ITEM);
             if (lv.size() == 0)
-                return ListValue.wrap(items.keySet().stream().map(ValueConversions::of).collect(Collectors.toList()));
+                return ListValue.wrap(items.keySet().stream().map(ValueConversions::of));
             String tag = lv.get(0).getString();
             Optional> itemTag = items.getTag(TagKey.create(Registries.ITEM, InputValidator.identifierOf(tag)));
             if (itemTag.isEmpty()) return Value.NULL;
-            return ListValue.wrap(itemTag.get().stream().map(b -> ValueConversions.of(items.getKey(b.value()))).collect(Collectors.toList()));
+            return ListValue.wrap(itemTag.get().stream().map(b -> ValueConversions.of(items.getKey(b.value()))));
             /*
             TagContainer tagManager = cc.s.getServer(). getTags();
             String tag = lv.get(0).getString();
             net.minecraft.tags.Tag itemTag = tagManager.getOrEmpty(Registry.ITEM_REGISTRY).getTag(InputValidator.identifierOf(tag));
             if (itemTag == null) return Value.NULL;
-            return ListValue.wrap(itemTag.getValues().stream().map(b -> ValueConversions.of(Registry.ITEM.getKey(b))).collect(Collectors.toList()));
+            return ListValue.wrap(itemTag.getValues().stream().map(b -> ValueConversions.of(Registry.ITEM.getKey(b))));
             */
         });
 
@@ -90,11 +88,11 @@ public static void apply(Expression expression)
 
             Registry blocks = cc.registry(Registries.ITEM);
             if (lv.size() == 0)
-                return ListValue.wrap(blocks.getTagNames().map(ValueConversions::of).collect(Collectors.toList()));
+                return ListValue.wrap(blocks.getTagNames().map(ValueConversions::of));
             Item item = NBTSerializableValue.parseItem(lv.get(0).getString(), cc.registryAccess()).getItem();
             if (lv.size() == 1)
             {
-                return ListValue.wrap( blocks.getTags().filter(e -> e.getSecond().stream().anyMatch(h -> (h.value() == item))).map(e -> ValueConversions.of(e.getFirst())).collect(Collectors.toList()));
+                return ListValue.wrap( blocks.getTags().filter(e -> e.getSecond().stream().anyMatch(h -> (h.value() == item))).map(e -> ValueConversions.of(e.getFirst())));
             }
             String tag = lv.get(1).getString();
             Optional> tagSet = blocks.getTag(TagKey.create(Registries.ITEM, InputValidator.identifierOf(tag)));
@@ -106,10 +104,10 @@ public static void apply(Expression expression)
             /*
             TagContainer tagManager = cc.s.getServer().getTags();
             if (lv.size() == 0)
-                return ListValue.wrap(tagManager.getOrEmpty(Registry.ITEM_REGISTRY).getAvailableTags().stream().map(ValueConversions::of).collect(Collectors.toList()));
+                return ListValue.wrap(tagManager.getOrEmpty(Registry.ITEM_REGISTRY).getAvailableTags().stream().map(ValueConversions::of));
             Item item = NBTSerializableValue.parseItem(lv.get(0).getString()).getItem();
             if (lv.size() == 1)
-                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()));
+                return ListValue.wrap(tagManager.getOrEmpty(Registry.ITEM_REGISTRY).getAllTags().entrySet().stream().filter(e -> e.getValue().contains(item)).map(e -> ValueConversions.of(e.getKey())));
             String tag = lv.get(1).getString();
             net.minecraft.tags.Tag itemTag = tagManager.getOrEmpty(Registry.ITEM_REGISTRY).getTag(InputValidator.identifierOf(tag));
             if (itemTag == null) return Value.NULL;
@@ -398,7 +396,7 @@ else if (nbtValue.isNull())
             else if (owner instanceof LivingEntity villager)
             {
                 // stolen from LookTargetUtil.give((VillagerEntity)owner, droppedStack, (LivingEntity) owner);
-                double double_1 = villager.getY() - 0.30000001192092896D + (double)villager.getEyeHeight();
+                double double_1 = villager.getY() - 0.30000001192092896D + 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);
diff --git a/src/main/java/carpet/script/api/Scoreboards.java b/src/main/java/carpet/script/api/Scoreboards.java
index 8332dcaf15..dae7769bee 100644
--- a/src/main/java/carpet/script/api/Scoreboards.java
+++ b/src/main/java/carpet/script/api/Scoreboards.java
@@ -18,7 +18,6 @@
 import com.google.common.collect.Lists;
 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.resources.ResourceLocation;
@@ -66,12 +65,12 @@ public static void apply(Expression expression)
             CarpetContext cc = (CarpetContext)c;
             Scoreboard scoreboard =  cc.server().getScoreboard();
             if (lv.size()==0)
-                return ListValue.wrap(scoreboard.getObjectiveNames().stream().map(StringValue::new).collect(Collectors.toList()));
+                return ListValue.wrap(scoreboard.getObjectiveNames().stream().map(StringValue::new));
             String objectiveName = lv.get(0).getString();
             Objective objective = scoreboard.getOrCreateObjective(objectiveName);
             if (objective == null) return Value.NULL;
             if (lv.size()==1)
-                return ListValue.wrap(scoreboard.getPlayerScores(objective).stream().map(s -> new StringValue(s.getOwner())).collect(Collectors.toList()));
+                return ListValue.wrap(scoreboard.getPlayerScores(objective).stream().map(s -> new StringValue(s.getOwner())));
             String key = getScoreboardKeyFromValue(lv.get(1));
             if(lv.size()==2)
             {
@@ -246,11 +245,11 @@ public static void apply(Expression expression)
             CarpetContext cc = (CarpetContext)c;
             ServerScoreboard scoreboard = cc.server().getScoreboard();
             if(lv.size() == 0)
-                return ListValue.wrap(scoreboard.getTeamNames().stream().map(StringValue::of).collect(Collectors.toList()));
+                return ListValue.wrap(scoreboard.getTeamNames().stream().map(StringValue::of));
             if (lv.size() != 1) return Value.NULL;
             PlayerTeam team = scoreboard.getPlayerTeam(lv.get(0).getString());
             if(team == null) return Value.NULL;
-            return ListValue.wrap(team.getPlayers().stream().map(StringValue::of).collect(Collectors.toList()));
+            return ListValue.wrap(team.getPlayers().stream().map(StringValue::of));
         });
 
 
@@ -398,7 +397,7 @@ public static void apply(Expression expression)
             CustomBossEvents bossBarManager = ((CarpetContext)c).server().getCustomBossEvents();
             if(lv.size() > 3) throw new InternalExpressionException("'bossbar' accepts max three arguments");
 
-            if(lv.size() == 0) return ListValue.wrap(bossBarManager.getEvents().stream().map(CustomBossEvent::getTextId).map(ResourceLocation::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));
 
             String id = lv.get(0).getString();
             ResourceLocation identifier;
@@ -458,7 +457,7 @@ public static void apply(Expression expression)
                     }
                     return Value.FALSE;
                 case "players":
-                    if (propertyValue == null) return ListValue.wrap(bossBar.getPlayers().stream().map(EntityValue::new).collect(Collectors.toList()));
+                    if (propertyValue == null) return ListValue.wrap(bossBar.getPlayers().stream().map(EntityValue::new));
                     if(propertyValue instanceof ListValue)
                     {
                         bossBar.removeAllPlayers();
diff --git a/src/main/java/carpet/script/api/WorldAccess.java b/src/main/java/carpet/script/api/WorldAccess.java
index cc9a546f3d..2f6768fb4f 100644
--- a/src/main/java/carpet/script/api/WorldAccess.java
+++ b/src/main/java/carpet/script/api/WorldAccess.java
@@ -44,7 +44,6 @@
 import net.minecraft.core.HolderSet;
 import net.minecraft.core.QuartPos;
 import net.minecraft.core.Registry;
-import net.minecraft.core.registries.BuiltInRegistries;
 import net.minecraft.core.registries.Registries;
 import net.minecraft.resources.ResourceKey;
 import net.minecraft.tags.TagKey;
@@ -342,7 +341,7 @@ else if (!("any".equals(statusString)))
                             new NumericValue(p.getPoiType().value().maxTickets() - ((PoiRecord_scarpetMixin)p).getFreeTickets()),
                             ValueConversions.of(p.getPos())
                     )
-            ).collect(Collectors.toList()));
+            ));
         });
 
         //poi_set(pos, null) poi_set(pos, type, occupied?,
@@ -1104,7 +1103,7 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin
             BlockState state = locator.block.getBlockState();
             StateDefinition states = state.getBlock().getStateDefinition();
             return ListValue.wrap(states.getProperties().stream().map(
-                    p -> new StringValue(p.getName())).collect(Collectors.toList())
+                    p -> new StringValue(p.getName()))
             );
         });
 
@@ -1136,12 +1135,12 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin
             CarpetContext cc = (CarpetContext)c;
             Registry blocks = cc.registry(Registries.BLOCK);
             if (lv.size() == 0)
-                return ListValue.wrap(blocks.keySet().stream().map(ValueConversions::of).collect(Collectors.toList()));
+                return ListValue.wrap(blocks.keySet().stream().map(ValueConversions::of));
             ResourceLocation tag = InputValidator.identifierOf(lv.get(0).getString());
 
             Optional> tagset = blocks.getTag(TagKey.create(Registries.BLOCK, tag));
             if (tagset.isEmpty()) return Value.NULL;
-            return ListValue.wrap(tagset.get().stream().map(b -> ValueConversions.of(blocks.getKey(b.value()))).collect(Collectors.toList()));
+            return ListValue.wrap(tagset.get().stream().map(b -> ValueConversions.of(blocks.getKey(b.value()))));
         });
 
         expression.addContextFunction("block_tags", -1, (c, t, lv) ->
@@ -1149,12 +1148,12 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin
             CarpetContext cc = (CarpetContext)c;
             Registry blocks = cc.registry(Registries.BLOCK);
             if (lv.size() == 0)
-                return ListValue.wrap(blocks.getTagNames().map(ValueConversions::of).collect(Collectors.toList()));
+                return ListValue.wrap(blocks.getTagNames().map(ValueConversions::of));
             BlockArgument blockLocator = BlockArgument.findIn(cc, lv, 0, true);
             if (blockLocator.offset == lv.size())
             {
                 Block target = blockLocator.block.getBlockState().getBlock();
-                return ListValue.wrap( blocks.getTags().filter(e -> e.getSecond().stream().anyMatch(h -> (h.value() == target))).map(e -> ValueConversions.of(e.getFirst())).collect(Collectors.toList()));
+                return ListValue.wrap( blocks.getTags().filter(e -> e.getSecond().stream().anyMatch(h -> (h.value() == target))).map(e -> ValueConversions.of(e.getFirst())));
             }
             String tag = lv.get(blockLocator.offset).getString();
             Optional> tagSet = blocks.getTag(TagKey.create(Registries.BLOCK, InputValidator.identifierOf(tag)));
@@ -1165,12 +1164,12 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin
             /* before
             TagContainer tagManager = cc.s.getServer().getTags();
             if (lv.size() == 0)
-                return ListValue.wrap(tagManager.getOrEmpty(Registry.BLOCK_REGISTRY).getAvailableTags().stream().map(ValueConversions::of).collect(Collectors.toList()));
+                return ListValue.wrap(tagManager.getOrEmpty(Registry.BLOCK_REGISTRY).getAvailableTags().stream().map(ValueConversions::of));
             BlockArgument blockLocator = BlockArgument.findIn(cc, lv, 0, true);
             if (blockLocator.offset == lv.size())
             {
                 Block target = blockLocator.block.getBlockState().getBlock();
-                return ListValue.wrap(tagManager.getOrEmpty(Registry.BLOCK_REGISTRY).getAllTags().entrySet().stream().filter(e -> e.getValue().contains(target)).map(e -> ValueConversions.of(e.getKey())).collect(Collectors.toList()));
+                return ListValue.wrap(tagManager.getOrEmpty(Registry.BLOCK_REGISTRY).getAllTags().entrySet().stream().filter(e -> e.getValue().contains(target)).map(e -> ValueConversions.of(e.getKey())));
             }
             String tag = lv.get(blockLocator.offset).getString();
             net.minecraft.tags.Tag blockTag = tagManager.getOrEmpty(Registry.BLOCK_REGISTRY).getTag(InputValidator.identifierOf(tag));
@@ -1303,7 +1302,7 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin
             if (lv.size() == locator.offset)
                 return ListValue.wrap(references.entrySet().stream().
                         filter(e -> e.getValue()!= null && !e.getValue().isEmpty()).
-                        map(e -> new StringValue(NBTSerializableValue.nameFromRegistryId(reg.getKey(e.getKey())))).collect(Collectors.toList())
+                        map(e -> new StringValue(NBTSerializableValue.nameFromRegistryId(reg.getKey(e.getKey()))))
                 );
             String simpleStructureName = lv.get(locator.offset).getString().toLowerCase(Locale.ROOT);
             Structure structureName = reg.get(InputValidator.identifierOf(simpleStructureName));
@@ -1313,7 +1312,7 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin
             return ListValue.wrap(structureReferences.longStream().mapToObj(l -> ListValue.of(
                     new NumericValue(16*ChunkPos.getX(l)),
                     Value.ZERO,
-                    new NumericValue(16*ChunkPos.getZ(l)))).collect(Collectors.toList()));
+                    new NumericValue(16*ChunkPos.getZ(l)))));
         });
 
         expression.addContextFunction("structure_eligibility", -1, (c, t, lv) ->
diff --git a/src/main/java/carpet/script/command/CommandArgument.java b/src/main/java/carpet/script/command/CommandArgument.java
index 280e10e93d..5fcd34ba24 100644
--- a/src/main/java/carpet/script/command/CommandArgument.java
+++ b/src/main/java/carpet/script/command/CommandArgument.java
@@ -2,7 +2,6 @@
 
 import carpet.CarpetServer;
 import carpet.fakes.BlockStateArgumentInterface;
-import carpet.script.CarpetContext;
 import carpet.script.CarpetScriptHost;
 import carpet.script.argument.FunctionArgument;
 import carpet.script.value.BlockValue;
@@ -96,7 +95,6 @@
 import net.minecraft.core.Holder;
 import net.minecraft.core.HolderSet;
 import net.minecraft.core.Registry;
-import net.minecraft.core.registries.BuiltInRegistries;
 import net.minecraft.core.registries.Registries;
 import net.minecraft.network.chat.Component;
 import net.minecraft.resources.ResourceKey;
@@ -613,7 +611,7 @@ protected ArgumentType getArgumentType(CarpetScriptHost host)
         protected Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException
         {
             Collection founds = net.minecraft.commands.arguments.EntityArgument.getOptionalEntities(context, param);
-            if (!single) return ListValue.wrap(founds.stream().map(EntityValue::new).collect(Collectors.toList()));
+            if (!single) return ListValue.wrap(founds.stream().map(EntityValue::new));
             if (founds.size() == 0) return Value.NULL;
             if (founds.size() == 1) return new EntityValue(founds.iterator().next());
             throw new SimpleCommandExceptionType(Component.literal("Multiple entities returned while only one was requested"+" for custom type "+suffix)).create();
@@ -653,7 +651,7 @@ protected ArgumentType getArgumentType(CarpetScriptHost host)
         protected Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException
         {
             Collection profiles = GameProfileArgument.getGameProfiles(context, param);
-            if (!single) return ListValue.wrap(profiles.stream().map(p -> StringValue.of(p.getName())).collect(Collectors.toList()));
+            if (!single) return ListValue.wrap(profiles.stream().map(p -> StringValue.of(p.getName())));
             int size = profiles.size();
             if (size == 0) return Value.NULL;
             if (size == 1) return StringValue.of(profiles.iterator().next().getName());
@@ -694,7 +692,7 @@ protected ArgumentType getArgumentType(CarpetScriptHost host)
         protected Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException
         {
             Collection holders = ScoreHolderArgument.getNames(context, param);
-            if (!single) return ListValue.wrap(holders.stream().map(StringValue::of).collect(Collectors.toList()));
+            if (!single) return ListValue.wrap(holders.stream().map(StringValue::of));
             int size = holders.size();
             if (size == 0) return Value.NULL;
             if (size == 1) return StringValue.of(holders.iterator().next());
diff --git a/src/main/java/carpet/script/language/ControlFlow.java b/src/main/java/carpet/script/language/ControlFlow.java
index d118a5149a..21fa410638 100644
--- a/src/main/java/carpet/script/language/ControlFlow.java
+++ b/src/main/java/carpet/script/language/ControlFlow.java
@@ -112,7 +112,7 @@ public static void apply(Expression expression) // public just to get the javado
                                 StringValue.of(f.getString()),
                                 NumericValue.of(f.getToken().lineno+1),
                                 NumericValue.of(f.getToken().linepos+1)
-                        )).collect(Collectors.toList())),
+                        ))),
 
                         StringValue.of("locals"), MapValue.wrap(ret.context.variables.entrySet().stream().filter(e -> !e.getKey().equals("_trace")).collect(Collectors.toMap(
                                 e -> StringValue.of(e.getKey()),
diff --git a/src/main/java/carpet/script/language/DataStructures.java b/src/main/java/carpet/script/language/DataStructures.java
index 81a1c393c9..1b9ed5e488 100644
--- a/src/main/java/carpet/script/language/DataStructures.java
+++ b/src/main/java/carpet/script/language/DataStructures.java
@@ -17,7 +17,6 @@
 import carpet.script.value.StringValue;
 import carpet.script.value.Value;
 import com.google.gson.JsonParseException;
-import com.google.gson.JsonParser;
 
 import java.nio.charset.StandardCharsets;
 import java.util.ArrayList;
@@ -186,7 +185,7 @@ else if (lv.size() == 2)
             if (v instanceof MapValue)
                 return ListValue.wrap(((MapValue) v).getMap().entrySet().stream().map(
                         (p) -> ListValue.of(p.getKey(), p.getValue())
-                ).collect(Collectors.toList()));
+                ));
             return Value.NULL;
         });
 
diff --git a/src/main/java/carpet/script/language/Functions.java b/src/main/java/carpet/script/language/Functions.java
index 7765d77779..28953ed776 100644
--- a/src/main/java/carpet/script/language/Functions.java
+++ b/src/main/java/carpet/script/language/Functions.java
@@ -18,7 +18,6 @@
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Locale;
-import java.util.stream.Collectors;
 
 public class Functions {
     public static void apply(Expression expression) // public just to get the javadoc right
@@ -31,10 +30,10 @@ public static void apply(Expression expression) // public just to get the javado
             c.host.importModule(c, moduleName);
             moduleName = moduleName.toLowerCase(Locale.ROOT);
             if (lv.size() > 1)
-                c.host.importNames(c, expression.module, moduleName, lv.subList(1, lv.size()).stream().map(Value::getString).collect(Collectors.toList()));
+                c.host.importNames(c, expression.module, moduleName, lv.subList(1, lv.size()).stream().map(Value::getString).toList());
             if (t == Context.VOID)
                 return Value.NULL;
-            return ListValue.wrap(c.host.availableImports(moduleName).map(StringValue::new).collect(Collectors.toList()));
+            return ListValue.wrap(c.host.availableImports(moduleName).map(StringValue::new));
         });
 
 
diff --git a/src/main/java/carpet/script/utils/BiomeInfo.java b/src/main/java/carpet/script/utils/BiomeInfo.java
index 69b448893a..f36054a1a6 100644
--- a/src/main/java/carpet/script/utils/BiomeInfo.java
+++ b/src/main/java/carpet/script/utils/BiomeInfo.java
@@ -10,7 +10,6 @@
 import java.util.Locale;
 import java.util.Map;
 import java.util.function.BiFunction;
-import java.util.stream.Collectors;
 
 import net.minecraft.core.BlockPos;
 import net.minecraft.core.Registry;
@@ -25,7 +24,7 @@ public class BiomeInfo
         //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(Biome.getBiomeCategory(Holder.direct(b)).getName()));
-        put("tags", (w, b) -> ListValue.wrap(w.registryAccess().registryOrThrow(Registries.BIOME).getTags().filter(p -> p.getSecond().stream().anyMatch(h -> h.value() == b)).map(p -> p.getFirst().location()).map(ValueConversions::of).collect(Collectors.toList())));
+        put("tags", (w, b) -> ListValue.wrap(w.registryAccess().registryOrThrow(Registries.BIOME).getTags().filter(p -> p.getSecond().stream().anyMatch(h -> h.value() == b)).map(p -> p.getFirst().location()).map(ValueConversions::of)));
 
         put("temperature", (w, b) -> NumericValue.of(b.getBaseTemperature()));
         put("fog_color", (w, b) -> ValueConversions.ofRGB(b.getSpecialEffects().getFogColor()));
diff --git a/src/main/java/carpet/script/utils/SystemInfo.java b/src/main/java/carpet/script/utils/SystemInfo.java
index e5112a1c04..9939085392 100644
--- a/src/main/java/carpet/script/utils/SystemInfo.java
+++ b/src/main/java/carpet/script/utils/SystemInfo.java
@@ -35,18 +35,17 @@
 import java.util.Map;
 import java.util.Objects;
 import java.util.function.Function;
-import java.util.stream.Collectors;
 
 public class SystemInfo {
-    private static final Map> options = new HashMap>(){{
+    private static final Map> options = new HashMap<>(){{
         put("app_name", c ->
         {
             String name = c.host.getName();
             return name == null?Value.NULL:new StringValue(name);
         });
-        put("app_list", c -> ListValue.wrap(((CarpetScriptHost)c.host).scriptServer().modules.keySet().stream().filter(Objects::nonNull).map(StringValue::new).collect(Collectors.toList())));
+        put("app_list", c -> ListValue.wrap(((CarpetScriptHost)c.host).scriptServer().modules.keySet().stream().filter(Objects::nonNull).map(StringValue::new)));
         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("app_players", c -> ListValue.wrap(c.host.getUserList().stream().map(StringValue::new)));
 
         put("world_name", c -> new StringValue(c.server().getWorldData().getLevelName()));
         put("world_seed", c -> new NumericValue(c.level().getSeed()));
@@ -59,7 +58,7 @@ public class SystemInfo {
             String tlf = serverPath.getName(nodeCount-2).toString();
             return StringValue.of(tlf);
         });
-        put("world_dimensions", c -> ListValue.wrap(c.server().levelKeys().stream().map(k -> ValueConversions.of(k.location())).collect(Collectors.toList())));
+        put("world_dimensions", c -> ListValue.wrap(c.server().levelKeys().stream().map(k -> ValueConversions.of(k.location()))));
         put("world_spawn_point", c -> {
             LevelData prop = c.server().overworld().getLevelData();
             return ListValue.of(NumericValue.of(prop.getXSpawn()), NumericValue.of(prop.getYSpawn()), NumericValue.of(prop.getZSpawn()));
@@ -143,7 +142,7 @@ public class SystemInfo {
             final long[] tickArray = c.server().tickTimes;
             for (int i=currentReportedTick+100; i > currentReportedTick; i--)
             {
-                ticks.add(new NumericValue(((double)tickArray[i % 100])/1000000.0));
+                ticks.add(new NumericValue((tickArray[i % 100])/1000000.0));
             }
             return ListValue.wrap(ticks);
         });
@@ -219,7 +218,7 @@ public static Value get(String what, CarpetContext cc)
     }
     public static Value getAll()
     {
-        return ListValue.wrap(options.keySet().stream().map(StringValue::of).collect(Collectors.toList()));
+        return ListValue.wrap(options.keySet().stream().map(StringValue::of));
     }
 
 }
diff --git a/src/main/java/carpet/script/value/EntityValue.java b/src/main/java/carpet/script/value/EntityValue.java
index ffc3d44ad7..037a918dac 100644
--- a/src/main/java/carpet/script/value/EntityValue.java
+++ b/src/main/java/carpet/script/value/EntityValue.java
@@ -456,16 +456,16 @@ public Value get(String what, Value arg)
         put("type", (e, a) -> new StringValue(nameFromRegistryId(e.getLevel().registryAccess().registryOrThrow(Registries.ENTITY_TYPE).getKey(e.getType()))));
         put("is_riding", (e, a) -> BooleanValue.of(e.isPassenger()));
         put("is_ridden", (e, a) -> BooleanValue.of(e.isVehicle()));
-        put("passengers", (e, a) -> ListValue.wrap(e.getPassengers().stream().map(EntityValue::new).collect(Collectors.toList())));
+        put("passengers", (e, a) -> ListValue.wrap(e.getPassengers().stream().map(EntityValue::new)));
         put("mount", (e, a) -> (e.getVehicle()!=null)?new EntityValue(e.getVehicle()):Value.NULL);
         put("unmountable", (e, a) -> BooleanValue.of(((EntityInterface)e).isPermanentVehicle()));
         // deprecated
-        put("tags", (e, a) -> ListValue.wrap(e.getTags().stream().map(StringValue::new).collect(Collectors.toList())));
+        put("tags", (e, a) -> ListValue.wrap(e.getTags().stream().map(StringValue::new)));
 
-        put("scoreboard_tags", (e, a) -> ListValue.wrap(e.getTags().stream().map(StringValue::new).collect(Collectors.toList())));
+        put("scoreboard_tags", (e, a) -> ListValue.wrap(e.getTags().stream().map(StringValue::new)));
         put("entity_tags", (e, a) -> {
             EntityType type = e.getType();
-            return ListValue.wrap(e.getServer().registryAccess().registryOrThrow(Registries.ENTITY_TYPE).getTags().filter(entry -> entry.getSecond().stream().anyMatch(h -> h.value()==type)).map(entry -> ValueConversions.of(entry.getFirst())).collect(Collectors.toList()));
+            return ListValue.wrap(e.getServer().registryAccess().registryOrThrow(Registries.ENTITY_TYPE).getTags().filter(entry -> entry.getSecond().stream().anyMatch(h -> h.value()==type)).map(entry -> ValueConversions.of(entry.getFirst())));
         });
         // deprecated
         put("has_tag", (e, a) -> BooleanValue.of(e.getTags().contains(a.getString())));
@@ -558,7 +558,7 @@ public Value get(String what, Value arg)
         put("home", (e, a) -> {
             if (e instanceof Mob)
             {
-                return (((Mob) e).getRestrictRadius () > 0)?new BlockValue(null, (ServerLevel) e.getCommandSenderWorld(), ((PathfinderMob) e).getRestrictCenter()):Value.FALSE;
+                return (((Mob) e).getRestrictRadius () > 0)?new BlockValue(null, e.getCommandSenderWorld(), ((PathfinderMob) e).getRestrictCenter()):Value.FALSE;
             }
             return Value.NULL;
         });
@@ -840,7 +840,7 @@ public Value get(String what, Value arg)
                 ServerPlayerInteractionManagerInterface manager = (ServerPlayerInteractionManagerInterface) (((ServerPlayer) e).gameMode);
                 BlockPos pos = manager.getCurrentBreakingBlock();
                 if (pos == null) return Value.NULL;
-                return new BlockValue(null, (ServerLevel) e.level, pos);
+                return new BlockValue(null, e.level, pos);
             }
             return Value.NULL;
         });
@@ -926,7 +926,7 @@ else if (entities)
             switch (hitres.getType())
             {
                 case MISS: return Value.NULL;
-                case BLOCK: return new BlockValue(null, (ServerLevel) e.getCommandSenderWorld(), ((BlockHitResult)hitres).getBlockPos() );
+                case BLOCK: return new BlockValue(null, e.getCommandSenderWorld(), ((BlockHitResult)hitres).getBlockPos() );
                 case ENTITY: return new EntityValue(((EntityHitResult)hitres).getEntity());
             }
             return Value.NULL;
diff --git a/src/main/java/carpet/script/value/NBTSerializableValue.java b/src/main/java/carpet/script/value/NBTSerializableValue.java
index d48721a8da..272f3fb1d9 100644
--- a/src/main/java/carpet/script/value/NBTSerializableValue.java
+++ b/src/main/java/carpet/script/value/NBTSerializableValue.java
@@ -17,7 +17,6 @@
 import java.util.function.Supplier;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
-import java.util.stream.Collectors;
 import net.minecraft.commands.arguments.NbtPathArgument;
 import net.minecraft.commands.arguments.item.ItemInput;
 import net.minecraft.commands.arguments.item.ItemParser;
@@ -609,7 +608,7 @@ public Value get(Value value)
                 return Value.NULL;
             if (tags.size()==1 && !valString.endsWith("[]"))
                 return NBTSerializableValue.decodeTag(tags.get(0));
-            return ListValue.wrap(tags.stream().map(NBTSerializableValue::decodeTag).collect(Collectors.toList()));
+            return ListValue.wrap(tags.stream().map(NBTSerializableValue::decodeTag));
         }
         catch (CommandSyntaxException ignored) { }
         return Value.NULL;
@@ -696,8 +695,7 @@ public Tag toTag(boolean force)
 
     public static class IncompatibleTypeException extends RuntimeException
     {
-        private IncompatibleTypeException() {}
-        public Value val;
+        public final Value val;
         public IncompatibleTypeException(Value val)
         {
             this.val = val;
diff --git a/src/main/java/carpet/script/value/Value.java b/src/main/java/carpet/script/value/Value.java
index a7d55e38c4..c2ed9544e7 100644
--- a/src/main/java/carpet/script/value/Value.java
+++ b/src/main/java/carpet/script/value/Value.java
@@ -10,7 +10,6 @@
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 import java.util.regex.PatternSyntaxException;
-import java.util.stream.Collectors;
 import net.minecraft.nbt.Tag;
 
 public abstract class Value implements Comparable, Cloneable
@@ -179,7 +178,7 @@ public Value split(Value delimiter)
         }
         try
         {
-            return ListValue.wrap(Arrays.stream(getString().split(delimiter.getString())).map(StringValue::new).collect(Collectors.toList()));
+            return ListValue.wrap(Arrays.stream(getString().split(delimiter.getString())).map(StringValue::new));
         }
         catch (PatternSyntaxException pse)
         {
diff --git a/src/main/java/carpet/script/value/ValueConversions.java b/src/main/java/carpet/script/value/ValueConversions.java
index 6b28bfd034..2535886d36 100644
--- a/src/main/java/carpet/script/value/ValueConversions.java
+++ b/src/main/java/carpet/script/value/ValueConversions.java
@@ -54,7 +54,6 @@
 import java.util.Set;
 import java.util.UUID;
 import java.util.function.Predicate;
-import java.util.stream.Collectors;
 import java.util.stream.StreamSupport;
 
 import com.mojang.brigadier.exceptions.CommandSyntaxException;
@@ -274,12 +273,12 @@ private static Value fromEntityMemory(Entity e, Object v)
         }
         if (v instanceof PositionTracker)
         {
-            return new BlockValue(null, (ServerLevel) e.getCommandSenderWorld(), ((PositionTracker)v).currentBlockPosition());
+            return new BlockValue(null, e.getCommandSenderWorld(), ((PositionTracker)v).currentBlockPosition());
         }
         if (v instanceof WalkTarget)
         {
             return ListValue.of(
-                    new BlockValue(null, (ServerLevel) e.getCommandSenderWorld(), ((WalkTarget)v).getTarget().currentBlockPosition()),
+                    new BlockValue(null, e.getCommandSenderWorld(), ((WalkTarget)v).getTarget().currentBlockPosition()),
                     new NumericValue(((WalkTarget) v).getSpeedModifier()),
                     new NumericValue(((WalkTarget) v).getCloseEnoughDist())
             );
@@ -297,11 +296,11 @@ private static Value fromEntityMemory(Entity e, Object v)
             Object el = l.get(0);
             if (el instanceof Entity)
             {
-                return ListValue.wrap(l.stream().map(o -> new EntityValue((Entity)o)).collect(Collectors.toList()));
+                return ListValue.wrap(l.stream().map(o -> new EntityValue((Entity)o)));
             }
             if (el instanceof GlobalPos)
             {
-                return ListValue.wrap(l.stream().map(o -> of((GlobalPos) o)).collect(Collectors.toList()));
+                return ListValue.wrap(l.stream().map(o -> of((GlobalPos) o)));
             }
         }
         return Value.NULL;
@@ -480,7 +479,7 @@ public static Value guess(ServerLevel serverWorld, Object o) {
         if (o == null)
             return Value.NULL;
         if (o instanceof List)
-            return ListValue.wrap(((List) o).stream().map(oo -> guess(serverWorld, oo)).collect(Collectors.toList()));
+            return ListValue.wrap(((List) o).stream().map(oo -> guess(serverWorld, oo)));
         if (o instanceof BlockPos)
             return new BlockValue(null, serverWorld, (BlockPos)o);
         if (o instanceof Entity)

From 3050a82b96760a00dc30b872ef06fd5e5a33596b Mon Sep 17 00:00:00 2001
From: altrisi 
Date: Thu, 19 Jan 2023 01:46:54 +0100
Subject: [PATCH 013/233] Replace one missed usage

It was also using the copy-constructor, so this way it should also be more efficient
---
 src/main/java/carpet/script/CarpetEventServer.java | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/src/main/java/carpet/script/CarpetEventServer.java b/src/main/java/carpet/script/CarpetEventServer.java
index 01ebfe990e..3c84663de0 100644
--- a/src/main/java/carpet/script/CarpetEventServer.java
+++ b/src/main/java/carpet/script/CarpetEventServer.java
@@ -1018,10 +1018,10 @@ public void onExplosion(ServerLevel world, Entity e,  Supplier att
                                 EntityValue.of(attacker!= null?attacker.get():Event.getExplosionCausingEntity(e)),
                                 StringValue.of(type.name().toLowerCase(Locale.ROOT)),
                                 BooleanValue.of(createFire),
-                                new ListValue(affectedBlocks.stream().filter(b -> !world.isEmptyBlock(b)). map( // da heck they send air blocks
+                                ListValue.wrap(affectedBlocks.stream().filter(b -> !world.isEmptyBlock(b)). map( // da heck they send air blocks
                                         b -> new BlockValue(world.getBlockState(b),world,b)
-                                ).collect(Collectors.toList())),
-                                new ListValue(affectedEntities.stream().map(EntityValue::of).collect(Collectors.toList()))
+                                )),
+                                ListValue.wrap(affectedEntities.stream().map(EntityValue::of))
                         ), () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel(world)
                 );
             }

From 914e129f6e7832b2aaa21681e99baad7d6ea4a94 Mon Sep 17 00:00:00 2001
From: altrisi 
Date: Fri, 20 Jan 2023 13:56:16 +0100
Subject: [PATCH 014/233] Merge particle caches (#1528)

* Merge particle caches

* Reset this cache on world reload
---
 src/main/java/carpet/CarpetServer.java        |  2 ++
 .../java/carpet/helpers/ParticleDisplay.java  | 33 ++++++++++---------
 .../carpet/script/utils/ShapeDispatcher.java  | 21 +++---------
 3 files changed, 25 insertions(+), 31 deletions(-)

diff --git a/src/main/java/carpet/CarpetServer.java b/src/main/java/carpet/CarpetServer.java
index d63c27e507..930ddff62b 100644
--- a/src/main/java/carpet/CarpetServer.java
+++ b/src/main/java/carpet/CarpetServer.java
@@ -20,6 +20,7 @@
 import carpet.commands.TickCommand;
 import carpet.network.ServerNetworkHandler;
 import carpet.helpers.HopperCounter;
+import carpet.helpers.ParticleDisplay;
 import carpet.helpers.TickSpeed;
 import carpet.logging.LoggerRegistry;
 import carpet.script.CarpetScriptServer;
@@ -194,6 +195,7 @@ public static void onServerClosed(MinecraftServer server)
 
             LoggerRegistry.stopLoggers();
             HUDController.resetScarpetHUDs();
+            ParticleDisplay.resetCache();
             extensions.forEach(e -> e.onServerClosed(server));
             minecraft_server = null;
         }
diff --git a/src/main/java/carpet/helpers/ParticleDisplay.java b/src/main/java/carpet/helpers/ParticleDisplay.java
index 5cc0b5db61..086a8c2381 100644
--- a/src/main/java/carpet/helpers/ParticleDisplay.java
+++ b/src/main/java/carpet/helpers/ParticleDisplay.java
@@ -5,42 +5,45 @@
 import java.util.HashMap;
 import java.util.Map;
 import net.minecraft.commands.arguments.ParticleArgument;
+import net.minecraft.core.HolderLookup;
 import net.minecraft.core.particles.ParticleOptions;
+import net.minecraft.core.particles.ParticleType;
 import net.minecraft.core.registries.Registries;
-import net.minecraft.server.level.ServerLevel;
 import net.minecraft.server.level.ServerPlayer;
 import net.minecraft.world.phys.Vec3;
 
 public class ParticleDisplay
 {
-    private static Map particleCache = new HashMap<>();
+    private static final Map particleCache = new HashMap<>(); // we reset this on reloads, but probably need something better
 
-    private static ParticleOptions parseParticle(String name, ServerLevel level)  // [SCARY SHIT] persistent caches over server reloads
+    private static ParticleOptions parseParticle(String name, HolderLookup> lookup)
     {
         try
         {
-            return ParticleArgument.readParticle(new StringReader(name), level.holderLookup(Registries.PARTICLE_TYPE));
+            return ParticleArgument.readParticle(new StringReader(name), lookup);
         }
         catch (CommandSyntaxException e)
         {
-            throw new RuntimeException("No such particle: "+name);
+            throw new IllegalArgumentException("No such particle: " + name);
         }
     }
-    public static ParticleOptions getEffect(String name, ServerLevel level)
+    public static ParticleOptions getEffect(String name, HolderLookup> lookup)
     {
         if (name == null) return null;
-        ParticleOptions res = particleCache.get(name);
-        if (res != null) return res;
-        particleCache.put(name, parseParticle(name, level));
-        return particleCache.get(name);
+        return particleCache.computeIfAbsent(name, particle -> parseParticle(particle, lookup));
+    }
+
+    public static void resetCache() {
+        particleCache.clear();
     }
 
     public static void drawParticleLine(ServerPlayer player, Vec3 from, Vec3 to, String main, String accent, int count, double spread)
     {
-        ParticleOptions accentParticle = getEffect(accent, player.getLevel());
-        ParticleOptions mainParticle = getEffect(main, player.getLevel());
+        HolderLookup> lookup = player.getLevel().holderLookup(Registries.PARTICLE_TYPE);
+        ParticleOptions accentParticle = getEffect(accent, lookup);
+        ParticleOptions mainParticle = getEffect(main, lookup);
 
-        if (accentParticle != null) ((ServerLevel)player.level).sendParticles(
+        if (accentParticle != null) player.getLevel().sendParticles(
                 player,
                 accentParticle,
                 true,
@@ -52,10 +55,10 @@ public static void drawParticleLine(ServerPlayer player, Vec3 from, Vec3 to, Str
 
         Vec3 incvec = to.subtract(from).normalize();//    multiply(50/sqrt(lineLengthSq));
         for (Vec3 delta = new Vec3(0.0,0.0,0.0);
-             delta.lengthSqr() particleCache = new HashMap<>();
     public static record ShapeWithConfig(ExpiringShape shape, Map config) {}
 
     public static ShapeWithConfig fromFunctionArgs(
@@ -177,19 +171,14 @@ public static void sendShape(Collection players, List parseParams(List items)
@@ -261,7 +250,7 @@ public static ExpiringShape fromTag(CompoundTag tag, Level level)
 
     public abstract static class ExpiringShape
     {
-        public static final Map, RegistryAccess, ExpiringShape>> shapeProviders = new HashMap, RegistryAccess, ExpiringShape>>(){{
+        public static final Map, RegistryAccess, ExpiringShape>> shapeProviders = new HashMap<>(){{
             put("line", creator(Line::new));
             put("box", creator(Box::new));
             put("sphere", creator(Sphere::new));
@@ -1200,7 +1189,7 @@ public static abstract class Param
                     "GROUND",
                     "FIXED")
                     {
-                        public Value validate(Map o, MinecraftServer s, Value v)
+                        public Value validate(Map o, MinecraftServer s, Value v)
                         {
                             return super.validate(o, s ,new StringValue(v.getString().toUpperCase(Locale.ROOT)));
                         }

From 811b330446ddc5e7f98996593fd205a82a0fa445 Mon Sep 17 00:00:00 2001
From: Ghoulboy 
Date: Fri, 20 Jan 2023 14:01:37 +0100
Subject: [PATCH 015/233] Adding system_info('world_min_spawning_light')
 (#1475)

---
 docs/scarpet/api/Auxiliary.md                     | 3 ++-
 src/main/java/carpet/script/utils/SystemInfo.java | 1 +
 2 files changed, 3 insertions(+), 1 deletion(-)

diff --git a/docs/scarpet/api/Auxiliary.md b/docs/scarpet/api/Auxiliary.md
index 1b05a90b26..d9589c9974 100644
--- a/docs/scarpet/api/Auxiliary.md
+++ b/docs/scarpet/api/Auxiliary.md
@@ -753,7 +753,8 @@ system calls. In all circumstances, these are only provided as read-only.
   * `world_center` - Returns coordinates of the center of the world with respect of the world border
   * `world_size` - Returns radius of world border for current dimension.
   * `world_max_size` - Returns maximum possible radius of world border for current dimension.
-  * 
+  * `world_min_spawning_light` - Returns minimum light level at which mobs can spawn for current dimension, taking into account datapacks
+
 ##### Relevant gameplay related properties
   * `game_difficulty` - current difficulty of the game: `'peaceful'`, `'easy'`, `'normal'`, or `'hard'`
   * `game_hardcore` - boolean whether the game is in hardcore mode
diff --git a/src/main/java/carpet/script/utils/SystemInfo.java b/src/main/java/carpet/script/utils/SystemInfo.java
index 9939085392..8022477cbf 100644
--- a/src/main/java/carpet/script/utils/SystemInfo.java
+++ b/src/main/java/carpet/script/utils/SystemInfo.java
@@ -200,6 +200,7 @@ public > void visit(GameRules.Key key, GameRules
             });
             return MapValue.wrap(rules);
         });
+        put("world_min_spawning_light", c-> NumericValue.of(c.s.getLevel().dimensionType().monsterSpawnBlockLightLimit()));
 
         put("source_entity", c -> EntityValue.of(c.source().getEntity()));
         put("source_position", c -> ValueConversions.of(c.source().getPosition()));

From d9a4a62f7cdc012888ebe8a0430c01f8393effae Mon Sep 17 00:00:00 2001
From: altrisi 
Date: Fri, 20 Jan 2023 14:34:45 +0100
Subject: [PATCH 016/233] Fix NPE in a validator from registry access refactor

---
 src/main/java/carpet/CarpetSettings.java | 1 +
 1 file changed, 1 insertion(+)

diff --git a/src/main/java/carpet/CarpetSettings.java b/src/main/java/carpet/CarpetSettings.java
index e8ffeabc38..f52fa3b390 100644
--- a/src/main/java/carpet/CarpetSettings.java
+++ b/src/main/java/carpet/CarpetSettings.java
@@ -977,6 +977,7 @@ public static class StructureBlockIgnoredValidator extends Validator {
 
         @Override
         public String validate(CommandSourceStack source, CarpetRule currentRule, String newValue, String string) {
+            if (source == null) return newValue; // closing or sync
             Optional ignoredBlock = source.registryAccess().registryOrThrow(Registries.BLOCK).getOptional(ResourceLocation.tryParse(newValue));
             if (!ignoredBlock.isPresent()) {
                 Messenger.m(source, "r Unknown block '" + newValue + "'.");

From 58a68739c5b00932898898301a811a4ec8f5d1eb Mon Sep 17 00:00:00 2001
From: altrisi 
Date: Fri, 20 Jan 2023 14:41:31 +0100
Subject: [PATCH 017/233] Annotate `source` in `Validator` with `@Nullable`

Using it without a check happens too many times
---
 src/main/java/carpet/api/settings/Validator.java | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/src/main/java/carpet/api/settings/Validator.java b/src/main/java/carpet/api/settings/Validator.java
index 62c680a421..1ddc78c1b4 100644
--- a/src/main/java/carpet/api/settings/Validator.java
+++ b/src/main/java/carpet/api/settings/Validator.java
@@ -1,5 +1,7 @@
 package carpet.api.settings;
 
+import org.jetbrains.annotations.Nullable;
+
 import carpet.utils.Messenger;
 import net.minecraft.commands.CommandSourceStack;
 
@@ -35,7 +37,7 @@ public abstract class Validator
      * @return The new value to set the rule to instead, can return the {@code newValue} if the given value is correct.
      *         Returns {@code null} if the given value is not correct.
      */
-    public abstract T validate(CommandSourceStack source, CarpetRule changingRule, T newValue, String userInput);
+    public abstract T validate(@Nullable CommandSourceStack source, CarpetRule changingRule, T newValue, String userInput);
 
     /**
      * @return A description of this {@link Validator}. It is used in the default {@link #notifyFailure(CommandSourceStack, CarpetRule, String)}

From bc5ece085c5d321d1f3378f00b9981c77ff37235 Mon Sep 17 00:00:00 2001
From: Ghoulboy 
Date: Fri, 20 Jan 2023 18:07:44 +0100
Subject: [PATCH 018/233] Added `thickHugeFungusGrowthFix` rule (#1458)

---
 src/main/java/carpet/CarpetSettings.java      | 10 ++++++++
 .../carpet/mixins/HugeFungusFeatureMixin.java | 24 +++++++++++++++++++
 src/main/resources/carpet.mixins.json         |  1 +
 3 files changed, 35 insertions(+)
 create mode 100644 src/main/java/carpet/mixins/HugeFungusFeatureMixin.java

diff --git a/src/main/java/carpet/CarpetSettings.java b/src/main/java/carpet/CarpetSettings.java
index f52fa3b390..3fe4c006f0 100644
--- a/src/main/java/carpet/CarpetSettings.java
+++ b/src/main/java/carpet/CarpetSettings.java
@@ -1051,4 +1051,14 @@ public String description() {
     )
     public static int sculkSensorRange = 8;
 
+    public enum FungusFixMode {
+        FALSE, VANILLA, ALL;
+    }
+
+    @Rule(
+            desc = "Allows to grow nether trees with 3x3 base with bonemeal",
+            extra = {"Setting to 'all' will make all nether fungi grow into 3x3 trees", "Setting to 'vanilla' will make 6% of all nether fungi grow into 3x3 trees", "(this being consistent with worldgen)", "Fixes [MC-215169](https://bugs.mojang.com/browse/MC-215169)."},
+            category = {SURVIVAL, BUGFIX}
+    )
+    public static FungusFixMode thickHugeFungusGrowthFix = FungusFixMode.FALSE;
 }
diff --git a/src/main/java/carpet/mixins/HugeFungusFeatureMixin.java b/src/main/java/carpet/mixins/HugeFungusFeatureMixin.java
new file mode 100644
index 0000000000..3fb870cdd4
--- /dev/null
+++ b/src/main/java/carpet/mixins/HugeFungusFeatureMixin.java
@@ -0,0 +1,24 @@
+package carpet.mixins;
+
+import carpet.CarpetSettings;
+import net.minecraft.util.RandomSource;
+import net.minecraft.world.level.levelgen.feature.HugeFungusConfiguration;
+import net.minecraft.world.level.levelgen.feature.HugeFungusFeature;
+import org.spongepowered.asm.mixin.Mixin;
+import org.spongepowered.asm.mixin.injection.At;
+import org.spongepowered.asm.mixin.injection.ModifyArgs;
+import org.spongepowered.asm.mixin.injection.invoke.arg.Args;
+
+import static carpet.CarpetSettings.FungusFixMode.*;
+
+@Mixin(HugeFungusFeature.class)
+public class HugeFungusFeatureMixin {
+    @ModifyArgs(method = "place", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/levelgen/feature/HugeFungusFeature;placeStem(Lnet/minecraft/world/level/LevelAccessor;Lnet/minecraft/util/RandomSource;Lnet/minecraft/world/level/levelgen/feature/HugeFungusConfiguration;Lnet/minecraft/core/BlockPos;IZ)V"))
+    private void mixin(Args args) {
+        boolean natural = !((HugeFungusConfiguration) args.get(2)).planted;
+        args.set(5, natural && ((boolean) args.get(5)) ||
+            !natural && (CarpetSettings.thickHugeFungusGrowthFix.equals(ALL) ||
+            CarpetSettings.thickHugeFungusGrowthFix.equals(VANILLA) && ((RandomSource) args.get(1)).nextFloat() < 0.06F)
+        );
+    }
+}
diff --git a/src/main/resources/carpet.mixins.json b/src/main/resources/carpet.mixins.json
index ddc27dbb4b..a963ad4fd0 100644
--- a/src/main/resources/carpet.mixins.json
+++ b/src/main/resources/carpet.mixins.json
@@ -26,6 +26,7 @@
     "FlowingFluid_liquidDamageDisabledMixin",
     "ServerStatus_motdMixin",
     "MinecraftServer_pingPlayerSampleLimit",
+    "HugeFungusFeatureMixin",
 
     "MinecraftServer_coreMixin",
 

From 583a372ba4f78fc74af9170fbafb6702b74e4f5d Mon Sep 17 00:00:00 2001
From: altrisi 
Date: Fri, 20 Jan 2023 18:09:15 +0100
Subject: [PATCH 019/233] Migrate `Context` usage from recently merged PR

---
 src/main/java/carpet/script/utils/SystemInfo.java | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/main/java/carpet/script/utils/SystemInfo.java b/src/main/java/carpet/script/utils/SystemInfo.java
index 8022477cbf..02cb4ebc2e 100644
--- a/src/main/java/carpet/script/utils/SystemInfo.java
+++ b/src/main/java/carpet/script/utils/SystemInfo.java
@@ -200,7 +200,7 @@ public > void visit(GameRules.Key key, GameRules
             });
             return MapValue.wrap(rules);
         });
-        put("world_min_spawning_light", c-> NumericValue.of(c.s.getLevel().dimensionType().monsterSpawnBlockLightLimit()));
+        put("world_min_spawning_light", c-> NumericValue.of(c.level().dimensionType().monsterSpawnBlockLightLimit()));
 
         put("source_entity", c -> EntityValue.of(c.source().getEntity()));
         put("source_position", c -> ValueConversions.of(c.source().getPosition()));

From 1f38a2e89c541abc239d8666ef01edf0140a659c Mon Sep 17 00:00:00 2001
From: altrisi 
Date: Fri, 20 Jan 2023 18:27:16 +0100
Subject: [PATCH 020/233] Remove `leadFix` rule

It's been fixed for ages, and the only code we still add is already in vanilla
---
 src/main/java/carpet/CarpetSettings.java      |  7 ----
 .../mixins/ServerEntity_leashFixMixin.java    | 34 -------------------
 src/main/resources/carpet.mixins.json         |  1 -
 3 files changed, 42 deletions(-)
 delete mode 100644 src/main/java/carpet/mixins/ServerEntity_leashFixMixin.java

diff --git a/src/main/java/carpet/CarpetSettings.java b/src/main/java/carpet/CarpetSettings.java
index 3fe4c006f0..e10f72cf58 100644
--- a/src/main/java/carpet/CarpetSettings.java
+++ b/src/main/java/carpet/CarpetSettings.java
@@ -864,13 +864,6 @@ public enum RenewableCoralMode {
     @Rule(desc = "fixes block placement rotation issue when player rotates quickly while placing blocks", category = RuleCategory.BUGFIX)
     public static boolean placementRotationFix = false;
 
-    @Rule(
-            desc = "Fixes leads breaking/becoming invisible in unloaded chunks",
-            extra = "You may still get visibly broken leash links on the client side, but server side the link is still there.",
-            category = RuleCategory.BUGFIX
-    )// needs checkfix for 1.15
-    public static boolean leadFix = false;
-
     @Rule(desc = "Spawning requires much less CPU and Memory", category = OPTIMIZATION)
     public static boolean lagFreeSpawning = false;
 
diff --git a/src/main/java/carpet/mixins/ServerEntity_leashFixMixin.java b/src/main/java/carpet/mixins/ServerEntity_leashFixMixin.java
deleted file mode 100644
index d2d7142391..0000000000
--- a/src/main/java/carpet/mixins/ServerEntity_leashFixMixin.java
+++ /dev/null
@@ -1,34 +0,0 @@
-package carpet.mixins;
-
-import carpet.CarpetSettings;
-import org.spongepowered.asm.mixin.Final;
-import org.spongepowered.asm.mixin.Mixin;
-import org.spongepowered.asm.mixin.Shadow;
-import org.spongepowered.asm.mixin.injection.At;
-import org.spongepowered.asm.mixin.injection.Inject;
-import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
-
-import java.util.function.Consumer;
-import net.minecraft.network.protocol.Packet;
-import net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket;
-import net.minecraft.server.level.ServerEntity;
-import net.minecraft.world.entity.Entity;
-import net.minecraft.world.entity.Mob;
-
-@Mixin(ServerEntity.class)
-public class ServerEntity_leashFixMixin
-{
-    @Shadow @Final private Entity entity;
-
-    @Inject(method = "sendPairingData", at = @At("RETURN"))
-    private void sendLeashPackets(Consumer> consumer_1, CallbackInfo ci)
-    {
-        if (CarpetSettings.leadFix)
-        {
-            if (entity instanceof Mob)
-            {
-                consumer_1.accept( new ClientboundSetEntityLinkPacket(entity, ((Mob) entity).getLeashHolder()));
-            }
-        }
-    }
-}
diff --git a/src/main/resources/carpet.mixins.json b/src/main/resources/carpet.mixins.json
index a963ad4fd0..13bd6b2394 100644
--- a/src/main/resources/carpet.mixins.json
+++ b/src/main/resources/carpet.mixins.json
@@ -54,7 +54,6 @@
     "ThreadedLevelLightEngine_scarpetChunkCreationMixin",
     "LivingEntity_cleanLogsMixin",
     "MobMixin",
-    "ServerEntity_leashFixMixin",
     "Villager_aiMixin",
     "Player_fakePlayersMixin",
     "ServerGamePacketListenerImpl_coreMixin",

From 1eb25ba1b54ea569f29e5e4bbff43ef73b64eb96 Mon Sep 17 00:00:00 2001
From: altrisi 
Date: Fri, 20 Jan 2023 18:53:26 +0100
Subject: [PATCH 021/233] Improve unexpected java exception in scarpet error
 slightly

---
 src/main/java/carpet/script/Expression.java | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/main/java/carpet/script/Expression.java b/src/main/java/carpet/script/Expression.java
index 3318393568..a498f22e1d 100644
--- a/src/main/java/carpet/script/Expression.java
+++ b/src/main/java/carpet/script/Expression.java
@@ -377,7 +377,7 @@ public static RuntimeException handleCodeException(Context c, RuntimeException e
             return exc;
         // unexpected really - should be caught earlier and converted to InternalExpressionException
         CarpetSettings.LOG.error("Unexpected exception while running Scarpet code", exc);
-        return new ExpressionException(c, e, token, "Error while evaluating expression: "+exc);
+        return new ExpressionException(c, e, token, "Internal error (please report this issue to Carpet) while evaluating: " + exc);
     }
 
     public void addUnaryOperator(String surface, boolean leftAssoc, Function fun)

From c9c1e5a4dc7f04300d6427cf1c9390b9ada82baa Mon Sep 17 00:00:00 2001
From: altrisi 
Date: Fri, 20 Jan 2023 19:00:47 +0100
Subject: [PATCH 022/233] Fix `undef` docs mentioning you can undef constant
 literals

Fuxes #1566
---
 docs/scarpet/language/SystemFunctions.md | 2 --
 1 file changed, 2 deletions(-)

diff --git a/docs/scarpet/language/SystemFunctions.md b/docs/scarpet/language/SystemFunctions.md
index 42caf30b9f..924dbce246 100644
--- a/docs/scarpet/language/SystemFunctions.md
+++ b/docs/scarpet/language/SystemFunctions.md
@@ -388,8 +388,6 @@ It can affect global variable pool, and local variable set for a particular func
 inc(i) -> i+1; foo = 5; inc(foo) => 6
 inc(i) -> i+1; foo = 5; undef('foo'); inc(foo) => 1
 inc(i) -> i+1; foo = 5; undef('inc'); undef('foo'); inc(foo) => Error: Function inc is not defined yet at pos 53
-undef('pi')  => bad idea - removes hidden variable holding the pi value
-undef('true')  => even worse idea, unbinds global true value, all references to true would now refer to the default 0
 
### `vars(prefix)` From fb7b1f79a5b35acbbd5c7ae02c47227831608490 Mon Sep 17 00:00:00 2001 From: altrisi Date: Mon, 23 Jan 2023 22:19:07 +0100 Subject: [PATCH 023/233] Fix unchecked removal of commands by app name --- src/main/java/carpet/script/CarpetScriptHost.java | 11 +++++++++-- src/main/java/carpet/script/CarpetScriptServer.java | 9 +++++---- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/src/main/java/carpet/script/CarpetScriptHost.java b/src/main/java/carpet/script/CarpetScriptHost.java index 4ce39f4467..7462db75a1 100644 --- a/src/main/java/carpet/script/CarpetScriptHost.java +++ b/src/main/java/carpet/script/CarpetScriptHost.java @@ -83,6 +83,7 @@ public class CarpetScriptHost extends ScriptHost Predicate commandValidator; boolean isRuleApp; public AppStoreManager.StoreNode storeSource; + boolean hasCommand; private CarpetScriptHost(CarpetScriptServer server, Module code, boolean perUser, ScriptHost parent, Map config, Map argTypes, Predicate commandValidator, boolean isRuleApp) { @@ -358,6 +359,12 @@ public int compare(Pair,?> p1, Pair,?> p2) { } } + // Used to ensure app gets marked as holding command from a central place + private void registerCommand(LiteralArgumentBuilder command) { + scriptServer().server.getCommands().getDispatcher().register(command); + hasCommand = true; + } + public void readCustomArgumentTypes() throws CommandSyntaxException { // read custom arguments @@ -401,7 +408,7 @@ public Boolean addAppCommands(Consumer notifier) LiteralArgumentBuilder command = readCommands(commandValidator); if (command != null) { - scriptServer().server.getCommands().getDispatcher().register(command); + registerCommand(command); return true; } else { @@ -523,7 +530,7 @@ private Boolean addLegacyCommand(Consumer notifier) }))); } } - scriptServer().server.getCommands().getDispatcher().register(command); + registerCommand(command); return true; } diff --git a/src/main/java/carpet/script/CarpetScriptServer.java b/src/main/java/carpet/script/CarpetScriptServer.java index e2d2f14001..4ddf57a46a 100644 --- a/src/main/java/carpet/script/CarpetScriptServer.java +++ b/src/main/java/carpet/script/CarpetScriptServer.java @@ -341,10 +341,11 @@ public boolean removeScriptHost(CommandSourceStack source, String name, boolean return false; } // stop all events associated with name - events.removeAllHostEvents(modules.get(name)); - modules.get(name).onClose(); - modules.remove(name); - ((CommandDispatcherInterface)server.getCommands().getDispatcher()).carpet$unregister(name); + CarpetScriptHost host = modules.remove(name); + events.removeAllHostEvents(host); + host.onClose(); + if (host.hasCommand) + ((CommandDispatcherInterface)server.getCommands().getDispatcher()).carpet$unregister(name); if (!isRuleApp) unloadableModules.remove(name); CommandHelper.notifyPlayersCommandsChanged(server); if (notifySource) Messenger.m(source, "gi Removed "+name+" app"); From 889e3b699963146f7c9fa50d749fa5cad980fea1 Mon Sep 17 00:00:00 2001 From: altrisi Date: Tue, 24 Jan 2023 13:46:01 +0100 Subject: [PATCH 024/233] Replace usages of `j.u.Stack` with fastutil's Java's is synchronized everywhere, reducing performance given we don't need it to be. It's recommended to use `Deque` as a replacement, but given we have fastutil's, we use those Closes #1640 --- src/main/java/carpet/script/Expression.java | 40 +++++++++++---------- 1 file changed, 21 insertions(+), 19 deletions(-) diff --git a/src/main/java/carpet/script/Expression.java b/src/main/java/carpet/script/Expression.java index a498f22e1d..90f493c276 100644 --- a/src/main/java/carpet/script/Expression.java +++ b/src/main/java/carpet/script/Expression.java @@ -32,7 +32,10 @@ import carpet.script.value.NumericValue; import carpet.script.value.StringValue; import carpet.script.value.Value; +import it.unimi.dsi.fastutil.Stack; +import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; import java.math.BigInteger; import java.util.ArrayList; @@ -41,7 +44,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -import java.util.Stack; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; @@ -763,7 +765,7 @@ public Expression(String expression) private List shuntingYard(Context c) { List outputQueue = new ArrayList<>(); - Stack stack = new Stack<>(); + Stack stack = new ObjectArrayList<>(); Tokenizer tokenizer = new Tokenizer(c, this, expression, allowComments, allowNewlineSubstitutions); // stripping lousy but acceptable semicolons @@ -801,7 +803,7 @@ private List shuntingYard(Context c) { throw new ExpressionException(c, this, previousToken, "Missing parameter(s) for operator "); } - while (!stack.isEmpty() && stack.peek().type != Tokenizer.Token.TokenType.OPEN_PAREN) + while (!stack.isEmpty() && stack.top().type != Tokenizer.Token.TokenType.OPEN_PAREN) { outputQueue.add(stack.pop()); } @@ -878,7 +880,7 @@ private List shuntingYard(Context c) { throw new ExpressionException(c, this, previousToken, "Missing parameter(s) for operator " + previousToken); } - while (!stack.isEmpty() && stack.peek().type != Tokenizer.Token.TokenType.OPEN_PAREN) + while (!stack.isEmpty() && stack.top().type != Tokenizer.Token.TokenType.OPEN_PAREN) { outputQueue.add(stack.pop()); } @@ -887,7 +889,7 @@ private List shuntingYard(Context c) throw new ExpressionException(c, this, "Mismatched parentheses"); } stack.pop(); - if (!stack.isEmpty() && stack.peek().type == Tokenizer.Token.TokenType.FUNCTION) + if (!stack.isEmpty() && stack.top().type == Tokenizer.Token.TokenType.FUNCTION) { outputQueue.add(stack.pop()); } @@ -918,7 +920,7 @@ private List shuntingYard(Context c) private void shuntOperators(List outputQueue, Stack stack, ILazyOperator o1) { - Tokenizer.Token nextToken = stack.isEmpty() ? null : stack.peek(); + Tokenizer.Token nextToken = stack.isEmpty() ? null : stack.top(); while (nextToken != null && (nextToken.type == Tokenizer.Token.TokenType.OPERATOR || nextToken.type == Tokenizer.Token.TokenType.UNARY_OPERATOR) @@ -926,7 +928,7 @@ private void shuntOperators(List outputQueue, Stack tokens, Context context) { - Stack nodeStack = new Stack<>(); + Stack nodeStack = new ObjectArrayList<>(); for (final Tokenizer.Token token : tokens) { switch (token.type) @@ -1041,7 +1043,7 @@ private ExpressionNode RPNToParseTree(List tokens, Context cont } // pop parameters off the stack until we hit the start of // this function's parameter list - while (!nodeStack.isEmpty() && nodeStack.peek() != ExpressionNode.PARAMS_START) + while (!nodeStack.isEmpty() && nodeStack.top() != ExpressionNode.PARAMS_START) { p.add(nodeStack.pop()); } @@ -1052,7 +1054,7 @@ private ExpressionNode RPNToParseTree(List tokens, Context cont } Collections.reverse(p); - if (nodeStack.peek() == ExpressionNode.PARAMS_START) + if (nodeStack.top() == ExpressionNode.PARAMS_START) { nodeStack.pop(); }; @@ -1377,7 +1379,7 @@ private void validate(Context c, List rpn) // each // layer on the stack being the count of the number of parameters in // that scope - Stack stack = new Stack<>(); + IntArrayList stack = new IntArrayList(); // IntArrayList instead of just IntStack because we need to query the size // push the 'global' scope stack.push(0); @@ -1387,13 +1389,13 @@ private void validate(Context c, List rpn) switch (token.type) { case UNARY_OPERATOR: - if (stack.peek() < 1) + if (stack.topInt() < 1) { throw new ExpressionException(c, this, token, "Missing parameter(s) for operator " + token); } break; case OPERATOR: - if (stack.peek() < 2) + if (stack.topInt() < 2) { if (token.surface.equals(";")) { @@ -1402,7 +1404,7 @@ private void validate(Context c, List rpn) throw new ExpressionException(c, this, token, "Missing parameter(s) for operator " + token); } // pop the operator's 2 parameters and add the result - stack.set(stack.size() - 1, stack.peek() - 2 + 1); + stack.set(stack.size() - 1, stack.topInt() - 2 + 1); break; case FUNCTION: //ILazyFunction f = functions.get(token.surface);// don't validate global - userdef functions @@ -1411,7 +1413,7 @@ private void validate(Context c, List rpn) //{ // throw new ExpressionException(c, this, token, "Function " + token + " expected " + f.getNumParams() + " parameters, got " + numParams); //} - stack.pop(); + stack.popInt(); // due to unpacking, all functions can have variable number of arguments // we will be checking that at runtime. // TODO try analyze arguments and assess if its possible that they are static @@ -1420,13 +1422,13 @@ private void validate(Context c, List rpn) throw new ExpressionException(c, this, token, "Too many function calls, maximum scope exceeded"); } // push the result of the function - stack.set(stack.size() - 1, stack.peek() + 1); + stack.set(stack.size() - 1, stack.topInt() + 1); break; case OPEN_PAREN: stack.push(0); break; default: - stack.set(stack.size() - 1, stack.peek() + 1); + stack.set(stack.size() - 1, stack.topInt() + 1); } } @@ -1434,11 +1436,11 @@ private void validate(Context c, List rpn) { throw new ExpressionException(c, this, "Too many unhandled function parameter lists"); } - else if (stack.peek() > 1) + else if (stack.topInt() > 1) { throw new ExpressionException(c, this, "Too many numbers or variables"); } - else if (stack.peek() < 1) + else if (stack.topInt() < 1) { throw new ExpressionException(c, this, "Empty expression"); } From a95622e749844c8a476e30b5f7954f94acd9dd41 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Tue, 24 Jan 2023 21:52:01 +0100 Subject: [PATCH 025/233] 22w04a --- gradle.properties | 4 ++-- src/main/java/carpet/mixins/RecipeManager_scarpetMixin.java | 2 +- src/main/java/carpet/script/api/Inventories.java | 2 +- src/main/java/carpet/script/utils/ShapesRenderer.java | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/gradle.properties b/gradle.properties index ec9b8ddf8d..74169a14f3 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,9 +4,9 @@ org.gradle.jvmargs=-Xmx1G # Fabric Properties # check these on https://fabricmc.net/use # or better: https://modmuss50.me/fabric.html - minecraft_version=23w03a + minecraft_version=23w04a loader_version=0.14.13 - fabric_version=0.72.0+1.19.3 + fabric_version=0.73.1+1.19.4 # Mod Properties mod_version = 1.4.94 diff --git a/src/main/java/carpet/mixins/RecipeManager_scarpetMixin.java b/src/main/java/carpet/mixins/RecipeManager_scarpetMixin.java index 39ae15912a..217e8aef11 100644 --- a/src/main/java/carpet/mixins/RecipeManager_scarpetMixin.java +++ b/src/main/java/carpet/mixins/RecipeManager_scarpetMixin.java @@ -34,6 +34,6 @@ public List> getAllMatching(RecipeType type, ResourceLocation outpu if (typeRecipes.containsKey(output)) return Collections.singletonList(typeRecipes.get(output)); final Registry regs = registryAccess.registryOrThrow(Registries.ITEM); return Lists.newArrayList(typeRecipes.values().stream().filter( - r -> regs.getKey(r.getResultItem().getItem()).equals(output)).collect(Collectors.toList())); + r -> regs.getKey(r.getResultItem(registryAccess).getItem()).equals(output)).collect(Collectors.toList())); } } diff --git a/src/main/java/carpet/script/api/Inventories.java b/src/main/java/carpet/script/api/Inventories.java index f03bb6e76e..055f2ae2df 100644 --- a/src/main/java/carpet/script/api/Inventories.java +++ b/src/main/java/carpet/script/api/Inventories.java @@ -134,7 +134,7 @@ public static void apply(Expression expression) RegistryAccess regs = cc.registryAccess(); for (Recipe recipe: recipes) { - ItemStack result = recipe.getResultItem(); + ItemStack result = recipe.getResultItem(regs); List ingredientValue = new ArrayList<>(); recipe.getIngredients().forEach( ingredient -> diff --git a/src/main/java/carpet/script/utils/ShapesRenderer.java b/src/main/java/carpet/script/utils/ShapesRenderer.java index 33ff5cf3e2..574803ad70 100644 --- a/src/main/java/carpet/script/utils/ShapesRenderer.java +++ b/src/main/java/carpet/script/utils/ShapesRenderer.java @@ -363,7 +363,7 @@ public void renderLines(PoseStack matrices, Tesselator tessellator, BufferBuilde { // draw the item client.getItemRenderer().renderStatic(shape.item, transformType, light, - OverlayTexture.NO_OVERLAY, matrices, immediate, (int) shape.key(client.level.registryAccess())); + OverlayTexture.NO_OVERLAY, matrices, immediate, client.level, (int) shape.key(client.level.registryAccess())); } } matrices.popPose(); From 1a88ac35b52c36f52293b0e848bcfc619a6d27c9 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Tue, 24 Jan 2023 21:58:02 +0100 Subject: [PATCH 026/233] 1.4.95 --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 74169a14f3..d380b9add8 100644 --- a/gradle.properties +++ b/gradle.properties @@ -9,7 +9,7 @@ org.gradle.jvmargs=-Xmx1G fabric_version=0.73.1+1.19.4 # Mod Properties - mod_version = 1.4.94 + mod_version = 1.4.95 maven_group = carpet archives_base_name = fabric-carpet From abe1d070de5b4a0e2702ce6c9c6b1e9182c8928a Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Tue, 24 Jan 2023 22:10:12 +0100 Subject: [PATCH 027/233] thick stuff its not a confirmed bug --- src/main/java/carpet/CarpetSettings.java | 11 ++++++----- .../java/carpet/mixins/HugeFungusFeatureMixin.java | 4 ++-- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/main/java/carpet/CarpetSettings.java b/src/main/java/carpet/CarpetSettings.java index e10f72cf58..0a2cee9df6 100644 --- a/src/main/java/carpet/CarpetSettings.java +++ b/src/main/java/carpet/CarpetSettings.java @@ -1045,13 +1045,14 @@ public String description() { public static int sculkSensorRange = 8; public enum FungusFixMode { - FALSE, VANILLA, ALL; + FALSE, RANDOM, ALL; } + // refers to "[MC-215169](https://bugs.mojang.com/browse/MC-215169)." - unconfirmed yet that its a java bug @Rule( - desc = "Allows to grow nether trees with 3x3 base with bonemeal", - extra = {"Setting to 'all' will make all nether fungi grow into 3x3 trees", "Setting to 'vanilla' will make 6% of all nether fungi grow into 3x3 trees", "(this being consistent with worldgen)", "Fixes [MC-215169](https://bugs.mojang.com/browse/MC-215169)."}, - category = {SURVIVAL, BUGFIX} + desc = "Allows to grow nether fungi with 3x3 base with bonemeal", + extra = {"Setting to 'all' will make all nether fungi grow into 3x3 trees", "Setting to 'random' will make 6% of all nether fungi grow into 3x3 trees", "(this being consistent with worldgen)"}, + category = {SURVIVAL, FEATURE} ) - public static FungusFixMode thickHugeFungusGrowthFix = FungusFixMode.FALSE; + public static FungusFixMode thickFungusGrowth = FungusFixMode.FALSE; } diff --git a/src/main/java/carpet/mixins/HugeFungusFeatureMixin.java b/src/main/java/carpet/mixins/HugeFungusFeatureMixin.java index 3fb870cdd4..99af900482 100644 --- a/src/main/java/carpet/mixins/HugeFungusFeatureMixin.java +++ b/src/main/java/carpet/mixins/HugeFungusFeatureMixin.java @@ -17,8 +17,8 @@ public class HugeFungusFeatureMixin { private void mixin(Args args) { boolean natural = !((HugeFungusConfiguration) args.get(2)).planted; args.set(5, natural && ((boolean) args.get(5)) || - !natural && (CarpetSettings.thickHugeFungusGrowthFix.equals(ALL) || - CarpetSettings.thickHugeFungusGrowthFix.equals(VANILLA) && ((RandomSource) args.get(1)).nextFloat() < 0.06F) + !natural && (CarpetSettings.thickFungusGrowth.equals(ALL) || + CarpetSettings.thickFungusGrowth.equals(RANDOM) && ((RandomSource) args.get(1)).nextFloat() < 0.06F) ); } } From d26a56ea980114d424e8e10b274d7a1fbb194ad2 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Tue, 24 Jan 2023 21:20:04 +0000 Subject: [PATCH 028/233] Merge docs for 'Carpet Mod 1.4.95 for Minecraft 23w04a' --- docs/scarpet/Full.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/docs/scarpet/Full.md b/docs/scarpet/Full.md index 35cb033866..72390719c0 100644 --- a/docs/scarpet/Full.md +++ b/docs/scarpet/Full.md @@ -1159,8 +1159,6 @@ It can affect global variable pool, and local variable set for a particular func inc(i) -> i+1; foo = 5; inc(foo) => 6 inc(i) -> i+1; foo = 5; undef('foo'); inc(foo) => 1 inc(i) -> i+1; foo = 5; undef('inc'); undef('foo'); inc(foo) => Error: Function inc is not defined yet at pos 53 -undef('pi') => bad idea - removes hidden variable holding the pi value -undef('true') => even worse idea, unbinds global true value, all references to true would now refer to the default 0
### `vars(prefix)` @@ -6049,7 +6047,8 @@ system calls. In all circumstances, these are only provided as read-only. * `world_center` - Returns coordinates of the center of the world with respect of the world border * `world_size` - Returns radius of world border for current dimension. * `world_max_size` - Returns maximum possible radius of world border for current dimension. - * + * `world_min_spawning_light` - Returns minimum light level at which mobs can spawn for current dimension, taking into account datapacks + ##### Relevant gameplay related properties * `game_difficulty` - current difficulty of the game: `'peaceful'`, `'easy'`, `'normal'`, or `'hard'` * `game_hardcore` - boolean whether the game is in hardcore mode From f2c658bf03562a88b1d283729fce3f00b6874b7e Mon Sep 17 00:00:00 2001 From: Crec0 <83436716+Crec0@users.noreply.github.com> Date: Wed, 25 Jan 2023 08:08:36 -0800 Subject: [PATCH 029/233] Add `compute_density_function` to replace removed `sample_noise (#1591) --- docs/scarpet/api/BlocksAndWorldAccess.md | 46 ++- docs/scarpet/resources/editors/idea/2.txt | 2 +- .../scarpet/resources/editors/npp/scarpet.xml | 2 +- .../fakes/NoiseColumnSamplerInterface.java | 5 - .../fakes/RandomStateVisitorAccessor.java | 7 + .../mixins/NoiseSampler_scarpetMixin.java | 265 ------------------ ...izedSpaghettiRarityMixin_scarpetMixin.java | 15 - .../mixins/RandomState_ScarpetMixin.java | 33 +++ .../java/carpet/script/api/WorldAccess.java | 83 +++++- src/main/resources/carpet.mixins.json | 3 +- 10 files changed, 142 insertions(+), 319 deletions(-) delete mode 100644 src/main/java/carpet/fakes/NoiseColumnSamplerInterface.java create mode 100644 src/main/java/carpet/fakes/RandomStateVisitorAccessor.java delete mode 100644 src/main/java/carpet/mixins/NoiseSampler_scarpetMixin.java delete mode 100644 src/main/java/carpet/mixins/QuantizedSpaghettiRarityMixin_scarpetMixin.java create mode 100644 src/main/java/carpet/mixins/RandomState_ScarpetMixin.java diff --git a/docs/scarpet/api/BlocksAndWorldAccess.md b/docs/scarpet/api/BlocksAndWorldAccess.md index 1eb3074770..883fd87b9a 100644 --- a/docs/scarpet/api/BlocksAndWorldAccess.md +++ b/docs/scarpet/api/BlocksAndWorldAccess.md @@ -509,30 +509,46 @@ Returns the map colour of a block at position. One of: `'brown_terracotta'`, `'green_terracotta'`, `'red_terracotta'`, `'black_terracotta'`, `'crimson_nylium'`, `'crimson_stem'`, `'crimson_hyphae'`, `'warped_nylium'`, `'warped_stem'`, `'warped_hyphae'`, `'warped_wart'` -### `sample_noise(pos, ...type?)` 1.18+ only +### `compute_density_function(pos, ...types?)` 1.19+ only - Samples the multi noise value(s) on the given position. -If no type is passed, returns a map of `continentalness`, `depth`, `erosion`, `humidity`, `temperature`, `weirdness`. -Otherwise, returns the map of that specific noise. +**Note: Replaces the old `sample_noise` function** + +Computes the density function(s) on the given position. Check the [Available Types](#available-types) for list of available density functions. + +If no types are passed in, it returns a list of all the available density functions. Built-in and custom ones.
-// without type
-sample_noise(pos) => {continentalness: 0.445300012827, erosion: 0.395399987698, temperature: 0.165399998426, ...}
 // passing type as multiple arguments
-sample_noise(pos, 'pillarRareness', 'aquiferBarrier') => {aquiferBarrier: -0.205013844481, pillarRareness: 1.04772473438}
+compute_density_function(pos, 'continents', 'depth') => {continents: -0.205013844481, depth: 1.04772473438}
 // passing types as a list with unpacking operator
-sample_noise(pos, ...['spaghetti3dFirst', 'spaghetti3dSecond']) => {spaghetti3dFirst: -0.186052125186, spaghetti3dSecond: 0.211626790923}
+compute_density_function(pos, ...['ridges', 'overworld/caves/pillars']) => {ridges: -0.186052125186, overworld/caves/pillars: 0.211626790923}
+// Custom Defined types
+compute_density_function(pos, 'mydatapack:my_density_func') => {mydatapack:my_density_func: -0.186052125186}
 
-Available types: +#### Available types: + +##### Built-in + +`'barrier_noise'`, `'continents'`, `'depth'`, `'end/base_3d_noise'`, `'end/sloped_cheese'`, `'erosion'`, `'final_density'`, +`'fluid_level_floodedness_noise'`, `'fluid_level_spread_noise'`, `'initial_density_without_jaggedness'`, `'lava_noise'`, +`'nether/base_3d_noise'`, `'overworld/base_3d_noise'`, `'overworld/base_continents'`, `'overworld/caves/entrances'`, +`'overworld/caves/noodle'`, `'overworld/caves/pillars'`, `'overworld/caves/spaghetti_2d'`, `'overworld/caves/spaghetti_2d_thickness_modulator'`, +`'overworld/caves/spaghetti_roughness_function'`, `'overworld/continents'`, `'overworld/depth'`, `'overworld/erosion'`, +`'overworld/factor'`, `'overworld/jaggedness'`, `'overworld/offset'`, `'overworld/ridges'`, `'overworld/ridges_folded'`, +`'overworld/sloped_cheese'`, `'overworld_amplified/depth'`, `'overworld_amplified/factor'`, `'overworld_amplified/jaggedness'`, +`'overworld_amplified/offset'`, `'overworld_amplified/sloped_cheese'`, `'overworld_large_biomes/base_continents'`, +`'overworld_large_biomes/continents'`, `'overworld_large_biomes/depth'`, `'overworld_large_biomes/erosion'`, +`'overworld_large_biomes/factor'`, `'overworld_large_biomes/jaggedness'`, `'overworld_large_biomes/offset'`, +`'overworld_large_biomes/sloped_cheese'`, `'ridges'`, `'shift_x'`, `'shift_z'`, `'temperature'`, `'vegetation'`, +`'vein_gap'`, `'vein_gapbarrier_noise'`, `'vein_ridged'`, `'vein_toggle'`, `'y'`, `'zero'` + +##### Custom -`aquiferBarrier`, `aquiferFluidLevelFloodedness`, `aquiferFluidLevelSpread`, `aquiferLava`, `caveCheese`, -`caveEntrance`, `caveLayer`, `continentalness`, `depth`, `erosion`, `humidity`, `island`, `jagged`, `oreGap`, -`pillar`, `pillarRareness`, `pillarThickness`, `shiftX`, `shiftY`, `shiftZ`, `spaghetti2d`, `spaghetti2dElevation`, -`spaghetti2dModulator`, `spaghetti2dThickness`, `spaghetti3d`, `spaghetti3dFirst`, `spaghetti3dRarity`, -`spaghetti3dSecond`, `spaghetti3dThickness`, `spaghettiRoughness`, `spaghettiRoughnessModulator`, `temperature`, -`terrain`, `terrainFactor`, `terrainOffset`, `terrainPeaks`, `weirdness` +Custom defined density functions from datapacks are also available and can be used. However, unlike built-in types, these +ones must use full namespace. i.e. `namespace:path`. Examples: `'mydatapack:density_function'`, `'mydatapack:nested/density_function'` +**Note: Custom density functions require a server relaunch after enabling the datapack.** ### `loaded(pos)` diff --git a/docs/scarpet/resources/editors/idea/2.txt b/docs/scarpet/resources/editors/idea/2.txt index d90729fda0..e26ea19d53 100644 --- a/docs/scarpet/resources/editors/idea/2.txt +++ b/docs/scarpet/resources/editors/idea/2.txt @@ -93,7 +93,7 @@ reload_chunk remove_all_markers reset_chunk run -sample_noise +compute_density_function save scan schedule diff --git a/docs/scarpet/resources/editors/npp/scarpet.xml b/docs/scarpet/resources/editors/npp/scarpet.xml index 8d84d458b7..3f3b6b0a53 100644 --- a/docs/scarpet/resources/editors/npp/scarpet.xml +++ b/docs/scarpet/resources/editors/npp/scarpet.xml @@ -57,7 +57,7 @@ hardness blast_resistance top loaded suffocates power ticks_randomly update block_tick random_tick in_slime_chunk set without_updates blocks_movement block_sound material map_colour block_state block_list block_tags block_data poi set_poi - place_item set_biome biome loaded_status generation_status sample_noise inhabited_time spawn_potential chunk_tickets + place_item set_biome biome loaded_status generation_status compute_density_function inhabited_time spawn_potential chunk_tickets plop harvest destroy create_explosion structure_eligibility structures structure_references set_structure reset_chunk reload_chunk create_datapack diff --git a/src/main/java/carpet/fakes/NoiseColumnSamplerInterface.java b/src/main/java/carpet/fakes/NoiseColumnSamplerInterface.java deleted file mode 100644 index 42efcc669a..0000000000 --- a/src/main/java/carpet/fakes/NoiseColumnSamplerInterface.java +++ /dev/null @@ -1,5 +0,0 @@ -package carpet.fakes; - -public interface NoiseColumnSamplerInterface { - double getNoiseSample(String name, int x, int y, int z); -} diff --git a/src/main/java/carpet/fakes/RandomStateVisitorAccessor.java b/src/main/java/carpet/fakes/RandomStateVisitorAccessor.java new file mode 100644 index 0000000000..d423bb5289 --- /dev/null +++ b/src/main/java/carpet/fakes/RandomStateVisitorAccessor.java @@ -0,0 +1,7 @@ +package carpet.fakes; + +import net.minecraft.world.level.levelgen.DensityFunction; + +public interface RandomStateVisitorAccessor { + DensityFunction.Visitor getVisitor(); +} diff --git a/src/main/java/carpet/mixins/NoiseSampler_scarpetMixin.java b/src/main/java/carpet/mixins/NoiseSampler_scarpetMixin.java deleted file mode 100644 index 02ec89a512..0000000000 --- a/src/main/java/carpet/mixins/NoiseSampler_scarpetMixin.java +++ /dev/null @@ -1,265 +0,0 @@ -package carpet.mixins; - -import carpet.fakes.NoiseColumnSamplerInterface; -import carpet.script.exception.InternalExpressionException; -import net.minecraft.core.QuartPos; -import net.minecraft.world.level.biome.Climate; -import net.minecraft.world.level.levelgen.NoiseRouter; -import net.minecraft.world.level.levelgen.NoiseRouterData; -//import net.minecraft.world.level.levelgen.NoiseSampler; -import net.minecraft.world.level.levelgen.NoiseSettings; -//import net.minecraft.world.level.levelgen.TerrainInfo; -import net.minecraft.world.level.levelgen.blending.Blender; -import net.minecraft.world.level.levelgen.synth.BlendedNoise; -import net.minecraft.world.level.levelgen.synth.NoiseUtils; -import net.minecraft.world.level.levelgen.synth.NormalNoise; -import net.minecraft.world.level.levelgen.synth.SimplexNoise; -import org.jetbrains.annotations.Nullable; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; - -@Mixin(NoiseRouterData.class) -public abstract class NoiseSampler_scarpetMixin implements NoiseColumnSamplerInterface { - - /* - @Shadow @Final - private NoiseRouter router; - - @Shadow @Final - private BlendedNoise blendedNoise; - - @Shadow @Final @Nullable - private SimplexNoise islandNoise; - - @Shadow @Final - private NormalNoise barrierNoise; - - @Shadow @Final - private NormalNoise fluidLevelFloodednessNoise; - - @Shadow @Final - private NormalNoise fluidLevelSpreadNoise; - - @Shadow @Final - private NormalNoise lavaNoise; - - @Shadow @Final - private NormalNoise pillarRarenessModulator; - - @Shadow @Final - private NormalNoise pillarThicknessModulator; - - @Shadow @Final - private NormalNoise spaghetti2DElevationModulator; - - @Shadow @Final - private NormalNoise spaghetti2DRarityModulator; - - @Shadow @Final - private NormalNoise spaghetti2DThicknessModulator; - - @Shadow @Final - private NormalNoise spaghetti3DNoiseSource1; - - @Shadow @Final - private NormalNoise spaghetti3DNoiseSource2; - - @Shadow @Final - private NormalNoise spaghetti3DRarityModulator; - - @Shadow @Final - private NormalNoise spaghetti3DThicknessModulator; - - @Shadow @Final - private NormalNoise spaghettiRoughnessModulator; - - @Shadow @Final - private NormalNoise cheeseNoiseSource; - - @Shadow @Final - private NormalNoise gapNoise; - - @Shadow @Final - private NoiseSettings noiseSettings; - - @Shadow - protected abstract double sampleJaggedNoise(double d, double e, double f); - - @Shadow - protected abstract double getLayerizedCaverns(int x, int y, int z); - - @Shadow - protected abstract double getPillars(int x, int y, int z); - - @Shadow - protected abstract double getSpaghetti2D(int x, int y, int z); - - @Shadow - protected abstract double getSpaghetti3D(int x, int y, int z); - - @Shadow - protected abstract double spaghettiRoughness(int x, int y, int z); - - @Shadow - protected abstract double getBigEntrances(int x, int y, int z); - - @Shadow - public abstract double getOffset(int x, int y, int z); - - @Shadow - private static double sampleWithRarity(NormalNoise sampler, double x, double y, double z, double invertedScale) { - throw new AssertionError(); - } - - @Shadow - public abstract Climate.TargetPoint sample(int i, int j, int k); - - @Shadow - public abstract TerrainInfo terrainInfo(int x, int z, float continentalness, float weirdness, float erosion, Blender blender); - - @Override - public double getNoiseSample(String name, int x, int y, int z) { - Climate.TargetPoint noiseValuePoint = this.sample(x, y, z); - TerrainInfo terrainNoisePoint = terrainInfo( - x, - z, - Climate.unquantizeCoord(noiseValuePoint.continentalness()), - Climate.unquantizeCoord(noiseValuePoint.weirdness()), - Climate.unquantizeCoord(noiseValuePoint.erosion()), - Blender.empty() - ); - switch (name) { - case "temperature" -> { - return Climate.unquantizeCoord(noiseValuePoint.temperature()); - } - case "humidity" -> { - return Climate.unquantizeCoord(noiseValuePoint.humidity()); - } - case "continentalness" -> { - return Climate.unquantizeCoord(noiseValuePoint.continentalness()); - } - case "erosion" -> { - return Climate.unquantizeCoord(noiseValuePoint.erosion()); - } - case "weirdness" -> { - return Climate.unquantizeCoord(noiseValuePoint.weirdness()); - } - case "depth" -> { - return Climate.unquantizeCoord(noiseValuePoint.depth()); - } - case "shiftX" -> { - return x + this.getOffset(x, 0, z); - } - case "shiftY" -> { - return y + this.getOffset(y, z, x); - } - case "shiftZ" -> { - return z + this.getOffset(z, x, 0); - } - case "terrain" -> { - return this.blendedNoise.calculateNoise(x, y, z); - } - case "island" -> { - return this.islandNoise == null ? 0 : this.islandNoise.getValue(x, y, z); - } - case "jagged" -> { - return this.sampleJaggedNoise(terrainNoisePoint.jaggedness(), x, z); - } - case "aquiferBarrier" -> { - return this.barrierNoise.getValue(x, y, z); - } - case "aquiferFluidLevelFloodedness" -> { - return this.fluidLevelFloodednessNoise.getValue(x, y, z); - } - case "aquiferFluidLevelSpread" -> { - return this.fluidLevelSpreadNoise.getValue(x, y, z); - } - case "aquiferLava" -> { - return this.lavaNoise.getValue(x, y, z); - } - case "pillar" -> { - return this.getPillars(x, y, z); - } - case "pillarRareness" -> { - return NoiseUtils.sampleNoiseAndMapToRange(this.pillarRarenessModulator, x, y, z, 0.0D, 2.0D); - } - case "pillarThickness" -> { - return NoiseUtils.sampleNoiseAndMapToRange(this.pillarThicknessModulator, x, y, z, 0.0D, 1.1D); - } - case "spaghetti2d" -> { - return this.getSpaghetti2D(x, y, z); - } - case "spaghetti2dElevation" -> { - return NoiseUtils.sampleNoiseAndMapToRange(this.spaghetti2DElevationModulator, x, 0.0, z, this.noiseSettings.getMinCellY(), 8.0); - } - case "spaghetti2dModulator" -> { - return this.spaghetti2DRarityModulator.getValue(x * 2, y, z * 2); - } - case "spaghetti2dThickness" -> { - return NoiseUtils.sampleNoiseAndMapToRange(this.spaghetti2DThicknessModulator, x * 2, y, z * 2, 0.6, 1.3); - } - case "spaghetti3d" -> { - return this.getSpaghetti3D(x, y, z); - } - case "spaghetti3dFirst" -> { - double d = this.spaghetti3DRarityModulator.getValue(x * 2, y, z * 2); - double e = QuantizedSpaghettiRarityMixin_scarpetMixin.invokeGetSpaghettiRarity3D(d); - return sampleWithRarity(this.spaghetti3DNoiseSource1, x, y, z, e); - } - case "spaghetti3dSecond" -> { - double d = this.spaghetti3DRarityModulator.getValue(x * 2, y, z * 2); - double e = QuantizedSpaghettiRarityMixin_scarpetMixin.invokeGetSpaghettiRarity3D(d); - return sampleWithRarity(this.spaghetti3DNoiseSource2, x, y, z, e); - } - case "spaghetti3dRarity" -> { - return this.spaghetti3DRarityModulator.getValue(x * 2, y, z * 2); - } - case "spaghetti3dThickness" -> { - return NoiseUtils.sampleNoiseAndMapToRange(this.spaghetti3DThicknessModulator, x, y, z, 0.065, 0.088); - } - case "spaghettiRoughness" -> { - return this.spaghettiRoughness(x, y, z); - } - case "spaghettiRoughnessModulator" -> { - return NoiseUtils.sampleNoiseAndMapToRange(this.spaghettiRoughnessModulator, x, y, z, 0.0, 0.1); - } - case "caveEntrance" -> { - return this.getBigEntrances( - QuartPos.toBlock(x), - QuartPos.toBlock(y), - QuartPos.toBlock(z) - ); - } - case "caveLayer" -> { - // scaling them by 4 because it's sampled in normal coords - return this.getLayerizedCaverns( - QuartPos.toBlock(x), - QuartPos.toBlock(y), - QuartPos.toBlock(z) - ); - } - case "caveCheese" -> { - // same reason as above - return this.cheeseNoiseSource.getValue( - QuartPos.toBlock(x), - QuartPos.toBlock(y) / 1.5, - QuartPos.toBlock(z) - ); - } - case "terrainPeaks" -> { - return terrainNoisePoint.jaggedness(); - } - case "terrainOffset" -> { - return terrainNoisePoint.offset(); - } - case "terrainFactor" -> { - return terrainNoisePoint.factor(); - } - case "oreGap" -> { - return this.gapNoise.getValue(x, y, z); - } - } - throw new InternalExpressionException("Unknown noise type: " + name); - }*/ -} diff --git a/src/main/java/carpet/mixins/QuantizedSpaghettiRarityMixin_scarpetMixin.java b/src/main/java/carpet/mixins/QuantizedSpaghettiRarityMixin_scarpetMixin.java deleted file mode 100644 index f3eed7df55..0000000000 --- a/src/main/java/carpet/mixins/QuantizedSpaghettiRarityMixin_scarpetMixin.java +++ /dev/null @@ -1,15 +0,0 @@ -package carpet.mixins; - -//import net.minecraft.world.level.levelgen.NoiseRouterData; -//import net.minecraft.world.level.levelgen.NoiseSampler; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Invoker; - - -@Mixin(targets = "net.minecraft.world.level.levelgen.NoiseRouterData$QuantizedSpaghettiRarity") -public interface QuantizedSpaghettiRarityMixin_scarpetMixin { - @Invoker - static double invokeGetSpaghettiRarity3D(double d) { - throw new AssertionError(); - } -} diff --git a/src/main/java/carpet/mixins/RandomState_ScarpetMixin.java b/src/main/java/carpet/mixins/RandomState_ScarpetMixin.java new file mode 100644 index 0000000000..2e855238ac --- /dev/null +++ b/src/main/java/carpet/mixins/RandomState_ScarpetMixin.java @@ -0,0 +1,33 @@ +package carpet.mixins; + +import carpet.fakes.RandomStateVisitorAccessor; +import net.minecraft.world.level.levelgen.DensityFunction; +import net.minecraft.world.level.levelgen.RandomState; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.ModifyArg; + +@Mixin(RandomState.class) +public class RandomState_ScarpetMixin implements RandomStateVisitorAccessor { + @Unique + private DensityFunction.Visitor visitor; + + @ModifyArg( + method = "", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/world/level/levelgen/NoiseRouter;mapAll(Lnet/minecraft/world/level/levelgen/DensityFunction$Visitor;)Lnet/minecraft/world/level/levelgen/NoiseRouter;" + ), + index = 0 + ) + private DensityFunction.Visitor captureVisitor(DensityFunction.Visitor visitor) { + this.visitor = visitor; + return visitor; + } + + @Override + public DensityFunction.Visitor getVisitor() { + return this.visitor; + } +} diff --git a/src/main/java/carpet/script/api/WorldAccess.java b/src/main/java/carpet/script/api/WorldAccess.java index 2f6768fb4f..44fb1a09de 100644 --- a/src/main/java/carpet/script/api/WorldAccess.java +++ b/src/main/java/carpet/script/api/WorldAccess.java @@ -3,6 +3,7 @@ import carpet.CarpetSettings; import carpet.fakes.ChunkGeneratorInterface; import carpet.fakes.ChunkTicketManagerInterface; +import carpet.fakes.RandomStateVisitorAccessor; import carpet.fakes.ServerChunkManagerInterface; import carpet.fakes.ServerWorldInterface; import carpet.fakes.SpawnHelperInnerInterface; @@ -41,15 +42,22 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.Holder; +import net.minecraft.core.HolderLookup; import net.minecraft.core.HolderSet; import net.minecraft.core.QuartPos; import net.minecraft.core.Registry; import net.minecraft.core.registries.Registries; import net.minecraft.resources.ResourceKey; import net.minecraft.tags.TagKey; +import net.minecraft.world.level.chunk.ChunkGenerator; import net.minecraft.world.level.chunk.PalettedContainer; +import net.minecraft.world.level.levelgen.DensityFunction; +import net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator; +import net.minecraft.world.level.levelgen.NoiseRouter; +import net.minecraft.world.level.levelgen.RandomState; import net.minecraft.world.level.levelgen.structure.Structure; import net.minecraft.world.level.levelgen.structure.StructureType; +import net.minecraft.world.level.levelgen.synth.NormalNoise; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; @@ -1626,23 +1634,68 @@ else if (ticket == TicketType.POST_TELEPORT) // post teleport } @ScarpetFunction(maxParams = -1) - public Value sample_noise(Context c, @Locator.Block BlockPos pos, String... noiseQueries) { - return Value.NULL; - /* - int mappedX = QuartPos.fromBlock(pos.getX()); - int mappedY = QuartPos.fromBlock(pos.getY()); - int mappedZ = QuartPos.fromBlock(pos.getZ()); - Climate.Sampler mns = ((CarpetContext) c).s.getLevel().getChunkSource().getGenerator().climateSampler(); - Map ret = new HashMap<>(); - - if (noiseQueries.length == 0) { - noiseQueries = new String[]{"continentalness", "erosion", "weirdness", "temperature", "humidity", "depth"}; + public Value compute_density_function(Context c, @Locator.Block BlockPos pos, String... densityFunctionQueries) { + + Map result = new HashMap<>(); + + ServerLevel level = ((CarpetContext) c).level(); + Registry densityFunctionRegistry = level.registryAccess().registryOrThrow(Registries.DENSITY_FUNCTION); + + if (densityFunctionQueries.length == 0) { + return ListValue.wrap(densityFunctionRegistry.keySet().stream().map(ValueConversions::of)); } - for (String noise : noiseQueries) { - double noiseValue = ((NoiseColumnSamplerInterface) mns).getNoiseSample(noise, mappedX, mappedY, mappedZ); - ret.put(new StringValue(noise), new NumericValue(noiseValue)); + ChunkGenerator chunkGenerator = level.getChunkSource().getGenerator(); + if (!(chunkGenerator instanceof NoiseBasedChunkGenerator generator)) { + return MapValue.wrap(result); + } + + RandomState randomState = RandomState.create( + generator.generatorSettings().value(), + level.registryAccess().lookupOrThrow(Registries.NOISE), level.getSeed() + ); + + DensityFunction.Visitor visitor = ((RandomStateVisitorAccessor) (Object) randomState).getVisitor(); + DensityFunction.SinglePointContext singlePointContext = new DensityFunction.SinglePointContext(pos.getX(), pos.getY(), pos.getZ()); + NoiseRouter router = generator.generatorSettings().value().noiseRouter(); + + for (String densityFunctionQuery : densityFunctionQueries) { + DensityFunction densityFunction = switch (densityFunctionQuery) { + case "barrier_noise" -> router.barrierNoise(); + case "fluid_level_floodedness_noise" -> router.fluidLevelFloodednessNoise(); + case "fluid_level_spread_noise" -> router.fluidLevelSpreadNoise(); + case "lava_noise" -> router.lavaNoise(); + case "temperature" -> router.temperature(); + case "vegetation" -> router.vegetation(); + case "continents" -> router.continents(); + case "erosion" -> router.erosion(); + case "depth" -> router.depth(); + case "ridges" -> router.ridges(); + case "initial_density_without_jaggedness" -> router.initialDensityWithoutJaggedness(); + case "final_density" -> router.finalDensity(); + case "vein_toggle" -> router.veinToggle(); + case "vein_ridged" -> router.veinRidged(); + case "vein_gap" -> router.veinGap(); + default -> { + ResourceLocation densityFunctionKey = InputValidator.identifierOf(densityFunctionQuery); + + if (densityFunctionRegistry.containsKey(densityFunctionKey)) { + yield densityFunctionRegistry.get(densityFunctionKey); + } + + throw new InternalExpressionException( + "Density function '" + densityFunctionQuery + "' doesn't exist. " + + "Please check the spelling or use with full 'namespace:value' if its custom defined." + ); + } + }; + + if (densityFunction == null) // IDE thinks may be null as Registry.get is Nullable, but we checked it + throw new IllegalStateException("density function can't be null here"); + + double value = densityFunction.mapAll(visitor).compute(singlePointContext); + result.put(StringValue.of(densityFunctionQuery), new NumericValue(value)); } - return MapValue.wrap(ret);*/ + return MapValue.wrap(result); } } diff --git a/src/main/resources/carpet.mixins.json b/src/main/resources/carpet.mixins.json index 13bd6b2394..f154e797d7 100644 --- a/src/main/resources/carpet.mixins.json +++ b/src/main/resources/carpet.mixins.json @@ -162,8 +162,7 @@ "BlockPredicate_scarpetMixin", "TagPredicate_scarpetMixin", "HorseBaseEntity_scarpetMixin", - "NoiseSampler_scarpetMixin", - "QuantizedSpaghettiRarityMixin_scarpetMixin", + "RandomState_ScarpetMixin", "Biome_scarpetMixin", "BlockEntity_movableBEMixin", From 0e2f6df4d38cd45fd35c305a096601288c5acb0e Mon Sep 17 00:00:00 2001 From: Space Walker <48224626+SpaceWalkerRS@users.noreply.github.com> Date: Wed, 25 Jan 2023 17:28:05 +0100 Subject: [PATCH 030/233] Allow setting qc range with `quasiConnectivity` setting (#1617) * add quasiConnectivityRange setting * make sure qc range respects different world heights * check if source == null in qc range validator * merge the two qc settings * Set minimum range down to zero (no qc) --- src/main/java/carpet/CarpetSettings.java | 28 +++++++++++++-- .../carpet/helpers/QuasiConnectivity.java | 24 +++++++++++++ .../carpet/mixins/DispenserBlock_qcMixin.java | 34 +++++++++++-------- .../mixins/PistonBaseBlock_qcMixin.java | 34 +++++++++---------- 4 files changed, 86 insertions(+), 34 deletions(-) create mode 100644 src/main/java/carpet/helpers/QuasiConnectivity.java diff --git a/src/main/java/carpet/CarpetSettings.java b/src/main/java/carpet/CarpetSettings.java index 0a2cee9df6..1e4849cf83 100644 --- a/src/main/java/carpet/CarpetSettings.java +++ b/src/main/java/carpet/CarpetSettings.java @@ -341,8 +341,32 @@ public String description() { ) public static boolean antiCheatDisabled = false; - @Rule(desc = "Pistons, droppers and dispensers react if block above them is powered", category = CREATIVE) - public static boolean quasiConnectivity = true; + private static class QuasiConnectivityValidator extends Validator { + + @Override + public Integer validate(CommandSourceStack source, CarpetRule changingRule, Integer newValue, String userInput) { + int minRange = 0; + int maxRange = 1; + + if (source == null) { + maxRange = Integer.MAX_VALUE; + } else { + for (Level level : source.getServer().getAllLevels()) { + maxRange = Math.max(maxRange, level.getHeight() - 1); + } + } + + return (newValue >= minRange && newValue <= maxRange) ? newValue : null; + } + } + + @Rule( + desc = "Pistons, droppers, and dispensers check for power to the block(s) above them.", + extra = { "Defines the range at which pistons, droppers, and dispensers check for 'quasi power'." }, + category = CREATIVE, + validate = QuasiConnectivityValidator.class + ) + public static int quasiConnectivity = 1; @Rule( desc = "Players can flip and rotate blocks when holding cactus", diff --git a/src/main/java/carpet/helpers/QuasiConnectivity.java b/src/main/java/carpet/helpers/QuasiConnectivity.java new file mode 100644 index 0000000000..0f8d221e34 --- /dev/null +++ b/src/main/java/carpet/helpers/QuasiConnectivity.java @@ -0,0 +1,24 @@ +package carpet.helpers; + +import carpet.CarpetSettings; + +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.Level; + +public class QuasiConnectivity { + + public static boolean hasQuasiSignal(Level level, BlockPos pos) { + for (int i = 1; i <= CarpetSettings.quasiConnectivity; i++) { + BlockPos above = pos.above(i); + + if (level.isOutsideBuildHeight(above)) { + break; + } + if (level.hasNeighborSignal(above)) { + return true; + } + } + + return false; + } +} diff --git a/src/main/java/carpet/mixins/DispenserBlock_qcMixin.java b/src/main/java/carpet/mixins/DispenserBlock_qcMixin.java index 69d0ecfd4a..6444c1a6d7 100644 --- a/src/main/java/carpet/mixins/DispenserBlock_qcMixin.java +++ b/src/main/java/carpet/mixins/DispenserBlock_qcMixin.java @@ -1,25 +1,29 @@ package carpet.mixins; -import carpet.CarpetSettings; -import net.minecraft.core.BlockPos; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.DispenserBlock; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; +import carpet.helpers.QuasiConnectivity; + +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.DispenserBlock; +import net.minecraft.world.level.block.state.BlockState; + @Mixin(DispenserBlock.class) -public class DispenserBlock_qcMixin -{ - @Redirect(method = "neighborChanged", at = @At( +public class DispenserBlock_qcMixin { + + @Redirect( + method = "neighborChanged", + at = @At( value = "INVOKE", - target = "Lnet/minecraft/world/level/Level;hasNeighborSignal(Lnet/minecraft/core/BlockPos;)Z", - ordinal = 1 - )) - private boolean checkUpPower(Level world, BlockPos blockPos_1) - { - if (!CarpetSettings.quasiConnectivity) - return false; - return world.hasNeighborSignal(blockPos_1); + ordinal = 1, + target = "Lnet/minecraft/world/level/Level;hasNeighborSignal(Lnet/minecraft/core/BlockPos;)Z" + ) + ) + private boolean carpet_hasQuasiSignal(Level _level, BlockPos above, BlockState state, Level level, BlockPos pos, Block neighborBlock, BlockPos neighborPos, boolean movedByPiston) { + return QuasiConnectivity.hasQuasiSignal(level, pos); } } diff --git a/src/main/java/carpet/mixins/PistonBaseBlock_qcMixin.java b/src/main/java/carpet/mixins/PistonBaseBlock_qcMixin.java index 74d46e1f4c..87ee3b4f1d 100644 --- a/src/main/java/carpet/mixins/PistonBaseBlock_qcMixin.java +++ b/src/main/java/carpet/mixins/PistonBaseBlock_qcMixin.java @@ -1,29 +1,29 @@ package carpet.mixins; -import carpet.CarpetSettings; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.piston.PistonBaseBlock; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; +import carpet.helpers.QuasiConnectivity; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.piston.PistonBaseBlock; + @Mixin(PistonBaseBlock.class) -public class PistonBaseBlock_qcMixin -{ - @Inject(method = "getNeighborSignal", cancellable = true, at = @At( +public class PistonBaseBlock_qcMixin { + + @Inject( + method = "getNeighborSignal", + cancellable = true, + at = @At( value = "INVOKE", target = "Lnet/minecraft/core/BlockPos;above()Lnet/minecraft/core/BlockPos;" - )) - private void cancelUpCheck(Level world_1, BlockPos blockPos_1, Direction direction_1, CallbackInfoReturnable cir) - { - if (!CarpetSettings.quasiConnectivity) - { - cir.setReturnValue(false); - cir.cancel(); - } + ) + ) + private void carpet_checkQuasiSignal(Level level, BlockPos pos, Direction facing, CallbackInfoReturnable cir) { + cir.setReturnValue(QuasiConnectivity.hasQuasiSignal(level, pos)); } - } From 009d97158402cf8911a430123d1cf5239b340dfd Mon Sep 17 00:00:00 2001 From: senseiwells <66843746+senseiwells@users.noreply.github.com> Date: Wed, 25 Jan 2023 16:40:18 +0000 Subject: [PATCH 031/233] Add rule to make the World Border update with ticks instead of real time (#1550) --- src/main/java/carpet/CarpetSettings.java | 44 +++++ .../carpet/mixins/WorldBorder_tickMixin.java | 25 +++ .../patches/TickSyncedBorderExtent.java | 168 ++++++++++++++++++ src/main/resources/carpet.accesswidener | 4 + src/main/resources/carpet.mixins.json | 1 + 5 files changed, 242 insertions(+) create mode 100644 src/main/java/carpet/mixins/WorldBorder_tickMixin.java create mode 100644 src/main/java/carpet/patches/TickSyncedBorderExtent.java diff --git a/src/main/java/carpet/CarpetSettings.java b/src/main/java/carpet/CarpetSettings.java index 1e4849cf83..92dc919f67 100644 --- a/src/main/java/carpet/CarpetSettings.java +++ b/src/main/java/carpet/CarpetSettings.java @@ -27,6 +27,8 @@ import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.entity.StructureBlockEntity; import net.minecraft.world.level.block.piston.PistonStructureResolver; +import net.minecraft.world.level.border.BorderStatus; +import net.minecraft.world.level.border.WorldBorder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -1068,6 +1070,48 @@ public String description() { ) public static int sculkSensorRange = 8; + /** + * Listener, we need to update world borders to change whether + * they are currently moving in real time or in game time. + */ + private static class WorldBorderValidator extends Validator + { + @Override + public Boolean validate(CommandSourceStack source, CarpetRule changingRule, Boolean newValue, String userInput) + { + if (changingRule.value() ^ newValue) + { + // Needed for the update + tickSyncedWorldBorders = newValue; + MinecraftServer server = CarpetServer.minecraft_server; + if (server == null) + { + return newValue; + } + for (ServerLevel level : server.getAllLevels()) + { + WorldBorder worldBorder = level.getWorldBorder(); + if (worldBorder.getStatus() != BorderStatus.STATIONARY) + { + double from = worldBorder.getSize(); + double to = worldBorder.getLerpTarget(); + long time = worldBorder.getLerpRemainingTime(); + worldBorder.lerpSizeBetween(from, to, time); + } + } + } + return newValue; + } + } + + @Rule( + desc = "Makes world borders move based on in game time instead of real time", + extra = "This has the effect that when the tick rate changes the world border speed also changes proportional to it", + category = FEATURE, + validate = WorldBorderValidator.class + ) + public static boolean tickSyncedWorldBorders = false; + public enum FungusFixMode { FALSE, RANDOM, ALL; } diff --git a/src/main/java/carpet/mixins/WorldBorder_tickMixin.java b/src/main/java/carpet/mixins/WorldBorder_tickMixin.java new file mode 100644 index 0000000000..fe80ab623c --- /dev/null +++ b/src/main/java/carpet/mixins/WorldBorder_tickMixin.java @@ -0,0 +1,25 @@ +package carpet.mixins; + +import carpet.CarpetSettings; +import carpet.patches.TickSyncedBorderExtent; +import net.minecraft.world.level.border.WorldBorder; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(WorldBorder.class) +public class WorldBorder_tickMixin +{ + @Shadow private WorldBorder.BorderExtent extent; + + @Inject(method = "lerpSizeBetween", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/border/WorldBorder;getListeners()Ljava/util/List;")) + private void getExtent(double d, double e, long l, CallbackInfo ci) + { + if (d != e && CarpetSettings.tickSyncedWorldBorders) + { + this.extent = new TickSyncedBorderExtent((WorldBorder) (Object) this, l, d, e); + } + } +} diff --git a/src/main/java/carpet/patches/TickSyncedBorderExtent.java b/src/main/java/carpet/patches/TickSyncedBorderExtent.java new file mode 100644 index 0000000000..f0c87319f3 --- /dev/null +++ b/src/main/java/carpet/patches/TickSyncedBorderExtent.java @@ -0,0 +1,168 @@ +package carpet.patches; + +import carpet.CarpetServer; +import carpet.helpers.TickSpeed; +import net.minecraft.server.MinecraftServer; +import net.minecraft.util.Mth; +import net.minecraft.world.level.border.BorderChangeListener; +import net.minecraft.world.level.border.BorderStatus; +import net.minecraft.world.level.border.WorldBorder; +import net.minecraft.world.phys.shapes.BooleanOp; +import net.minecraft.world.phys.shapes.Shapes; +import net.minecraft.world.phys.shapes.VoxelShape; +import org.jetbrains.annotations.NotNull; + +import java.util.Arrays; + +/** + * This class is essentially a copy of {@link net.minecraft.world.level.border.WorldBorder.MovingBorderExtent} + * but instead of using real time to lerp the border + * this class uses the in game ticks. + */ +@SuppressWarnings("JavadocReference") +public class TickSyncedBorderExtent implements WorldBorder.BorderExtent +{ + private final WorldBorder border; + private final long realDuration; + private final double tickDuration; + private final double from; + private final double to; + + private int ticks; + + public TickSyncedBorderExtent(WorldBorder border, long realDuration, double from, double to) + { + this.border = border; + this.realDuration = realDuration; + this.tickDuration = realDuration / 50.0; + this.from = from; + this.to = to; + this.ticks = 0; + } + + @Override + public double getMinX() + { + int maxSize = this.border.getAbsoluteMaxSize(); + return Mth.clamp(this.border.getCenterX() - this.getSize() / 2.0, -maxSize, maxSize); + } + + @Override + public double getMaxX() + { + int maxSize = this.border.getAbsoluteMaxSize(); + return Mth.clamp(this.border.getCenterX() + this.getSize() / 2.0, -maxSize, maxSize); + } + + @Override + public double getMinZ() + { + int maxSize = this.border.getAbsoluteMaxSize(); + return Mth.clamp(this.border.getCenterZ() - this.getSize() / 2.0, -maxSize, maxSize); + } + + @Override + public double getMaxZ() + { + int maxSize = this.border.getAbsoluteMaxSize(); + return Mth.clamp(this.border.getCenterZ() + this.getSize() / 2.0, -maxSize, maxSize); + } + + @Override + public double getSize() + { + double progress = this.ticks / this.tickDuration; + return progress < 1.0 ? Mth.lerp(progress, this.from, this.to) : this.to; + } + + @Override + public double getLerpSpeed() + { + return Math.abs(this.from - this.to) / this.realDuration; + } + + @Override + public long getLerpRemainingTime() + { + // Rough estimation + MinecraftServer server = CarpetServer.minecraft_server; + double ms; + if (server == null) + { + ms = TickSpeed.mspt; + } + else + { + ms = Arrays.stream(server.tickTimes).average().orElseThrow(IllegalStateException::new) * 1.0E-6D; + } + double tps = 1_000.0D / Math.max((TickSpeed.time_warp_start_time != 0) ? 0.0 : TickSpeed.mspt, ms); + return (long) ((this.tickDuration - this.ticks) / tps * 1_000); + } + + @Override + public double getLerpTarget() + { + return this.to; + } + + @NotNull + @Override + public BorderStatus getStatus() + { + return this.to < this.from ? BorderStatus.SHRINKING : BorderStatus.GROWING; + } + + @Override + public void onAbsoluteMaxSizeChange() + { + + } + + @Override + public void onCenterChange() + { + + } + + @NotNull + @Override + public WorldBorder.BorderExtent update() + { + if (this.ticks++ % 20 == 0) + { + // We need to update any listeners + // Most importantly those that send updates to the client + // This is because the client logic uses real time + // So if the tick speed has changed we need to tell the client + for (BorderChangeListener listener : this.border.getListeners()) + { + // We do not want to update DelegateBorderChangeListener + // This updates borders in other dimensions + if (!(listener instanceof BorderChangeListener.DelegateBorderChangeListener)) + { + listener.onBorderSizeLerping(this.border, this.from, this.to, this.realDuration); + } + } + } + + return this.ticks >= this.tickDuration ? this.border.new StaticBorderExtent(this.to) : this; + } + + @NotNull + @Override + public VoxelShape getCollisionShape() + { + return Shapes.join( + Shapes.INFINITY, + Shapes.box( + Math.floor(this.getMinX()), + Double.NEGATIVE_INFINITY, + Math.floor(this.getMinZ()), + Math.ceil(this.getMaxX()), + Double.POSITIVE_INFINITY, + Math.ceil(this.getMaxZ()) + ), + BooleanOp.ONLY_FIRST + ); + } +} diff --git a/src/main/resources/carpet.accesswidener b/src/main/resources/carpet.accesswidener index 903db44003..e33690214a 100644 --- a/src/main/resources/carpet.accesswidener +++ b/src/main/resources/carpet.accesswidener @@ -4,7 +4,11 @@ accessible class net/minecraft/server/level/ChunkMap$DistanceManager accessible class net/minecraft/server/level/ThreadedLevelLightEngine$TaskType accessible class net/minecraft/world/item/crafting/Ingredient$Value accessible class net/minecraft/world/level/lighting/BlockLightSectionStorage$BlockDataLayerStorageMap +accessible class net/minecraft/world/level/border/WorldBorder$BorderExtent +accessible class net/minecraft/world/level/border/WorldBorder$StaticBorderExtent accessible class net/minecraft/server/MinecraftServer$ReloadableResources accessible class net/minecraft/world/level/biome/Biome$ClimateSettings +accessible method net/minecraft/world/level/border/WorldBorder getListeners ()Ljava/util/List; + accessible field net/minecraft/world/level/block/state/BlockBehaviour UPDATE_SHAPE_ORDER [Lnet/minecraft/core/Direction; diff --git a/src/main/resources/carpet.mixins.json b/src/main/resources/carpet.mixins.json index f154e797d7..aae9683cde 100644 --- a/src/main/resources/carpet.mixins.json +++ b/src/main/resources/carpet.mixins.json @@ -38,6 +38,7 @@ "ChunkMap_tickMixin", "DistanceManager_tickMixin", "ServerFunctionManager_tickMixin", + "WorldBorder_tickMixin", "ChunkMap_scarpetChunkCreationMixin", "LevelEntityGetterAdapter_scarpetMixin", "ChunkHolder_scarpetChunkCreationMixin", From 6adccfd46ace8e9d0e103fdd453cdf1480167e29 Mon Sep 17 00:00:00 2001 From: altrisi Date: Wed, 25 Jan 2023 17:54:49 +0100 Subject: [PATCH 032/233] Some minor cleanup in CarpetServer - Fully remove late registration handling - That removes the reference to the command dispatcher - Fix displaced comment - Simplify "don't mixin to register" checking --- src/main/java/carpet/CarpetServer.java | 18 ++++-------------- 1 file changed, 4 insertions(+), 14 deletions(-) diff --git a/src/main/java/carpet/CarpetServer.java b/src/main/java/carpet/CarpetServer.java index 930ddff62b..ea0f34c3b1 100644 --- a/src/main/java/carpet/CarpetServer.java +++ b/src/main/java/carpet/CarpetServer.java @@ -42,12 +42,10 @@ public class CarpetServer // static for now - easier to handle all around the code, its one anyways { public static MinecraftServer minecraft_server; - private static CommandDispatcher currentCommandDispatcher; public static CarpetScriptServer scriptServer; public static carpet.settings.SettingsManager settingsManager; // to change type to api type, can't change right now because of binary and source compat public static final List extensions = new ArrayList<>(); - // Separate from onServerLoaded, because a server can be loaded multiple times in singleplayer /** * Registers a {@link CarpetExtension} to be managed by Carpet.
* Should be called before Carpet's startup, like in Fabric Loader's @@ -58,22 +56,16 @@ public static void manageExtension(CarpetExtension extension) { extensions.add(extension); // Stop the stupid practice of extensions mixing into Carpet just to register themselves - if (StackWalker.getInstance().walk(stream -> stream.anyMatch(el -> - el.getClassName() == CarpetServer.class.getName() && !el.getMethodName().equals("manageExtension") - ))) { + if (StackWalker.getInstance().walk(stream -> stream.skip(1) + .anyMatch(el -> el.getClassName() == CarpetServer.class.getName()))) + { CarpetSettings.LOG.warn(""" Extension '%s' is registering itself using a mixin into Carpet instead of a regular ModInitializer! This is stupid and will crash the game in future versions!""".formatted(extension.getClass().getSimpleName())); } - - // for extensions that come late to the party, we used to handle them, but we've been giving them warnings about - // it for a while. Cause a crash - if (currentCommandDispatcher != null) - { - throw new IllegalStateException("Extension %s tried to register too late!".formatted(extension.getClass().getSimpleName())); - } } + // Separate from onServerLoaded, because a server can be loaded multiple times in singleplayer // Gets called by Fabric Loader from a ServerModInitializer and a ClientModInitializer, in both to allow extensions // to register before this call in a ModInitializer (declared in fabric.mod.json) public static void onGameStarted() @@ -150,7 +142,6 @@ public static void registerCarpetCommands(CommandDispatcher extensions.forEach(e -> { e.registerCommands(dispatcher, commandBuildContext); }); - currentCommandDispatcher = dispatcher; if (environment != Commands.CommandSelection.DEDICATED) PerfCommand.register(dispatcher); @@ -191,7 +182,6 @@ public static void onServerClosed(MinecraftServer server) if (scriptServer != null) scriptServer.onClose(); scriptServer = null; ServerNetworkHandler.close(); - currentCommandDispatcher = null; LoggerRegistry.stopLoggers(); HUDController.resetScarpetHUDs(); From ea88c09c42edf78f54985baeab03b15bdb72f4b7 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Sat, 28 Jan 2023 19:20:44 +0100 Subject: [PATCH 033/233] cached access to worldgen noise functions --- .../java/carpet/script/api/WorldAccess.java | 69 +++++++++---------- 1 file changed, 34 insertions(+), 35 deletions(-) diff --git a/src/main/java/carpet/script/api/WorldAccess.java b/src/main/java/carpet/script/api/WorldAccess.java index 44fb1a09de..5e983124f4 100644 --- a/src/main/java/carpet/script/api/WorldAccess.java +++ b/src/main/java/carpet/script/api/WorldAccess.java @@ -39,10 +39,10 @@ import com.mojang.brigadier.exceptions.CommandSyntaxException; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import it.unimi.dsi.fastutil.longs.LongSet; +import net.minecraft.Util; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.Holder; -import net.minecraft.core.HolderLookup; import net.minecraft.core.HolderSet; import net.minecraft.core.QuartPos; import net.minecraft.core.Registry; @@ -57,7 +57,7 @@ import net.minecraft.world.level.levelgen.RandomState; import net.minecraft.world.level.levelgen.structure.Structure; import net.minecraft.world.level.levelgen.structure.StructureType; -import net.minecraft.world.level.levelgen.synth.NormalNoise; +import org.apache.commons.lang3.tuple.Pair; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; @@ -71,6 +71,7 @@ import java.util.Optional; import java.util.function.BiFunction; import java.util.function.BiPredicate; +import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -1633,33 +1634,14 @@ else if (ticket == TicketType.POST_TELEPORT) // post teleport } - @ScarpetFunction(maxParams = -1) - public Value compute_density_function(Context c, @Locator.Block BlockPos pos, String... densityFunctionQueries) { - - Map result = new HashMap<>(); - - ServerLevel level = ((CarpetContext) c).level(); - Registry densityFunctionRegistry = level.registryAccess().registryOrThrow(Registries.DENSITY_FUNCTION); - - if (densityFunctionQueries.length == 0) { - return ListValue.wrap(densityFunctionRegistry.keySet().stream().map(ValueConversions::of)); - } - - ChunkGenerator chunkGenerator = level.getChunkSource().getGenerator(); - if (!(chunkGenerator instanceof NoiseBasedChunkGenerator generator)) { - return MapValue.wrap(result); - } - - RandomState randomState = RandomState.create( - generator.generatorSettings().value(), - level.registryAccess().lookupOrThrow(Registries.NOISE), level.getSeed() - ); + public static Function, Function> stupidWorldgenNoiseCacheGetter = Util.memoize(pair -> { + ServerLevel level = pair.getKey(); + String densityFunctionQuery = pair.getValue(); + ChunkGenerator generator = level.getChunkSource().getGenerator(); - DensityFunction.Visitor visitor = ((RandomStateVisitorAccessor) (Object) randomState).getVisitor(); - DensityFunction.SinglePointContext singlePointContext = new DensityFunction.SinglePointContext(pos.getX(), pos.getY(), pos.getZ()); - NoiseRouter router = generator.generatorSettings().value().noiseRouter(); - - for (String densityFunctionQuery : densityFunctionQueries) { + if (generator instanceof NoiseBasedChunkGenerator noiseBasedChunkGenerator) { + Registry densityFunctionRegistry = level.registryAccess().registryOrThrow(Registries.DENSITY_FUNCTION); + final NoiseRouter router = noiseBasedChunkGenerator.generatorSettings().value().noiseRouter(); DensityFunction densityFunction = switch (densityFunctionQuery) { case "barrier_noise" -> router.barrierNoise(); case "fluid_level_floodedness_noise" -> router.fluidLevelFloodednessNoise(); @@ -1684,18 +1666,35 @@ public Value compute_density_function(Context c, @Locator.Block BlockPos pos, St } throw new InternalExpressionException( - "Density function '" + densityFunctionQuery + "' doesn't exist. " + - "Please check the spelling or use with full 'namespace:value' if its custom defined." + "Density function '" + densityFunctionQuery + "' doesn't exist. " + + "Please check the spelling or use with full 'namespace:value' if its custom defined." ); } }; - if (densityFunction == null) // IDE thinks may be null as Registry.get is Nullable, but we checked it - throw new IllegalStateException("density function can't be null here"); + RandomState randomState = RandomState.create( + noiseBasedChunkGenerator.generatorSettings().value(), + level.registryAccess().lookupOrThrow(Registries.NOISE), level.getSeed() + ); + DensityFunction.Visitor visitor = ((RandomStateVisitorAccessor) (Object) randomState).getVisitor(); + + DensityFunction temp = densityFunction.mapAll(visitor); + + return pos -> temp.compute(new DensityFunction.SinglePointContext(pos.getX(), pos.getY(), pos.getZ())); + } + return origin -> 0.0; + }); - double value = densityFunction.mapAll(visitor).compute(singlePointContext); - result.put(StringValue.of(densityFunctionQuery), new NumericValue(value)); + @ScarpetFunction(maxParams = -1) + public Value compute_density_function(Context c, @Locator.Block BlockPos pos, String... densityFunctionQueries) { + final CarpetContext cc = (CarpetContext) c; + if (densityFunctionQueries.length == 0) { + return ListValue.wrap(cc.registry(Registries.DENSITY_FUNCTION).keySet().stream().map(ValueConversions::of)); + } + final ServerLevel level = cc.level(); + if (densityFunctionQueries.length == 1) { + return NumericValue.of(stupidWorldgenNoiseCacheGetter.apply(Pair.of(level, densityFunctionQueries[0])).apply(pos)); } - return MapValue.wrap(result); + return ListValue.wrap(Arrays.stream(densityFunctionQueries).map(s -> NumericValue.of(stupidWorldgenNoiseCacheGetter.apply(Pair.of(level, s)).apply(pos)))); } } From 659f0106e32c6d8e99bc0a4d8f709e47958f8d29 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Sat, 28 Jan 2023 19:51:13 +0100 Subject: [PATCH 034/233] renamed compute_density_function with 'sample_density' and tweaked its use --- docs/scarpet/api/BlocksAndWorldAccess.md | 47 ++++++------------- docs/scarpet/resources/editors/idea/2.txt | 2 +- .../scarpet/resources/editors/npp/scarpet.xml | 2 +- .../java/carpet/script/api/WorldAccess.java | 36 +++++++------- 4 files changed, 35 insertions(+), 52 deletions(-) diff --git a/docs/scarpet/api/BlocksAndWorldAccess.md b/docs/scarpet/api/BlocksAndWorldAccess.md index 883fd87b9a..76a55997f8 100644 --- a/docs/scarpet/api/BlocksAndWorldAccess.md +++ b/docs/scarpet/api/BlocksAndWorldAccess.md @@ -509,47 +509,28 @@ Returns the map colour of a block at position. One of: `'brown_terracotta'`, `'green_terracotta'`, `'red_terracotta'`, `'black_terracotta'`, `'crimson_nylium'`, `'crimson_stem'`, `'crimson_hyphae'`, `'warped_nylium'`, `'warped_stem'`, `'warped_hyphae'`, `'warped_wart'` -### `compute_density_function(pos, ...types?)` 1.19+ only +### `sample_density()`, `sample_density(pos, ... types?)` 1.19+ -**Note: Replaces the old `sample_noise` function** +**Note: Replaces the old defunct `sample_noise` function** -Computes the density function(s) on the given position. Check the [Available Types](#available-types) for list of available density functions. +Samples the density function(s) / worldgen noise values at a given position. -If no types are passed in, it returns a list of all the available density functions. Built-in and custom ones. +If no types are passed in, or no arguments are given, it returns a list of all the available registry defined density functions. + +Function accepts any registry defined density functions, both built in, as well as namespaced defined in datapacks. +On top of that, scarpet provides the following list of functions for convenience (not returned with no-argument call): + +`'barrier_noise'`, `'fluid_level_floodedness_noise'`, `'fluid_level_spread_noise'`, `'lava_noise'`, +`'temperature'`, `'vegetation'`, `'continents'`, `'erosion'`, `'depth'`, `'ridges'`, +`'initial_density_without_jaggedness'`, `'final_density'`, `'vein_toggle'`, `'vein_ridged'` and `'vein_gap'`
+// requesting single value
+sample_density(pos, 'continents') => 0.211626790923
 // passing type as multiple arguments
-compute_density_function(pos, 'continents', 'depth') => {continents: -0.205013844481, depth: 1.04772473438}
-// passing types as a list with unpacking operator
-compute_density_function(pos, ...['ridges', 'overworld/caves/pillars']) => {ridges: -0.186052125186, overworld/caves/pillars: 0.211626790923}
-// Custom Defined types
-compute_density_function(pos, 'mydatapack:my_density_func') => {mydatapack:my_density_func: -0.186052125186}
+sample_density(pos, 'continents', 'depth', 'overworld/caves/pillars', 'mydatapack:foo/my_function') => [-0.205013844481, 1.04772473438, 0.211626790923, 0.123]
 
-#### Available types: - -##### Built-in - -`'barrier_noise'`, `'continents'`, `'depth'`, `'end/base_3d_noise'`, `'end/sloped_cheese'`, `'erosion'`, `'final_density'`, -`'fluid_level_floodedness_noise'`, `'fluid_level_spread_noise'`, `'initial_density_without_jaggedness'`, `'lava_noise'`, -`'nether/base_3d_noise'`, `'overworld/base_3d_noise'`, `'overworld/base_continents'`, `'overworld/caves/entrances'`, -`'overworld/caves/noodle'`, `'overworld/caves/pillars'`, `'overworld/caves/spaghetti_2d'`, `'overworld/caves/spaghetti_2d_thickness_modulator'`, -`'overworld/caves/spaghetti_roughness_function'`, `'overworld/continents'`, `'overworld/depth'`, `'overworld/erosion'`, -`'overworld/factor'`, `'overworld/jaggedness'`, `'overworld/offset'`, `'overworld/ridges'`, `'overworld/ridges_folded'`, -`'overworld/sloped_cheese'`, `'overworld_amplified/depth'`, `'overworld_amplified/factor'`, `'overworld_amplified/jaggedness'`, -`'overworld_amplified/offset'`, `'overworld_amplified/sloped_cheese'`, `'overworld_large_biomes/base_continents'`, -`'overworld_large_biomes/continents'`, `'overworld_large_biomes/depth'`, `'overworld_large_biomes/erosion'`, -`'overworld_large_biomes/factor'`, `'overworld_large_biomes/jaggedness'`, `'overworld_large_biomes/offset'`, -`'overworld_large_biomes/sloped_cheese'`, `'ridges'`, `'shift_x'`, `'shift_z'`, `'temperature'`, `'vegetation'`, -`'vein_gap'`, `'vein_gapbarrier_noise'`, `'vein_ridged'`, `'vein_toggle'`, `'y'`, `'zero'` - -##### Custom - -Custom defined density functions from datapacks are also available and can be used. However, unlike built-in types, these -ones must use full namespace. i.e. `namespace:path`. Examples: `'mydatapack:density_function'`, `'mydatapack:nested/density_function'` - -**Note: Custom density functions require a server relaunch after enabling the datapack.** - ### `loaded(pos)` Boolean function, true if the block is accessible for the game mechanics. Normally `scarpet` doesn't check if operates diff --git a/docs/scarpet/resources/editors/idea/2.txt b/docs/scarpet/resources/editors/idea/2.txt index e26ea19d53..e87e81ee63 100644 --- a/docs/scarpet/resources/editors/idea/2.txt +++ b/docs/scarpet/resources/editors/idea/2.txt @@ -93,7 +93,7 @@ reload_chunk remove_all_markers reset_chunk run -compute_density_function +sample_density save scan schedule diff --git a/docs/scarpet/resources/editors/npp/scarpet.xml b/docs/scarpet/resources/editors/npp/scarpet.xml index 3f3b6b0a53..8e09742c95 100644 --- a/docs/scarpet/resources/editors/npp/scarpet.xml +++ b/docs/scarpet/resources/editors/npp/scarpet.xml @@ -57,7 +57,7 @@ hardness blast_resistance top loaded suffocates power ticks_randomly update block_tick random_tick in_slime_chunk set without_updates blocks_movement block_sound material map_colour block_state block_list block_tags block_data poi set_poi - place_item set_biome biome loaded_status generation_status compute_density_function inhabited_time spawn_potential chunk_tickets + place_item set_biome biome loaded_status generation_status sample_density inhabited_time spawn_potential chunk_tickets plop harvest destroy create_explosion structure_eligibility structures structure_references set_structure reset_chunk reload_chunk create_datapack diff --git a/src/main/java/carpet/script/api/WorldAccess.java b/src/main/java/carpet/script/api/WorldAccess.java index 5e983124f4..969d971c9a 100644 --- a/src/main/java/carpet/script/api/WorldAccess.java +++ b/src/main/java/carpet/script/api/WorldAccess.java @@ -1632,6 +1632,24 @@ else if (ticket == TicketType.POST_TELEPORT) // post teleport return new NumericValue(ticket.timeout()); }); + expression.addContextFunction("sample_density", -1, (c, t, lv) -> + { + final CarpetContext cc = (CarpetContext) c; + if (lv.size() == 0) { + return ListValue.wrap(cc.registry(Registries.DENSITY_FUNCTION).keySet().stream().map(ValueConversions::of)); + } + final ServerLevel level = cc.level(); + final BlockArgument locator = BlockArgument.findIn(cc, lv, 0); + final BlockPos pos = locator.block.getPos(); + final String[] densityFunctionQueries = lv.stream().skip(locator.offset).map(Value::getString).toArray(String[]::new); + if (densityFunctionQueries.length == 0) { + return ListValue.wrap(cc.registry(Registries.DENSITY_FUNCTION).keySet().stream().map(ValueConversions::of)); + } + if (densityFunctionQueries.length == 1) { + return NumericValue.of(stupidWorldgenNoiseCacheGetter.apply(Pair.of(level, densityFunctionQueries[0])).apply(pos)); + } + return ListValue.wrap(Arrays.stream(densityFunctionQueries).map(s -> NumericValue.of(stupidWorldgenNoiseCacheGetter.apply(Pair.of(level, s)).apply(pos)))); + }); } public static Function, Function> stupidWorldgenNoiseCacheGetter = Util.memoize(pair -> { @@ -1665,10 +1683,7 @@ else if (ticket == TicketType.POST_TELEPORT) // post teleport yield densityFunctionRegistry.get(densityFunctionKey); } - throw new InternalExpressionException( - "Density function '" + densityFunctionQuery + "' doesn't exist. " + - "Please check the spelling or use with full 'namespace:value' if its custom defined." - ); + throw new InternalExpressionException("Density function '" + densityFunctionQuery + "' is not defined in the registies."); } }; @@ -1684,17 +1699,4 @@ else if (ticket == TicketType.POST_TELEPORT) // post teleport } return origin -> 0.0; }); - - @ScarpetFunction(maxParams = -1) - public Value compute_density_function(Context c, @Locator.Block BlockPos pos, String... densityFunctionQueries) { - final CarpetContext cc = (CarpetContext) c; - if (densityFunctionQueries.length == 0) { - return ListValue.wrap(cc.registry(Registries.DENSITY_FUNCTION).keySet().stream().map(ValueConversions::of)); - } - final ServerLevel level = cc.level(); - if (densityFunctionQueries.length == 1) { - return NumericValue.of(stupidWorldgenNoiseCacheGetter.apply(Pair.of(level, densityFunctionQueries[0])).apply(pos)); - } - return ListValue.wrap(Arrays.stream(densityFunctionQueries).map(s -> NumericValue.of(stupidWorldgenNoiseCacheGetter.apply(Pair.of(level, s)).apply(pos)))); - } } From ec2b56183a929f13f56839bd9b11ff453512d648 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Sat, 28 Jan 2023 19:54:41 +0100 Subject: [PATCH 035/233] renamed compute_density_function with 'sample_density' and tweaked its use --- docs/scarpet/api/BlocksAndWorldAccess.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/scarpet/api/BlocksAndWorldAccess.md b/docs/scarpet/api/BlocksAndWorldAccess.md index 76a55997f8..28f75b5d13 100644 --- a/docs/scarpet/api/BlocksAndWorldAccess.md +++ b/docs/scarpet/api/BlocksAndWorldAccess.md @@ -520,6 +520,8 @@ If no types are passed in, or no arguments are given, it returns a list of all t Function accepts any registry defined density functions, both built in, as well as namespaced defined in datapacks. On top of that, scarpet provides the following list of functions for convenience (not returned with no-argument call): +With a single function name passed in, it returns a scalar. With multiple function names passed in, it returns a list of results. + `'barrier_noise'`, `'fluid_level_floodedness_noise'`, `'fluid_level_spread_noise'`, `'lava_noise'`, `'temperature'`, `'vegetation'`, `'continents'`, `'erosion'`, `'depth'`, `'ridges'`, `'initial_density_without_jaggedness'`, `'final_density'`, `'vein_toggle'`, `'vein_ridged'` and `'vein_gap'` From 2133675ac72699c23a77b15036853836ec4c11c6 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Mon, 30 Jan 2023 18:02:08 +0100 Subject: [PATCH 036/233] renamed sample_density with 'sample_noise'. sample noise values directly from the local router if possible. --- docs/scarpet/api/BlocksAndWorldAccess.md | 11 ++-- docs/scarpet/resources/editors/idea/2.txt | 2 +- .../scarpet/resources/editors/npp/scarpet.xml | 2 +- .../java/carpet/script/api/WorldAccess.java | 52 ++++++++++++++++--- 4 files changed, 53 insertions(+), 14 deletions(-) diff --git a/docs/scarpet/api/BlocksAndWorldAccess.md b/docs/scarpet/api/BlocksAndWorldAccess.md index 28f75b5d13..e900466eaa 100644 --- a/docs/scarpet/api/BlocksAndWorldAccess.md +++ b/docs/scarpet/api/BlocksAndWorldAccess.md @@ -509,18 +509,17 @@ Returns the map colour of a block at position. One of: `'brown_terracotta'`, `'green_terracotta'`, `'red_terracotta'`, `'black_terracotta'`, `'crimson_nylium'`, `'crimson_stem'`, `'crimson_hyphae'`, `'warped_nylium'`, `'warped_stem'`, `'warped_hyphae'`, `'warped_wart'` -### `sample_density()`, `sample_density(pos, ... types?)` 1.19+ +### `sample_noise()`, `sample_noise(pos, ... types?)` 1.18+ -**Note: Replaces the old defunct `sample_noise` function** - -Samples the density function(s) / worldgen noise values at a given position. +Samples the world generation noise values / data driven density function(s) at a given position. If no types are passed in, or no arguments are given, it returns a list of all the available registry defined density functions. +With a single function name passed in, it returns a scalar. With multiple function names passed in, it returns a list of results. + Function accepts any registry defined density functions, both built in, as well as namespaced defined in datapacks. -On top of that, scarpet provides the following list of functions for convenience (not returned with no-argument call): +On top of that, scarpet provides the following list of noises sampled directly from the current level (and not returned with no-argument call): -With a single function name passed in, it returns a scalar. With multiple function names passed in, it returns a list of results. `'barrier_noise'`, `'fluid_level_floodedness_noise'`, `'fluid_level_spread_noise'`, `'lava_noise'`, `'temperature'`, `'vegetation'`, `'continents'`, `'erosion'`, `'depth'`, `'ridges'`, diff --git a/docs/scarpet/resources/editors/idea/2.txt b/docs/scarpet/resources/editors/idea/2.txt index e87e81ee63..d90729fda0 100644 --- a/docs/scarpet/resources/editors/idea/2.txt +++ b/docs/scarpet/resources/editors/idea/2.txt @@ -93,7 +93,7 @@ reload_chunk remove_all_markers reset_chunk run -sample_density +sample_noise save scan schedule diff --git a/docs/scarpet/resources/editors/npp/scarpet.xml b/docs/scarpet/resources/editors/npp/scarpet.xml index 8e09742c95..8d84d458b7 100644 --- a/docs/scarpet/resources/editors/npp/scarpet.xml +++ b/docs/scarpet/resources/editors/npp/scarpet.xml @@ -57,7 +57,7 @@ hardness blast_resistance top loaded suffocates power ticks_randomly update block_tick random_tick in_slime_chunk set without_updates blocks_movement block_sound material map_colour block_state block_list block_tags block_data poi set_poi - place_item set_biome biome loaded_status generation_status sample_density inhabited_time spawn_potential chunk_tickets + place_item set_biome biome loaded_status generation_status sample_noise inhabited_time spawn_potential chunk_tickets plop harvest destroy create_explosion structure_eligibility structures structure_references set_structure reset_chunk reload_chunk create_datapack diff --git a/src/main/java/carpet/script/api/WorldAccess.java b/src/main/java/carpet/script/api/WorldAccess.java index 969d971c9a..44d3d5e8e9 100644 --- a/src/main/java/carpet/script/api/WorldAccess.java +++ b/src/main/java/carpet/script/api/WorldAccess.java @@ -52,6 +52,7 @@ import net.minecraft.world.level.chunk.ChunkGenerator; import net.minecraft.world.level.chunk.PalettedContainer; import net.minecraft.world.level.levelgen.DensityFunction; +import net.minecraft.world.level.levelgen.DensityFunctions; import net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator; import net.minecraft.world.level.levelgen.NoiseRouter; import net.minecraft.world.level.levelgen.RandomState; @@ -1632,7 +1633,7 @@ else if (ticket == TicketType.POST_TELEPORT) // post teleport return new NumericValue(ticket.timeout()); }); - expression.addContextFunction("sample_density", -1, (c, t, lv) -> + expression.addContextFunction("sample_noise", -1, (c, t, lv) -> { final CarpetContext cc = (CarpetContext) c; if (lv.size() == 0) { @@ -1645,14 +1646,53 @@ else if (ticket == TicketType.POST_TELEPORT) // post teleport if (densityFunctionQueries.length == 0) { return ListValue.wrap(cc.registry(Registries.DENSITY_FUNCTION).keySet().stream().map(ValueConversions::of)); } + NoiseRouter router = level.getChunkSource().randomState().router(); if (densityFunctionQueries.length == 1) { - return NumericValue.of(stupidWorldgenNoiseCacheGetter.apply(Pair.of(level, densityFunctionQueries[0])).apply(pos)); + return NumericValue.of(sampleNoise(router, level, densityFunctionQueries[0], pos)); } - return ListValue.wrap(Arrays.stream(densityFunctionQueries).map(s -> NumericValue.of(stupidWorldgenNoiseCacheGetter.apply(Pair.of(level, s)).apply(pos)))); + return ListValue.wrap(Arrays.stream(densityFunctionQueries).map(s -> NumericValue.of(sampleNoise(router, level, s, pos)))); }); } - public static Function, Function> stupidWorldgenNoiseCacheGetter = Util.memoize(pair -> { + public static double sampleNoise(NoiseRouter router, ServerLevel level, String what, BlockPos pos) { + DensityFunction densityFunction = switch (what) { + case "barrier_noise" -> router.barrierNoise(); + case "fluid_level_floodedness_noise" -> router.fluidLevelFloodednessNoise(); + case "fluid_level_spread_noise" -> router.fluidLevelSpreadNoise(); + case "lava_noise" -> router.lavaNoise(); + case "temperature" -> router.temperature(); + case "vegetation" -> router.vegetation(); + case "continents" -> router.continents(); + case "erosion" -> router.erosion(); + case "depth" -> router.depth(); + case "ridges" -> router.ridges(); + case "initial_density_without_jaggedness" -> router.initialDensityWithoutJaggedness(); + case "final_density" -> router.finalDensity(); + case "vein_toggle" -> router.veinToggle(); + case "vein_ridged" -> router.veinRidged(); + case "vein_gap" -> router.veinGap(); + default -> stupidWorldgenNoiseCacheGetter.apply(Pair.of(level, what)); + /*ResourceLocation densityFunctionKey = InputValidator.identifierOf(what); + Registry densityFunctionRegistry = level.registryAccess().registryOrThrow(Registries.DENSITY_FUNCTION); + if (densityFunctionRegistry.containsKey(densityFunctionKey) && level.getChunkSource().getGenerator() instanceof NoiseBasedChunkGenerator noiseBasedChunkGenerator) { + DensityFunction densityFunction1 = densityFunctionRegistry.get(densityFunctionKey); + RandomState randomState = RandomState.create( + noiseBasedChunkGenerator.generatorSettings().value(), + level.registryAccess().lookupOrThrow(Registries.NOISE), level.getSeed() + ); + DensityFunction.Visitor visitor = ((RandomStateVisitorAccessor) (Object) randomState).getVisitor(); + + DensityFunction temp = densityFunction.mapAll(visitor); + } + + throw new InternalExpressionException("Density function '" + what + "' is not defined in the registies.");*/ + + }; + return densityFunction.compute(new DensityFunction.SinglePointContext(pos.getX(), pos.getY(), pos.getZ())); + } + + // to be used with future seedable noise + public static Function, DensityFunction> stupidWorldgenNoiseCacheGetter = Util.memoize(pair -> { ServerLevel level = pair.getKey(); String densityFunctionQuery = pair.getValue(); ChunkGenerator generator = level.getChunkSource().getGenerator(); @@ -1695,8 +1735,8 @@ else if (ticket == TicketType.POST_TELEPORT) // post teleport DensityFunction temp = densityFunction.mapAll(visitor); - return pos -> temp.compute(new DensityFunction.SinglePointContext(pos.getX(), pos.getY(), pos.getZ())); + return temp; } - return origin -> 0.0; + return DensityFunctions.zero(); }); } From d49be89e23c5e4a99962f248b352bc87a11e5249 Mon Sep 17 00:00:00 2001 From: vlad2305m <43315575+vlad2305m@users.noreply.github.com> Date: Tue, 31 Jan 2023 21:39:37 +0100 Subject: [PATCH 037/233] Do not load clientside-only classes in serverside ShapeDispatcher code (#1642) fixed use of client side classes in shape dispatcher --- .../carpet/script/utils/ShapeDispatcher.java | 18 ++++++++---------- .../carpet/script/utils/ShapesRenderer.java | 8 ++++---- 2 files changed, 12 insertions(+), 14 deletions(-) diff --git a/src/main/java/carpet/script/utils/ShapeDispatcher.java b/src/main/java/carpet/script/utils/ShapeDispatcher.java index 601631e500..787c24a651 100644 --- a/src/main/java/carpet/script/utils/ShapeDispatcher.java +++ b/src/main/java/carpet/script/utils/ShapeDispatcher.java @@ -22,8 +22,6 @@ import carpet.script.value.ValueConversions; import com.google.common.collect.Sets; -import com.mojang.blaze3d.vertex.VertexFormat; -import com.mojang.blaze3d.vertex.VertexFormat.Mode; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.Registry; @@ -763,7 +761,7 @@ public static class Polyface extends ExpiringShape public long calcKey(final RegistryAccess regs){ long hash = super.calcKey(regs); hash ^= 6; hash *= 1099511628211L; - hash ^= mode.hashCode(); hash *= 1099511628211L; + hash ^= mode; hash *= 1099511628211L; hash ^= relative.hashCode(); hash *= 1099511628211L; for (Vec3 i :vertex_list){ hash ^= vec3dhash(i); @@ -784,7 +782,7 @@ ArrayList alter_point(ServerPlayer p){ } alter_point=new ArrayList<>(); switch (mode) { - case TRIANGLES: + case 4: for (int i=0;i alter_point(ServerPlayer p){ alter_draw_triangles(vecA, vecB, vecC); } break; - case TRIANGLE_FAN: + case 6: Vec3 vec0=vertex_list.get(0); if(relative.get(0)){ vec0=relativiseRender(p.level, vec0, 0); @@ -821,7 +819,7 @@ ArrayList alter_point(ServerPlayer p){ vec1=vec; } break; - case TRIANGLE_STRIP: + case 5: Vec3 vecA=vertex_list.get(0); if(relative.get(0)){ vecA=relativiseRender(p.level, vecA, 0); @@ -886,7 +884,7 @@ public Consumer alternative() { @Override protected Set optionalParams() { return Sets.union(super.optionalParams(), optional.keySet()); } ArrayList vertex_list=new ArrayList<>(); - Mode mode; + int mode; ArrayList relative=new ArrayList<>(); boolean inneredges; @Override @@ -907,11 +905,11 @@ protected void init(Map options, RegistryAccess regs) inneredges=false; } if("polygon".equals(_mode)){ - mode=VertexFormat.Mode.TRIANGLE_FAN; + mode=6; }else if("strip".equals(_mode)){ - mode=VertexFormat.Mode.TRIANGLE_STRIP; + mode=5; }else if("triangles".equals(_mode)){ - mode=VertexFormat.Mode.TRIANGLES; + mode=4; if(vertex_list.size()%3!=0){ throw new IllegalArgumentException("Unexpected vertex list size: " + vertex_list.size()); } diff --git a/src/main/java/carpet/script/utils/ShapesRenderer.java b/src/main/java/carpet/script/utils/ShapesRenderer.java index 574803ad70..8eca33e2f5 100644 --- a/src/main/java/carpet/script/utils/ShapesRenderer.java +++ b/src/main/java/carpet/script/utils/ShapesRenderer.java @@ -563,7 +563,7 @@ public void renderFaces(Tesselator tessellator, BufferBuilder bufferBuilder, dou else RenderSystem.enableCull(); - bufferBuilder.begin(shape.mode, DefaultVertexFormat.POSITION_COLOR); + bufferBuilder.begin(VertexFormat.Mode.values()[shape.mode], DefaultVertexFormat.POSITION_COLOR); for(int i=0;i Date: Tue, 31 Jan 2023 21:54:34 +0100 Subject: [PATCH 038/233] fixed use of client side classes in shape dispatcher --- src/main/java/carpet/script/utils/ShapesRenderer.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/java/carpet/script/utils/ShapesRenderer.java b/src/main/java/carpet/script/utils/ShapesRenderer.java index 8eca33e2f5..ae431fcdec 100644 --- a/src/main/java/carpet/script/utils/ShapesRenderer.java +++ b/src/main/java/carpet/script/utils/ShapesRenderer.java @@ -549,6 +549,9 @@ public void renderLines(PoseStack matrices, Tesselator tessellator, BufferBuilde } public static class RenderedPolyface extends RenderedShape { + private static final VertexFormat.Mode[] faceIndices = new VertexFormat.Mode[]{ + Mode.LINES, Mode.LINE_STRIP, Mode.DEBUG_LINES, Mode.DEBUG_LINE_STRIP, Mode.TRIANGLES, Mode.TRIANGLE_STRIP, Mode.TRIANGLE_FAN, Mode.QUADS}; + public RenderedPolyface(Minecraft client, ShapeDispatcher.ExpiringShape shape) { super(client, (ShapeDispatcher.Polyface)shape); @@ -563,7 +566,7 @@ public void renderFaces(Tesselator tessellator, BufferBuilder bufferBuilder, dou else RenderSystem.enableCull(); - bufferBuilder.begin(VertexFormat.Mode.values()[shape.mode], DefaultVertexFormat.POSITION_COLOR); + bufferBuilder.begin(faceIndices[shape.mode], DefaultVertexFormat.POSITION_COLOR); for(int i=0;i Date: Wed, 1 Feb 2023 20:26:46 +0100 Subject: [PATCH 039/233] 1.4.96 --- gradle.properties | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/gradle.properties b/gradle.properties index d380b9add8..02f4665861 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,12 +4,12 @@ org.gradle.jvmargs=-Xmx1G # Fabric Properties # check these on https://fabricmc.net/use # or better: https://modmuss50.me/fabric.html - minecraft_version=23w04a + minecraft_version=23w05a loader_version=0.14.13 - fabric_version=0.73.1+1.19.4 + fabric_version=0.73.3+1.19.4 # Mod Properties - mod_version = 1.4.95 + mod_version = 1.4.96 maven_group = carpet archives_base_name = fabric-carpet @@ -19,10 +19,10 @@ org.gradle.jvmargs=-Xmx1G # Can also be the version ID directly coming from https://minecraft.curseforge.com/api/game/versions?token=[API_TOKEN] release-curse-versions = Minecraft 1.19:1.19.4 # Whether or not to build another branch on release - release-extra-branch = false + release-extra-branch = true # The name of the second branch to release - release-extra-branch-name = future + release-extra-branch-name = hotfix # The "name" or id of the Curseforge version for the secondary branch # This is needed because CF uses too vague names for snapshots # Can also be the version ID directly coming from https://minecraft.curseforge.com/api/game/versions?token=[API_TOKEN] - release-extra-curse-version = Minecraft 1.19:1.19.4 \ No newline at end of file + release-extra-curse-version = Minecraft 1.19:1.19.3 \ No newline at end of file From 07deaceb3742de2af0b2911242c9b01f4829f04d Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Wed, 1 Feb 2023 19:57:35 +0000 Subject: [PATCH 040/233] Merge docs for 'Carpet Mod 1.4.96 for Minecraft 23w05a and 1.19.3' --- docs/scarpet/Full.md | 36 +++++++++++++++++------------------- 1 file changed, 17 insertions(+), 19 deletions(-) diff --git a/docs/scarpet/Full.md b/docs/scarpet/Full.md index 72390719c0..f77fda7084 100644 --- a/docs/scarpet/Full.md +++ b/docs/scarpet/Full.md @@ -2834,30 +2834,28 @@ Returns the map colour of a block at position. One of: `'brown_terracotta'`, `'green_terracotta'`, `'red_terracotta'`, `'black_terracotta'`, `'crimson_nylium'`, `'crimson_stem'`, `'crimson_hyphae'`, `'warped_nylium'`, `'warped_stem'`, `'warped_hyphae'`, `'warped_wart'` -### `sample_noise(pos, ...type?)` 1.18+ only +### `sample_noise()`, `sample_noise(pos, ... types?)` 1.18+ - Samples the multi noise value(s) on the given position. -If no type is passed, returns a map of `continentalness`, `depth`, `erosion`, `humidity`, `temperature`, `weirdness`. -Otherwise, returns the map of that specific noise. +Samples the world generation noise values / data driven density function(s) at a given position. -
-// without type
-sample_noise(pos) => {continentalness: 0.445300012827, erosion: 0.395399987698, temperature: 0.165399998426, ...}
-// passing type as multiple arguments
-sample_noise(pos, 'pillarRareness', 'aquiferBarrier') => {aquiferBarrier: -0.205013844481, pillarRareness: 1.04772473438}
-// passing types as a list with unpacking operator
-sample_noise(pos, ...['spaghetti3dFirst', 'spaghetti3dSecond']) => {spaghetti3dFirst: -0.186052125186, spaghetti3dSecond: 0.211626790923}
-
+If no types are passed in, or no arguments are given, it returns a list of all the available registry defined density functions. + +With a single function name passed in, it returns a scalar. With multiple function names passed in, it returns a list of results. -Available types: +Function accepts any registry defined density functions, both built in, as well as namespaced defined in datapacks. +On top of that, scarpet provides the following list of noises sampled directly from the current level (and not returned with no-argument call): -`aquiferBarrier`, `aquiferFluidLevelFloodedness`, `aquiferFluidLevelSpread`, `aquiferLava`, `caveCheese`, -`caveEntrance`, `caveLayer`, `continentalness`, `depth`, `erosion`, `humidity`, `island`, `jagged`, `oreGap`, -`pillar`, `pillarRareness`, `pillarThickness`, `shiftX`, `shiftY`, `shiftZ`, `spaghetti2d`, `spaghetti2dElevation`, -`spaghetti2dModulator`, `spaghetti2dThickness`, `spaghetti3d`, `spaghetti3dFirst`, `spaghetti3dRarity`, -`spaghetti3dSecond`, `spaghetti3dThickness`, `spaghettiRoughness`, `spaghettiRoughnessModulator`, `temperature`, -`terrain`, `terrainFactor`, `terrainOffset`, `terrainPeaks`, `weirdness` +`'barrier_noise'`, `'fluid_level_floodedness_noise'`, `'fluid_level_spread_noise'`, `'lava_noise'`, +`'temperature'`, `'vegetation'`, `'continents'`, `'erosion'`, `'depth'`, `'ridges'`, +`'initial_density_without_jaggedness'`, `'final_density'`, `'vein_toggle'`, `'vein_ridged'` and `'vein_gap'` + +
+// requesting single value
+sample_density(pos, 'continents') => 0.211626790923
+// passing type as multiple arguments
+sample_density(pos, 'continents', 'depth', 'overworld/caves/pillars', 'mydatapack:foo/my_function') => [-0.205013844481, 1.04772473438, 0.211626790923, 0.123]
+
### `loaded(pos)` From cad80f82c6e0ff76debbeea3c3140ff3a0808da3 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Thu, 2 Feb 2023 07:50:23 +0100 Subject: [PATCH 041/233] don't publish extra next time --- gradle.properties | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gradle.properties b/gradle.properties index 02f4665861..cc97e2cb16 100644 --- a/gradle.properties +++ b/gradle.properties @@ -19,9 +19,9 @@ org.gradle.jvmargs=-Xmx1G # Can also be the version ID directly coming from https://minecraft.curseforge.com/api/game/versions?token=[API_TOKEN] release-curse-versions = Minecraft 1.19:1.19.4 # Whether or not to build another branch on release - release-extra-branch = true + release-extra-branch = false # The name of the second branch to release - release-extra-branch-name = hotfix + release-extra-branch-name = hotfixx # The "name" or id of the Curseforge version for the secondary branch # This is needed because CF uses too vague names for snapshots # Can also be the version ID directly coming from https://minecraft.curseforge.com/api/game/versions?token=[API_TOKEN] From 8f6127160666d6c2688a145a8ffdaed3f0cca65b Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Sat, 4 Feb 2023 13:26:21 +0100 Subject: [PATCH 042/233] semi-auto cleanup --- .../java/carpet/script/CarpetContext.java | 10 +- .../java/carpet/script/CarpetEventServer.java | 845 +++++--- .../java/carpet/script/CarpetExpression.java | 72 +- .../java/carpet/script/CarpetScriptHost.java | 711 ++++--- .../carpet/script/CarpetScriptServer.java | 276 +-- src/main/java/carpet/script/Context.java | 73 +- .../java/carpet/script/EntityEventsGroup.java | 97 +- src/main/java/carpet/script/Expression.java | 849 ++++---- src/main/java/carpet/script/Fluff.java | 136 +- src/main/java/carpet/script/LazyValue.java | 26 +- src/main/java/carpet/script/Module.java | 98 +- src/main/java/carpet/script/ScriptHost.java | 317 +-- src/main/java/carpet/script/ScriptServer.java | 3 +- src/main/java/carpet/script/Tokenizer.java | 162 +- .../script/annotation/AnnotationParser.java | 88 +- .../script/annotation/ListConverter.java | 28 +- .../carpet/script/annotation/Locator.java | 82 +- .../script/annotation/MapConverter.java | 51 +- .../script/annotation/OptionalConverter.java | 22 +- .../script/annotation/OutputConverter.java | 18 +- .../java/carpet/script/annotation/Param.java | 46 +- .../script/annotation/ScarpetFunction.java | 2 +- .../annotation/SimpleTypeConverter.java | 13 +- .../carpet/script/annotation/ValueCaster.java | 13 +- .../script/annotation/ValueConverter.java | 41 +- .../java/carpet/script/api/Auxiliary.java | 927 +++++---- .../carpet/script/api/BlockIterators.java | 281 +-- src/main/java/carpet/script/api/Entities.java | 274 +-- .../java/carpet/script/api/Inventories.java | 438 +++-- .../java/carpet/script/api/Monitoring.java | 50 +- .../java/carpet/script/api/Scoreboards.java | 750 +++++--- .../java/carpet/script/api/Threading.java | 39 +- .../java/carpet/script/api/WorldAccess.java | 1376 ++++++------- .../java/carpet/script/argument/Argument.java | 1 + .../carpet/script/argument/BlockArgument.java | 46 +- .../carpet/script/argument/FileArgument.java | 495 +++-- .../script/argument/FunctionArgument.java | 80 +- .../script/argument/Vector3Argument.java | 39 +- .../script/command/CommandArgument.java | 593 +++--- .../carpet/script/command/CommandToken.java | 82 +- .../script/exception/BreakStatement.java | 2 +- .../exception/CarpetExpressionException.java | 11 +- .../script/exception/ContinueStatement.java | 2 +- .../script/exception/ExitStatement.java | 3 +- .../script/exception/ExpressionException.java | 32 +- .../script/exception/IntegrityException.java | 2 +- .../InternalExpressionException.java | 18 +- .../script/exception/LoadException.java | 14 +- .../exception/ProcessedThrowStatement.java | 10 +- .../script/exception/ReturnStatement.java | 3 +- .../exception/StacklessRuntimeException.java | 12 +- .../script/exception/ThrowStatement.java | 21 +- .../carpet/script/exception/Throwables.java | 61 +- .../carpet/script/language/Arithmetic.java | 103 +- .../carpet/script/language/ControlFlow.java | 88 +- .../script/language/DataStructures.java | 274 +-- .../carpet/script/language/Functions.java | 70 +- .../java/carpet/script/language/Loops.java | 322 ++-- .../carpet/script/language/Operators.java | 463 +++-- src/main/java/carpet/script/language/Sys.java | 233 ++- .../carpet/script/language/Threading.java | 57 +- .../carpet/script/utils/AppStoreManager.java | 277 ++- .../java/carpet/script/utils/BiomeInfo.java | 17 +- .../script/utils/EquipmentInventory.java | 45 +- .../java/carpet/script/utils/GlocalFlag.java | 18 +- .../carpet/script/utils/InputValidator.java | 16 +- .../script/utils/PerlinNoiseSampler.java | 201 +- .../script/utils/ScarpetJsonDeserializer.java | 35 +- .../carpet/script/utils/ShapeDispatcher.java | 1713 +++++++++++------ .../carpet/script/utils/ShapesRenderer.java | 906 +++++---- .../script/utils/SimplexNoiseSampler.java | 198 +- .../script/utils/SnoopyCommandSource.java | 75 +- .../java/carpet/script/utils/SystemInfo.java | 134 +- .../java/carpet/script/utils/WorldTools.java | 72 +- .../script/utils/shapes/ShapeDirection.java | 15 +- .../script/value/AbstractListValue.java | 14 +- .../java/carpet/script/value/BlockValue.java | 181 +- .../carpet/script/value/BooleanValue.java | 32 +- .../script/value/ContainerValueInterface.java | 6 +- .../java/carpet/script/value/EntityValue.java | 1312 +++++++------ .../script/value/FormattedTextValue.java | 61 +- .../carpet/script/value/FrameworkValue.java | 2 +- .../script/value/FunctionAnnotationValue.java | 8 +- .../script/value/FunctionSignatureValue.java | 12 +- .../value/FunctionUnpackedArgumentsValue.java | 6 +- .../carpet/script/value/FunctionValue.java | 150 +- .../carpet/script/value/LContainerValue.java | 17 +- .../carpet/script/value/LazyListValue.java | 87 +- .../java/carpet/script/value/ListValue.java | 333 ++-- .../java/carpet/script/value/MapValue.java | 127 +- .../script/value/NBTSerializableValue.java | 480 +++-- .../java/carpet/script/value/NullValue.java | 45 +- .../carpet/script/value/NumericValue.java | 232 +-- .../java/carpet/script/value/ScreenValue.java | 420 ++-- .../java/carpet/script/value/StringValue.java | 17 +- .../java/carpet/script/value/ThreadValue.java | 72 +- .../java/carpet/script/value/UndefValue.java | 40 +- src/main/java/carpet/script/value/Value.java | 165 +- .../carpet/script/value/ValueConversions.java | 362 ++-- 99 files changed, 11355 insertions(+), 7899 deletions(-) diff --git a/src/main/java/carpet/script/CarpetContext.java b/src/main/java/carpet/script/CarpetContext.java index cfb21effd5..0455c1c5a2 100644 --- a/src/main/java/carpet/script/CarpetContext.java +++ b/src/main/java/carpet/script/CarpetContext.java @@ -18,11 +18,12 @@ public class CarpetContext extends Context public CommandSourceStack s; private final BlockPos origin; - public CarpetContext(CarpetScriptHost host, CommandSourceStack source) { + public CarpetContext(final CarpetScriptHost host, final CommandSourceStack source) + { this(host, source, BlockPos.ZERO); } - public CarpetContext(ScriptHost host, CommandSourceStack source, BlockPos origin) + public CarpetContext(final ScriptHost host, final CommandSourceStack source, final BlockPos origin) { super(host); s = source; @@ -59,7 +60,8 @@ public RegistryAccess registryAccess() return s.getLevel().registryAccess(); } - public Registry registry(ResourceKey> resourceKey) { + public Registry registry(final ResourceKey> resourceKey) + { return registryAccess().registryOrThrow(resourceKey); } @@ -73,7 +75,7 @@ public BlockPos origin() return origin; } - public void swapSource(CommandSourceStack source) + public void swapSource(final CommandSourceStack source) { s = source; } diff --git a/src/main/java/carpet/script/CarpetEventServer.java b/src/main/java/carpet/script/CarpetEventServer.java index 3c84663de0..96a198778c 100644 --- a/src/main/java/carpet/script/CarpetEventServer.java +++ b/src/main/java/carpet/script/CarpetEventServer.java @@ -22,6 +22,7 @@ import carpet.utils.CarpetProfiler; import carpet.utils.Messenger; import com.mojang.brigadier.exceptions.CommandSyntaxException; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -40,6 +41,7 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; + import net.minecraft.commands.CommandSourceStack; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -92,27 +94,31 @@ public static class Callback public final FunctionValue function; public final List parametrizedArgs; - public Callback(String host, String target, FunctionValue function, List parametrizedArgs) + public Callback(final String host, final String target, final FunctionValue function, final List parametrizedArgs) { this.host = host; this.function = function; this.optionalTarget = target; - this.parametrizedArgs = parametrizedArgs==null?NOARGS:parametrizedArgs; + this.parametrizedArgs = parametrizedArgs == null ? NOARGS : parametrizedArgs; } /** * Used also in entity events - * @param sender - entity command source + * + * @param sender - entity command source * @param runtimeArgs = options */ - public CallbackResult execute(CommandSourceStack sender, List runtimeArgs) + public CallbackResult execute(final CommandSourceStack sender, List runtimeArgs) { if (!this.parametrizedArgs.isEmpty()) { runtimeArgs = new ArrayList<>(runtimeArgs); runtimeArgs.addAll(this.parametrizedArgs); } - if (CarpetServer.scriptServer == null) return CallbackResult.FAIL; // already stopped + if (CarpetServer.scriptServer == null) + { + return CallbackResult.FAIL; // already stopped + } return CarpetServer.scriptServer.events.runEventCall( sender.withPermission(CarpetSettings.runPermissionLevel), host, optionalTarget, function, runtimeArgs); @@ -120,31 +126,33 @@ public CallbackResult execute(CommandSourceStack sender, List runtimeArgs /** * Used also in entity events - * @param sender - sender of the signal + * + * @param sender - sender of the signal * @param optionalRecipient - optional target player argument - * @param runtimeArgs = options + * @param runtimeArgs = options */ - public CallbackResult signal(CommandSourceStack sender, ServerPlayer optionalRecipient, List runtimeArgs) + public CallbackResult signal(final CommandSourceStack sender, final ServerPlayer optionalRecipient, final List runtimeArgs) { // recipent of the call doesn't match the handlingHost - if (optionalRecipient != null && !optionalRecipient.getScoreboardName().equals(optionalTarget)) - return CallbackResult.FAIL; - return execute(sender, runtimeArgs); + return optionalRecipient != null && !optionalRecipient.getScoreboardName().equals(optionalTarget) ? CallbackResult.FAIL : execute(sender, runtimeArgs); } @Override public String toString() { - return function.getString()+((host==null)?"":"(from "+host+(optionalTarget == null?"":"/"+optionalTarget)+")"); + return function.getString() + ((host == null) ? "" : "(from " + host + (optionalTarget == null ? "" : "/" + optionalTarget) + ")"); + } + + public record Signature(String function, String host, String target) + { } - public static record Signature(String function, String host, String target) {} - - public static Signature fromString(String str) + + public static Signature fromString(final String str) { - Pattern find = Pattern.compile("(\\w+)(?:\\(from (\\w+)(?:/(\\w+))?\\))?"); - Matcher matcher = find.matcher(str); - if(matcher.matches()) + final Pattern find = Pattern.compile("(\\w+)(?:\\(from (\\w+)(?:/(\\w+))?\\))?"); + final Matcher matcher = find.matcher(str); + if (matcher.matches()) { return new Signature(matcher.group(1), matcher.group(2), matcher.group(3)); } @@ -158,7 +166,7 @@ public static class ScheduledCall extends Callback private final CarpetContext ctx; public long dueTime; - public ScheduledCall(CarpetContext context, FunctionValue function, List args, long dueTime) + public ScheduledCall(final CarpetContext context, final FunctionValue function, final List args, final long dueTime) { // ignoring target as we will be always calling self super(context.host.getName(), null, function, args); @@ -186,7 +194,7 @@ public static class CallbackList final boolean isSystem; final boolean perPlayerDistribution; - public CallbackList(int reqArgs, boolean isSystem, boolean isGlobalOnly) + public CallbackList(final int reqArgs, final boolean isSystem, final boolean isGlobalOnly) { this.callList = new ArrayList<>(); this.removedCalls = new ArrayList<>(); @@ -202,7 +210,7 @@ public List inspectCurrentCalls() return new ArrayList<>(callList); } - private void removeCallsIf(Predicate when) + private void removeCallsIf(final Predicate when) { if (!inCall && !inSignal) { @@ -212,34 +220,38 @@ private void removeCallsIf(Predicate when) // we are ok with list growing in the meantime and parallel access, we are only scanning. for (int i = 0; i < callList.size(); i++) { - Callback call = callList.get(i); - if (when.test(call)) removedCalls.add(call); + final Callback call = callList.get(i); + if (when.test(call)) + { + removedCalls.add(call); + } } } /** * Handles only built-in events from the events system + * * @param argumentSupplier * @param cmdSourceSupplier * @return Whether this event call has been cancelled */ - public boolean call(Supplier> argumentSupplier, Supplier cmdSourceSupplier) + public boolean call(final Supplier> argumentSupplier, final Supplier cmdSourceSupplier) { - if (callList.size() > 0 && CarpetServer.scriptServer != null) + if (!callList.isEmpty() && CarpetServer.scriptServer != null) { - Boolean isCancelled = CarpetServer.scriptServer.events.handleEvents.runIfEnabled( () -> { - CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet events", CarpetProfiler.TYPE.GENERAL); - List argv = argumentSupplier.get(); // empty for onTickDone - CommandSourceStack source; + final Boolean isCancelled = CarpetServer.scriptServer.events.handleEvents.runIfEnabled(() -> { + final CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet events", CarpetProfiler.TYPE.GENERAL); + final List argv = argumentSupplier.get(); // empty for onTickDone + final CommandSourceStack source; try { source = cmdSourceSupplier.get(); } - catch (NullPointerException noReference) // todo figure out what happens when closing. + catch (final NullPointerException noReference) // todo figure out what happens when closing. { return false; } - String nameCheck = perPlayerDistribution ? source.getTextName() : null; + final String nameCheck = perPlayerDistribution ? source.getTextName() : null; assert argv.size() == reqArgs; boolean cancelled = false; try @@ -249,23 +261,33 @@ public boolean call(Supplier> argumentSupplier, Supplier> argumentSupplier, Supplier callArg) + public int signal(final CommandSourceStack sender, final ServerPlayer optinoalReceipient, final List callArg) { - if (callList.isEmpty()) return 0; + if (callList.isEmpty()) + { + return 0; + } int successes = 0; try { @@ -285,7 +310,10 @@ public int signal(CommandSourceStack sender, ServerPlayer optinoalReceipient, Li for (int i = 0; i < callList.size(); i++) { // skipping tracking of fails, its explicit call - if (callList.get(i).signal(sender, optinoalReceipient, callArg) == CallbackResult.SUCCESS) successes++; + if (callList.get(i).signal(sender, optinoalReceipient, callArg) == CallbackResult.SUCCESS) + { + successes++; + } } } finally @@ -295,21 +323,21 @@ public int signal(CommandSourceStack sender, ServerPlayer optinoalReceipient, Li return successes; } - public boolean addFromExternal(CommandSourceStack source, String hostName, String funName, Consumer hostOnEventHandler) + public boolean addFromExternal(final CommandSourceStack source, final String hostName, final String funName, final Consumer hostOnEventHandler) { - ScriptHost host = CarpetServer.scriptServer.getAppHostByName(hostName); + final ScriptHost host = CarpetServer.scriptServer.getAppHostByName(hostName); if (host == null) { // impossible call to add - Messenger.m(source, "r Unknown app "+hostName); + Messenger.m(source, "r Unknown app " + hostName); return false; } hostOnEventHandler.accept(host); - FunctionValue udf = host.getFunction(funName); + final FunctionValue udf = host.getFunction(funName); if (udf == null || udf.getArguments().size() != reqArgs) { // call won't match arguments - Messenger.m(source, "r Callback doesn't expect required number of arguments: "+reqArgs); + Messenger.m(source, "r Callback doesn't expect required number of arguments: " + reqArgs); return false; } String target = null; @@ -319,7 +347,7 @@ public boolean addFromExternal(CommandSourceStack source, String hostName, Strin { target = source.getPlayerOrException().getScoreboardName(); } - catch (CommandSyntaxException e) + catch (final CommandSyntaxException e) { Messenger.m(source, "r Cannot add event to a player scoped app from a command without a player context"); return false; @@ -332,7 +360,8 @@ public boolean addFromExternal(CommandSourceStack source, String hostName, Strin callList.add(new Callback(hostName, target, udf, null)); return true; } - public boolean addEventCallInternal(ScriptHost host, FunctionValue function, List args) + + public boolean addEventCallInternal(final ScriptHost host, final FunctionValue function, final List args) { if (function == null || (function.getArguments().size() - args.size()) != reqArgs) { @@ -344,27 +373,27 @@ public boolean addEventCallInternal(ScriptHost host, FunctionValue function, Lis return true; } - public void removeEventCall(String hostName, String target, String funName) + public void removeEventCall(final String hostName, final String target, final String funName) { - removeCallsIf((c)-> c.function.getString().equals(funName) + removeCallsIf((c) -> c.function.getString().equals(funName) && (Objects.equals(c.host, hostName)) && (Objects.equals(c.optionalTarget, target)) ); } - public void removeAllCalls(CarpetScriptHost host) + public void removeAllCalls(final CarpetScriptHost host) { - removeCallsIf((c)-> (Objects.equals(c.host, host.getName())) + removeCallsIf((c) -> (Objects.equals(c.host, host.getName())) && (Objects.equals(c.optionalTarget, host.user))); } - public void createChildEvents(CarpetScriptHost host) + public void createChildEvents(final CarpetScriptHost host) { - List copyCalls = new ArrayList<>(); - callList.forEach((c)-> + final List copyCalls = new ArrayList<>(); + callList.forEach((c) -> { if ((Objects.equals(c.host, host.getName())) - && c.optionalTarget == null) + && c.optionalTarget == null) { copyCalls.add(new Callback(c.host, host.user, c.function, c.parametrizedArgs)); } @@ -375,11 +404,15 @@ public void createChildEvents(CarpetScriptHost host) public void clearEverything() { // when some moron puts /reload in an event call. - if (inSignal || inCall) callList = new ArrayList<>(); + if (inSignal || inCall) + { + callList = new ArrayList<>(); + } callList.clear(); } - public void sortByPriority(CarpetScriptServer scriptServer) { + public void sortByPriority(final CarpetScriptServer scriptServer) + { callList.sort(Comparator.comparingDouble(c -> -scriptServer.getAppHostByName(c.host).eventPriority)); } } @@ -387,10 +420,14 @@ public void sortByPriority(CarpetScriptServer scriptServer) { public static class Event { public static final Map byName = new HashMap<>(); - public static List publicEvents(CarpetScriptServer server) + + public static List publicEvents(final CarpetScriptServer server) { - List events = byName.values().stream().filter(e -> e.isPublic).collect(Collectors.toList()); - if (server != null) events.addAll(server.events.customEvents.values()); + final List events = byName.values().stream().filter(e -> e.isPublic).collect(Collectors.toList()); + if (server != null) + { + events.addAll(server.events.customEvents.values()); + } return events; } @@ -453,6 +490,7 @@ public boolean deprecated() { return true; } + @Override public void onTick() { @@ -465,24 +503,22 @@ public void onTick() public static final Event CHUNK_GENERATED = new Event("chunk_generated", 2, true) { @Override - public void onChunkEvent(ServerLevel world, ChunkPos chPos, boolean generated) + public void onChunkEvent(final ServerLevel world, final ChunkPos chPos, final boolean generated) { - handler.call( () -> - { - return Arrays.asList(new NumericValue(chPos.x << 4), new NumericValue(chPos.z << 4)); - }, () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel(world) + handler.call( + () -> Arrays.asList(new NumericValue(chPos.x << 4), new NumericValue(chPos.z << 4)), + () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel(world) ); } }; public static final Event CHUNK_LOADED = new Event("chunk_loaded", 2, true) { @Override - public void onChunkEvent(ServerLevel world, ChunkPos chPos, boolean generated) + public void onChunkEvent(final ServerLevel world, final ChunkPos chPos, final boolean generated) { - handler.call( () -> - { - return Arrays.asList(new NumericValue(chPos.x << 4), new NumericValue(chPos.z << 4)); - }, () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel(world) + handler.call( + () -> Arrays.asList(new NumericValue(chPos.x << 4), new NumericValue(chPos.z << 4)), + () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel(world) ); } }; @@ -490,7 +526,7 @@ public void onChunkEvent(ServerLevel world, ChunkPos chPos, boolean generated) public static final Event CHUNK_UNLOADED = new Event("chunk_unloaded", 2, true) { @Override - public void onChunkEvent(ServerLevel world, ChunkPos chPos, boolean generated) + public void onChunkEvent(final ServerLevel world, final ChunkPos chPos, final boolean generated) { handler.call( () -> Arrays.asList(new NumericValue(chPos.x << 4), new NumericValue(chPos.z << 4)), @@ -502,45 +538,45 @@ public void onChunkEvent(ServerLevel world, ChunkPos chPos, boolean generated) public static final Event PLAYER_JUMPS = new Event("player_jumps", 1, false) { @Override - public boolean onPlayerEvent(ServerPlayer player) + public boolean onPlayerEvent(final ServerPlayer player) { - handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); + handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); return false; } }; public static final Event PLAYER_DEPLOYS_ELYTRA = new Event("player_deploys_elytra", 1, false) { @Override - public boolean onPlayerEvent(ServerPlayer player) + public boolean onPlayerEvent(final ServerPlayer player) { - handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); + handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); return false; } }; public static final Event PLAYER_WAKES_UP = new Event("player_wakes_up", 1, false) { @Override - public boolean onPlayerEvent(ServerPlayer player) + public boolean onPlayerEvent(final ServerPlayer player) { - handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); + handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); return false; } }; public static final Event PLAYER_ESCAPES_SLEEP = new Event("player_escapes_sleep", 1, false) { @Override - public boolean onPlayerEvent(ServerPlayer player) + public boolean onPlayerEvent(final ServerPlayer player) { - handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); + handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); return false; } }; public static final Event PLAYER_RIDES = new Event("player_rides", 5, false) { @Override - public void onMountControls(ServerPlayer player, float strafeSpeed, float forwardSpeed, boolean jumping, boolean sneaking) + public void onMountControls(final ServerPlayer player, final float strafeSpeed, final float forwardSpeed, final boolean jumping, final boolean sneaking) { - handler.call( () -> Arrays.asList(new EntityValue(player), + handler.call(() -> Arrays.asList(new EntityValue(player), new NumericValue(forwardSpeed), new NumericValue(strafeSpeed), BooleanValue.of(jumping), BooleanValue.of(sneaking) ), player::createCommandSourceStack); } @@ -548,45 +584,40 @@ public void onMountControls(ServerPlayer player, float strafeSpeed, float forwar public static final Event PLAYER_USES_ITEM = new Event("player_uses_item", 3, false) { @Override - public boolean onItemAction(ServerPlayer player, InteractionHand enumhand, ItemStack itemstack) + public boolean onItemAction(final ServerPlayer player, final InteractionHand enumhand, final ItemStack itemstack) { - return handler.call( () -> - { - //ItemStack itemstack = player.getStackInHand(enumhand); - return Arrays.asList( - new EntityValue(player), - ValueConversions.of(itemstack, player.getLevel().registryAccess()), - StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand") - ); - }, player::createCommandSourceStack); + return handler.call(() -> + Arrays.asList( + new EntityValue(player), + ValueConversions.of(itemstack, player.getLevel().registryAccess()), + StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand") + ), player::createCommandSourceStack); } }; public static final Event PLAYER_CLICKS_BLOCK = new Event("player_clicks_block", 3, false) { @Override - public boolean onBlockAction(ServerPlayer player, BlockPos blockpos, Direction facing) + public boolean onBlockAction(final ServerPlayer player, final BlockPos blockpos, final Direction facing) { - return handler.call( () -> - { - return Arrays.asList( - new EntityValue(player), - new BlockValue(null, player.getLevel(), blockpos), - StringValue.of(facing.getName()) - ); - }, player::createCommandSourceStack); + return handler.call(() -> + Arrays.asList( + new EntityValue(player), + new BlockValue(null, player.getLevel(), blockpos), + StringValue.of(facing.getName()) + ), player::createCommandSourceStack); } }; public static final Event PLAYER_RIGHT_CLICKS_BLOCK = new Event("player_right_clicks_block", 6, false) { @Override - public boolean onBlockHit(ServerPlayer player, InteractionHand enumhand, BlockHitResult hitRes)//ItemStack itemstack, Hand enumhand, BlockPos blockpos, Direction enumfacing, Vec3d vec3d) + public boolean onBlockHit(final ServerPlayer player, final InteractionHand enumhand, final BlockHitResult hitRes) { - return handler.call( () -> + return handler.call(() -> { - ItemStack itemstack = player.getItemInHand(enumhand); - BlockPos blockpos = hitRes.getBlockPos(); - Direction enumfacing = hitRes.getDirection(); - Vec3 vec3d = hitRes.getLocation().subtract(blockpos.getX(), blockpos.getY(), blockpos.getZ()); + final ItemStack itemstack = player.getItemInHand(enumhand); + final BlockPos blockpos = hitRes.getBlockPos(); + final Direction enumfacing = hitRes.getDirection(); + final Vec3 vec3d = hitRes.getLocation().subtract(blockpos.getX(), blockpos.getY(), blockpos.getZ()); return Arrays.asList( new EntityValue(player), ValueConversions.of(itemstack, player.getLevel().registryAccess()), @@ -605,13 +636,13 @@ public boolean onBlockHit(ServerPlayer player, InteractionHand enumhand, BlockHi public static final Event PLAYER_INTERACTS_WITH_BLOCK = new Event("player_interacts_with_block", 5, false) { @Override - public boolean onBlockHit(ServerPlayer player, InteractionHand enumhand, BlockHitResult hitRes) + public boolean onBlockHit(final ServerPlayer player, final InteractionHand enumhand, final BlockHitResult hitRes) { - handler.call( () -> + handler.call(() -> { - BlockPos blockpos = hitRes.getBlockPos(); - Direction enumfacing = hitRes.getDirection(); - Vec3 vec3d = hitRes.getLocation().subtract(blockpos.getX(), blockpos.getY(), blockpos.getZ()); + final BlockPos blockpos = hitRes.getBlockPos(); + final Direction enumfacing = hitRes.getDirection(); + final Vec3 vec3d = hitRes.getLocation().subtract(blockpos.getX(), blockpos.getY(), blockpos.getZ()); return Arrays.asList( new EntityValue(player), StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand"), @@ -630,9 +661,9 @@ public boolean onBlockHit(ServerPlayer player, InteractionHand enumhand, BlockHi public static final Event PLAYER_PLACING_BLOCK = new Event("player_placing_block", 4, false) { @Override - public boolean onBlockPlaced(ServerPlayer player, BlockPos pos, InteractionHand enumhand, ItemStack itemstack) + public boolean onBlockPlaced(final ServerPlayer player, final BlockPos pos, final InteractionHand enumhand, final ItemStack itemstack) { - return handler.call( () -> Arrays.asList( + return handler.call(() -> Arrays.asList( new EntityValue(player), ValueConversions.of(itemstack, player.getLevel().registryAccess()), StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand"), @@ -643,9 +674,9 @@ public boolean onBlockPlaced(ServerPlayer player, BlockPos pos, InteractionHand public static final Event PLAYER_PLACES_BLOCK = new Event("player_places_block", 4, false) { @Override - public boolean onBlockPlaced(ServerPlayer player, BlockPos pos, InteractionHand enumhand, ItemStack itemstack) + public boolean onBlockPlaced(final ServerPlayer player, final BlockPos pos, final InteractionHand enumhand, final ItemStack itemstack) { - handler.call( () -> Arrays.asList( + handler.call(() -> Arrays.asList( new EntityValue(player), ValueConversions.of(itemstack, player.getLevel().registryAccess()), StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand"), @@ -657,7 +688,7 @@ public boolean onBlockPlaced(ServerPlayer player, BlockPos pos, InteractionHand public static final Event PLAYER_BREAK_BLOCK = new Event("player_breaks_block", 2, false) { @Override - public boolean onBlockBroken(ServerPlayer player, BlockPos pos, BlockState previousBS) + public boolean onBlockBroken(final ServerPlayer player, final BlockPos pos, final BlockState previousBS) { return handler.call( () -> Arrays.asList(new EntityValue(player), new BlockValue(previousBS, player.getLevel(), pos)), @@ -668,22 +699,22 @@ public boolean onBlockBroken(ServerPlayer player, BlockPos pos, BlockState previ public static final Event PLAYER_INTERACTS_WITH_ENTITY = new Event("player_interacts_with_entity", 3, false) { @Override - public boolean onEntityHandAction(ServerPlayer player, Entity entity, InteractionHand enumhand) + public boolean onEntityHandAction(final ServerPlayer player, final Entity entity, final InteractionHand enumhand) { - return handler.call( () -> Arrays.asList( - new EntityValue(player), new EntityValue(entity), StringValue.of(enumhand==InteractionHand.MAIN_HAND?"mainhand":"offhand") + return handler.call(() -> Arrays.asList( + new EntityValue(player), new EntityValue(entity), StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand") ), player::createCommandSourceStack); } }; public static final Event PLAYER_TRADES = new Event("player_trades", 5, false) { @Override - public void onTrade(ServerPlayer player, Merchant merchant, MerchantOffer tradeOffer) + public void onTrade(final ServerPlayer player, final Merchant merchant, final MerchantOffer tradeOffer) { final RegistryAccess regs = player.getLevel().registryAccess(); - handler.call( () -> Arrays.asList( + handler.call(() -> Arrays.asList( new EntityValue(player), - merchant instanceof AbstractVillager ? new EntityValue((AbstractVillager) merchant) : Value.NULL, + merchant instanceof final AbstractVillager villager? new EntityValue(villager) : Value.NULL, ValueConversions.of(tradeOffer.getBaseCostA(), regs), ValueConversions.of(tradeOffer.getCostB(), regs), ValueConversions.of(tradeOffer.getResult(), regs) @@ -693,8 +724,9 @@ public void onTrade(ServerPlayer player, Merchant merchant, MerchantOffer tradeO public static final Event PLAYER_PICKS_UP_ITEM = new Event("player_picks_up_item", 2, false) { @Override - public boolean onItemAction(ServerPlayer player, InteractionHand enumhand, ItemStack itemstack) { - handler.call( () -> Arrays.asList(new EntityValue(player), ValueConversions.of(itemstack, player.getLevel().registryAccess())), player::createCommandSourceStack); + public boolean onItemAction(final ServerPlayer player, final InteractionHand enumhand, final ItemStack itemstack) + { + handler.call(() -> Arrays.asList(new EntityValue(player), ValueConversions.of(itemstack, player.getLevel().registryAccess())), player::createCommandSourceStack); return false; } }; @@ -702,44 +734,44 @@ public boolean onItemAction(ServerPlayer player, InteractionHand enumhand, ItemS public static final Event PLAYER_ATTACKS_ENTITY = new Event("player_attacks_entity", 2, false) { @Override - public boolean onEntityHandAction(ServerPlayer player, Entity entity, InteractionHand enumhand) + public boolean onEntityHandAction(final ServerPlayer player, final Entity entity, final InteractionHand enumhand) { - return handler.call( () -> Arrays.asList(new EntityValue(player), new EntityValue(entity)), player::createCommandSourceStack); + return handler.call(() -> Arrays.asList(new EntityValue(player), new EntityValue(entity)), player::createCommandSourceStack); } }; public static final Event PLAYER_STARTS_SNEAKING = new Event("player_starts_sneaking", 1, false) { @Override - public boolean onPlayerEvent(ServerPlayer player) + public boolean onPlayerEvent(final ServerPlayer player) { - handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); + handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); return false; } }; public static final Event PLAYER_STOPS_SNEAKING = new Event("player_stops_sneaking", 1, false) { @Override - public boolean onPlayerEvent(ServerPlayer player) + public boolean onPlayerEvent(final ServerPlayer player) { - handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); + handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); return false; } }; public static final Event PLAYER_STARTS_SPRINTING = new Event("player_starts_sprinting", 1, false) { @Override - public boolean onPlayerEvent(ServerPlayer player) + public boolean onPlayerEvent(final ServerPlayer player) { - handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); + handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); return false; } }; public static final Event PLAYER_STOPS_SPRINTING = new Event("player_stops_sprinting", 1, false) { @Override - public boolean onPlayerEvent(ServerPlayer player) + public boolean onPlayerEvent(final ServerPlayer player) { - handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); + handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); return false; } }; @@ -747,10 +779,10 @@ public boolean onPlayerEvent(ServerPlayer player) public static final Event PLAYER_RELEASED_ITEM = new Event("player_releases_item", 3, false) { @Override - public boolean onItemAction(ServerPlayer player, InteractionHand enumhand, ItemStack itemstack) + public boolean onItemAction(final ServerPlayer player, final InteractionHand enumhand, final ItemStack itemstack) { // this.getStackInHand(this.getActiveHand()), this.activeItemStack) - handler.call( () -> + handler.call(() -> Arrays.asList( new EntityValue(player), ValueConversions.of(itemstack, player.getLevel().registryAccess()), @@ -762,10 +794,10 @@ public boolean onItemAction(ServerPlayer player, InteractionHand enumhand, ItemS public static final Event PLAYER_FINISHED_USING_ITEM = new Event("player_finishes_using_item", 3, false) { @Override - public boolean onItemAction(ServerPlayer player, InteractionHand enumhand, ItemStack itemstack) + public boolean onItemAction(final ServerPlayer player, final InteractionHand enumhand, final ItemStack itemstack) { // this.getStackInHand(this.getActiveHand()), this.activeItemStack) - return handler.call( () -> + return handler.call(() -> Arrays.asList( new EntityValue(player), ValueConversions.of(itemstack, player.getLevel().registryAccess()), @@ -776,25 +808,25 @@ public boolean onItemAction(ServerPlayer player, InteractionHand enumhand, ItemS public static final Event PLAYER_DROPS_ITEM = new Event("player_drops_item", 1, false) { @Override - public boolean onPlayerEvent(ServerPlayer player) + public boolean onPlayerEvent(final ServerPlayer player) { - return handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); + return handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); } }; public static final Event PLAYER_DROPS_STACK = new Event("player_drops_stack", 1, false) { @Override - public boolean onPlayerEvent(ServerPlayer player) + public boolean onPlayerEvent(final ServerPlayer player) { - return handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); + return handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); } }; public static final Event PLAYER_CHOOSES_RECIPE = new Event("player_chooses_recipe", 3, false) { @Override - public boolean onRecipeSelected(ServerPlayer player, ResourceLocation recipe, boolean fullStack) + public boolean onRecipeSelected(final ServerPlayer player, final ResourceLocation recipe, final boolean fullStack) { - return handler.call( () -> + return handler.call(() -> Arrays.asList( new EntityValue(player), StringValue.of(NBTSerializableValue.nameFromRegistryId(recipe)), @@ -805,10 +837,13 @@ public boolean onRecipeSelected(ServerPlayer player, ResourceLocation recipe, bo public static final Event PLAYER_SWITCHES_SLOT = new Event("player_switches_slot", 3, false) { @Override - public void onSlotSwitch(ServerPlayer player, int from, int to) + public void onSlotSwitch(final ServerPlayer player, final int from, final int to) { - if (from == to) return; // initial slot update - handler.call( () -> + if (from == to) + { + return; // initial slot update + } + handler.call(() -> Arrays.asList( new EntityValue(player), new NumericValue(from), @@ -819,19 +854,19 @@ public void onSlotSwitch(ServerPlayer player, int from, int to) public static final Event PLAYER_SWAPS_HANDS = new Event("player_swaps_hands", 1, false) { @Override - public boolean onPlayerEvent(ServerPlayer player) + public boolean onPlayerEvent(final ServerPlayer player) { - return handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); + return handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); } }; public static final Event PLAYER_SWINGS_HAND = new Event("player_swings_hand", 2, false) { @Override - public void onHandAction(ServerPlayer player, InteractionHand hand) + public void onHandAction(final ServerPlayer player, final InteractionHand hand) { - handler.call( () -> Arrays.asList( - new EntityValue(player), - StringValue.of(hand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand") + handler.call(() -> Arrays.asList( + new EntityValue(player), + StringValue.of(hand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand") ) , player::createCommandSourceStack); } @@ -839,24 +874,24 @@ public void onHandAction(ServerPlayer player, InteractionHand hand) public static final Event PLAYER_TAKES_DAMAGE = new Event("player_takes_damage", 4, false) { @Override - public boolean onDamage(Entity target, float amount, DamageSource source) + public boolean onDamage(final Entity target, final float amount, final DamageSource source) { - return handler.call( () -> + return handler.call(() -> Arrays.asList( - new EntityValue(target), - new NumericValue(amount), - StringValue.of(source.getMsgId()), - source.getEntity()==null?Value.NULL:new EntityValue(source.getEntity()) + new EntityValue(target), + new NumericValue(amount), + StringValue.of(source.getMsgId()), + source.getEntity() == null ? Value.NULL : new EntityValue(source.getEntity()) ), target::createCommandSourceStack); } }; public static final Event PLAYER_DEALS_DAMAGE = new Event("player_deals_damage", 3, false) { @Override - public boolean onDamage(Entity target, float amount, DamageSource source) + public boolean onDamage(final Entity target, final float amount, final DamageSource source) { - return handler.call( () -> - Arrays.asList(new EntityValue(source.getEntity()), new NumericValue(amount), new EntityValue(target)), + return handler.call(() -> + Arrays.asList(new EntityValue(source.getEntity()), new NumericValue(amount), new EntityValue(target)), () -> source.getEntity().createCommandSourceStack() ); } @@ -864,8 +899,9 @@ public boolean onDamage(Entity target, float amount, DamageSource source) public static final Event PLAYER_COLLIDES_WITH_ENTITY = new Event("player_collides_with_entity", 2, false) { @Override - public boolean onEntityHandAction(ServerPlayer player, Entity entity, InteractionHand enumhand) { - handler.call( () -> Arrays.asList(new EntityValue(player), new EntityValue(entity)), player::createCommandSourceStack); + public boolean onEntityHandAction(final ServerPlayer player, final Entity entity, final InteractionHand enumhand) + { + handler.call(() -> Arrays.asList(new EntityValue(player), new EntityValue(entity)), player::createCommandSourceStack); return false; } }; @@ -873,86 +909,96 @@ public boolean onEntityHandAction(ServerPlayer player, Entity entity, Interactio public static final Event PLAYER_DIES = new Event("player_dies", 1, false) { @Override - public boolean onPlayerEvent(ServerPlayer player) + public boolean onPlayerEvent(final ServerPlayer player) { - handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); + handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); return false; } }; public static final Event PLAYER_RESPAWNS = new Event("player_respawns", 1, false) { @Override - public boolean onPlayerEvent(ServerPlayer player) + public boolean onPlayerEvent(final ServerPlayer player) { - handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); + handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); return false; } }; public static final Event PLAYER_CHANGES_DIMENSION = new Event("player_changes_dimension", 5, false) { @Override - public void onDimensionChange(ServerPlayer player, Vec3 from, Vec3 to, ResourceKey fromDim, ResourceKey dimTo) + public void onDimensionChange(final ServerPlayer player, final Vec3 from, final Vec3 to, final ResourceKey fromDim, final ResourceKey dimTo) { // eligibility already checked in mixin - Value fromValue = ListValue.fromTriple(from.x, from.y, from.z); - Value toValue = (to == null)?Value.NULL:ListValue.fromTriple(to.x, to.y, to.z); - Value fromDimStr = new StringValue(NBTSerializableValue.nameFromRegistryId(fromDim.location())); - Value toDimStr = new StringValue(NBTSerializableValue.nameFromRegistryId(dimTo.location())); + final Value fromValue = ListValue.fromTriple(from.x, from.y, from.z); + final Value toValue = (to == null) ? Value.NULL : ListValue.fromTriple(to.x, to.y, to.z); + final Value fromDimStr = new StringValue(NBTSerializableValue.nameFromRegistryId(fromDim.location())); + final Value toDimStr = new StringValue(NBTSerializableValue.nameFromRegistryId(dimTo.location())); - handler.call( () -> Arrays.asList(new EntityValue(player), fromValue, fromDimStr, toValue, toDimStr), player::createCommandSourceStack); + handler.call(() -> Arrays.asList(new EntityValue(player), fromValue, fromDimStr, toValue, toDimStr), player::createCommandSourceStack); } }; - public static final Event PLAYER_CONNECTS = new Event("player_connects", 1, false) { + public static final Event PLAYER_CONNECTS = new Event("player_connects", 1, false) + { @Override - public boolean onPlayerEvent(ServerPlayer player) + public boolean onPlayerEvent(final ServerPlayer player) { - handler.call( () -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); + handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); return false; } }; - public static final Event PLAYER_DISCONNECTS = new Event("player_disconnects", 2, false) { + public static final Event PLAYER_DISCONNECTS = new Event("player_disconnects", 2, false) + { @Override - public boolean onPlayerMessage(ServerPlayer player, String message) + public boolean onPlayerMessage(final ServerPlayer player, final String message) { - handler.call( () -> Arrays.asList(new EntityValue(player), new StringValue(message)), player::createCommandSourceStack); + handler.call(() -> Arrays.asList(new EntityValue(player), new StringValue(message)), player::createCommandSourceStack); return false; } }; - public static final Event PLAYER_MESSAGE = new Event("player_message", 2, false) { + public static final Event PLAYER_MESSAGE = new Event("player_message", 2, false) + { @Override - public boolean onPlayerMessage(ServerPlayer player, String message) { - return handler.call( () -> Arrays.asList(new EntityValue(player), new StringValue(message)), player::createCommandSourceStack); + public boolean onPlayerMessage(final ServerPlayer player, final String message) + { + return handler.call(() -> Arrays.asList(new EntityValue(player), new StringValue(message)), player::createCommandSourceStack); } }; - public static final Event PLAYER_COMMAND = new Event("player_command", 2, false) { + public static final Event PLAYER_COMMAND = new Event("player_command", 2, false) + { @Override - public boolean onPlayerMessage(ServerPlayer player, String message) { - return handler.call( () -> Arrays.asList(new EntityValue(player), new StringValue(message)), player::createCommandSourceStack); + public boolean onPlayerMessage(final ServerPlayer player, final String message) + { + return handler.call(() -> Arrays.asList(new EntityValue(player), new StringValue(message)), player::createCommandSourceStack); } }; public static final Event STATISTICS = new Event("statistic", 4, false) { - private ResourceLocation getStatId(Stat stat) + private ResourceLocation getStatId(final Stat stat) { return stat.getType().getRegistry().getKey(stat.getValue()); } + private final Set skippedStats = Set.of( - Stats.TIME_SINCE_DEATH, - Stats.TIME_SINCE_REST, - //Stats.PLAY_ONE_MINUTE, - Stats.PLAY_TIME, - Stats.TOTAL_WORLD_TIME + Stats.TIME_SINCE_DEATH, + Stats.TIME_SINCE_REST, + Stats.PLAY_TIME, + Stats.TOTAL_WORLD_TIME ); + @Override - public void onPlayerStatistic(ServerPlayer player, Stat stat, int amount) + public void onPlayerStatistic(final ServerPlayer player, final Stat stat, final int amount) { - ResourceLocation id = getStatId(stat); - if (skippedStats.contains(id)) return; + final ResourceLocation id = getStatId(stat); + if (skippedStats.contains(id)) + { + return; + } final Registry> registry = player.getLevel().registryAccess().registryOrThrow(Registries.STAT_TYPE); - handler.call( () -> Arrays.asList( + handler.call(() -> Arrays.asList( new EntityValue(player), StringValue.of(NBTSerializableValue.nameFromRegistryId(registry.getKey(stat.getType()))), StringValue.of(NBTSerializableValue.nameFromRegistryId(id)), @@ -963,12 +1009,12 @@ public void onPlayerStatistic(ServerPlayer player, Stat stat, int amount) public static final Event LIGHTNING = new Event("lightning", 2, true) { @Override - public void onWorldEventFlag(ServerLevel world, BlockPos pos, int flag) + public void onWorldEventFlag(final ServerLevel world, final BlockPos pos, final int flag) { handler.call( () -> Arrays.asList( new BlockValue(null, world, pos), - flag>0?Value.TRUE:Value.FALSE + flag > 0 ? Value.TRUE : Value.FALSE ), () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel(world) ); } @@ -976,31 +1022,49 @@ public void onWorldEventFlag(ServerLevel world, BlockPos pos, int flag) public static final Event CARPET_RULE_CHANGES = new Event("carpet_rule_changes", 2, true) { @Override - public void onCarpetRuleChanges(CarpetRule rule, CommandSourceStack source) + public void onCarpetRuleChanges(final CarpetRule rule, final CommandSourceStack source) { - String identifier = rule.settingsManager().identifier(); + final String identifier = rule.settingsManager().identifier(); final String namespace; - if (!identifier.equals("carpet")) + if (!identifier.equals("carpet")) { - namespace = identifier+":"; - } else { namespace = "";} + namespace = identifier + ":"; + } + else + { + namespace = ""; + } handler.call( () -> Arrays.asList( - new StringValue(namespace+rule.name()), + new StringValue(namespace + rule.name()), new StringValue(RuleHelper.toRuleString(rule.value())) ), () -> source ); } }; + //copy of Explosion.getCausingEntity() #TRACK# - private static LivingEntity getExplosionCausingEntity(Entity entity) + private static LivingEntity getExplosionCausingEntity(final Entity entity) { - if (entity == null) return null; - else if (entity instanceof PrimedTnt) return ((PrimedTnt)entity).getOwner(); - else if (entity instanceof LivingEntity) return (LivingEntity)entity; - else if (entity instanceof Projectile) { - Entity owner = ((Projectile)entity).getOwner(); - if (owner instanceof LivingEntity) return (LivingEntity)owner; + if (entity == null) + { + return null; + } + else if (entity instanceof final PrimedTnt tnt) + { + return tnt.getOwner(); + } + else if (entity instanceof final LivingEntity le) + { + return le; + } + else if (entity instanceof final Projectile p) + { + final Entity owner = p.getOwner(); + if (owner instanceof final LivingEntity le) + { + return le; + } } return null; } @@ -1008,18 +1072,18 @@ else if (entity instanceof Projectile) { public static final Event EXPLOSION_OUTCOME = new Event("explosion_outcome", 8, true) { @Override - public void onExplosion(ServerLevel world, Entity e, Supplier attacker, double x, double y, double z, float power, boolean createFire, List affectedBlocks, List affectedEntities, Explosion.BlockInteraction type) + public void onExplosion(final ServerLevel world, final Entity e, final Supplier attacker, final double x, final double y, final double z, final float power, final boolean createFire, final List affectedBlocks, final List affectedEntities, final Explosion.BlockInteraction type) { handler.call( () -> Arrays.asList( ListValue.fromTriple(x, y, z), NumericValue.of(power), EntityValue.of(e), - EntityValue.of(attacker!= null?attacker.get():Event.getExplosionCausingEntity(e)), + EntityValue.of(attacker != null ? attacker.get() : Event.getExplosionCausingEntity(e)), StringValue.of(type.name().toLowerCase(Locale.ROOT)), BooleanValue.of(createFire), - ListValue.wrap(affectedBlocks.stream().filter(b -> !world.isEmptyBlock(b)). map( // da heck they send air blocks - b -> new BlockValue(world.getBlockState(b),world,b) + ListValue.wrap(affectedBlocks.stream().filter(b -> !world.isEmptyBlock(b)).map( // da heck they send air blocks + b -> new BlockValue(world.getBlockState(b), world, b) )), ListValue.wrap(affectedEntities.stream().map(EntityValue::of)) ), () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel(world) @@ -1031,14 +1095,14 @@ public void onExplosion(ServerLevel world, Entity e, Supplier att public static final Event EXPLOSION = new Event("explosion", 6, true) { @Override - public void onExplosion(ServerLevel world, Entity e, Supplier attacker, double x, double y, double z, float power, boolean createFire, List affectedBlocks, List affectedEntities, Explosion.BlockInteraction type) + public void onExplosion(final ServerLevel world, final Entity e, final Supplier attacker, final double x, final double y, final double z, final float power, final boolean createFire, final List affectedBlocks, final List affectedEntities, final Explosion.BlockInteraction type) { handler.call( () -> Arrays.asList( ListValue.fromTriple(x, y, z), NumericValue.of(power), EntityValue.of(e), - EntityValue.of(attacker!= null?attacker.get():Event.getExplosionCausingEntity(e)), + EntityValue.of(attacker != null ? attacker.get() : Event.getExplosionCausingEntity(e)), StringValue.of(type.name().toLowerCase(Locale.ROOT)), BooleanValue.of(createFire) ), () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel(world) @@ -1047,7 +1111,7 @@ public void onExplosion(ServerLevel world, Entity e, Supplier atta }; @Deprecated - public static String getEntityLoadEventName(EntityType et) + public static String getEntityLoadEventName(final EntityType et) { return "entity_loaded_" + ValueConversions.of(BuiltInRegistries.ENTITY_TYPE.getKey(et)).getString(); } @@ -1058,7 +1122,7 @@ public static String getEntityLoadEventName(EntityType et) .map(et -> Map.entry(et, new Event(getEntityLoadEventName(et), 1, true, false) { @Override - public void onEntityAction(Entity entity, boolean created) + public void onEntityAction(final Entity entity, final boolean created) { handler.call( () -> Collections.singletonList(new EntityValue(entity)), @@ -1067,16 +1131,18 @@ public void onEntityAction(Entity entity, boolean created) } })).collect(Collectors.toUnmodifiableMap(Map.Entry::getKey, Map.Entry::getValue)); - public static String getEntityHandlerEventName(EntityType et) + public static String getEntityHandlerEventName(final EntityType et) { return "entity_handler_" + ValueConversions.of(BuiltInRegistries.ENTITY_TYPE.getKey(et)).getString(); } public static final Map, Event> ENTITY_HANDLER = BuiltInRegistries.ENTITY_TYPE .stream() - .map(et -> Map.entry(et, new Event(getEntityHandlerEventName(et), 2, true, false) { + .map(et -> Map.entry(et, new Event(getEntityHandlerEventName(et), 2, true, false) + { @Override - public void onEntityAction(Entity entity, boolean created) { + public void onEntityAction(final Entity entity, final boolean created) + { handler.call( () -> Arrays.asList(new EntityValue(entity), BooleanValue.of(created)), () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel((ServerLevel) entity.level).withPermission(CarpetSettings.runPermissionLevel) @@ -1091,11 +1157,13 @@ public void onEntityAction(Entity entity, boolean created) { public final CallbackList handler; public final boolean isPublic; // public events can be targetted with __on_ defs - public Event(String name, int reqArgs, boolean isGlobalOnly) + + public Event(final String name, final int reqArgs, final boolean isGlobalOnly) { this(name, reqArgs, isGlobalOnly, true); } - public Event(String name, int reqArgs, boolean isGlobalOnly, boolean isPublic) + + public Event(final String name, final int reqArgs, final boolean isGlobalOnly, final boolean isPublic) { this.name = name; this.handler = new CallbackList(reqArgs, true, isGlobalOnly); @@ -1103,34 +1171,43 @@ public Event(String name, int reqArgs, boolean isGlobalOnly, boolean isPublic) byName.put(name, this); } - public static List getAllEvents(CarpetScriptServer server, Predicate predicate) + public static List getAllEvents(final CarpetScriptServer server, final Predicate predicate) { - List eventList = new ArrayList<>(CarpetEventServer.Event.byName.values()); + final List eventList = new ArrayList<>(CarpetEventServer.Event.byName.values()); eventList.addAll(server.events.customEvents.values()); - if (predicate == null) return eventList; - return eventList.stream().filter(predicate).collect(Collectors.toList()); + if (predicate == null) + { + return eventList; + } + return eventList.stream().filter(predicate).toList(); } - public static Event getEvent(String name, CarpetScriptServer server) + public static Event getEvent(final String name, final CarpetScriptServer server) { - if (byName.containsKey(name)) return byName.get(name); + if (byName.containsKey(name)) + { + return byName.get(name); + } return server.events.customEvents.get(name); } - public static Event getOrCreateCustom(String name, CarpetScriptServer server) + public static Event getOrCreateCustom(final String name, final CarpetScriptServer server) { - Event event = getEvent(name, server); - if (event != null) return event; + final Event event = getEvent(name, server); + if (event != null) + { + return event; + } return new Event(name, server); } - public static void removeAllHostEvents(CarpetScriptHost host) + public static void removeAllHostEvents(final CarpetScriptHost host) { byName.values().forEach((e) -> e.handler.removeAllCalls(host)); host.scriptServer().events.customEvents.values().forEach((e) -> e.handler.removeAllCalls(host)); } - public static void transferAllHostEventsToChild(CarpetScriptHost host) + public static void transferAllHostEventsToChild(final CarpetScriptHost host) { byName.values().forEach((e) -> e.handler.createChildEvents(host)); host.scriptServer().events.customEvents.values().forEach((e) -> e.handler.createChildEvents(host)); @@ -1142,7 +1219,7 @@ public static void clearAllBuiltinEvents() } // custom event constructor - private Event(String name, CarpetScriptServer server) + private Event(final String name, final CarpetScriptServer server) { this.name = name; this.handler = new CallbackList(1, false, false); @@ -1157,41 +1234,126 @@ public boolean isNeeded() { return handler.callList.size() > 0; } - public boolean deprecated() {return false;} + + public boolean deprecated() + { + return false; + } + //stubs for calls just to ease calls in vanilla code so they don't need to deal with scarpet value types - public void onTick() { } - public void onChunkEvent(ServerLevel world, ChunkPos chPos, boolean generated) { } - public boolean onPlayerEvent(ServerPlayer player) {return false;} - public boolean onPlayerMessage(ServerPlayer player, String message) {return false;} - public void onPlayerStatistic(ServerPlayer player, Stat stat, int amount) { } - public void onMountControls(ServerPlayer player, float strafeSpeed, float forwardSpeed, boolean jumping, boolean sneaking) { } - public boolean onItemAction(ServerPlayer player, InteractionHand enumhand, ItemStack itemstack) {return false;} - public boolean onBlockAction(ServerPlayer player, BlockPos blockpos, Direction facing) {return false;} - public boolean onBlockHit(ServerPlayer player, InteractionHand enumhand, BlockHitResult hitRes) {return false;} - public boolean onBlockBroken(ServerPlayer player, BlockPos pos, BlockState previousBS) {return false;} - public boolean onBlockPlaced(ServerPlayer player, BlockPos pos, InteractionHand enumhand, ItemStack itemstack) {return false;} - public boolean onEntityHandAction(ServerPlayer player, Entity entity, InteractionHand enumhand) {return false;} - public void onHandAction(ServerPlayer player, InteractionHand enumhand) { } - public void onEntityAction(Entity entity, boolean created) { } - public void onDimensionChange(ServerPlayer player, Vec3 from, Vec3 to, ResourceKey fromDim, ResourceKey dimTo) {} - public boolean onDamage(Entity target, float amount, DamageSource source) {return false;} - public boolean onRecipeSelected(ServerPlayer player, ResourceLocation recipe, boolean fullStack) {return false;} - public void onSlotSwitch(ServerPlayer player, int from, int to) {} - public void onTrade(ServerPlayer player, Merchant merchant, MerchantOffer tradeOffer) {} - - public void onExplosion(ServerLevel world, Entity e, Supplier attacker, double x, double y, double z, float power, boolean createFire, List affectedBlocks, List affectedEntities, Explosion.BlockInteraction type) { } - public void onWorldEvent(ServerLevel world, BlockPos pos) { } - public void onWorldEventFlag(ServerLevel world, BlockPos pos, int flag) { } - public void onCarpetRuleChanges(CarpetRule rule, CommandSourceStack source) { } - public void onCustomPlayerEvent(ServerPlayer player, Object ... args) - { - if (handler.reqArgs != (args.length+1)) - throw new InternalExpressionException("Expected "+handler.reqArgs+" arguments for "+name+", got "+(args.length+1)); + public void onTick() + { + } + + public void onChunkEvent(final ServerLevel world, final ChunkPos chPos, final boolean generated) + { + } + + public boolean onPlayerEvent(final ServerPlayer player) + { + return false; + } + + public boolean onPlayerMessage(final ServerPlayer player, final String message) + { + return false; + } + + public void onPlayerStatistic(final ServerPlayer player, final Stat stat, final int amount) + { + } + + public void onMountControls(final ServerPlayer player, final float strafeSpeed, final float forwardSpeed, final boolean jumping, final boolean sneaking) + { + } + + public boolean onItemAction(final ServerPlayer player, final InteractionHand enumhand, final ItemStack itemstack) + { + return false; + } + + public boolean onBlockAction(final ServerPlayer player, final BlockPos blockpos, final Direction facing) + { + return false; + } + + public boolean onBlockHit(final ServerPlayer player, final InteractionHand enumhand, final BlockHitResult hitRes) + { + return false; + } + + public boolean onBlockBroken(final ServerPlayer player, final BlockPos pos, final BlockState previousBS) + { + return false; + } + + public boolean onBlockPlaced(final ServerPlayer player, final BlockPos pos, final InteractionHand enumhand, final ItemStack itemstack) + { + return false; + } + + public boolean onEntityHandAction(final ServerPlayer player, final Entity entity, final InteractionHand enumhand) + { + return false; + } + + public void onHandAction(final ServerPlayer player, final InteractionHand enumhand) + { + } + + public void onEntityAction(final Entity entity, final boolean created) + { + } + + public void onDimensionChange(final ServerPlayer player, final Vec3 from, final Vec3 to, final ResourceKey fromDim, final ResourceKey dimTo) + { + } + + public boolean onDamage(final Entity target, final float amount, final DamageSource source) + { + return false; + } + + public boolean onRecipeSelected(final ServerPlayer player, final ResourceLocation recipe, final boolean fullStack) + { + return false; + } + + public void onSlotSwitch(final ServerPlayer player, final int from, final int to) + { + } + + public void onTrade(final ServerPlayer player, final Merchant merchant, final MerchantOffer tradeOffer) + { + } + + public void onExplosion(final ServerLevel world, final Entity e, final Supplier attacker, final double x, final double y, final double z, final float power, final boolean createFire, final List affectedBlocks, final List affectedEntities, final Explosion.BlockInteraction type) + { + } + + public void onWorldEvent(final ServerLevel world, final BlockPos pos) + { + } + + public void onWorldEventFlag(final ServerLevel world, final BlockPos pos, final int flag) + { + } + + public void onCarpetRuleChanges(final CarpetRule rule, final CommandSourceStack source) + { + } + + public void onCustomPlayerEvent(final ServerPlayer player, final Object... args) + { + if (handler.reqArgs != (args.length + 1)) + { + throw new InternalExpressionException("Expected " + handler.reqArgs + " arguments for " + name + ", got " + (args.length + 1)); + } handler.call( () -> { - List valArgs = new ArrayList<>(); + final List valArgs = new ArrayList<>(); valArgs.add(EntityValue.of(player)); - for (Object o: args) + for (final Object o : args) { valArgs.add(ValueConversions.guess(player.getLevel(), o)); } @@ -1199,14 +1361,17 @@ public void onCustomPlayerEvent(ServerPlayer player, Object ... args) }, player::createCommandSourceStack ); } - public void onCustomWorldEvent(ServerLevel world, Object ... args) + + public void onCustomWorldEvent(final ServerLevel world, final Object... args) { if (handler.reqArgs != args.length) - throw new InternalExpressionException("Expected "+handler.reqArgs+" arguments for "+name+", got "+args.length); + { + throw new InternalExpressionException("Expected " + handler.reqArgs + " arguments for " + name + ", got " + args.length); + } handler.call( () -> { - List valArgs = new ArrayList<>(); - for (Object o: args) + final List valArgs = new ArrayList<>(); + for (final Object o : args) { valArgs.add(ValueConversions.guess(world, o)); } @@ -1217,7 +1382,7 @@ public void onCustomWorldEvent(ServerLevel world, Object ... args) } - public CarpetEventServer(CarpetScriptServer scriptServer) + public CarpetEventServer(final CarpetScriptServer scriptServer) { this.scriptServer = scriptServer; Event.clearAllBuiltinEvents(); @@ -1226,12 +1391,14 @@ public CarpetEventServer(CarpetScriptServer scriptServer) public void tick() { if (!TickSpeed.process_entities) + { return; - Iterator eventIterator = scheduledCalls.iterator(); - List currentCalls = new ArrayList<>(); - while(eventIterator.hasNext()) + } + final Iterator eventIterator = scheduledCalls.iterator(); + final List currentCalls = new ArrayList<>(); + while (eventIterator.hasNext()) { - ScheduledCall call = eventIterator.next(); + final ScheduledCall call = eventIterator.next(); call.dueTime--; if (call.dueTime <= 0) { @@ -1239,133 +1406,169 @@ public void tick() eventIterator.remove(); } } - for (ScheduledCall call: currentCalls) + for (final ScheduledCall call : currentCalls) { call.execute(); } } - public void scheduleCall(CarpetContext context, FunctionValue function, List args, long due) + + public void scheduleCall(final CarpetContext context, final FunctionValue function, final List args, final long due) { scheduledCalls.add(new ScheduledCall(context, function, args, due)); } - public void runScheduledCall(BlockPos origin, CommandSourceStack source, String hostname, CarpetScriptHost host, FunctionValue udf, List argv) + public void runScheduledCall(final BlockPos origin, final CommandSourceStack source, final String hostname, final CarpetScriptHost host, final FunctionValue udf, final List argv) { if (hostname != null && !scriptServer.modules.containsKey(hostname)) // well - scheduled call app got unloaded + { return; + } try { host.callUDF(origin, source, udf, argv); } - catch (NullPointerException | InvalidCallbackException | IntegrityException ignored) { } + catch (final NullPointerException | InvalidCallbackException | IntegrityException ignored) + { + } } - public CallbackResult runEventCall(CommandSourceStack sender, String hostname, String optionalTarget, FunctionValue udf, List argv) + public CallbackResult runEventCall(final CommandSourceStack sender, final String hostname, final String optionalTarget, final FunctionValue udf, final List argv) { - CarpetScriptHost appHost = scriptServer.getAppHostByName(hostname); + final CarpetScriptHost appHost = scriptServer.getAppHostByName(hostname); // no such app - if (appHost == null) return CallbackResult.FAIL; + if (appHost == null) + { + return CallbackResult.FAIL; + } // dummy call for player apps that reside on the global copy - do not run them, but report as passes. - if (appHost.isPerUser() && optionalTarget==null) return CallbackResult.PASS; + if (appHost.isPerUser() && optionalTarget == null) + { + return CallbackResult.PASS; + } ServerPlayer target = null; if (optionalTarget != null) { target = sender.getServer().getPlayerList().getPlayerByName(optionalTarget); - if (target == null) return CallbackResult.FAIL; + if (target == null) + { + return CallbackResult.FAIL; + } + } + final CommandSourceStack source = sender.withPermission(CarpetSettings.runPermissionLevel); + final CarpetScriptHost executingHost = appHost.retrieveForExecution(sender, target); + if (executingHost == null) + { + return CallbackResult.FAIL; } - CommandSourceStack source = sender.withPermission(CarpetSettings.runPermissionLevel); - CarpetScriptHost executingHost = appHost.retrieveForExecution(sender, target); - if (executingHost == null) return CallbackResult.FAIL; try { - Value returnValue = executingHost.callUDF(source.withPermission(CarpetSettings.runPermissionLevel), udf, argv); + final Value returnValue = executingHost.callUDF(source.withPermission(CarpetSettings.runPermissionLevel), udf, argv); return returnValue instanceof StringValue && returnValue.getString().equals("cancel") ? CallbackResult.CANCEL : CallbackResult.SUCCESS; } - catch (NullPointerException | InvalidCallbackException | IntegrityException error) + catch (final NullPointerException | InvalidCallbackException | IntegrityException error) { CarpetScriptServer.LOG.error("Got exception when running event call ", error); return CallbackResult.FAIL; } } - public boolean addEventFromCommand(CommandSourceStack source, String event, String host, String funName) + public boolean addEventFromCommand(final CommandSourceStack source, final String event, final String host, final String funName) { - Event ev = Event.getEvent(event, CarpetServer.scriptServer); + final Event ev = Event.getEvent(event, CarpetServer.scriptServer); if (ev == null) { return false; } - boolean added = ev.handler.addFromExternal(source, host, funName, h -> onEventAddedToHost(ev, h)); - if (added) Messenger.m(source, "gi Added " + funName + " to " + event); + final boolean added = ev.handler.addFromExternal(source, host, funName, h -> onEventAddedToHost(ev, h)); + if (added) + { + Messenger.m(source, "gi Added " + funName + " to " + event); + } return added; } - public void addBuiltInEvent(String event, ScriptHost host, FunctionValue function, List args) + public void addBuiltInEvent(final String event, final ScriptHost host, final FunctionValue function, final List args) { // this is globals only - Event ev = Event.byName.get(event); + final Event ev = Event.byName.get(event); onEventAddedToHost(ev, host); - boolean success = ev.handler.addEventCallInternal(host, function, args==null?NOARGS:args); - if (!success) throw new InternalExpressionException("Global event "+event+" requires "+ev.handler.reqArgs+", not "+(function.getNumParams()-((args==null)?0:args.size()))); + final boolean success = ev.handler.addEventCallInternal(host, function, args == null ? NOARGS : args); + if (!success) + { + throw new InternalExpressionException("Global event " + event + " requires " + ev.handler.reqArgs + ", not " + (function.getNumParams() - ((args == null) ? 0 : args.size()))); + } } - public boolean handleCustomEvent(String event, CarpetScriptHost host, FunctionValue function, List args) + public boolean handleCustomEvent(final String event, final CarpetScriptHost host, final FunctionValue function, final List args) { - Event ev = Event.getOrCreateCustom(event, scriptServer); + final Event ev = Event.getOrCreateCustom(event, scriptServer); onEventAddedToHost(ev, host); - return ev.handler.addEventCallInternal(host, function, args==null?NOARGS:args); + return ev.handler.addEventCallInternal(host, function, args == null ? NOARGS : args); } - public int signalEvent(String event, CarpetContext cc, ServerPlayer optionalTarget, List callArgs) + public int signalEvent(final String event, final CarpetContext cc, final ServerPlayer optionalTarget, final List callArgs) { - Event ev = Event.getEvent(event, ((CarpetScriptHost)cc.host).scriptServer()); - if (ev == null) return -1; - return ev.handler.signal(cc.source(), optionalTarget, callArgs); + final Event ev = Event.getEvent(event, ((CarpetScriptHost) cc.host).scriptServer()); + return ev == null ? -1 : ev.handler.signal(cc.source(), optionalTarget, callArgs); } - private void onEventAddedToHost(Event event, ScriptHost host) + private void onEventAddedToHost(final Event event, final ScriptHost host) { - if (event.deprecated()) host.issueDeprecation(event.name+" event"); + if (event.deprecated()) + { + host.issueDeprecation(event.name + " event"); + } event.handler.sortByPriority(this.scriptServer); - //return !(event.globalOnly && (host.perUser || host.parent != null)); } - public boolean removeEventFromCommand(CommandSourceStack source, String event, String funName) + public boolean removeEventFromCommand(final CommandSourceStack source, final String event, final String funName) { - Event ev = Event.getEvent(event, CarpetServer.scriptServer); + final Event ev = Event.getEvent(event, CarpetServer.scriptServer); if (ev == null) { Messenger.m(source, "r Unknown event: " + event); return false; } - Callback.Signature call = Callback.fromString(funName); + final Callback.Signature call = Callback.fromString(funName); ev.handler.removeEventCall(call.host, call.target, call.function); // could verified if actually removed - Messenger.m(source, "gi Removed event: " + funName + " from "+event); + Messenger.m(source, "gi Removed event: " + funName + " from " + event); return true; } - public boolean removeBuiltInEvent(String event, CarpetScriptHost host) + + public boolean removeBuiltInEvent(final String event, final CarpetScriptHost host) { - Event ev = Event.getEvent(event, host.scriptServer()); - if (ev == null) return false; + final Event ev = Event.getEvent(event, host.scriptServer()); + if (ev == null) + { + return false; + } ev.handler.removeAllCalls(host); return true; } - public void removeBuiltInEvent(String event, CarpetScriptHost host, String funName) + public void removeBuiltInEvent(final String event, final CarpetScriptHost host, final String funName) { - Event ev = Event.getEvent(event, host.scriptServer()); - if (ev != null) ev.handler.removeEventCall(host.getName(), host.user, funName); + final Event ev = Event.getEvent(event, host.scriptServer()); + if (ev != null) + { + ev.handler.removeEventCall(host.getName(), host.user, funName); + } } - public void removeAllHostEvents(CarpetScriptHost host) + public void removeAllHostEvents(final CarpetScriptHost host) { // remove event handlers Event.removeAllHostEvents(host); if (host.isPerUser()) - for (ScriptHost child: host.userHosts.values()) Event.removeAllHostEvents((CarpetScriptHost) child); + { + for (final ScriptHost child : host.userHosts.values()) + { + Event.removeAllHostEvents((CarpetScriptHost) child); + } + } // remove scheduled calls scheduledCalls.removeIf(sc -> sc.host != null && sc.host.equals(host.getName())); } -} +} \ No newline at end of file diff --git a/src/main/java/carpet/script/CarpetExpression.java b/src/main/java/carpet/script/CarpetExpression.java index 6873ff6e12..ef78a103d5 100644 --- a/src/main/java/carpet/script/CarpetExpression.java +++ b/src/main/java/carpet/script/CarpetExpression.java @@ -25,12 +25,24 @@ public class CarpetExpression private final CommandSourceStack source; private final BlockPos origin; private final Expression expr; + // these are for extensions - public Expression getExpr() {return expr;} - public CommandSourceStack getSource() {return source;} - public BlockPos getOrigin() {return origin;} + public Expression getExpr() + { + return expr; + } - public CarpetExpression(Module module, String expression, CommandSourceStack source, BlockPos origin) + public CommandSourceStack getSource() + { + return source; + } + + public BlockPos getOrigin() + { + return origin; + } + + public CarpetExpression(final Module module, final String expression, final CommandSourceStack source, final BlockPos origin) { this.origin = origin; this.source = source; @@ -49,76 +61,80 @@ public CarpetExpression(Module module, String expression, CommandSourceStack sou CarpetServer.extensions.forEach(e -> e.scarpetApi(this)); } - public boolean fillAndScanCommand(ScriptHost host, int x, int y, int z) + public boolean fillAndScanCommand(final ScriptHost host, final int x, final int y, final int z) { if (CarpetServer.scriptServer.stopAll) + { return false; + } try { - Context context = new CarpetContext(host, source, origin). + final Context context = new CarpetContext(host, source, origin). with("x", (c, t) -> new NumericValue(x - origin.getX()).bindTo("x")). with("y", (c, t) -> new NumericValue(y - origin.getY()).bindTo("y")). with("z", (c, t) -> new NumericValue(z - origin.getZ()).bindTo("z")). with("_", (c, t) -> new BlockValue(null, source.getLevel(), new BlockPos(x, y, z)).bindTo("_")); - Entity e = source.getEntity(); - if (e==null) + final Entity e = source.getEntity(); + if (e == null) { - Value nullPlayer = Value.NULL.reboundedTo("p"); - context.with("p", (cc, tt) -> nullPlayer ); + final Value nullPlayer = Value.NULL.reboundedTo("p"); + context.with("p", (cc, tt) -> nullPlayer); } else { - Value playerValue = new EntityValue(e).bindTo("p"); + final Value playerValue = new EntityValue(e).bindTo("p"); context.with("p", (cc, tt) -> playerValue); } - return CarpetServer.scriptServer.events.handleEvents.getWhileDisabled(()-> this.expr.eval(context).getBoolean()); + return CarpetServer.scriptServer.events.handleEvents.getWhileDisabled(() -> this.expr.eval(context).getBoolean()); } - catch (ExpressionException e) + catch (final ExpressionException e) { throw new CarpetExpressionException(e.getMessage(), e.stack); } - catch (ArithmeticException ae) + catch (final ArithmeticException ae) { - throw new CarpetExpressionException("Math doesn't compute... "+ae.getMessage(), null); + throw new CarpetExpressionException("Math doesn't compute... " + ae.getMessage(), null); } - catch (StackOverflowError soe) + catch (final StackOverflowError soe) { throw new CarpetExpressionException("Your thoughts are too deep", null); } } - public Value scriptRunCommand(ScriptHost host, BlockPos pos) + public Value scriptRunCommand(final ScriptHost host, final BlockPos pos) { if (CarpetServer.scriptServer.stopAll) + { throw new CarpetExpressionException("SCRIPTING PAUSED (unpause with /script resume)", null); + } try { - Context context = new CarpetContext(host, source, origin). + final Context context = new CarpetContext(host, source, origin). with("x", (c, t) -> new NumericValue(pos.getX() - origin.getX()).bindTo("x")). with("y", (c, t) -> new NumericValue(pos.getY() - origin.getY()).bindTo("y")). with("z", (c, t) -> new NumericValue(pos.getZ() - origin.getZ()).bindTo("z")); - Entity e = source.getEntity(); - if (e==null) + final Entity e = source.getEntity(); + if (e == null) { - Value nullPlayer = Value.NULL.reboundedTo("p"); - context.with("p", (cc, tt) -> nullPlayer ); + final Value nullPlayer = Value.NULL.reboundedTo("p"); + context.with("p", (cc, tt) -> nullPlayer); } else { - Value playerValue = new EntityValue(e).bindTo("p"); + final Value playerValue = new EntityValue(e).bindTo("p"); context.with("p", (cc, tt) -> playerValue); } - return CarpetServer.scriptServer.events.handleEvents.getWhileDisabled(()-> this.expr.eval(context)); + return CarpetServer.scriptServer.events.handleEvents.getWhileDisabled(() -> this.expr.eval(context)); } - catch (ExpressionException e) + catch (final ExpressionException e) { throw new CarpetExpressionException(e.getMessage(), e.stack); } - catch (ArithmeticException ae) + catch (final ArithmeticException ae) { - throw new CarpetExpressionException("Math doesn't compute... "+ae.getMessage(), null); + throw new CarpetExpressionException("Math doesn't compute... " + ae.getMessage(), null); } - catch (StackOverflowError soe) + catch (final StackOverflowError soe) { throw new CarpetExpressionException("Your thoughts are too deep", null); } diff --git a/src/main/java/carpet/script/CarpetScriptHost.java b/src/main/java/carpet/script/CarpetScriptHost.java index 7462db75a1..64a46da04b 100644 --- a/src/main/java/carpet/script/CarpetScriptHost.java +++ b/src/main/java/carpet/script/CarpetScriptHost.java @@ -85,7 +85,7 @@ public class CarpetScriptHost extends ScriptHost public AppStoreManager.StoreNode storeSource; boolean hasCommand; - private CarpetScriptHost(CarpetScriptServer server, Module code, boolean perUser, ScriptHost parent, Map config, Map argTypes, Predicate commandValidator, boolean isRuleApp) + private CarpetScriptHost(final CarpetScriptServer server, final Module code, final boolean perUser, final ScriptHost parent, final Map config, final Map argTypes, final Predicate commandValidator, final boolean isRuleApp) { super(code, server, perUser, parent); this.saveTimeout = 0; @@ -96,7 +96,7 @@ private CarpetScriptHost(CarpetScriptServer server, Module code, boolean perUser } else if (parent != null) { - persistenceRequired = ((CarpetScriptHost)parent).persistenceRequired; + persistenceRequired = ((CarpetScriptHost) parent).persistenceRequired; strict = parent.strict; } appConfig = config; @@ -106,31 +106,31 @@ else if (parent != null) storeSource = null; } - public static CarpetScriptHost create(CarpetScriptServer scriptServer, Module module, boolean perPlayer, CommandSourceStack source, Predicate commandValidator, boolean isRuleApp, AppStoreManager.StoreNode storeSource) + public static CarpetScriptHost create(final CarpetScriptServer scriptServer, final Module module, final boolean perPlayer, final CommandSourceStack source, final Predicate commandValidator, final boolean isRuleApp, final AppStoreManager.StoreNode storeSource) { - CarpetScriptHost host = new CarpetScriptHost(scriptServer, module, perPlayer, null, Collections.emptyMap(), new HashMap<>(), commandValidator, isRuleApp); + final CarpetScriptHost host = new CarpetScriptHost(scriptServer, module, perPlayer, null, Collections.emptyMap(), new HashMap<>(), commandValidator, isRuleApp); // parse code and convert to expression if (module != null) { try { host.setChatErrorSnooper(source); - CarpetExpression ex = new CarpetExpression(host.main, module.code(), source, new BlockPos(0, 0, 0)); + final CarpetExpression ex = new CarpetExpression(host.main, module.code(), source, new BlockPos(0, 0, 0)); ex.getExpr().asATextSource(); host.storeSource = storeSource; ex.scriptRunCommand(host, new BlockPos(source.getPosition())); } - catch (CarpetExpressionException e) + catch (final CarpetExpressionException e) { host.handleErrorWithStack("Error while evaluating expression", e); throw new LoadException(); } - catch (ArithmeticException ae) // is this branch ever reached? Seems like arithmetic exceptions are converted to CEEs earlier + catch (final ArithmeticException ae) // is this branch ever reached? Seems like arithmetic exceptions are converted to CEEs earlier { host.handleErrorWithStack("Math doesn't compute", ae); throw new LoadException(); } - catch (StackOverflowError soe) + catch (final StackOverflowError soe) { host.handleErrorWithStack("Your thoughts are too deep", soe); } @@ -142,42 +142,44 @@ public static CarpetScriptHost create(CarpetScriptServer scriptServer, Module mo return host; } - private static int execute(CommandContext ctx, String hostName, FunctionArgument funcSpec, List paramNames) throws CommandSyntaxException + private static int execute(final CommandContext ctx, final String hostName, final FunctionArgument funcSpec, final List paramNames) throws CommandSyntaxException { - CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet command", CarpetProfiler.TYPE.GENERAL); - CarpetScriptHost cHost = CarpetServer.scriptServer.modules.get(hostName).retrieveOwnForExecution(ctx.getSource()); - List argNames = funcSpec.function.getArguments(); - if ((argNames.size()-funcSpec.args.size()) != paramNames.size()) - throw new SimpleCommandExceptionType(Component.literal("Target function "+funcSpec.function.getPrettyString()+" as wrong number of arguments, required "+paramNames.size()+", found "+argNames.size()+" with "+funcSpec.args.size()+" provided")).create(); - List args = new ArrayList<>(argNames.size()); - for (String s : paramNames) + final CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet command", CarpetProfiler.TYPE.GENERAL); + final CarpetScriptHost cHost = CarpetServer.scriptServer.modules.get(hostName).retrieveOwnForExecution(ctx.getSource()); + final List argNames = funcSpec.function.getArguments(); + if ((argNames.size() - funcSpec.args.size()) != paramNames.size()) + { + throw new SimpleCommandExceptionType(Component.literal("Target function " + funcSpec.function.getPrettyString() + " as wrong number of arguments, required " + paramNames.size() + ", found " + argNames.size() + " with " + funcSpec.args.size() + " provided")).create(); + } + final List args = new ArrayList<>(argNames.size()); + for (final String s : paramNames) { args.add(CommandArgument.getValue(ctx, s, cHost)); } args.addAll(funcSpec.args); - Value response = cHost.handleCommand(ctx.getSource(), funcSpec.function, args); - // will skip prints for new - //if (!response.isNull()) Messenger.m(ctx.getSource(), "gi " + response.getString()); - int intres = (int) response.readInteger(); + final Value response = cHost.handleCommand(ctx.getSource(), funcSpec.function, args); + final int intres = (int) response.readInteger(); CarpetProfiler.end_current_section(currentSection); return intres; } public LiteralArgumentBuilder addPathToCommand( - LiteralArgumentBuilder command, - List path, - FunctionArgument functionSpec + final LiteralArgumentBuilder command, + final List path, + final FunctionArgument functionSpec ) throws CommandSyntaxException { - String hostName = main.name(); - List commandArgs = path.stream().filter(t -> t.isArgument).map(t -> t.surface).collect(Collectors.toList()); - if (commandArgs.size() != (functionSpec.function.getNumParams()-functionSpec.args.size()) ) - throw CommandArgument.error("Number of parameters in function "+functionSpec.function.fullName()+" doesn't match parameters for a command"); + final String hostName = main.name(); + final List commandArgs = path.stream().filter(t -> t.isArgument).map(t -> t.surface).collect(Collectors.toList()); + if (commandArgs.size() != (functionSpec.function.getNumParams() - functionSpec.args.size())) + { + throw CommandArgument.error("Number of parameters in function " + functionSpec.function.fullName() + " doesn't match parameters for a command"); + } if (path.isEmpty()) { return command.executes((c) -> execute(c, hostName, functionSpec, Collections.emptyList())); } - List reversedPath = new ArrayList<>(path); + final List reversedPath = new ArrayList<>(path); Collections.reverse(reversedPath); ArgumentBuilder argChain = reversedPath.get(0).getCommandNode(this).executes(c -> execute(c, hostName, functionSpec, commandArgs)); for (int i = 1; i < reversedPath.size(); i++) @@ -188,14 +190,14 @@ public LiteralArgumentBuilder addPathToCommand( } public LiteralArgumentBuilder getNewCommandTree( - List,FunctionArgument>> entries, Predicate useValidator + final List, FunctionArgument>> entries, final Predicate useValidator ) throws CommandSyntaxException { - String hostName = main.name(); - Predicate configValidator = getCommandConfigPermissions(); + final String hostName = main.name(); + final Predicate configValidator = getCommandConfigPermissions(); LiteralArgumentBuilder command = literal(hostName). - requires((player) -> useValidator.test(player) && configValidator.test(player)); - for (Pair,FunctionArgument> commandData : entries) + requires((player) -> useValidator.test(player) && configValidator.test(player)); + for (final Pair, FunctionArgument> commandData : entries) { command = this.addPathToCommand(command, commandData.getKey(), commandData.getValue()); } @@ -204,45 +206,51 @@ public LiteralArgumentBuilder getNewCommandTree( public Predicate getCommandConfigPermissions() throws CommandSyntaxException { - Value confValue = appConfig.get(StringValue.of("command_permission")); - if (confValue == null) return s -> true; - if (confValue instanceof NumericValue) + final Value confValue = appConfig.get(StringValue.of("command_permission")); + if (confValue == null) { - int level = ((NumericValue) confValue).getInt(); - if (level < 1 || level > 4) throw CommandArgument.error("Numeric permission level for custom commands should be between 1 and 4"); - return s -> s.hasPermission(level); + return s -> true; } - if (!(confValue instanceof FunctionValue)) + if (confValue instanceof final NumericValue number) { - String perm = confValue.getString().toLowerCase(Locale.ROOT); - switch (perm) + final int level = number.getInt(); + if (level < 1 || level > 4) { - case "ops": return s -> s.hasPermission(2); - case "server": return s -> !(s.getEntity() instanceof ServerPlayer); - case "players": return s -> s.getEntity() instanceof ServerPlayer; - case "all": return s -> true; - default: throw CommandArgument.error("Unknown command permission: "+perm); + throw CommandArgument.error("Numeric permission level for custom commands should be between 1 and 4"); } + return s -> s.hasPermission(level); + } + if (!(confValue instanceof final FunctionValue fun)) + { + final String perm = confValue.getString().toLowerCase(Locale.ROOT); + return switch (perm) { + case "ops" -> s -> s.hasPermission(2); + case "server" -> s -> !(s.getEntity() instanceof ServerPlayer); + case "players" -> s -> s.getEntity() instanceof ServerPlayer; + case "all" -> s -> true; + default -> throw CommandArgument.error("Unknown command permission: " + perm); + }; + } + if (fun.getNumParams() != 1) + { + throw CommandArgument.error("Custom command permission function should expect 1 argument"); } - FunctionValue fun = (FunctionValue) confValue; - if (fun.getNumParams() != 1) throw CommandArgument.error("Custom command permission function should expect 1 argument"); - String hostName = getName(); + final String hostName = getName(); return s -> { try { - CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet command", CarpetProfiler.TYPE.GENERAL); - CarpetScriptHost cHost = null; - cHost = CarpetServer.scriptServer.modules.get(hostName).retrieveOwnForExecution(s); - Value response = cHost.handleCommand(s, fun, Collections.singletonList( - (s.getEntity() instanceof ServerPlayer)?new EntityValue(s.getEntity()):Value.NULL) + final CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet command", CarpetProfiler.TYPE.GENERAL); + final CarpetScriptHost cHost = CarpetServer.scriptServer.modules.get(hostName).retrieveOwnForExecution(s); + final Value response = cHost.handleCommand(s, fun, Collections.singletonList( + (s.getEntity() instanceof ServerPlayer) ? new EntityValue(s.getEntity()) : Value.NULL) ); - boolean res = response.getBoolean(); + final boolean res = response.getBoolean(); CarpetProfiler.end_current_section(currentSection); return res; } - catch (CommandSyntaxException e) + catch (final CommandSyntaxException e) { - Messenger.m(s, "rb Unable to run app command: "+e.getMessage()); + Messenger.m(s, "rb Unable to run app command: " + e.getMessage()); return false; } }; @@ -255,35 +263,45 @@ protected ScriptHost duplicate() } @Override - protected void setupUserHost(ScriptHost host) + protected void setupUserHost(final ScriptHost host) { super.setupUserHost(host); // transfer Events - CarpetScriptHost child = (CarpetScriptHost) host; + final CarpetScriptHost child = (CarpetScriptHost) host; CarpetEventServer.Event.transferAllHostEventsToChild(child); - FunctionValue onStart = child.getFunction("__on_start"); - if (onStart != null) child.callNow(onStart, Collections.emptyList()); + final FunctionValue onStart = child.getFunction("__on_start"); + if (onStart != null) + { + child.callNow(onStart, Collections.emptyList()); + } } @Override - public void addUserDefinedFunction(Context ctx, Module module, String funName, FunctionValue function) + public void addUserDefinedFunction(final Context ctx, final Module module, final String funName, final FunctionValue function) { super.addUserDefinedFunction(ctx, module, funName, function); - if (ctx.host.main != module) return; // not dealing with automatic imports / exports /configs / apps from imports + if (ctx.host.main != module) + { + return; // not dealing with automatic imports / exports /configs / apps from imports + } if (funName.startsWith("__")) // potential fishy activity { if (funName.startsWith("__on_")) // here we can make a determination if we want to only accept events from main module. { // this is nasty, we have the host and function, yet we add it via names, but hey - works for now - String event = funName.replaceFirst("__on_", ""); + final String event = funName.replaceFirst("__on_", ""); if (CarpetEventServer.Event.byName.containsKey(event)) + { scriptServer().events.addBuiltInEvent(event, this, function, null); + } } else if (funName.equals("__config")) { // needs to be added as we read the code, cause other events may be affected. if (!readConfig()) + { throw new InternalExpressionException("Invalid app config (via '__config()' function)"); + } } } } @@ -292,43 +310,57 @@ private boolean readConfig() { try { - FunctionValue configFunction = getFunction("__config"); - if (configFunction == null) return false; - Value ret = callNow(configFunction, Collections.emptyList()); - if (!(ret instanceof MapValue)) return false; - Map config = ((MapValue) ret).getMap(); + final FunctionValue configFunction = getFunction("__config"); + if (configFunction == null) + { + return false; + } + final Value ret = callNow(configFunction, Collections.emptyList()); + if (!(ret instanceof final MapValue map)) + { + return false; + } + final Map config = map.getMap(); setPerPlayer(config.getOrDefault(new StringValue("scope"), new StringValue("player")).getString().equalsIgnoreCase("player")); persistenceRequired = config.getOrDefault(new StringValue("stay_loaded"), Value.TRUE).getBoolean(); strict = config.getOrDefault(StringValue.of("strict"), Value.FALSE).getBoolean(); eventPriority = config.getOrDefault(new StringValue("event_priority"), Value.ZERO).readDoubleNumber(); // check requires - Value loadRequirements = config.get(new StringValue("requires")); - if (loadRequirements instanceof FunctionValue) + final Value loadRequirements = config.get(new StringValue("requires")); + if (loadRequirements instanceof final FunctionValue functionValue) { - Value reqResult = callNow((FunctionValue) loadRequirements, Collections.emptyList()); + final Value reqResult = callNow(functionValue, Collections.emptyList()); if (reqResult.getBoolean()) // != false or null + { throw new LoadException(reqResult.getString()); + } } else { checkModVersionRequirements(loadRequirements); - }; + } if (storeSource != null) { - Value resources = config.get(new StringValue("resources")); + final Value resources = config.get(new StringValue("resources")); if (resources != null) { - if (!(resources instanceof ListValue)) throw new InternalExpressionException("App resources not defined as a list"); - for (Value resource : ((ListValue) resources).getItems()) + if (!(resources instanceof final ListValue list)) + { + throw new InternalExpressionException("App resources not defined as a list"); + } + for (final Value resource : list.getItems()) { AppStoreManager.addResource(this, storeSource, resource); } } - Value libraries = config.get(new StringValue("libraries")); + final Value libraries = config.get(new StringValue("libraries")); if (libraries != null) { - if (!(libraries instanceof ListValue)) throw new InternalExpressionException("App libraries not defined as a list"); - for (Value library : ((ListValue) libraries).getItems()) + if (!(libraries instanceof final ListValue list)) + { + throw new InternalExpressionException("App libraries not defined as a list"); + } + for (final Value library : list.getItems()) { AppStoreManager.addLibrary(this, storeSource, library); } @@ -336,22 +368,25 @@ private boolean readConfig() } appConfig = config; } - catch (NullPointerException ignored) + catch (final NullPointerException ignored) { return false; } return true; } - static class ListComparator> implements Comparator,?>> + static class ListComparator> implements Comparator, ?>> { @Override - public int compare(Pair,?> p1, Pair,?> p2) { - List o1 = p1.getKey(); - List o2 = p2.getKey(); - for (int i = 0; i < Math.min(o1.size(), o2.size()); i++) { - int c = o1.get(i).compareTo(o2.get(i)); - if (c != 0) { + public int compare(final Pair, ?> p1, final Pair, ?> p2) + { + final List o1 = p1.getKey(); + final List o2 = p2.getKey(); + for (int i = 0; i < Math.min(o1.size(), o2.size()); i++) + { + final int c = o1.get(i).compareTo(o2.get(i)); + if (c != 0) + { return c; } } @@ -360,7 +395,8 @@ public int compare(Pair,?> p1, Pair,?> p2) { } // Used to ensure app gets marked as holding command from a central place - private void registerCommand(LiteralArgumentBuilder command) { + private void registerCommand(final LiteralArgumentBuilder command) + { scriptServer().server.getCommands().getDispatcher().register(command); hasCommand = true; } @@ -368,32 +404,37 @@ private void registerCommand(LiteralArgumentBuilder command) public void readCustomArgumentTypes() throws CommandSyntaxException { // read custom arguments - Value arguments = appConfig.get(StringValue.of("arguments")); + final Value arguments = appConfig.get(StringValue.of("arguments")); if (arguments != null) { - if (!(arguments instanceof MapValue)) + if (!(arguments instanceof final MapValue map)) + { throw CommandArgument.error("'arguments' element in config should be a map"); + } appArgTypes.clear(); - for (Map.Entry typeData : ((MapValue)arguments).getMap().entrySet()) + for (final Map.Entry typeData : map.getMap().entrySet()) { - String argument = typeData.getKey().getString(); - Value spec = typeData.getValue(); - if (!(spec instanceof MapValue)) throw CommandArgument.error("Spec for '"+argument+"' should be a map"); - Map specData = ((MapValue) spec).getMap().entrySet().stream().collect(Collectors.toMap(e -> e.getKey().getString(), Map.Entry::getValue)); + final String argument = typeData.getKey().getString(); + final Value spec = typeData.getValue(); + if (!(spec instanceof final MapValue specMap)) + { + throw CommandArgument.error("Spec for '" + argument + "' should be a map"); + } + final Map specData = specMap.getMap().entrySet().stream().collect(Collectors.toMap(e -> e.getKey().getString(), Map.Entry::getValue)); appArgTypes.put(argument, CommandArgument.buildFromConfig(argument, specData, this)); } } } - public Boolean addAppCommands(Consumer notifier) + public Boolean addAppCommands(final Consumer notifier) { try { readCustomArgumentTypes(); } - catch (CommandSyntaxException e) + catch (final CommandSyntaxException e) { - notifier.accept(Messenger.c("r Error when handling of setting up custom argument types: "+e.getMessage())); + notifier.accept(Messenger.c("r Error when handling of setting up custom argument types: " + e.getMessage())); return false; } if (appConfig.get(StringValue.of("commands")) != null) @@ -405,17 +446,15 @@ public Boolean addAppCommands(Consumer notifier) } try { - LiteralArgumentBuilder command = readCommands(commandValidator); + final LiteralArgumentBuilder command = readCommands(commandValidator); if (command != null) { registerCommand(command); return true; } - else { - return false; - } + return false; } - catch (CommandSyntaxException cse) + catch (final CommandSyntaxException cse) { // failed notifier.accept(Messenger.c("r Failed to build command system: ", cse.getRawMessage())); @@ -425,30 +464,36 @@ public Boolean addAppCommands(Consumer notifier) } return addLegacyCommand(notifier); } - - public void checkModVersionRequirements(Value reqs) { + + public void checkModVersionRequirements(final Value reqs) + { if (reqs == null) + { return; - if (!(reqs instanceof MapValue)) + } + if (!(reqs instanceof final MapValue map)) { throw new InternalExpressionException("`requires` field must be a map of mod dependencies or a function to be executed"); } - Map requirements = ((MapValue)reqs).getMap(); - for (Entry requirement : requirements.entrySet()) + final Map requirements = map.getMap(); + for (final Entry requirement : requirements.entrySet()) { - String requiredModId = requirement.getKey().getString(); - String stringPredicate = requirement.getValue().getString(); - VersionPredicate predicate; - try { + final String requiredModId = requirement.getKey().getString(); + final String stringPredicate = requirement.getValue().getString(); + final VersionPredicate predicate; + try + { predicate = VersionPredicate.parse(stringPredicate); - } catch (VersionParsingException e) { + } + catch (final VersionParsingException e) + { throw new InternalExpressionException("Failed to parse version conditions for '" + requiredModId + "' in 'requires': " + e.getMessage()); } - ModContainer mod = FabricLoader.getInstance().getModContainer(requiredModId).orElse(null); + final ModContainer mod = FabricLoader.getInstance().getModContainer(requiredModId).orElse(null); if (mod != null) { - Version presentVersion = mod.getMetadata().getVersion(); + final Version presentVersion = mod.getMetadata().getVersion(); if (predicate.test(presentVersion) || (FabricLoader.getInstance().isDevelopmentEnvironment() && !(presentVersion instanceof SemanticVersion))) { // in a dev env, mod version is usually replaced with ${version}, and that isn't semantic continue; @@ -458,10 +503,12 @@ public void checkModVersionRequirements(Value reqs) { } } - private Boolean addLegacyCommand(Consumer notifier) + private Boolean addLegacyCommand(final Consumer notifier) { - if (main == null) return false; - if (getFunction("__command") == null) return false; + if (main == null || getFunction("__command") == null) + { + return false; + } if (scriptServer().isInvalidCommandRoot(getName())) { @@ -469,43 +516,46 @@ private Boolean addLegacyCommand(Consumer notifier) return null; } - Predicate configValidator; + final Predicate configValidator; try { configValidator = getCommandConfigPermissions(); } - catch (CommandSyntaxException e) + catch (final CommandSyntaxException e) { - notifier.accept(Messenger.c("rb "+e.getMessage())); + notifier.accept(Messenger.c("rb " + e.getMessage())); return null; } - String hostName = getName(); + final String hostName = getName(); LiteralArgumentBuilder command = literal(hostName). requires((player) -> commandValidator.test(player) && configValidator.test(player)). - executes( (c) -> + executes((c) -> { - CarpetScriptHost targetHost = scriptServer().modules.get(hostName).retrieveOwnForExecution(c.getSource()); - Value response = targetHost.handleCommandLegacy(c.getSource(),"__command", null, ""); - if (!response.isNull()) Messenger.m(c.getSource(), "gi "+response.getString()); - return (int)response.readInteger(); + final CarpetScriptHost targetHost = scriptServer().modules.get(hostName).retrieveOwnForExecution(c.getSource()); + final Value response = targetHost.handleCommandLegacy(c.getSource(), "__command", null, ""); + if (!response.isNull()) + { + Messenger.m(c.getSource(), "gi " + response.getString()); + } + return (int) response.readInteger(); }); - boolean hasTypeSupport = appConfig.getOrDefault(StringValue.of("legacy_command_type_support"), Value.FALSE).getBoolean(); + final boolean hasTypeSupport = appConfig.getOrDefault(StringValue.of("legacy_command_type_support"), Value.FALSE).getBoolean(); - for (String function : globalFunctionNames(main, s -> !s.startsWith("_")).sorted().collect(Collectors.toList())) + for (final String function : globalFunctionNames(main, s -> !s.startsWith("_")).sorted().collect(Collectors.toList())) { if (hasTypeSupport) { try { - FunctionValue functionValue = getFunction(function); + final FunctionValue functionValue = getFunction(function); command = addPathToCommand( command, CommandToken.parseSpec(CommandToken.specFromSignature(functionValue), this), FunctionArgument.fromCommandSpec(this, functionValue) ); } - catch (CommandSyntaxException e) + catch (final CommandSyntaxException e) { return false; } @@ -516,17 +566,23 @@ private Boolean addLegacyCommand(Consumer notifier) then(literal(function). requires((player) -> scriptServer().modules.get(hostName).getFunction(function) != null). executes((c) -> { - CarpetScriptHost targetHost = scriptServer().modules.get(hostName).retrieveOwnForExecution(c.getSource()); - Value response = targetHost.handleCommandLegacy(c.getSource(),function, null, ""); - if (!response.isNull()) Messenger.m(c.getSource(), "gi " + response.getString()); + final CarpetScriptHost targetHost = scriptServer().modules.get(hostName).retrieveOwnForExecution(c.getSource()); + final Value response = targetHost.handleCommandLegacy(c.getSource(), function, null, ""); + if (!response.isNull()) + { + Messenger.m(c.getSource(), "gi " + response.getString()); + } return (int) response.readInteger(); }). then(argument("args...", StringArgumentType.greedyString()). - executes( (c) -> { - CarpetScriptHost targetHost = scriptServer().modules.get(hostName).retrieveOwnForExecution(c.getSource()); - Value response = targetHost.handleCommandLegacy(c.getSource(),function, null, StringArgumentType.getString(c, "args...")); - if (!response.isNull()) Messenger.m(c.getSource(), "gi "+response.getString()); - return (int)response.readInteger(); + executes((c) -> { + final CarpetScriptHost targetHost = scriptServer().modules.get(hostName).retrieveOwnForExecution(c.getSource()); + final Value response = targetHost.handleCommandLegacy(c.getSource(), function, null, StringArgumentType.getString(c, "args...")); + if (!response.isNull()) + { + Messenger.m(c.getSource(), "gi " + response.getString()); + } + return (int) response.readInteger(); }))); } } @@ -534,39 +590,48 @@ private Boolean addLegacyCommand(Consumer notifier) return true; } - public LiteralArgumentBuilder readCommands(Predicate useValidator) throws CommandSyntaxException + public LiteralArgumentBuilder readCommands(final Predicate useValidator) throws CommandSyntaxException { - Value commands = appConfig.get(StringValue.of("commands")); + final Value commands = appConfig.get(StringValue.of("commands")); - if (commands == null) return null; - if (!(commands instanceof MapValue)) + if (commands == null) + { + return null; + } + if (!(commands instanceof final MapValue map)) + { throw CommandArgument.error("'commands' element in config should be a map"); - List,FunctionArgument>> commandEntries = new ArrayList<>(); + } + final List, FunctionArgument>> commandEntries = new ArrayList<>(); - for (Map.Entry commandsData : ((MapValue)commands).getMap().entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors.toList())) + for (final Map.Entry commandsData : map.getMap().entrySet().stream().sorted(Entry.comparingByKey()).toList()) { - List elements = CommandToken.parseSpec(commandsData.getKey().getString(), this); - FunctionArgument funSpec = FunctionArgument.fromCommandSpec(this, commandsData.getValue()); + final List elements = CommandToken.parseSpec(commandsData.getKey().getString(), this); + final FunctionArgument funSpec = FunctionArgument.fromCommandSpec(this, commandsData.getValue()); commandEntries.add(Pair.of(elements, funSpec)); } commandEntries.sort(new ListComparator<>()); if (!appConfig.getOrDefault(StringValue.of("allow_command_conflicts"), Value.FALSE).getBoolean()) { - for (int i = 0; i < commandEntries.size()-1; i++) + for (int i = 0; i < commandEntries.size() - 1; i++) { - List first = commandEntries.get(i).getKey(); - List other = commandEntries.get(i+1).getKey(); - int checkSize = Math.min(first.size(), other.size()); + final List first = commandEntries.get(i).getKey(); + final List other = commandEntries.get(i + 1).getKey(); + final int checkSize = Math.min(first.size(), other.size()); for (int t = 0; t < checkSize; t++) { - CommandToken tik = first.get(t); - CommandToken tok = other.get(t); + final CommandToken tik = first.get(t); + final CommandToken tok = other.get(t); if (tik.isArgument && tok.isArgument && !tik.surface.equals(tok.surface)) - throw CommandArgument.error("Conflicting commands: \n"+ - " - [" +first.stream().map(tt -> tt.surface).collect(Collectors.joining(" ")) + "] at "+tik.surface+"\n"+ - " - [" +other.stream().map(tt -> tt.surface).collect(Collectors.joining(" ")) + "] at "+tok.surface+"\n"); + { + throw CommandArgument.error("Conflicting commands: \n" + + " - [" + first.stream().map(tt -> tt.surface).collect(Collectors.joining(" ")) + "] at " + tik.surface + "\n" + + " - [" + other.stream().map(tt -> tt.surface).collect(Collectors.joining(" ")) + "] at " + tok.surface + "\n"); + } if (!tik.equals(tok)) + { break; + } } } } @@ -574,37 +639,39 @@ public LiteralArgumentBuilder readCommands(Predicate coords, String arg) + public Value handleCommandLegacy(final CommandSourceStack source, final String call, final List coords, final String arg) { try { - CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet command", CarpetProfiler.TYPE.GENERAL); - Value res = callLegacy(source, call, coords, arg); + final CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet command", CarpetProfiler.TYPE.GENERAL); + final Value res = callLegacy(source, call, coords, arg); CarpetProfiler.end_current_section(currentSection); return res; } - catch (CarpetExpressionException exc) + catch (final CarpetExpressionException exc) { handleErrorWithStack("Error while running custom command", exc); } - catch (ArithmeticException ae) + catch (final ArithmeticException ae) { handleErrorWithStack("Math doesn't compute", ae); } - catch (StackOverflowError soe) + catch (final StackOverflowError soe) { handleErrorWithStack("Your thoughts are too deep", soe); } return Value.NULL; } - public Value handleCommand(CommandSourceStack source, FunctionValue function, List args) + public Value handleCommand(final CommandSourceStack source, final FunctionValue function, final List args) { try { return scriptServer().events.handleEvents.getWhileDisabled(() -> call(source, function, args)); } - catch (CarpetExpressionException exc) + catch (final CarpetExpressionException exc) { handleErrorWithStack("Error while running custom command", exc); } - catch (ArithmeticException ae) + catch (final ArithmeticException ae) { handleErrorWithStack("Math doesn't compute", ae); } - catch (StackOverflowError soe) + catch (final StackOverflowError soe) { handleErrorWithStack("Your thoughts are too deep", soe); } return Value.NULL; } - public Value callLegacy(CommandSourceStack source, String call, List coords, String arg) + public Value callLegacy(final CommandSourceStack source, final String call, final List coords, final String arg) { if (CarpetServer.scriptServer.stopAll) + { throw new CarpetExpressionException("SCARPET PAUSED (unpause with /script resume)", null); - FunctionValue function = getFunction(call); + } + final FunctionValue function = getFunction(call); if (function == null) + { throw new CarpetExpressionException("Couldn't find function '" + call + "' in app '" + this.getName() + "'", null); - List argv = new ArrayList<>(); + } + final List argv = new ArrayList<>(); if (coords != null) - for (Integer i: coords) - argv.add( (c, t) -> new NumericValue(i)); + { + for (final Integer i : coords) + { + argv.add((c, t) -> new NumericValue(i)); + } + } String sign = ""; - for (Tokenizer.Token tok : Tokenizer.simplepass(arg)) + for (final Tokenizer.Token tok : Tokenizer.simplepass(arg)) { switch (tok.type) { case VARIABLE: - LazyValue var = getGlobalVariable(tok.surface); - if (var != null) argv.add(var); + final LazyValue variable = getGlobalVariable(tok.surface); + if (variable != null) + { + argv.add(variable); + } break; case STRINGPARAM: argv.add((c, t) -> new StringValue(tok.surface)); @@ -714,31 +801,30 @@ public Value callLegacy(CommandSourceStack source, String call, List co case LITERAL: try { - String finalSign = sign; - argv.add((c, t) ->new NumericValue(finalSign+tok.surface)); + final String finalSign = sign; + argv.add((c, t) -> new NumericValue(finalSign + tok.surface)); sign = ""; } - catch (NumberFormatException exception) + catch (final NumberFormatException exception) { - throw new CarpetExpressionException("Fail: "+sign+tok.surface+" seems like a number but it is" + + throw new CarpetExpressionException("Fail: " + sign + tok.surface + " seems like a number but it is" + " not a number. Use quotes to ensure its a string", null); } break; case HEX_LITERAL: try { - String finalSign = sign; - argv.add((c, t) -> new NumericValue(new BigInteger(finalSign+tok.surface.substring(2), 16).doubleValue())); + final String finalSign = sign; + argv.add((c, t) -> new NumericValue(new BigInteger(finalSign + tok.surface.substring(2), 16).doubleValue())); sign = ""; } - catch (NumberFormatException exception) + catch (final NumberFormatException exception) { - throw new CarpetExpressionException("Fail: "+sign+tok.surface+" seems like a number but it is" + + throw new CarpetExpressionException("Fail: " + sign + tok.surface + " seems like a number but it is" + " not a number. Use quotes to ensure its a string", null); } break; - case OPERATOR: - case UNARY_OPERATOR: + case OPERATOR, UNARY_OPERATOR: if ((tok.surface.equals("-") || tok.surface.equals("-u")) && sign.isEmpty()) { sign = "-"; @@ -750,22 +836,19 @@ public Value callLegacy(CommandSourceStack source, String call, List co } break; case FUNCTION: - throw new CarpetExpressionException("Fail: passing functions like "+tok.surface+"() to invoke is " + + throw new CarpetExpressionException("Fail: passing functions like " + tok.surface + "() to invoke is " + "not allowed", null); - case OPEN_PAREN: - case COMMA: - case CLOSE_PAREN: - case MARKER: - throw new CarpetExpressionException("Fail: "+tok.surface+" is not allowed in invoke", null); + case OPEN_PAREN, COMMA, CLOSE_PAREN, MARKER: + throw new CarpetExpressionException("Fail: " + tok.surface + " is not allowed in invoke", null); } } - List args = function.getArguments(); + final List args = function.getArguments(); if (argv.size() != args.size()) { - String error = "Fail: stored function "+call+" takes "+args.size()+" arguments, not "+argv.size()+ ":\n"; + String error = "Fail: stored function " + call + " takes " + args.size() + " arguments, not " + argv.size() + ":\n"; for (int i = 0; i < max(argv.size(), args.size()); i++) { - error += (i "+(i " + (i < argv.size() ? argv.get(i).evalValue(null).getString() : "??") + "\n"; } throw new CarpetExpressionException(error, null); } @@ -773,97 +856,102 @@ public Value callLegacy(CommandSourceStack source, String call, List co { // TODO: this is just for now - invoke would be able to invoke other hosts scripts assertAppIntegrity(function.getModule()); - Context context = new CarpetContext(this, source); + final Context context = new CarpetContext(this, source); return scriptServer().events.handleEvents.getWhileDisabled(() -> function.getExpression().evalValue( () -> function.lazyEval(context, Context.VOID, function.getExpression(), function.getToken(), argv), context, Context.VOID )); } - catch (ExpressionException e) + catch (final ExpressionException e) { throw new CarpetExpressionException(e.getMessage(), e.stack); } } - public Value call(CommandSourceStack source, FunctionValue function, List argv) + public Value call(final CommandSourceStack source, final FunctionValue function, final List argv) { if (CarpetServer.scriptServer.stopAll) + { throw new CarpetExpressionException("SCARPET PAUSED (unpause with /script resume)", null); + } - List args = function.getArguments(); + final List args = function.getArguments(); if (argv.size() != args.size()) { - String error = "Fail: stored function "+function.getPrettyString()+" takes "+args.size()+" arguments, not "+argv.size()+ ":\n"; + String error = "Fail: stored function " + function.getPrettyString() + " takes " + args.size() + " arguments, not " + argv.size() + ":\n"; for (int i = 0; i < max(argv.size(), args.size()); i++) { - error += (i "+(i " + (i < argv.size() ? argv.get(i).getString() : "??") + "\n"; } throw new CarpetExpressionException(error, null); } try { assertAppIntegrity(function.getModule()); - Context context = new CarpetContext(this, source); + final Context context = new CarpetContext(this, source); return function.getExpression().evalValue( () -> function.execute(context, Context.VOID, function.getExpression(), function.getToken(), argv), context, Context.VOID ); } - catch (ExpressionException e) + catch (final ExpressionException e) { throw new CarpetExpressionException(e.getMessage(), e.stack); } } - public Value callUDF(CommandSourceStack source, FunctionValue fun, List argv) throws InvalidCallbackException, IntegrityException + public Value callUDF(final CommandSourceStack source, final FunctionValue fun, final List argv) throws InvalidCallbackException, IntegrityException { return callUDF(BlockPos.ZERO, source, fun, argv); } - public Value callUDF(BlockPos origin, CommandSourceStack source, FunctionValue fun, List argv) throws InvalidCallbackException, IntegrityException + public Value callUDF(final BlockPos origin, final CommandSourceStack source, final FunctionValue fun, final List argv) throws InvalidCallbackException, IntegrityException { if (CarpetServer.scriptServer.stopAll) + { return Value.NULL; - try { // cause we can't throw checked exceptions in lambda. Left if be until need to handle these more gracefully + } + try + { // cause we can't throw checked exceptions in lambda. Left if be until need to handle these more gracefully fun.assertArgsOk(argv, (b) -> { throw new InternalExpressionException(""); }); } - catch (InternalExpressionException ignored) + catch (final InternalExpressionException ignored) { throw new InvalidCallbackException(); } try { assertAppIntegrity(fun.getModule()); - Context context = new CarpetContext(this, source, origin); + final Context context = new CarpetContext(this, source, origin); return fun.getExpression().evalValue( () -> fun.execute(context, Context.VOID, fun.getExpression(), fun.getToken(), argv), context, Context.VOID); } - catch (ExpressionException e) + catch (final ExpressionException e) { handleExpressionException("Callback failed", e); } return Value.NULL; } - public Value callNow(FunctionValue fun, List arguments) + public Value callNow(final FunctionValue fun, final List arguments) { - ServerPlayer player = (user==null)?null:scriptServer().server.getPlayerList().getPlayerByName(user); - CommandSourceStack source = (player != null)?player.createCommandSourceStack():scriptServer().server.createCommandSourceStack(); - return scriptServer().events.handleEvents.getWhileDisabled(()->{ - try - { - return callUDF(source, fun, arguments); - } - catch (InvalidCallbackException ignored) - { - return Value.NULL; - } + final ServerPlayer player = (user == null) ? null : scriptServer().server.getPlayerList().getPlayerByName(user); + final CommandSourceStack source = (player != null) ? player.createCommandSourceStack() : scriptServer().server.createCommandSourceStack(); + return scriptServer().events.handleEvents.getWhileDisabled(() -> { + try + { + return callUDF(source, fun, arguments); + } + catch (final InvalidCallbackException ignored) + { + return Value.NULL; + } }); } @@ -872,26 +960,28 @@ public Value callNow(FunctionValue fun, List arguments) public void onClose() { super.onClose(); - FunctionValue closing = getFunction("__on_close"); + final FunctionValue closing = getFunction("__on_close"); if (closing != null && (parent != null || !isPerUser())) - // either global instance of a global task, or - // user host in player scoped app + // either global instance of a global task, or + // user host in player scoped app { callNow(closing, Collections.emptyList()); } if (user == null) { - String markerName = Auxiliary.MARKER_STRING + "_" + ((getName() == null) ? "" : getName()); - for (ServerLevel world : scriptServer().server.getAllLevels()) + final String markerName = Auxiliary.MARKER_STRING + "_" + ((getName() == null) ? "" : getName()); + for (final ServerLevel world : scriptServer().server.getAllLevels()) { - for (Entity e : world.getEntities(EntityType.ARMOR_STAND, (as) -> as.getTags().contains(markerName))) + for (final Entity e : world.getEntities(EntityType.ARMOR_STAND, (as) -> as.getTags().contains(markerName))) { e.discard(); } } if (this.saveTimeout > 0) + { dumpState(); + } } } @@ -905,26 +995,36 @@ private Tag loadState() return Module.getData(main); } - public Tag readFileTag(FileArgument fdesc) + public Tag readFileTag(final FileArgument fdesc) { - if (getName() == null && !fdesc.isShared) return null; + if (getName() == null && !fdesc.isShared) + { + return null; + } if (fdesc.resource != null) + { return fdesc.getNbtData(main); + } if (parent == null) + { return globalState; - return ((CarpetScriptHost)parent).globalState; + } + return ((CarpetScriptHost) parent).globalState; } - public boolean writeTagFile(Tag tag, FileArgument fdesc) + public boolean writeTagFile(final Tag tag, final FileArgument fdesc) { - if (getName() == null && !fdesc.isShared) return false; // if belongs to an app, cannot be default host. + if (getName() == null && !fdesc.isShared) + { + return false; // if belongs to an app, cannot be default host. + } if (fdesc.resource != null) { return fdesc.saveNbtData(main, tag); } - CarpetScriptHost responsibleHost = (parent != null)?(CarpetScriptHost) parent:this; + final CarpetScriptHost responsibleHost = (parent != null) ? (CarpetScriptHost) parent : this; responsibleHost.globalState = tag; if (responsibleHost.saveTimeout == 0) { @@ -934,48 +1034,42 @@ public boolean writeTagFile(Tag tag, FileArgument fdesc) return true; } - public boolean removeResourceFile(FileArgument fdesc) + public boolean removeResourceFile(final FileArgument fdesc) { - if (getName() == null && !fdesc.isShared) return false; // - return fdesc.dropExistingFile(main); + return (getName() != null || fdesc.isShared) && fdesc.dropExistingFile(main); // } - public boolean appendLogFile(FileArgument fdesc, List data) + public boolean appendLogFile(final FileArgument fdesc, final List data) { - if (getName() == null && !fdesc.isShared) return false; // if belongs to an app, cannot be default host. - return fdesc.appendToTextFile(main, data); + return (getName() != null || fdesc.isShared) && fdesc.appendToTextFile(main, data); // if belongs to an app, cannot be default host. } - public List readTextResource(FileArgument fdesc) + public List readTextResource(final FileArgument fdesc) { - if (getName() == null && !fdesc.isShared) return null; - return fdesc.listFile(main); + return getName() == null && !fdesc.isShared ? null : fdesc.listFile(main); } - - public JsonElement readJsonFile(FileArgument fdesc) + + public JsonElement readJsonFile(final FileArgument fdesc) { - if (getName() == null && !fdesc.isShared) return null; - return fdesc.readJsonFile(main); + return getName() == null && !fdesc.isShared ? null : fdesc.readJsonFile(main); } - public Stream listFolder(FileArgument fdesc) + public Stream listFolder(final FileArgument fdesc) { - if (getName() == null && !fdesc.isShared) return null; // - return fdesc.listFolder(main); + return getName() == null && !fdesc.isShared ? null : fdesc.listFolder(main); } - public boolean applyActionForResource(String path, boolean shared, Consumer action) + public boolean applyActionForResource(final String path, final boolean shared, final Consumer action) { - FileArgument fdesc = FileArgument.resourceFromPath(path, FileArgument.Reason.CREATE, shared); + final FileArgument fdesc = FileArgument.resourceFromPath(path, FileArgument.Reason.CREATE, shared); return fdesc.findPathAndApply(main, action); } - public void tick() { if (this.saveTimeout > 0) { - this.saveTimeout --; + this.saveTimeout--; if (this.saveTimeout == 0) { dumpState(); @@ -983,7 +1077,7 @@ public void tick() } } - public void setChatErrorSnooper(CommandSourceStack source) + public void setChatErrorSnooper(final CommandSourceStack source) { responsibleSource = source; errorSnooper = (expr, /*Nullable*/ token, ctx, message) -> @@ -992,15 +1086,15 @@ public void setChatErrorSnooper(CommandSourceStack source) { source.getPlayerOrException(); } - catch (CommandSyntaxException e) + catch (final CommandSyntaxException e) { return null; } - String shebang = message+" in "+expr.getModuleName(); + String shebang = message + " in " + expr.getModuleName(); if (token != null) { - String[] lines = expr.getCodeString().split("\n"); + final String[] lines = expr.getCodeString().split("\n"); if (lines.length > 1) { @@ -1015,7 +1109,7 @@ public void setChatErrorSnooper(CommandSourceStack source) { Messenger.m(source, withLocals("l", lines[token.lineno - 1], ctx)); } - Messenger.m(source, withLocals("l", lines[token.lineno].substring(0, token.linepos), ctx), "r HERE>> ", + Messenger.m(source, withLocals("l", lines[token.lineno].substring(0, token.linepos), ctx), "r HERE>> ", withLocals("l", lines[token.lineno].substring(token.linepos), ctx)); if (lines.length > 1 && token.lineno < lines.length - 1) { @@ -1032,56 +1126,62 @@ public void setChatErrorSnooper(CommandSourceStack source) /** *

Creates a {@link Component} using {@link Messenger} that has the locals in the {@code line} snippet with a hover over - * tooltip with the value of the local at that location

- * @param line The line to find references to locals on + * tooltip with the value of the local at that location

+ * + * @param line The line to find references to locals on * @param context The {@link Context} to extract the locals from - * @param format The format to apply to each part of the line, without the trailing space + * @param format The format to apply to each part of the line, without the trailing space * @return A BaseText of the given line with the given format, that is visibly the same as passing those to Messenger, but with references to the - * locals in the {@link Context} with a hover over tooltip text + * locals in the {@link Context} with a hover over tooltip text * @implNote The implementation of this method is far from perfect, and won't detect actual references to variables, but try to find the strings - * and add the hover effect to anything that equals to any variable name, so short variable names may appear on random positions + * and add the hover effect to anything that equals to any variable name, so short variable names may appear on random positions */ - private static Component withLocals(String format, String line, Context context) + private static Component withLocals(String format, final String line, final Context context) { format += " "; - List stringsToFormat = new ArrayList<>(); - TreeMap posToLocal = new TreeMap<>(); //Holds whether a local variable name is found at a specific index - for (String local: context.variables.keySet()) + final List stringsToFormat = new ArrayList<>(); + final TreeMap posToLocal = new TreeMap<>(); //Holds whether a local variable name is found at a specific index + for (final String local : context.variables.keySet()) { int pos = line.indexOf(local); while (pos != -1) { posToLocal.merge(pos, local, (existingLocal, newLocal) -> { - if (newLocal.length() > existingLocal.length()) // Prefer longer variable names at the same position, since else single chars everywhere - return local; - else - return existingLocal; + // Prefer longer variable names at the same position, since else single chars everywhere + return newLocal.length() > existingLocal.length() ? local : existingLocal; }); pos = line.indexOf(local, pos + 1); } } int lastPos = 0; - for (Entry foundLocal : posToLocal.entrySet()) + for (final Entry foundLocal : posToLocal.entrySet()) { if (foundLocal.getKey() < lastPos) // system isn't perfect: part of another local + { continue; + } stringsToFormat.add(format + line.substring(lastPos, foundLocal.getKey())); stringsToFormat.add(format + foundLocal.getValue()); - Value val = context.variables.get(foundLocal.getValue()).evalValue(context); - String type = val.getTypeString(); + final Value val = context.variables.get(foundLocal.getValue()).evalValue(context); + final String type = val.getTypeString(); String value; - try { + try + { value = val.getPrettyString(); - } catch (StackOverflowError e) { + } + catch (final StackOverflowError e) + { value = "Exception while rendering variable, there seems to be a recursive reference in there"; } stringsToFormat.add("^ Value of '" + foundLocal.getValue() + "' at position (" + type + "): \n" - + value); + + value); lastPos = foundLocal.getKey() + foundLocal.getValue().length(); } if (line.length() != lastPos) - stringsToFormat.add(format + line.substring(lastPos, line.length())); + { + stringsToFormat.add(format + line.substring(lastPos)); + } return Messenger.c(stringsToFormat.toArray()); } @@ -1092,22 +1192,25 @@ public void resetErrorSnooper() super.resetErrorSnooper(); } - public void handleErrorWithStack(String intro, Throwable exception) + public void handleErrorWithStack(final String intro, final Throwable exception) { if (responsibleSource != null) { - if (exception instanceof CarpetExpressionException) ((CarpetExpressionException) exception).printStack(responsibleSource); - String message = exception.getMessage(); - Messenger.m(responsibleSource, "r "+intro+( (message == null || message.isEmpty())?"":": "+message)); + if (exception instanceof final CarpetExpressionException cee) + { + cee.printStack(responsibleSource); + } + final String message = exception.getMessage(); + Messenger.m(responsibleSource, "r " + intro + ((message == null || message.isEmpty()) ? "" : ": " + message)); } else { - CarpetSettings.LOG.error(intro+": "+exception.getMessage()); + CarpetSettings.LOG.error(intro + ": " + exception.getMessage()); } } @Override - synchronized public void handleExpressionException(String message, ExpressionException exc) + public synchronized void handleExpressionException(final String message, final ExpressionException exc) { handleErrorWithStack(message, new CarpetExpressionException(exc.getMessage(), exc.stack)); } @@ -1120,19 +1223,19 @@ public CarpetScriptServer getScriptServer() { return scriptServer(); } - + @Override public CarpetScriptServer scriptServer() { - return (CarpetScriptServer)super.scriptServer(); + return (CarpetScriptServer) super.scriptServer(); } @Override - public boolean issueDeprecation(String feature) + public boolean issueDeprecation(final String feature) { - if(super.issueDeprecation(feature)) + if (super.issueDeprecation(feature)) { - Messenger.m(responsibleSource, "rb '"+feature+"' is deprecated and soon will be removed. Please consult the docs for their replacement"); + Messenger.m(responsibleSource, "rb '" + feature + "' is deprecated and soon will be removed. Please consult the docs for their replacement"); return true; } return false; diff --git a/src/main/java/carpet/script/CarpetScriptServer.java b/src/main/java/carpet/script/CarpetScriptServer.java index 4ddf57a46a..9ae29a2cb6 100644 --- a/src/main/java/carpet/script/CarpetScriptServer.java +++ b/src/main/java/carpet/script/CarpetScriptServer.java @@ -59,35 +59,38 @@ public class CarpetScriptServer extends ScriptServer //make static for now, but will change that later: public static final Logger LOG = LoggerFactory.getLogger("Scarpet"); public final MinecraftServer server; - public CarpetScriptHost globalHost; - public Map modules; - public Set unloadableModules; + public CarpetScriptHost globalHost; + public Map modules; + public Set unloadableModules; public long tickStart; public boolean stopAll; public int tickDepth; - private Set holyMoly; - public CarpetEventServer events; + private Set holyMoly; + public CarpetEventServer events; private static final List bundledModuleData = new ArrayList<>(); private static final List ruleModuleData = new ArrayList<>(); + /** * Registers a Scarpet App to be always available under the {@code /script load} list. - * @see Module#fromJarPath(String, String, boolean) - * + * * @param app The {@link Module} of the app + * @see Module#fromJarPath(String, String, boolean) */ - public static void registerBuiltInApp(Module app) { + public static void registerBuiltInApp(final Module app) + { bundledModuleData.add(app); } /** * Registers a Scarpet App to be used as a Rule App (to be controlled with the value of a Carpet rule). * Libraries should be registered with {@link #registerBuiltInScript(BundledModule)} instead - * @see Module#fromJarPath(String, String, boolean) - * + * * @param app The {@link Module} of the app. + * @see Module#fromJarPath(String, String, boolean) */ - public static void registerSettingsApp(Module app) { + public static void registerSettingsApp(final Module app) + { ruleModuleData.add(app); } @@ -105,7 +108,7 @@ public static void registerSettingsApp(Module app) { registerBuiltInApp(Module.carpetNative("distance_beta", false)); } - public CarpetScriptServer(MinecraftServer server) + public CarpetScriptServer(final MinecraftServer server) { this.server = server; init(); @@ -126,13 +129,14 @@ public void initializeForWorld() { CarpetServer.settingsManager.initializeScarpetRules(); CarpetServer.extensions.forEach(e -> { - if (e.extensionSettingsManager() != null) { + if (e.extensionSettingsManager() != null) + { e.extensionSettingsManager().initializeScarpetRules(); } }); if (CarpetSettings.scriptsAutoload) { - for (String moduleName: listAvailableModules(false)) + for (final String moduleName : listAvailableModules(false)) { addScriptHost(server.createCommandSourceStack(), moduleName, null, true, true, false, null); } @@ -140,40 +144,53 @@ public void initializeForWorld() CarpetEventServer.Event.START.onTick(); } - public Module getModule(String name, boolean allowLibraries) + public Module getModule(final String name, final boolean allowLibraries) { - try { - Path folder = server.getWorldPath(LevelResource.ROOT).resolve("scripts"); - if (!Files.exists(folder)) + try + { + final Path folder = server.getWorldPath(LevelResource.ROOT).resolve("scripts"); + if (!Files.exists(folder)) + { Files.createDirectories(folder); - try (Stream folderLister = Files.list(folder)) { - Optional scriptPath = folderLister - .filter(script -> - script.getFileName().toString().equalsIgnoreCase(name + ".sc") || - (allowLibraries && script.getFileName().toString().equalsIgnoreCase(name+".scl")) - ).findFirst(); + } + try (final Stream folderLister = Files.list(folder)) + { + final Optional scriptPath = folderLister + .filter(script -> + script.getFileName().toString().equalsIgnoreCase(name + ".sc") || + (allowLibraries && script.getFileName().toString().equalsIgnoreCase(name + ".scl")) + ).findFirst(); if (scriptPath.isPresent()) + { return Module.fromPath(scriptPath.get()); + } } if (FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT) { - Path globalFolder = FabricLoader.getInstance().getConfigDir().resolve("carpet/scripts"); - if (!Files.exists(globalFolder)) + final Path globalFolder = FabricLoader.getInstance().getConfigDir().resolve("carpet/scripts"); + if (!Files.exists(globalFolder)) + { Files.createDirectories(globalFolder); - try (Stream folderWalker = Files.walk(globalFolder)) { - Optional scriptPath = folderWalker + } + try (final Stream folderWalker = Files.walk(globalFolder)) + { + final Optional scriptPath = folderWalker .filter(script -> script.getFileName().toString().equalsIgnoreCase(name + ".sc") || (allowLibraries && script.getFileName().toString().equalsIgnoreCase(name + ".scl"))) .findFirst(); if (scriptPath.isPresent()) + { return Module.fromPath(scriptPath.get()); + } } } - } catch (IOException e) { + } + catch (final IOException e) + { CarpetSettings.LOG.error("Exception while loading the app: ", e); } - for (Module moduleData : bundledModuleData) + for (final Module moduleData : bundledModuleData) { if (moduleData.name().equalsIgnoreCase(name) && (allowLibraries || !moduleData.library())) { @@ -182,10 +199,10 @@ public Module getModule(String name, boolean allowLibraries) } return null; } - - public Module getRuleModule(String name) + + public Module getRuleModule(final String name) { - for (Module moduleData : ruleModuleData) + for (final Module moduleData : ruleModuleData) { if (moduleData.name().equalsIgnoreCase(name)) { @@ -195,101 +212,116 @@ public Module getRuleModule(String name) return null; } - public List listAvailableModules(boolean includeBuiltIns) + public List listAvailableModules(final boolean includeBuiltIns) { - List moduleNames = new ArrayList<>(); + final List moduleNames = new ArrayList<>(); if (includeBuiltIns) { - for (Module mi : bundledModuleData) + for (final Module mi : bundledModuleData) { - if (!mi.library() && !mi.name().endsWith("_beta")) moduleNames.add(mi.name()); + if (!mi.library() && !mi.name().endsWith("_beta")) + { + moduleNames.add(mi.name()); + } } } - try { - Path worldScripts = server.getWorldPath(LevelResource.ROOT).resolve("scripts"); - if (!Files.exists(worldScripts)) + try + { + final Path worldScripts = server.getWorldPath(LevelResource.ROOT).resolve("scripts"); + if (!Files.exists(worldScripts)) + { Files.createDirectories(worldScripts); - try (Stream folderLister = Files.list(worldScripts)) { + } + try (final Stream folderLister = Files.list(worldScripts)) + { folderLister - .filter(f -> f.toString().endsWith(".sc")) - .forEach(f -> moduleNames.add(f.getFileName().toString().replaceFirst("\\.sc$","").toLowerCase(Locale.ROOT))); + .filter(f -> f.toString().endsWith(".sc")) + .forEach(f -> moduleNames.add(f.getFileName().toString().replaceFirst("\\.sc$", "").toLowerCase(Locale.ROOT))); } if (includeBuiltIns && (FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT)) { - Path globalScripts = FabricLoader.getInstance().getConfigDir().resolve("carpet/scripts"); + final Path globalScripts = FabricLoader.getInstance().getConfigDir().resolve("carpet/scripts"); if (!Files.exists(globalScripts)) + { Files.createDirectories(globalScripts); - try (Stream folderWalker = Files.walk(globalScripts, FileVisitOption.FOLLOW_LINKS)) { + } + try (final Stream folderWalker = Files.walk(globalScripts, FileVisitOption.FOLLOW_LINKS)) + { folderWalker - .filter(f -> f.toString().endsWith(".sc")) - .forEach(f -> moduleNames.add(f.getFileName().toString().replaceFirst("\\.sc$","").toLowerCase(Locale.ROOT))); + .filter(f -> f.toString().endsWith(".sc")) + .forEach(f -> moduleNames.add(f.getFileName().toString().replaceFirst("\\.sc$", "").toLowerCase(Locale.ROOT))); } } - } catch (IOException e) { + } + catch (final IOException e) + { CarpetSettings.LOG.error("Exception while searching for apps: ", e); } return moduleNames; } - public CarpetScriptHost getAppHostByName(String name) + public CarpetScriptHost getAppHostByName(final String name) { - if (name == null) - return globalHost; - return modules.get(name); + return name == null ? globalHost : modules.get(name); } - public boolean addScriptHost(CommandSourceStack source, String name, Predicate commandValidator, - boolean perPlayer, boolean autoload, boolean isRuleApp, AppStoreManager.StoreNode installer) + public boolean addScriptHost(final CommandSourceStack source, String name, Predicate commandValidator, + final boolean perPlayer, final boolean autoload, final boolean isRuleApp, final AppStoreManager.StoreNode installer) { - CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet load", CarpetProfiler.TYPE.GENERAL); - if (commandValidator == null) commandValidator = p -> true; - long start = System.nanoTime(); + final CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet load", CarpetProfiler.TYPE.GENERAL); + if (commandValidator == null) + { + commandValidator = p -> true; + } + final long start = System.nanoTime(); name = name.toLowerCase(Locale.ROOT); boolean reload = false; if (modules.containsKey(name)) { - if (isRuleApp) return false; + if (isRuleApp) + { + return false; + } removeScriptHost(source, name, false, isRuleApp); reload = true; } - Module module = isRuleApp ? getRuleModule(name) : getModule(name, false); + final Module module = isRuleApp ? getRuleModule(name) : getModule(name, false); if (module == null) { - Messenger.m(source, "r Failed to add "+name+" app: App not found"); + Messenger.m(source, "r Failed to add " + name + " app: App not found"); return false; } - CarpetScriptHost newHost; + final CarpetScriptHost newHost; try { newHost = CarpetScriptHost.create(this, module, perPlayer, source, commandValidator, isRuleApp, installer); } - catch (LoadException e) + catch (final LoadException e) { Messenger.m(source, "r Failed to add " + name + " app" + (e.getMessage() == null ? "" : ": " + e.getMessage())); return false; } - // config needs to be read as we load the app since some events use that info - //if (!newHost.readConfig()) - //{ - // Messenger.m(source, "r Failed to add "+name+" app: invalid app config (via '__config()' function)"); - // return false; - //} modules.put(name, newHost); - if (!isRuleApp) unloadableModules.add(name); + if (!isRuleApp) + { + unloadableModules.add(name); + } if (autoload && !newHost.persistenceRequired) { removeScriptHost(source, name, false, false); return false; } - //addEvents(source, name); - String action = (installer!=null)?(reload?"reinstalled":"installed"):(reload?"reloaded":"loaded"); + final String action = (installer != null) ? (reload ? "reinstalled" : "installed") : (reload ? "reloaded" : "loaded"); - String finalName = name; - Boolean isCommandAdded = newHost.addAppCommands(s -> { - if (!isRuleApp) Messenger.m(source, Messenger.c("r Failed to add app '" + finalName + "': ", s)); + final String finalName = name; + final Boolean isCommandAdded = newHost.addAppCommands(s -> { + if (!isRuleApp) + { + Messenger.m(source, Messenger.c("r Failed to add app '" + finalName + "': ", s)); + } }); if (isCommandAdded == null) // error should be dispatched { @@ -299,17 +331,23 @@ public boolean addScriptHost(CommandSourceStack source, String name, Predicate {events.tick(); return null;}); + events.handleEvents.getWhileDisabled(() -> { + events.tick(); + return null; + }); CarpetProfiler.end_current_section(token); token = CarpetProfiler.start_section(null, "Scarpet app data", CarpetProfiler.TYPE.GENERAL); - for (CarpetScriptHost host : modules.values()) + for (final CarpetScriptHost host : modules.values()) { host.tick(); } @@ -393,14 +451,14 @@ public void tick() public void onClose() { CarpetEventServer.Event.SHUTDOWN.onTick(); - for (CarpetScriptHost host : modules.values()) + for (final CarpetScriptHost host : modules.values()) { host.onClose(); events.removeAllHostEvents(host); } } - public void onPlayerJoin(ServerPlayer player) + public void onPlayerJoin(final ServerPlayer player) { modules.values().forEach(h -> { @@ -410,36 +468,38 @@ public void onPlayerJoin(ServerPlayer player) { h.retrieveOwnForExecution(player.createCommandSourceStack()); } - catch (CommandSyntaxException ignored) + catch (final CommandSyntaxException ignored) { } } }); } - private static record TransferData(boolean perUser, Predicate commandValidator, boolean isRuleApp) + private record TransferData(boolean perUser, Predicate commandValidator, + boolean isRuleApp) { - private TransferData(CarpetScriptHost host) + private TransferData(final CarpetScriptHost host) { this(host.perUser, host.commandValidator, host.isRuleApp); } } - public void reload(MinecraftServer server) + public void reload(final MinecraftServer server) { - Map apps = new HashMap<>(); + final Map apps = new HashMap<>(); modules.forEach((s, h) -> apps.put(s, new TransferData(h))); apps.keySet().forEach(s -> removeScriptHost(server.createCommandSourceStack(), s, false, false)); CarpetEventServer.Event.clearAllBuiltinEvents(); init(); - apps.forEach((s, data) -> addScriptHost(server.createCommandSourceStack(), s,data.commandValidator, data.perUser,false, data.isRuleApp, null)); + apps.forEach((s, data) -> addScriptHost(server.createCommandSourceStack(), s, data.commandValidator, data.perUser, false, data.isRuleApp, null)); } public void reAddCommands() { - modules.values().forEach(host -> host.addAppCommands(s -> {})); + modules.values().forEach(host -> host.addAppCommands(s -> { + })); } - + public static void parseFunctionClasses() { ExpressionException.prepareForDoom(); // see fc-#1172 @@ -451,7 +511,7 @@ public static void parseFunctionClasses() AnnotationParser.parseFunctionClass(Loops.class); AnnotationParser.parseFunctionClass(Sys.class); AnnotationParser.parseFunctionClass(Threading.class); - + // API AnnotationParser.parseFunctionClass(Auxiliary.class); AnnotationParser.parseFunctionClass(BlockIterators.class); diff --git a/src/main/java/carpet/script/Context.java b/src/main/java/carpet/script/Context.java index 748da05067..430159caf6 100644 --- a/src/main/java/carpet/script/Context.java +++ b/src/main/java/carpet/script/Context.java @@ -13,6 +13,7 @@ public enum Type { NONE, VOID, BOOLEAN, NUMBER, STRING, LIST, ITERATOR, SIGNATURE, LOCALIZATION, LVALUE, MAPDEF } + public static final Type NONE = Type.NONE; public static final Type VOID = Type.VOID; public static final Type BOOLEAN = Type.BOOLEAN; @@ -29,32 +30,32 @@ public enum Type public final ScriptHost host; - public Context(ScriptHost host) + public Context(final ScriptHost host) { this.host = host; } - public LazyValue getVariable(String name) + public LazyValue getVariable(final String name) { return variables.get(name); } - public void setVariable(String name, LazyValue lv) + public void setVariable(final String name, final LazyValue lv) { variables.put(name, lv); } - public void delVariable(String variable) + public void delVariable(final String variable) { variables.remove(variable); } - public void removeVariablesMatching(String varname) + public void removeVariablesMatching(final String varname) { variables.entrySet().removeIf(e -> e.getKey().startsWith(varname)); } - public Context with(String variable, LazyValue lv) + public Context with(final String variable, final LazyValue lv) { variables.put(variable, lv); return this; @@ -67,7 +68,7 @@ public Set getAllVariableNames() public Context recreate() { - Context ctx = duplicate(); + final Context ctx = duplicate(); ctx.initialize(); return ctx; } @@ -84,12 +85,12 @@ public Context duplicate() { return new Context(this.host); } + public ScriptHost.ErrorSnooper getErrorSnooper() { return host.errorSnooper; } - /** * immutable context only for reason on reporting access violations in evaluating expressions in optimizization * mode detecting any potential violations that may happen on the way @@ -97,10 +98,11 @@ public ScriptHost.ErrorSnooper getErrorSnooper() public static class ContextForErrorReporting extends Context { public ScriptHost.ErrorSnooper optmizerEerrorSnooper; - public ContextForErrorReporting(Context parent) + + public ContextForErrorReporting(final Context parent) { super(null); - optmizerEerrorSnooper = parent.host.errorSnooper; + optmizerEerrorSnooper = parent.host.errorSnooper; } @Override @@ -116,31 +118,64 @@ public void badProgrammer() "of scarpet authors. Please report this issue directly to the scarpet issue tracker"); } + @Override - public LazyValue getVariable(String name) { badProgrammer(); return null;} + public LazyValue getVariable(final String name) + { + badProgrammer(); + return null; + } @Override - public void setVariable(String name, LazyValue lv) { badProgrammer(); } + public void setVariable(final String name, final LazyValue lv) + { + badProgrammer(); + } @Override - public void delVariable(String variable) { badProgrammer(); } + public void delVariable(final String variable) + { + badProgrammer(); + } @Override - public void removeVariablesMatching(String varname) { badProgrammer(); } + public void removeVariablesMatching(final String varname) + { + badProgrammer(); + } @Override - public Context with(String variable, LazyValue lv) { badProgrammer(); return this; } + public Context with(final String variable, final LazyValue lv) + { + badProgrammer(); + return this; + } @Override - public Set getAllVariableNames() { badProgrammer(); return null;} + public Set getAllVariableNames() + { + badProgrammer(); + return null; + } @Override - public Context recreate() { badProgrammer(); return null;} + public Context recreate() + { + badProgrammer(); + return null; + } @Override - protected void initialize() { badProgrammer();} + protected void initialize() + { + badProgrammer(); + } @Override - public Context duplicate() { badProgrammer(); return null;} + public Context duplicate() + { + badProgrammer(); + return null; + } } } diff --git a/src/main/java/carpet/script/EntityEventsGroup.java b/src/main/java/carpet/script/EntityEventsGroup.java index a249f67cbe..41b1dc3e8b 100644 --- a/src/main/java/carpet/script/EntityEventsGroup.java +++ b/src/main/java/carpet/script/EntityEventsGroup.java @@ -8,72 +8,93 @@ import carpet.script.value.StringValue; import carpet.script.value.Value; import carpet.script.value.ValueConversions; + import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; + import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.Entity; import net.minecraft.world.phys.Vec3; public class EntityEventsGroup { - private static record EventKey(String host, String user) {} + private record EventKey(String host, String user) + { + } + private final Map> actions; private final Entity entity; - public EntityEventsGroup(Entity e) + + public EntityEventsGroup(final Entity e) { actions = new HashMap<>(); entity = e; } - public void onEvent(Event type, Object... args) + public void onEvent(final Event type, final Object... args) { - if (actions.isEmpty()) return; // most of the cases, trying to be nice - Map actionSet = actions.get(type); - if (actionSet == null) return; - if (CarpetServer.scriptServer == null) return; // executed after world is closin down - for (Iterator> iterator = actionSet.entrySet().iterator(); iterator.hasNext(); ) + if (actions.isEmpty()) { - Map.Entry action = iterator.next(); - EventKey key = action.getKey(); - ScriptHost host = CarpetServer.scriptServer.getAppHostByName(key.host()); + return; // most of the cases, trying to be nice + } + final Map actionSet = actions.get(type); + if (actionSet == null) + { + return; + } + if (CarpetServer.scriptServer == null) + { + return; // executed after world is closin down + } + for (final Iterator> iterator = actionSet.entrySet().iterator(); iterator.hasNext(); ) + { + final Map.Entry action = iterator.next(); + final EventKey key = action.getKey(); + final ScriptHost host = CarpetServer.scriptServer.getAppHostByName(key.host()); if (host == null) { iterator.remove(); continue; } - if (key.user() != null) + if (key.user() != null && entity.getServer().getPlayerList().getPlayerByName(key.user()) == null) { - if (entity.getServer().getPlayerList().getPlayerByName(key.user())==null) - { - iterator.remove(); - continue; - } + iterator.remove(); + continue; } if (type.call(action.getValue(), entity, args) == CarpetEventServer.CallbackResult.FAIL) + { iterator.remove(); + } + } + if (actionSet.isEmpty()) + { + actions.remove(type); } - if (actionSet.isEmpty()) actions.remove(type); } - public void addEvent(Event type, ScriptHost host, FunctionValue fun, List extraargs) + public void addEvent(final Event type, final ScriptHost host, final FunctionValue fun, final List extraargs) { - EventKey key = new EventKey(host.getName(), host.user); + final EventKey key = new EventKey(host.getName(), host.user); if (fun != null) { - CarpetEventServer.Callback call = type.create(key, fun, extraargs); + final CarpetEventServer.Callback call = type.create(key, fun, extraargs); if (call == null) - throw new InternalExpressionException("wrong number of arguments for callback, required "+type.argcount); + { + throw new InternalExpressionException("wrong number of arguments for callback, required " + type.argcount); + } actions.computeIfAbsent(type, k -> new HashMap<>()).put(key, call); } else { actions.computeIfAbsent(type, k -> new HashMap<>()).remove(key); if (actions.get(type).isEmpty()) + { actions.remove(type); + } } } @@ -84,11 +105,11 @@ public static class Event public static final Event ON_DEATH = new Event("on_death", 1) { @Override - public List makeArgs(Entity entity, Object... providedArgs) + public List makeArgs(final Entity entity, final Object... providedArgs) { return Arrays.asList( new EntityValue(entity), - new StringValue((String)providedArgs[0]) + new StringValue((String) providedArgs[0]) ); } }; @@ -97,22 +118,22 @@ public List makeArgs(Entity entity, Object... providedArgs) public static final Event ON_DAMAGE = new Event("on_damaged", 3) { @Override - public List makeArgs(Entity entity, Object... providedArgs) + public List makeArgs(final Entity entity, final Object... providedArgs) { - float amount = (Float)providedArgs[0]; - DamageSource source = (DamageSource)providedArgs[1]; + final float amount = (Float) providedArgs[0]; + final DamageSource source = (DamageSource) providedArgs[1]; return Arrays.asList( new EntityValue(entity), new NumericValue(amount), new StringValue(source.getMsgId()), - source.getEntity()==null?Value.NULL:new EntityValue(source.getEntity()) + source.getEntity() == null ? Value.NULL : new EntityValue(source.getEntity()) ); } }; public static final Event ON_MOVE = new Event("on_move", 3) { @Override - public List makeArgs(Entity entity, Object... providedArgs) + public List makeArgs(final Entity entity, final Object... providedArgs) { return Arrays.asList( new EntityValue(entity), @@ -125,26 +146,30 @@ public List makeArgs(Entity entity, Object... providedArgs) public final int argcount; public final String id; - public Event(String identifier, int args) + + public Event(final String identifier, final int args) { id = identifier; - argcount = args+1; // entity is not extra + argcount = args + 1; // entity is not extra byName.put(identifier, this); } - public CarpetEventServer.Callback create(EventKey key, FunctionValue function, List extraArgs) + + public CarpetEventServer.Callback create(final EventKey key, final FunctionValue function, final List extraArgs) { - if ((function.getArguments().size()-(extraArgs == null ? 0 : extraArgs.size())) != argcount) + if ((function.getArguments().size() - (extraArgs == null ? 0 : extraArgs.size())) != argcount) { return null; } return new CarpetEventServer.Callback(key.host(), key.user(), function, extraArgs); } - public CarpetEventServer.CallbackResult call(CarpetEventServer.Callback tickCall, Entity entity, Object ... args) + + public CarpetEventServer.CallbackResult call(final CarpetEventServer.Callback tickCall, final Entity entity, final Object... args) { - assert args.length == argcount-1; + assert args.length == argcount - 1; return tickCall.execute(entity.createCommandSourceStack(), makeArgs(entity, args)); } - protected List makeArgs(Entity entity, Object ... args) + + protected List makeArgs(final Entity entity, final Object... args) { return Collections.singletonList(new EntityValue(entity)); } diff --git a/src/main/java/carpet/script/Expression.java b/src/main/java/carpet/script/Expression.java index 90f493c276..c9aca6af0d 100644 --- a/src/main/java/carpet/script/Expression.java +++ b/src/main/java/carpet/script/Expression.java @@ -44,9 +44,7 @@ import java.util.List; import java.util.Map; import java.util.Set; -import java.util.function.BiFunction; -import java.util.function.Function; -import java.util.function.Supplier; +import java.util.function.*; import java.util.stream.Collectors; import static java.lang.Math.max; @@ -54,9 +52,15 @@ public class Expression { - /** The current infix expression */ + /** + * The current infix expression + */ private String expression; - String getCodeString() {return expression;} + + String getCodeString() + { + return expression; + } private boolean allowNewlineSubstitutions = true; private boolean allowComments = false; @@ -74,23 +78,36 @@ public void asATextSource() allowComments = true; } - public void asAModule(Module mi) + public void asAModule(final Module mi) { module = mi; } - /** Cached AST (Abstract Syntax Tree) (root) of the expression */ + /** + * Cached AST (Abstract Syntax Tree) (root) of the expression + */ private LazyValue ast = null; - /** script specific operatos and built-in functions */ + /** + * script specific operatos and built-in functions + */ private final Map operators = new Object2ObjectOpenHashMap<>(); - public boolean isAnOperator(String opname) { return operators.containsKey(opname) || operators.containsKey(opname+"u");} - private final Map functions = new Object2ObjectOpenHashMap<>(); - public Set getFunctionNames() {return functions.keySet();} + public boolean isAnOperator(final String opname) + { + return operators.containsKey(opname) || operators.containsKey(opname + "u"); + } + + private final Map functions = new Object2ObjectOpenHashMap<>(); + + public Set getFunctionNames() + { + return functions.keySet(); + } private final Map functionalEquivalence = new Object2ObjectOpenHashMap<>(); - public void addFunctionalEquivalence(String operator, String function) + + public void addFunctionalEquivalence(final String operator, final String function) { assert operators.containsKey(operator); assert functions.containsKey(function); @@ -105,27 +122,30 @@ public void addFunctionalEquivalence(String operator, String function) "false", Value.FALSE ); - protected Value getConstantFor(String surface) + protected Value getConstantFor(final String surface) { return constants.get(surface); } - public List getExpressionSnippet(Tokenizer.Token token) + public List getExpressionSnippet(final Tokenizer.Token token) { - String code = this.getCodeString(); - List output = new ArrayList<>(getExpressionSnippetLeftContext(token, code, 1)); - List context = getExpressionSnippetContext(token, code); - output.add(context.get(0)+" HERE>> "+context.get(1)); + final String code = this.getCodeString(); + final List output = new ArrayList<>(getExpressionSnippetLeftContext(token, code, 1)); + final List context = getExpressionSnippetContext(token, code); + output.add(context.get(0) + " HERE>> " + context.get(1)); output.addAll(getExpressionSnippetRightContext(token, code, 1)); return output; } - private static List getExpressionSnippetLeftContext(Tokenizer.Token token, String expr, int contextsize) + private static List getExpressionSnippetLeftContext(final Tokenizer.Token token, final String expr, final int contextsize) { - List output = new ArrayList<>(); - String[] lines = expr.split("\n"); - if (lines.length == 1) return output; - for (int lno=token.lineno-1; lno >=0 && output.size() < contextsize; lno-- ) + final List output = new ArrayList<>(); + final String[] lines = expr.split("\n"); + if (lines.length == 1) + { + return output; + } + for (int lno = token.lineno - 1; lno >= 0 && output.size() < contextsize; lno--) { output.add(lines[lno]); } @@ -133,10 +153,10 @@ private static List getExpressionSnippetLeftContext(Tokenizer.Token toke return output; } - private static List getExpressionSnippetContext(Tokenizer.Token token, String expr) + private static List getExpressionSnippetContext(final Tokenizer.Token token, final String expr) { - List output = new ArrayList<>(); - String[] lines = expr.split("\n"); + final List output = new ArrayList<>(); + final String[] lines = expr.split("\n"); if (lines.length > 1) { output.add(lines[token.lineno].substring(0, token.linepos)); @@ -144,18 +164,21 @@ private static List getExpressionSnippetContext(Tokenizer.Token token, S } else { - output.add( expr.substring(max(0, token.pos-40), token.pos)); - output.add( expr.substring(token.pos, min(token.pos+1+40, expr.length()))); + output.add(expr.substring(max(0, token.pos - 40), token.pos)); + output.add(expr.substring(token.pos, min(token.pos + 1 + 40, expr.length()))); } return output; } - private static List getExpressionSnippetRightContext(Tokenizer.Token token, String expr, int contextsize) + private static List getExpressionSnippetRightContext(final Tokenizer.Token token, final String expr, final int contextsize) { - List output = new ArrayList<>(); - String[] lines = expr.split("\n"); - if (lines.length == 1) { return output; } - for (int lno=token.lineno+1; lno < lines.length && output.size() < contextsize; lno++ ) + final List output = new ArrayList<>(); + final String[] lines = expr.split("\n"); + if (lines.length == 1) + { + return output; + } + for (int lno = token.lineno + 1; lno < lines.length && output.size() < contextsize; lno++) { output.add(lines[lno]); } @@ -163,34 +186,37 @@ private static List getExpressionSnippetRightContext(Tokenizer.Token tok } - public void addLazyUnaryOperator(String surface, int precedence, boolean leftAssoc, boolean pure, Function staticTyper, - TriFunction lazyfun) + public void addLazyUnaryOperator(final String surface, final int precedence, final boolean leftAssoc, final boolean pure, final Function staticTyper, + final TriFunction lazyfun) { - operators.put(surface+"u", new AbstractLazyOperator(precedence, leftAssoc) + operators.put(surface + "u", new AbstractLazyOperator(precedence, leftAssoc) { @Override - public boolean pure() { + public boolean pure() + { return pure; } @Override - public boolean transitive() { + public boolean transitive() + { return false; } @Override - public Context.Type staticType(Context.Type outerType) { + public Context.Type staticType(final Context.Type outerType) + { return staticTyper.apply(outerType); } @Override - public LazyValue lazyEval(Context c, Context.Type t, Expression e, Tokenizer.Token token, LazyValue v, LazyValue v2) + public LazyValue lazyEval(final Context c, final Context.Type t, final Expression e, final Tokenizer.Token token, final LazyValue v, final LazyValue v2) { try { return lazyfun.apply(c, t, v); } - catch (RuntimeException exc) + catch (final RuntimeException exc) { throw handleCodeException(c, exc, e, token); } @@ -199,29 +225,31 @@ public LazyValue lazyEval(Context c, Context.Type t, Expression e, Tokenizer.Tok } - public void addLazyBinaryOperatorWithDelegation(String surface, int precedence, boolean leftAssoc, boolean pure, - SexFunction lazyfun) + public void addLazyBinaryOperatorWithDelegation(final String surface, final int precedence, final boolean leftAssoc, final boolean pure, + final SexFunction lazyfun) { operators.put(surface, new AbstractLazyOperator(precedence, leftAssoc) { @Override - public boolean pure() { + public boolean pure() + { return pure; } @Override - public boolean transitive() { + public boolean transitive() + { return false; } @Override - public LazyValue lazyEval(Context c, Context.Type type, Expression e, Tokenizer.Token t, LazyValue v1, LazyValue v2) + public LazyValue lazyEval(final Context c, final Context.Type type, final Expression e, final Tokenizer.Token t, final LazyValue v1, final LazyValue v2) { try { return lazyfun.apply(c, type, e, t, v1, v2); } - catch (RuntimeException exc) + catch (final RuntimeException exc) { throw handleCodeException(c, exc, e, t); } @@ -229,35 +257,37 @@ public LazyValue lazyEval(Context c, Context.Type type, Expression e, Tokenizer. }); } - public void addCustomFunction(String name, ILazyFunction fun) + public void addCustomFunction(final String name, final ILazyFunction fun) { functions.put(name, fun); } - public void addLazyFunctionWithDelegation(String name, int numpar, boolean pure, boolean transitive, - QuinnFunction, LazyValue> lazyfun) + public void addLazyFunctionWithDelegation(final String name, final int numpar, final boolean pure, final boolean transitive, + final QuinnFunction, LazyValue> lazyfun) { functions.put(name, new AbstractLazyFunction(numpar, name) { @Override - public boolean pure() { + public boolean pure() + { return pure; } @Override - public boolean transitive() { + public boolean transitive() + { return transitive; } @Override - public LazyValue lazyEval(Context c, Context.Type type, Expression e, Tokenizer.Token t, List lv) + public LazyValue lazyEval(final Context c, final Context.Type type, final Expression e, final Tokenizer.Token t, final List lv) { ILazyFunction.checkInterrupts(); try { return lazyfun.apply(c, type, e, t, lv); } - catch (RuntimeException exc) + catch (final RuntimeException exc) { throw handleCodeException(c, exc, e, t); } @@ -265,30 +295,32 @@ public LazyValue lazyEval(Context c, Context.Type type, Expression e, Tokenizer. }); } - public void addFunctionWithDelegation(String name, int numpar, boolean pure, boolean transitive, - QuinnFunction, Value> fun) + public void addFunctionWithDelegation(final String name, final int numpar, final boolean pure, final boolean transitive, + final QuinnFunction, Value> fun) { functions.put(name, new AbstractLazyFunction(numpar, name) { @Override - public boolean pure() { + public boolean pure() + { return pure; } @Override - public boolean transitive() { + public boolean transitive() + { return transitive; } @Override - public LazyValue lazyEval(Context c, Context.Type type, Expression e, Tokenizer.Token t, List lv) + public LazyValue lazyEval(final Context c, final Context.Type type, final Expression e, final Tokenizer.Token t, final List lv) { try { - Value res = fun.apply(c, type, e, t, unpackArgs(lv, c, Context.NONE)); + final Value res = fun.apply(c, type, e, t, unpackArgs(lv, c, Context.NONE)); return (cc, tt) -> res; } - catch (RuntimeException exc) + catch (final RuntimeException exc) { throw handleCodeException(c, exc, e, t); } @@ -296,37 +328,39 @@ public LazyValue lazyEval(Context c, Context.Type type, Expression e, Tokenizer. }); } - public void addLazyBinaryOperator(String surface, int precedence, boolean leftAssoc, boolean pure, Function typer, - QuadFunction lazyfun) + public void addLazyBinaryOperator(final String surface, final int precedence, final boolean leftAssoc, final boolean pure, final Function typer, + final QuadFunction lazyfun) { operators.put(surface, new AbstractLazyOperator(precedence, leftAssoc) { @Override - public boolean pure() { + public boolean pure() + { return pure; } @Override - public boolean transitive() { + public boolean transitive() + { return false; } @Override - public Context.Type staticType(Context.Type outerType) + public Context.Type staticType(final Context.Type outerType) { return typer.apply(outerType); } @Override - public LazyValue lazyEval(Context c, Context.Type t, Expression e, Tokenizer.Token token, LazyValue v1, LazyValue v2) + public LazyValue lazyEval(final Context c, final Context.Type t, final Expression e, final Tokenizer.Token token, final LazyValue v1, final LazyValue v2) { ILazyFunction.checkInterrupts(); try { return lazyfun.apply(c, t, v1, v2); } - catch (RuntimeException exc) + catch (final RuntimeException exc) { throw handleCodeException(c, exc, e, token); } @@ -334,30 +368,32 @@ public LazyValue lazyEval(Context c, Context.Type t, Expression e, Tokenizer.Tok }); } - public void addBinaryContextOperator(String surface, int precedence, boolean leftAssoc, boolean pure, boolean transitive, - QuadFunction fun) + public void addBinaryContextOperator(final String surface, final int precedence, final boolean leftAssoc, final boolean pure, final boolean transitive, + final QuadFunction fun) { operators.put(surface, new AbstractLazyOperator(precedence, leftAssoc) { @Override - public boolean pure() { + public boolean pure() + { return pure; } @Override - public boolean transitive() { + public boolean transitive() + { return transitive; } @Override - public LazyValue lazyEval(Context c, Context.Type t, Expression e, Tokenizer.Token token, LazyValue v1, LazyValue v2) + public LazyValue lazyEval(final Context c, final Context.Type t, final Expression e, final Tokenizer.Token token, final LazyValue v1, final LazyValue v2) { try { - Value ret = fun.apply(c, t, v1.evalValue(c, Context.NONE), v2.evalValue(c, Context.NONE)); + final Value ret = fun.apply(c, t, v1.evalValue(c, Context.NONE), v2.evalValue(c, Context.NONE)); return (cc, tt) -> ret; } - catch (RuntimeException exc) + catch (final RuntimeException exc) { throw handleCodeException(c, exc, e, token); } @@ -365,144 +401,176 @@ public LazyValue lazyEval(Context c, Context.Type t, Expression e, Tokenizer.Tok }); } - public static RuntimeException handleCodeException(Context c, RuntimeException exc, Expression e, Tokenizer.Token token) + public static RuntimeException handleCodeException(final Context c, final RuntimeException exc, final Expression e, final Tokenizer.Token token) { if (exc instanceof ExitStatement) + { return exc; + } if (exc instanceof IntegrityException) + { return exc; - if (exc instanceof InternalExpressionException) - return ((InternalExpressionException) exc).promote(c, e, token); + } + if (exc instanceof final InternalExpressionException iee) + { + return iee.promote(c, e, token); + } if (exc instanceof ArithmeticException) - return new ExpressionException(c, e, token, "Your math is wrong, "+exc.getMessage()); + { + return new ExpressionException(c, e, token, "Your math is wrong, " + exc.getMessage()); + } if (exc instanceof ResolvedException) + { return exc; + } // unexpected really - should be caught earlier and converted to InternalExpressionException CarpetSettings.LOG.error("Unexpected exception while running Scarpet code", exc); return new ExpressionException(c, e, token, "Internal error (please report this issue to Carpet) while evaluating: " + exc); } - public void addUnaryOperator(String surface, boolean leftAssoc, Function fun) + public void addUnaryOperator(final String surface, final boolean leftAssoc, final Function fun) { - operators.put(surface+"u", new AbstractUnaryOperator(Operators.precedence.get("unary+-!..."), leftAssoc) + operators.put(surface + "u", new AbstractUnaryOperator(Operators.precedence.get("unary+-!..."), leftAssoc) { @Override - public Value evalUnary(Value v1) + public Value evalUnary(final Value v1) { return fun.apply(v1); } }); } - public void addBinaryOperator(String surface, int precedence, boolean leftAssoc, BiFunction fun) + public void addBinaryOperator(final String surface, final int precedence, final boolean leftAssoc, final BiFunction fun) { operators.put(surface, new AbstractOperator(precedence, leftAssoc) { @Override - public Value eval(Value v1, Value v2) { return fun.apply(v1, v2); } + public Value eval(final Value v1, final Value v2) + { + return fun.apply(v1, v2); + } }); } - public void addUnaryFunction(String name, Function fun) + public void addUnaryFunction(final String name, final Function fun) { - functions.put(name, new AbstractFunction(1, name) + functions.put(name, new AbstractFunction(1, name) { @Override - public Value eval(List parameters) { return fun.apply(parameters.get(0)); } + public Value eval(final List parameters) + { + return fun.apply(parameters.get(0)); + } }); } - public void addImpureUnaryFunction(String name, Function fun) + public void addImpureUnaryFunction(final String name, final Function fun) { - functions.put(name, new AbstractFunction(1, name) + functions.put(name, new AbstractFunction(1, name) { @Override - public boolean pure() { + public boolean pure() + { return false; } @Override - public Value eval(List parameters) { return fun.apply(parameters.get(0)); } + public Value eval(final List parameters) + { + return fun.apply(parameters.get(0)); + } }); } - public void addBinaryFunction(String name, BiFunction fun) + public void addBinaryFunction(final String name, final BiFunction fun) { functions.put(name, new AbstractFunction(2, name) { @Override - public Value eval(List parameters) { return fun.apply(parameters.get(0), parameters.get(1)); } + public Value eval(final List parameters) + { + return fun.apply(parameters.get(0), parameters.get(1)); + } }); } - public void addFunction(String name, Function, Value> fun) + public void addFunction(final String name, final Function, Value> fun) { functions.put(name, new AbstractFunction(-1, name) { @Override - public Value eval(List parameters) { return fun.apply(parameters); } + public Value eval(final List parameters) + { + return fun.apply(parameters); + } }); } - public void addImpureFunction(String name, Function, Value> fun) + public void addImpureFunction(final String name, final Function, Value> fun) { functions.put(name, new AbstractFunction(-1, name) { @Override - public boolean pure() { + public boolean pure() + { return false; } @Override - public Value eval(List parameters) { return fun.apply(parameters); } + public Value eval(final List parameters) + { + return fun.apply(parameters); + } }); } - public void addMathematicalUnaryFunction(String name, Function fun) + public void addMathematicalUnaryFunction(final String name, final DoubleUnaryOperator fun) { - addUnaryFunction(name, (v) -> new NumericValue(fun.apply(NumericValue.asNumber(v).getDouble()))); + addUnaryFunction(name, (v) -> new NumericValue(fun.applyAsDouble(NumericValue.asNumber(v).getDouble()))); } - public void addMathematicalUnaryIntFunction(String name, Function fun) + public void addMathematicalUnaryIntFunction(final String name, final DoubleToLongFunction fun) { - addUnaryFunction(name, (v) -> new NumericValue(fun.apply(NumericValue.asNumber(v).getDouble()))); + addUnaryFunction(name, (v) -> new NumericValue(fun.applyAsLong(NumericValue.asNumber(v).getDouble()))); } - public void addMathematicalBinaryIntFunction(String name, BiFunction fun) + public void addMathematicalBinaryIntFunction(final String name, final BinaryOperator fun) { addBinaryFunction(name, (w, v) -> new NumericValue(fun.apply(NumericValue.asNumber(w).getLong(), NumericValue.asNumber(v).getLong()))); } - - public void addMathematicalBinaryFunction(String name, BiFunction fun) + + public void addMathematicalBinaryFunction(final String name, final BinaryOperator fun) { addBinaryFunction(name, (w, v) -> new NumericValue(fun.apply(NumericValue.asNumber(w).getDouble(), NumericValue.asNumber(v).getDouble()))); } - public void addLazyFunction(String name, int numParams, TriFunction, LazyValue> fun) + public void addLazyFunction(final String name, final int numParams, final TriFunction, LazyValue> fun) { functions.put(name, new AbstractLazyFunction(numParams, name) { @Override - public boolean pure() { + public boolean pure() + { return false; } @Override - public boolean transitive() { + public boolean transitive() + { return false; } @Override - public LazyValue lazyEval(Context c, Context.Type i, Expression e, Tokenizer.Token t, List lazyParams) + public LazyValue lazyEval(final Context c, final Context.Type i, final Expression e, final Tokenizer.Token t, final List lazyParams) { ILazyFunction.checkInterrupts(); if (numParams >= 0 && lazyParams.size() != numParams) { - String error = "Function '"+name+"' requires "+numParams+" arguments, got "+lazyParams.size()+". "; + final String error = "Function '" + name + "' requires " + numParams + " arguments, got " + lazyParams.size() + ". "; throw new InternalExpressionException(error + (fun instanceof Fluff.UsageProvider up ? up.getUsage() : "")); } @@ -510,7 +578,7 @@ public LazyValue lazyEval(Context c, Context.Type i, Expression e, Tokenizer.Tok { return fun.apply(c, i, lazyParams); } - catch (RuntimeException exc) + catch (final RuntimeException exc) { throw handleCodeException(c, exc, e, t); } @@ -518,29 +586,31 @@ public LazyValue lazyEval(Context c, Context.Type i, Expression e, Tokenizer.Tok }); } - public void addLazyFunction(String name, TriFunction, LazyValue> fun) + public void addLazyFunction(final String name, final TriFunction, LazyValue> fun) { functions.put(name, new AbstractLazyFunction(-1, name) { @Override - public boolean pure() { + public boolean pure() + { return false; } @Override - public boolean transitive() { + public boolean transitive() + { return false; } @Override - public LazyValue lazyEval(Context c, Context.Type i, Expression e, Tokenizer.Token t, List lazyParams) + public LazyValue lazyEval(final Context c, final Context.Type i, final Expression e, final Tokenizer.Token t, final List lazyParams) { ILazyFunction.checkInterrupts(); try { return fun.apply(c, i, lazyParams); } - catch (RuntimeException exc) + catch (final RuntimeException exc) { throw handleCodeException(c, exc, e, t); } @@ -548,35 +618,37 @@ public LazyValue lazyEval(Context c, Context.Type i, Expression e, Tokenizer.Tok }); } - public void addPureLazyFunction(String name, int num_params, Function typer, TriFunction, LazyValue> fun) + public void addPureLazyFunction(final String name, final int num_params, final Function typer, final TriFunction, LazyValue> fun) { functions.put(name, new AbstractLazyFunction(num_params, name) { @Override - public boolean pure() { + public boolean pure() + { return true; } @Override - public boolean transitive() { + public boolean transitive() + { return false; } @Override - public Context.Type staticType(Context.Type outerType) + public Context.Type staticType(final Context.Type outerType) { return typer.apply(outerType); } @Override - public LazyValue lazyEval(Context c, Context.Type i, Expression e, Tokenizer.Token t, List lazyParams) + public LazyValue lazyEval(final Context c, final Context.Type i, final Expression e, final Tokenizer.Token t, final List lazyParams) { ILazyFunction.checkInterrupts(); try { return fun.apply(c, i, lazyParams); } - catch (RuntimeException exc) + catch (final RuntimeException exc) { throw handleCodeException(c, exc, e, t); } @@ -584,30 +656,32 @@ public LazyValue lazyEval(Context c, Context.Type i, Expression e, Tokenizer.Tok }); } - public void addContextFunction(String name, int num_params, TriFunction, Value> fun) + public void addContextFunction(final String name, final int num_params, final TriFunction, Value> fun) { functions.put(name, new AbstractLazyFunction(num_params, name) { @Override - public boolean pure() { + public boolean pure() + { return false; } @Override - public boolean transitive() { + public boolean transitive() + { return false; } @Override - public LazyValue lazyEval(Context c, Context.Type i, Expression e, Tokenizer.Token t, List lazyParams) + public LazyValue lazyEval(final Context c, final Context.Type i, final Expression e, final Tokenizer.Token t, final List lazyParams) { ILazyFunction.checkInterrupts(); try { - Value ret = fun.apply(c, i, unpackArgs(lazyParams, c, Context.NONE)); + final Value ret = fun.apply(c, i, unpackArgs(lazyParams, c, Context.NONE)); return (cc, tt) -> ret; } - catch (RuntimeException exc) + catch (final RuntimeException exc) { throw handleCodeException(c, exc, e, t); } @@ -615,34 +689,37 @@ public LazyValue lazyEval(Context c, Context.Type i, Expression e, Tokenizer.Tok }); } - public void addTypedContextFunction(String name, int num_params, Context.Type reqType, TriFunction, Value> fun) + public void addTypedContextFunction(final String name, final int num_params, final Context.Type reqType, final TriFunction, Value> fun) { functions.put(name, new AbstractLazyFunction(num_params, name) { @Override - public boolean pure() { + public boolean pure() + { return true; } @Override - public boolean transitive() { + public boolean transitive() + { return false; } @Override - public Context.Type staticType(Context.Type outerType) { + public Context.Type staticType(final Context.Type outerType) + { return reqType; } @Override - public LazyValue lazyEval(Context c, Context.Type i, Expression e, Tokenizer.Token t, List lazyParams) + public LazyValue lazyEval(final Context c, final Context.Type i, final Expression e, final Tokenizer.Token t, final List lazyParams) { try { - Value ret = fun.apply(c, i, unpackArgs(lazyParams, c, reqType)); + final Value ret = fun.apply(c, i, unpackArgs(lazyParams, c, reqType)); return (cc, tt) -> ret; } - catch (RuntimeException exc) + catch (final RuntimeException exc) { throw handleCodeException(c, exc, e, t); } @@ -650,34 +727,42 @@ public LazyValue lazyEval(Context c, Context.Type i, Expression e, Tokenizer.Tok }); } - public FunctionValue createUserDefinedFunction(Context context, String name, Expression expr, Tokenizer.Token token, List arguments, String varArgs, List outers, LazyValue code) + public FunctionValue createUserDefinedFunction(final Context context, final String name, final Expression expr, final Tokenizer.Token token, final List arguments, final String varArgs, final List outers, final LazyValue code) { if (functions.containsKey(name)) - throw new ExpressionException(context, expr, token, "Function "+name+" would mask a built-in function"); + { + throw new ExpressionException(context, expr, token, "Function " + name + " would mask a built-in function"); + } Map contextValues = new HashMap<>(); - for (String outer : outers) + for (final String outer : outers) { - LazyValue lv = context.getVariable(outer); + final LazyValue lv = context.getVariable(outer); if (lv == null) { - throw new InternalExpressionException("Variable "+outer+" needs to be defined in outer scope to be used as outer parameter, and cannot be global"); + throw new InternalExpressionException("Variable " + outer + " needs to be defined in outer scope to be used as outer parameter, and cannot be global"); } else { contextValues.put(outer, lv); } } - if (contextValues.isEmpty()) contextValues = null; + if (contextValues.isEmpty()) + { + contextValues = null; + } - FunctionValue result = new FunctionValue(expr, token, name, code, arguments, varArgs, contextValues); + final FunctionValue result = new FunctionValue(expr, token, name, code, arguments, varArgs, contextValues); // do not store lambda definitions - if (!name.equals("_")) context.host.addUserDefinedFunction(context, module, name, result); + if (!name.equals("_")) + { + context.host.addUserDefinedFunction(context, module, name, result); + } return result; } - public void alias(String copy, String original) + public void alias(final String copy, final String original) { - ILazyFunction originalFunction = functions.get(original); + final ILazyFunction originalFunction = functions.get(original); functions.put(copy, new ILazyFunction() { @Override @@ -693,31 +778,34 @@ public boolean numParamsVaries() } @Override - public boolean pure() { + public boolean pure() + { return originalFunction.pure(); } @Override - public boolean transitive() { + public boolean transitive() + { return originalFunction.transitive(); } @Override - public Context.Type staticType(Context.Type outerType) { + public Context.Type staticType(final Context.Type outerType) + { return originalFunction.staticType(outerType); } @Override - public LazyValue lazyEval(Context c, Context.Type type, Expression expr, Tokenizer.Token token, List lazyParams) + public LazyValue lazyEval(final Context c, final Context.Type type, final Expression expr, final Tokenizer.Token token, final List lazyParams) { - c.host.issueDeprecation(copy+"(...)"); + c.host.issueDeprecation(copy + "(...)"); return originalFunction.lazyEval(c, type, expr, token, lazyParams); } }); } - public void setAnyVariable(Context c, String name, LazyValue lv) + public void setAnyVariable(final Context c, final String name, final LazyValue lv) { if (name.startsWith("global_")) { @@ -729,28 +817,35 @@ public void setAnyVariable(Context c, String name, LazyValue lv) } } - public LazyValue getOrSetAnyVariable(Context c, String name) + public LazyValue getOrSetAnyVariable(final Context c, final String name) { - LazyValue var; + LazyValue variable; if (!name.startsWith("global_")) { - var = c.getVariable(name); - if (var != null) return var; + variable = c.getVariable(name); + if (variable != null) + { + return variable; + } + } + variable = c.host.getGlobalVariable(module, name); + if (variable != null) + { + return variable; } - var = c.host.getGlobalVariable(module, name); - if (var != null) return var; - var = (_c, _t ) -> _c.host.strict ? Value.UNDEF.reboundedTo(name) : Value.NULL.reboundedTo(name); - setAnyVariable(c, name, var); - return var; + variable = (_c, _t) -> _c.host.strict ? Value.UNDEF.reboundedTo(name) : Value.NULL.reboundedTo(name); + setAnyVariable(c, name, variable); + return variable; } public static final Expression none = new Expression("null"); + /** * @param expression . */ - public Expression(String expression) + public Expression(final String expression) { - this.expression = expression.stripTrailing().replaceAll("\\r\\n?", "\n").replaceAll("\\t"," "); + this.expression = expression.stripTrailing().replaceAll("\\r\\n?", "\n").replaceAll("\\t", " "); Operators.apply(this); ControlFlow.apply(this); Functions.apply(this); @@ -762,26 +857,25 @@ public Expression(String expression) } - private List shuntingYard(Context c) + private List shuntingYard(final Context c) { - List outputQueue = new ArrayList<>(); - Stack stack = new ObjectArrayList<>(); + final List outputQueue = new ArrayList<>(); + final Stack stack = new ObjectArrayList<>(); - Tokenizer tokenizer = new Tokenizer(c, this, expression, allowComments, allowNewlineSubstitutions); + final Tokenizer tokenizer = new Tokenizer(c, this, expression, allowComments, allowNewlineSubstitutions); // stripping lousy but acceptable semicolons - List cleanedTokens = tokenizer.postProcess(); + final List cleanedTokens = tokenizer.postProcess(); Tokenizer.Token lastFunction = null; Tokenizer.Token previousToken = null; - for (Tokenizer.Token token : cleanedTokens) + for (final Tokenizer.Token token : cleanedTokens) { switch (token.type) { case STRINGPARAM: //stack.push(token); // changed that so strings are treated like literals //break; - case LITERAL: - case HEX_LITERAL: + case LITERAL, HEX_LITERAL: if (previousToken != null && ( previousToken.type == Tokenizer.Token.TokenType.LITERAL || previousToken.type == Tokenizer.Token.TokenType.HEX_LITERAL || @@ -824,9 +918,9 @@ private List shuntingYard(Context c) if (previousToken != null && (previousToken.type == Tokenizer.Token.TokenType.COMMA || previousToken.type == Tokenizer.Token.TokenType.OPEN_PAREN)) { - throw new ExpressionException(c, this, token, "Missing parameter(s) for operator '" + token+"'"); + throw new ExpressionException(c, this, token, "Missing parameter(s) for operator '" + token + "'"); } - ILazyOperator o1 = operators.get(token.surface); + final ILazyOperator o1 = operators.get(token.surface); if (o1 == null) { throw new ExpressionException(c, this, token, "Unknown operator '" + token + "'"); @@ -841,9 +935,9 @@ private List shuntingYard(Context c) if (previousToken != null && previousToken.type != Tokenizer.Token.TokenType.OPERATOR && previousToken.type != Tokenizer.Token.TokenType.COMMA && previousToken.type != Tokenizer.Token.TokenType.OPEN_PAREN) { - throw new ExpressionException(c, this, token, "Invalid position for unary operator " + token ); + throw new ExpressionException(c, this, token, "Invalid position for unary operator " + token); } - ILazyOperator o1 = operators.get(token.surface); + final ILazyOperator o1 = operators.get(token.surface); if (o1 == null) { throw new ExpressionException(c, this, token, "Unknown unary operator '" + token.surface.substring(0, token.surface.length() - 1) + "'"); @@ -854,24 +948,10 @@ private List shuntingYard(Context c) break; } case OPEN_PAREN: - if (previousToken != null) + // removed implicit multiplication in this missing code block + if (previousToken != null && previousToken.type == Tokenizer.Token.TokenType.FUNCTION) { - //if (previousToken.type == Tokenizer.Token.TokenType.LITERAL || previousToken.type == Tokenizer.Token.TokenType.CLOSE_PAREN - // || previousToken.type == Tokenizer.Token.TokenType.VARIABLE - // || previousToken.type == Tokenizer.Token.TokenType.HEX_LITERAL) - //{ - // Implicit multiplication, e.g. 23(a+b) or (a+b)(a-b) - // Tokenizer.Token multiplication = new Tokenizer.Token(); - // multiplication.append("*"); - // multiplication.type = Tokenizer.Token.TokenType.OPERATOR; - // stack.push(multiplication); - //} - // if the ( is preceded by a valid function, then it - // denotes the start of a parameter list - if (previousToken.type == Tokenizer.Token.TokenType.FUNCTION) - { - outputQueue.add(token); - } + outputQueue.add(token); } stack.push(token); break; @@ -897,18 +977,21 @@ private List shuntingYard(Context c) case MARKER: if ("$".equals(token.surface)) { - StringBuilder sb = new StringBuilder(expression); + final StringBuilder sb = new StringBuilder(expression); sb.setCharAt(token.pos, '\n'); expression = sb.toString(); } break; } - if (token.type != Tokenizer.Token.TokenType.MARKER) previousToken = token; + if (token.type != Tokenizer.Token.TokenType.MARKER) + { + previousToken = token; + } } while (!stack.isEmpty()) { - Tokenizer.Token element = stack.pop(); + final Tokenizer.Token element = stack.pop(); if (element.type == Tokenizer.Token.TokenType.OPEN_PAREN || element.type == Tokenizer.Token.TokenType.CLOSE_PAREN) { throw new ExpressionException(c, this, element, "Mismatched parentheses"); @@ -918,7 +1001,7 @@ private List shuntingYard(Context c) return outputQueue; } - private void shuntOperators(List outputQueue, Stack stack, ILazyOperator o1) + private void shuntOperators(final List outputQueue, final Stack stack, final ILazyOperator o1) { Tokenizer.Token nextToken = stack.isEmpty() ? null : stack.top(); while (nextToken != null @@ -932,7 +1015,7 @@ private void shuntOperators(List outputQueue, Stack ast, c, Context.Type.NONE); } - public Value evalValue(Supplier exprProvider, Context c, Context.Type expectedType) + public Value evalValue(final Supplier exprProvider, final Context c, final Context.Type expectedType) { try { return exprProvider.get().evalValue(c, expectedType); } - catch (ContinueStatement | BreakStatement | ReturnStatement exc) + catch (final ContinueStatement | BreakStatement | ReturnStatement exc) { throw new ExpressionException(c, this, "Control flow functions, like continue, break or return, should only be used in loops, and functions respectively."); } - catch (ExitStatement exit) + catch (final ExitStatement exit) { - return exit.retval==null?Value.NULL:exit.retval; + return exit.retval == null ? Value.NULL : exit.retval; } - catch (StackOverflowError ignored) + catch (final StackOverflowError ignored) { throw new ExpressionException(c, this, "Your thoughts are too deep"); } - catch (InternalExpressionException exc) + catch (final InternalExpressionException exc) { - throw new ExpressionException(c, this, "Your expression result is incorrect: "+exc.getMessage()); + throw new ExpressionException(c, this, "Your expression result is incorrect: " + exc.getMessage()); } - catch (ArithmeticException exc) + catch (final ArithmeticException exc) { - throw new ExpressionException(c, this, "The final result is incorrect: "+exc.getMessage()); + throw new ExpressionException(c, this, "The final result is incorrect: " + exc.getMessage()); } } @@ -980,7 +1063,8 @@ public static class ExpressionNode * varying numbers of function parameters. */ public static final ExpressionNode PARAMS_START = new ExpressionNode(null, null, Tokenizer.Token.NONE); - public ExpressionNode(LazyValue op, List args, Tokenizer.Token token) + + public ExpressionNode(final LazyValue op, final List args, final Tokenizer.Token token) { this.op = op; this.args = args; @@ -988,49 +1072,48 @@ public ExpressionNode(LazyValue op, List args, Tokenizer.Token t range = new ArrayList<>(); range.add(token); } - public static ExpressionNode ofConstant(Value val, Tokenizer.Token token) + + public static ExpressionNode ofConstant(final Value val, final Tokenizer.Token token) { return new ExpressionNode(new LazyValue.Constant(val), Collections.emptyList(), token); } } - private ExpressionNode RPNToParseTree(List tokens, Context context) + private ExpressionNode RPNToParseTree(final List tokens, final Context context) { - Stack nodeStack = new ObjectArrayList<>(); + final Stack nodeStack = new ObjectArrayList<>(); for (final Tokenizer.Token token : tokens) { - switch (token.type) - { - case UNARY_OPERATOR: - { + switch (token.type) { + case UNARY_OPERATOR -> { final ExpressionNode node = nodeStack.pop(); - LazyValue result = (c, t) -> operators.get(token.surface).lazyEval(c, t, this, token, node.op, null).evalValue(c, t); + final LazyValue result = (c, t) -> operators.get(token.surface).lazyEval(c, t, this, token, node.op, null).evalValue(c, t); nodeStack.push(new ExpressionNode(result, Collections.singletonList(node), token)); - break; } - case OPERATOR: + case OPERATOR -> { final ExpressionNode v1 = nodeStack.pop(); final ExpressionNode v2 = nodeStack.pop(); - LazyValue result = (c,t) -> operators.get(token.surface).lazyEval(c, t,this, token, v2.op, v1.op).evalValue(c, t); - nodeStack.push(new ExpressionNode(result, List.of(v2, v1), token )); - break; - case VARIABLE: - Value constant = getConstantFor(token.surface); + final LazyValue result = (c, t) -> operators.get(token.surface).lazyEval(c, t, this, token, v2.op, v1.op).evalValue(c, t); + nodeStack.push(new ExpressionNode(result, List.of(v2, v1), token)); + } + case VARIABLE -> { + final Value constant = getConstantFor(token.surface); if (constant != null) { token.morph(Tokenizer.Token.TokenType.CONSTANT, token.surface); nodeStack.push(new ExpressionNode(LazyValue.ofConstant(constant), Collections.emptyList(), token)); } - else { + else + { nodeStack.push(new ExpressionNode(((c, t) -> getOrSetAnyVariable(c, token.surface).evalValue(c, t)), Collections.emptyList(), token)); } - break; - case FUNCTION: - String name = token.surface; - ILazyFunction f; - ArrayList p; - boolean isKnown = functions.containsKey(name); // globals will be evaluated lazily, not at compile time via . + } + case FUNCTION -> { + final String name = token.surface; + final ILazyFunction f; + final ArrayList p; + final boolean isKnown = functions.containsKey(name); // globals will be evaluated lazily, not at compile time via . if (isKnown) { f = functions.get(name); @@ -1053,190 +1136,230 @@ private ExpressionNode RPNToParseTree(List tokens, Context cont token.morph(Tokenizer.Token.TokenType.FUNCTION, "call"); } Collections.reverse(p); - if (nodeStack.top() == ExpressionNode.PARAMS_START) { nodeStack.pop(); - }; - List params = p.stream().map(n -> n.op).collect(Collectors.toList()); - + } + final List params = p.stream().map(n -> n.op).collect(Collectors.toList()); nodeStack.push(new ExpressionNode( (c, t) -> f.lazyEval(c, t, this, token, params).evalValue(c, t), - p,token + p, token )); - break; - case OPEN_PAREN: - nodeStack.push(ExpressionNode.PARAMS_START); - break; - case LITERAL: - Value number; + } + case OPEN_PAREN -> nodeStack.push(ExpressionNode.PARAMS_START); + case LITERAL -> { + final Value number; try { number = new NumericValue(token.surface); } - catch (NumberFormatException exception) + catch (final NumberFormatException exception) { throw new ExpressionException(context, this, token, "Not a number"); } token.morph(Tokenizer.Token.TokenType.CONSTANT, token.surface); nodeStack.push(ExpressionNode.ofConstant(number, token)); - break; - case STRINGPARAM: + } + case STRINGPARAM -> { token.morph(Tokenizer.Token.TokenType.CONSTANT, token.surface); nodeStack.push(ExpressionNode.ofConstant(new StringValue(token.surface), token)); - break; - case HEX_LITERAL: - Value hexNumber; + } + case HEX_LITERAL -> { + final Value hexNumber; try { hexNumber = new NumericValue(new BigInteger(token.surface.substring(2), 16).longValue()); } - catch (NumberFormatException exception) + catch (final NumberFormatException exception) { throw new ExpressionException(context, this, token, "Not a number"); } token.morph(Tokenizer.Token.TokenType.CONSTANT, token.surface); nodeStack.push(ExpressionNode.ofConstant(hexNumber, token)); - break; - default: - throw new ExpressionException(context, this, token, "Unexpected token '" + token.surface + "'"); + } + default -> throw new ExpressionException(context, this, token, "Unexpected token '" + token.surface + "'"); } } return nodeStack.pop(); } - private LazyValue getAST(Context context) + private LazyValue getAST(final Context context) { - //Stack stack = new Stack<>(); - List rpn = shuntingYard(context); + final List rpn = shuntingYard(context); validate(context, rpn); - ExpressionNode root = RPNToParseTree(rpn, context); + final ExpressionNode root = RPNToParseTree(rpn, context); if (!CarpetSettings.scriptsOptimization) + { return root.op; + } - Context optimizeOnlyContext = new Context.ContextForErrorReporting(context); + final Context optimizeOnlyContext = new Context.ContextForErrorReporting(context); if (CarpetSettings.scriptsDebugging) - CarpetScriptServer.LOG.info("Input code size for "+getModuleName()+": " + treeSize(root) + " nodes, " + treeDepth(root) + " deep"); + { + CarpetScriptServer.LOG.info("Input code size for " + getModuleName() + ": " + treeSize(root) + " nodes, " + treeDepth(root) + " deep"); + } // Defined out here to not need to conditionally assign them with debugging disabled int prevTreeSize = -1; int prevTreeDepth = -1; boolean changed = true; - while(changed) { + while (changed) + { changed = false; - while (true) { - if (CarpetSettings.scriptsDebugging) { + while (true) + { + if (CarpetSettings.scriptsDebugging) + { prevTreeSize = treeSize(root); prevTreeDepth = treeDepth(root); } - boolean optimized = compactTree(root, Context.Type.NONE, 0); - if (!optimized) break; + final boolean optimized = compactTree(root, Context.Type.NONE, 0); + if (!optimized) + { + break; + } changed = true; if (CarpetSettings.scriptsDebugging) + { CarpetScriptServer.LOG.info("Compacted from " + prevTreeSize + " nodes, " + prevTreeDepth + " code depth to " + treeSize(root) + " nodes, " + treeDepth(root) + " code depth"); + } } - while (true) { - if (CarpetSettings.scriptsDebugging) { + while (true) + { + if (CarpetSettings.scriptsDebugging) + { prevTreeSize = treeSize(root); prevTreeDepth = treeDepth(root); } - boolean optimized = optimizeTree(optimizeOnlyContext, root, Context.Type.NONE, 0); - if (!optimized) break; + final boolean optimized = optimizeTree(optimizeOnlyContext, root, Context.Type.NONE, 0); + if (!optimized) + { + break; + } changed = true; if (CarpetSettings.scriptsDebugging) + { CarpetScriptServer.LOG.info("Optimized from " + prevTreeSize + " nodes, " + prevTreeDepth + " code depth to " + treeSize(root) + " nodes, " + treeDepth(root) + " code depth"); + } } } return extractOp(optimizeOnlyContext, root, Context.Type.NONE); } - private int treeSize(ExpressionNode node) + private int treeSize(final ExpressionNode node) { - if (node.op instanceof LazyValue.ContextFreeLazyValue) return 1; - return node.args.stream().mapToInt(this::treeSize).sum()+1; + return node.op instanceof LazyValue.ContextFreeLazyValue ? 1 : node.args.stream().mapToInt(this::treeSize).sum() + 1; } - private int treeDepth(ExpressionNode node) + + private int treeDepth(final ExpressionNode node) { - if (node.op instanceof LazyValue.ContextFreeLazyValue) return 1; - return node.args.stream().mapToInt(this::treeDepth).max().orElse(0)+1; + return node.op instanceof LazyValue.ContextFreeLazyValue ? 1 : node.args.stream().mapToInt(this::treeDepth).max().orElse(0) + 1; } - private boolean compactTree(ExpressionNode node, Context.Type expectedType, int indent) { + private boolean compactTree(final ExpressionNode node, final Context.Type expectedType, final int indent) + { // ctx is just to report errors, not values evaluation boolean optimized = false; - Tokenizer.Token.TokenType token = node.token.type; - if (!token.isFunctional()) return false; + final Tokenizer.Token.TokenType token = node.token.type; + if (!token.isFunctional()) + { + return false; + } // input special cases here, like function signature - if (node.op instanceof LazyValue.Constant) return false; // optimized already + if (node.op instanceof LazyValue.Constant) + { + return false; // optimized already + } // function or operator - String symbol = node.token.surface; - Fluff.EvalNode operation = ((token == Tokenizer.Token.TokenType.FUNCTION) ? functions : operators).get(symbol); - Context.Type requestedType = operation.staticType(expectedType); - for (ExpressionNode arg : node.args) { - if (compactTree(arg, requestedType, indent+1)) optimized = true; + final String symbol = node.token.surface; + final Fluff.EvalNode operation = ((token == Tokenizer.Token.TokenType.FUNCTION) ? functions : operators).get(symbol); + final Context.Type requestedType = operation.staticType(expectedType); + for (final ExpressionNode arg : node.args) + { + if (compactTree(arg, requestedType, indent + 1)) + { + optimized = true; + } } - if (expectedType != Context.Type.MAPDEF && symbol.equals("->") && node.args.size() == 2) { - String rop = node.args.get(1).token.surface; + if (expectedType != Context.Type.MAPDEF && symbol.equals("->") && node.args.size() == 2) + { + final String rop = node.args.get(1).token.surface; ExpressionNode returnNode = null; - if ((rop.equals(";") || rop.equals("then"))) { - List thenArgs = node.args.get(1).args; - if (thenArgs.size() > 1 && thenArgs.get(thenArgs.size() - 1).token.surface.equals("return")) { + if ((rop.equals(";") || rop.equals("then"))) + { + final List thenArgs = node.args.get(1).args; + if (thenArgs.size() > 1 && thenArgs.get(thenArgs.size() - 1).token.surface.equals("return")) + { returnNode = thenArgs.get(thenArgs.size() - 1); } - } else if (rop.equals("return")) { + } + else if (rop.equals("return")) + { returnNode = node.args.get(1); } if (returnNode != null) // tail return { - if (returnNode.args.size() > 0) { + if (!returnNode.args.isEmpty()) + { returnNode.op = returnNode.args.get(0).op; returnNode.token = returnNode.args.get(0).token; returnNode.range = returnNode.args.get(0).range; returnNode.args = returnNode.args.get(0).args; if (CarpetSettings.scriptsDebugging) + { CarpetScriptServer.LOG.info(" - Removed unnecessary tail return of " + returnNode.token.surface + " from function body at line " + (returnNode.token.lineno + 1) + ", node depth " + indent); - - } else { + } + } + else + { returnNode.op = LazyValue.ofConstant(Value.NULL); returnNode.token.morph(Tokenizer.Token.TokenType.CONSTANT, ""); returnNode.args = Collections.emptyList(); if (CarpetSettings.scriptsDebugging) + { CarpetScriptServer.LOG.info(" - Removed unnecessary tail return from function body at line " + (returnNode.token.lineno + 1) + ", node depth " + indent); - + } } } } - for (Map.Entry pair : functionalEquivalence.entrySet()) { - String operator = pair.getKey(); - String function = pair.getValue(); + for (final Map.Entry pair : functionalEquivalence.entrySet()) + { + final String operator = pair.getKey(); + final String function = pair.getValue(); if ((symbol.equals(operator) || symbol.equals(function)) && node.args.size() > 0) { - boolean leftOptimizable = operators.get(operator).isLeftAssoc(); - ExpressionNode optimizedChild = node.args.get(leftOptimizable?0:(node.args.size()-1)); - String type = optimizedChild.token.surface; + final boolean leftOptimizable = operators.get(operator).isLeftAssoc(); + final ExpressionNode optimizedChild = node.args.get(leftOptimizable ? 0 : (node.args.size() - 1)); + final String type = optimizedChild.token.surface; if ((type.equals(operator) || type.equals(function)) && (!(optimizedChild.op instanceof LazyValue.ContextFreeLazyValue))) { optimized = true; - List newargs = new ArrayList<>(); + final List newargs = new ArrayList<>(); if (leftOptimizable) { newargs.addAll(optimizedChild.args); for (int i = 1; i < node.args.size(); i++) + { newargs.add(node.args.get(i)); + } } else { - for (int i = 0; i < node.args.size()-1; i++) + for (int i = 0; i < node.args.size() - 1; i++) + { newargs.add(node.args.get(i)); + } newargs.addAll(optimizedChild.args); } if (CarpetSettings.scriptsDebugging) + { CarpetScriptServer.LOG.info(" - " + symbol + "(" + node.args.size() + ") => " + function + "(" + newargs.size() + ") at line " + (node.token.lineno + 1) + ", node depth " + indent); + } node.token.morph(Tokenizer.Token.TokenType.FUNCTION, function); node.args = newargs; } @@ -1245,131 +1368,155 @@ private boolean compactTree(ExpressionNode node, Context.Type expectedType, int return optimized; } - private boolean optimizeTree(Context ctx, ExpressionNode node, Context.Type expectedType, int indent) { + private boolean optimizeTree(final Context ctx, final ExpressionNode node, Context.Type expectedType, final int indent) + { // ctx is just to report errors, not values evaluation boolean optimized = false; - Tokenizer.Token.TokenType token = node.token.type; - if (!token.isFunctional()) return false; - String symbol = node.token.surface; + final Tokenizer.Token.TokenType token = node.token.type; + if (!token.isFunctional()) + { + return false; + } + final String symbol = node.token.surface; // input special cases here, like function signature - if (node.op instanceof LazyValue.Constant) return false; // optimized already + if (node.op instanceof LazyValue.Constant) + { + return false; // optimized already + } // function or operator - Fluff.EvalNode operation = ((token == Tokenizer.Token.TokenType.FUNCTION) ? functions : operators).get(symbol); - Context.Type requestedType = operation.staticType(expectedType); - for (ExpressionNode arg : node.args) { - if (optimizeTree(ctx, arg, requestedType, indent+1)) optimized = true; + final Fluff.EvalNode operation = ((token == Tokenizer.Token.TokenType.FUNCTION) ? functions : operators).get(symbol); + final Context.Type requestedType = operation.staticType(expectedType); + for (final ExpressionNode arg : node.args) + { + if (optimizeTree(ctx, arg, requestedType, indent + 1)) + { + optimized = true; + } } - for (ExpressionNode arg : node.args) { - if (arg.token.type.isConstant()) continue; - if (arg.op instanceof LazyValue.ContextFreeLazyValue) continue; + for (final ExpressionNode arg : node.args) + { + if (arg.token.type.isConstant()) + { + continue; + } + if (arg.op instanceof LazyValue.ContextFreeLazyValue) + { + continue; + } return optimized; } // a few exceptions which we don't implement in the framework for simplicity for now if (!operation.pure()) { - if (symbol.equals("->") && expectedType == Context.Type.MAPDEF) + if (!symbol.equals("->") || expectedType != Context.Type.MAPDEF) { - - } - else { return optimized; } } - if (operation.pure()) + // element access with constant elements will always resolve the same way. + if (operation.pure() && symbol.equals(":") && expectedType == Context.Type.LVALUE) { - // element access with constant elements will always resolve the same way. - if (symbol.equals(":") && expectedType == Context.Type.LVALUE) - { - expectedType = Context.Type.NONE; - } + expectedType = Context.Type.NONE; } List args = new ArrayList<>(node.args.size()); - for (ExpressionNode arg : node.args) { - try { - if (arg.op instanceof LazyValue.Constant) { - Value val = ((LazyValue.Constant) arg.op).get(); + for (final ExpressionNode arg : node.args) + { + try + { + if (arg.op instanceof LazyValue.Constant) + { + final Value val = ((LazyValue.Constant) arg.op).get(); args.add((c, t) -> val); } - else args.add((c, t) -> arg.op.evalValue(ctx, requestedType)); - } catch (NullPointerException npe) { + else + { + args.add((c, t) -> arg.op.evalValue(ctx, requestedType)); + } + } + catch (final NullPointerException npe) + { throw new ExpressionException(ctx, this, node.token, "Attempted to evaluate context free expression"); } } // applying argument unpacking - args= AbstractLazyFunction.lazify(AbstractLazyFunction.unpackLazy(args, ctx, requestedType)); - Value result; + args = AbstractLazyFunction.lazify(AbstractLazyFunction.unpackLazy(args, ctx, requestedType)); + final Value result; if (operation instanceof ILazyFunction) { result = ((ILazyFunction) operation).lazyEval(ctx, expectedType, this, node.token, args).evalValue(null, expectedType); } else if (args.size() == 1) { - result = ((ILazyOperator)operation).lazyEval(ctx, expectedType, this, node.token, args.get(0), null).evalValue(null, expectedType); + result = ((ILazyOperator) operation).lazyEval(ctx, expectedType, this, node.token, args.get(0), null).evalValue(null, expectedType); } else // args == 2 { - result = ((ILazyOperator)operation).lazyEval(ctx, expectedType, this, node.token, args.get(0), args.get(1)).evalValue(null, expectedType); + result = ((ILazyOperator) operation).lazyEval(ctx, expectedType, this, node.token, args.get(0), args.get(1)).evalValue(null, expectedType); } node.op = LazyValue.ofConstant(result); - //node.token.morph(Tokenizer.Token.TokenType.CONSTANT, node.token.surface); if (CarpetSettings.scriptsDebugging) - CarpetScriptServer.LOG.info(" - "+symbol+"("+args.stream().map(a -> a.evalValue(null, requestedType).getString()).collect(Collectors.joining(", "))+") => "+result.getString()+" at line "+(node.token.lineno+1) +", node depth "+indent); + { + CarpetScriptServer.LOG.info(" - " + symbol + "(" + args.stream().map(a -> a.evalValue(null, requestedType).getString()).collect(Collectors.joining(", ")) + ") => " + result.getString() + " at line " + (node.token.lineno + 1) + ", node depth " + indent); + } return true; } - private LazyValue extractOp(Context ctx, ExpressionNode node, Context.Type expectedType) + private LazyValue extractOp(final Context ctx, final ExpressionNode node, final Context.Type expectedType) { if (node.op instanceof LazyValue.Constant) { // constants are immutable if (node.token.type.isConstant()) { - Value value = ((LazyValue.Constant) node.op).get(); + final Value value = ((LazyValue.Constant) node.op).get(); return (c, t) -> value; } return node.op; } if (node.op instanceof LazyValue.ContextFreeLazyValue) { - Value ret = ((LazyValue.ContextFreeLazyValue) node.op).evalType(expectedType); + final Value ret = ((LazyValue.ContextFreeLazyValue) node.op).evalType(expectedType); return (c, t) -> ret; } - Tokenizer.Token token = node.token; + final Tokenizer.Token token = node.token; switch (token.type) { - case UNARY_OPERATOR: { - ILazyOperator op = operators.get(token.surface); - Context.Type requestedType = op.staticType(expectedType); - LazyValue arg = extractOp(ctx, node.args.get(0), requestedType); + case UNARY_OPERATOR: + { + final ILazyOperator op = operators.get(token.surface); + final Context.Type requestedType = op.staticType(expectedType); + final LazyValue arg = extractOp(ctx, node.args.get(0), requestedType); return (c, t) -> op.lazyEval(c, t, this, token, arg, null).evalValue(c, t); } - case OPERATOR: { - ILazyOperator op = operators.get(token.surface); - Context.Type requestedType = op.staticType(expectedType); - LazyValue arg = extractOp(ctx, node.args.get(0), requestedType); - LazyValue arh = extractOp(ctx, node.args.get(1), requestedType); + case OPERATOR: + { + final ILazyOperator op = operators.get(token.surface); + final Context.Type requestedType = op.staticType(expectedType); + final LazyValue arg = extractOp(ctx, node.args.get(0), requestedType); + final LazyValue arh = extractOp(ctx, node.args.get(1), requestedType); return (c, t) -> op.lazyEval(c, t, this, token, arg, arh).evalValue(c, t); } case VARIABLE: return (c, t) -> getOrSetAnyVariable(c, token.surface).evalValue(c, t); - case FUNCTION: { - ILazyFunction f = functions.get(token.surface); - Context.Type requestedType = f.staticType(expectedType); - List params = node.args.stream().map(n -> extractOp(ctx, n, requestedType)).collect(Collectors.toList()); + case FUNCTION: + { + final ILazyFunction f = functions.get(token.surface); + final Context.Type requestedType = f.staticType(expectedType); + final List params = node.args.stream().map(n -> extractOp(ctx, n, requestedType)).collect(Collectors.toList()); return (c, t) -> f.lazyEval(c, t, this, token, params).evalValue(c, t); } case CONSTANT: return node.op; default: - throw new ExpressionException(ctx, this, node.token, "Unexpected token '" + node.token.type +" "+node.token.surface + "'"); + throw new ExpressionException(ctx, this, node.token, "Unexpected token '" + node.token.type + " " + node.token.surface + "'"); } } - private void validate(Context c, List rpn) + private void validate(final Context c, final List rpn) { /*- * Thanks to Norman Ramsey: @@ -1379,7 +1526,7 @@ private void validate(Context c, List rpn) // each // layer on the stack being the count of the number of parameters in // that scope - IntArrayList stack = new IntArrayList(); // IntArrayList instead of just IntStack because we need to query the size + final IntArrayList stack = new IntArrayList(); // IntArrayList instead of just IntStack because we need to query the size // push the 'global' scope stack.push(0); diff --git a/src/main/java/carpet/script/Fluff.java b/src/main/java/carpet/script/Fluff.java index 9fa199bc4c..ca91195e2e 100644 --- a/src/main/java/carpet/script/Fluff.java +++ b/src/main/java/carpet/script/Fluff.java @@ -13,24 +13,33 @@ public abstract class Fluff { @FunctionalInterface - public interface TriFunction { R apply(A a, B b, C c); } - - @FunctionalInterface - public interface TriConsumer { void accept(A a, B b, C c); } - - @FunctionalInterface - public interface QuadConsumer { void accept(A a, B b, C c, D d); } + public interface TriFunction + { + R apply(A a, B b, C c); + } @FunctionalInterface - public interface QuadFunction { R apply(A a, B b, C c, D d);} + public interface QuadFunction + { + R apply(A a, B b, C c, D d); + } @FunctionalInterface - public interface QuinnFunction { R apply(A a, B b, C c, D d, E e);} + public interface QuinnFunction + { + R apply(A a, B b, C c, D d, E e); + } @FunctionalInterface - public interface SexFunction { R apply(A a, B b, C c, D d, E e, F f);} + public interface SexFunction + { + R apply(A a, B b, C c, D d, E e, F f); + } - public interface UsageProvider { String getUsage();} + public interface UsageProvider + { + String getUsage(); + } public interface EvalNode { @@ -49,7 +58,11 @@ public interface EvalNode /** * @return required argument eval type in case its evaluated statically without context but with a given context type */ - default Context.Type staticType(Context.Type outerType) {return transitive()?outerType:Context.NONE;}; + default Context.Type staticType(final Context.Type outerType) + { + return transitive() ? outerType : Context.NONE; + } + } public interface ILazyFunction extends EvalNode @@ -63,9 +76,11 @@ public interface ILazyFunction extends EvalNode static void checkInterrupts() { if (ScriptHost.mainThread != Thread.currentThread() && Thread.currentThread().isInterrupted()) + { throw new InternalExpressionException("Thread interrupted"); + } } - // lazy function has a chance to change execution based on contxt + // lazy function has a chance to change execution based on context } public interface IFunction extends ILazyFunction @@ -92,94 +107,109 @@ public abstract static class AbstractLazyFunction implements ILazyFunction protected String name; int numParams; - public AbstractLazyFunction(int numParams, String name) + public AbstractLazyFunction(final int numParams, final String name) { + super(); this.numParams = numParams; this.name = name; } - public String getName() { + public String getName() + { return name; } @Override - public int getNumParams() { + public int getNumParams() + { return numParams; } @Override - public boolean numParamsVaries() { + public boolean numParamsVaries() + { return numParams < 0; } - public static List unpackLazy(List lzargs, Context c, Context.Type contextType) + public static List unpackLazy(final List lzargs, final Context c, final Context.Type contextType) { - List args = new ArrayList<>(); - for (LazyValue lv : lzargs) + final List args = new ArrayList<>(); + for (final LazyValue lv : lzargs) { - Value arg = lv.evalValue(c, contextType); + final Value arg = lv.evalValue(c, contextType); if (arg instanceof FunctionUnpackedArgumentsValue) + { args.addAll(((ListValue) arg).getItems()); + } else + { args.add(arg); + } } return args; } - public List unpackArgs(List lzargs, Context c, Context.Type contextType) + public List unpackArgs(final List lzargs, final Context c, final Context.Type contextType) { - List args = unpackLazy(lzargs, c, contextType); + final List args = unpackLazy(lzargs, c, contextType); if (!numParamsVaries() && getNumParams() != args.size()) + { throw new InternalExpressionException("Function " + getName() + " expected " + getNumParams() + " parameters, got " + args.size()); + } return args; } - public static List lazify(List args) + public static List lazify(final List args) { - List lzargs = new ArrayList<>(args.size()); - args.forEach( v -> lzargs.add( (c, t) -> v)); + final List lzargs = new ArrayList<>(args.size()); + args.forEach(v -> lzargs.add((c, t) -> v)); return lzargs; } } public abstract static class AbstractFunction extends AbstractLazyFunction implements IFunction { - AbstractFunction(int numParams, String name) { + AbstractFunction(final int numParams, final String name) + { super(numParams, name); } @Override - public boolean pure() { + public boolean pure() + { return true; } @Override - public boolean transitive() { + public boolean transitive() + { return false; } @Override - public LazyValue lazyEval(Context cc, Context.Type type, Expression e, Tokenizer.Token t, final List lazyParams) + public LazyValue lazyEval(final Context cc, final Context.Type type, final Expression e, final Tokenizer.Token t, final List lazyParams) { return new LazyValue() { // eager evaluation always ignores the required type and evals params by none default private List params; + @Override - public Value evalValue(Context c, Context.Type type) + public Value evalValue(final Context c, final Context.Type type) { ILazyFunction.checkInterrupts(); try { return AbstractFunction.this.eval(getParams(c)); } - catch (RuntimeException exc) + catch (final RuntimeException exc) { throw Expression.handleCodeException(cc, exc, e, t); } } - private List getParams(Context c) + + private List getParams(final Context c) { if (params == null) { @@ -202,18 +232,22 @@ public abstract static class AbstractLazyOperator implements ILazyOperator boolean leftAssoc; - AbstractLazyOperator(int precedence, boolean leftAssoc) { + AbstractLazyOperator(final int precedence, final boolean leftAssoc) + { + super(); this.precedence = precedence; this.leftAssoc = leftAssoc; } @Override - public int getPrecedence() { + public int getPrecedence() + { return precedence; } @Override - public boolean isLeftAssoc() { + public boolean isLeftAssoc() + { return leftAssoc; } @@ -222,28 +256,32 @@ public boolean isLeftAssoc() { public abstract static class AbstractOperator extends AbstractLazyOperator implements IOperator { - AbstractOperator(int precedence, boolean leftAssoc) { + AbstractOperator(final int precedence, final boolean leftAssoc) + { super(precedence, leftAssoc); } + @Override - public boolean pure() { + public boolean pure() + { return true; } @Override - public boolean transitive() { + public boolean transitive() + { return false; } @Override - public LazyValue lazyEval(Context cc, Context.Type type, Expression e, Tokenizer.Token t, final LazyValue v1, final LazyValue v2) + public LazyValue lazyEval(final Context cc, final Context.Type type, final Expression e, final Tokenizer.Token t, final LazyValue v1, final LazyValue v2) { return (c, typeIgnored) -> { try { return AbstractOperator.this.eval(v1.evalValue(c, Context.Type.NONE), v2.evalValue(c, Context.Type.NONE)); } - catch (RuntimeException exc) + catch (final RuntimeException exc) { throw Expression.handleCodeException(cc, exc, e, t); } @@ -253,21 +291,25 @@ public LazyValue lazyEval(Context cc, Context.Type type, Expression e, Tokenizer public abstract static class AbstractUnaryOperator extends AbstractOperator { - AbstractUnaryOperator(int precedence, boolean leftAssoc) { + AbstractUnaryOperator(final int precedence, final boolean leftAssoc) + { super(precedence, leftAssoc); } + @Override - public boolean pure() { + public boolean pure() + { return true; } @Override - public boolean transitive() { + public boolean transitive() + { return false; } @Override - public LazyValue lazyEval(Context cc, Context.Type type, Expression e, Tokenizer.Token t, final LazyValue v1, final LazyValue v2) + public LazyValue lazyEval(final Context cc, final Context.Type type, final Expression e, final Tokenizer.Token t, final LazyValue v1, final LazyValue v2) { if (v2 != null) { @@ -278,7 +320,7 @@ public LazyValue lazyEval(Context cc, Context.Type type, Expression e, Tokenizer { return AbstractUnaryOperator.this.evalUnary(v1.evalValue(c, Context.Type.NONE)); } - catch (RuntimeException exc) + catch (final RuntimeException exc) { throw Expression.handleCodeException(cc, exc, e, t); } @@ -286,7 +328,7 @@ public LazyValue lazyEval(Context cc, Context.Type type, Expression e, Tokenizer } @Override - public Value eval(Value v1, Value v2) + public Value eval(final Value v1, final Value v2) { throw new IllegalStateException("Shouldn't end up here"); } diff --git a/src/main/java/carpet/script/LazyValue.java b/src/main/java/carpet/script/LazyValue.java index 6f0fc15bd0..88713d0880 100644 --- a/src/main/java/carpet/script/LazyValue.java +++ b/src/main/java/carpet/script/LazyValue.java @@ -2,7 +2,9 @@ import carpet.script.value.Value; -/** LazyNumber interface created for lazily evaluated functions */ +/** + * LazyNumber interface created for lazily evaluated functions + */ @FunctionalInterface public interface LazyValue { @@ -11,13 +13,15 @@ public interface LazyValue LazyValue NULL = (c, t) -> Value.NULL; LazyValue ZERO = (c, t) -> Value.ZERO; - public static LazyValue ofConstant(Value val) { + static LazyValue ofConstant(final Value val) + { return new Constant(val); } Value evalValue(Context c, Context.Type type); - default Value evalValue(Context c){ + default Value evalValue(final Context c) + { return evalValue(c, Context.Type.NONE); } @@ -28,7 +32,8 @@ interface ContextFreeLazyValue extends LazyValue Value evalType(Context.Type type); @Override - default Value evalValue(Context c, Context.Type type) { + default Value evalValue(final Context c, final Context.Type type) + { return evalType(type); } } @@ -38,21 +43,26 @@ class Constant implements ContextFreeLazyValue { Value result; - public Constant(Value value) + public Constant(final Value value) { result = value; } - public Value get() {return result;} + public Value get() + { + return result; + } @Override - public Value evalType(Context.Type type) { + public Value evalType(final Context.Type type) + { return result.fromConstant(); } @Override - public Value evalValue(Context c, Context.Type type) { + public Value evalValue(final Context c, final Context.Type type) + { return result.fromConstant(); } } diff --git a/src/main/java/carpet/script/Module.java b/src/main/java/carpet/script/Module.java index 8bf867548f..b687c07349 100644 --- a/src/main/java/carpet/script/Module.java +++ b/src/main/java/carpet/script/Module.java @@ -14,23 +14,24 @@ import net.minecraft.nbt.Tag; import net.minecraft.world.level.storage.LevelResource; -public record Module(String name, String code, boolean library) { +public record Module(String name, String code, boolean library) +{ public Module { Objects.requireNonNull(name); Objects.requireNonNull(code); } - public static Module fromPath(Path path) + public static Module fromPath(final Path path) { - boolean library = path.getFileName().toString().endsWith(".scl"); + final boolean library = path.getFileName().toString().endsWith(".scl"); try { - String name = path.getFileName().toString().replaceFirst("\\.scl?","").toLowerCase(Locale.ROOT); - String code = new String(Files.readAllBytes(path), StandardCharsets.UTF_8); + final String name = path.getFileName().toString().replaceFirst("\\.scl?", "").toLowerCase(Locale.ROOT); + final String code = new String(Files.readAllBytes(path), StandardCharsets.UTF_8); return new Module(name, code, library); } - catch (IOException e) + catch (final IOException e) { throw new IllegalArgumentException("Failed to load scarpet module", e); } @@ -38,79 +39,96 @@ public static Module fromPath(Path path) /** * Creates a new {@link Module} with an app located in Carpet's JAR. + * * @param scriptName A {@link String} being the name of the script. The extension will be autocompleted - * @param isLibrary A {@link boolean} indicating whether or not the script is a library + * @param isLibrary A {@link boolean} indicating whether or not the script is a library * @return The created {@link BundledModule} */ - public static Module carpetNative(String scriptName, boolean isLibrary) + public static Module carpetNative(final String scriptName, final boolean isLibrary) { return fromJarPath("assets/carpet/scripts/", scriptName, isLibrary); } - + /** * Creates a new {@link Module} with an app located at a specified path inside some mod's JAR. - * @see #fromJarPathWithCustomName(String, String, boolean) - * - * @param path A {@link String} being the path to the directory where the app is located. + * + * @param path A {@link String} being the path to the directory where the app is located. * @param scriptName A {@link String} being the name of the script. The extension will be autocompleted - * @param isLibrary A {@link boolean} indicating whether or not the script is a library + * @param isLibrary A {@link boolean} indicating whether or not the script is a library * @return The created {@link BundledModule} + * @see #fromJarPathWithCustomName(String, String, boolean) */ - public static Module fromJarPath(String path, String scriptName, boolean isLibrary) { - return fromJarPathWithCustomName(path + scriptName + (isLibrary ? ".scl":".sc"), scriptName, isLibrary); + public static Module fromJarPath(final String path, final String scriptName, final boolean isLibrary) + { + return fromJarPathWithCustomName(path + scriptName + (isLibrary ? ".scl" : ".sc"), scriptName, isLibrary); } - + /** * Creates a new {@link Module} with an app located at the specified fullPath (inside a mod jar)with a custom name. - * @see #fromJarPath(String, String, boolean) - * - * @param fullPath A {@link String} being the full path to the app's code, including file and extension. + * + * @param fullPath A {@link String} being the full path to the app's code, including file and extension. * @param customName A {@link String} being the custom name for the script. - * @param isLibrary A {@link boolean} indicating whether or not the script is a library + * @param isLibrary A {@link boolean} indicating whether or not the script is a library * @return The created {@link Module} + * @see #fromJarPath(String, String, boolean) */ - public static Module fromJarPathWithCustomName(String fullPath, String customName, boolean isLibrary) { + public static Module fromJarPathWithCustomName(final String fullPath, final String customName, final boolean isLibrary) + { try { - String name = customName.toLowerCase(Locale.ROOT); - String code = IOUtils.toString( + final String name = customName.toLowerCase(Locale.ROOT); + final String code = IOUtils.toString( Module.class.getClassLoader().getResourceAsStream(fullPath), StandardCharsets.UTF_8 ); return new Module(name, code, isLibrary); } - catch (IOException e) + catch (final IOException e) { throw new IllegalArgumentException("Failed to load bundled module", e); } } - - public static Tag getData(Module module) + + public static Tag getData(final Module module) { - Path dataFile = resolveResource(module); - if (dataFile == null) return null; - if (!Files.exists(dataFile) || !(Files.isRegularFile(dataFile))) return null; - synchronized (FileArgument.writeIOSync) { return FileArgument.readTag(dataFile); } + final Path dataFile = resolveResource(module); + if (dataFile == null || !Files.exists(dataFile) || !(Files.isRegularFile(dataFile))) + { + return null; + } + synchronized (FileArgument.writeIOSync) + { + return FileArgument.readTag(dataFile); + } } - public static void saveData(Module module, Tag globalState) + public static void saveData(final Module module, final Tag globalState) { - Path dataFile = resolveResource(module); - if (dataFile == null) return; - if (!Files.exists(dataFile.getParent())) { - try { + final Path dataFile = resolveResource(module); + if (dataFile == null) + { + return; + } + if (!Files.exists(dataFile.getParent())) + { + try + { Files.createDirectories(dataFile.getParent()); - } catch (IOException e) { + } + catch (final IOException e) + { throw new IllegalStateException(e); } } - synchronized (FileArgument.writeIOSync) { FileArgument.writeTagDisk(globalState, dataFile, false); } + synchronized (FileArgument.writeIOSync) + { + FileArgument.writeTagDisk(globalState, dataFile, false); + } } - private static Path resolveResource(Module module) + private static Path resolveResource(final Module module) { - if (module == null) return null; // commandline app - return CarpetServer.minecraft_server.getWorldPath(LevelResource.ROOT).resolve("scripts/"+module.name()+".data.nbt"); + return module == null ? null : CarpetServer.minecraft_server.getWorldPath(LevelResource.ROOT).resolve("scripts/" + module.name() + ".data.nbt"); // commandline app } } diff --git a/src/main/java/carpet/script/ScriptHost.java b/src/main/java/carpet/script/ScriptHost.java index a8eb3e85e7..6737be00c2 100644 --- a/src/main/java/carpet/script/ScriptHost.java +++ b/src/main/java/carpet/script/ScriptHost.java @@ -38,41 +38,45 @@ public abstract class ScriptHost private final Set deprecations = new HashSet<>(); - public Random getRandom(long aLong) + public Random getRandom(final long aLong) { if (randomizers.size() > 65536) + { randomizers.clear(); + } return randomizers.computeIfAbsent(aLong, Random::new); } - public boolean resetRandom(long aLong) { + public boolean resetRandom(final long aLong) + { return randomizers.remove(aLong) != null; } public static class ModuleData { Module parent; - public Map globalFunctions = new Object2ObjectOpenHashMap<>(); - public Map globalVariables = new Object2ObjectOpenHashMap<>(); - public Map functionImports = new Object2ObjectOpenHashMap<>(); // imported functions string to module - public Map globalsImports = new Object2ObjectOpenHashMap<>(); // imported global variables string to module - public Map futureImports = new Object2ObjectOpenHashMap<>(); // imports not known before used + public final Map globalFunctions = new Object2ObjectOpenHashMap<>(); + public final Map globalVariables = new Object2ObjectOpenHashMap<>(); + public final Map functionImports = new Object2ObjectOpenHashMap<>(); // imported functions string to module + public final Map globalsImports = new Object2ObjectOpenHashMap<>(); // imported global variables string to module + public final Map futureImports = new Object2ObjectOpenHashMap<>(); // imports not known before used - public ModuleData(Module parent, ModuleData other) + public ModuleData(final Module parent, final ModuleData other) { + super(); // imports are just pointers, but they still point to the wrong modules (point to the parent) this.parent = parent; globalFunctions.putAll(other.globalFunctions); other.globalVariables.forEach((key, value) -> { - Value var = value.evalValue(null); - Value copy = var.deepcopy(); + final Value var = value.evalValue(null); + final Value copy = var.deepcopy(); copy.boundVariable = var.boundVariable; globalVariables.put(key, (c, t) -> copy); }); } - public void setImportsBasedOn(ScriptHost host, ModuleData other) + public void setImportsBasedOn(final ScriptHost host, final ModuleData other) { // fixing imports other.functionImports.forEach((name, targetData) -> { @@ -87,20 +91,24 @@ public void setImportsBasedOn(ScriptHost host, ModuleData other) } - public ModuleData(Module parent) + public ModuleData(final Module parent) { this.parent = parent; } } + protected final Map userHosts = new Object2ObjectOpenHashMap<>(); - private Map moduleData = new HashMap<>(); // marking imports - private Map modules = new HashMap<>(); + private final Map moduleData = new HashMap<>(); // marking imports + private final Map modules = new HashMap<>(); protected ScriptHost parent; protected boolean perUser; public String user; - public String getName() {return main ==null?null: main.name();} + public String getName() + { + return main == null ? null : main.name(); + } public final Module main; @@ -109,9 +117,10 @@ public interface ErrorSnooper { List apply(Expression expression, Tokenizer.Token token, Context context, String message); } + public ErrorSnooper errorSnooper = null; - protected ScriptHost(Module code, ScriptServer scriptServer, boolean perUser, ScriptHost parent) + protected ScriptHost(final Module code, final ScriptServer scriptServer, final boolean perUser, final ScriptHost parent) { this.parent = parent; this.main = code; @@ -119,24 +128,30 @@ protected ScriptHost(Module code, ScriptServer scriptServer, boolean perUser, Sc this.user = null; this.strict = false; this.scriptServer = scriptServer; - ModuleData moduleData = new ModuleData(code); + final ModuleData moduleData = new ModuleData(code); initializeModuleGlobals(moduleData); this.moduleData.put(code, moduleData); - this.modules.put(code==null?null:code.name(), code); + this.modules.put(code == null ? null : code.name(), code); mainThread = Thread.currentThread(); } - void initializeModuleGlobals(ModuleData md) + void initializeModuleGlobals(final ModuleData md) { } - public void importModule(Context c, String moduleName) + public void importModule(final Context c, final String moduleName) { - if (modules.containsKey(moduleName.toLowerCase(Locale.ROOT))) return; // aready imported - Module module = getModuleOrLibraryByName(moduleName); - if (modules.containsKey(module.name())) return; // aready imported, once again, in case some discrepancies in names? + if (modules.containsKey(moduleName.toLowerCase(Locale.ROOT))) + { + return; // aready imported + } + final Module module = getModuleOrLibraryByName(moduleName); + if (modules.containsKey(module.name())) + { + return; // aready imported, once again, in case some discrepancies in names? + } modules.put(module.name(), module); - ModuleData data = new ModuleData(module); + final ModuleData data = new ModuleData(module); initializeModuleGlobals(data); moduleData.put(module, data); runModuleCode(c, module); @@ -144,20 +159,21 @@ public void importModule(Context c, String moduleName) //modules.remove(module.getName()); //throw new InternalExpressionException("Failed to import a module "+moduleName); } - public void importNames(Context c, Module targetModule, String sourceModuleName, List identifiers ) + + public void importNames(final Context c, final Module targetModule, final String sourceModuleName, final List identifiers) { if (!moduleData.containsKey(targetModule)) { throw new InternalExpressionException("Cannot import to module that doesn't exist"); } - Module source = modules.get(sourceModuleName); - ModuleData sourceData = moduleData.get(source); - ModuleData targetData = moduleData.get(targetModule); + final Module source = modules.get(sourceModuleName); + final ModuleData sourceData = moduleData.get(source); + final ModuleData targetData = moduleData.get(targetModule); if (sourceData == null || targetData == null) { throw new InternalExpressionException("Cannot import from module that is not imported"); } - for (String identifier: identifiers) + for (final String identifier : identifiers) { if (sourceData.globalFunctions.containsKey(identifier)) { @@ -174,10 +190,10 @@ else if (sourceData.globalVariables.containsKey(identifier)) } } - public Stream availableImports(String moduleName) + public Stream availableImports(final String moduleName) { - Module source = modules.get(moduleName); - ModuleData sourceData = moduleData.get(source); + final Module source = modules.get(moduleName); + final ModuleData sourceData = moduleData.get(source); if (sourceData == null) { throw new InternalExpressionException("Cannot import from module that is not imported"); @@ -192,136 +208,195 @@ public Stream availableImports(String moduleName) protected abstract void runModuleCode(Context c, Module module); // this should be shell out in the executor - public FunctionValue getFunction(String name) { return getFunction(main, name); } - public FunctionValue getAssertFunction(Module module, String name) + public FunctionValue getFunction(final String name) + { + return getFunction(main, name); + } + + public FunctionValue getAssertFunction(final Module module, final String name) { - FunctionValue ret = getFunction(module, name); + final FunctionValue ret = getFunction(module, name); if (ret == null) { if (module == main) - throw new InternalExpressionException("Function '"+name+"' is not defined yet"); + { + throw new InternalExpressionException("Function '" + name + "' is not defined yet"); + } else - throw new InternalExpressionException("Function '"+name+"' is not defined nor visible by its name in the imported module '"+module.name()+"'"); + { + throw new InternalExpressionException("Function '" + name + "' is not defined nor visible by its name in the imported module '" + module.name() + "'"); + } } return ret; } - private FunctionValue getFunction(Module module, String name) + + private FunctionValue getFunction(final Module module, final String name) { - ModuleData local = getModuleData(module); + final ModuleData local = getModuleData(module); FunctionValue ret = local.globalFunctions.get(name); // most uses would be from local scope anyways - if (ret != null) return ret; + if (ret != null) + { + return ret; + } ModuleData target = local.functionImports.get(name); if (target != null) { ret = target.globalFunctions.get(name); - if (ret != null) return ret; + if (ret != null) + { + return ret; + } } // not in local scope - will need to travel over import links target = local.futureImports.get(name); - if (target == null) return null; + if (target == null) + { + return null; + } target = findModuleDataFromFunctionImports(name, target, 0); - if (target == null) return null; + if (target == null) + { + return null; + } local.futureImports.remove(name); local.functionImports.put(name, target); return target.globalFunctions.get(name); } - private ModuleData findModuleDataFromFunctionImports(String name, ModuleData source, int ttl) + private ModuleData findModuleDataFromFunctionImports(final String name, final ModuleData source, final int ttl) { - if (ttl > 64) throw new InternalExpressionException("Cannot import "+name+", either your imports are too deep or too loopy"); + if (ttl > 64) + { + throw new InternalExpressionException("Cannot import " + name + ", either your imports are too deep or too loopy"); + } if (source.globalFunctions.containsKey(name)) + { return source; + } if (source.functionImports.containsKey(name)) - return findModuleDataFromFunctionImports(name, source.functionImports.get(name), ttl+1); + { + return findModuleDataFromFunctionImports(name, source.functionImports.get(name), ttl + 1); + } if (source.futureImports.containsKey(name)) - return findModuleDataFromFunctionImports(name, source.futureImports.get(name), ttl+1); + { + return findModuleDataFromFunctionImports(name, source.futureImports.get(name), ttl + 1); + } return null; } - public LazyValue getGlobalVariable(String name) { return getGlobalVariable(main, name); } - public LazyValue getGlobalVariable(Module module, String name) + public LazyValue getGlobalVariable(final String name) + { + return getGlobalVariable(main, name); + } + + public LazyValue getGlobalVariable(final Module module, final String name) { - ModuleData local = getModuleData(module); + final ModuleData local = getModuleData(module); LazyValue ret = local.globalVariables.get(name); // most uses would be from local scope anyways - if (ret != null) return ret; + if (ret != null) + { + return ret; + } ModuleData target = local.globalsImports.get(name); if (target != null) { ret = target.globalVariables.get(name); - if (ret != null) return ret; + if (ret != null) + { + return ret; + } } // not in local scope - will need to travel over import links target = local.futureImports.get(name); - if (target == null) return null; + if (target == null) + { + return null; + } target = findModuleDataFromGlobalImports(name, target, 0); - if (target == null) return null; + if (target == null) + { + return null; + } local.futureImports.remove(name); local.globalsImports.put(name, target); return target.globalVariables.get(name); } - private ModuleData findModuleDataFromGlobalImports(String name, ModuleData source, int ttl) + private ModuleData findModuleDataFromGlobalImports(final String name, final ModuleData source, final int ttl) { - if (ttl > 64) throw new InternalExpressionException("Cannot import "+name+", either your imports are too deep or too loopy"); + if (ttl > 64) + { + throw new InternalExpressionException("Cannot import " + name + ", either your imports are too deep or too loopy"); + } if (source.globalVariables.containsKey(name)) + { return source; + } if (source.globalsImports.containsKey(name)) - return findModuleDataFromGlobalImports(name, source.globalsImports.get(name), ttl+1); + { + return findModuleDataFromGlobalImports(name, source.globalsImports.get(name), ttl + 1); + } if (source.futureImports.containsKey(name)) - return findModuleDataFromGlobalImports(name, source.futureImports.get(name), ttl+1); + { + return findModuleDataFromGlobalImports(name, source.futureImports.get(name), ttl + 1); + } return null; } - public void delFunctionWithPrefix(Module module, String prefix) + public void delFunctionWithPrefix(final Module module, final String prefix) { - ModuleData data = getModuleData(module); + final ModuleData data = getModuleData(module); data.globalFunctions.entrySet().removeIf(e -> e.getKey().startsWith(prefix)); data.functionImports.entrySet().removeIf(e -> e.getKey().startsWith(prefix)); } - public void delFunction(Module module, String funName) + + public void delFunction(final Module module, final String funName) { - ModuleData data = getModuleData(module); + final ModuleData data = getModuleData(module); data.globalFunctions.remove(funName); data.functionImports.remove(funName); } - public void delGlobalVariableWithPrefix(Module module, String prefix) + public void delGlobalVariableWithPrefix(final Module module, final String prefix) { - ModuleData data = getModuleData(module); + final ModuleData data = getModuleData(module); data.globalVariables.entrySet().removeIf(e -> e.getKey().startsWith(prefix)); data.globalsImports.entrySet().removeIf(e -> e.getKey().startsWith(prefix)); } - public void delGlobalVariable(Module module, String varName) + public void delGlobalVariable(final Module module, final String varName) { - ModuleData data = getModuleData(module); + final ModuleData data = getModuleData(module); data.globalFunctions.remove(varName); data.functionImports.remove(varName); } - private ModuleData getModuleData(Module module) + private ModuleData getModuleData(final Module module) { - ModuleData data = moduleData.get(module); - if (data == null) throw new IntegrityException("Module structure changed for the app. Did you reload the app with tasks running?"); + final ModuleData data = moduleData.get(module); + if (data == null) + { + throw new IntegrityException("Module structure changed for the app. Did you reload the app with tasks running?"); + } return data; } - protected void assertAppIntegrity(Module module) + protected void assertAppIntegrity(final Module module) { getModuleData(module); } - public void addUserDefinedFunction(Context ctx, Module module, String name, FunctionValue fun) + public void addUserDefinedFunction(final Context ctx, final Module module, final String name, final FunctionValue fun) { getModuleData(module).globalFunctions.put(name, fun); } - public void setGlobalVariable(Module module, String name, LazyValue lv) + public void setGlobalVariable(final Module module, final String name, final LazyValue lv) { getModuleData(module).globalVariables.put(name, lv); } - public Stream globalVariableNames(Module module, Predicate predicate) + public Stream globalVariableNames(final Module module, final Predicate predicate) { return Stream.concat(Stream.concat( getModuleData(module).globalVariables.keySet().stream(), @@ -329,27 +404,33 @@ public Stream globalVariableNames(Module module, Predicate predi ), getModuleData(module).futureImports.keySet().stream().filter(s -> s.startsWith("global_"))).filter(predicate); } - public Stream globalFunctionNames(Module module, Predicate predicate) + public Stream globalFunctionNames(final Module module, final Predicate predicate) { return Stream.concat(Stream.concat( getModuleData(module).globalFunctions.keySet().stream(), getModuleData(module).functionImports.keySet().stream() - ),getModuleData(module).futureImports.keySet().stream().filter(s -> !s.startsWith("global_"))).filter(predicate); + ), getModuleData(module).futureImports.keySet().stream().filter(s -> !s.startsWith("global_"))).filter(predicate); } - public ScriptHost retrieveForExecution(String /*Nullable*/ user) + public ScriptHost retrieveForExecution(final String /*Nullable*/ user) { - if (!perUser) return this; - ScriptHost oldUserHost = userHosts.get(user); - if (oldUserHost != null) return oldUserHost; - ScriptHost userHost = this.duplicate(); + if (!perUser) + { + return this; + } + final ScriptHost oldUserHost = userHosts.get(user); + if (oldUserHost != null) + { + return oldUserHost; + } + final ScriptHost userHost = this.duplicate(); userHost.user = user; this.setupUserHost(userHost); userHosts.put(user, userHost); return userHost; } - protected void setupUserHost(ScriptHost host) + protected void setupUserHost(final ScriptHost host) { // adding imports host.modules.putAll(this.modules); @@ -358,57 +439,65 @@ protected void setupUserHost(ScriptHost host) host.moduleData.forEach((module, data) -> data.setImportsBasedOn(host, this.moduleData.get(data.parent))); } - synchronized public void handleExpressionException(String msg, ExpressionException exc) + public synchronized void handleExpressionException(final String msg, final ExpressionException exc) { - System.out.println(msg+": "+exc); + System.out.println(msg + ": " + exc); } - protected abstract ScriptHost duplicate(); - public Object getLock(Value name) + public Object getLock(final Value name) { - return locks.computeIfAbsent(name, (n) -> new Object()); + return locks.computeIfAbsent(name, n -> new Object()); } - public ThreadPoolExecutor getExecutor(Value pool) + public ThreadPoolExecutor getExecutor(final Value pool) { - if (inTermination) return null; - return executorServices.computeIfAbsent(pool, (v) -> (ThreadPoolExecutor) Executors.newCachedThreadPool()); + if (inTermination) + { + return null; + } + return executorServices.computeIfAbsent(pool, v -> (ThreadPoolExecutor) Executors.newCachedThreadPool()); } public int taskCount() { return executorServices.values().stream().map(ThreadPoolExecutor::getActiveCount).reduce(0, Integer::sum); } - public int taskCount(Value pool) + + public int taskCount(final Value pool) { - if (executorServices.containsKey(pool)) - { - return executorServices.get(pool).getActiveCount(); - } - return 0; + return executorServices.containsKey(pool) ? executorServices.get(pool).getActiveCount() : 0; } public void onClose() { inTermination = true; executorServices.values().forEach(ThreadPoolExecutor::shutdown); - for (ScriptHost uh : userHosts.values()) uh.onClose(); + for (final ScriptHost uh : userHosts.values()) + { + uh.onClose(); + } if (taskCount() > 0) { executorServices.values().forEach(e -> { - ExecutorService stopper = Executors.newSingleThreadExecutor(); - stopper.submit( () -> { - try { + final ExecutorService stopper = Executors.newSingleThreadExecutor(); + stopper.submit(() -> { + try + { // Wait a while for existing tasks to terminate - if (!e.awaitTermination(1500, TimeUnit.MILLISECONDS)) { + if (!e.awaitTermination(1500, TimeUnit.MILLISECONDS)) + { e.shutdownNow(); // Cancel currently executing tasks // Wait a while for tasks to respond to being cancelled if (!e.awaitTermination(1500, TimeUnit.MILLISECONDS)) + { CarpetScriptServer.LOG.error("Failed to stop app's thread"); + } } - } catch (InterruptedException ie) { + } + catch (final InterruptedException ie) + { // (Re-)Cancel if current thread also interrupted e.shutdownNow(); // Preserve interrupt status @@ -421,12 +510,15 @@ public void onClose() } } - public void setPerPlayer(boolean isPerUser) + public void setPerPlayer(final boolean isPerUser) { perUser = isPerUser; } - public boolean isPerUser() {return perUser;} + public boolean isPerUser() + { + return perUser; + } public Set getUserList() { @@ -436,21 +528,24 @@ public Set getUserList() public void resetErrorSnooper() { - errorSnooper=null; + errorSnooper = null; } public static final Logger DEPRECATION_LOG = LoggerFactory.getLogger("Scarpet Deprecation Warnings"); - public boolean issueDeprecation(String feature) + public boolean issueDeprecation(final String feature) { - if (deprecations.contains(feature)) return false; + if (deprecations.contains(feature)) + { + return false; + } deprecations.add(feature); - DEPRECATION_LOG.warn("'"+feature+"' is deprecated and soon will be removed. Please consult the docs for their replacement"); + DEPRECATION_LOG.warn("'" + feature + "' is deprecated and soon will be removed. Please consult the docs for their replacement"); return true; } - public ScriptServer scriptServer() - { - return scriptServer; - } + public ScriptServer scriptServer() + { + return scriptServer; + } } diff --git a/src/main/java/carpet/script/ScriptServer.java b/src/main/java/carpet/script/ScriptServer.java index 24e363832e..5d13d02430 100644 --- a/src/main/java/carpet/script/ScriptServer.java +++ b/src/main/java/carpet/script/ScriptServer.java @@ -6,6 +6,7 @@ import carpet.script.value.Value; // WIP -public class ScriptServer { +public class ScriptServer +{ public final Map systemGlobals = new ConcurrentHashMap<>(); } diff --git a/src/main/java/carpet/script/Tokenizer.java b/src/main/java/carpet/script/Tokenizer.java index 645b53ad75..e62d4394ee 100644 --- a/src/main/java/carpet/script/Tokenizer.java +++ b/src/main/java/carpet/script/Tokenizer.java @@ -16,25 +16,35 @@ */ public class Tokenizer implements Iterator { - /** What character to use for decimal separators. */ + /** + * What character to use for decimal separators. + */ private static final char decimalSeparator = '.'; - /** What character to use for minus sign (negative values). */ + /** + * What character to use for minus sign (negative values). + */ private static final char minusSign = '-'; - /** Actual position in expression string. */ + /** + * Actual position in expression string. + */ private int pos = 0; private int lineno = 0; private int linepos = 0; - private boolean comments; - private boolean newLinesMarkers; - /** The original input expression. */ - private String input; - /** The previous token or null if none. */ + private final boolean comments; + private final boolean newLinesMarkers; + /** + * The original input expression. + */ + private final String input; + /** + * The previous token or null if none. + */ private Token previousToken; - private Expression expression; - private Context context; + private final Expression expression; + private final Context context; - Tokenizer(Context c, Expression expr, String input, boolean allowComments, boolean allowNewLineMakers) + Tokenizer(final Context c, final Expression expr, final String input, final boolean allowComments, final boolean allowNewLineMakers) { this.input = input; this.expression = expr; @@ -45,16 +55,18 @@ public class Tokenizer implements Iterator public List postProcess() { - Iterable iterable = () -> this; - List originalTokens = StreamSupport.stream(iterable.spliterator(), false).collect(Collectors.toList()); - List cleanedTokens = new ArrayList<>(); + final Iterable iterable = () -> this; + final List originalTokens = StreamSupport.stream(iterable.spliterator(), false).collect(Collectors.toList()); + final List cleanedTokens = new ArrayList<>(); Token last = null; - while (originalTokens.size() > 0) + while (!originalTokens.isEmpty()) { - Token current = originalTokens.remove(originalTokens.size()-1); + final Token current = originalTokens.remove(originalTokens.size() - 1); if (current.type == Token.TokenType.MARKER && current.surface.startsWith("//")) + { continue; - // skipping comments + } + // skipping comments if (!isSemicolon(current) || (last != null && last.type != Token.TokenType.CLOSE_PAREN && last.type != Token.TokenType.COMMA && !isSemicolon(last))) { @@ -84,7 +96,9 @@ else if ("}".equals(current.surface) || "]".equals(current.surface)) cleanedTokens.add(current); } if (!(current.type == Token.TokenType.MARKER && current.surface.equals("$"))) + { last = current; + } } Collections.reverse(cleanedTokens); return cleanedTokens; @@ -106,30 +120,33 @@ private char peekNextChar() return (pos < (input.length() - 1)) ? input.charAt(pos + 1) : 0; } - private boolean isHexDigit(char ch) + private boolean isHexDigit(final char ch) { return ch == 'x' || ch == 'X' || (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F'); } - private static boolean isSemicolon(Token tok) + private static boolean isSemicolon(final Token tok) { - return ( tok.type == Token.TokenType.OPERATOR && tok.surface.equals(";") ) - || (tok.type == Token.TokenType.UNARY_OPERATOR && tok.surface.equals(";u") ); + return (tok.type == Token.TokenType.OPERATOR && tok.surface.equals(";")) + || (tok.type == Token.TokenType.UNARY_OPERATOR && tok.surface.equals(";u")); } - public static List simplepass(String input) + public static List simplepass(final String input) { - Tokenizer tok = new Tokenizer(null, null, input, false, false); - List res = new ArrayList<>(); - while (tok.hasNext()) res.add(tok.next()); + final Tokenizer tok = new Tokenizer(null, null, input, false, false); + final List res = new ArrayList<>(); + while (tok.hasNext()) + { + res.add(tok.next()); + } return res; } @Override public Token next() { - Token token = new Token(); + final Token token = new Token(); if (pos >= input.length()) { @@ -139,7 +156,7 @@ public Token next() while (Character.isWhitespace(ch) && pos < input.length()) { linepos++; - if (ch=='\n') + if (ch == '\n') { lineno++; linepos = 0; @@ -153,10 +170,12 @@ public Token next() boolean isHex = false; if (Character.isDigit(ch)) // || (ch == decimalSeparator && Character.isDigit(peekNextChar()))) - // decided to no support this notation to favour element access via . operator + // decided to no support this notation to favour element access via . operator { if (ch == '0' && (peekNextChar() == 'x' || peekNextChar() == 'X')) + { isHex = true; + } while ((isHex && isHexDigit( ch)) @@ -181,13 +200,15 @@ else if (ch == '\'') linepos++; token.type = Token.TokenType.STRINGPARAM; if (pos == input.length() && expression != null && context != null) + { throw new ExpressionException(context, this.expression, token, "Program truncated"); + } ch = input.charAt(pos); while (ch != '\'') { if (ch == '\\') { - char nextChar = peekNextChar(); + final char nextChar = peekNextChar(); if (nextChar == 'n') { token.append('\n'); @@ -213,22 +234,26 @@ else if (nextChar == '\\' || nextChar == '\'') pos--; linepos--; } - pos+=2; - linepos+=2; + pos += 2; + linepos += 2; if (pos == input.length() && expression != null && context != null) + { throw new ExpressionException(context, this.expression, token, "Program truncated"); + } } else { token.append(input.charAt(pos++)); linepos++; - if (ch=='\n') + if (ch == '\n') { lineno++; linepos = 0; } if (pos == input.length() && expression != null && context != null) + { throw new ExpressionException(context, this.expression, token, "Program truncated"); + } } ch = input.charAt(pos); } @@ -252,7 +277,7 @@ else if (Character.isLetter(ch) || "_".indexOf(ch) >= 0) { ch = input.charAt(pos++); linepos++; - if (ch=='\n') + if (ch == '\n') { lineno++; linepos = 0; @@ -291,14 +316,16 @@ else if (ch == ',') (ch == ')' || ch == ',' || ch == ']' || ch == '}') && !previousToken.surface.equalsIgnoreCase(";") ) + { throw new ExpressionException(context, this.expression, previousToken, "Can't have operator " + previousToken.surface + " at the end of a subexpression"); + } } else { String greedyMatch = ""; - int initialPos = pos; - int initialLinePos = linepos; + final int initialPos = pos; + final int initialLinePos = linepos; ch = input.charAt(pos); int validOperatorSeenUntil = -1; while (!Character.isLetter(ch) && !Character.isDigit(ch) && "_".indexOf(ch) < 0 @@ -309,13 +336,13 @@ else if (ch == ',') if (comments && "//".equals(greedyMatch)) { - while ( ch != '\n' && pos < input.length()) + while (ch != '\n' && pos < input.length()) { ch = input.charAt(pos++); linepos++; greedyMatch += ch; } - if (ch=='\n') + if (ch == '\n') { lineno++; linepos = 0; @@ -344,7 +371,7 @@ else if (ch == ',') { token.append(input.substring(initialPos, validOperatorSeenUntil)); pos = validOperatorSeenUntil; - linepos = initialLinePos+validOperatorSeenUntil-initialPos; + linepos = initialLinePos + validOperatorSeenUntil - initialPos; } else { @@ -353,7 +380,7 @@ else if (ch == ',') if (previousToken == null || previousToken.type == Token.TokenType.OPERATOR || previousToken.type == Token.TokenType.OPEN_PAREN || previousToken.type == Token.TokenType.COMMA - || (previousToken.type == Token.TokenType.MARKER && ( previousToken.surface.equals("{") || previousToken.surface.equals("[") ) ) + || (previousToken.type == Token.TokenType.MARKER && (previousToken.surface.equals("{") || previousToken.surface.equals("["))) ) { token.surface += "u"; @@ -365,25 +392,25 @@ else if (ch == ',') } } if (expression != null && context != null && previousToken != null && - ( - token.type == Token.TokenType.LITERAL || - token.type == Token.TokenType.HEX_LITERAL || - token.type == Token.TokenType.VARIABLE || - token.type == Token.TokenType.STRINGPARAM || - ( token.type == Token.TokenType.MARKER && ( previousToken.surface.equalsIgnoreCase("{") || previousToken.surface.equalsIgnoreCase("["))) || - token.type == Token.TokenType.FUNCTION - ) &&( + ( + token.type == Token.TokenType.LITERAL || + token.type == Token.TokenType.HEX_LITERAL || + token.type == Token.TokenType.VARIABLE || + token.type == Token.TokenType.STRINGPARAM || + (token.type == Token.TokenType.MARKER && (previousToken.surface.equalsIgnoreCase("{") || previousToken.surface.equalsIgnoreCase("["))) || + token.type == Token.TokenType.FUNCTION + ) && ( previousToken.type == Token.TokenType.VARIABLE || - previousToken.type == Token.TokenType.FUNCTION || - previousToken.type == Token.TokenType.LITERAL || - previousToken.type == Token.TokenType.CLOSE_PAREN || - ( previousToken.type == Token.TokenType.MARKER && ( previousToken.surface.equalsIgnoreCase("}") || previousToken.surface.equalsIgnoreCase("]"))) || - previousToken.type == Token.TokenType.HEX_LITERAL || - previousToken.type == Token.TokenType.STRINGPARAM - ) + previousToken.type == Token.TokenType.FUNCTION || + previousToken.type == Token.TokenType.LITERAL || + previousToken.type == Token.TokenType.CLOSE_PAREN || + (previousToken.type == Token.TokenType.MARKER && (previousToken.surface.equalsIgnoreCase("}") || previousToken.surface.equalsIgnoreCase("]"))) || + previousToken.type == Token.TokenType.HEX_LITERAL || + previousToken.type == Token.TokenType.STRINGPARAM + ) ) { - throw new ExpressionException(context, this.expression, previousToken, "'"+token.surface +"' is not allowed after '"+previousToken.surface+"'"); + throw new ExpressionException(context, this.expression, previousToken, "'" + token.surface + "' is not allowed after '" + previousToken.surface + "'"); } return previousToken = token; } @@ -403,10 +430,10 @@ enum TokenType LITERAL(false, true), HEX_LITERAL(false, true), STRINGPARAM(false, true), OPEN_PAREN(false, true), COMMA(false, true), CLOSE_PAREN(false, true), MARKER(false, true); - boolean functional; - boolean constant; + final boolean functional; + final boolean constant; - TokenType(boolean functional, boolean constant) + TokenType(final boolean functional, final boolean constant) { this.functional = functional; this.constant = constant; @@ -417,44 +444,47 @@ public boolean isFunctional() return functional; } - public boolean isConstant() { + public boolean isConstant() + { return constant; } } + public String surface = ""; public TokenType type; public int pos; public int linepos; public int lineno; public static final Token NONE = new Token(); - public Token morphedInto(TokenType newType, String newSurface) + + public Token morphedInto(final TokenType newType, final String newSurface) { - Token created = new Token(); + final Token created = new Token(); created.surface = newSurface; created.type = newType; created.pos = pos; created.linepos = linepos; - created.lineno= lineno; + created.lineno = lineno; return created; } - public void morph(TokenType type, String s) + public void morph(final TokenType type, final String s) { this.type = type; this.surface = s; } - public void append(char c) + public void append(final char c) { surface += c; } - public void append(String s) + public void append(final String s) { surface += s; } - public char charAt(int pos) + public char charAt(final int pos) { return surface.charAt(pos); } diff --git a/src/main/java/carpet/script/annotation/AnnotationParser.java b/src/main/java/carpet/script/annotation/AnnotationParser.java index 891c64a3c5..052cb524a4 100644 --- a/src/main/java/carpet/script/annotation/AnnotationParser.java +++ b/src/main/java/carpet/script/annotation/AnnotationParser.java @@ -105,32 +105,38 @@ public final class AnnotationParser * @see ScarpetFunction * @param clazz The class to parse */ - public static void parseFunctionClass(Class clazz) + public static void parseFunctionClass(final Class clazz) { // Only try to instantiate or require concrete classes if there are non-static annotated methods - Supplier instanceSupplier = Suppliers.memoize(() -> { + final Supplier instanceSupplier = Suppliers.memoize(() -> { if (Modifier.isAbstract(clazz.getModifiers())) + { throw new IllegalArgumentException("Function class must be concrete to support non-static methods! Class: " + clazz.getSimpleName()); + } try { return clazz.getConstructor().newInstance(); } - catch (ReflectiveOperationException e) + catch (final ReflectiveOperationException e) { throw new IllegalArgumentException( "Couldn't create instance of given " + clazz + ". This is needed for non-static methods. Make sure default constructor is available", e); } }); - Method[] methodz = clazz.getDeclaredMethods(); - for (Method method : methodz) + final Method[] methodz = clazz.getDeclaredMethods(); + for (final Method method : methodz) { if (!method.isAnnotationPresent(ScarpetFunction.class)) + { continue; + } if (method.getExceptionTypes().length != 0) + { throw new IllegalArgumentException("Annotated method '" + method.getName() +"', provided in '"+clazz+"' must not declare checked exceptions"); + } - ParsedFunction function = new ParsedFunction(method, clazz, instanceSupplier); + final ParsedFunction function = new ParsedFunction(method, clazz, instanceSupplier); functionList.add(function); } } @@ -141,10 +147,12 @@ public static void parseFunctionClass(Class clazz) * * @param expr The expression to add every function to */ - public static void apply(Expression expr) + public static void apply(final Expression expr) { - for (ParsedFunction function : functionList) + for (final ParsedFunction function : functionList) + { expr.addLazyFunction(function.name, function.scarpetParamCount, function); + } } private static class ParsedFunction implements TriFunction, LazyValue>, UsageProvider @@ -164,25 +172,27 @@ private static class ParsedFunction implements TriFunction originClass, Supplier instance) + private ParsedFunction(final Method method, final Class originClass, final Supplier instance) { this.name = method.getName(); this.isMethodVarArgs = method.isVarArgs(); this.methodParamCount = method.getParameterCount(); - Parameter[] methodParameters = method.getParameters(); + final Parameter[] methodParameters = method.getParameters(); this.valueConverters = new ValueConverter[isMethodVarArgs ? methodParamCount - 1 : methodParamCount]; for (int i = 0; i < this.methodParamCount; i++) { - Parameter param = methodParameters[i]; + final Parameter param = methodParameters[i]; if (!isMethodVarArgs || i != this.methodParamCount - 1) // Varargs converter is separate + { this.valueConverters[i] = ValueConverter.fromAnnotatedType(param.getAnnotatedType()); + } } - Class originalVarArgsType = isMethodVarArgs ? methodParameters[methodParamCount - 1].getType().getComponentType() : null; + final Class originalVarArgsType = isMethodVarArgs ? methodParameters[methodParamCount - 1].getType().getComponentType() : null; this.varArgsType = ClassUtils.primitiveToWrapper(originalVarArgsType); // Primitive array cannot be cast to Obj[] this.primitiveVarArgs = originalVarArgsType != null && originalVarArgsType.isPrimitive(); this.varArgsConverter = isMethodVarArgs ? ValueConverter.fromAnnotatedType(methodParameters[methodParamCount - 1].getAnnotatedType()) : null; - @SuppressWarnings("unchecked") // Yes. Making a T is not worth + @SuppressWarnings("unchecked") final // Yes. Making a T is not worth OutputConverter converter = OutputConverter.get((Class) method.getReturnType()); this.outputConverter = converter; @@ -193,13 +203,19 @@ private ParsedFunction(Method method, Class originClass, Supplier ins { maxParams = method.getAnnotation(ScarpetFunction.class).maxParams(); if (maxParams == UNDEFINED_PARAMS) + { throw new IllegalArgumentException("No maximum number of params specified for " + name + ", use ScarpetFunction.UNLIMITED_PARAMS for unlimited. " + "Provided in " + originClass); + } if (maxParams == ScarpetFunction.UNLIMITED_PARAMS) + { maxParams = Integer.MAX_VALUE; + } if (maxParams < this.minParams) + { throw new IllegalArgumentException("Provided maximum number of params for " + name + " is smaller than method's param count." + "Provided in " + originClass); + } } this.maxParams = maxParams; @@ -227,56 +243,66 @@ private ParsedFunction(Method method, Class originClass, Supplier ins } @Override - public LazyValue apply(Context context, Context.Type t, List lazyValues) + public LazyValue apply(final Context context, final Context.Type t, final List lazyValues) { - List lv = AbstractLazyFunction.unpackLazy(lazyValues, context, contextType); + final List lv = AbstractLazyFunction.unpackLazy(lazyValues, context, contextType); if (isEffectivelyVarArgs) { if (lv.size() < minParams) - throw new InternalExpressionException("Function '" + name + "' expected at least " + minParams + " arguments, got " + lv.size() + ". " + { + throw new InternalExpressionException("Function '" + name + "' expected at least " + minParams + " arguments, got " + lv.size() + ". " + getUsage()); + } if (lv.size() > maxParams) - throw new InternalExpressionException("Function '" + name + " expected up to " + maxParams + " arguments, got " + lv.size() + ". " + { + throw new InternalExpressionException("Function '" + name + " expected up to " + maxParams + " arguments, got " + lv.size() + ". " + getUsage()); + } } - Object[] params = getMethodParams(lv, context, t); + final Object[] params = getMethodParams(lv, context, t); try { return outputConverter.convert(handle.invokeExact(params)); } - catch (Throwable e) + catch (final Throwable e) { - if (e instanceof RuntimeException) - throw (RuntimeException) e; + if (e instanceof RuntimeException re) + { + throw re; + } throw (Error) e; // Stack overflow or something. Methods are guaranteed not to throw checked exceptions } } // Hot code: Must be optimized - private Object[] getMethodParams(final List lv, final Context context, Context.Type theLazyT) + private Object[] getMethodParams(final List lv, final Context context, final Context.Type theLazyT) { - Object[] params = new Object[methodParamCount]; - ListIterator lvIterator = lv.listIterator(); + final Object[] params = new Object[methodParamCount]; + final ListIterator lvIterator = lv.listIterator(); - int regularArgs = isMethodVarArgs ? methodParamCount - 1 : methodParamCount; + final int regularArgs = isMethodVarArgs ? methodParamCount - 1 : methodParamCount; for (int i = 0; i < regularArgs; i++) { params[i] = valueConverters[i].checkAndConvert(lvIterator, context, theLazyT); if (params[i] == null) + { throw new InternalExpressionException("Incorrect argument passsed to '" + name + "' function.\n" + getUsage()); + } } if (isMethodVarArgs) { - int remaining = lv.size() - lvIterator.nextIndex(); - Object[] varArgs; + final int remaining = lv.size() - lvIterator.nextIndex(); + final Object[] varArgs; if (varArgsConverter.consumesVariableArgs()) { - List varArgsList = new ArrayList<>(); // fastutil's is extremely slow in toArray, and we use that + final List varArgsList = new ArrayList<>(); // fastutil's is extremely slow in toArray, and we use that while (lvIterator.hasNext()) { - Object obj = varArgsConverter.checkAndConvert(lvIterator, context, theLazyT); + final Object obj = varArgsConverter.checkAndConvert(lvIterator, context, theLazyT); if (obj == null) + { throw new InternalExpressionException("Incorrect argument passsed to '" + name + "' function.\n" + getUsage()); + } varArgsList.add(obj); } varArgs = varArgsList.toArray((Object[])Array.newInstance(varArgsType, 0)); @@ -287,7 +313,9 @@ private Object[] getMethodParams(final List lv, final Context context, Co { varArgs[i] = varArgsConverter.checkAndConvert(lvIterator, context, theLazyT); if (varArgs[i] == null) + { throw new InternalExpressionException("Incorrect argument passsed to '" + name + "' function.\n" + getUsage()); + } } } params[methodParamCount - 1] = primitiveVarArgs ? ArrayUtils.toPrimitive(varArgs) : varArgs; // Copies the array @@ -299,7 +327,7 @@ private Object[] getMethodParams(final List lv, final Context context, Co public String getUsage() { // Possibility: More descriptive messages using param.getName()? Would need changing gradle setup to keep those - StringBuilder builder = new StringBuilder("Usage: '"); + final StringBuilder builder = new StringBuilder("Usage: '"); builder.append(name); builder.append('('); builder.append(Arrays.stream(valueConverters).map(ValueConverter::getTypeName).filter(Objects::nonNull).collect(Collectors.joining(", "))); diff --git a/src/main/java/carpet/script/annotation/ListConverter.java b/src/main/java/carpet/script/annotation/ListConverter.java index 5abf88ff6b..abdfbc5b16 100644 --- a/src/main/java/carpet/script/annotation/ListConverter.java +++ b/src/main/java/carpet/script/annotation/ListConverter.java @@ -32,34 +32,38 @@ public String getTypeName() } @Override - public List convert(Value value) + public List convert(final Value value) { return value instanceof ListValue ? convertListValue((ListValue) value) : allowSingletonCreation ? convertSingleton(value) : null; } - private List convertListValue(ListValue values) + private List convertListValue(final ListValue values) { - List list = new ArrayList<>(values.getItems().size()); - for (Value value : values) + final List list = new ArrayList<>(values.getItems().size()); + for (final Value value : values) { - T converted = itemConverter.convert(value); + final T converted = itemConverter.convert(value); if (converted == null) + { return null; + } list.add(converted); } return list; } - private List convertSingleton(Value val) + private List convertSingleton(final Value val) { - T converted = itemConverter.convert(val); + final T converted = itemConverter.convert(val); if (converted == null) + { return null; + } return Collections.singletonList(converted); } - private ListConverter(AnnotatedType itemType, boolean allowSingletonCreation) + private ListConverter(final AnnotatedType itemType, final boolean allowSingletonCreation) { itemConverter = ValueConverter.fromAnnotatedType(itemType); this.allowSingletonCreation = allowSingletonCreation; @@ -79,11 +83,11 @@ private ListConverter(AnnotatedType itemType, boolean allowSingletonCreation) * @param annotatedType The type to get generics information from * @return A new {@link ListConverter} for the data specified in the {@link AnnotatedType} */ - static ListConverter fromAnnotatedType(AnnotatedType annotatedType) + static ListConverter fromAnnotatedType(final AnnotatedType annotatedType) { - AnnotatedParameterizedType paramType = (AnnotatedParameterizedType) annotatedType; - AnnotatedType itemType = paramType.getAnnotatedActualTypeArguments()[0]; - boolean allowSingletonCreation = annotatedType.isAnnotationPresent(Param.AllowSingleton.class); + final AnnotatedParameterizedType paramType = (AnnotatedParameterizedType) annotatedType; + final AnnotatedType itemType = paramType.getAnnotatedActualTypeArguments()[0]; + final boolean allowSingletonCreation = annotatedType.isAnnotationPresent(Param.AllowSingleton.class); return new ListConverter<>(itemType, allowSingletonCreation); } diff --git a/src/main/java/carpet/script/annotation/Locator.java b/src/main/java/carpet/script/annotation/Locator.java index 3f19560702..0c447c3e46 100644 --- a/src/main/java/carpet/script/annotation/Locator.java +++ b/src/main/java/carpet/script/annotation/Locator.java @@ -37,7 +37,7 @@ public interface Locator @Documented @Retention(RUNTIME) @Target({ PARAMETER, TYPE_USE }) - public @interface Block + @interface Block { /** *

Whether or not should the locator accept a single {@link String} as the parameter and let parsing to {@link BlockValue}.

@@ -66,7 +66,7 @@ public interface Locator @Documented @Retention(RUNTIME) @Target({ PARAMETER, TYPE_USE }) - public @interface Vec3d + @interface Vec3d { /** *

Whether or not should the {@link Vector3Argument} locator accept an optional direction aside from the @@ -94,7 +94,7 @@ public interface Locator @Documented @Retention(RUNTIME) @Target({ PARAMETER, TYPE_USE }) - public @interface Function + @interface Function { /** *

Whether this Locator should allow no function to be passed.

This is not compatible with {@link FunctionValue} type, since a @@ -115,18 +115,27 @@ public interface Locator * *

Not part of the public API, just that interfaces must have all members public

*/ - static final class Locators + final class Locators { - private Locators() {} + private Locators() + { + super(); + } - static ValueConverter fromAnnotatedType(AnnotatedType annoType, Class type) + static ValueConverter fromAnnotatedType(final AnnotatedType annoType, final Class type) { if (annoType.isAnnotationPresent(Block.class)) - return new BlockLocator(annoType.getAnnotation(Block.class), type); + { + return new BlockLocator<>(annoType.getAnnotation(Block.class), type); + } if (annoType.isAnnotationPresent(Function.class)) - return new FunctionLocator(annoType.getAnnotation(Function.class), type); + { + return new FunctionLocator<>(annoType.getAnnotation(Function.class), type); + } if (annoType.isAnnotationPresent(Vec3d.class)) - return new Vec3dLocator(annoType.getAnnotation(Vec3d.class), type); + { + return new Vec3dLocator<>(annoType.getAnnotation(Vec3d.class), type); + } throw new IllegalStateException("Locator#fromAnnotatedType got called with an incompatible AnnotatedType"); } @@ -137,28 +146,42 @@ private static class BlockLocator extends AbstractLocator private final boolean anyString; private final boolean optional; - public BlockLocator(Block annotation, Class type) + public BlockLocator(final Block annotation, final Class type) { + super(); this.acceptString = annotation.acceptString(); this.anyString = annotation.anyString(); this.optional = annotation.optional(); if (type != BlockArgument.class && (anyString || optional)) + { throw new IllegalArgumentException("Can only use anyString or optional parameters of Locator.Block if targeting a BlockArgument"); + } this.returnFunction = getReturnFunction(type); if (returnFunction == null) + { throw new IllegalArgumentException("Locator.Block can only be used against BlockArgument, BlockValue, BlockPos or BlockState types!"); + } } @SuppressWarnings("unchecked") - private static java.util.function.Function getReturnFunction(Class type) { + private static java.util.function.Function getReturnFunction(final Class type) + { if (type == BlockArgument.class) + { return r -> (R) r; + } if (type == BlockValue.class) + { return r -> (R) r.block; + } if (type == BlockPos.class) + { return r -> (R) r.block.getPos(); + } if (type == BlockState.class) + { return r -> (R) r.block.getBlockState(); + } return null; } @@ -169,9 +192,9 @@ public String getTypeName() } @Override - public R checkAndConvert(Iterator valueIterator, Context context, Context.Type theLazyT) + public R checkAndConvert(final Iterator valueIterator, final Context context, final Context.Type theLazyT) { - BlockArgument locator = BlockArgument.findIn((CarpetContext) context, valueIterator, 0, acceptString, optional, anyString); + final BlockArgument locator = BlockArgument.findIn((CarpetContext) context, valueIterator, 0, acceptString, optional, anyString); return returnFunction.apply(locator); } } @@ -182,15 +205,19 @@ private static class Vec3dLocator extends AbstractLocator private final boolean optionalEntity; private final boolean returnVec3d; - public Vec3dLocator(Vec3d annotation, Class type) + public Vec3dLocator(final Vec3d annotation, final Class type) { this.optionalDirection = annotation.optionalDirection(); this.optionalEntity = annotation.optionalEntity(); this.returnVec3d = type == net.minecraft.world.phys.Vec3.class; // Because of the locator if (returnVec3d && optionalDirection) + { throw new IllegalArgumentException("optionalDirection Locator.Vec3d cannot be used for Vec3d type, use Vector3Argument instead"); + } if (!returnVec3d && type != Vector3Argument.class) + { throw new IllegalArgumentException("Locator.Vec3d can only be used in Vector3Argument or Vec3d types"); + } } @Override @@ -200,11 +227,10 @@ public String getTypeName() } @Override - public R checkAndConvert(Iterator valueIterator, Context context, Context.Type theLazyT) + public R checkAndConvert(final Iterator valueIterator, final Context context, final Context.Type theLazyT) { - Vector3Argument locator = Vector3Argument.findIn(valueIterator, 0, optionalDirection, optionalEntity); - @SuppressWarnings("unchecked") - R ret = (R) (returnVec3d ? locator.vec : locator); + final Vector3Argument locator = Vector3Argument.findIn(valueIterator, 0, optionalDirection, optionalEntity); + @SuppressWarnings("unchecked") final R ret = (R) (returnVec3d ? locator.vec : locator); return ret; } } @@ -215,24 +241,28 @@ private static class FunctionLocator extends AbstractLocator private final boolean allowNone; private final boolean checkArgs; - FunctionLocator(Function annotation, Class type) + FunctionLocator(final Function annotation, final Class type) { + super(); this.returnFunctionValue = type == FunctionValue.class; if (!returnFunctionValue && type != FunctionArgument.class) + { throw new IllegalArgumentException("Params annotated with Locator.Function must be of either FunctionArgument or FunctionValue type"); + } this.allowNone = annotation.allowNone(); this.checkArgs = annotation.checkArgs(); if (returnFunctionValue && allowNone) + { throw new IllegalArgumentException("Cannot use allowNone of Locator.Function in FunctionValue types, use FunctionArgument"); + } } @Override - public R checkAndConvert(Iterator valueIterator, Context context, Context.Type theLazyT) + public R checkAndConvert(final Iterator valueIterator, final Context context, final Context.Type theLazyT) { - Module module = context.host.main; - FunctionArgument locator = FunctionArgument.findIn(context, module, Lists.newArrayList(valueIterator), 0, allowNone, checkArgs); - @SuppressWarnings("unchecked") - R ret = (R) (returnFunctionValue ? locator.function : locator); + final Module module = context.host.main; + final FunctionArgument locator = FunctionArgument.findIn(context, module, Lists.newArrayList(valueIterator), 0, allowNone, checkArgs); + @SuppressWarnings("unchecked") final R ret = (R) (returnFunctionValue ? locator.function : locator); return ret; } @@ -243,10 +273,10 @@ public String getTypeName() } } - private static abstract class AbstractLocator implements ValueConverter, Locator + private abstract static class AbstractLocator implements ValueConverter, Locator { @Override - public R convert(Value value) + public R convert(final Value value) { throw new UnsupportedOperationException("Cannot call a locator in a parameter that doesn't contain a context!"); } diff --git a/src/main/java/carpet/script/annotation/MapConverter.java b/src/main/java/carpet/script/annotation/MapConverter.java index fd26d30f1d..a39671f5d5 100644 --- a/src/main/java/carpet/script/annotation/MapConverter.java +++ b/src/main/java/carpet/script/annotation/MapConverter.java @@ -37,17 +37,19 @@ public String getTypeName() } @Override - public Map convert(Value value) + public Map convert(final Value value) { - Map result = new HashMap<>(); + final Map result = new HashMap<>(); if (value instanceof MapValue) { - for (Entry entry : ((MapValue) value).getMap().entrySet()) + for (final Entry entry : ((MapValue) value).getMap().entrySet()) { - K key = keyConverter.convert(entry.getKey()); - V val = valueConverter.convert(entry.getValue()); + final K key = keyConverter.convert(entry.getKey()); + final V val = valueConverter.convert(entry.getValue()); if (key == null || val == null) + { return null; + } result.put(key, val); } return result; @@ -55,8 +57,9 @@ public Map convert(Value value) return null; } - private MapConverter(AnnotatedType keyType, AnnotatedType valueType) + private MapConverter(final AnnotatedType keyType, final AnnotatedType valueType) { + super(); keyConverter = ValueConverter.fromAnnotatedType(keyType); valueConverter = ValueConverter.fromAnnotatedType(valueType); } @@ -77,9 +80,9 @@ private MapConverter(AnnotatedType keyType, AnnotatedType valueType) * @param annotatedType The type to get generics information from * @return A new {@link MapConverter} for the data specified in the {@link AnnotatedType} */ - static MapConverter fromAnnotatedType(AnnotatedType annotatedType) + static MapConverter fromAnnotatedType(final AnnotatedType annotatedType) { - AnnotatedType[] annotatedGenerics = ((AnnotatedParameterizedType) annotatedType).getAnnotatedActualTypeArguments(); + final AnnotatedType[] annotatedGenerics = ((AnnotatedParameterizedType) annotatedType).getAnnotatedActualTypeArguments(); return annotatedType.isAnnotationPresent(Param.KeyValuePairs.class) ? new PairConverter<>(annotatedGenerics[0], annotatedGenerics[1], annotatedType.getAnnotation(Param.KeyValuePairs.class)) : new MapConverter<>(annotatedGenerics[0], annotatedGenerics[1]); @@ -89,7 +92,7 @@ private static final class PairConverter extends MapConverter { private final boolean acceptMultiParam; - private PairConverter(AnnotatedType keyType, AnnotatedType valueType, Param.KeyValuePairs config) + private PairConverter(final AnnotatedType keyType, final AnnotatedType valueType, final Param.KeyValuePairs config) { super(keyType, valueType); acceptMultiParam = config.allowMultiparam(); @@ -102,51 +105,63 @@ public boolean consumesVariableArgs() } @Override - public Map convert(Value value) { + public Map convert(final Value value) { return value instanceof MapValue ? super.convert(value) : value instanceof ListValue ? convertList(((ListValue)value).getItems()) : null; // Multiparam mode can only be used in evalAndConvert } - private Map convertList(List valueList) + private Map convertList(final List valueList) { if (valueList.size() % 2 == 1) + { return null; - Map map = new HashMap<>(); - Iterator val = valueList.iterator(); + } + final Map map = new HashMap<>(); + final Iterator val = valueList.iterator(); while (val.hasNext()) { - K key = keyConverter.convert(val.next()); - V value = valueConverter.convert(val.next()); + final K key = keyConverter.convert(val.next()); + final V value = valueConverter.convert(val.next()); if (key == null || value == null) + { return null; + } map.put(key, value); } return map; } @Override - public Map checkAndConvert(Iterator valueIterator, Context context, Context.Type theLazyT) + public Map checkAndConvert(final Iterator valueIterator, final Context context, final Context.Type theLazyT) { if (!valueIterator.hasNext()) + { return null; - Value val = valueIterator.next(); + } + final Value val = valueIterator.next(); if (!acceptMultiParam || val instanceof MapValue || (val instanceof ListValue && !(keyConverter instanceof ListConverter))) + { return convert(val); // @KeyValuePairs Map, Boolean> will not support list consumption + } - Map map = new HashMap<>(); + final Map map = new HashMap<>(); K key = keyConverter.convert(val); //First pair is manual since we got it to check for a different conversion mode V value = valueConverter.checkAndConvert(valueIterator, context, theLazyT); if (key == null || value == null) + { return null; + } map.put(key, value); while (valueIterator.hasNext()) { key = keyConverter.checkAndConvert(valueIterator, context, theLazyT); value = valueConverter.checkAndConvert(valueIterator, context, theLazyT); if (key == null || value == null) + { return null; + } map.put(key, value); } return map; diff --git a/src/main/java/carpet/script/annotation/OptionalConverter.java b/src/main/java/carpet/script/annotation/OptionalConverter.java index e610e9c396..0851915734 100644 --- a/src/main/java/carpet/script/annotation/OptionalConverter.java +++ b/src/main/java/carpet/script/annotation/OptionalConverter.java @@ -50,25 +50,33 @@ private OptionalConverter(AnnotatedType type) * {@link #checkAndConvert(Iterator, Context, Context.Type)} and is only used as a fallback in types that don't support it. */ @Override - public Optional convert(Value value) + public Optional convert(final Value value) { if (value.isNull()) + { return Optional.empty(); - R converted = typeConverter.convert(value); + } + final R converted = typeConverter.convert(value); if (converted == null) + { return null; + } return Optional.of(converted); } @Override - public Optional checkAndConvert(Iterator valueIterator, Context context, Context.Type theLazyT) + public Optional checkAndConvert(final Iterator valueIterator, final Context context, final Context.Type theLazyT) { if (!valueIterator.hasNext() || valueIterator.next().isNull()) + { return Optional.empty(); + } ((ListIterator) valueIterator).previous(); - R converted = typeConverter.checkAndConvert(valueIterator, context, theLazyT); + final R converted = typeConverter.checkAndConvert(valueIterator, context, theLazyT); if (converted == null) + { return null; + } return Optional.of(converted); } @@ -98,10 +106,10 @@ public int valueConsumption() * @param annotatedType The type to get generics information from * @return A new {@link OptionalConverter} for the data specified in the {@link AnnotatedType} */ - static OptionalConverter fromAnnotatedType(AnnotatedType annotatedType) + static OptionalConverter fromAnnotatedType(final AnnotatedType annotatedType) { - AnnotatedParameterizedType paramType = (AnnotatedParameterizedType) annotatedType; - AnnotatedType wrappedType = paramType.getAnnotatedActualTypeArguments()[0]; + final AnnotatedParameterizedType paramType = (AnnotatedParameterizedType) annotatedType; + final AnnotatedType wrappedType = paramType.getAnnotatedActualTypeArguments()[0]; return new OptionalConverter<>(wrappedType); } } diff --git a/src/main/java/carpet/script/annotation/OutputConverter.java b/src/main/java/carpet/script/annotation/OutputConverter.java index 59f9923355..b7947618d4 100644 --- a/src/main/java/carpet/script/annotation/OutputConverter.java +++ b/src/main/java/carpet/script/annotation/OutputConverter.java @@ -58,7 +58,7 @@ public final class OutputConverter private final Function converter; - private OutputConverter(Function converter) + private OutputConverter(final Function converter) { this.converter = converter; } @@ -75,7 +75,9 @@ private OutputConverter(Function converter) public static OutputConverter get(Class returnType) { if (Value.class.isAssignableFrom(returnType)) + { return (OutputConverter) VALUE; + } returnType = (Class) ClassUtils.primitiveToWrapper(returnType); // wrapper holds same generic as primitive: wrapped return (OutputConverter) Objects.requireNonNull(byResult.get(returnType), "Unregistered output type: " + returnType + ". Register in OutputConverter"); @@ -89,7 +91,7 @@ public static OutputConverter get(Class returnType) * @param input The value to convert * @return The converted value */ - public LazyValue convert(T input) + public LazyValue convert(final T input) { return input == null ? LazyValue.NULL : converter.apply(input); } @@ -102,11 +104,13 @@ public LazyValue convert(T input) * @param inputType The class of T * @param converter The function that converts the an instance of T to a {@link LazyValue} */ - public static void register(Class inputType, Function converter) + public static void register(final Class inputType, final Function converter) { - OutputConverter instance = new OutputConverter(converter); + final OutputConverter instance = new OutputConverter<>(converter); if (byResult.containsKey(inputType)) + { throw new IllegalArgumentException(inputType + " already has a registered OutputConverter"); + } byResult.put(inputType, instance); } @@ -119,11 +123,13 @@ public static void register(Class inputType, Function conve * @param inputType The class of T * @param converter The function that converts an instance of T to a {@link Value} */ - public static void registerToValue(Class inputType, Function converter) + public static void registerToValue(final Class inputType, final Function converter) { - OutputConverter instance = new OutputConverter<>(converter.andThen(v -> (c, t) -> v)); + final OutputConverter instance = new OutputConverter<>(converter.andThen(v -> (c, t) -> v)); if (byResult.containsKey(inputType)) + { throw new IllegalArgumentException(inputType + " already has a registered OutputConverter"); + } byResult.put(inputType, instance); } } diff --git a/src/main/java/carpet/script/annotation/Param.java b/src/main/java/carpet/script/annotation/Param.java index 89ac37fdb8..7ec081cd6f 100644 --- a/src/main/java/carpet/script/annotation/Param.java +++ b/src/main/java/carpet/script/annotation/Param.java @@ -51,7 +51,7 @@ public interface Param @Documented @Retention(RUNTIME) @Target({ PARAMETER, TYPE_USE }) - public @interface AllowSingleton + @interface AllowSingleton { } @@ -71,7 +71,7 @@ public interface Param @Documented @Retention(RUNTIME) @Target({ PARAMETER, TYPE_USE }) - public @interface KeyValuePairs + @interface KeyValuePairs { /** *

Whether or not this accepts the key-value pairs directly in the function call as myFunction(..., key, value, key2, value2)

@@ -91,7 +91,7 @@ public interface Param @Documented @Retention(RUNTIME) @Target({ PARAMETER, TYPE_USE }) - public @interface Custom + @interface Custom { } @@ -111,7 +111,7 @@ public interface Param @Documented @Retention(RUNTIME) @Target({ PARAMETER, TYPE_USE }) - public @interface Strict + @interface Strict { /** *

Defines whether this parameter can accept types with "shallow strictness", that is, in order to get a {@link Component}, accepting either a @@ -137,7 +137,7 @@ public interface Param * @see #registerCustomConverterFactory(BiFunction) * */ - public static final class Params + final class Params { /** *

A {@link ValueConverter} that outputs the {@link Context} in which the function has been called, and throws {@link UnsupportedOperationException} when trying to convert a {@link Value} @@ -148,13 +148,13 @@ public static final class Params @Override public String getTypeName() { return null; } @Override - public Context convert(Value value) + public Context convert(final Value value) { throw new UnsupportedOperationException("Called convert() with Value in Context Provider converter, where only checkAndConvert is supported"); } @Override - public Context checkAndConvert(Iterator valueIterator, Context context, Context.Type theLazyT) + public Context checkAndConvert(final Iterator valueIterator, final Context context, final Context.Type theLazyT) { return context; } @@ -175,13 +175,13 @@ public int valueConsumption() @Override public String getTypeName() { return null; } @Override - public Context.Type convert(Value value) + public Context.Type convert(final Value value) { throw new UnsupportedOperationException("Called convert() with a Value in TheLazyT Provider, where only checkAndConvert is supported"); } @Override - public Context.Type checkAndConvert(Iterator valueIterator, Context context, Context.Type theLazyT) + public Context.Type checkAndConvert(final Iterator valueIterator, final Context context, final Context.Type theLazyT) { return theLazyT; } @@ -193,7 +193,7 @@ public int valueConsumption() } }; - static record StrictConverterInfo(Class type, boolean shallow) {} + record StrictConverterInfo(Class type, boolean shallow) {} private static final Map> strictParamsByClassAndShallowness = new HashMap<>(); static { // TODO Specify strictness in name? @@ -214,14 +214,16 @@ static record StrictConverterInfo(Class type, boolean shallow) {} * @throws IllegalArgumentException If the type doesn't accept the {@link Strict} annotation or if it has been used incorrectly (shallow in * unsupported places) */ - static ValueConverter getStrictConverter(AnnotatedType type) + static ValueConverter getStrictConverter(final AnnotatedType type) { - boolean shallow = type.getAnnotation(Strict.class).shallow(); - Class clazz = (Class) type.getType(); - var key = new StrictConverterInfo(clazz, shallow); - ValueConverter converter = strictParamsByClassAndShallowness.get(key); + final boolean shallow = type.getAnnotation(Strict.class).shallow(); + final Class clazz = (Class) type.getType(); + final StrictConverterInfo key = new StrictConverterInfo(clazz, shallow); + final ValueConverter converter = strictParamsByClassAndShallowness.get(key); if (converter != null) + { return converter; + } throw new IllegalArgumentException("Incorrect use of @Param.Strict annotation"); } @@ -237,11 +239,13 @@ static ValueConverter getStrictConverter(AnnotatedType type) * @param shallow {@code true} if you are registering a shallow-strict parameter, {@code false} if a "fully" strict one * @param converter The {@link ValueConverter} for the given type and shallowness. */ - public static void registerStrictConverter(Class type, boolean shallow, ValueConverter converter) + public static void registerStrictConverter(final Class type, final boolean shallow, final ValueConverter converter) { - var key = new StrictConverterInfo(type, shallow); + final StrictConverterInfo key = new StrictConverterInfo(type, shallow); if (strictParamsByClassAndShallowness.containsKey(key)) + { throw new IllegalArgumentException(type + " already has a registered " + (shallow ? "" : "non-") + "shallow StrictConverter"); + } strictParamsByClassAndShallowness.put(key, converter); } @@ -267,19 +271,21 @@ public static void registerStrictConverter(Class type, boolean shallow, V * avoid possible collisions with other extensions. */ @SuppressWarnings("unchecked") // this makes no sense... But I guess its preferable to enforce typesafety in callers - public static void registerCustomConverterFactory(BiFunction, ValueConverter> factory) + public static void registerCustomConverterFactory(final BiFunction, ValueConverter> factory) { customFactories.add((BiFunction, ValueConverter>) (Object) factory); } @SuppressWarnings("unchecked") // Stored correctly - static ValueConverter getCustomConverter(AnnotatedType annoType, Class type) + static ValueConverter getCustomConverter(final AnnotatedType annoType, final Class type) { ValueConverter result; - for (BiFunction, ValueConverter> factory : customFactories) + for (final BiFunction, ValueConverter> factory : customFactories) { if ((result = (ValueConverter) factory.apply(annoType, type)) != null) + { return result; + } } throw new IllegalArgumentException("No custom converter found for Param.Custom annotated param with type " + annoType.getType().getTypeName()); } diff --git a/src/main/java/carpet/script/annotation/ScarpetFunction.java b/src/main/java/carpet/script/annotation/ScarpetFunction.java index 745760b759..c4ad698f78 100644 --- a/src/main/java/carpet/script/annotation/ScarpetFunction.java +++ b/src/main/java/carpet/script/annotation/ScarpetFunction.java @@ -53,7 +53,7 @@ /** *

Used to define that this {@link ScarpetFunction} can accept an unlimited number of parameters

*/ - public static final int UNLIMITED_PARAMS = -1; + int UNLIMITED_PARAMS = -1; /** *

If the function can accept a variable number of parameters, either by declaring its last parameter as a varargs parameter or by having one diff --git a/src/main/java/carpet/script/annotation/SimpleTypeConverter.java b/src/main/java/carpet/script/annotation/SimpleTypeConverter.java index 498e3b36c3..e6beccbaf8 100644 --- a/src/main/java/carpet/script/annotation/SimpleTypeConverter.java +++ b/src/main/java/carpet/script/annotation/SimpleTypeConverter.java @@ -58,8 +58,9 @@ public final class SimpleTypeConverter implements ValueConve * @param inputType The required type for the input {@link Value} * @param converter The function to convert an instance of inputType into R. */ - public SimpleTypeConverter(Class inputType, Function converter, String typeName) + public SimpleTypeConverter(final Class inputType, final Function converter, final String typeName) { + super(); this.converter = converter; this.valueClass = inputType; this.typeName = typeName; @@ -79,14 +80,14 @@ public String getTypeName() * @return The {@link SimpleTypeConverter} for the specified outputType */ @SuppressWarnings("unchecked") // T always extends Value, R is always the same as map's key, since map is private. - static SimpleTypeConverter get(Class outputType) + static SimpleTypeConverter get(final Class outputType) { return (SimpleTypeConverter) byResult.get(outputType); } @Override @SuppressWarnings("unchecked") // more than checked. not using class.cast because then "method is too big" for inlining, because javac is useless - public R convert(Value value) // and adds millions of casts. This one is even removed + public R convert(final Value value) // and adds millions of casts. This one is even removed { return valueClass.isInstance(value) ? converter.apply((T)value) : null; } @@ -103,10 +104,10 @@ public R convert(Value value) * can also throw an {@link InternalExpressionException} by itself if really necessary. * @param typeName The name of the type, following the conventions of {@link ValueConverter#getTypeName()} */ - public static void registerType(Class requiredInputType, Class outputType, - Function converter, String typeName) + public static void registerType(final Class requiredInputType, final Class outputType, + final Function converter, final String typeName) { - SimpleTypeConverter type = new SimpleTypeConverter<>(requiredInputType, converter, typeName); + final SimpleTypeConverter type = new SimpleTypeConverter<>(requiredInputType, converter, typeName); byResult.put(outputType, type); } } diff --git a/src/main/java/carpet/script/annotation/ValueCaster.java b/src/main/java/carpet/script/annotation/ValueCaster.java index 1ca8fee77c..cc8c01ce8b 100644 --- a/src/main/java/carpet/script/annotation/ValueCaster.java +++ b/src/main/java/carpet/script/annotation/ValueCaster.java @@ -50,8 +50,9 @@ public final class ValueCaster implements ValueConverter // R always exten private final Class outputType; private final String typeName; - private ValueCaster(Class outputType, String typeName) + private ValueCaster(final Class outputType, final String typeName) { + super(); this.outputType = outputType; this.typeName = typeName; } @@ -71,17 +72,19 @@ public String getTypeName() */ @SuppressWarnings("unchecked") // Casters are stored with their exact class, for sure since the map is private (&& class has same generic as // caster) - public static ValueCaster get(Class outputType) + public static ValueCaster get(final Class outputType) { return (ValueCaster) byResult.get(outputType); } @Override @SuppressWarnings("unchecked") // more than checked, see SimpleTypeConverter#converter for reasoning - public R convert(Value value) + public R convert(final Value value) { if (!outputType.isInstance(value)) + { return null; + } return (R)value; } @@ -94,9 +97,9 @@ public R convert(Value value) * required */ - public static void register(Class valueClass, String typeName) + public static void register(final Class valueClass, final String typeName) { - ValueCaster caster = new ValueCaster(valueClass, typeName); + final ValueCaster caster = new ValueCaster<>(valueClass, typeName); byResult.putIfAbsent(valueClass, caster); } } diff --git a/src/main/java/carpet/script/annotation/ValueConverter.java b/src/main/java/carpet/script/annotation/ValueConverter.java index ed1a18127a..ebf3914806 100644 --- a/src/main/java/carpet/script/annotation/ValueConverter.java +++ b/src/main/java/carpet/script/annotation/ValueConverter.java @@ -37,7 +37,7 @@ public interface ValueConverter * @apiNote This method is intended to only be called when an error has occurred and therefore there is a need to print a stacktrace with some * helpful usage instructions. */ - public String getTypeName(); + String getTypeName(); /** *

Converts the given {@link Value} to {@code }, which was defined when being registered.

@@ -62,8 +62,7 @@ public interface ValueConverter *

Even with the above reasons, {@link ValueConverter} users should try to implement {@link #convert(Value)} whenever possible instead of * {@link #checkAndConvert(Iterator, Context, Context.Type)}, since it allows its usage in generics of lists and maps.

*/ - @Nullable - public R convert(Value value); + @Nullable R convert(Value value); /** *

Returns whether this {@link ValueConverter} consumes a variable number of elements from the {@link Iterator} passed to it via @@ -72,7 +71,7 @@ public interface ValueConverter * @implNote The default implementation returns {@code false} * @see #valueConsumption() */ - default public boolean consumesVariableArgs() + default boolean consumesVariableArgs() { return false; } @@ -87,7 +86,7 @@ default public boolean consumesVariableArgs() * @implNote The default implementation returns {@code 1} * */ - default public int valueConsumption() + default int valueConsumption() { return 1; } @@ -107,7 +106,7 @@ default public int valueConsumption() * @return A usable {@link ValueConverter} to convert from a {@link Value} to {@code } */ @SuppressWarnings("unchecked") - public static ValueConverter fromAnnotatedType(AnnotatedType annoType) + static ValueConverter fromAnnotatedType(final AnnotatedType annoType) { Class type = annoType.getType() instanceof ParameterizedType ? // We are defining R here. (Class) ((ParameterizedType) annoType.getType()).getRawType() : @@ -118,33 +117,51 @@ public static ValueConverter fromAnnotatedType(AnnotatedType annoType) // Example: AnnotatedGenericTypeArray (or similar) being (@Paran.KeyValuePairs Map... name) // Those will just fail with a ClassCastException. if (type.isArray()) + { type = (Class) type.getComponentType(); // Varargs + } type = (Class) ClassUtils.primitiveToWrapper(type); // It will be boxed anyway, this saves unboxing-boxing if (type == List.class) + { return (ValueConverter) ListConverter.fromAnnotatedType(annoType); // Already checked that type is List + } if (type == Map.class) + { return (ValueConverter) MapConverter.fromAnnotatedType(annoType); // Already checked that type is Map + } if (type == Optional.class) + { return (ValueConverter) OptionalConverter.fromAnnotatedType(annoType); + } if (annoType.getDeclaredAnnotations().length != 0) { if (annoType.isAnnotationPresent(Param.Custom.class)) - return Param.Params.getCustomConverter(annoType, type); // Throws if incorrect usage + { + return Params.getCustomConverter(annoType, type); // Throws if incorrect usage + } if (annoType.isAnnotationPresent(Param.Strict.class)) + { return (ValueConverter) Params.getStrictConverter(annoType); // Throws if incorrect usage + } if (annoType.getAnnotations()[0].annotationType().getEnclosingClass() == Locator.class) + { return Locator.Locators.fromAnnotatedType(annoType, type); + } } // Class only checks if (Value.class.isAssignableFrom(type)) + { return Objects.requireNonNull(ValueCaster.get(type), "Value subclass " + type + " is not registered. Register it in ValueCaster to use it"); - // if (type == LazyValue.class) // No longer supported - // return (ValueConverter) Params.LAZY_VALUE_IDENTITY; + } if (type == Context.class) + { return (ValueConverter) Params.CONTEXT_PROVIDER; + } if (type == Context.Type.class) + { return (ValueConverter) Params.CONTEXT_TYPE_PROVIDER; + } return Objects.requireNonNull(SimpleTypeConverter.get(type), "Type " + type + " is not registered. Register it in SimpleTypeConverter to use it"); } @@ -168,10 +185,8 @@ public static ValueConverter fromAnnotatedType(AnnotatedType annoType) * @implNote This method's default implementation runs the {@link #convert(Value)} function in the next {@link Value} ignoring {@link Context} and * {@code theLazyT}. */ - default public R checkAndConvert(Iterator valueIterator, Context context, Context.Type contextType) + default R checkAndConvert(final Iterator valueIterator, final Context context, final Context.Type contextType) { - if (!valueIterator.hasNext()) - return null; - return convert(valueIterator.next()); + return !valueIterator.hasNext() ? null : convert(valueIterator.next()); } } diff --git a/src/main/java/carpet/script/api/Auxiliary.java b/src/main/java/carpet/script/api/Auxiliary.java index 3357fb87b8..4faa92fb2d 100644 --- a/src/main/java/carpet/script/api/Auxiliary.java +++ b/src/main/java/carpet/script/api/Auxiliary.java @@ -112,61 +112,67 @@ import static java.lang.Math.max; import static java.lang.Math.min; -public class Auxiliary { +public class Auxiliary +{ public static final String MARKER_STRING = "__scarpet_marker"; private static final Map 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 - public static String recognizeResource(Value value, boolean isFloder) + public static String recognizeResource(final Value value, final boolean isFloder) { - String origfile = value.getString(); + final String origfile = value.getString(); String file = origfile.toLowerCase(Locale.ROOT).replaceAll("[^A-Za-z0-9\\-+_/]", ""); file = Arrays.stream(file.split("/+")).filter(s -> !s.isEmpty()).collect(Collectors.joining("/")); if (file.isEmpty() && !isFloder) { - throw new InternalExpressionException("Cannot use "+origfile+" as resource name - must have some letters and numbers"); + throw new InternalExpressionException("Cannot use " + origfile + " as resource name - must have some letters and numbers"); } return file; } - public static void apply(Expression expression) + public static void apply(final Expression expression) { expression.addContextFunction("sound", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext)c; + final CarpetContext cc = (CarpetContext) c; if (lv.size() == 0) { return ListValue.wrap(cc.registry(Registries.SOUND_EVENT).keySet().stream().map(ValueConversions::of)); } - String rawString = lv.get(0).getString(); - ResourceLocation soundName = InputValidator.identifierOf(rawString); - Vector3Argument locator = Vector3Argument.findIn(lv, 1); + final String rawString = lv.get(0).getString(); + final ResourceLocation soundName = InputValidator.identifierOf(rawString); + final Vector3Argument locator = Vector3Argument.findIn(lv, 1); if (cc.registry(Registries.SOUND_EVENT).get(soundName) == null) + { throw new ThrowStatement(rawString, Throwables.UNKNOWN_SOUND); + } final Holder soundHolder = Holder.direct(SoundEvent.createVariableRangeEvent(soundName)); float volume = 1.0F; float pitch = 1.0F; SoundSource mixer = SoundSource.MASTER; - if (lv.size() > 0+locator.offset) + if (lv.size() > 0 + locator.offset) { - volume = (float) NumericValue.asNumber(lv.get(0+locator.offset)).getDouble(); - if (lv.size() > 1+locator.offset) + volume = (float) NumericValue.asNumber(lv.get(0 + locator.offset)).getDouble(); + if (lv.size() > 1 + locator.offset) { - pitch = (float) NumericValue.asNumber(lv.get(1+locator.offset)).getDouble(); - if (lv.size() > 2+locator.offset) + pitch = (float) NumericValue.asNumber(lv.get(1 + locator.offset)).getDouble(); + if (lv.size() > 2 + locator.offset) { - String mixerName = lv.get(2+locator.offset).getString(); + final String mixerName = lv.get(2 + locator.offset).getString(); mixer = mixerMap.get(mixerName.toLowerCase(Locale.ROOT)); - if (mixer == null) throw new InternalExpressionException(mixerName +" is not a valid mixer name"); + if (mixer == null) + { + throw new InternalExpressionException(mixerName + " is not a valid mixer name"); + } } } } - Vec3 vec = locator.vec; - double d0 = Math.pow(volume > 1.0F ? (double)(volume * 16.0F) : 16.0D, 2.0D); + final Vec3 vec = locator.vec; + final double d0 = Math.pow(volume > 1.0F ? (double) (volume * 16.0F) : 16.0D, 2.0D); int count = 0; final ServerLevel level = cc.level(); - long seed = level.getRandom().nextLong(); - for (ServerPlayer player : level.getPlayers( (p) -> p.distanceToSqr(vec) < d0)) + final long seed = level.getRandom().nextLong(); + for (final ServerPlayer player : level.getPlayers((p) -> p.distanceToSqr(vec) < d0)) { count++; player.connection.send(new ClientboundSoundPacket(soundHolder, mixer, vec.x, vec.y, vec.z, volume, pitch, seed)); @@ -176,12 +182,15 @@ public static void apply(Expression expression) expression.addContextFunction("particle", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext)c; - if (lv.size() == 0) return ListValue.wrap(cc.registry(Registries.PARTICLE_TYPE).keySet().stream().map(ValueConversions::of)); - MinecraftServer ms = cc.server(); - ServerLevel world = cc.level(); - Vector3Argument locator = Vector3Argument.findIn(lv, 1); - String particleName = lv.get(0).getString(); + final CarpetContext cc = (CarpetContext) c; + if (lv.size() == 0) + { + return ListValue.wrap(cc.registry(Registries.PARTICLE_TYPE).keySet().stream().map(ValueConversions::of)); + } + final MinecraftServer ms = cc.server(); + final ServerLevel world = cc.level(); + final Vector3Argument locator = Vector3Argument.findIn(lv, 1); + final String particleName = lv.get(0).getString(); int count = 10; double speed = 0; float spread = 0.5f; @@ -189,10 +198,10 @@ public static void apply(Expression expression) if (lv.size() > locator.offset) { count = (int) NumericValue.asNumber(lv.get(locator.offset)).getLong(); - if (lv.size() > 1+locator.offset) + if (lv.size() > 1 + locator.offset) { - spread = (float) NumericValue.asNumber(lv.get(1+locator.offset)).getDouble(); - if (lv.size() > 2+locator.offset) + spread = (float) NumericValue.asNumber(lv.get(1 + locator.offset)).getDouble(); + if (lv.size() > 2 + locator.offset) { 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 @@ -202,13 +211,13 @@ public static void apply(Expression expression) } } } - ParticleOptions particle = ShapeDispatcher.getParticleData(particleName, world.registryAccess()); - Vec3 vec = locator.vec; + final ParticleOptions particle = ShapeDispatcher.getParticleData(particleName, world.registryAccess()); + final Vec3 vec = locator.vec; if (player == null) { - for (Player p : (world.players())) + for (final ServerPlayer p : (world.players())) { - world.sendParticles((ServerPlayer)p, particle, true, vec.x, vec.y, vec.z, count, + world.sendParticles(p, particle, true, vec.x, vec.y, vec.z, count, spread, spread, spread, speed); } } @@ -224,29 +233,32 @@ public static void apply(Expression expression) expression.addContextFunction("particle_line", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext)c; - ServerLevel world = cc.level(); - String particleName = lv.get(0).getString(); - ParticleOptions particle = ShapeDispatcher.getParticleData(particleName, world.registryAccess()); - Vector3Argument pos1 = Vector3Argument.findIn(lv, 1); - Vector3Argument pos2 = Vector3Argument.findIn(lv, pos1.offset); + final CarpetContext cc = (CarpetContext) c; + final ServerLevel world = cc.level(); + final String particleName = lv.get(0).getString(); + final ParticleOptions particle = ShapeDispatcher.getParticleData(particleName, world.registryAccess()); + final Vector3Argument pos1 = Vector3Argument.findIn(lv, 1); + final Vector3Argument pos2 = Vector3Argument.findIn(lv, pos1.offset); double density = 1.0; ServerPlayer player = null; - if (lv.size() > pos2.offset+0 ) + if (lv.size() > pos2.offset + 0) { - density = NumericValue.asNumber(lv.get(pos2.offset+0)).getDouble(); + density = NumericValue.asNumber(lv.get(pos2.offset + 0)).getDouble(); if (density <= 0) { throw new InternalExpressionException("Particle density should be positive"); } - if (lv.size() > pos2.offset+1) + if (lv.size() > pos2.offset + 1) { - Value playerValue = lv.get(pos2.offset+1); - if (playerValue instanceof EntityValue) + final Value playerValue = lv.get(pos2.offset + 1); + if (playerValue instanceof EntityValue entityValue) { - Entity e = ((EntityValue) playerValue).getEntity(); - if (!(e instanceof ServerPlayer)) throw new InternalExpressionException("'particle_line' player argument has to be a player"); - player = (ServerPlayer) e; + final Entity e = entityValue.getEntity(); + if (!(e instanceof final ServerPlayer sp)) + { + throw new InternalExpressionException("'particle_line' player argument has to be a player"); + } + player = sp; } else { @@ -256,39 +268,42 @@ public static void apply(Expression expression) } return new NumericValue(ShapeDispatcher.drawParticleLine( - (player == null)?world.players(): Collections.singletonList(player), + (player == null) ? world.players() : Collections.singletonList(player), particle, pos1.vec, pos2.vec, density )); }); - expression.addContextFunction("item_display_name", 1, (c, t, lv) -> new FormattedTextValue(ValueConversions.getItemStackFromValue(lv.get(0), false, ((CarpetContext)c).registryAccess()).getHoverName())); + expression.addContextFunction("item_display_name", 1, (c, t, lv) -> new FormattedTextValue(ValueConversions.getItemStackFromValue(lv.get(0), false, ((CarpetContext) c).registryAccess()).getHoverName())); expression.addContextFunction("particle_box", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext)c; - ServerLevel world = cc.level(); - String particleName = lv.get(0).getString(); - ParticleOptions particle = ShapeDispatcher.getParticleData(particleName, world.registryAccess() ); - Vector3Argument pos1 = Vector3Argument.findIn(lv, 1); - Vector3Argument pos2 = Vector3Argument.findIn(lv, pos1.offset); + final CarpetContext cc = (CarpetContext) c; + final ServerLevel world = cc.level(); + final String particleName = lv.get(0).getString(); + final ParticleOptions particle = ShapeDispatcher.getParticleData(particleName, world.registryAccess()); + final Vector3Argument pos1 = Vector3Argument.findIn(lv, 1); + final Vector3Argument pos2 = Vector3Argument.findIn(lv, pos1.offset); double density = 1.0; ServerPlayer player = null; - if (lv.size() > pos2.offset+0 ) + if (lv.size() > pos2.offset + 0) { - density = NumericValue.asNumber(lv.get(pos2.offset+0)).getDouble(); + density = NumericValue.asNumber(lv.get(pos2.offset + 0)).getDouble(); if (density <= 0) { throw new InternalExpressionException("Particle density should be positive"); } - if (lv.size() > pos2.offset+1) + if (lv.size() > pos2.offset + 1) { - Value playerValue = lv.get(pos2.offset+1); - if (playerValue instanceof EntityValue) + final Value playerValue = lv.get(pos2.offset + 1); + if (playerValue instanceof EntityValue entityValue) { - Entity e = ((EntityValue) playerValue).getEntity(); - if (!(e instanceof ServerPlayer)) throw new InternalExpressionException("'particle_box' player argument has to be a player"); - player = (ServerPlayer) e; + final Entity e = entityValue.getEntity(); + if (!(e instanceof final ServerPlayer sp)) + { + throw new InternalExpressionException("'particle_box' player argument has to be a player"); + } + player = sp; } else { @@ -296,12 +311,12 @@ public static void apply(Expression expression) } } } - 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.players():Collections.singletonList(player), + final Vec3 a = pos1.vec; + final Vec3 b = pos2.vec; + final Vec3 from = new Vec3(min(a.x, b.x), min(a.y, b.y), min(a.z, b.z)); + final Vec3 to = new Vec3(max(a.x, b.x), max(a.y, b.y), max(a.z, b.z)); + final int particleCount = ShapeDispatcher.Box.particleMesh( + player == null ? world.players() : Collections.singletonList(player), particle, density, from, to ); return new NumericValue(particleCount); @@ -312,19 +327,25 @@ public static void apply(Expression expression) expression.addContextFunction("draw_shape", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext)c; - ServerLevel world = cc.level(); - MinecraftServer server = world.getServer(); - Set playerTargets = new HashSet<>(); - List shapes = new ArrayList<>(); + final CarpetContext cc = (CarpetContext) c; + final ServerLevel world = cc.level(); + final MinecraftServer server = world.getServer(); + final Set playerTargets = new HashSet<>(); + final List shapes = new ArrayList<>(); if (lv.size() == 1) // bulk { - Value specLoad = lv.get(0); - if (!(specLoad instanceof ListValue)) throw new InternalExpressionException("In bulk mode - shapes need to be provided as a list of shape specs"); - for (Value list : ((ListValue) specLoad).getItems()) + final Value specLoad = lv.get(0); + if (!(specLoad instanceof final ListValue spec)) { - if (!(list instanceof ListValue)) throw new InternalExpressionException("In bulk mode - shapes need to be provided as a list of shape specs"); - shapes.add( ShapeDispatcher.fromFunctionArgs(server, world, ((ListValue) list).getItems(), playerTargets)); + throw new InternalExpressionException("In bulk mode - shapes need to be provided as a list of shape specs"); + } + for (final Value list : spec.getItems()) + { + if (!(list instanceof final ListValue inner)) + { + throw new InternalExpressionException("In bulk mode - shapes need to be provided as a list of shape specs"); + } + shapes.add(ShapeDispatcher.fromFunctionArgs(server, world, inner.getItems(), playerTargets)); } } else @@ -333,27 +354,30 @@ public static void apply(Expression expression) } ShapeDispatcher.sendShape( - (playerTargets.isEmpty())?cc.level().players():playerTargets, + (playerTargets.isEmpty()) ? cc.level().players() : playerTargets, shapes ); return Value.TRUE; }); - expression.addContextFunction("create_marker", -1, (c, t, lv) ->{ - CarpetContext cc = (CarpetContext)c; + expression.addContextFunction("create_marker", -1, (c, t, lv) -> { + final CarpetContext cc = (CarpetContext) c; BlockState targetBlock = null; - Vector3Argument pointLocator; + final Vector3Argument pointLocator; boolean interactable = true; - Component name; + final Component name; try { - Value nameValue = lv.get(0); + final Value nameValue = lv.get(0); name = nameValue.isNull() ? null : FormattedTextValue.getTextByValue(nameValue); pointLocator = Vector3Argument.findIn(lv, 1, true, false); - if (lv.size()>pointLocator.offset) + if (lv.size() > pointLocator.offset) { - BlockArgument blockLocator = BlockArgument.findIn(cc, lv, pointLocator.offset, true, true, false); - if (blockLocator.block != null) targetBlock = blockLocator.block.getBlockState(); + final BlockArgument blockLocator = BlockArgument.findIn(cc, lv, pointLocator.offset, true, true, false); + if (blockLocator.block != null) + { + targetBlock = blockLocator.block.getBlockState(); + } if (lv.size() > blockLocator.offset) { interactable = lv.get(blockLocator.offset).getBoolean(); @@ -364,9 +388,9 @@ public static void apply(Expression expression) { throw new InternalExpressionException("'create_marker' requires a name and three coordinates, with optional direction, and optional block on its head"); } - Level level = cc.level(); - ArmorStand armorstand = new ArmorStand(EntityType.ARMOR_STAND, level); - double yoffset; + final Level level = cc.level(); + final ArmorStand armorstand = new ArmorStand(EntityType.ARMOR_STAND, level); + final double yoffset; if (targetBlock == null && name == null) { yoffset = 0.0; @@ -377,13 +401,13 @@ else if (!interactable && targetBlock == null) } else { - if (targetBlock==null) + if (targetBlock == null) { - yoffset = -armorstand.getBbHeight()-0.41; + yoffset = -armorstand.getBbHeight() - 0.41; } else { - yoffset = -armorstand.getBbHeight()+0.3; + yoffset = -armorstand.getBbHeight() + 0.3; } } armorstand.moveTo( @@ -391,34 +415,36 @@ else if (!interactable && targetBlock == null) //pointLocator.vec.y - ((!interactable && targetBlock == null)?0.41f:((targetBlock==null)?(armorstand.getHeight()+0.41):(armorstand.getHeight()-0.3))), pointLocator.vec.y + yoffset, pointLocator.vec.z, - (float)pointLocator.yaw, + (float) pointLocator.yaw, (float) pointLocator.pitch ); - armorstand.addTag(MARKER_STRING+"_"+((cc.host.getName()==null)?"":cc.host.getName())); + armorstand.addTag(MARKER_STRING + "_" + ((cc.host.getName() == null) ? "" : cc.host.getName())); armorstand.addTag(MARKER_STRING); if (targetBlock != null) + { armorstand.setItemSlot(EquipmentSlot.HEAD, new ItemStack(targetBlock.getBlock().asItem())); + } if (name != null) { armorstand.setCustomName(name); armorstand.setCustomNameVisible(true); } - armorstand.setHeadPose(new Rotations((int)pointLocator.pitch,0,0)); + armorstand.setHeadPose(new Rotations((int) pointLocator.pitch, 0, 0)); armorstand.setNoGravity(true); armorstand.setInvisible(true); armorstand.setInvulnerable(true); - armorstand.getEntityData().set(ArmorStand.DATA_CLIENT_FLAGS, (byte)(interactable?8 : 16|8)); + armorstand.getEntityData().set(ArmorStand.DATA_CLIENT_FLAGS, (byte) (interactable ? 8 : 16 | 8)); level.addFreshEntity(armorstand); return new EntityValue(armorstand); }); expression.addContextFunction("remove_all_markers", 0, (c, t, lv) -> { - CarpetContext cc = (CarpetContext)c; + final CarpetContext cc = (CarpetContext) c; int total = 0; - String markerName = MARKER_STRING+"_"+((cc.host.getName()==null)?"":cc.host.getName()); - for (Entity e : cc.level().getEntities(EntityType.ARMOR_STAND, (as) -> as.getTags().contains(markerName))) + final String markerName = MARKER_STRING + "_" + ((cc.host.getName() == null) ? "" : cc.host.getName()); + for (final Entity e : cc.level().getEntities(EntityType.ARMOR_STAND, (as) -> as.getTags().contains(markerName))) { - total ++; + total++; e.discard(); // discard // remove(); } return new NumericValue(total); @@ -429,35 +455,49 @@ else if (!interactable && targetBlock == null) expression.addUnaryFunction("escape_nbt", v -> new StringValue(StringTag.quoteAndEscape(v.getString()))); expression.addUnaryFunction("parse_nbt", v -> { - if (v instanceof NBTSerializableValue) return ((NBTSerializableValue) v).toValue(); - NBTSerializableValue ret = NBTSerializableValue.parseString(v.getString(), false); - if (ret == null) return Value.NULL; - return ret.toValue(); + if (v instanceof final NBTSerializableValue nbtsv) + { + return nbtsv.toValue(); + } + final NBTSerializableValue ret = NBTSerializableValue.parseString(v.getString(), false); + return ret == null ? Value.NULL : ret.toValue(); }); expression.addFunction("tag_matches", (lv) -> { - int numParam = lv.size(); - 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; - Tag source = ((NBTSerializableValue)(NBTSerializableValue.fromValue(lv.get(0)))).getTag(); - Tag match = ((NBTSerializableValue)(NBTSerializableValue.fromValue(lv.get(1)))).getTag(); + final int numParam = lv.size(); + 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; + } + final Tag source = ((NBTSerializableValue) (NBTSerializableValue.fromValue(lv.get(0)))).getTag(); + final 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 -> { - int argSize = lv.size(); - 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(); - Tag tag; + final int argSize = lv.size(); + if (argSize == 0 || argSize > 2) + { + throw new InternalExpressionException("'encode_nbt' requires 1 or 2 parameters"); + } + final Value v = lv.get(0); + final boolean force = (argSize > 1) && lv.get(1).getBoolean(); + final Tag tag; try { tag = v.toTag(force); } - catch (NBTSerializableValue.IncompatibleTypeException ignored) + catch (final NBTSerializableValue.IncompatibleTypeException exception) { - throw new InternalExpressionException("cannot reliably encode to a tag the value of '"+ignored.val.getPrettyString()+"'"); + throw new InternalExpressionException("cannot reliably encode to a tag the value of '" + exception.val.getPrettyString() + "'"); } return new NBTSerializableValue(tag); }); @@ -465,24 +505,30 @@ else if (!interactable && targetBlock == null) //"overridden" native call that prints to stderr expression.addContextFunction("print", -1, (c, t, lv) -> { - if (lv.size() == 0 || lv.size() > 2) throw new InternalExpressionException("'print' takes one or two arguments"); - CommandSourceStack s = ((CarpetContext)c).source(); - MinecraftServer server = s.getServer(); + if (lv.size() == 0 || lv.size() > 2) + { + throw new InternalExpressionException("'print' takes one or two arguments"); + } + final CommandSourceStack s = ((CarpetContext) c).source(); + final MinecraftServer server = s.getServer(); Value res = lv.get(0); List targets = null; if (lv.size() == 2) { - List playerValues = (res instanceof ListValue)?((ListValue) res).getItems():Collections.singletonList(res); - List playerTargets = new ArrayList<>(); + final List playerValues = (res instanceof ListValue list) ? list.getItems() : Collections.singletonList(res); + final List playerTargets = new ArrayList<>(); playerValues.forEach(pv -> { - ServerPlayer player = EntityValue.getPlayerByValue(server, pv); - if (player == null) throw new InternalExpressionException("Cannot target player "+pv.getString()+" in print"); + final 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); } - Component message = FormattedTextValue.getTextByValue(res); + final Component message = FormattedTextValue.getTextByValue(res); if (targets == null) { s.sendSuccess(message, false); @@ -495,55 +541,62 @@ else if (!interactable && targetBlock == null) }); expression.addContextFunction("display_title", -1, (c, t, lv) -> { - if (lv.size() < 2) throw new InternalExpressionException("'display_title' needs at least a target, type and message, and optionally times"); + if (lv.size() < 2) + { + throw new InternalExpressionException("'display_title' needs at least a target, type and message, and optionally times"); + } Value pVal = lv.get(0); - if (!(pVal instanceof ListValue)) pVal = ListValue.of(pVal); - MinecraftServer server = ((CarpetContext)c).server(); - Stream targets = ((ListValue) pVal).getItems().stream().map(v -> + if (!(pVal instanceof ListValue)) + { + pVal = ListValue.of(pVal); + } + final MinecraftServer server = ((CarpetContext) c).server(); + final Stream targets = ((ListValue) pVal).getItems().stream().map(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."); + final 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> packetGetter = null; - //TitleS2CPacket.Action action; - String actionString = lv.get(1).getString().toLowerCase(Locale.ROOT); + final String actionString = lv.get(1).getString().toLowerCase(Locale.ROOT); switch (actionString) { case "title": 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 = 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 = 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 ClientboundClearTitlesPacket(true); // resetting default fade - //action = Action.CLEAR; + packetGetter = x -> new ClientboundClearTitlesPacket(true); // resetting default fade break; - case "player_list_header": - case "player_list_footer": + case "player_list_header", "player_list_footer": break; default: throw new InternalExpressionException("'display_title' requires 'title', 'subtitle', 'actionbar', 'player_list_header', 'player_list_footer' or 'clear' as second argument"); } - //if (action != Action.CLEAR && lv.size() < 3) - // throw new InternalExpressionException("Third argument of 'display_title' must be present except for 'clear' type"); - Component title; + final Component title; boolean soundsTrue = false; if (lv.size() > 2) { @@ -551,47 +604,65 @@ else if (!interactable && targetBlock == null) title = FormattedTextValue.getTextByValue(pVal); soundsTrue = pVal.getBoolean(); } - else title = null; // Will never happen, just to make lambda happy + else + { + title = null; // Will never happen, just to make lambda happy + } if (packetGetter == null) { - Map map; + final Map map; if (actionString.equals("player_list_header")) + { map = HUDController.scarpet_headers; + } else + { map = HUDController.scarpet_footers; + } - AtomicInteger total = new AtomicInteger(0); - List targetList = targets.collect(Collectors.toList()); + final AtomicInteger total = new AtomicInteger(0); + final List targetList = targets.collect(Collectors.toList()); if (!soundsTrue) // null or empty string + { targetList.forEach(target -> { map.remove(target.getScoreboardName()); total.getAndIncrement(); }); + } else + { targetList.forEach(target -> { map.put(target.getScoreboardName(), title); total.getAndIncrement(); }); - HUDController.update_hud(((CarpetContext)c).server(), targetList); + } + HUDController.update_hud(((CarpetContext) c).server(), targetList); return NumericValue.of(total.get()); } - ClientboundSetTitlesAnimationPacket timesPacket; // TimesPacket + final 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(); + if (lv.size() != 6) + { + throw new InternalExpressionException("'display_title' needs all fade-in, stay and fade-out times"); + } + final int in = NumericValue.asNumber(lv.get(3), "fade in for display_title").getInt(); + final int stay = NumericValue.asNumber(lv.get(4), "stay for display_title").getInt(); + final int out = NumericValue.asNumber(lv.get(5), "fade out for display_title").getInt(); timesPacket = new ClientboundSetTitlesAnimationPacket(in, stay, out); - //timesPacket = new TitleS2CPacket(Action.TIMES, null, in, stay, out); } - else timesPacket = null; + else + { + timesPacket = null; + } - Packet packet = packetGetter.apply(title); - //TitleS2CPacket packet = new TitleS2CPacket(action, title); - AtomicInteger total = new AtomicInteger(0); + final Packet packet = packetGetter.apply(title); + final AtomicInteger total = new AtomicInteger(0); targets.forEach(p -> { - if (timesPacket != null) p.connection.send(timesPacket); + if (timesPacket != null) + { + p.connection.send(timesPacket); + } p.connection.send(packet); total.getAndIncrement(); }); @@ -599,20 +670,25 @@ else if (!interactable && targetBlock == null) }); expression.addFunction("format", values -> { - if (values.size() == 0 ) throw new InternalExpressionException("'format' requires at least one component"); - if (values.get(0) instanceof ListValue && values.size()==1) - values = ((ListValue) values.get(0)).getItems(); + if (values.size() == 0) + { + throw new InternalExpressionException("'format' requires at least one component"); + } + if (values.get(0) instanceof final ListValue list && values.size() == 1) + { + values = list.getItems(); + } return new FormattedTextValue(Messenger.c(values.stream().map(Value::getString).toArray())); }); expression.addContextFunction("run", 1, (c, t, lv) -> { - CommandSourceStack s = ((CarpetContext)c).source(); + final CommandSourceStack s = ((CarpetContext) c).source(); try { - Component[] error = {null}; - List output = new ArrayList<>(); - Value retval = new NumericValue(s.getServer().getCommands().performPrefixedCommand( + final Component[] error = {null}; + final List output = new ArrayList<>(); + final Value retval = new NumericValue(s.getServer().getCommands().performPrefixedCommand( new SnoopyCommandSource(s, error, output), lv.get(0).getString()) ); @@ -622,7 +698,7 @@ else if (!interactable && targetBlock == null) FormattedTextValue.of(error[0]) ); } - catch (Exception exc) + catch (final Exception exc) { return ListValue.of(Value.NULL, ListValue.of(), new FormattedTextValue(Component.literal(exc.getMessage()))); } @@ -630,10 +706,10 @@ else if (!interactable && targetBlock == null) expression.addContextFunction("save", 0, (c, t, lv) -> { - CommandSourceStack s = ((CarpetContext)c).source(); + final CommandSourceStack s = ((CarpetContext) c).source(); s.getServer().getPlayerList().saveAll(); - s.getServer().saveAllChunks(true,true,true); - for (ServerLevel world : s.getServer().getAllLevels()) + s.getServer().saveAllChunks(true, true, true); + for (final ServerLevel world : s.getServer().getAllLevels()) { world.getChunkSource().tick(() -> true, false); } @@ -651,11 +727,14 @@ else if (!interactable && targetBlock == null) expression.addContextFunction("day_time", -1, (c, t, lv) -> { - Value time = new NumericValue(((CarpetContext) c).level().getDayTime()); + final Value time = new NumericValue(((CarpetContext) c).level().getDayTime()); if (lv.size() > 0) { long newTime = NumericValue.asNumber(lv.get(0)).getLong(); - if (newTime < 0) newTime = 0; + if (newTime < 0) + { + newTime = 0; + } ((CarpetContext) c).level().setDayTime(newTime); } return time; @@ -664,33 +743,41 @@ else if (!interactable && targetBlock == null) expression.addContextFunction("last_tick_times", -1, (c, t, lv) -> { c.host.issueDeprecation("last_tick_times()"); - return SystemInfo.get("server_last_tick_times", (CarpetContext)c); + return SystemInfo.get("server_last_tick_times", (CarpetContext) c); }); expression.addContextFunction("game_tick", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext)c; - //CommandSourceStack s = cc.source(); - MinecraftServer server = cc.server(); - if (CarpetServer.scriptServer == null) return Value.NULL; - if (!server.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."); + final CarpetContext cc = (CarpetContext) c; + final MinecraftServer server = cc.server(); + if (CarpetServer.scriptServer == null) + { + return Value.NULL; + } + if (!server.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 { - CarpetServer.scriptServer.tickDepth ++; + CarpetServer.scriptServer.tickDepth++; ((MinecraftServerInterface) server).forceTick(() -> System.nanoTime() - CarpetServer.scriptServer.tickStart < 50000000L); if (lv.size() > 0) { - long ms_total = NumericValue.asNumber(lv.get(0)).getLong(); - long end_expected = CarpetServer.scriptServer.tickStart + ms_total * 1000000L; - long wait = end_expected - System.nanoTime(); + final long ms_total = NumericValue.asNumber(lv.get(0)).getLong(); + final long end_expected = CarpetServer.scriptServer.tickStart + ms_total * 1000000L; + final long wait = end_expected - System.nanoTime(); if (wait > 0L) { try { Thread.sleep(wait / 1000000L); } - catch (InterruptedException ignored) + catch (final InterruptedException ignored) { } } @@ -701,25 +788,29 @@ else if (!interactable && targetBlock == null) finally { if (CarpetServer.scriptServer != null) - CarpetServer.scriptServer.tickDepth --; + { + CarpetServer.scriptServer.tickDepth--; + } } - if(CarpetServer.scriptServer != null && CarpetServer.scriptServer.stopAll) + if (CarpetServer.scriptServer != null && CarpetServer.scriptServer.stopAll) + { throw new ExitStatement(Value.NULL); + } return Value.TRUE; }); expression.addContextFunction("seed", -1, (c, t, lv) -> { - CommandSourceStack s = ((CarpetContext)c).source(); + final CommandSourceStack s = ((CarpetContext) c).source(); c.host.issueDeprecation("seed()"); return new NumericValue(s.getLevel().getSeed()); }); expression.addContextFunction("relight", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext) c; - BlockArgument locator = BlockArgument.findIn(cc, lv, 0); - BlockPos pos = locator.block.getPos(); - ServerLevel world = cc.level(); + final CarpetContext cc = (CarpetContext) c; + final BlockArgument locator = BlockArgument.findIn(cc, lv, 0); + final BlockPos pos = locator.block.getPos(); + final ServerLevel world = cc.level(); ((ThreadedAnvilChunkStorageInterface) world.getChunkSource().chunkMap).relightChunk(new ChunkPos(pos)); WorldTools.forceChunkUpdate(pos, world); return Value.TRUE; @@ -727,32 +818,35 @@ else if (!interactable && targetBlock == null) // Should this be deprecated for system_info('source_dimension')? expression.addContextFunction("current_dimension", 0, (c, t, lv) -> - ValueConversions.of( ((CarpetContext)c).level())); + ValueConversions.of(((CarpetContext) c).level())); expression.addContextFunction("view_distance", 0, (c, t, lv) -> { c.host.issueDeprecation("view_distance()"); - return new NumericValue(((CarpetContext)c).server().getPlayerList().getViewDistance()); + return new NumericValue(((CarpetContext) c).server().getPlayerList().getViewDistance()); }); // lazy due to passthrough and context changing ability expression.addLazyFunction("in_dimension", 2, (c, t, lv) -> { - CommandSourceStack outerSource = ((CarpetContext)c).source(); - Value dimensionValue = lv.get(0).evalValue(c); - 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(); + final CommandSourceStack outerSource = ((CarpetContext) c).source(); + final Value dimensionValue = lv.get(0).evalValue(c); + final Level world = ValueConversions.dimFromValue(dimensionValue, outerSource.getServer()); + if (world == outerSource.getLevel()) + { + return lv.get(1); + } + final CommandSourceStack innerSource = outerSource.withLevel((ServerLevel) world); + final Context newCtx = c.recreate(); ((CarpetContext) newCtx).swapSource(innerSource); newCtx.variables = c.variables; - Value retval = lv.get(1).evalValue(newCtx); + final Value retval = lv.get(1).evalValue(newCtx); return (cc, tt) -> retval; }); - expression.addContextFunction("plop", -1, (c, t, lv) ->{ + expression.addContextFunction("plop", -1, (c, t, lv) -> { if (lv.size() == 0) { - Map plopData = new HashMap<>(); - CarpetContext cc = (CarpetContext)c; + final Map plopData = new HashMap<>(); + final CarpetContext cc = (CarpetContext) c; plopData.put(StringValue.of("scarpet_custom"), ListValue.wrap(FeatureGenerator.featureMap.keySet().stream().sorted().map(StringValue::of)) ); @@ -770,30 +864,38 @@ else if (!interactable && targetBlock == null) ); return MapValue.wrap(plopData); } - BlockArgument locator = BlockArgument.findIn((CarpetContext)c, lv, 0); + final BlockArgument locator = BlockArgument.findIn((CarpetContext) c, lv, 0); if (lv.size() <= locator.offset) + { 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).server().executeBlocking( () -> + } + final String what = lv.get(locator.offset).getString(); + final Value[] result = new Value[]{Value.NULL}; + ((CarpetContext) c).server().executeBlocking(() -> { - Boolean res = FeatureGenerator.plop(what, ((CarpetContext) c).level(), locator.block.getPos()); + final Boolean res = FeatureGenerator.plop(what, ((CarpetContext) c).level(), locator.block.getPos()); if (res == null) + { return; + } if (what.equalsIgnoreCase("forest_rock")) // there might be more of those + { WorldTools.forceChunkUpdate(locator.block.getPos(), ((CarpetContext) c).level()); + } result[0] = BooleanValue.of(res); }); return result[0]; }); expression.addContextFunction("schedule", -1, (c, t, lv) -> { - if (lv.size()<2) + if (lv.size() < 2) + { throw new InternalExpressionException("'schedule' should have at least 2 arguments, delay and call name"); - long delay = NumericValue.asNumber(lv.get(0)).getLong(); + } + final long delay = NumericValue.asNumber(lv.get(0)).getLong(); - FunctionArgument functionArgument = FunctionArgument.findIn(c, expression.module, lv, 1, false, false); + final FunctionArgument functionArgument = FunctionArgument.findIn(c, expression.module, lv, 1, false, false); CarpetServer.scriptServer.events.scheduleCall( (CarpetContext) c, functionArgument.function, @@ -805,103 +907,99 @@ else if (!interactable && targetBlock == null) expression.addImpureFunction("logger", lv -> { - Value res; + final Value res; - if(lv.size()==1) + if (lv.size() == 1) { res = lv.get(0); CarpetScriptServer.LOG.info(res.getString()); } - else if(lv.size()==2) + else if (lv.size() == 2) { - String level = lv.get(0).getString().toLowerCase(Locale.ROOT); + final String level = lv.get(0).getString().toLowerCase(Locale.ROOT); res = lv.get(1); - switch(level){ - case "debug": CarpetScriptServer.LOG.debug(res.getString()); break; - case "warn": CarpetScriptServer.LOG.warn(res.getString()); break; - case "info": CarpetScriptServer.LOG.info(res.getString()); break; - case "fatal": - // Somehow issue deprecation - case "error": - CarpetScriptServer.LOG.error(res.getString()); - break; - default: throw new InternalExpressionException("Unknown log level for 'logger': "+level); + switch (level) + { + case "debug" -> CarpetScriptServer.LOG.debug(res.getString()); + case "warn" -> CarpetScriptServer.LOG.warn(res.getString()); + case "info" -> CarpetScriptServer.LOG.info(res.getString()); + // Somehow issue deprecation + case "fatal", "error" -> CarpetScriptServer.LOG.error(res.getString()); + default -> throw new InternalExpressionException("Unknown log level for 'logger': " + level); } } - else throw new InternalExpressionException("logger takes 1 or 2 arguments"); + else + { + throw new InternalExpressionException("logger takes 1 or 2 arguments"); + } return res; // pass through for variables }); expression.addContextFunction("list_files", 2, (c, t, lv) -> { - FileArgument fdesc = FileArgument.from(lv,true, FileArgument.Reason.READ); - Stream files = ((CarpetScriptHost) c.host).listFolder(fdesc); - if (files == null) return Value.NULL; - return ListValue.wrap(files.map(StringValue::of)); + final FileArgument fdesc = FileArgument.from(lv, true, FileArgument.Reason.READ); + final Stream files = ((CarpetScriptHost) c.host).listFolder(fdesc); + return files == null ? Value.NULL : ListValue.wrap(files.map(StringValue::of)); }); expression.addContextFunction("read_file", 2, (c, t, lv) -> { - FileArgument fdesc = FileArgument.from(lv,false, FileArgument.Reason.READ); - Value retVal; + final FileArgument fdesc = FileArgument.from(lv, false, FileArgument.Reason.READ); if (fdesc.type == FileArgument.Type.NBT) { - Tag state = ((CarpetScriptHost) c.host).readFileTag(fdesc); - if (state == null) return Value.NULL; - retVal = new NBTSerializableValue(state); + final Tag state = ((CarpetScriptHost) c.host).readFileTag(fdesc); + return state == null ? Value.NULL : new NBTSerializableValue(state); } else if (fdesc.type == FileArgument.Type.JSON) { - JsonElement json; + final JsonElement json; json = ((CarpetScriptHost) c.host).readJsonFile(fdesc); - Value parsedJson = GSON.fromJson(json, Value.class); - if (parsedJson == null) - retVal = Value.NULL; - else - retVal = parsedJson; + final Value parsedJson = GSON.fromJson(json, Value.class); + return parsedJson == null ? Value.NULL : parsedJson; } else { - List content = ((CarpetScriptHost) c.host).readTextResource(fdesc); - if (content == null) return Value.NULL; - retVal = ListValue.wrap(content.stream().map(StringValue::new)); + final List content = ((CarpetScriptHost) c.host).readTextResource(fdesc); + return content == null ? Value.NULL : ListValue.wrap(content.stream().map(StringValue::new)); } - return retVal; }); expression.addContextFunction("delete_file", 2, (c, t, lv) -> - BooleanValue.of(((CarpetScriptHost) c.host).removeResourceFile(FileArgument.from(lv,false, FileArgument.Reason.DELETE)))); + BooleanValue.of(((CarpetScriptHost) c.host).removeResourceFile(FileArgument.from(lv, false, FileArgument.Reason.DELETE)))); expression.addContextFunction("write_file", -1, (c, t, lv) -> { - if (lv.size() < 3) throw new InternalExpressionException("'write_file' requires three or more arguments"); - FileArgument fdesc = FileArgument.from(lv, false, FileArgument.Reason.CREATE); + if (lv.size() < 3) + { + throw new InternalExpressionException("'write_file' requires three or more arguments"); + } + final FileArgument fdesc = FileArgument.from(lv, false, FileArgument.Reason.CREATE); - boolean success; + final boolean success; if (fdesc.type == FileArgument.Type.NBT) { - Value val = lv.get(2); - NBTSerializableValue tagValue = (val instanceof NBTSerializableValue) - ? (NBTSerializableValue) val + final Value val = lv.get(2); + final NBTSerializableValue tagValue = (val instanceof final NBTSerializableValue nbtsv) + ? nbtsv : new NBTSerializableValue(val.getString()); - Tag tag = tagValue.getTag(); + final Tag tag = tagValue.getTag(); success = ((CarpetScriptHost) c.host).writeTagFile(tag, fdesc); } else if (fdesc.type == FileArgument.Type.JSON) { - List data = Collections.singletonList(GSON.toJson(lv.get(2).toJson())); + final List data = Collections.singletonList(GSON.toJson(lv.get(2).toJson())); ((CarpetScriptHost) c.host).removeResourceFile(fdesc); success = ((CarpetScriptHost) c.host).appendLogFile(fdesc, data); } else { - List data = new ArrayList<>(); - if (lv.size()==3) + final List data = new ArrayList<>(); + if (lv.size() == 3) { - Value val = lv.get(2); - if (val instanceof ListValue) + final Value val = lv.get(2); + if (val instanceof final ListValue list) { - List lval = ((ListValue) val).getItems(); + final List lval = list.getItems(); lval.forEach(v -> data.add(v.getString())); } else @@ -911,7 +1009,7 @@ else if (fdesc.type == FileArgument.Type.JSON) } else { - for(int i = 2; i < lv.size(); i++) + for (int i = 2; i < lv.size(); i++) { data.add(lv.get(i).getString()); } @@ -924,11 +1022,11 @@ else if (fdesc.type == FileArgument.Type.JSON) expression.addContextFunction("load_app_data", -1, (c, t, lv) -> { FileArgument fdesc = new FileArgument(null, FileArgument.Type.NBT, null, false, false, FileArgument.Reason.READ); - if (lv.size()>0) + if (lv.size() > 0) { c.host.issueDeprecation("load_app_data(...) with arguments"); - String resource = recognizeResource(lv.get(0), false); - boolean shared = lv.size() > 1 && lv.get(1).getBoolean(); + final String resource = recognizeResource(lv.get(0), false); + final boolean shared = lv.size() > 1 && lv.get(1).getBoolean(); fdesc = new FileArgument(resource, FileArgument.Type.NBT, null, false, shared, FileArgument.Reason.READ); } return NBTSerializableValue.of(((CarpetScriptHost) c.host).readFileTag(fdesc)); @@ -937,35 +1035,46 @@ else if (fdesc.type == FileArgument.Type.JSON) expression.addContextFunction("store_app_data", -1, (c, t, lv) -> { if (lv.size() == 0) + { throw new InternalExpressionException("'store_app_data' needs NBT tag and an optional file"); - Value val = lv.get(0); + } + final Value val = lv.get(0); FileArgument fdesc = new FileArgument(null, FileArgument.Type.NBT, null, false, false, FileArgument.Reason.CREATE); - if (lv.size()>1) + if (lv.size() > 1) { c.host.issueDeprecation("store_app_data(...) with more than one argument"); - String resource = recognizeResource(lv.get(1), false); - boolean shared = lv.size() > 2 && lv.get(2).getBoolean(); + final String resource = recognizeResource(lv.get(1), false); + final boolean shared = lv.size() > 2 && lv.get(2).getBoolean(); fdesc = new FileArgument(resource, FileArgument.Type.NBT, null, false, shared, FileArgument.Reason.CREATE); } - NBTSerializableValue tagValue = (val instanceof NBTSerializableValue) - ? (NBTSerializableValue) val + final NBTSerializableValue tagValue = (val instanceof final NBTSerializableValue nbtsv) + ? nbtsv : new NBTSerializableValue(val.getString()); return BooleanValue.of(((CarpetScriptHost) c.host).writeTagFile(tagValue.getTag(), fdesc)); }); expression.addContextFunction("statistic", 3, (c, t, lv) -> { - CarpetContext cc = (CarpetContext)c; - ServerPlayer player = EntityValue.getPlayerByValue(cc.server(), lv.get(0)); - if (player == null) return Value.NULL; - ResourceLocation category; - ResourceLocation statName; + final CarpetContext cc = (CarpetContext) c; + final ServerPlayer player = EntityValue.getPlayerByValue(cc.server(), lv.get(0)); + if (player == null) + { + return Value.NULL; + } + final ResourceLocation category; + final ResourceLocation statName; category = InputValidator.identifierOf(lv.get(1).getString()); statName = InputValidator.identifierOf(lv.get(2).getString()); - StatType type = cc.registry(Registries.STAT_TYPE).get(category); - if (type == null) return Value.NULL; - Stat stat = getStat(type, statName); - if (stat == null) return Value.NULL; + final StatType type = cc.registry(Registries.STAT_TYPE).get(category); + if (type == null) + { + return Value.NULL; + } + final Stat stat = getStat(type, statName); + if (stat == null) + { + return Value.NULL; + } return new NumericValue(player.getStats().getValue(stat)); }); @@ -973,34 +1082,49 @@ else if (fdesc.type == FileArgument.Type.JSON) expression.addContextFunction("handle_event", -1, (c, t, lv) -> { if (lv.size() < 2) + { throw new InternalExpressionException("'handle_event' requires at least two arguments, event name, and a callback"); - String event = lv.get(0).getString(); - FunctionArgument callback = FunctionArgument.findIn(c, expression.module, lv, 1, true, false); - CarpetScriptHost host = ((CarpetScriptHost)c.host); + } + final String event = lv.get(0).getString(); + final FunctionArgument callback = FunctionArgument.findIn(c, expression.module, lv, 1, true, false); + final CarpetScriptHost host = ((CarpetScriptHost) c.host); if (callback.function == null) + { return BooleanValue.of(host.scriptServer().events.removeBuiltInEvent(event, host)); + } // args don't need to be checked will be checked at the event - return BooleanValue.of( host.scriptServer().events.handleCustomEvent(event, host, callback.function, callback.args )); + return BooleanValue.of(host.scriptServer().events.handleCustomEvent(event, host, callback.function, callback.args)); }); //signal_event('event', player or null, args.... ) -> number of apps notified expression.addContextFunction("signal_event", -1, (c, t, lv) -> { if (lv.size() == 0) + { throw new InternalExpressionException("'signal' requires at least one argument"); - CarpetContext cc = (CarpetContext)c; - CarpetScriptServer server = ((CarpetScriptHost)c.host).scriptServer(); - String eventName = lv.get(0).getString(); + } + final CarpetContext cc = (CarpetContext) c; + final CarpetScriptServer server = ((CarpetScriptHost) c.host).scriptServer(); + final String eventName = lv.get(0).getString(); // no such event yet - if (CarpetEventServer.Event.getEvent(eventName, server) == null) return Value.NULL; + if (CarpetEventServer.Event.getEvent(eventName, server) == null) + { + return Value.NULL; + } ServerPlayer player = null; List args = Collections.emptyList(); if (lv.size() > 1) { player = EntityValue.getPlayerByValue(server.server, lv.get(1)); - if (lv.size() > 2) args = lv.subList(2, lv.size()); + if (lv.size() > 2) + { + args = lv.subList(2, lv.size()); + } + } + final int counts = ((CarpetScriptHost) c.host).scriptServer().events.signalEvent(eventName, cc, player, args); + if (counts < 0) + { + return Value.NULL; } - int counts = ((CarpetScriptHost)c.host).scriptServer().events.signalEvent(eventName, cc, player, args); - if (counts < 0) return Value.NULL; return new NumericValue(counts); }); @@ -1008,16 +1132,23 @@ else if (fdesc.type == FileArgument.Type.JSON) // nbt_storage(key) // nbt_storage(key, nbt) 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; - CommandStorage storage = cc.server().getCommandStorage(); + if (lv.size() > 2) + { + throw new InternalExpressionException("'nbt_storage' requires 0, 1 or 2 arguments."); + } + final CarpetContext cc = (CarpetContext) c; + final CommandStorage storage = cc.server().getCommandStorage(); if (lv.size() == 0) + { return ListValue.wrap(storage.keys().map(i -> new StringValue(nameFromRegistryId(i)))); - String key = lv.get(0).getString(); - 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 + } + final String key = lv.get(0).getString(); + final CompoundTag old_nbt = storage.get(InputValidator.identifierOf(key)); + if (lv.size() == 2) + { + final Value nbt = lv.get(1); + final NBTSerializableValue new_nbt = (nbt instanceof final NBTSerializableValue nbtsv) + ? nbtsv : NBTSerializableValue.parseString(nbt.getString(), true); storage.set(InputValidator.identifierOf(key), new_nbt.getCompoundTag()); } @@ -1026,31 +1157,39 @@ else if (fdesc.type == FileArgument.Type.JSON) // script run create_datapack('foo', {'foo' -> {'bar.json' -> {'c' -> true,'d' -> false,'e' -> {'foo' -> [1,2,3]},'a' -> 'foobar','b' -> 5}}}) expression.addContextFunction("create_datapack", 2, (c, t, lv) -> { - CarpetContext cc = (CarpetContext)c; - String origName = lv.get(0).getString(); - String name = InputValidator.validateSimpleString(origName, true); - MinecraftServer server = cc.server(); - for (String dpName : server.getPackRepository().getAvailableIds()) - { - if (dpName.equalsIgnoreCase("file/"+name+".zip") || - dpName.equalsIgnoreCase("file/"+name)) + final CarpetContext cc = (CarpetContext) c; + final String origName = lv.get(0).getString(); + final String name = InputValidator.validateSimpleString(origName, true); + final MinecraftServer server = cc.server(); + for (final String dpName : server.getPackRepository().getAvailableIds()) + { + if (dpName.equalsIgnoreCase("file/" + name + ".zip") || + dpName.equalsIgnoreCase("file/" + name)) + { return Value.NULL; + } } - Value dpdata = lv.get(1); - if (!(dpdata instanceof MapValue)) + final Value dpdata = lv.get(1); + if (!(dpdata instanceof final MapValue dpMap)) + { throw new InternalExpressionException("datapack data needs to be a valid map type"); - 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.executeBlocking( () -> - { - try { - //Files.createDirectory(packFloder); - try (FileSystem zipfs = FileSystems.newFileSystem(URI.create("jar:" + packFloder.toUri().toString()), Map.of("create", "true"))) { - Path zipRoot = zipfs.getPath("/"); + } + final PackRepository packManager = server.getPackRepository(); + final Path dbFloder = server.getWorldPath(LevelResource.DATAPACK_DIR); + final Path packFloder = dbFloder.resolve(name + ".zip"); + if (Files.exists(packFloder) || Files.exists(dbFloder.resolve(name))) + { + return Value.NULL; + } + final Boolean[] successful = new Boolean[]{true}; + server.executeBlocking(() -> + { + try + { + try (final FileSystem zipfs = FileSystems.newFileSystem(URI.create("jar:" + packFloder.toUri().toString()), Map.of("create", "true"))) + { + final 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.getCurrentVersion().getPackVersion(PackType.SERVER_DATA)), @@ -1058,14 +1197,15 @@ else if (fdesc.type == FileArgument.Type.JSON) StringValue.of("source"), StringValue.of("scarpet") ))) )); - walkTheDPMap((MapValue) dpdata, zipRoot); + walkTheDPMap(dpMap, zipRoot); } packManager.reload(); - Pack resourcePackProfile = packManager.getPack("file/" + name + ".zip"); - if (resourcePackProfile == null || packManager.getSelectedPacks().contains(resourcePackProfile)) { + final Pack resourcePackProfile = packManager.getPack("file/" + name + ".zip"); + if (resourcePackProfile == null || packManager.getSelectedPacks().contains(resourcePackProfile)) + { throw new IOException(); } - List list = Lists.newArrayList(packManager.getSelectedPacks()); + final List list = Lists.newArrayList(packManager.getSelectedPacks()); resourcePackProfile.getDefaultPosition().insert(list, resourcePackProfile, p -> p, false); @@ -1074,15 +1214,20 @@ else if (fdesc.type == FileArgument.Type.JSON) successful[0] = false; return null; }).join(); - if (!successful[0]) { + if (!successful[0]) + { throw new IOException(); } - } catch (IOException e) + } + catch (final IOException e) { successful[0] = false; - try { + try + { PathUtils.delete(packFloder); - } catch (IOException ignored) { + } + catch (final IOException ignored) + { throw new InternalExpressionException("Failed to install a datapack and failed to clean up after it"); } @@ -1092,145 +1237,165 @@ else if (fdesc.type == FileArgument.Type.JSON) }); expression.addContextFunction("enable_hidden_dimensions", 0, (c, t, lv) -> { - CarpetContext cc = (CarpetContext)c; - cc.host.issueDeprecation("enable_hidden_dimensions in 1.18.2 and 1.19"); + final CarpetContext cc = (CarpetContext) c; + cc.host.issueDeprecation("enable_hidden_dimensions in 1.18.2 and 1.19+"); return Value.NULL; }); } - private static void zipValueToJson(Path path, Value output) throws IOException + private static void zipValueToJson(final Path path, final Value output) throws IOException { - JsonElement element = output.toJson(); + final JsonElement element = output.toJson(); if (element == null) - throw new InternalExpressionException("Cannot interpret "+output.getPrettyString()+" as a json object"); - String string = GSON.toJson(element); + { + throw new InternalExpressionException("Cannot interpret " + output.getPrettyString() + " as a json object"); + } + final String string = GSON.toJson(element); Files.createDirectories(path.getParent()); - BufferedWriter bufferedWriter = Files.newBufferedWriter(path); + final BufferedWriter bufferedWriter = Files.newBufferedWriter(path); Throwable incident = null; try { bufferedWriter.write(string); } - catch (Throwable shitHappened) + catch (final Throwable shitHappened) { incident = shitHappened; throw shitHappened; } finally { - if (incident != null) { - try { + if (incident != null) + { + try + { bufferedWriter.close(); - } catch (Throwable otherShitHappened) { + } + catch (final Throwable otherShitHappened) + { incident.addSuppressed(otherShitHappened); } - } else { + } + else + { bufferedWriter.close(); } } } - private static void zipValueToText(Path path, Value output) throws IOException + + private static void zipValueToText(final Path path, final Value output) throws IOException { - List toJoin; - String string; - String delimiter=System.lineSeparator(); + final List toJoin; + final String string; + final String delimiter = System.lineSeparator(); // i dont know it shoule be \n or System.lineSeparator - if (output instanceof LazyListValue) + if (output instanceof LazyListValue lazyListValue) { - toJoin = ((LazyListValue) output).unroll(); + toJoin = lazyListValue.unroll(); string = toJoin.stream().map(Value::getString).collect(Collectors.joining(delimiter)); } - else if (output instanceof ListValue) + else if (output instanceof ListValue listValue) { - toJoin = ((ListValue) output).getItems(); + toJoin = listValue.getItems(); string = toJoin.stream().map(Value::getString).collect(Collectors.joining(delimiter)); } else { string = output.getString(); } - - + + Files.createDirectories(path.getParent()); - BufferedWriter bufferedWriter = Files.newBufferedWriter(path); + final BufferedWriter bufferedWriter = Files.newBufferedWriter(path); Throwable incident = null; try { bufferedWriter.write(string); } - catch (Throwable shitHappened) + catch (final Throwable shitHappened) { incident = shitHappened; throw shitHappened; } finally { - if (incident != null) { - try { + if (incident != null) + { + try + { bufferedWriter.close(); - } catch (Throwable otherShitHappened) { + } + catch (final Throwable otherShitHappened) + { incident.addSuppressed(otherShitHappened); } - } else { + } + else + { bufferedWriter.close(); } } } - private static void zipValueToNBT(Path path, Value output) throws IOException + private static void zipValueToNBT(final Path path, final Value output) throws IOException { - - - NBTSerializableValue tagValue = (output instanceof NBTSerializableValue) - ? (NBTSerializableValue) output - : new NBTSerializableValue(output.getString()); - Tag tag = tagValue.getTag(); + final NBTSerializableValue tagValue = (output instanceof NBTSerializableValue nbtSerializableValue) + ? nbtSerializableValue + : new NBTSerializableValue(output.getString()); + final Tag tag = tagValue.getTag(); Files.createDirectories(path.getParent()); - - try { - if (tag instanceof CompoundTag) - NbtIo.writeCompressed((CompoundTag) tag, Files.newOutputStream(path)); + if (tag instanceof final CompoundTag cTag) + { + NbtIo.writeCompressed(cTag, Files.newOutputStream(path)); + } } - catch (Throwable shitHappened) + catch (final Throwable shitHappened) { throw shitHappened; } } - private static void walkTheDPMap(MapValue node, Path path) throws IOException + private static void walkTheDPMap(final MapValue node, final Path path) throws IOException { - Map items = node.getMap(); - for (Map.Entry entry : items.entrySet()) + final Map items = node.getMap(); + for (final Map.Entry entry : items.entrySet()) { - Value val = entry.getValue(); - String strkey = entry.getKey().getString(); - Path child = path.resolve(strkey); + final Value val = entry.getValue(); + final String strkey = entry.getKey().getString(); + final Path child = path.resolve(strkey); if (strkey.endsWith(".json")) { zipValueToJson(child, val); } - else if (strkey.endsWith(".mcfunction")|strkey.endsWith(".txt")|strkey.endsWith(".mcmeta")) + else if (strkey.endsWith(".mcfunction") || strkey.endsWith(".txt") || strkey.endsWith(".mcmeta")) { zipValueToText(child, val); - }else if (strkey.endsWith(".nbt")) + } + else if (strkey.endsWith(".nbt")) { zipValueToNBT(child, val); - }else + } + else { - if (!(val instanceof MapValue)) throw new InternalExpressionException("Value of "+strkey+" should be a map"); + if (!(val instanceof final MapValue map)) + { + throw new InternalExpressionException("Value of " + strkey + " should be a map"); + } Files.createDirectory(child); - walkTheDPMap((MapValue) val, child); + walkTheDPMap(map, child); } } } - private static Stat getStat(StatType type, ResourceLocation id) + private static Stat getStat(final StatType type, final ResourceLocation id) { - T key = type.getRegistry().get(id); + final T key = type.getRegistry().get(id); if (key == null || !type.contains(key)) + { return null; + } return type.get(key); } } diff --git a/src/main/java/carpet/script/api/BlockIterators.java b/src/main/java/carpet/script/api/BlockIterators.java index d5ee8ac6b7..e171632973 100644 --- a/src/main/java/carpet/script/api/BlockIterators.java +++ b/src/main/java/carpet/script/api/BlockIterators.java @@ -15,9 +15,11 @@ import carpet.script.value.ListValue; import carpet.script.value.NumericValue; import carpet.script.value.Value; + 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; @@ -27,19 +29,23 @@ import static java.lang.Math.max; import static java.lang.Math.min; -public class BlockIterators { - public static void apply(Expression expression) +public class BlockIterators +{ + public static void apply(final Expression expression) { // lazy cause of lazy expression expression.addLazyFunction("scan", (c, t, llv) -> { - if (llv.size() < 3) throw new InternalExpressionException("'scan' needs many more arguments"); - List lv = Fluff.AbstractFunction.unpackLazy(llv.subList(0, llv.size()-1), c, Context.NONE); - CarpetContext cc = (CarpetContext)c; - BlockArgument centerLocator = BlockArgument.findIn(cc, lv, 0); + if (llv.size() < 3) + { + throw new InternalExpressionException("'scan' needs many more arguments"); + } + final List lv = Fluff.AbstractFunction.unpackLazy(llv.subList(0, llv.size() - 1), c, Context.NONE); + final CarpetContext cc = (CarpetContext) c; + final BlockArgument centerLocator = BlockArgument.findIn(cc, lv, 0); Vector3Argument rangeLocator = Vector3Argument.findIn(lv, centerLocator.offset); - BlockPos center = centerLocator.block.getPos(); - Vec3i range; + final BlockPos center = centerLocator.block.getPos(); + final Vec3i range; if (rangeLocator.fromBlock) { @@ -48,14 +54,13 @@ public static void apply(Expression expression) abs(rangeLocator.vec.y - center.getY()), abs(rangeLocator.vec.z - center.getZ()) ); - //if (lv.size() > rangeLocator.offset+1) throw new InternalExpressionException("'scan' takes two block positions, and the expression") } else { range = new Vec3i(abs(rangeLocator.vec.x), abs(rangeLocator.vec.y), abs(rangeLocator.vec.z)); } Vec3i upperRange = range; - if (lv.size() > rangeLocator.offset+1) // +1 cause we still need the expression + if (lv.size() > rangeLocator.offset + 1) // +1 cause we still need the expression { rangeLocator = Vector3Argument.findIn(lv, rangeLocator.offset); if (rangeLocator.fromBlock) @@ -65,60 +70,60 @@ public static void apply(Expression expression) abs(rangeLocator.vec.y - center.getY()), abs(rangeLocator.vec.z - center.getZ()) ); - //if (lv.size() > rangeLocator.offset+1) throw new InternalExpressionException("'scan' takes two block positions, and the expression") } else { upperRange = new Vec3i(abs(rangeLocator.vec.x), abs(rangeLocator.vec.y), abs(rangeLocator.vec.z)); } } - if (llv.size() != rangeLocator.offset+1) + if (llv.size() != rangeLocator.offset + 1) { - throw new InternalExpressionException("'scan' takes two, or three block positions, and an expression: "+lv.size()+" "+rangeLocator.offset); + throw new InternalExpressionException("'scan' takes two, or three block positions, and an expression: " + lv.size() + " " + rangeLocator.offset); } - LazyValue expr = llv.get(rangeLocator.offset); - - int cx = center.getX(); - int cy = center.getY(); - int cz = center.getZ(); - int xrange = range.getX(); - int yrange = range.getY(); - int zrange = range.getZ(); - int xprange = upperRange.getX(); - int yprange = upperRange.getY(); - int zprange = upperRange.getZ(); + final LazyValue expr = llv.get(rangeLocator.offset); + + final int cx = center.getX(); + final int cy = center.getY(); + final int cz = center.getZ(); + final int xrange = range.getX(); + final int yrange = range.getY(); + final int zrange = range.getZ(); + final int xprange = upperRange.getX(); + final int yprange = upperRange.getY(); + final int zprange = upperRange.getZ(); //saving outer scope - LazyValue _x = c.getVariable("_x"); - LazyValue _y = c.getVariable("_y"); - LazyValue _z = c.getVariable("_z"); - LazyValue __ = c.getVariable("_"); + final LazyValue _x = c.getVariable("_x"); + final LazyValue _y = c.getVariable("_y"); + final LazyValue _z = c.getVariable("_z"); + final LazyValue __ = c.getVariable("_"); int sCount = 0; - outer:for (int y=cy-yrange; y <= cy+yprange; y++) + outer: + for (int y = cy - yrange; y <= cy + yprange; y++) { - int yFinal = y; + final int yFinal = y; c.setVariable("_y", (c_, t_) -> new NumericValue(yFinal).bindTo("_y")); - for (int x=cx-xrange; x <= cx+xprange; x++) + for (int x = cx - xrange; x <= cx + xprange; x++) { - int xFinal = x; + final int xFinal = x; c.setVariable("_x", (c_, t_) -> new NumericValue(xFinal).bindTo("_x")); - for (int z=cz-zrange; z <= cz+zprange; z++) + for (int z = cz - zrange; z <= cz + zprange; z++) { - int zFinal = z; + final int zFinal = z; c.setVariable("_z", (c_, t_) -> new NumericValue(zFinal).bindTo("_z")); - Value blockValue = BlockValue.fromCoords(((CarpetContext)c), xFinal,yFinal,zFinal).bindTo("_"); - c.setVariable( "_", (cc_, t_c) -> blockValue); + final Value blockValue = BlockValue.fromCoords(((CarpetContext) c), xFinal, yFinal, zFinal).bindTo("_"); + c.setVariable("_", (cc_, t_c) -> blockValue); Value result; try { result = expr.evalValue(c, t); } - catch (ContinueStatement notIgnored) + catch (final ContinueStatement notIgnored) { result = notIgnored.retval; } - catch (BreakStatement notIgnored) + catch (final BreakStatement notIgnored) { break outer; } @@ -134,66 +139,70 @@ public static void apply(Expression expression) c.setVariable("_y", _y); c.setVariable("_z", _z); c.setVariable("_", __); - int finalSCount = sCount; + final int finalSCount = sCount; return (c_, t_) -> new NumericValue(finalSCount); }); // must be lazy expression.addLazyFunction("volume", (c, t, llv) -> { - CarpetContext cc = (CarpetContext)c; - if (llv.size() < 3) throw new InternalExpressionException("'volume' needs many more arguments"); - List lv = Fluff.AbstractFunction.unpackLazy(llv.subList(0, llv.size()-1), c, Context.NONE); - - BlockArgument pos1Locator = BlockArgument.findIn(cc, lv, 0); - BlockArgument pos2Locator = BlockArgument.findIn(cc, lv, pos1Locator.offset); - BlockPos pos1 = pos1Locator.block.getPos(); - BlockPos pos2 = pos2Locator.block.getPos(); - - int x1 = pos1.getX(); - int y1 = pos1.getY(); - int z1 = pos1.getZ(); - int x2 = pos2.getX(); - int y2 = pos2.getY(); - int z2 = pos2.getZ(); - int minx = min(x1, x2); - int miny = min(y1, y2); - int minz = min(z1, z2); - int maxx = max(x1, x2); - int maxy = max(y1, y2); - int maxz = max(z1, z2); - LazyValue expr = llv.get(pos2Locator.offset); + final CarpetContext cc = (CarpetContext) c; + if (llv.size() < 3) + { + throw new InternalExpressionException("'volume' needs many more arguments"); + } + final List lv = Fluff.AbstractFunction.unpackLazy(llv.subList(0, llv.size() - 1), c, Context.NONE); + + final BlockArgument pos1Locator = BlockArgument.findIn(cc, lv, 0); + final BlockArgument pos2Locator = BlockArgument.findIn(cc, lv, pos1Locator.offset); + final BlockPos pos1 = pos1Locator.block.getPos(); + final BlockPos pos2 = pos2Locator.block.getPos(); + + final int x1 = pos1.getX(); + final int y1 = pos1.getY(); + final int z1 = pos1.getZ(); + final int x2 = pos2.getX(); + final int y2 = pos2.getY(); + final int z2 = pos2.getZ(); + final int minx = min(x1, x2); + final int miny = min(y1, y2); + final int minz = min(z1, z2); + final int maxx = max(x1, x2); + final int maxy = max(y1, y2); + final int maxz = max(z1, z2); + final LazyValue expr = llv.get(pos2Locator.offset); //saving outer scope - LazyValue _x = c.getVariable("_x"); - LazyValue _y = c.getVariable("_y"); - LazyValue _z = c.getVariable("_z"); - LazyValue __ = c.getVariable("_"); + final LazyValue _x = c.getVariable("_x"); + final LazyValue _y = c.getVariable("_y"); + final LazyValue _z = c.getVariable("_z"); + final LazyValue __ = c.getVariable("_"); int sCount = 0; - outer:for (int y=miny; y <= maxy; y++) + outer: + for (int y = miny; y <= maxy; y++) { - int yFinal = y; + final int yFinal = y; c.setVariable("_y", (c_, t_) -> new NumericValue(yFinal).bindTo("_y")); - for (int x=minx; x <= maxx; x++) + for (int x = minx; x <= maxx; x++) { - int xFinal = x; + final int xFinal = x; c.setVariable("_x", (c_, t_) -> new NumericValue(xFinal).bindTo("_x")); - for (int z=minz; z <= maxz; z++) + for (int z = minz; z <= maxz; z++) { - int zFinal = z; + final int zFinal = z; c.setVariable("_z", (c_, t_) -> new NumericValue(zFinal).bindTo("_z")); - Value blockValue = BlockValue.fromCoords(((CarpetContext)c), xFinal,yFinal,zFinal).bindTo("_"); - c.setVariable( "_", (cc_, t_c) -> blockValue); + final Value blockValue = BlockValue.fromCoords(((CarpetContext) c), xFinal, yFinal, zFinal).bindTo("_"); + c.setVariable("_", (cc_, t_c) -> blockValue); Value result; try { result = expr.evalValue(c, t); } - catch (ContinueStatement notIgnored) + catch (final ContinueStatement notIgnored) { result = notIgnored.retval; } - catch (BreakStatement notIgnored) + catch (final BreakStatement notIgnored) { break outer; } @@ -209,16 +218,16 @@ public static void apply(Expression expression) c.setVariable("_y", _y); c.setVariable("_z", _z); c.setVariable("_", __); - int finalSCount = sCount; + final int finalSCount = sCount; return (c_, t_) -> new NumericValue(finalSCount); }); - expression.addContextFunction("neighbours", -1, (c, t, lv)-> + expression.addContextFunction("neighbours", -1, (c, t, lv) -> { - BlockPos center = BlockArgument.findIn((CarpetContext) c, lv,0).block.getPos(); - ServerLevel world = ((CarpetContext) c).level(); + final BlockPos center = BlockArgument.findIn((CarpetContext) c, lv, 0).block.getPos(); + final ServerLevel world = ((CarpetContext) c).level(); - List neighbours = new ArrayList<>(); + final List neighbours = new ArrayList<>(); neighbours.add(new BlockValue(null, world, center.above())); neighbours.add(new BlockValue(null, world, center.below())); neighbours.add(new BlockValue(null, world, center.north())); @@ -228,20 +237,26 @@ public static void apply(Expression expression) return ListValue.wrap(neighbours); }); - expression.addContextFunction("rect", -1, (c, t, lv)-> + expression.addContextFunction("rect", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext) c; - int cx, cy, cz; - int sminx, sminy, sminz; - int smaxx, smaxy, smaxz; - BlockArgument cposLocator = BlockArgument.findIn(cc, lv, 0); - BlockPos cpos = cposLocator.block.getPos(); + final CarpetContext cc = (CarpetContext) c; + final int cx; + final int cy; + final int cz; + final int sminx; + final int sminy; + final int sminz; + final int smaxx; + final int smaxy; + final int smaxz; + final BlockArgument cposLocator = BlockArgument.findIn(cc, lv, 0); + final BlockPos cpos = cposLocator.block.getPos(); cx = cpos.getX(); cy = cpos.getY(); cz = cpos.getZ(); if (lv.size() > cposLocator.offset) { - Vector3Argument diffLocator = Vector3Argument.findIn(lv, cposLocator.offset); + final Vector3Argument diffLocator = Vector3Argument.findIn(lv, cposLocator.offset); if (diffLocator.fromBlock) { sminx = Mth.floor(abs(diffLocator.vec.x - cx)); @@ -256,7 +271,7 @@ public static void apply(Expression expression) } if (lv.size() > diffLocator.offset) { - Vector3Argument posDiff = Vector3Argument.findIn(lv, diffLocator.offset); + final Vector3Argument posDiff = Vector3Argument.findIn(lv, diffLocator.offset); if (posDiff.fromBlock) { smaxx = Mth.floor(abs(posDiff.vec.x - cx)); @@ -289,19 +304,21 @@ public static void apply(Expression expression) return new LazyListValue() { - final int minx = cx-sminx; - final int miny = cy-sminy; - final int minz = cz-sminz; - final int maxx = cx+smaxx; - final int maxy = cy+smaxy; - final int maxz = cz+smaxz; + final int minx = cx - sminx; + final int miny = cy - sminy; + final int minz = cz - sminz; + final int maxx = cx + smaxx; + final int maxy = cy + smaxy; + final int maxz = cz + smaxz; int x; int y; int z; + { reset(); } + @Override public boolean hasNext() { @@ -311,7 +328,7 @@ public boolean hasNext() @Override public Value next() { - Value r = BlockValue.fromCoords(cc, x,y,z); + final Value r = BlockValue.fromCoords(cc, x, y, z); //possibly reroll context x++; if (x > maxx) @@ -347,56 +364,57 @@ public void reset() @Override public String getString() { - return String.format(Locale.ROOT, "rect[(%d,%d,%d),..,(%d,%d,%d)]",minx, miny, minz, maxx, maxy, maxz); + return String.format(Locale.ROOT, "rect[(%d,%d,%d),..,(%d,%d,%d)]", minx, miny, minz, maxx, maxy, maxz); } }; }); - expression.addContextFunction("diamond", -1, (c, t, lv)-> + expression.addContextFunction("diamond", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext)c; + final CarpetContext cc = (CarpetContext) c; - BlockArgument cposLocator=BlockArgument.findIn((CarpetContext)c,lv,0); - BlockPos cpos = cposLocator.block.getPos(); + final BlockArgument cposLocator = BlockArgument.findIn((CarpetContext) c, lv, 0); + final BlockPos cpos = cposLocator.block.getPos(); - int cx; - int cy; - int cz; - int width; - int height; + final int cx; + final int cy; + final int cz; + final int width; + final int height; try { cx = cpos.getX(); cy = cpos.getY(); cz = cpos.getZ(); - if (lv.size()==cposLocator.offset) + if (lv.size() == cposLocator.offset) { - Value retval = ListValue.of( - BlockValue.fromCoords(cc, cx, cy-1, cz), + return ListValue.of( + BlockValue.fromCoords(cc, cx, cy - 1, cz), BlockValue.fromCoords(cc, cx, cy, cz), - BlockValue.fromCoords(cc, cx-1, cy, cz), - BlockValue.fromCoords(cc, cx, cy, cz-1), - BlockValue.fromCoords(cc, cx+1, cy, cz), - BlockValue.fromCoords(cc, cx, cy, cz+1), - BlockValue.fromCoords(cc, cx, cy+1, cz) + BlockValue.fromCoords(cc, cx - 1, cy, cz), + BlockValue.fromCoords(cc, cx, cy, cz - 1), + BlockValue.fromCoords(cc, cx + 1, cy, cz), + BlockValue.fromCoords(cc, cx, cy, cz + 1), + BlockValue.fromCoords(cc, cx, cy + 1, cz) ); - return retval; } - else if (lv.size()==1+cposLocator.offset) + else if (lv.size() == 1 + cposLocator.offset) { width = (int) ((NumericValue) lv.get(cposLocator.offset)).getLong(); height = 0; } - else if(lv.size()==2+cposLocator.offset) + else if (lv.size() == 2 + cposLocator.offset) { width = (int) ((NumericValue) lv.get(cposLocator.offset)).getLong(); - height = (int) ((NumericValue) lv.get(cposLocator.offset+1)).getLong(); - } else{ + height = (int) ((NumericValue) lv.get(cposLocator.offset + 1)).getLong(); + } + else + { throw new InternalExpressionException("Incorrect number of arguments for 'diamond'"); } } - catch (ClassCastException exc) + catch (final ClassCastException ignored) { throw new InternalExpressionException("Attempted to pass a non-number to 'diamond'"); } @@ -406,9 +424,11 @@ else if(lv.size()==2+cposLocator.offset) { int curradius; int curpos; + { reset(); } + @Override public boolean hasNext() { @@ -425,9 +445,9 @@ public Value next() } // x = 3-|i-6| // z = |( (i-3)%12-6|-3 - Value block = BlockValue.fromCoords(cc, cx+(curradius-abs(curpos-2*curradius)), cy, cz-curradius+abs( abs(curpos-curradius)%(4*curradius) -2*curradius )); + final Value block = BlockValue.fromCoords(cc, cx + (curradius - abs(curpos - 2 * curradius)), cy, cz - curradius + abs(abs(curpos - curradius) % (4 * curradius) - 2 * curradius)); curpos++; - if (curpos>=curradius*4) + if (curpos >= curradius * 4) { curradius++; curpos = 0; @@ -446,7 +466,7 @@ public void reset() @Override public String getString() { - return String.format(Locale.ROOT, "diamond[(%d,%d,%d),%d,0]",cx, cy, cz, width); + return String.format(Locale.ROOT, "diamond[(%d,%d,%d),%d,0]", cx, cy, cz, width); } }; } @@ -457,9 +477,11 @@ public String getString() int curradius; int curpos; int curheight; + { reset(); } + @Override public boolean hasNext() { @@ -471,27 +493,26 @@ public Value next() { if (curheight == -height || curheight == height) { - return BlockValue.fromCoords(cc, cx, cy+curheight++, cz); + return BlockValue.fromCoords(cc, cx, cy + curheight++, cz); } if (curradius == 0) { curradius++; - return BlockValue.fromCoords(cc, cx, cy+curheight, cz); + return BlockValue.fromCoords(cc, cx, cy + curheight, cz); } // x = 3-|i-6| // z = |( (i-3)%12-6|-3 - Value block = BlockValue.fromCoords(cc, cx+(curradius-abs(curpos-2*curradius)), cy+curheight, cz-curradius+abs( abs(curpos-curradius)%(4*curradius) -2*curradius )); + final Value block = BlockValue.fromCoords(cc, cx + (curradius - abs(curpos - 2 * curradius)), cy + curheight, cz - curradius + abs(abs(curpos - curradius) % (4 * curradius) - 2 * curradius)); curpos++; - if (curpos>=curradius*4) + if (curpos >= curradius * 4) { curradius++; curpos = 0; - if (curradius>width -abs(width*curheight/height)) + if (curradius > width - abs(width * curheight / height)) { curheight++; curradius = 0; - curpos = 0; } } return block; @@ -508,7 +529,7 @@ public void reset() @Override public String getString() { - return String.format(Locale.ROOT, "diamond[(%d,%d,%d),%d,%d]",cx, cy, cz, width, height); + return String.format(Locale.ROOT, "diamond[(%d,%d,%d),%d,%d]", cx, cy, cz, width, height); } }; } diff --git a/src/main/java/carpet/script/api/Entities.java b/src/main/java/carpet/script/api/Entities.java index 00b6036c25..ed917f2ef0 100644 --- a/src/main/java/carpet/script/api/Entities.java +++ b/src/main/java/carpet/script/api/Entities.java @@ -15,6 +15,7 @@ import carpet.script.value.Value; import com.mojang.brigadier.StringReader; import com.mojang.brigadier.exceptions.CommandSyntaxException; + import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; @@ -23,6 +24,7 @@ import java.util.Set; import java.util.UUID; import java.util.function.Predicate; + import net.minecraft.commands.CommandSourceStack; import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; @@ -38,159 +40,183 @@ import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.Vec3; -public class Entities { - private static ListValue getPlayersFromWorldMatching(Context c, Predicate condition) { - List ret = new ArrayList<>(); - for (ServerPlayer player: ((CarpetContext) c).level().players()) { - if (condition.test(player)) { +public class Entities +{ + private static ListValue getPlayersFromWorldMatching(final Context c, final Predicate condition) + { + final List ret = new ArrayList<>(); + for (final ServerPlayer player : ((CarpetContext) c).level().players()) + { + if (condition.test(player)) + { ret.add(new EntityValue(player)); } } return ListValue.wrap(ret); } - public static void apply(Expression expression) + public static void apply(final Expression expression) { expression.addContextFunction("player", -1, (c, t, lv) -> { if (lv.size() == 0) { - CarpetContext cc = (CarpetContext)c; + final CarpetContext cc = (CarpetContext) c; if (cc.host.user != null) { - ServerPlayer player = cc.server().getPlayerList().getPlayerByName(cc.host.user); + final ServerPlayer player = cc.server().getPlayerList().getPlayerByName(cc.host.user); return EntityValue.of(player); } - Entity callingEntity = cc.source().getEntity(); - if (callingEntity instanceof Player) return EntityValue.of(callingEntity); - Vec3 pos = ((CarpetContext)c).source().getPosition(); - Player closestPlayer = ((CarpetContext)c).level().getNearestPlayer(pos.x, pos.y, pos.z, -1.0, EntitySelector.ENTITY_STILL_ALIVE); + final Entity callingEntity = cc.source().getEntity(); + if (callingEntity instanceof Player) + { + return EntityValue.of(callingEntity); + } + final Vec3 pos = ((CarpetContext) c).source().getPosition(); + final Player closestPlayer = ((CarpetContext) c).level().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 ret = new ArrayList<>(); - for (ServerPlayer player: ((CarpetContext)c).server().getPlayerList().getPlayers()) - ret.add(new EntityValue(player)); - yield ListValue.wrap(ret); - } - case "*" -> getPlayersFromWorldMatching(c, p -> true); - 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 -> { - ServerPlayer player = ((CarpetContext) c).server().getPlayerList().getPlayerByName(playerName); - if (player != null) { - yield new EntityValue(player); - } - yield Value.NULL; - } - }; + final String playerName = lv.get(0).getString(); + return switch (playerName) + { + case "all" -> { + final List ret = new ArrayList<>(); + for (final ServerPlayer player : ((CarpetContext) c).server().getPlayerList().getPlayers()) + { + ret.add(new EntityValue(player)); + } + yield ListValue.wrap(ret); + } + case "*" -> getPlayersFromWorldMatching(c, p -> true); + 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 -> { + final ServerPlayer player = ((CarpetContext) c).server().getPlayerList().getPlayerByName(playerName); + yield player != null ? new EntityValue(player) : Value.NULL; + } + }; }); expression.addContextFunction("spawn", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext)c; + final CarpetContext cc = (CarpetContext) c; if (lv.size() < 2) + { throw new InternalExpressionException("'spawn' function takes mob name, and position to spawn"); - String entityString = lv.get(0).getString(); - ResourceLocation entityId; + } + final String entityString = lv.get(0).getString(); + final ResourceLocation entityId; try { entityId = ResourceLocation.read(new StringReader(entityString)); - EntityType type = cc.registry(Registries.ENTITY_TYPE).getOptional(entityId).orElse(null); + final EntityType type = cc.registry(Registries.ENTITY_TYPE).getOptional(entityId).orElse(null); if (type == null || !type.canSummon()) + { return Value.NULL; + } } - catch (CommandSyntaxException exception) + catch (final CommandSyntaxException ignored) { - return Value.NULL; + return Value.NULL; } - Vector3Argument position = Vector3Argument.findIn(lv, 1); + final Vector3Argument position = Vector3Argument.findIn(lv, 1); if (position.fromBlock) + { position.vec = position.vec.subtract(0, 0.5, 0); + } CompoundTag tag = new CompoundTag(); boolean hasTag = false; if (lv.size() > position.offset) { - Value nbt = lv.get(position.offset); - NBTSerializableValue v = (nbt instanceof NBTSerializableValue) ? (NBTSerializableValue) nbt + final Value nbt = lv.get(position.offset); + final NBTSerializableValue v = (nbt instanceof final NBTSerializableValue nbtsv) + ? nbtsv : NBTSerializableValue.parseString(nbt.getString(), true); hasTag = true; tag = v.getCompoundTag(); - } tag.putString("id", entityId.toString()); - Vec3 vec3d = position.vec; + final Vec3 vec3d = position.vec; - ServerLevel serverWorld = cc.level(); - 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; + final ServerLevel serverWorld = cc.level(); + final Entity entity = EntityType.loadEntityRecursive(tag, serverWorld, e -> { + e.moveTo(vec3d.x, vec3d.y, vec3d.z, e.getYRot(), e.getXRot()); + return !serverWorld.addWithUUID(e) ? null : e; }); - if (entity_1 == null) { + if (entity == null) + { return Value.NULL; - } else { - 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); } + if (!hasTag && entity instanceof final Mob mob) + { + mob.finalizeSpawn(serverWorld, serverWorld.getCurrentDifficultyAt(entity.blockPosition()), MobSpawnType.COMMAND, null, null); + } + return new EntityValue(entity); }); expression.addContextFunction("entity_id", 1, (c, t, lv) -> { - Value who = lv.get(0); - if (who instanceof NumericValue) - return EntityValue.of(((CarpetContext)c).level().getEntity((int)((NumericValue) who).getLong())); - return EntityValue.of(((CarpetContext)c).level().getEntity(UUID.fromString(who.getString()))); + final Value who = lv.get(0); + if (who instanceof final NumericValue numericValue) + { + return EntityValue.of(((CarpetContext) c).level().getEntity((int) numericValue.getLong())); + } + return EntityValue.of(((CarpetContext) c).level().getEntity(UUID.fromString(who.getString()))); }); expression.addContextFunction("entity_list", 1, (c, t, lv) -> { - String who = lv.get(0).getString(); - CommandSourceStack source = ((CarpetContext)c).source(); - EntityValue.EntityClassDescriptor eDesc = EntityValue.getEntityDescriptor(who, source.getServer()); - List entityList = source.getLevel().getEntities(eDesc.directType, eDesc.filteringPredicate); + final String who = lv.get(0).getString(); + final CommandSourceStack source = ((CarpetContext) c).source(); + final EntityValue.EntityClassDescriptor eDesc = EntityValue.getEntityDescriptor(who, source.getServer()); + final List entityList = source.getLevel().getEntities(eDesc.directType, eDesc.filteringPredicate); return ListValue.wrap(entityList.stream().map(EntityValue::new)); }); expression.addContextFunction("entity_area", -1, (c, t, lv) -> { - if (lv.size()<3) throw new InternalExpressionException("'entity_area' requires entity type, center and range arguments"); - String who = lv.get(0).getString(); - CarpetContext cc = (CarpetContext)c; - Vector3Argument centerLocator = Vector3Argument.findIn(lv, 1, false, true); + if (lv.size() < 3) + { + throw new InternalExpressionException("'entity_area' requires entity type, center and range arguments"); + } + final String who = lv.get(0).getString(); + final CarpetContext cc = (CarpetContext) c; + final Vector3Argument centerLocator = Vector3Argument.findIn(lv, 1, false, true); - AABB centerBox; + final AABB centerBox; if (centerLocator.entity != null) { centerBox = centerLocator.entity.getBoundingBox(); } else { - Vec3 center = centerLocator.vec; - if (centerLocator.fromBlock) center.add(0.5, 0.5, 0.5); + final Vec3 center = centerLocator.vec; + if (centerLocator.fromBlock) + { + center.add(0.5, 0.5, 0.5); + } centerBox = new AABB(center, center); } - Vector3Argument rangeLocator = Vector3Argument.findIn(lv, centerLocator.offset); + final Vector3Argument rangeLocator = Vector3Argument.findIn(lv, centerLocator.offset); if (rangeLocator.fromBlock) + { throw new InternalExpressionException("Range of 'entity_area' cannot come from a block argument"); - Vec3 range = rangeLocator.vec; - AABB area = centerBox.inflate(range.x, range.y, range.z); - EntityValue.EntityClassDescriptor eDesc = EntityValue.getEntityDescriptor(who, cc.server()); - List entityList = cc.level().getEntities(eDesc.directType, area,eDesc.filteringPredicate); + } + final Vec3 range = rangeLocator.vec; + final AABB area = centerBox.inflate(range.x, range.y, range.z); + final EntityValue.EntityClassDescriptor eDesc = EntityValue.getEntityDescriptor(who, cc.server()); + final List entityList = cc.level().getEntities(eDesc.directType, area, eDesc.filteringPredicate); return ListValue.wrap(entityList.stream().map(EntityValue::new)); }); expression.addContextFunction("entity_selector", -1, (c, t, lv) -> { - String selector = lv.get(0).getString(); - List retlist = new ArrayList<>(); - for (Entity e: EntityValue.getEntitiesFromSelector(((CarpetContext)c).source(), selector)) + final String selector = lv.get(0).getString(); + final List retlist = new ArrayList<>(); + for (final Entity e : EntityValue.getEntitiesFromSelector(((CarpetContext) c).source(), selector)) { retlist.add(new EntityValue(e)); } @@ -199,64 +225,74 @@ public static void apply(Expression expression) expression.addContextFunction("query", -1, (c, t, lv) -> { - if (lv.size()<2) + if (lv.size() < 2) { throw new InternalExpressionException("'query' takes entity as a first argument, and queried feature as a second"); } - Value v = lv.get(0); - if (!(v instanceof EntityValue)) + final Value v = lv.get(0); + if (!(v instanceof final EntityValue ev)) + { throw new InternalExpressionException("First argument to query should be an entity"); - String what = lv.get(1).getString().toLowerCase(Locale.ROOT); + } + final String what = lv.get(1).getString().toLowerCase(Locale.ROOT); if (what.equals("tags")) + { c.host.issueDeprecation("'tags' for entity querying"); - Value retval; - if (lv.size()==2) - retval = ((EntityValue) v).get(what, null); - else if (lv.size()==3) - retval = ((EntityValue) v).get(what, lv.get(2)); - else - retval = ((EntityValue) v).get(what, ListValue.wrap(lv.subList(2, lv.size()))); - return retval; + } + return switch (lv.size()) + { + case 2 -> ev.get(what, null); + case 3 -> ev.get(what, lv.get(2)); + default -> ev.get(what, ListValue.wrap(lv.subList(2, lv.size()))); + }; }); // or update expression.addContextFunction("modify", -1, (c, t, lv) -> { - if (lv.size()<2) + if (lv.size() < 2) { throw new InternalExpressionException("'modify' takes entity as a first argument, and queried feature as a second"); } - Value v = lv.get(0); - if (!(v instanceof EntityValue)) + final Value v = lv.get(0); + if (!(v instanceof final EntityValue ev)) + { throw new InternalExpressionException("First argument to modify should be an entity"); - String what = lv.get(1).getString(); - if (lv.size()==2) - ((EntityValue) v).set(what, null); - else if (lv.size()==3) - ((EntityValue) v).set(what, lv.get(2)); - else - ((EntityValue) v).set(what, ListValue.wrap(lv.subList(2, lv.size()))); + } + final String what = lv.get(1).getString(); + switch (lv.size()) + { + case 2 -> ev.set(what, null); + case 3 -> ev.set(what, lv.get(2)); + default -> ev.set(what, ListValue.wrap(lv.subList(2, lv.size()))); + } return v; }); expression.addContextFunction("entity_types", -1, (c, t, lv) -> { - if (lv.size() > 1) throw new InternalExpressionException("'entity_types' requires one or no arguments"); - String desc = (lv.size() == 1)?lv.get(0).getString():"*"; - return EntityValue.getEntityDescriptor(desc, ((CarpetContext) c).server()).listValue(((CarpetContext)c).registryAccess()); + if (lv.size() > 1) + { + throw new InternalExpressionException("'entity_types' requires one or no arguments"); + } + final String desc = (lv.size() == 1) ? lv.get(0).getString() : "*"; + return EntityValue.getEntityDescriptor(desc, ((CarpetContext) c).server()).listValue(((CarpetContext) c).registryAccess()); }); expression.addContextFunction("entity_load_handler", -1, (c, t, lv) -> { - if (lv.size() < 2) throw new InternalExpressionException("'entity_load_handler' required the entity type, and a function to call"); - Value entityValue = lv.get(0); - List descriptors = (entityValue instanceof ListValue) - ? ((ListValue) entityValue).getItems().stream().map(Value::getString).toList() + if (lv.size() < 2) + { + throw new InternalExpressionException("'entity_load_handler' required the entity type, and a function to call"); + } + final Value entityValue = lv.get(0); + final List descriptors = (entityValue instanceof final ListValue list) + ? list.getItems().stream().map(Value::getString).toList() : Collections.singletonList(entityValue.getString()); - Set> types = new HashSet<>(); + final Set> types = new HashSet<>(); descriptors.forEach(s -> types.addAll(EntityValue.getEntityDescriptor(s, ((CarpetContext) c).server()).types)); - FunctionArgument funArg = FunctionArgument.findIn(c, expression.module, lv, 1, true, false); - CarpetEventServer events = ((CarpetScriptHost)c.host).scriptServer().events; + final FunctionArgument funArg = FunctionArgument.findIn(c, expression.module, lv, 1, true, false); + final CarpetEventServer events = ((CarpetScriptHost) c.host).scriptServer().events; if (funArg.function == null) { types.forEach(et -> events.removeBuiltInEvent(CarpetEventServer.Event.getEntityLoadEventName(et), (CarpetScriptHost) c.host)); @@ -265,8 +301,8 @@ else if (lv.size()==3) else { ///compat - int argno = funArg.function.getArguments().size() - funArg.args.size(); - if (argno == 1) + final int numberOfArguments = funArg.function.getArguments().size() - funArg.args.size(); + if (numberOfArguments == 1) { c.host.issueDeprecation("entity_load_handler() with single argument callback"); types.forEach(et -> events.addBuiltInEvent(CarpetEventServer.Event.getEntityLoadEventName(et), c.host, funArg.function, funArg.args)); @@ -282,16 +318,20 @@ else if (lv.size()==3) // or update expression.addContextFunction("entity_event", -1, (c, t, lv) -> { - if (lv.size()<3) + if (lv.size() < 3) + { throw new InternalExpressionException("'entity_event' requires at least 3 arguments, entity, event to be handled, and function name, with optional arguments"); - Value v = lv.get(0); - if (!(v instanceof EntityValue)) + } + final Value v = lv.get(0); + if (!(v instanceof final EntityValue ev)) + { throw new InternalExpressionException("First argument to entity_event should be an entity"); - String what = lv.get(1).getString(); + } + final String what = lv.get(1).getString(); - FunctionArgument funArg = FunctionArgument.findIn(c, expression.module, lv, 2, true, false); + final FunctionArgument funArg = FunctionArgument.findIn(c, expression.module, lv, 2, true, false); - ((EntityValue) v).setEvent((CarpetContext)c, what, funArg.function, funArg.args); + ev.setEvent((CarpetContext) c, what, funArg.function, funArg.args); return Value.NULL; }); diff --git a/src/main/java/carpet/script/api/Inventories.java b/src/main/java/carpet/script/api/Inventories.java index 055f2ae2df..93450aea85 100644 --- a/src/main/java/carpet/script/api/Inventories.java +++ b/src/main/java/carpet/script/api/Inventories.java @@ -21,11 +21,13 @@ import carpet.script.value.Value; import carpet.script.value.ValueConversions; import com.mojang.brigadier.exceptions.CommandSyntaxException; + import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.Set; + import net.minecraft.commands.arguments.item.ItemInput; import net.minecraft.core.HolderSet; import net.minecraft.core.Registry; @@ -51,129 +53,110 @@ import net.minecraft.world.item.crafting.SingleItemRecipe; import net.minecraft.world.phys.Vec3; -public class Inventories { - public static void apply(Expression expression) +public class Inventories +{ + public static void apply(final Expression expression) { expression.addContextFunction("stack_limit", 1, (c, t, lv) -> - new NumericValue(NBTSerializableValue.parseItem(lv.get(0).getString(), ((CarpetContext) c).registryAccess() ).getItem().getMaxStackSize())); + new NumericValue(NBTSerializableValue.parseItem(lv.get(0).getString(), ((CarpetContext) c).registryAccess()).getItem().getMaxStackSize())); expression.addContextFunction("item_category", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext)c; - cc.host.issueDeprecation("item_category in 1.19.3+"); + c.host.issueDeprecation("item_category in 1.19.3+"); return Value.NULL; }); expression.addContextFunction("item_list", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext)c; - Registry items = cc.registry(Registries.ITEM); + final CarpetContext cc = (CarpetContext) c; + final Registry items = cc.registry(Registries.ITEM); if (lv.size() == 0) + { return ListValue.wrap(items.keySet().stream().map(ValueConversions::of)); - String tag = lv.get(0).getString(); - Optional> itemTag = items.getTag(TagKey.create(Registries.ITEM, InputValidator.identifierOf(tag))); - if (itemTag.isEmpty()) return Value.NULL; - return ListValue.wrap(itemTag.get().stream().map(b -> ValueConversions.of(items.getKey(b.value())))); - /* - TagContainer tagManager = cc.s.getServer(). getTags(); - String tag = lv.get(0).getString(); - net.minecraft.tags.Tag itemTag = tagManager.getOrEmpty(Registry.ITEM_REGISTRY).getTag(InputValidator.identifierOf(tag)); - if (itemTag == null) return Value.NULL; - return ListValue.wrap(itemTag.getValues().stream().map(b -> ValueConversions.of(Registry.ITEM.getKey(b)))); - */ + } + final String tag = lv.get(0).getString(); + final Optional> itemTag = items.getTag(TagKey.create(Registries.ITEM, InputValidator.identifierOf(tag))); + return itemTag.isEmpty() ? Value.NULL : ListValue.wrap(itemTag.get().stream().map(b -> ValueConversions.of(items.getKey(b.value())))); }); expression.addContextFunction("item_tags", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext)c; + final CarpetContext cc = (CarpetContext) c; - Registry blocks = cc.registry(Registries.ITEM); + final Registry blocks = cc.registry(Registries.ITEM); if (lv.size() == 0) + { return ListValue.wrap(blocks.getTagNames().map(ValueConversions::of)); - Item item = NBTSerializableValue.parseItem(lv.get(0).getString(), cc.registryAccess()).getItem(); + } + final Item item = NBTSerializableValue.parseItem(lv.get(0).getString(), cc.registryAccess()).getItem(); if (lv.size() == 1) { - return ListValue.wrap( blocks.getTags().filter(e -> e.getSecond().stream().anyMatch(h -> (h.value() == item))).map(e -> ValueConversions.of(e.getFirst()))); + return ListValue.wrap(blocks.getTags().filter(e -> e.getSecond().stream().anyMatch(h -> (h.value() == item))).map(e -> ValueConversions.of(e.getFirst()))); } - String tag = lv.get(1).getString(); - Optional> tagSet = blocks.getTag(TagKey.create(Registries.ITEM, InputValidator.identifierOf(tag))); - if (tagSet.isEmpty()) return Value.NULL; - - //return BooleanValue.of(tagSet.get().contains(item.builtInRegistryHolder())); - return BooleanValue.of(tagSet.get().stream().anyMatch(h -> h.value() == item)); - - /* - TagContainer tagManager = cc.s.getServer().getTags(); - if (lv.size() == 0) - return ListValue.wrap(tagManager.getOrEmpty(Registry.ITEM_REGISTRY).getAvailableTags().stream().map(ValueConversions::of)); - Item item = NBTSerializableValue.parseItem(lv.get(0).getString()).getItem(); - if (lv.size() == 1) - return ListValue.wrap(tagManager.getOrEmpty(Registry.ITEM_REGISTRY).getAllTags().entrySet().stream().filter(e -> e.getValue().contains(item)).map(e -> ValueConversions.of(e.getKey()))); - String tag = lv.get(1).getString(); - net.minecraft.tags.Tag itemTag = tagManager.getOrEmpty(Registry.ITEM_REGISTRY).getTag(InputValidator.identifierOf(tag)); - if (itemTag == null) return Value.NULL; - return BooleanValue.of(itemTag.contains(item)); - */ + final String tag = lv.get(1).getString(); + final Optional> tagSet = blocks.getTag(TagKey.create(Registries.ITEM, InputValidator.identifierOf(tag))); + return tagSet.isEmpty() ? Value.NULL : BooleanValue.of(tagSet.get().stream().anyMatch(h -> h.value() == item)); }); expression.addContextFunction("recipe_data", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext)c; - if (lv.size() < 1) throw new InternalExpressionException("'recipe_data' requires at least one argument"); - String recipeName = lv.get(0).getString(); + final CarpetContext cc = (CarpetContext) c; + if (lv.size() < 1) + { + throw new InternalExpressionException("'recipe_data' requires at least one argument"); + } + final String recipeName = lv.get(0).getString(); RecipeType type = RecipeType.CRAFTING; if (lv.size() > 1) { - String recipeType = lv.get(1).getString(); + final String recipeType = lv.get(1).getString(); type = cc.registry(Registries.RECIPE_TYPE).get(InputValidator.identifierOf(recipeType)); } - List> recipes; - recipes = ((RecipeManagerInterface) cc.server().getRecipeManager()).getAllMatching(type, InputValidator.identifierOf(recipeName), cc.registryAccess()); + final List> recipes = ((RecipeManagerInterface) cc.server().getRecipeManager()).getAllMatching(type, InputValidator.identifierOf(recipeName), cc.registryAccess()); if (recipes.isEmpty()) + { return Value.NULL; - List recipesOutput = new ArrayList<>(); - RegistryAccess regs = cc.registryAccess(); - for (Recipe recipe: recipes) - { - ItemStack result = recipe.getResultItem(regs); - List ingredientValue = new ArrayList<>(); - recipe.getIngredients().forEach( - ingredient -> - { - // I am flattening ingredient lists per slot. - // consider recipe_data('wooden_sword','crafting') and ('iron_nugget', 'blasting') and notice difference - // in depths of lists. - List> stacks = ((IngredientInterface) (Object) ingredient).getRecipeStacks(); - if (stacks.isEmpty()) - { - ingredientValue.add(Value.NULL); - } - else - { - List alternatives = new ArrayList<>(); - stacks.forEach(col -> col.stream().map(is -> ValueConversions.of(is, regs)).forEach(alternatives::add)); - ingredientValue.add(ListValue.wrap(alternatives)); - } - } - ); - Value recipeSpec; - if (recipe instanceof ShapedRecipe) + } + final List recipesOutput = new ArrayList<>(); + final RegistryAccess regs = cc.registryAccess(); + for (final Recipe recipe : recipes) + { + final ItemStack result = recipe.getResultItem(regs); + final List ingredientValue = new ArrayList<>(); + recipe.getIngredients().forEach( ingredient -> { + // I am flattening ingredient lists per slot. + // consider recipe_data('wooden_sword','crafting') and ('iron_nugget', 'blasting') and notice difference + // in depths of lists. + final List> stacks = ((IngredientInterface) (Object) ingredient).getRecipeStacks(); + if (stacks.isEmpty()) + { + ingredientValue.add(Value.NULL); + } + else + { + final List alternatives = new ArrayList<>(); + stacks.forEach(col -> col.stream().map(is -> ValueConversions.of(is, regs)).forEach(alternatives::add)); + ingredientValue.add(ListValue.wrap(alternatives)); + } + }); + final Value recipeSpec; + if (recipe instanceof final ShapedRecipe shapedRecipe) { recipeSpec = ListValue.of( new StringValue("shaped"), - new NumericValue(((ShapedRecipe) recipe).getWidth()), - new NumericValue(((ShapedRecipe) recipe).getHeight()) + new NumericValue(shapedRecipe.getWidth()), + new NumericValue(shapedRecipe.getHeight()) ); } else if (recipe instanceof ShapelessRecipe) { recipeSpec = ListValue.of(new StringValue("shapeless")); } - else if (recipe instanceof AbstractCookingRecipe) + else if (recipe instanceof final AbstractCookingRecipe abstractCookingRecipe) { recipeSpec = ListValue.of( new StringValue("smelting"), - new NumericValue(((AbstractCookingRecipe) recipe).getCookingTime()), - new NumericValue(((AbstractCookingRecipe) recipe).getExperience()) + new NumericValue(abstractCookingRecipe.getCookingTime()), + new NumericValue(abstractCookingRecipe.getExperience()) ); } else if (recipe instanceof SingleItemRecipe) @@ -196,100 +179,117 @@ else if (recipe instanceof CustomRecipe) expression.addContextFunction("crafting_remaining_item", 1, (c, t, v) -> { - String itemStr = v.get(0).getString(); - Item item; - ResourceLocation id = InputValidator.identifierOf(itemStr); - Registry registry = ((CarpetContext)c).registry(Registries.ITEM); - item = registry.getOptional(id).orElseThrow(() -> new ThrowStatement(itemStr, Throwables.UNKNOWN_ITEM)); - if (!item.hasCraftingRemainingItem()) return Value.NULL; - return new StringValue(NBTSerializableValue.nameFromRegistryId(registry.getKey(item.getCraftingRemainingItem()))); + final String itemStr = v.get(0).getString(); + final ResourceLocation id = InputValidator.identifierOf(itemStr); + final Registry registry = ((CarpetContext) c).registry(Registries.ITEM); + final Item item = registry.getOptional(id).orElseThrow(() -> new ThrowStatement(itemStr, Throwables.UNKNOWN_ITEM)); + return !item.hasCraftingRemainingItem() + ? Value.NULL + : new StringValue(NBTSerializableValue.nameFromRegistryId(registry.getKey(item.getCraftingRemainingItem()))); }); expression.addContextFunction("inventory_size", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext) c; - NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); - if (inventoryLocator == null) return Value.NULL; - return new NumericValue(inventoryLocator.inventory().getContainerSize()); + final CarpetContext cc = (CarpetContext) c; + final NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); + return inventoryLocator == null ? Value.NULL : new NumericValue(inventoryLocator.inventory().getContainerSize()); }); expression.addContextFunction("inventory_has_items", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext) c; - NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); - if (inventoryLocator == null) return Value.NULL; - return BooleanValue.of(!inventoryLocator.inventory().isEmpty()); + final CarpetContext cc = (CarpetContext) c; + final NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); + return inventoryLocator == null ? Value.NULL : BooleanValue.of(!inventoryLocator.inventory().isEmpty()); }); //inventory_get(, ) -> item_triple expression.addContextFunction("inventory_get", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext) c; - NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); - if (inventoryLocator == null) return Value.NULL; - RegistryAccess regs = cc.registryAccess(); + final CarpetContext cc = (CarpetContext) c; + final NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); + if (inventoryLocator == null) + { + return Value.NULL; + } + final RegistryAccess regs = cc.registryAccess(); if (lv.size() == inventoryLocator.offset()) { - List fullInventory = new ArrayList<>(); + final List fullInventory = new ArrayList<>(); for (int i = 0, maxi = inventoryLocator.inventory().getContainerSize(); i < maxi; i++) + { fullInventory.add(ValueConversions.of(inventoryLocator.inventory().getItem(i), regs)); + } return ListValue.wrap(fullInventory); } - int slot = (int)NumericValue.asNumber(lv.get(inventoryLocator.offset())).getLong(); + int slot = (int) NumericValue.asNumber(lv.get(inventoryLocator.offset())).getLong(); slot = NBTSerializableValue.validateSlot(slot, inventoryLocator.inventory()); - if (slot == inventoryLocator.inventory().getContainerSize()) return Value.NULL; - return ValueConversions.of(inventoryLocator.inventory().getItem(slot), regs); + return slot == inventoryLocator.inventory().getContainerSize() + ? Value.NULL + : ValueConversions.of(inventoryLocator.inventory().getItem(slot), regs); }); //inventory_set(, , , , ) expression.addContextFunction("inventory_set", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext) c; - NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); - if (inventoryLocator == null) return Value.NULL; - if (lv.size() < inventoryLocator.offset()+2) + final CarpetContext cc = (CarpetContext) c; + final NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); + if (inventoryLocator == null) + { + return Value.NULL; + } + if (lv.size() < inventoryLocator.offset() + 2) + { 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(); + } + int slot = (int) NumericValue.asNumber(lv.get(inventoryLocator.offset() + 0)).getLong(); slot = NBTSerializableValue.validateSlot(slot, inventoryLocator.inventory()); - if (slot == inventoryLocator.inventory().getContainerSize()) return Value.NULL; - int count = (int) NumericValue.asNumber(lv.get(inventoryLocator.offset()+1)).getLong(); - RegistryAccess regs = cc.registryAccess(); + if (slot == inventoryLocator.inventory().getContainerSize()) + { + return Value.NULL; + } + final int count = (int) NumericValue.asNumber(lv.get(inventoryLocator.offset() + 1)).getLong(); + final RegistryAccess regs = cc.registryAccess(); if (count == 0) { // clear slot - ItemStack removedStack = inventoryLocator.inventory().removeItemNoUpdate(slot); + final 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, regs); } - if (lv.size() < inventoryLocator.offset()+3) + if (lv.size() < inventoryLocator.offset() + 3) { - ItemStack previousStack = inventoryLocator.inventory().getItem(slot); - ItemStack newStack = previousStack.copy(); + final ItemStack previousStack = inventoryLocator.inventory().getItem(slot); + final ItemStack newStack = previousStack.copy(); newStack.setCount(count); inventoryLocator.inventory().setItem(slot, newStack); syncPlayerInventory(inventoryLocator, slot); return ValueConversions.of(previousStack, regs); } CompoundTag nbt = null; // skipping one argument - if (lv.size() > inventoryLocator.offset()+3) + if (lv.size() > inventoryLocator.offset() + 3) { - Value nbtValue = lv.get(inventoryLocator.offset()+3); - if (nbtValue instanceof NBTSerializableValue) - nbt = ((NBTSerializableValue)nbtValue).getCompoundTag(); + final Value nbtValue = lv.get(inventoryLocator.offset() + 3); + if (nbtValue instanceof final NBTSerializableValue nbtsv) + { + nbt = nbtsv.getCompoundTag(); + } else if (nbtValue.isNull()) + { nbt = null; + } else + { nbt = new NBTSerializableValue(nbtValue.getString()).getCompoundTag(); + } } - ItemInput newitem = NBTSerializableValue.parseItem(lv.get(inventoryLocator.offset()+2).getString(), nbt, cc.registryAccess()); - ItemStack previousStack = inventoryLocator.inventory().getItem(slot); + final ItemInput newitem = NBTSerializableValue.parseItem(lv.get(inventoryLocator.offset() + 2).getString(), nbt, cc.registryAccess()); + final ItemStack previousStack = inventoryLocator.inventory().getItem(slot); try { inventoryLocator.inventory().setItem(slot, newitem.createItemStack(count, false)); syncPlayerInventory(inventoryLocator, slot); } - catch (CommandSyntaxException e) + catch (final CommandSyntaxException e) { throw new InternalExpressionException(e.getMessage()); } @@ -299,27 +299,34 @@ else if (nbtValue.isNull()) //inventory_find(, or null (first empty slot), ) -> or null expression.addContextFunction("inventory_find", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext) c; - NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); - if (inventoryLocator == null) return Value.NULL; + final CarpetContext cc = (CarpetContext) c; + final NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); + if (inventoryLocator == null) + { + return Value.NULL; + } ItemInput itemArg = null; if (lv.size() > inventoryLocator.offset()) { - Value secondArg = lv.get(inventoryLocator.offset()+0); + final Value secondArg = lv.get(inventoryLocator.offset() + 0); if (!secondArg.isNull()) + { itemArg = NBTSerializableValue.parseItem(secondArg.getString(), cc.registryAccess()); + } } int startIndex = 0; - if (lv.size() > inventoryLocator.offset()+1) + if (lv.size() > inventoryLocator.offset() + 1) { - startIndex = (int) NumericValue.asNumber(lv.get(inventoryLocator.offset()+1)).getLong(); + startIndex = (int) NumericValue.asNumber(lv.get(inventoryLocator.offset() + 1)).getLong(); } startIndex = NBTSerializableValue.validateSlot(startIndex, inventoryLocator.inventory()); for (int i = startIndex, maxi = inventoryLocator.inventory().getContainerSize(); i < maxi; i++) { - ItemStack stack = inventoryLocator.inventory().getItem(i); - if ( (itemArg == null && stack.isEmpty()) || (itemArg != null && itemArg.getItem().equals(stack.getItem())) ) + final ItemStack stack = inventoryLocator.inventory().getItem(i); + if ((itemArg == null && stack.isEmpty()) || (itemArg != null && itemArg.getItem().equals(stack.getItem()))) + { return new NumericValue(i); + } } return Value.NULL; }); @@ -327,26 +334,36 @@ else if (nbtValue.isNull()) //inventory_remove(, , ) -> bool expression.addContextFunction("inventory_remove", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext) c; - NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); - if (inventoryLocator == null) return Value.NULL; + final CarpetContext cc = (CarpetContext) c; + final NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); + if (inventoryLocator == null) + { + return Value.NULL; + } if (lv.size() <= inventoryLocator.offset()) + { throw new InternalExpressionException("'inventory_remove' requires at least an item to be removed"); - ItemInput searchItem = NBTSerializableValue.parseItem(lv.get(inventoryLocator.offset()).getString(), cc.registryAccess()); + } + final ItemInput searchItem = NBTSerializableValue.parseItem(lv.get(inventoryLocator.offset()).getString(), cc.registryAccess()); int amount = 1; - if (lv.size() > inventoryLocator.offset()+1) - amount = (int)NumericValue.asNumber(lv.get(inventoryLocator.offset()+1)).getLong(); + if (lv.size() > inventoryLocator.offset() + 1) + { + amount = (int) NumericValue.asNumber(lv.get(inventoryLocator.offset() + 1)).getLong(); + } // not enough if (((amount == 1) && (!inventoryLocator.inventory().hasAnyOf(Set.of(searchItem.getItem())))) - || (inventoryLocator.inventory().countItem(searchItem.getItem()) < amount)) return Value.FALSE; + || (inventoryLocator.inventory().countItem(searchItem.getItem()) < amount)) + { + return Value.FALSE; + } for (int i = 0, maxi = inventoryLocator.inventory().getContainerSize(); i < maxi; i++) { - ItemStack stack = inventoryLocator.inventory().getItem(i); - if (stack.isEmpty()) - continue; - if (!stack.getItem().equals(searchItem.getItem())) + final ItemStack stack = inventoryLocator.inventory().getItem(i); + if (stack.isEmpty() || !stack.getItem().equals(searchItem.getItem())) + { continue; - int left = stack.getCount()-amount; + } + final int left = stack.getCount() - amount; if (left > 0) { stack.setCount(left); @@ -354,58 +371,78 @@ else if (nbtValue.isNull()) syncPlayerInventory(inventoryLocator, i); return Value.TRUE; } - else - { - inventoryLocator.inventory().removeItemNoUpdate(i); - syncPlayerInventory(inventoryLocator, i); - amount -= stack.getCount(); - } + inventoryLocator.inventory().removeItemNoUpdate(i); + syncPlayerInventory(inventoryLocator, i); + amount -= stack.getCount(); } if (amount > 0) + { throw new InternalExpressionException("Something bad happened - cannot pull all items from inventory"); + } return Value.TRUE; }); //inventory_drop(, , ) -> entity_item (and sets slot) or null if cannot expression.addContextFunction("drop_item", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext) c; - NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); - if (inventoryLocator == null) return Value.NULL; + final CarpetContext cc = (CarpetContext) c; + final NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); + if (inventoryLocator == null) + { + return Value.NULL; + } if (lv.size() == inventoryLocator.offset()) + { throw new InternalExpressionException("Slot number is required for inventory_drop"); - int slot = (int)NumericValue.asNumber(lv.get(inventoryLocator.offset())).getLong(); + } + int slot = (int) NumericValue.asNumber(lv.get(inventoryLocator.offset())).getLong(); slot = NBTSerializableValue.validateSlot(slot, inventoryLocator.inventory()); - if (slot == inventoryLocator.inventory().getContainerSize()) 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 (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().getItem(slot); - if (stack == null || stack.isEmpty()) return Value.ZERO; - if (amount == 0) amount = stack.getCount(); - ItemStack droppedStack = inventoryLocator.inventory().removeItem(slot, amount); - if (droppedStack.isEmpty()) return Value.ZERO; - Object owner = inventoryLocator.owner(); - ItemEntity item; - if (owner instanceof Player) + } + final ItemStack stack = inventoryLocator.inventory().getItem(slot); + if (stack == null || stack.isEmpty()) + { + return Value.ZERO; + } + if (amount == 0) + { + amount = stack.getCount(); + } + final ItemStack droppedStack = inventoryLocator.inventory().removeItem(slot, amount); + if (droppedStack.isEmpty()) + { + return Value.ZERO; + } + final Object owner = inventoryLocator.owner(); + final ItemEntity item; + if (owner instanceof final Player player) { - item = ((Player) owner).drop(droppedStack, false, true); + item = player.drop(droppedStack, false, true); } - else if (owner instanceof LivingEntity villager) + else if (owner instanceof LivingEntity livingEntity) { // stolen from LookTargetUtil.give((VillagerEntity)owner, droppedStack, (LivingEntity) owner); - double double_1 = villager.getY() - 0.30000001192092896D + 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); + double double_1 = livingEntity.getY() - 0.30000001192092896D + livingEntity.getEyeHeight(); + item = new ItemEntity(livingEntity.level, livingEntity.getX(), double_1, livingEntity.getZ(), droppedStack); + final Vec3 vec3d = livingEntity.getViewVector(1.0F).normalize().scale(0.3);// new Vec3d(0, 0.3, 0); + item.setDeltaMovement(vec3d); item.setDefaultPickUpDelay(); cc.level().addFreshEntity(item); } else { - Vec3 point = Vec3.atCenterOf(inventoryLocator.position()); //pos+0.5v + final Vec3 point = Vec3.atCenterOf(inventoryLocator.position()); //pos+0.5v item = new ItemEntity(cc.level(), point.x, point.y, point.z, droppedStack); item.setDefaultPickUpDelay(); cc.level().addFreshEntity(item); @@ -413,49 +450,64 @@ else if (owner instanceof LivingEntity villager) return new NumericValue(item.getItem().getCount()); }); - expression.addContextFunction("create_screen",-1, (c, t, lv) -> + 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); - ServerPlayer player = EntityValue.getPlayerByValue(((CarpetContext) c).server(), playerValue); - if(player == null) throw new InternalExpressionException("'create_screen' requires a valid online player as the first argument."); - String type = lv.get(1).getString(); - Component name = FormattedTextValue.getTextByValue(lv.get(2)); + if (lv.size() < 3) + { + throw new InternalExpressionException("'create_screen' requires at least three arguments"); + } + final Value playerValue = lv.get(0); + final ServerPlayer player = EntityValue.getPlayerByValue(((CarpetContext) c).server(), playerValue); + if (player == null) + { + throw new InternalExpressionException("'create_screen' requires a valid online player as the first argument."); + } + final String type = lv.get(1).getString(); + final Component name = FormattedTextValue.getTextByValue(lv.get(2)); FunctionValue function = null; - if(lv.size() > 3) + if (lv.size() > 3) + { function = FunctionArgument.findIn(c, expression.module, lv, 3, true, false).function; + } - return new ScreenValue(player,type,name,function,c); + return new ScreenValue(player, type, name, function, c); }); - expression.addContextFunction("close_screen",1, (c, t, lv) -> + expression.addContextFunction("close_screen", 1, (c, t, lv) -> { - Value value = lv.get(0); - if(!(value instanceof ScreenValue screenValue)) throw new InternalExpressionException("'close_screen' requires a screen value as the first argument."); - if(!screenValue.isOpen()) return Value.FALSE; + final Value value = lv.get(0); + if (!(value instanceof final ScreenValue screenValue)) + { + throw new InternalExpressionException("'close_screen' requires a screen value as the first argument."); + } + if (!screenValue.isOpen()) + { + return Value.FALSE; + } screenValue.close(); return Value.TRUE; }); - expression.addContextFunction("screen_property",-1, (c, t, lv) -> + expression.addContextFunction("screen_property", -1, (c, t, lv) -> { - if(lv.size()<2) throw new InternalExpressionException("'screen_property' requires at least a screen and a property name"); - if(!(lv.get(0) instanceof ScreenValue screenValue)) throw new InternalExpressionException("'screen_property' requires a screen value as the first argument"); - String propertyName = lv.get(1).getString(); - if(lv.size()>=3) + if (lv.size() < 2) { - return screenValue.modifyProperty(propertyName,lv.subList(2,lv.size())); + throw new InternalExpressionException("'screen_property' requires at least a screen and a property name"); } - else + if (!(lv.get(0) instanceof final ScreenValue screenValue)) { - return screenValue.queryProperty(propertyName); + throw new InternalExpressionException("'screen_property' requires a screen value as the first argument"); } + final String propertyName = lv.get(1).getString(); + return lv.size() >= 3 + ? screenValue.modifyProperty(propertyName, lv.subList(2, lv.size())) + : screenValue.queryProperty(propertyName); }); } - private static void syncPlayerInventory(NBTSerializableValue.InventoryLocator inventory, int int_1) + private static void syncPlayerInventory(final NBTSerializableValue.InventoryLocator inventory, final int int_1) { - if (inventory.owner() instanceof ServerPlayer player && !inventory.isEnder() && !(inventory.inventory() instanceof ScreenValue.ScreenHandlerInventory)) + if (inventory.owner() instanceof final ServerPlayer player && !inventory.isEnder() && !(inventory.inventory() instanceof ScreenValue.ScreenHandlerInventory)) { player.connection.send(new ClientboundContainerSetSlotPacket( -2, 0, // resolve mystery argument diff --git a/src/main/java/carpet/script/api/Monitoring.java b/src/main/java/carpet/script/api/Monitoring.java index bf8344d874..e32674a23f 100644 --- a/src/main/java/carpet/script/api/Monitoring.java +++ b/src/main/java/carpet/script/api/Monitoring.java @@ -1,6 +1,5 @@ package carpet.script.api; -import carpet.fakes.SpawnHelperInnerInterface; import carpet.script.CarpetContext; import carpet.script.Expression; import carpet.script.exception.InternalExpressionException; @@ -24,10 +23,11 @@ import net.minecraft.world.entity.MobCategory; import net.minecraft.world.level.NaturalSpawner; -public class Monitoring { +public class Monitoring +{ private static final Map MOB_CATEGORY_MAP = Arrays.stream(MobCategory.values()).collect(Collectors.toMap(MobCategory::getName, Function.identity())); - public static void apply(Expression expression) + public static void apply(final Expression expression) { expression.addContextFunction("system_info", -1, (c, t, lv) -> { @@ -35,10 +35,14 @@ public static void apply(Expression expression) { return SystemInfo.getAll(); } - if (lv.size() == 1) { - String what = lv.get(0).getString(); - Value res = SystemInfo.get(what, (CarpetContext) c); - if (res == null) throw new InternalExpressionException("Unknown option for 'system_info': " + what); + if (lv.size() == 1) + { + final String what = lv.get(0).getString(); + final Value res = SystemInfo.get(what, (CarpetContext) c); + if (res == null) + { + throw new InternalExpressionException("Unknown option for 'system_info': " + what); + } return res; } throw new InternalExpressionException("'system_info' requires one or no parameters"); @@ -46,18 +50,21 @@ public static void apply(Expression expression) // game processed snooper functions expression.addContextFunction("get_mob_counts", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext)c; - ServerLevel world = cc.level(); - NaturalSpawner.SpawnState info = world.getChunkSource().getLastSpawnState(); - if (info == null) return Value.NULL; - Object2IntMap mobcounts = info.getMobCategoryCounts(); - int chunks = info.getSpawnableChunkCount(); + final CarpetContext cc = (CarpetContext) c; + final ServerLevel world = cc.level(); + final NaturalSpawner.SpawnState info = world.getChunkSource().getLastSpawnState(); + if (info == null) + { + return Value.NULL; + } + final Object2IntMap mobcounts = info.getMobCategoryCounts(); + final int chunks = info.getSpawnableChunkCount(); if (lv.size() == 0) { - Map retDict = new HashMap<>(); - for (MobCategory category: mobcounts.keySet()) + final Map retDict = new HashMap<>(); + for (final MobCategory category : mobcounts.keySet()) { - int currentCap = (int)(category.getMaxInstancesPerChunk() * chunks / SpawnReporter.MAGIC_NUMBER); + final int currentCap = category.getMaxInstancesPerChunk() * chunks / SpawnReporter.MAGIC_NUMBER; retDict.put( new StringValue(category.getSerializedName().toLowerCase(Locale.ROOT)), ListValue.of( @@ -67,12 +74,15 @@ public static void apply(Expression expression) } return MapValue.wrap(retDict); } - String catString = lv.get(0).getString(); - MobCategory cat = MOB_CATEGORY_MAP.get(catString.toLowerCase(Locale.ROOT)); - if (cat == null) throw new InternalExpressionException("Unreconized mob category: "+catString); + final String catString = lv.get(0).getString(); + final MobCategory cat = MOB_CATEGORY_MAP.get(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.getMaxInstancesPerChunk() * chunks / SpawnReporter.MAGIC_NUMBER)) + new NumericValue((int) (cat.getMaxInstancesPerChunk() * chunks / SpawnReporter.MAGIC_NUMBER)) ); }); } diff --git a/src/main/java/carpet/script/api/Scoreboards.java b/src/main/java/carpet/script/api/Scoreboards.java index dae7769bee..f1030d43db 100644 --- a/src/main/java/carpet/script/api/Scoreboards.java +++ b/src/main/java/carpet/script/api/Scoreboards.java @@ -16,8 +16,10 @@ import carpet.script.value.FormattedTextValue; import carpet.script.value.Value; import com.google.common.collect.Lists; + import java.util.ArrayList; import java.util.List; + import net.minecraft.ChatFormatting; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; @@ -35,80 +37,90 @@ import net.minecraft.world.scores.Team; import net.minecraft.world.scores.criteria.ObjectiveCriteria; -public class Scoreboards { - private static String getScoreboardKeyFromValue(Value keyValue) +public class Scoreboards +{ + private static String getScoreboardKeyFromValue(final Value keyValue) { - if (keyValue instanceof EntityValue) + if (keyValue instanceof final EntityValue ev) { - Entity e = ((EntityValue) keyValue).getEntity(); - if (e instanceof Player) - { - return e.getName().getString(); - } - else - { - return e.getStringUUID(); - } - } - else - { - return keyValue.getString(); + final Entity e = ev.getEntity(); + return e instanceof Player ? e.getName().getString() : e.getStringUUID(); } + return keyValue.getString(); } - public static void apply(Expression expression) + public static void apply(final Expression expression) { // scoreboard(player,'objective') // scoreboard(player, objective, newValue) expression.addContextFunction("scoreboard", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext)c; - Scoreboard scoreboard = cc.server().getScoreboard(); - if (lv.size()==0) + final CarpetContext cc = (CarpetContext) c; + final Scoreboard scoreboard = cc.server().getScoreboard(); + if (lv.size() == 0) + { return ListValue.wrap(scoreboard.getObjectiveNames().stream().map(StringValue::new)); - String objectiveName = lv.get(0).getString(); - Objective objective = scoreboard.getOrCreateObjective(objectiveName); - if (objective == null) return Value.NULL; - if (lv.size()==1) + } + final String objectiveName = lv.get(0).getString(); + final Objective objective = scoreboard.getOrCreateObjective(objectiveName); + if (objective == null) + { + return Value.NULL; + } + if (lv.size() == 1) + { return ListValue.wrap(scoreboard.getPlayerScores(objective).stream().map(s -> new StringValue(s.getOwner()))); - String key = getScoreboardKeyFromValue(lv.get(1)); - if(lv.size()==2) + } + final String key = getScoreboardKeyFromValue(lv.get(1)); + if (lv.size() == 2) { - if(!scoreboard.hasPlayerScore(key, objective)) return Value.NULL; - return NumericValue.of(scoreboard.getOrCreatePlayerScore(key,objective).getScore()); + return !scoreboard.hasPlayerScore(key, objective) + ? Value.NULL + : NumericValue.of(scoreboard.getOrCreatePlayerScore(key, objective).getScore()); } - Value value = lv.get(2); - if(value.isNull()) { - Score score = scoreboard.getOrCreatePlayerScore(key, objective); - scoreboard.resetPlayerScore(key,objective); + final Value value = lv.get(2); + if (value.isNull()) + { + final Score score = scoreboard.getOrCreatePlayerScore(key, objective); + scoreboard.resetPlayerScore(key, objective); return NumericValue.of(score.getScore()); } - if (value instanceof NumericValue) { - Score score = scoreboard.getOrCreatePlayerScore(key, objective); + if (value instanceof NumericValue) + { + final Score score = scoreboard.getOrCreatePlayerScore(key, objective); score.setScore(NumericValue.asNumber(value).getInt()); return NumericValue.of(score.getScore()); } throw new InternalExpressionException("'scoreboard' requires a number or null as the third parameter"); }); - expression.addContextFunction("scoreboard_remove", -1, (c, t, lv)-> + expression.addContextFunction("scoreboard_remove", -1, (c, t, lv) -> { - if (lv.size()==0) throw new InternalExpressionException("'scoreboard_remove' requires at least one parameter"); - CarpetContext cc = (CarpetContext)c; - Scoreboard scoreboard = cc.server().getScoreboard(); - String objectiveName = lv.get(0).getString(); - Objective objective = scoreboard.getOrCreateObjective(objectiveName); - if (objective == null) return Value.FALSE; + if (lv.size() == 0) + { + throw new InternalExpressionException("'scoreboard_remove' requires at least one parameter"); + } + final CarpetContext cc = (CarpetContext) c; + final Scoreboard scoreboard = cc.server().getScoreboard(); + final String objectiveName = lv.get(0).getString(); + final Objective objective = scoreboard.getOrCreateObjective(objectiveName); + if (objective == null) + { + return Value.FALSE; + } if (lv.size() == 1) { scoreboard.removeObjective(objective); return Value.TRUE; } - String key = getScoreboardKeyFromValue(lv.get(1)); - if (!scoreboard.hasPlayerScore(key, objective)) return Value.NULL; - Score scoreboardPlayerScore = scoreboard.getOrCreatePlayerScore(key, objective); - Value previous = new NumericValue(scoreboardPlayerScore.getScore()); + final String key = getScoreboardKeyFromValue(lv.get(1)); + if (!scoreboard.hasPlayerScore(key, objective)) + { + return Value.NULL; + } + final Score scoreboardPlayerScore = scoreboard.getOrCreatePlayerScore(key, objective); + final Value previous = new NumericValue(scoreboardPlayerScore.getScore()); scoreboard.resetPlayerScore(key, objective); return previous; }); @@ -116,175 +128,247 @@ public static void apply(Expression expression) // objective_add('lvl','level') // objective_add('counter') - expression.addContextFunction("scoreboard_add", -1, (c, t, lv)-> + expression.addContextFunction("scoreboard_add", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext)c; - Scoreboard scoreboard = cc.server().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(); - ObjectiveCriteria criterion; - if (lv.size() == 1 ) + final CarpetContext cc = (CarpetContext) c; + final Scoreboard scoreboard = cc.server().getScoreboard(); + if (lv.size() == 0 || lv.size() > 2) + { + throw new InternalExpressionException("'scoreboard_add' should have one or two parameters"); + } + final String objectiveName = lv.get(0).getString(); + final ObjectiveCriteria criterion; + if (lv.size() == 1) { criterion = ObjectiveCriteria.DUMMY; } else { - String critetionName = lv.get(1).getString(); + final String critetionName = lv.get(1).getString(); criterion = ObjectiveCriteria.byName(critetionName).orElse(null); - if (criterion==null) + if (criterion == null) { throw new ThrowStatement(critetionName, Throwables.UNKNOWN_CRITERION); } } - Objective objective = scoreboard.getOrCreateObjective(objectiveName); - if (objective != null) { + final 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.getCriteria().getName()); - if(objective.getCriteria().equals(criterion) || lv.size() == 1) return Value.NULL; - ((Scoreboard_scarpetMixin)scoreboard).getObjectivesByCriterion().get(objective.getCriteria()).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); ((Objective_scarpetMixin) objective).setCriterion(criterion); - (((Scoreboard_scarpetMixin)scoreboard).getObjectivesByCriterion().computeIfAbsent(criterion, (criterion1) -> Lists.newArrayList())).add(objective); + (((Scoreboard_scarpetMixin) scoreboard).getObjectivesByCriterion().computeIfAbsent(criterion, (criterion1) -> Lists.newArrayList())).add(objective); scoreboard.onObjectiveAdded(objective); return Value.FALSE; } - scoreboard.addObjective(objectiveName, criterion, Component.literal(objectiveName), criterion.getDefaultRenderType()); return Value.TRUE; }); expression.addContextFunction("scoreboard_property", -1, (c, t, lv) -> { - if(lv.size() < 2) throw new InternalExpressionException("'scoreboard_property' requires at least two parameters"); - CarpetContext cc = (CarpetContext)c; - Scoreboard scoreboard = cc.server().getScoreboard(); - Objective objective = scoreboard.getOrCreateObjective(lv.get(0).getString()); - if(objective == null) return Value.NULL; + if (lv.size() < 2) + { + throw new InternalExpressionException("'scoreboard_property' requires at least two parameters"); + } + final CarpetContext cc = (CarpetContext) c; + final Scoreboard scoreboard = cc.server().getScoreboard(); + final Objective objective = scoreboard.getOrCreateObjective(lv.get(0).getString()); + if (objective == null) + { + return Value.NULL; + } - boolean modify = lv.size() > 2; + final boolean modify = lv.size() > 2; Value setValue = null; - if(modify) { + if (modify) + { setValue = lv.get(2); } - String property = lv.get(1).getString(); - switch (property) { - case "criterion": - if(modify) { - ObjectiveCriteria criterion = ObjectiveCriteria.byName(setValue.getString()).orElse(null); - if (criterion==null) throw new InternalExpressionException("Unknown scoreboard criterion: "+ setValue.getString()); - if(objective.getCriteria().equals(criterion) || lv.size() == 1) return Value.FALSE; - ((Scoreboard_scarpetMixin)scoreboard).getObjectivesByCriterion().get(objective.getCriteria()).remove(objective); + final String property = lv.get(1).getString(); + switch (property) + { + case "criterion" -> { + if (modify) + { + final ObjectiveCriteria criterion = ObjectiveCriteria.byName(setValue.getString()).orElse(null); + if (criterion == null) + { + throw new InternalExpressionException("Unknown scoreboard criterion: " + setValue.getString()); + } + if (objective.getCriteria().equals(criterion) || lv.size() == 1) + { + return Value.FALSE; + } + ((Scoreboard_scarpetMixin) scoreboard).getObjectivesByCriterion().get(objective.getCriteria()).remove(objective); ((Objective_scarpetMixin) objective).setCriterion(criterion); - (((Scoreboard_scarpetMixin)scoreboard).getObjectivesByCriterion().computeIfAbsent(criterion, (criterion1) -> Lists.newArrayList())).add(objective); + (((Scoreboard_scarpetMixin) scoreboard).getObjectivesByCriterion().computeIfAbsent(criterion, (criterion1) -> Lists.newArrayList())).add(objective); scoreboard.onObjectiveAdded(objective); return Value.TRUE; } return StringValue.of(objective.getCriteria().getName()); - case "display_name": - if(modify) { - Component text = FormattedTextValue.getTextByValue(setValue); + } + case "display_name" -> { + if (modify) + { + final Component text = FormattedTextValue.getTextByValue(setValue); objective.setDisplayName(text); return Value.TRUE; } return new FormattedTextValue(objective.getDisplayName()); - case "display_slot": - if(modify) { - int slotId = Scoreboard.getDisplaySlotByName(setValue.getString()); - if(slotId == -1) throw new InternalExpressionException("Unknown scoreboard display slot: " + setValue.getString()); - if(objective.equals(scoreboard.getDisplayObjective(slotId))) { + } + case "display_slot" -> { + if (modify) + { + final int slotId = Scoreboard.getDisplaySlotByName(setValue.getString()); + if (slotId == -1) + { + throw new InternalExpressionException("Unknown scoreboard display slot: " + setValue.getString()); + } + if (objective.equals(scoreboard.getDisplayObjective(slotId))) + { return Value.FALSE; } - scoreboard.setDisplayObjective(slotId,objective); + scoreboard.setDisplayObjective(slotId, objective); return Value.TRUE; } - - List slots = new ArrayList<>(); - for(int i = 0; i < 19; i++) { - if (scoreboard.getDisplayObjective(i) == objective) { - String slotName = Scoreboard.getDisplaySlotName(i); + final List slots = new ArrayList<>(); + for (int i = 0; i < 19; i++) + { + if (scoreboard.getDisplayObjective(i) == objective) + { + final String slotName = Scoreboard.getDisplaySlotName(i); slots.add(StringValue.of(slotName)); } } return ListValue.wrap(slots); - case "render_type": - if(modify) { - ObjectiveCriteria.RenderType renderType = ObjectiveCriteria.RenderType.byId(setValue.getString().toLowerCase()); - if(objective.getRenderType().equals(renderType)) return Value.FALSE; + } + case "render_type" -> { + if (modify) + { + final 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().getId()); - default: - throw new InternalExpressionException("scoreboard property '" + property + "' is not a valid property"); + } + default -> throw new InternalExpressionException("scoreboard property '" + property + "' is not a valid property"); } }); expression.addContextFunction("scoreboard_display", 2, (c, t, lv) -> { - CarpetContext cc = (CarpetContext)c; - Scoreboard scoreboard = cc.server().getScoreboard(); - String location = lv.get(0).getString(); - int slot = Scoreboard.getDisplaySlotByName(location); - if (slot < 0) throw new InternalExpressionException("Invalid objective slot: "+location); - Value target = lv.get(1); + final CarpetContext cc = (CarpetContext) c; + final Scoreboard scoreboard = cc.server().getScoreboard(); + final String location = lv.get(0).getString(); + final int slot = Scoreboard.getDisplaySlotByName(location); + if (slot < 0) + { + throw new InternalExpressionException("Invalid objective slot: " + location); + } + final Value target = lv.get(1); if (target.isNull()) { scoreboard.setDisplayObjective(slot, null); return new NumericValue(slot); } - String objectiveString = target.getString(); - Objective objective = scoreboard.getOrCreateObjective(objectiveString); - if (objective == null) return Value.NULL; + final String objectiveString = target.getString(); + final Objective objective = scoreboard.getOrCreateObjective(objectiveString); + if (objective == null) + { + return Value.NULL; + } scoreboard.setDisplayObjective(slot, objective); return new NumericValue(slot); }); expression.addContextFunction("team_list", -1, (c, t, lv) -> { - if(lv.size() > 1) throw new InternalExpressionException("'team_list' requires zero or one parameters"); - CarpetContext cc = (CarpetContext)c; - ServerScoreboard scoreboard = cc.server().getScoreboard(); - if(lv.size() == 0) + if (lv.size() > 1) + { + throw new InternalExpressionException("'team_list' requires zero or one parameters"); + } + final CarpetContext cc = (CarpetContext) c; + final ServerScoreboard scoreboard = cc.server().getScoreboard(); + if (lv.size() == 0) + { return ListValue.wrap(scoreboard.getTeamNames().stream().map(StringValue::of)); - if (lv.size() != 1) return Value.NULL; - PlayerTeam team = scoreboard.getPlayerTeam(lv.get(0).getString()); - if(team == null) return Value.NULL; - return ListValue.wrap(team.getPlayers().stream().map(StringValue::of)); + } + if (lv.size() != 1) + { + return Value.NULL; + } + final PlayerTeam team = scoreboard.getPlayerTeam(lv.get(0).getString()); + return team == null ? Value.NULL : ListValue.wrap(team.getPlayers().stream().map(StringValue::of)); }); expression.addContextFunction("team_add", -1, (c, t, lv) -> { - if(!(lv.size() < 3 && lv.size() > 0)) throw new InternalExpressionException("'team_add' requires one or two parameters"); + if (!(lv.size() < 3 && lv.size() > 0)) + { + throw new InternalExpressionException("'team_add' requires one or two parameters"); + } - CarpetContext cc = (CarpetContext)c; - ServerScoreboard scoreboard = cc.server().getScoreboard(); - String teamName = lv.get(0).getString(); + final CarpetContext cc = (CarpetContext) c; + final ServerScoreboard scoreboard = cc.server().getScoreboard(); + final String teamName = lv.get(0).getString(); - if(lv.size() == 1) + if (lv.size() == 1) { - if (scoreboard.getPlayerTeam(teamName) != null) return Value.NULL; + 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; - PlayerTeam team = scoreboard.getPlayerTeam(teamName); - if(team == null) return Value.NULL; - if(team.isAlliedTo(scoreboard.getPlayersTeam(player))) return Value.FALSE; - scoreboard.addPlayerToTeam(player,scoreboard.getPlayerTeam(teamName)); + if (lv.size() != 2) + { + return Value.NULL; + } + final Value playerVal = lv.get(1); + final String player = EntityValue.getPlayerNameByValue(playerVal); + if (player == null) + { + return Value.NULL; + } + final PlayerTeam team = scoreboard.getPlayerTeam(teamName); + if (team == null) + { + return Value.NULL; + } + if (team.isAlliedTo(scoreboard.getPlayersTeam(player))) + { + return Value.FALSE; + } + scoreboard.addPlayerToTeam(player, scoreboard.getPlayerTeam(teamName)); return Value.TRUE; }); expression.addContextFunction("team_remove", 1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext)c; - ServerScoreboard scoreboard = cc.server().getScoreboard(); - Value teamVal = lv.get(0); - String team = teamVal.getString(); - if(scoreboard.getPlayerTeam(team) == null) return Value.NULL; + final CarpetContext cc = (CarpetContext) c; + final ServerScoreboard scoreboard = cc.server().getScoreboard(); + final Value teamVal = lv.get(0); + final String team = teamVal.getString(); + if (scoreboard.getPlayerTeam(team) == null) + { + return Value.NULL; + } scoreboard.removePlayerTeam(scoreboard.getPlayerTeam(team)); return Value.TRUE; }); @@ -292,212 +376,328 @@ public static void apply(Expression expression) expression.addContextFunction("team_leave", 1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext)c; - ServerScoreboard scoreboard = cc.server().getScoreboard(); - Value playerVal = lv.get(0); - String player = EntityValue.getPlayerNameByValue(playerVal); - if(player == null) return Value.NULL; - return BooleanValue.of(scoreboard.removePlayerFromTeam(player)); + final CarpetContext cc = (CarpetContext) c; + final ServerScoreboard scoreboard = cc.server().getScoreboard(); + final Value playerVal = lv.get(0); + final String player = EntityValue.getPlayerNameByValue(playerVal); + return player == null ? Value.NULL : BooleanValue.of(scoreboard.removePlayerFromTeam(player)); }); expression.addContextFunction("team_property", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext)c; - ServerScoreboard scoreboard = cc.server().getScoreboard(); - - if(lv.size() < 2 || lv.size() > 3) throw new InternalExpressionException("'team_property' requires two or three arguments"); - - Value teamVal = lv.get(0); - Value propertyVal = lv.get(1); + final CarpetContext cc = (CarpetContext) c; + final ServerScoreboard scoreboard = cc.server().getScoreboard(); + if (lv.size() < 2 || lv.size() > 3) + { + throw new InternalExpressionException("'team_property' requires two or three arguments"); + } + final Value teamVal = lv.get(0); + final Value propertyVal = lv.get(1); Value settingVal = null; boolean modifying = false; - if(lv.size() == 3) + if (lv.size() == 3) { modifying = true; settingVal = lv.get(2); } - PlayerTeam team = scoreboard.getPlayerTeam(teamVal.getString()); - if(team == null) return Value.NULL; + final 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"); + if (!(propertyVal instanceof StringValue)) + { + throw new InternalExpressionException("'team_property' requires a string as the second argument"); + } - switch (propertyVal.getString()) { - 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()); - Team.CollisionRule collisionRule = Team.CollisionRule.byName(settingVal.getString()); - if(collisionRule == null) throw new InternalExpressionException("Unknown value for property " + propertyVal.getString() + ": " + settingVal.getString()); + switch (propertyVal.getString()) + { + 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()); + } + final 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.getColor().getName()); - if(!(settingVal instanceof StringValue)) throw new InternalExpressionException("'team_property' requires a string as the third argument for the property " + propertyVal.getString()); - ChatFormatting color = ChatFormatting.getByName(settingVal.getString().toUpperCase()); - if(color == null || !color.isColor()) throw new InternalExpressionException("Unknown value for property " + propertyVal.getString() + ": " + settingVal.getString()); + } + case "color" -> { + if (!modifying) + { + return new StringValue(team.getColor().getName()); + } + if (!(settingVal instanceof StringValue)) + { + throw new InternalExpressionException("'team_property' requires a string as the third argument for the property " + propertyVal.getString()); + } + final 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.getDeathMessageVisibility().name); - if(!(settingVal instanceof StringValue)) throw new InternalExpressionException("'team_property' requires a string as the third argument for the property " + propertyVal.getString()); - Team.Visibility deathMessageVisibility = Team.Visibility.byName(settingVal.getString()); - if(deathMessageVisibility == null) throw new InternalExpressionException("Unknown value for property " + propertyVal.getString() + ": " + settingVal.getString()); + } + case "deathMessageVisibility" -> { + 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()); + } + final Team.Visibility deathMessageVisibility = Team.Visibility.byName(settingVal.getString()); + if (deathMessageVisibility == null) + { + throw new InternalExpressionException("Unknown value for property " + propertyVal.getString() + ": " + settingVal.getString()); + } 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()); - Component displayName; - displayName = FormattedTextValue.getTextByValue(settingVal); - team.setDisplayName(displayName); - break; - case "friendlyFire": - 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.setAllowFriendlyFire(friendlyFire); - break; - case "nametagVisibility": - 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()); - Team.Visibility nametagVisibility = Team.Visibility.byName(settingVal.getString()); - if(nametagVisibility == null) throw new InternalExpressionException("Unknown value for property " + propertyVal.getString() + ": " + settingVal.getString()); + } + 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()); + } + team.setDisplayName(FormattedTextValue.getTextByValue(settingVal)); + } + case "friendlyFire" -> { + 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()); + } + team.setAllowFriendlyFire(settingVal.getBoolean()); + } + case "nametagVisibility" -> { + 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()); + } + final Team.Visibility nametagVisibility = Team.Visibility.byName(settingVal.getString()); + if (nametagVisibility == null) + { + throw new InternalExpressionException("Unknown value for property " + propertyVal.getString() + ": " + settingVal.getString()); + } team.setNameTagVisibility(nametagVisibility); - - break; - case "prefix": - 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()); - Component prefix; - prefix = FormattedTextValue.getTextByValue(settingVal); - team.setPlayerPrefix(prefix); - break; - case "seeFriendlyInvisibles": - 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.setSeeFriendlyInvisibles(seeFriendlyInvisibles); - break; - case "suffix": - 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()); - Component suffix; - suffix = FormattedTextValue.getTextByValue(settingVal); - team.setPlayerSuffix(suffix); - break; - default: - throw new InternalExpressionException("team property '" + propertyVal.getString() + "' is not a valid property"); + } + case "prefix" -> { + 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()); + } + team.setPlayerPrefix(FormattedTextValue.getTextByValue(settingVal)); + } + case "seeFriendlyInvisibles" -> { + 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()); + } + team.setSeeFriendlyInvisibles(settingVal.getBoolean()); + } + case "suffix" -> { + 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()); + } + team.setPlayerSuffix(FormattedTextValue.getTextByValue(settingVal)); + } + default -> throw new InternalExpressionException("team property '" + propertyVal.getString() + "' is not a valid property"); } return Value.TRUE; }); expression.addContextFunction("bossbar", -1, (c, t, lv) -> { - CustomBossEvents bossBarManager = ((CarpetContext)c).server().getCustomBossEvents(); - if(lv.size() > 3) throw new InternalExpressionException("'bossbar' accepts max three arguments"); + final CustomBossEvents bossBarManager = ((CarpetContext) c).server().getCustomBossEvents(); + if (lv.size() > 3) + { + throw new InternalExpressionException("'bossbar' accepts max three arguments"); + } - if(lv.size() == 0) return ListValue.wrap(bossBarManager.getEvents().stream().map(CustomBossEvent::getTextId).map(ResourceLocation::toString).map(StringValue::of)); + if (lv.size() == 0) + { + return ListValue.wrap(bossBarManager.getEvents().stream().map(CustomBossEvent::getTextId).map(ResourceLocation::toString).map(StringValue::of)); + } - String id = lv.get(0).getString(); - ResourceLocation identifier; - identifier = InputValidator.identifierOf(id); + final String id = lv.get(0).getString(); + final ResourceLocation identifier = InputValidator.identifierOf(id); - if(lv.size() == 1) + if (lv.size() == 1) { - if(bossBarManager.get(identifier) != null) return Value.FALSE; - return StringValue.of(bossBarManager.create(identifier,Component.literal(id)).getTextId().toString()); + if (bossBarManager.get(identifier) != null) + { + return Value.FALSE; + } + return StringValue.of(bossBarManager.create(identifier, Component.literal(id)).getTextId().toString()); } - String property = lv.get(1).getString(); + final String property = lv.get(1).getString(); - CustomBossEvent bossBar = bossBarManager.get(identifier); - if(bossBar == null) return Value.NULL; + final CustomBossEvent bossBar = bossBarManager.get(identifier); + if (bossBar == null) + { + return Value.NULL; + } - Value propertyValue = (lv.size() == 3)?lv.get(2):null; + final Value propertyValue = (lv.size() == 3) ? lv.get(2) : null; - switch (property) { - case "color": - if(propertyValue == null) { - BossEvent.BossBarColor color = (bossBar).getColor(); - if(color == null) return Value.NULL; - return StringValue.of(color.getName()); + switch (property) + { + case "color" -> { + if (propertyValue == null) + { + final BossEvent.BossBarColor color = (bossBar).getColor(); + return color == null ? Value.NULL : StringValue.of(color.getName()); + } + final BossEvent.BossBarColor color = BossEvent.BossBarColor.byName(propertyValue.getString()); + if (color == null) + { + return Value.NULL; } - - BossEvent.BossBarColor color = BossEvent.BossBarColor.byName(propertyValue.getString()); - if(color == null) return Value.NULL; bossBar.setColor(BossEvent.BossBarColor.byName(propertyValue.getString())); return Value.TRUE; - case "max": - 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.setMax(((NumericValue) propertyValue).getInt()); + } + case "max" -> { + if (propertyValue == null) + { + return NumericValue.of(bossBar.getMax()); + } + if (!(propertyValue instanceof final NumericValue number)) + { + throw new InternalExpressionException("'bossbar' requires a number as the value for the property " + property); + } + bossBar.setMax(number.getInt()); return Value.TRUE; - case "name": - if(propertyValue == null) return new FormattedTextValue(bossBar.getName()); - + } + case "name" -> { + if (propertyValue == null) + { + return new FormattedTextValue(bossBar.getName()); + } bossBar.setName(FormattedTextValue.getTextByValue(propertyValue)); return Value.TRUE; - case "add_player": - if(propertyValue == null) throw new InternalExpressionException("Bossbar property " + property + " can't be queried, add a third parameter"); - - if(propertyValue instanceof ListValue) { - ((ListValue) propertyValue).getItems().forEach((v)->{ - ServerPlayer player = EntityValue.getPlayerByValue(((CarpetContext)c).server(), propertyValue); - if(player != null) bossBar.addPlayer(player); + } + case "add_player" -> { + if (propertyValue == null) + { + throw new InternalExpressionException("Bossbar property " + property + " can't be queried, add a third parameter"); + } + if (propertyValue instanceof final ListValue list) + { + list.getItems().forEach((v) -> { + final ServerPlayer player = EntityValue.getPlayerByValue(((CarpetContext) c).server(), propertyValue); + if (player != null) + { + bossBar.addPlayer(player); + } }); return Value.TRUE; } - - ServerPlayer player = EntityValue.getPlayerByValue(((CarpetContext) c).server(), propertyValue); - if(player != null) { + final ServerPlayer player = EntityValue.getPlayerByValue(((CarpetContext) c).server(), propertyValue); + if (player != null) + { bossBar.addPlayer(player); return Value.TRUE; } return Value.FALSE; - case "players": - if (propertyValue == null) return ListValue.wrap(bossBar.getPlayers().stream().map(EntityValue::new)); - if(propertyValue instanceof ListValue) + } + case "players" -> { + if (propertyValue == null) + { + return ListValue.wrap(bossBar.getPlayers().stream().map(EntityValue::new)); + } + if (propertyValue instanceof final ListValue list) { bossBar.removeAllPlayers(); - ((ListValue) propertyValue).getItems().forEach((v) -> { + list.getItems().forEach(v -> { ServerPlayer p = EntityValue.getPlayerByValue(((CarpetContext) c).server(), v); - if (p != null) bossBar.addPlayer(p); + if (p != null) + { + bossBar.addPlayer(p); + } }); return Value.TRUE; } - - - ServerPlayer p = EntityValue.getPlayerByValue(((CarpetContext) c).server(), propertyValue); + final ServerPlayer p = EntityValue.getPlayerByValue(((CarpetContext) c).server(), propertyValue); bossBar.removeAllPlayers(); - if (p != null) { + if (p != null) + { bossBar.addPlayer(p); return Value.TRUE; } return Value.FALSE; - case "style": - 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); + } + case "style" -> { + if (propertyValue == null) + { + return StringValue.of(bossBar.getOverlay().getName()); + } + final 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.setOverlay(style); return Value.TRUE; - case "value": - if(propertyValue == null) return NumericValue.of(bossBar.getValue()); - - if(!(propertyValue instanceof NumericValue)) throw new InternalExpressionException("'bossbar' requires a number as the value for the property " + property); - bossBar.setValue(((NumericValue) propertyValue).getInt()); + } + case "value" -> { + if (propertyValue == null) + { + return NumericValue.of(bossBar.getValue()); + } + if (!(propertyValue instanceof final NumericValue number)) + { + throw new InternalExpressionException("'bossbar' requires a number as the value for the property " + property); + } + bossBar.setValue(number.getInt()); return Value.TRUE; - case "visible": - if(propertyValue == null) return BooleanValue.of(bossBar.isVisible()); - + } + case "visible" -> { + if (propertyValue == null) + { + return BooleanValue.of(bossBar.isVisible()); + } bossBar.setVisible(propertyValue.getBoolean()); return Value.TRUE; - case "remove": + } + case "remove" -> { bossBarManager.remove(bossBar); return Value.TRUE; - default: - throw new InternalExpressionException("Unknown bossbar property " + property); + } + default -> throw new InternalExpressionException("Unknown bossbar property " + property); } }); } diff --git a/src/main/java/carpet/script/api/Threading.java b/src/main/java/carpet/script/api/Threading.java index 54f55c5622..eef2531757 100644 --- a/src/main/java/carpet/script/api/Threading.java +++ b/src/main/java/carpet/script/api/Threading.java @@ -16,21 +16,28 @@ public static void apply(Expression expression) { //"overidden" native call to cancel if on main thread expression.addContextFunction("task_join", 1, (c, t, lv) -> { - if (((CarpetContext)c).server().isSameThread()) + if (((CarpetContext) c).server().isSameThread()) + { throw new InternalExpressionException("'task_join' cannot be called from main thread to avoid deadlocks"); - Value v = lv.get(0); - if (!(v instanceof ThreadValue)) + } + final Value v = lv.get(0); + if (!(v instanceof final ThreadValue tv)) + { throw new InternalExpressionException("'task_join' could only be used with a task value"); - return ((ThreadValue) v).join(); + } + return tv.join(); }); // has to be lazy due to deferred execution of the expression - expression.addLazyFunctionWithDelegation("task_dock", 1, false,true, (c, t, expr, tok, lv) -> { - CarpetContext cc = (CarpetContext)c; - MinecraftServer server = cc.server(); - if (server.isSameThread()) return lv.get(0); // pass through for on thread tasks - Value[] result = new Value[]{Value.NULL}; - RuntimeException[] internal = new RuntimeException[]{null}; + expression.addLazyFunctionWithDelegation("task_dock", 1, false, true, (c, t, expr, tok, lv) -> { + final CarpetContext cc = (CarpetContext) c; + final MinecraftServer server = cc.server(); + if (server.isSameThread()) + { + return lv.get(0); // pass through for on thread tasks + } + final Value[] result = new Value[]{Value.NULL}; + final RuntimeException[] internal = new RuntimeException[]{null}; try { ((CarpetContext) c).server().executeBlocking(() -> @@ -39,22 +46,22 @@ public static void apply(Expression expression) { result[0] = lv.get(0).evalValue(c, t); } - catch (ExpressionException exc) + catch (final ExpressionException exc) { internal[0] = exc; } - catch (InternalExpressionException exc) + catch (final InternalExpressionException exc) { internal[0] = new ExpressionException(c, expr, tok, exc.getMessage(), exc.stack); } - catch (ArithmeticException exc) + catch (final ArithmeticException exc) { - internal[0] = new ExpressionException(c, expr, tok, "Your math is wrong, "+exc.getMessage()); + internal[0] = new ExpressionException(c, expr, tok, "Your math is wrong, " + exc.getMessage()); } }); } - catch (CompletionException exc) + catch (final CompletionException exc) { throw new InternalExpressionException("Error while executing docked task section, internal stack trace is gone"); } @@ -62,7 +69,7 @@ public static void apply(Expression expression) { throw internal[0]; } - Value ret = result[0]; // preventing from lazy evaluating of the result in case a future completes later + final Value ret = result[0]; // preventing from lazy evaluating of the result in case a future completes later return (_c, _t) -> ret; // pass through placeholder // implmenetation should dock the task on the main thread. diff --git a/src/main/java/carpet/script/api/WorldAccess.java b/src/main/java/carpet/script/api/WorldAccess.java index 44d3d5e8e9..5900a3eeb5 100644 --- a/src/main/java/carpet/script/api/WorldAccess.java +++ b/src/main/java/carpet/script/api/WorldAccess.java @@ -137,112 +137,116 @@ import static carpet.script.utils.WorldTools.canHasChunk; -public class WorldAccess { +public class WorldAccess +{ private static final Map DIRECTION_MAP = Arrays.stream(Direction.values()).collect(Collectors.toMap(Direction::getName, (direction) -> direction)); - static { + + static + { DIRECTION_MAP.put("y", Direction.UP); DIRECTION_MAP.put("z", Direction.SOUTH); DIRECTION_MAP.put("x", Direction.EAST); - } + private static final Map> ticketTypes = Map.of( - "portal", TicketType.PORTAL, - "teleport", TicketType.POST_TELEPORT, - "unknown", TicketType.UNKNOWN + "portal", TicketType.PORTAL, + "teleport", TicketType.POST_TELEPORT, + "unknown", TicketType.UNKNOWN ); // dummy entity for dummy requirements in the loot tables (see snowball) private static FallingBlockEntity DUMMY_ENTITY = null; + private static Value booleanStateTest( - Context c, - String name, - List params, - BiPredicate test + final Context c, + final String name, + final List params, + final BiPredicate test ) { - CarpetContext cc = (CarpetContext) c; + final CarpetContext cc = (CarpetContext) c; if (params.size() == 0) + { throw new InternalExpressionException("'" + name + "' requires at least one parameter"); - Value v0 = params.get(0); - if (v0 instanceof BlockValue) - return BooleanValue.of(test.test(((BlockValue) v0).getBlockState(), ((BlockValue) v0).getPos())); - BlockValue block = BlockArgument.findIn(cc, params, 0).block; + } + if (params.get(0) instanceof final BlockValue bv) + { + return BooleanValue.of(test.test(bv.getBlockState(), bv.getPos())); + } + final BlockValue block = BlockArgument.findIn(cc, params, 0).block; return BooleanValue.of(test.test(block.getBlockState(), block.getPos())); } private static Value stateStringQuery( - Context c, - String name, - List params, - BiFunction test + final Context c, + final String name, + final List params, + final BiFunction test ) { - CarpetContext cc = (CarpetContext) c; + final CarpetContext cc = (CarpetContext) c; if (params.size() == 0) { throw new InternalExpressionException("'" + name + "' requires at least one parameter"); } - - Value v0 = params.get(0); - if (v0 instanceof BlockValue) + if (params.get(0) instanceof final BlockValue bv) { - String strVal = test.apply( ((BlockValue) v0).getBlockState(), ((BlockValue) v0).getPos()); - return StringValue.of(strVal); + return StringValue.of(test.apply(bv.getBlockState(), bv.getPos())); } - BlockValue block = BlockArgument.findIn(cc, params, 0).block; + final BlockValue block = BlockArgument.findIn(cc, params, 0).block; return StringValue.of(test.apply(block.getBlockState(), block.getPos())); } private static Value genericStateTest( - Context c, - String name, - List params, - Fluff.TriFunction test + final Context c, + final String name, + final List params, + final Fluff.TriFunction test ) { - CarpetContext cc = (CarpetContext) c; + final CarpetContext cc = (CarpetContext) c; if (params.size() == 0) + { throw new InternalExpressionException("'" + name + "' requires at least one parameter"); - Value v0 = params.get(0); - if (v0 instanceof BlockValue) + } + if (params.get(0) instanceof final BlockValue bv) { try { - return test.apply(((BlockValue) v0).getBlockState(), ((BlockValue) v0).getPos(), cc.level()); + return test.apply(bv.getBlockState(), bv.getPos(), cc.level()); } - catch (NullPointerException ignored) + catch (final NullPointerException ignored) { throw new InternalExpressionException("'" + name + "' function requires a block that is positioned in the world"); } } - BlockValue block = BlockArgument.findIn(cc, params, 0).block; + final BlockValue block = BlockArgument.findIn(cc, params, 0).block; return test.apply(block.getBlockState(), block.getPos(), cc.level()); } - private static > BlockState setProperty(Property property, String name, String value, - BlockState bs) + private static > BlockState setProperty(final Property property, final String name, final String value, + final BlockState bs) { - Optional optional = property.getValue(value); - - if (optional.isPresent()) - { - bs = bs.setValue(property, optional.get()); - } - else + final Optional optional = property.getValue(value); + if (optional.isEmpty()) { throw new InternalExpressionException(value + " is not a valid value for property " + name); } - return bs; + return bs.setValue(property, optional.get()); } - private static void nullCheck(Value v, String name) { - if (v.isNull()) { + private static void nullCheck(final Value v, final String name) + { + if (v.isNull()) + { throw new IllegalArgumentException(name + " cannot be null"); } } - private static float numberGetOrThrow(Value v) { - double num = v.readDoubleNumber(); - if (Double.isNaN(num)) { + private static float numberGetOrThrow(final Value v) + { + final double num = v.readDoubleNumber(); + if (Double.isNaN(num)) + { throw new IllegalArgumentException(v.getString() + " needs to be a numeric value"); } return (float) num; @@ -252,20 +256,20 @@ private static void BooYah(final ServerLevel level) { synchronized (level) { - ((ChunkGeneratorInterface)level.getChunkSource().getGenerator()).initStrongholds(level); + ((ChunkGeneratorInterface) level.getChunkSource().getGenerator()).initStrongholds(level); } } - public static void apply(Expression expression) + public static void apply(final Expression expression) { expression.addContextFunction("block", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext) c; + final CarpetContext cc = (CarpetContext) c; if (lv.size() == 0) { throw new InternalExpressionException("Block requires at least one parameter"); } - BlockValue retval = BlockArgument.findIn(cc, lv, 0, true).block; + final BlockValue retval = BlockArgument.findIn(cc, lv, 0, true).block; // fixing block state and data retval.getBlockState(); retval.getData(); @@ -275,80 +279,94 @@ public static void apply(Expression expression) expression.addContextFunction("block_data", -1, (c, t, lv) -> { if (lv.size() == 0) + { throw new InternalExpressionException("Block requires at least one parameter"); - CompoundTag tag = BlockArgument.findIn( (CarpetContext) c, lv, 0, true).block.getData(); - return NBTSerializableValue.of(tag); + } + return NBTSerializableValue.of(BlockArgument.findIn((CarpetContext) c, lv, 0, true).block.getData()); }); // poi_get(pos, radius?, type?, occupation?, column_mode?) expression.addContextFunction("poi", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext) c; - if (lv.size() == 0) throw new InternalExpressionException("'poi' requires at least one parameter"); - BlockArgument locator = BlockArgument.findIn(cc, lv, 0, false); - BlockPos pos = locator.block.getPos(); - PoiManager store = cc.level().getPoiManager(); - Registry poiReg = cc.registry(Registries.POINT_OF_INTEREST_TYPE); + final CarpetContext cc = (CarpetContext) c; + if (lv.size() == 0) + { + throw new InternalExpressionException("'poi' requires at least one parameter"); + } + final BlockArgument locator = BlockArgument.findIn(cc, lv, 0, false); + final BlockPos pos = locator.block.getPos(); + final PoiManager store = cc.level().getPoiManager(); + final Registry poiReg = cc.registry(Registries.POINT_OF_INTEREST_TYPE); if (lv.size() == locator.offset) { - Optional> foo = store.getType(pos); - if (foo.isEmpty()) return Value.NULL; - PoiType poiType = foo.get().value(); + final Optional> foo = store.getType(pos); + if (foo.isEmpty()) + { + return Value.NULL; + } + final PoiType poiType = foo.get().value(); // this feels wrong, but I don't want to mix-in more than I really need to. // also distance adds 0.5 to each point which screws up accurate distance calculations // you shoudn't be using POI with that in mind anyways, so I am not worried about it. - PoiRecord poi = store.getInRange( + final PoiRecord poi = store.getInRange( type -> type.value() == poiType, pos, 1, PoiManager.Occupancy.ANY ).filter(p -> p.getPos().equals(pos)).findFirst().orElse(null); - if (poi == null) - return Value.NULL; - return ListValue.of( + return poi == null ? Value.NULL : ListValue.of( ValueConversions.of(poiReg.getKey(poi.getPoiType().value())), - new NumericValue(poiType.maxTickets() - ((PoiRecord_scarpetMixin)poi).getFreeTickets()) + new NumericValue(poiType.maxTickets() - ((PoiRecord_scarpetMixin) poi).getFreeTickets()) ); } - int radius = NumericValue.asNumber(lv.get(locator.offset+0)).getInt(); - if (radius < 0) return ListValue.of(); + final int radius = NumericValue.asNumber(lv.get(locator.offset + 0)).getInt(); + if (radius < 0) + { + return ListValue.of(); + } Predicate> condition = p -> true; PoiManager.Occupancy status = PoiManager.Occupancy.ANY; boolean inColumn = false; if (locator.offset + 1 < lv.size()) { - String poiType = lv.get(locator.offset+1).getString().toLowerCase(Locale.ROOT); + final String poiType = lv.get(locator.offset + 1).getString().toLowerCase(Locale.ROOT); if (!"any".equals(poiType)) { - PoiType type = poiReg.getOptional(InputValidator.identifierOf(poiType)) + final PoiType type = poiReg.getOptional(InputValidator.identifierOf(poiType)) .orElseThrow(() -> new ThrowStatement(poiType, Throwables.UNKNOWN_POI)); condition = (tt) -> tt.value() == type; } if (locator.offset + 2 < lv.size()) { - String statusString = lv.get(locator.offset+2).getString().toLowerCase(Locale.ROOT); + final String statusString = lv.get(locator.offset + 2).getString().toLowerCase(Locale.ROOT); if ("occupied".equals(statusString)) + { status = PoiManager.Occupancy.IS_OCCUPIED; + } else if ("available".equals(statusString)) + { status = PoiManager.Occupancy.HAS_SPACE; + } else if (!("any".equals(statusString))) + { throw new InternalExpressionException( - "Incorrect POI occupation status "+status+ " use `any`, " + "`occupied` or `available`" + "Incorrect POI occupation status " + status + " use `any`, " + "`occupied` or `available`" ); + } if (locator.offset + 3 < lv.size()) { - inColumn = lv.get(locator.offset+3).getBoolean(); + inColumn = lv.get(locator.offset + 3).getBoolean(); } } } - Stream pois = inColumn? - store.getInSquare(condition, pos, radius, status): + final Stream pois = inColumn ? + store.getInSquare(condition, pos, radius, status) : store.getInRange(condition, pos, radius, status); return ListValue.wrap(pois.sorted(Comparator.comparingDouble(p -> p.getPos().distSqr(pos))).map(p -> ListValue.of( ValueConversions.of(poiReg.getKey(p.getPoiType().value())), - new NumericValue(p.getPoiType().value().maxTickets() - ((PoiRecord_scarpetMixin)p).getFreeTickets()), + new NumericValue(p.getPoiType().value().maxTickets() - ((PoiRecord_scarpetMixin) p).getFreeTickets()), ValueConversions.of(p.getPos()) ) )); @@ -357,98 +375,100 @@ else if (!("any".equals(statusString))) //poi_set(pos, null) poi_set(pos, type, occupied?, expression.addContextFunction("set_poi", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext) c; - if (lv.size() == 0) throw new InternalExpressionException("'set_poi' requires at least one parameter"); - BlockArgument locator = BlockArgument.findIn(cc, lv, 0, false); - BlockPos pos = locator.block.getPos(); - if (lv.size() < locator.offset) throw new InternalExpressionException("'set_poi' requires the new poi type or null, after position argument"); - Value poi = lv.get(locator.offset+0); - PoiManager store = cc.level().getPoiManager(); + final CarpetContext cc = (CarpetContext) c; + if (lv.size() == 0) + { + throw new InternalExpressionException("'set_poi' requires at least one parameter"); + } + final BlockArgument locator = BlockArgument.findIn(cc, lv, 0, false); + final BlockPos pos = locator.block.getPos(); + if (lv.size() < locator.offset) + { + throw new InternalExpressionException("'set_poi' requires the new poi type or null, after position argument"); + } + final Value poi = lv.get(locator.offset + 0); + final PoiManager store = cc.level().getPoiManager(); if (poi.isNull()) { // clear poi information - if (!store.getType(pos).isPresent()) return Value.FALSE; + if (store.getType(pos).isEmpty()) + { + return Value.FALSE; + } store.remove(pos); return Value.TRUE; } - String poiTypeString = poi.getString().toLowerCase(Locale.ROOT); - ResourceLocation resource = InputValidator.identifierOf(poiTypeString); - Registry poiReg = cc.registry(Registries.POINT_OF_INTEREST_TYPE); - PoiType type = poiReg.getOptional(resource) + final String poiTypeString = poi.getString().toLowerCase(Locale.ROOT); + final ResourceLocation resource = InputValidator.identifierOf(poiTypeString); + final Registry poiReg = cc.registry(Registries.POINT_OF_INTEREST_TYPE); + final PoiType type = poiReg.getOptional(resource) .orElseThrow(() -> new ThrowStatement(poiTypeString, Throwables.UNKNOWN_POI)); - Holder holder = poiReg.getHolderOrThrow(ResourceKey.create(Registries.POINT_OF_INTEREST_TYPE, resource)); + final Holder holder = poiReg.getHolderOrThrow(ResourceKey.create(Registries.POINT_OF_INTEREST_TYPE, resource)); int occupancy = 0; if (locator.offset + 1 < lv.size()) { - occupancy = (int)NumericValue.asNumber(lv.get(locator.offset + 1)).getLong(); - if (occupancy < 0) throw new InternalExpressionException("Occupancy cannot be negative"); + occupancy = (int) NumericValue.asNumber(lv.get(locator.offset + 1)).getLong(); + if (occupancy < 0) + { + throw new InternalExpressionException("Occupancy cannot be negative"); + } + } + if (store.getType(pos).isPresent()) + { + store.remove(pos); } - if (store.getType(pos).isPresent()) store.remove(pos); store.add(pos, holder); // setting occupancy for a // again - don't want to mix in unnecessarily - peeps not gonna use it that often so not worries about it. if (occupancy > 0) { - int finalO = occupancy; - store.getInSquare((tt) -> tt.value()==type, pos, 1, PoiManager.Occupancy.ANY + final int finalO = occupancy; + store.getInSquare((tt) -> tt.value() == type, pos, 1, PoiManager.Occupancy.ANY ).filter(p -> p.getPos().equals(pos)).findFirst().ifPresent(p -> { - for (int i=0; i < finalO; i++) ((PoiRecord_scarpetMixin)p).callAcquireTicket(); + for (int i = 0; i < finalO; i++) + { + ((PoiRecord_scarpetMixin) p).callAcquireTicket(); + } }); } return Value.TRUE; }); - expression.addContextFunction("weather",-1,(c, t, lv) -> { - ServerLevel world = ((CarpetContext) c).level(); + expression.addContextFunction("weather", -1, (c, t, lv) -> { + final ServerLevel world = ((CarpetContext) c).level(); - if(lv.size()==0)//cos it can thunder when raining or when clear. + if (lv.size() == 0)//cos it can thunder when raining or when clear. + { return new StringValue(world.isThundering() ? "thunder" : (world.isRaining() ? "rain" : "clear")); + } - Value weather = lv.get(0); - ServerLevelData worldProperties = ((ServerWorldInterface) world).getWorldPropertiesCM(); - if(lv.size()==1) - { - int ticks; - switch (weather.getString().toLowerCase(Locale.ROOT)) { - case "clear": - ticks = worldProperties.getClearWeatherTime(); - break; - case "rain": - ticks = world.isRaining()? worldProperties.getRainTime():0;//cos if not it gives 1 for some reason - break; - case "thunder": - ticks = world.isThundering()? worldProperties.getThunderTime():0;//same dealio here - break; - default: - throw new InternalExpressionException("Weather can only be 'clear', 'rain' or 'thunder'"); - } - return new NumericValue(ticks); + final Value weather = lv.get(0); + final ServerLevelData worldProperties = ((ServerWorldInterface) world).getWorldPropertiesCM(); + if (lv.size() == 1) + { + return new NumericValue(switch (weather.getString().toLowerCase(Locale.ROOT)) + { + case "clear" -> worldProperties.getClearWeatherTime(); + case "rain" -> world.isRaining() ? worldProperties.getRainTime() : 0;//cos if not it gives 1 for some reason + case "thunder" -> world.isThundering() ? worldProperties.getThunderTime() : 0;//same dealio here + default -> throw new InternalExpressionException("Weather can only be 'clear', 'rain' or 'thunder'"); + }); } - if(lv.size()==2) + if (lv.size() == 2) { - int ticks = NumericValue.asNumber(lv.get(1), "tick_time in 'weather'").getInt(); + final int ticks = NumericValue.asNumber(lv.get(1), "tick_time in 'weather'").getInt(); switch (weather.getString().toLowerCase(Locale.ROOT)) { - case "clear": - world.setWeatherParameters(ticks,0,false,false); - break; - - case "rain": - world.setWeatherParameters(0,ticks,true,false); - break; - - case "thunder": - world.setWeatherParameters( - 0, - ticks,//this is used to set thunder time, idk why... - true, - true - ); - break; - - default: - throw new InternalExpressionException("Weather can only be 'clear', 'rain' or 'thunder'"); + case "clear" -> world.setWeatherParameters(ticks, 0, false, false); + case "rain" -> world.setWeatherParameters(0, ticks, true, false); + case "thunder" -> world.setWeatherParameters( + 0, + ticks,//this is used to set thunder time, idk why... + true, + true + ); + default -> throw new InternalExpressionException("Weather can only be 'clear', 'rain' or 'thunder'"); } return NumericValue.of(ticks); } @@ -457,41 +477,47 @@ else if (!("any".equals(statusString))) expression.addUnaryFunction("pos", v -> { - if (v instanceof BlockValue) + if (v instanceof final BlockValue bv) { - BlockPos pos = ((BlockValue) v).getPos(); + final BlockPos pos = bv.getPos(); if (pos == null) + { throw new InternalExpressionException("Cannot fetch position of an unrealized block"); + } return ValueConversions.of(pos); } - else if (v instanceof EntityValue) + if (v instanceof final EntityValue ev) { - Entity e = ((EntityValue) v).getEntity(); + final Entity e = ev.getEntity(); if (e == null) + { throw new InternalExpressionException("Null entity"); + } return ValueConversions.of(e.position()); } - else - { - throw new InternalExpressionException("'pos' works only with a block or an entity type"); - } + throw new InternalExpressionException("'pos' works only with a block or an entity type"); }); expression.addContextFunction("pos_offset", -1, (c, t, lv) -> { - BlockArgument locator = BlockArgument.findIn((CarpetContext)c, lv, 0); - BlockPos pos = locator.block.getPos(); + final BlockArgument locator = BlockArgument.findIn((CarpetContext) c, lv, 0); + final BlockPos pos = locator.block.getPos(); if (lv.size() <= locator.offset) + { throw new InternalExpressionException("'pos_offset' needs at least position, and direction"); - String directionString = lv.get(locator.offset).getString(); - Direction dir = DIRECTION_MAP.get(directionString); + } + final String directionString = lv.get(locator.offset).getString(); + final Direction dir = DIRECTION_MAP.get(directionString); if (dir == null) - throw new InternalExpressionException("Unknown direction: "+directionString); + { + throw new InternalExpressionException("Unknown direction: " + directionString); + } int howMuch = 1; - if (lv.size() > locator.offset+1) - howMuch = (int) NumericValue.asNumber(lv.get(locator.offset+1)).getLong(); - BlockPos retpos = pos.relative(dir, howMuch); - return ValueConversions.of(retpos); + if (lv.size() > locator.offset + 1) + { + howMuch = (int) NumericValue.asNumber(lv.get(locator.offset + 1)).getLong(); + } + return ValueConversions.of(pos.relative(dir, howMuch)); }); expression.addContextFunction("solid", -1, (c, t, lv) -> @@ -544,33 +570,32 @@ else if (v instanceof EntityValue) expression.addContextFunction("in_slime_chunk", -1, (c, t, lv) -> { - BlockPos pos = BlockArgument.findIn((CarpetContext)c, lv, 0).block.getPos(); - ChunkPos chunkPos = new ChunkPos(pos); + final BlockPos pos = BlockArgument.findIn((CarpetContext) c, lv, 0).block.getPos(); + final ChunkPos chunkPos = new ChunkPos(pos); return BooleanValue.of(WorldgenRandom.seedSlimeChunk( chunkPos.x, chunkPos.z, - ((CarpetContext)c).level().getSeed(), + ((CarpetContext) c).level().getSeed(), 987234911L ).nextInt(10) == 0); }); expression.addContextFunction("top", -1, (c, t, lv) -> { - String type = lv.get(0).getString().toLowerCase(Locale.ROOT); - Heightmap.Types htype; - switch (type) + final String type = lv.get(0).getString().toLowerCase(Locale.ROOT); + final Heightmap.Types htype = switch (type) { //case "light": htype = Heightmap.Type.LIGHT_BLOCKING; break; //investigate - case "motion": htype = Heightmap.Types.MOTION_BLOCKING; break; - case "terrain": htype = Heightmap.Types.MOTION_BLOCKING_NO_LEAVES; break; - case "ocean_floor": htype = Heightmap.Types.OCEAN_FLOOR; break; - case "surface": htype = Heightmap.Types.WORLD_SURFACE; break; - default: throw new InternalExpressionException("Unknown heightmap type: "+type); - } - BlockArgument locator = BlockArgument.findIn((CarpetContext)c, lv, 1); - BlockPos pos = locator.block.getPos(); - int x = pos.getX(); - int z = pos.getZ(); - return new NumericValue(((CarpetContext)c).level().getChunk(x >> 4, z >> 4).getHeight(htype, x & 15, z & 15) + 1); + case "motion" -> Heightmap.Types.MOTION_BLOCKING; + case "terrain" -> Heightmap.Types.MOTION_BLOCKING_NO_LEAVES; + case "ocean_floor" -> Heightmap.Types.OCEAN_FLOOR; + case "surface" -> Heightmap.Types.WORLD_SURFACE; + default -> throw new InternalExpressionException("Unknown heightmap type: " + type); + }; + final BlockArgument locator = BlockArgument.findIn((CarpetContext) c, lv, 1); + final BlockPos pos = locator.block.getPos(); + final int x = pos.getX(); + final int z = pos.getZ(); + return new NumericValue(((CarpetContext) c).level().getChunk(x >> 4, z >> 4).getHeight(htype, x & 15, z & 15) + 1); }); expression.addContextFunction("loaded", -1, (c, t, lv) -> @@ -580,54 +605,56 @@ else if (v instanceof EntityValue) expression.addContextFunction("loaded_ep", -1, (c, t, lv) -> { c.host.issueDeprecation("loaded_ep(...)"); - BlockPos pos = BlockArgument.findIn((CarpetContext)c, lv, 0).block.getPos(); - return BooleanValue.of(((CarpetContext)c).level().isPositionEntityTicking(pos));// 1.17pre1 getChunkManager().shouldTickChunk(new ChunkPos(pos))); + final BlockPos pos = BlockArgument.findIn((CarpetContext) c, lv, 0).block.getPos(); + return BooleanValue.of(((CarpetContext) c).level().isPositionEntityTicking(pos)); }); expression.addContextFunction("loaded_status", -1, (c, t, lv) -> { - BlockPos pos = BlockArgument.findIn((CarpetContext)c, lv, 0).block.getPos(); - LevelChunk chunk = ((CarpetContext)c).level().getChunkSource().getChunk(pos.getX()>>4, pos.getZ()>>4, false); - if (chunk == null) return Value.ZERO; - return new NumericValue(chunk.getFullStatus().ordinal()); + final BlockPos pos = BlockArgument.findIn((CarpetContext) c, lv, 0).block.getPos(); + final LevelChunk chunk = ((CarpetContext) c).level().getChunkSource().getChunk(pos.getX() >> 4, pos.getZ() >> 4, false); + return chunk == null ? Value.ZERO : new NumericValue(chunk.getFullStatus().ordinal()); }); expression.addContextFunction("is_chunk_generated", -1, (c, t, lv) -> { - BlockArgument locator = BlockArgument.findIn((CarpetContext)c, lv, 0); - BlockPos pos = locator.block.getPos(); + final BlockArgument locator = BlockArgument.findIn((CarpetContext) c, lv, 0); + final BlockPos pos = locator.block.getPos(); boolean force = false; if (lv.size() > locator.offset) + { force = lv.get(locator.offset).getBoolean(); - return BooleanValue.of(canHasChunk(((CarpetContext)c).level(), new ChunkPos(pos), null, force)); + } + return BooleanValue.of(canHasChunk(((CarpetContext) c).level(), new ChunkPos(pos), null, force)); }); expression.addContextFunction("generation_status", -1, (c, t, lv) -> { - BlockArgument blockArgument = BlockArgument.findIn((CarpetContext)c, lv, 0); - BlockPos pos = blockArgument.block.getPos(); + final BlockArgument blockArgument = BlockArgument.findIn((CarpetContext) c, lv, 0); + final BlockPos pos = blockArgument.block.getPos(); boolean forceLoad = false; if (lv.size() > blockArgument.offset) + { forceLoad = lv.get(blockArgument.offset).getBoolean(); - ChunkAccess chunk = ((CarpetContext)c).level().getChunk(pos.getX()>>4, pos.getZ()>>4, ChunkStatus.EMPTY, forceLoad); - if (chunk == null) return Value.NULL; - return new StringValue(chunk.getStatus().getName()); + } + final ChunkAccess chunk = ((CarpetContext) c).level().getChunk(pos.getX() >> 4, pos.getZ() >> 4, ChunkStatus.EMPTY, forceLoad); + return chunk == null ? Value.NULL : new StringValue(chunk.getStatus().getName()); }); expression.addContextFunction("chunk_tickets", -1, (c, t, lv) -> { - ServerLevel world = ((CarpetContext) c).level(); - Long2ObjectOpenHashMap>> levelTickets = ( + final ServerLevel world = ((CarpetContext) c).level(); + final Long2ObjectOpenHashMap>> levelTickets = ( (ChunkTicketManagerInterface) ((ServerChunkManagerInterface) world.getChunkSource()) .getCMTicketManager() ).getTicketsByPosition(); - List res = new ArrayList<>(); + final List res = new ArrayList<>(); if (lv.size() == 0) { - for (long key : levelTickets.keySet()) + for (final long key : levelTickets.keySet()) { - ChunkPos chpos = new ChunkPos(key); - for (Ticket ticket : levelTickets.get(key)) + final ChunkPos chpos = new ChunkPos(key); + for (final Ticket ticket : levelTickets.get(key)) { res.add(ListValue.of( new StringValue(ticket.getType().toString()), @@ -640,12 +667,12 @@ else if (v instanceof EntityValue) } else { - BlockArgument blockArgument = BlockArgument.findIn((CarpetContext) c, lv, 0); - BlockPos pos = blockArgument.block.getPos(); - SortedArraySet> tickets = levelTickets.get(new ChunkPos(pos).toLong()); + final BlockArgument blockArgument = BlockArgument.findIn((CarpetContext) c, lv, 0); + final BlockPos pos = blockArgument.block.getPos(); + final SortedArraySet> tickets = levelTickets.get(new ChunkPos(pos).toLong()); if (tickets != null) { - for (Ticket ticket : tickets) + for (final Ticket ticket : tickets) { res.add(ListValue.of( new StringValue(ticket.getType().toString()), @@ -677,7 +704,7 @@ else if (v instanceof EntityValue) expression.addContextFunction("block_tick", -1, (c, t, lv) -> booleanStateTest(c, "block_tick", lv, (s, p) -> { - ServerLevel w = ((CarpetContext)c).level(); + final ServerLevel w = ((CarpetContext) c).level(); s.randomTick(w, p, w.random); return true; })); @@ -685,19 +712,24 @@ else if (v instanceof EntityValue) expression.addContextFunction("random_tick", -1, (c, t, lv) -> booleanStateTest(c, "random_tick", lv, (s, p) -> { - ServerLevel w = ((CarpetContext)c).level(); + final ServerLevel w = ((CarpetContext) c).level(); if (s.isRandomlyTicking() || s.getFluidState().isRandomlyTicking()) + { s.randomTick(w, p, w.random); + } return true; })); // lazy cause its parked execution expression.addLazyFunction("without_updates", 1, (c, t, lv) -> { - boolean previous = CarpetSettings.impendingFillSkipUpdates.get(); - if (previous) return lv.get(0); - Value [] result = new Value[]{Value.NULL}; - ((CarpetContext)c).server().executeBlocking( () -> + final boolean previous = CarpetSettings.impendingFillSkipUpdates.get(); + if (previous) + { + return lv.get(0); + } + final Value[] result = new Value[]{Value.NULL}; + ((CarpetContext) c).server().executeBlocking(() -> { try { @@ -706,7 +738,7 @@ else if (v instanceof EntityValue) } finally { - CarpetSettings.impendingFillSkipUpdates.set(previous); + CarpetSettings.impendingFillSkipUpdates.set(false); } }); return (cc, tt) -> result[0]; @@ -714,12 +746,12 @@ else if (v instanceof EntityValue) expression.addContextFunction("set", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext)c; - ServerLevel world = cc.level(); - BlockArgument targetLocator = BlockArgument.findIn(cc, lv, 0); - BlockArgument sourceLocator = BlockArgument.findIn(cc, lv, targetLocator.offset, true); + final CarpetContext cc = (CarpetContext) c; + final ServerLevel world = cc.level(); + final BlockArgument targetLocator = BlockArgument.findIn(cc, lv, 0); + final BlockArgument sourceLocator = BlockArgument.findIn(cc, lv, targetLocator.offset, true); BlockState sourceBlockState = sourceLocator.block.getBlockState(); - BlockState targetBlockState = world.getBlockState(targetLocator.block.getPos()); + final BlockState targetBlockState = world.getBlockState(targetLocator.block.getPos()); CompoundTag data = null; if (lv.size() > sourceLocator.offset) { @@ -728,74 +760,72 @@ else if (v instanceof EntityValue) { args.add(lv.get(i)); } - if (args.get(0) instanceof ListValue) + if (args.get(0) instanceof final ListValue list) { - if (args.size() == 2) + if (args.size() == 2 && NBTSerializableValue.fromValue(args.get(1)) instanceof final NBTSerializableValue nbtsv) { - Value dataValue = NBTSerializableValue.fromValue( args.get(1)); - if (dataValue instanceof NBTSerializableValue) - { - data = ((NBTSerializableValue) dataValue).getCompoundTag(); - } + data = nbtsv.getCompoundTag(); } - args = ((ListValue) args.get(0)).getItems(); + args = list.getItems(); } - else if (args.get(0) instanceof MapValue) + else if (args.get(0) instanceof final MapValue map) { - if (args.size() == 2) + if (args.size() == 2 && NBTSerializableValue.fromValue(args.get(1)) instanceof final NBTSerializableValue nbtsv) { - Value dataValue = NBTSerializableValue.fromValue( args.get(1)); - if (dataValue instanceof NBTSerializableValue) - { - data = ((NBTSerializableValue) dataValue).getCompoundTag(); - } + data = nbtsv.getCompoundTag(); } - Map state = ((MapValue) args.get(0)).getMap(); - List mapargs = new ArrayList<>(); - state.forEach( (k, v) -> {mapargs.add(k); mapargs.add(v);}); + final Map state = map.getMap(); + final List mapargs = new ArrayList<>(); + state.forEach((k, v) -> { + mapargs.add(k); + mapargs.add(v); + }); args = mapargs; } else { - if ((args.size() & 1) == 1) + if ((args.size() & 1) == 1 && NBTSerializableValue.fromValue(args.get(args.size() - 1)) instanceof final NBTSerializableValue nbtsv) { - Value dataValue = NBTSerializableValue.fromValue( args.get(args.size()-1)); - if (dataValue instanceof NBTSerializableValue) - { - data = ((NBTSerializableValue) dataValue).getCompoundTag(); - } + data = nbtsv.getCompoundTag(); } } - StateDefinition states = sourceBlockState.getBlock().getStateDefinition(); - for (int i = 0; i < args.size()-1; i += 2) + final StateDefinition states = sourceBlockState.getBlock().getStateDefinition(); + for (int i = 0; i < args.size() - 1; i += 2) { - String paramString = args.get(i).getString(); - Property property = states.getProperty(paramString); + final String paramString = args.get(i).getString(); + final Property property = states.getProperty(paramString); if (property == null) + { throw new InternalExpressionException("Property " + paramString + " doesn't apply to " + sourceLocator.block.getString()); - String paramValue = args.get(i + 1).getString(); + } + final String paramValue = args.get(i + 1).getString(); sourceBlockState = setProperty(property, paramString, paramValue, sourceBlockState); } } - if (data == null) data = sourceLocator.block.getData(); - CompoundTag finalData = data; + if (data == null) + { + data = sourceLocator.block.getData(); + } + final CompoundTag finalData = data; if (sourceBlockState == targetBlockState && data == null) + { return Value.FALSE; - BlockState finalSourceBlockState = sourceBlockState; - BlockPos targetPos = targetLocator.block.getPos(); - Boolean[] result = new Boolean[]{true}; - cc.server().executeBlocking( () -> + } + final BlockState finalSourceBlockState = sourceBlockState; + final BlockPos targetPos = targetLocator.block.getPos(); + final Boolean[] result = new Boolean[]{true}; + cc.server().executeBlocking(() -> { Clearable.tryClear(world.getBlockEntity(targetPos)); boolean success = world.setBlock(targetPos, finalSourceBlockState, 2); if (finalData != null) { - BlockEntity be = world.getBlockEntity(targetPos); + final BlockEntity be = world.getBlockEntity(targetPos); if (be != null) { - CompoundTag destTag = finalData.copy(); + final CompoundTag destTag = finalData.copy(); destTag.putInt("x", targetPos.getX()); destTag.putInt("y", targetPos.getY()); destTag.putInt("z", targetPos.getZ()); @@ -806,68 +836,84 @@ else if (args.get(0) instanceof MapValue) } result[0] = success; }); - if (!result[0]) return Value.FALSE; - return new BlockValue(finalSourceBlockState, world, targetLocator.block.getPos()); + return !result[0] ? Value.FALSE : new BlockValue(finalSourceBlockState, world, targetLocator.block.getPos()); }); expression.addContextFunction("destroy", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext)c; - ServerLevel world = cc.level(); - BlockArgument locator = BlockArgument.findIn(cc, lv, 0); - BlockState state = locator.block.getBlockState(); - if (state.isAir()) return Value.FALSE; - BlockPos where = locator.block.getPos(); - BlockEntity be = world.getBlockEntity(where); + final CarpetContext cc = (CarpetContext) c; + final ServerLevel world = cc.level(); + final BlockArgument locator = BlockArgument.findIn(cc, lv, 0); + final BlockState state = locator.block.getBlockState(); + if (state.isAir()) + { + return Value.FALSE; + } + final BlockPos where = locator.block.getPos(); + final BlockEntity be = world.getBlockEntity(where); long how = 0; Item item = Items.DIAMOND_PICKAXE; boolean playerBreak = false; if (lv.size() > locator.offset) { - Value val = lv.get(locator.offset); - if (val instanceof NumericValue) + final Value val = lv.get(locator.offset); + if (val instanceof final NumericValue number) { - how = ((NumericValue) val).getLong(); + how = number.getLong(); } else { playerBreak = true; - String itemString = val.getString(); + final String itemString = val.getString(); item = cc.registry(Registries.ITEM).getOptional(InputValidator.identifierOf(itemString)) .orElseThrow(() -> new ThrowStatement(itemString, Throwables.UNKNOWN_ITEM)); } } CompoundTag tag = null; - if (lv.size() > locator.offset+1) + if (lv.size() > locator.offset + 1) { - if (!playerBreak) throw new InternalExpressionException("tag is not necessary with 'destroy' with no item"); - Value tagValue = lv.get(locator.offset+1); + if (!playerBreak) + { + throw new InternalExpressionException("tag is not necessary with 'destroy' with no item"); + } + final Value tagValue = lv.get(locator.offset + 1); if (tagValue.isNull()) + { tag = null; - else if (tagValue instanceof NBTSerializableValue) - tag = ((NBTSerializableValue) tagValue).getCompoundTag(); + } + else if (tagValue instanceof final NBTSerializableValue nbtsv) + { + tag = nbtsv.getCompoundTag(); + } else { - NBTSerializableValue readTag = NBTSerializableValue.parseString(tagValue.getString(), true); - tag = readTag.getCompoundTag(); + tag = NBTSerializableValue.parseString(tagValue.getString(), true).getCompoundTag(); } } - ItemStack tool = new ItemStack(item, 1); + final ItemStack tool = new ItemStack(item, 1); if (tag != null) + { tool.setTag(tag); - if (playerBreak && state.getDestroySpeed(world, where) < 0.0) return Value.FALSE; - boolean removed = world.removeBlock(where, false); - if (!removed) return Value.FALSE; + } + if (playerBreak && state.getDestroySpeed(world, where) < 0.0) + { + return Value.FALSE; + } + final boolean removed = world.removeBlock(where, false); + if (!removed) + { + return Value.FALSE; + } world.levelEvent(null, 2001, where, Block.getId(state)); boolean toolBroke = false; boolean dropLoot = true; if (playerBreak) { - boolean isUsingEffectiveTool = !state.requiresCorrectToolForDrops() || tool.isCorrectToolForDrops(state); + final boolean isUsingEffectiveTool = !state.requiresCorrectToolForDrops() || tool.isCorrectToolForDrops(state); //postMine() durability from item classes - float hardness = state.getDestroySpeed(world, where); + final float hardness = state.getDestroySpeed(world, where); int damageAmount = 0; if ((item instanceof DiggerItem && hardness > 0.0) || item instanceof ShearsItem) { @@ -877,9 +923,11 @@ else if (item instanceof TridentItem || item instanceof SwordItem) { damageAmount = 2; } - toolBroke = damageAmount>0 && tool.hurt(damageAmount, world.getRandom(), null); + toolBroke = damageAmount > 0 && tool.hurt(damageAmount, world.getRandom(), null); if (!isUsingEffectiveTool) + { dropLoot = false; + } } if (dropLoot) @@ -891,125 +939,163 @@ else if (item instanceof TridentItem || item instanceof SwordItem) else { if (how > 0) + { tool.enchant(Enchantments.BLOCK_FORTUNE, (int) how); - if (DUMMY_ENTITY == null) DUMMY_ENTITY = new FallingBlockEntity(EntityType.FALLING_BLOCK, null); + } + if (DUMMY_ENTITY == null) + { + DUMMY_ENTITY = new FallingBlockEntity(EntityType.FALLING_BLOCK, null); + } Block.dropResources(state, world, where, be, DUMMY_ENTITY, tool); } } if (!playerBreak) // no tool info - block brokwn + { return Value.TRUE; + } if (toolBroke) + { return Value.NULL; - Tag outtag = tool.getTag(); - if (outtag == null) - return Value.TRUE; - return new NBTSerializableValue(() -> outtag); + } + final Tag outtag = tool.getTag(); + return outtag == null ? Value.TRUE : new NBTSerializableValue(() -> outtag); }); expression.addContextFunction("harvest", -1, (c, t, lv) -> { - if (lv.size()<2) + if (lv.size() < 2) + { throw new InternalExpressionException("'harvest' takes at least 2 parameters: entity and block, or position, to harvest"); - CarpetContext cc = (CarpetContext)c; - Level world = cc.level(); - Value entityValue = lv.get(0); - if (!(entityValue instanceof EntityValue)) + } + final CarpetContext cc = (CarpetContext) c; + final Level world = cc.level(); + final Value entityValue = lv.get(0); + if (!(entityValue instanceof final EntityValue ev)) + { return Value.FALSE; - Entity e = ((EntityValue) entityValue).getEntity(); - if (!(e instanceof ServerPlayer)) + } + final Entity e = ev.getEntity(); + if (!(e instanceof final ServerPlayer player)) + { return Value.FALSE; - ServerPlayer player = (ServerPlayer)e; - BlockArgument locator = BlockArgument.findIn(cc, lv, 1); - BlockPos where = locator.block.getPos(); - BlockState state = locator.block.getBlockState(); - Block block = state.getBlock(); + } + final BlockArgument locator = BlockArgument.findIn(cc, lv, 1); + final BlockPos where = locator.block.getPos(); + final BlockState state = locator.block.getBlockState(); + final Block block = state.getBlock(); boolean success = false; if (!((block == Blocks.BEDROCK || block == Blocks.BARRIER) && player.gameMode.isSurvival())) + { success = player.gameMode.destroyBlock(where); + } if (success) + { world.levelEvent(null, 2001, where, Block.getId(state)); + } return BooleanValue.of(success); }); expression.addContextFunction("create_explosion", -1, (c, t, lv) -> { if (lv.isEmpty()) + { throw new InternalExpressionException("'create_explosion' requires at least a position to explode"); - CarpetContext cc = (CarpetContext)c; + } + final CarpetContext cc = (CarpetContext) c; float powah = 4.0f; Explosion.BlockInteraction mode = Explosion.BlockInteraction.DESTROY; // should probably read the gamerule for default behaviour boolean createFire = false; Entity source = null; LivingEntity attacker = null; - Vector3Argument location = Vector3Argument.findIn(lv, 0, false, true); - Vec3 pos = location.vec; + final Vector3Argument location = Vector3Argument.findIn(lv, 0, false, true); + final Vec3 pos = location.vec; if (lv.size() > location.offset) { powah = NumericValue.asNumber(lv.get(location.offset), "explosion power").getFloat(); - if (powah < 0) throw new InternalExpressionException("Explosion power cannot be negative"); - if (lv.size() > location.offset+1) + if (powah < 0) { - String strval = lv.get(location.offset+1).getString(); - try { + throw new InternalExpressionException("Explosion power cannot be negative"); + } + if (lv.size() > location.offset + 1) + { + final String strval = lv.get(location.offset + 1).getString(); + try + { mode = Explosion.BlockInteraction.valueOf(strval.toUpperCase(Locale.ROOT)); } - catch (IllegalArgumentException ile) { throw new InternalExpressionException("Illegal explosions block behaviour: "+strval); } - if (lv.size() > location.offset+2) + catch (final IllegalArgumentException ile) + { + throw new InternalExpressionException("Illegal explosions block behaviour: " + strval); + } + if (lv.size() > location.offset + 2) { - createFire = lv.get(location.offset+2).getBoolean(); - if (lv.size() > location.offset+3) + createFire = lv.get(location.offset + 2).getBoolean(); + if (lv.size() > location.offset + 3) { - Value enVal= lv.get(location.offset+3); - if (enVal.isNull()) {} // is null already - else if (enVal instanceof EntityValue) + Value enVal = lv.get(location.offset + 3); + if (enVal.isNull()) { - source = ((EntityValue) enVal).getEntity(); + } // is null already + else if (enVal instanceof final EntityValue ev) + { + source = ev.getEntity(); } else { - throw new InternalExpressionException("Fourth parameter of the explosion has to be an entity, not "+enVal.getTypeString()); + throw new InternalExpressionException("Fourth parameter of the explosion has to be an entity, not " + enVal.getTypeString()); } - if (lv.size() > location.offset+4) + if (lv.size() > location.offset + 4) { - enVal = lv.get(location.offset+4); - if (enVal.isNull()) {} // is null already - else if (enVal instanceof EntityValue) + enVal = lv.get(location.offset + 4); + if (enVal.isNull()) + { + } // is null already + else if (enVal instanceof final EntityValue ev) { - Entity attackingEntity = ((EntityValue) enVal).getEntity(); - if (attackingEntity instanceof LivingEntity) + final Entity attackingEntity = ev.getEntity(); + if (attackingEntity instanceof final LivingEntity le) { - attacker = (LivingEntity) attackingEntity; + attacker = le; + } + else + { + throw new InternalExpressionException("Attacking entity needs to be a living thing, " + + ValueConversions.of(cc.registry(Registries.ENTITY_TYPE).getKey(attackingEntity.getType())).getString() + " ain't it."); } - else throw new InternalExpressionException("Attacking entity needs to be a living thing, "+ - ValueConversions.of(cc.registry(Registries.ENTITY_TYPE).getKey(attackingEntity.getType())).getString() +" ain't it."); - } else { - throw new InternalExpressionException("Fifth parameter of the explosion has to be a living entity, not "+enVal.getTypeString()); + throw new InternalExpressionException("Fifth parameter of the explosion has to be a living entity, not " + enVal.getTypeString()); } } } } } } - LivingEntity theAttacker = attacker; - float thePowah = powah; + final LivingEntity theAttacker = attacker; + final float thePowah = powah; // copy of ServerWorld.createExplosion #TRACK# - Explosion explosion = new Explosion(cc.level(), source, null, null, pos.x, pos.y, pos.z, powah, createFire, mode){ + final Explosion explosion = new Explosion(cc.level(), source, null, null, pos.x, pos.y, pos.z, powah, createFire, mode) + { @Override - public @Nullable LivingEntity getIndirectSourceEntity() { + public @Nullable LivingEntity getIndirectSourceEntity() + { return theAttacker; } }; explosion.explode(); explosion.finalizeExplosion(false); - if (mode == Explosion.BlockInteraction.KEEP) explosion.clearToBlow(); + if (mode == Explosion.BlockInteraction.KEEP) + { + explosion.clearToBlow(); + } cc.level().players().forEach(spe -> { if (spe.distanceToSqr(pos) < 4096.0D) + { spe.connection.send(new ClientboundExplodePacket(pos.x, pos.y, pos.z, thePowah, explosion.getToBlow(), explosion.getHitPlayers().get(spe))); + } }); return Value.TRUE; }); @@ -1017,37 +1103,38 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin // TODO rename to use_item expression.addContextFunction("place_item", -1, (c, t, lv) -> { - if (lv.size()<2) + if (lv.size() < 2) + { throw new InternalExpressionException("'place_item' takes at least 2 parameters: item and block, or position, to place onto"); - CarpetContext cc = (CarpetContext) c; - String itemString = lv.get(0).getString(); - Vector3Argument locator = Vector3Argument.findIn(lv, 1); - ItemInput stackArg = NBTSerializableValue.parseItem(itemString, cc.registryAccess()); - BlockPos where = new BlockPos(locator.vec); - String facing; - if (lv.size() > locator.offset) { - facing = lv.get(locator.offset).getString(); - } else { - // Paintings throw an exception if their direction is vertical, therefore we change the default here - facing = stackArg.getItem() != Items.PAINTING ? "up" : "north"; } + final CarpetContext cc = (CarpetContext) c; + final String itemString = lv.get(0).getString(); + final Vector3Argument locator = Vector3Argument.findIn(lv, 1); + final ItemInput stackArg = NBTSerializableValue.parseItem(itemString, cc.registryAccess()); + final BlockPos where = new BlockPos(locator.vec); + // Paintings throw an exception if their direction is vertical, therefore we change the default here + final String facing = lv.size() > locator.offset + ? lv.get(locator.offset).getString() + : stackArg.getItem() != Items.PAINTING ? "up" : "north"; boolean sneakPlace = false; - if (lv.size() > locator.offset+1) - sneakPlace = lv.get(locator.offset+1).getBoolean(); + if (lv.size() > locator.offset + 1) + { + sneakPlace = lv.get(locator.offset + 1).getBoolean(); + } - BlockValue.PlacementContext ctx; + final BlockValue.PlacementContext ctx; try { ctx = BlockValue.PlacementContext.from(cc.level(), where, facing, sneakPlace, stackArg.createItemStack(1, false)); } - catch (CommandSyntaxException e) + catch (final CommandSyntaxException e) { throw new InternalExpressionException(e.getMessage()); } - if (!(stackArg.getItem() instanceof BlockItem)) + if (!(stackArg.getItem() instanceof final BlockItem blockItem)) { - InteractionResult useResult = ctx.getItemInHand().useOn(ctx); + final InteractionResult useResult = ctx.getItemInHand().useOn(ctx); if (useResult == InteractionResult.CONSUME || useResult == InteractionResult.SUCCESS) { return Value.TRUE; @@ -1055,16 +1142,18 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin } else { // not sure we need special case for block items, since useOnBlock can do that as well - BlockItem blockItem = (BlockItem) stackArg.getItem(); - if (!ctx.canPlace()) return Value.FALSE; - BlockState placementState = blockItem.getBlock().getStateForPlacement(ctx); + if (!ctx.canPlace()) + { + return Value.FALSE; + } + final BlockState placementState = blockItem.getBlock().getStateForPlacement(ctx); if (placementState != null) { final Level level = ctx.getLevel(); if (placementState.canSurvive(level, where)) { level.setBlock(where, placementState, 2); - SoundType blockSoundGroup = placementState.getSoundType(); + final SoundType blockSoundGroup = placementState.getSoundType(); level.playSound(null, where, blockSoundGroup.getPlaceSound(), SoundSource.BLOCKS, (blockSoundGroup.getVolume() + 1.0F) / 2.0F, blockSoundGroup.getPitch() * 0.8F); return Value.TRUE; } @@ -1087,31 +1176,32 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin expression.addContextFunction("map_colour", -1, (c, t, lv) -> stateStringQuery(c, "map_colour", lv, (s, p) -> - BlockInfo.mapColourName.get(s.getMapColor(((CarpetContext)c).level(), p)))); + BlockInfo.mapColourName.get(s.getMapColor(((CarpetContext) c).level(), p)))); // Deprecated for block_state() expression.addContextFunction("property", -1, (c, t, lv) -> { c.host.issueDeprecation("property(...)"); - BlockArgument locator = BlockArgument.findIn((CarpetContext) c, lv, 0); - BlockState state = locator.block.getBlockState(); + final BlockArgument locator = BlockArgument.findIn((CarpetContext) c, lv, 0); + final BlockState state = locator.block.getBlockState(); if (lv.size() <= locator.offset) + { throw new InternalExpressionException("'property' requires to specify a property to query"); - String tag = lv.get(locator.offset).getString(); - StateDefinition states = state.getBlock().getStateDefinition(); - Property property = states.getProperty(tag); - if (property == null) return Value.NULL; - return new StringValue(state.getValue(property).toString().toLowerCase(Locale.ROOT)); + } + final String tag = lv.get(locator.offset).getString(); + final StateDefinition states = state.getBlock().getStateDefinition(); + final Property property = states.getProperty(tag); + return property == null ? Value.NULL : new StringValue(state.getValue(property).toString().toLowerCase(Locale.ROOT)); }); // Deprecated for block_state() expression.addContextFunction("block_properties", -1, (c, t, lv) -> { c.host.issueDeprecation("block_properties(...)"); - BlockArgument locator = BlockArgument.findIn((CarpetContext) c, lv, 0); - BlockState state = locator.block.getBlockState(); - StateDefinition states = state.getBlock().getStateDefinition(); + final BlockArgument locator = BlockArgument.findIn((CarpetContext) c, lv, 0); + final BlockState state = locator.block.getBlockState(); + final StateDefinition states = state.getBlock().getStateDefinition(); return ListValue.wrap(states.getProperties().stream().map( p -> new StringValue(p.getName())) ); @@ -1121,104 +1211,89 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin // block_state(block, property) expression.addContextFunction("block_state", -1, (c, t, lv) -> { - BlockArgument locator = BlockArgument.findIn((CarpetContext) c, lv, 0, true); - BlockState state = locator.block.getBlockState(); - StateDefinition states = state.getBlock().getStateDefinition(); + final BlockArgument locator = BlockArgument.findIn((CarpetContext) c, lv, 0, true); + final BlockState state = locator.block.getBlockState(); + final StateDefinition states = state.getBlock().getStateDefinition(); if (locator.offset == lv.size()) { - Map properties = new HashMap<>(); - for(Property p : states.getProperties()) + final Map properties = new HashMap<>(); + for (final Property p : states.getProperties()) { - properties.put(StringValue.of(p.getName()), ValueConversions.fromProperty(state, p));// ValueConversions.fromObject(state.get(p), false)); + properties.put(StringValue.of(p.getName()), ValueConversions.fromProperty(state, p)); } return MapValue.wrap(properties); } - String tag = lv.get(locator.offset).getString(); - Property property = states.getProperty(tag); - if (property == null) - return Value.NULL; - return ValueConversions.fromProperty(state, property); + final String tag = lv.get(locator.offset).getString(); + final Property property = states.getProperty(tag); + return property == null ? Value.NULL : ValueConversions.fromProperty(state, property); }); expression.addContextFunction("block_list", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext)c; - Registry blocks = cc.registry(Registries.BLOCK); + final CarpetContext cc = (CarpetContext) c; + final Registry blocks = cc.registry(Registries.BLOCK); if (lv.size() == 0) + { return ListValue.wrap(blocks.keySet().stream().map(ValueConversions::of)); - ResourceLocation tag = InputValidator.identifierOf(lv.get(0).getString()); - - Optional> tagset = blocks.getTag(TagKey.create(Registries.BLOCK, tag)); - if (tagset.isEmpty()) return Value.NULL; - return ListValue.wrap(tagset.get().stream().map(b -> ValueConversions.of(blocks.getKey(b.value())))); + } + final ResourceLocation tag = InputValidator.identifierOf(lv.get(0).getString()); + final Optional> tagset = blocks.getTag(TagKey.create(Registries.BLOCK, tag)); + return tagset.isEmpty() ? Value.NULL : ListValue.wrap(tagset.get().stream().map(b -> ValueConversions.of(blocks.getKey(b.value())))); }); expression.addContextFunction("block_tags", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext)c; - Registry blocks = cc.registry(Registries.BLOCK); + final CarpetContext cc = (CarpetContext) c; + final Registry blocks = cc.registry(Registries.BLOCK); if (lv.size() == 0) - return ListValue.wrap(blocks.getTagNames().map(ValueConversions::of)); - BlockArgument blockLocator = BlockArgument.findIn(cc, lv, 0, true); - if (blockLocator.offset == lv.size()) { - Block target = blockLocator.block.getBlockState().getBlock(); - return ListValue.wrap( blocks.getTags().filter(e -> e.getSecond().stream().anyMatch(h -> (h.value() == target))).map(e -> ValueConversions.of(e.getFirst()))); + return ListValue.wrap(blocks.getTagNames().map(ValueConversions::of)); } - String tag = lv.get(blockLocator.offset).getString(); - Optional> tagSet = blocks.getTag(TagKey.create(Registries.BLOCK, InputValidator.identifierOf(tag))); - if (tagSet.isEmpty()) return Value.NULL; - return BooleanValue.of(blockLocator.block.getBlockState().is(tagSet.get())); - - - /* before - TagContainer tagManager = cc.s.getServer().getTags(); - if (lv.size() == 0) - return ListValue.wrap(tagManager.getOrEmpty(Registry.BLOCK_REGISTRY).getAvailableTags().stream().map(ValueConversions::of)); - BlockArgument blockLocator = BlockArgument.findIn(cc, lv, 0, true); + final BlockArgument blockLocator = BlockArgument.findIn(cc, lv, 0, true); if (blockLocator.offset == lv.size()) { - Block target = blockLocator.block.getBlockState().getBlock(); - return ListValue.wrap(tagManager.getOrEmpty(Registry.BLOCK_REGISTRY).getAllTags().entrySet().stream().filter(e -> e.getValue().contains(target)).map(e -> ValueConversions.of(e.getKey()))); + final Block target = blockLocator.block.getBlockState().getBlock(); + return ListValue.wrap(blocks.getTags().filter(e -> e.getSecond().stream().anyMatch(h -> (h.value() == target))).map(e -> ValueConversions.of(e.getFirst()))); } - String tag = lv.get(blockLocator.offset).getString(); - net.minecraft.tags.Tag blockTag = tagManager.getOrEmpty(Registry.BLOCK_REGISTRY).getTag(InputValidator.identifierOf(tag)); - if (blockTag == null) return Value.NULL; - return BooleanValue.of(blockLocator.block.getBlockState().is(blockTag)); - */ + final String tag = lv.get(blockLocator.offset).getString(); + final Optional> tagSet = blocks.getTag(TagKey.create(Registries.BLOCK, InputValidator.identifierOf(tag))); + return tagSet.isEmpty() ? Value.NULL : BooleanValue.of(blockLocator.block.getBlockState().is(tagSet.get())); }); expression.addContextFunction("biome", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext) c; - ServerLevel world = cc.level(); + final CarpetContext cc = (CarpetContext) c; + final ServerLevel world = cc.level(); if (lv.size() == 0) + { return ListValue.wrap(world.registryAccess().registryOrThrow(Registries.BIOME).keySet().stream().map(ValueConversions::of)); + } - Biome biome; - BiomeSource biomeSource = world.getChunkSource().getGenerator().getBiomeSource(); - if ( lv.size() == 1 - && lv.get(0) instanceof MapValue map - && biomeSource instanceof MultiNoiseBiomeSource mnbs - ) { - Value temperature = map.get(new StringValue("temperature")); + final Biome biome; + final BiomeSource biomeSource = world.getChunkSource().getGenerator().getBiomeSource(); + if (lv.size() == 1 + && lv.get(0) instanceof final MapValue map + && biomeSource instanceof final MultiNoiseBiomeSource mnbs + ) + { + final Value temperature = map.get(new StringValue("temperature")); nullCheck(temperature, "temperature"); - Value humidity = map.get(new StringValue("humidity")); + final Value humidity = map.get(new StringValue("humidity")); nullCheck(humidity, "humidity"); - Value continentalness = map.get(new StringValue("continentalness")); + final Value continentalness = map.get(new StringValue("continentalness")); nullCheck(continentalness, "continentalness"); - Value erosion = map.get(new StringValue("erosion")); + final Value erosion = map.get(new StringValue("erosion")); nullCheck(erosion, "erosion"); - Value depth = map.get(new StringValue("depth")); + final Value depth = map.get(new StringValue("depth")); nullCheck(depth, "depth"); - Value weirdness = map.get(new StringValue("weirdness")); + final Value weirdness = map.get(new StringValue("weirdness")); nullCheck(weirdness, "weirdness"); - Climate.TargetPoint point = new Climate.TargetPoint( + final Climate.TargetPoint point = new Climate.TargetPoint( Climate.quantizeCoord(numberGetOrThrow(temperature)), Climate.quantizeCoord(numberGetOrThrow(humidity)), Climate.quantizeCoord(numberGetOrThrow(continentalness)), @@ -1227,127 +1302,145 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin Climate.quantizeCoord(numberGetOrThrow(weirdness)) ); biome = mnbs.getNoiseBiome(point).value(); - ResourceLocation biomeId = cc.registry(Registries.BIOME).getKey(biome); + final ResourceLocation biomeId = cc.registry(Registries.BIOME).getKey(biome); return new StringValue(NBTSerializableValue.nameFromRegistryId(biomeId)); } - BlockArgument locator = BlockArgument.findIn(cc, lv, 0, false, false, true); + final BlockArgument locator = BlockArgument.findIn(cc, lv, 0, false, false, true); if (locator.replacement != null) { biome = world.registryAccess().registryOrThrow(Registries.BIOME).get(InputValidator.identifierOf(locator.replacement)); - if (biome == null) throw new ThrowStatement(locator.replacement, Throwables.UNKNOWN_BIOME); + if (biome == null) + { + throw new ThrowStatement(locator.replacement, Throwables.UNKNOWN_BIOME); + } } else { - BlockPos pos = locator.block.getPos(); - biome = world.getBiome(pos).value(); + biome = world.getBiome(locator.block.getPos()).value(); } // in locatebiome if (locator.offset == lv.size()) { - ResourceLocation biomeId = cc.registry(Registries.BIOME).getKey(biome); + final ResourceLocation biomeId = cc.registry(Registries.BIOME).getKey(biome); return new StringValue(NBTSerializableValue.nameFromRegistryId(biomeId)); } - String biomeFeature = lv.get(locator.offset).getString(); - BiFunction featureProvider = BiomeInfo.biomeFeatures.get(biomeFeature); + final String biomeFeature = lv.get(locator.offset).getString(); + final BiFunction featureProvider = BiomeInfo.biomeFeatures.get(biomeFeature); if (featureProvider == null) + { throw new InternalExpressionException("Unknown biome feature: " + biomeFeature); + } return featureProvider.apply(world, biome); }); expression.addContextFunction("set_biome", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext)c; - BlockArgument locator = BlockArgument.findIn(cc, lv, 0); + final CarpetContext cc = (CarpetContext) c; + final BlockArgument locator = BlockArgument.findIn(cc, lv, 0); if (lv.size() == locator.offset) + { throw new InternalExpressionException("'set_biome' needs a biome name as an argument"); - String biomeName = lv.get(locator.offset+0).getString(); + } + final String biomeName = lv.get(locator.offset + 0).getString(); // from locatebiome command code - Holder biome = cc.registry(Registries.BIOME).getHolder(ResourceKey.create(Registries.BIOME, InputValidator.identifierOf(biomeName))) - .orElseThrow(() -> new ThrowStatement(biomeName, Throwables.UNKNOWN_BIOME)); - - + final Holder biome = cc.registry(Registries.BIOME).getHolder(ResourceKey.create(Registries.BIOME, InputValidator.identifierOf(biomeName))) + .orElseThrow(() -> new ThrowStatement(biomeName, Throwables.UNKNOWN_BIOME)); boolean doImmediateUpdate = true; - if (lv.size() > locator.offset+1) - { - doImmediateUpdate = lv.get(locator.offset+1).getBoolean(); - } - ServerLevel world = cc.level(); - BlockPos pos = locator.block.getPos(); - ChunkAccess chunk = world.getChunk(pos); // getting level chunk instead of protochunk with biomes - int biomeX = QuartPos.fromBlock(pos.getX()); - int biomeY = QuartPos.fromBlock(pos.getY()); - int biomeZ = QuartPos.fromBlock(pos.getZ()); - try { - int i = QuartPos.fromBlock(chunk.getMinBuildHeight()); - int j = i + QuartPos.fromBlock(chunk.getHeight()) - 1; - int k = Mth.clamp(biomeY, i, j); - int l = chunk.getSectionIndex(QuartPos.toBlock(k)); + if (lv.size() > locator.offset + 1) + { + doImmediateUpdate = lv.get(locator.offset + 1).getBoolean(); + } + final ServerLevel world = cc.level(); + final BlockPos pos = locator.block.getPos(); + final ChunkAccess chunk = world.getChunk(pos); // getting level chunk instead of protochunk with biomes + final int biomeX = QuartPos.fromBlock(pos.getX()); + final int biomeY = QuartPos.fromBlock(pos.getY()); + final int biomeZ = QuartPos.fromBlock(pos.getZ()); + try + { + final int i = QuartPos.fromBlock(chunk.getMinBuildHeight()); + final int j = i + QuartPos.fromBlock(chunk.getHeight()) - 1; + final int k = Mth.clamp(biomeY, i, j); + final int l = chunk.getSectionIndex(QuartPos.toBlock(k)); // accessing outside of the interface - might be dangerous in the future. ((PalettedContainer>) chunk.getSection(l).getBiomes()).set(biomeX & 3, k & 3, biomeZ & 3, biome); - } catch (Throwable var8) { + } + catch (final Throwable var8) + { return Value.FALSE; } - if (doImmediateUpdate) WorldTools.forceChunkUpdate(pos, world); + if (doImmediateUpdate) + { + WorldTools.forceChunkUpdate(pos, world); + } chunk.setUnsaved(true); return Value.TRUE; }); expression.addContextFunction("reload_chunk", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext)c; - BlockPos pos = BlockArgument.findIn(cc, lv, 0).block.getPos(); - ServerLevel world = cc.level(); - cc.server().executeBlocking( () -> WorldTools.forceChunkUpdate(pos, world)); + final CarpetContext cc = (CarpetContext) c; + final BlockPos pos = BlockArgument.findIn(cc, lv, 0).block.getPos(); + final ServerLevel world = cc.level(); + cc.server().executeBlocking(() -> WorldTools.forceChunkUpdate(pos, world)); return Value.TRUE; }); expression.addContextFunction("structure_references", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext)c; - BlockArgument locator = BlockArgument.findIn(cc, lv, 0); - ServerLevel world = cc.level(); - BlockPos pos = locator.block.getPos(); - Map references = world.getChunk(pos.getX() >> 4, pos.getZ() >> 4, ChunkStatus.STRUCTURE_REFERENCES).getAllReferences(); - Registry reg = cc.registry(Registries.STRUCTURE); + final CarpetContext cc = (CarpetContext) c; + final BlockArgument locator = BlockArgument.findIn(cc, lv, 0); + final ServerLevel world = cc.level(); + final BlockPos pos = locator.block.getPos(); + final Map references = world.getChunk(pos.getX() >> 4, pos.getZ() >> 4, ChunkStatus.STRUCTURE_REFERENCES).getAllReferences(); + final Registry reg = cc.registry(Registries.STRUCTURE); if (lv.size() == locator.offset) + { return ListValue.wrap(references.entrySet().stream(). - filter(e -> e.getValue()!= null && !e.getValue().isEmpty()). + filter(e -> e.getValue() != null && !e.getValue().isEmpty()). map(e -> new StringValue(NBTSerializableValue.nameFromRegistryId(reg.getKey(e.getKey())))) ); - String simpleStructureName = lv.get(locator.offset).getString().toLowerCase(Locale.ROOT); - Structure structureName = reg.get(InputValidator.identifierOf(simpleStructureName)); - if (structureName == null) return Value.NULL; - LongSet structureReferences = references.get(structureName); - if (structureReferences == null || structureReferences.isEmpty()) return ListValue.of(); + } + final String simpleStructureName = lv.get(locator.offset).getString().toLowerCase(Locale.ROOT); + final Structure structureName = reg.get(InputValidator.identifierOf(simpleStructureName)); + if (structureName == null) + { + return Value.NULL; + } + final LongSet structureReferences = references.get(structureName); + if (structureReferences == null || structureReferences.isEmpty()) + { + return ListValue.of(); + } return ListValue.wrap(structureReferences.longStream().mapToObj(l -> ListValue.of( - new NumericValue(16*ChunkPos.getX(l)), + new NumericValue(16 * ChunkPos.getX(l)), Value.ZERO, - new NumericValue(16*ChunkPos.getZ(l))))); + new NumericValue(16 * ChunkPos.getZ(l))))); }); expression.addContextFunction("structure_eligibility", -1, (c, t, lv) -> {// TODO rename structureName to class - CarpetContext cc = (CarpetContext)c; - BlockArgument locator = BlockArgument.findIn(cc, lv, 0); + final CarpetContext cc = (CarpetContext) c; + final BlockArgument locator = BlockArgument.findIn(cc, lv, 0); - ServerLevel world = cc.level(); + final ServerLevel world = cc.level(); // well, because BooYah(world); - BlockPos pos = locator.block.getPos(); + final BlockPos pos = locator.block.getPos(); final List structure = new ArrayList<>(); boolean needSize = false; boolean singleOutput = false; - Registry reg = cc.registry(Registries.STRUCTURE); + final Registry reg = cc.registry(Registries.STRUCTURE); if (lv.size() > locator.offset) { - Value requested = lv.get(locator.offset+0); + final Value requested = lv.get(locator.offset + 0); if (!requested.isNull()) { - String reqString = requested.getString(); - var id = InputValidator.identifierOf(reqString); - Structure requestedStructure = reg.get(id); + final String reqString = requested.getString(); + final ResourceLocation id = InputValidator.identifierOf(reqString); + final Structure requestedStructure = reg.get(id); if (requestedStructure != null) { singleOutput = true; @@ -1355,8 +1448,8 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin } else { - StructureType sss = cc.registry(Registries.STRUCTURE_TYPE).get(id); - reg.entrySet().stream().filter(e -> e.getValue().type() ==sss).forEach(e -> structure.add(e.getValue())); + final StructureType sss = cc.registry(Registries.STRUCTURE_TYPE).get(id); + reg.entrySet().stream().filter(e -> e.getValue().type() == sss).forEach(e -> structure.add(e.getValue())); } if (structure.isEmpty()) { @@ -1368,9 +1461,9 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin { structure.addAll(reg.entrySet().stream().map(Map.Entry::getValue).toList()); } - if (lv.size() > locator.offset+1) + if (lv.size() > locator.offset + 1) { - needSize = lv.get(locator.offset+1).getBoolean(); + needSize = lv.get(locator.offset + 1).getBoolean(); } } else @@ -1379,50 +1472,53 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin } if (singleOutput) { - StructureStart start = FeatureGenerator.shouldStructureStartAt(world, pos, structure.get(0), needSize); - if (start == null) return Value.NULL; - if (!needSize) return Value.TRUE; - return ValueConversions.of(start, cc.registryAccess()); + final StructureStart start = FeatureGenerator.shouldStructureStartAt(world, pos, structure.get(0), needSize); + return start == null ? Value.NULL : !needSize ? Value.TRUE : ValueConversions.of(start, cc.registryAccess()); } - Map ret = new HashMap<>(); - for(Structure str: structure) + final Map ret = new HashMap<>(); + for (final Structure str : structure) { StructureStart start; try { start = FeatureGenerator.shouldStructureStartAt(world, pos, str, needSize); } - catch (NullPointerException npe) + catch (final NullPointerException npe) { - CarpetSettings.LOG.error("Failed to detect structure: "+ reg.getKey(str)); + CarpetSettings.LOG.error("Failed to detect structure: " + reg.getKey(str)); start = null; } - if (start == null) continue; + if (start == null) + { + continue; + } - Value key = new StringValue(NBTSerializableValue.nameFromRegistryId(reg.getKey(str))); - ret.put(key, (!needSize)?Value.NULL: ValueConversions.of(start, cc.registryAccess())); + final Value key = new StringValue(NBTSerializableValue.nameFromRegistryId(reg.getKey(str))); + ret.put(key, (!needSize) ? Value.NULL : ValueConversions.of(start, cc.registryAccess())); } return MapValue.wrap(ret); }); expression.addContextFunction("structures", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext)c; - BlockArgument locator = BlockArgument.findIn(cc, lv, 0); + final CarpetContext cc = (CarpetContext) c; + final BlockArgument locator = BlockArgument.findIn(cc, lv, 0); - ServerLevel world = cc.level(); - BlockPos pos = locator.block.getPos(); - Map structures = world.getChunk(pos.getX() >> 4, pos.getZ() >> 4, ChunkStatus.STRUCTURE_STARTS).getAllStarts(); - Registry reg = cc.registry(Registries.STRUCTURE); + final ServerLevel world = cc.level(); + final BlockPos pos = locator.block.getPos(); + final Map structures = world.getChunk(pos.getX() >> 4, pos.getZ() >> 4, ChunkStatus.STRUCTURE_STARTS).getAllStarts(); + final Registry reg = cc.registry(Registries.STRUCTURE); if (lv.size() == locator.offset) { - Map structureList = new HashMap<>(); - for (Map.Entry entry : structures.entrySet()) + final Map structureList = new HashMap<>(); + for (final Map.Entry entry : structures.entrySet()) { - StructureStart start = entry.getValue(); + final StructureStart start = entry.getValue(); if (start == StructureStart.INVALID_START) + { continue; - BoundingBox box = start.getBoundingBox(); + } + final BoundingBox box = start.getBoundingBox(); structureList.put( new StringValue(NBTSerializableValue.nameFromRegistryId(reg.getKey(entry.getKey()))), ValueConversions.of(box) @@ -1430,57 +1526,67 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin } return MapValue.wrap(structureList); } - String structureName = lv.get(locator.offset).getString().toLowerCase(Locale.ROOT); + final String structureName = lv.get(locator.offset).getString().toLowerCase(Locale.ROOT); return ValueConversions.of(structures.get(reg.get(InputValidator.identifierOf(structureName))), cc.registryAccess()); }); expression.addContextFunction("set_structure", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext)c; - BlockArgument locator = BlockArgument.findIn(cc, lv, 0); + final CarpetContext cc = (CarpetContext) c; + final BlockArgument locator = BlockArgument.findIn(cc, lv, 0); - ServerLevel world = cc.level(); - BlockPos pos = locator.block.getPos(); + final ServerLevel world = cc.level(); + final BlockPos pos = locator.block.getPos(); if (lv.size() == locator.offset) + { throw new InternalExpressionException("'set_structure requires at least position and a structure name"); - String structureName = lv.get(locator.offset).getString().toLowerCase(Locale.ROOT); - Structure configuredStructure = FeatureGenerator.resolveConfiguredStructure(structureName, world, pos); - if (configuredStructure == null) throw new ThrowStatement(structureName, Throwables.UNKNOWN_STRUCTURE); + } + final String structureName = lv.get(locator.offset).getString().toLowerCase(Locale.ROOT); + final Structure configuredStructure = FeatureGenerator.resolveConfiguredStructure(structureName, world, pos); + if (configuredStructure == null) + { + throw new ThrowStatement(structureName, Throwables.UNKNOWN_STRUCTURE); + } // good 'ol pointer - Value[] result = new Value[]{Value.NULL}; + final Value[] result = new Value[]{Value.NULL}; // technically a world modification. Even if we could let it slide, we will still park it ((CarpetContext) c).server().executeBlocking(() -> { - Map structures = world.getChunk(pos).getAllStarts(); + final Map structures = world.getChunk(pos).getAllStarts(); if (lv.size() == locator.offset + 1) { - Boolean res = FeatureGenerator.plopGrid(configuredStructure, ((CarpetContext) c).level(), locator.block.getPos()); - if (res == null) return; - result[0] = res?Value.TRUE:Value.FALSE; + final Boolean res = FeatureGenerator.plopGrid(configuredStructure, ((CarpetContext) c).level(), locator.block.getPos()); + if (res == null) + { + return; + } + result[0] = res ? Value.TRUE : Value.FALSE; return; } - Value newValue = lv.get(locator.offset+1); + final Value newValue = lv.get(locator.offset + 1); if (newValue.isNull()) // remove structure { - Structure structure = configuredStructure; + final Structure structure = configuredStructure; if (!structures.containsKey(structure)) { return; } - StructureStart start = structures.get(structure); - ChunkPos structureChunkPos = start.getChunkPos(); - BoundingBox box = start.getBoundingBox(); + final StructureStart start = structures.get(structure); + final ChunkPos structureChunkPos = start.getChunkPos(); + final BoundingBox box = start.getBoundingBox(); for (int chx = box.minX() / 16; chx <= box.maxX() / 16; chx++) // minx maxx { for (int chz = box.minZ() / 16; chz <= box.maxZ() / 16; chz++) //minZ maxZ { - ChunkPos chpos = new ChunkPos(chx, chz); + final ChunkPos chpos = new ChunkPos(chx, chz); // getting a chunk will convert it to full, allowing to modify references - Map references = + final Map references = world.getChunk(chpos.getWorldPosition()).getAllReferences(); if (references.containsKey(structure) && references.get(structure) != null) + { references.get(structure).remove(structureChunkPos.toLong()); + } } } structures.remove(structure); @@ -1489,46 +1595,19 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin }); return result[0]; // preventing from lazy evaluating of the result in case a future completes later }); -/* - expression.addContextFunction("custom_dimension", -1, (c, t, lv) -> - { - if (lv.size() == 0) throw new InternalExpressionException("'custom_dimension' requires at least one argument"); - CarpetContext cc = (CarpetContext)c; - cc.host.issueDeprecation("custom_dimension()"); - String worldKey = lv.get(0).getString(); - - Long seed = null; - if (lv.size() > 1) - { - String seedKey = lv.get(1).getString(); - try - { - seed = Long.parseLong(seedKey); - } - catch (NumberFormatException ignored) - { - throw new InternalExpressionException("Incorrect number format for seed: " + seedKey); - } - } - boolean success = WorldTools.createWorld(cc.s.getServer(), worldKey, seed); - if (!success) return Value.FALSE; - CommandHelper.notifyPlayersCommandsChanged(cc.s.getServer()); - return Value.TRUE; - }); -*/ // todo maybe enable chunk blending? expression.addContextFunction("reset_chunk", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext)c; - List requestedChunks = new ArrayList<>(); + final CarpetContext cc = (CarpetContext) c; + final List requestedChunks = new ArrayList<>(); if (lv.size() == 1) { //either one block or list of chunks - Value first = lv.get(0); - if (first instanceof ListValue) + final Value first = lv.get(0); + if (first instanceof final ListValue list) { - List listVal = ((ListValue) first).getItems(); + final List listVal = list.getItems(); BlockArgument locator = BlockArgument.findIn(cc, listVal, 0); requestedChunks.add(new ChunkPos(locator.block.getPos())); while (listVal.size() > locator.offset) @@ -1539,23 +1618,26 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin } else { - BlockArgument locator = BlockArgument.findIn(cc, Collections.singletonList(first), 0); + final BlockArgument locator = BlockArgument.findIn(cc, Collections.singletonList(first), 0); requestedChunks.add(new ChunkPos(locator.block.getPos())); } } else { BlockArgument locator = BlockArgument.findIn(cc, lv, 0); - ChunkPos from = new ChunkPos(locator.block.getPos()); + final ChunkPos from = new ChunkPos(locator.block.getPos()); if (lv.size() > locator.offset) { locator = BlockArgument.findIn(cc, lv, locator.offset); - ChunkPos to = new ChunkPos(locator.block.getPos()); - int xmax = Math.max(from.x, to.x); - int zmax = Math.max(from.z, to.z); - for (int x = Math.min(from.x, to.x); x <= xmax; x++) for (int z = Math.min(from.z, to.z); z <= zmax; z++) + final ChunkPos to = new ChunkPos(locator.block.getPos()); + final int xmax = Math.max(from.x, to.x); + final int zmax = Math.max(from.z, to.z); + for (int x = Math.min(from.x, to.x); x <= xmax; x++) { - requestedChunks.add(new ChunkPos(x,z)); + for (int z = Math.min(from.z, to.z); z <= zmax; z++) + { + requestedChunks.add(new ChunkPos(x, z)); + } } } else @@ -1563,25 +1645,14 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin requestedChunks.add(from); } } - - - ServerLevel world = cc.level(); - - Value [] result = new Value[]{Value.NULL}; - - ((CarpetContext)c).server().executeBlocking( () -> + final ServerLevel world = cc.level(); + final Value[] result = new Value[]{Value.NULL}; + ((CarpetContext) c).server().executeBlocking(() -> { - Map report = ((ThreadedAnvilChunkStorageInterface) world.getChunkSource().chunkMap).regenerateChunkRegion(requestedChunks); - /*for (ChunkPos chpos: requestedChunks) // needed in 1.16 only - { - if (world.getChunk(chpos.x, chpos.z, ChunkStatus.FULL, false) != null) - { - WorldTools.forceChunkUpdate(chpos.getStartPos(), world); - } - }*/ + final Map report = ((ThreadedAnvilChunkStorageInterface) world.getChunkSource().chunkMap).regenerateChunkRegion(requestedChunks); result[0] = MapValue.wrap(report.entrySet().stream().collect(Collectors.toMap( e -> new StringValue(e.getKey()), - e -> new NumericValue(e.getValue()) + e -> new NumericValue(e.getValue()) ))); }); return result[0]; @@ -1589,73 +1660,92 @@ else throw new InternalExpressionException("Attacking entity needs to be a livin expression.addContextFunction("inhabited_time", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext)c; - BlockArgument locator = BlockArgument.findIn(cc, lv, 0); - BlockPos pos = locator.block.getPos(); + final CarpetContext cc = (CarpetContext) c; + final BlockArgument locator = BlockArgument.findIn(cc, lv, 0); + final BlockPos pos = locator.block.getPos(); return new NumericValue(cc.level().getChunk(pos).getInhabitedTime()); }); expression.addContextFunction("spawn_potential", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext)c; - BlockArgument locator = BlockArgument.findIn(cc, lv, 0); - BlockPos pos = locator.block.getPos(); + final CarpetContext cc = (CarpetContext) c; + final BlockArgument locator = BlockArgument.findIn(cc, lv, 0); + final BlockPos pos = locator.block.getPos(); double required_charge = 1; if (lv.size() > locator.offset) + { required_charge = NumericValue.asNumber(lv.get(locator.offset)).getDouble(); - NaturalSpawner.SpawnState charger = cc.level().getChunkSource().getLastSpawnState(); - if (charger == null) return Value.NULL; - return new NumericValue( - ((SpawnHelperInnerInterface)charger).getPotentialCalculator(). - getPotentialEnergyChange(pos, required_charge ) + } + final NaturalSpawner.SpawnState charger = cc.level().getChunkSource().getLastSpawnState(); + return charger == null ? Value.NULL : new NumericValue( + ((SpawnHelperInnerInterface) charger).getPotentialCalculator(). + getPotentialEnergyChange(pos, required_charge) ); }); expression.addContextFunction("add_chunk_ticket", -1, (c, t, lv) -> { - CarpetContext cc = (CarpetContext)c; - BlockArgument locator = BlockArgument.findIn(cc, lv, 0); - BlockPos pos = locator.block.getPos(); - if (lv.size() != locator.offset+2) throw new InternalExpressionException("'add_chunk_ticket' requires block position, ticket type and radius"); - String type = lv.get(locator.offset).getString(); - TicketType ticket = ticketTypes.get(type.toLowerCase(Locale.ROOT)); - if (ticket == null) throw new InternalExpressionException("Unknown ticket type: "+type); - int radius = NumericValue.asNumber(lv.get(locator.offset+1)).getInt(); - if (radius < 1 || radius > 32) throw new InternalExpressionException("Ticket radius should be between 1 and 32 chunks"); + final CarpetContext cc = (CarpetContext) c; + final BlockArgument locator = BlockArgument.findIn(cc, lv, 0); + final BlockPos pos = locator.block.getPos(); + if (lv.size() != locator.offset + 2) + { + throw new InternalExpressionException("'add_chunk_ticket' requires block position, ticket type and radius"); + } + final String type = lv.get(locator.offset).getString(); + final TicketType ticket = ticketTypes.get(type.toLowerCase(Locale.ROOT)); + if (ticket == null) + { + throw new InternalExpressionException("Unknown ticket type: " + type); + } + final int radius = NumericValue.asNumber(lv.get(locator.offset + 1)).getInt(); + if (radius < 1 || radius > 32) + { + throw new InternalExpressionException("Ticket radius should be between 1 and 32 chunks"); + } // due to types we will wing it: - ChunkPos target = new ChunkPos(pos); + final ChunkPos target = new ChunkPos(pos); if (ticket == TicketType.PORTAL) // portal + { cc.level().getChunkSource().addRegionTicket(TicketType.PORTAL, target, radius, pos); + } else if (ticket == TicketType.POST_TELEPORT) // post teleport + { cc.level().getChunkSource().addRegionTicket(TicketType.POST_TELEPORT, target, radius, 1); + } else + { cc.level().getChunkSource().addRegionTicket(TicketType.UNKNOWN, target, radius, target); + } return new NumericValue(ticket.timeout()); }); expression.addContextFunction("sample_noise", -1, (c, t, lv) -> { final CarpetContext cc = (CarpetContext) c; - if (lv.size() == 0) { + if (lv.size() == 0) + { return ListValue.wrap(cc.registry(Registries.DENSITY_FUNCTION).keySet().stream().map(ValueConversions::of)); } final ServerLevel level = cc.level(); final BlockArgument locator = BlockArgument.findIn(cc, lv, 0); final BlockPos pos = locator.block.getPos(); final String[] densityFunctionQueries = lv.stream().skip(locator.offset).map(Value::getString).toArray(String[]::new); - if (densityFunctionQueries.length == 0) { + if (densityFunctionQueries.length == 0) + { return ListValue.wrap(cc.registry(Registries.DENSITY_FUNCTION).keySet().stream().map(ValueConversions::of)); } - NoiseRouter router = level.getChunkSource().randomState().router(); - if (densityFunctionQueries.length == 1) { - return NumericValue.of(sampleNoise(router, level, densityFunctionQueries[0], pos)); - } - return ListValue.wrap(Arrays.stream(densityFunctionQueries).map(s -> NumericValue.of(sampleNoise(router, level, s, pos)))); + final NoiseRouter router = level.getChunkSource().randomState().router(); + return densityFunctionQueries.length == 1 + ? NumericValue.of(sampleNoise(router, level, densityFunctionQueries[0], pos)) + : ListValue.wrap(Arrays.stream(densityFunctionQueries).map(s -> NumericValue.of(sampleNoise(router, level, s, pos)))); }); } - public static double sampleNoise(NoiseRouter router, ServerLevel level, String what, BlockPos pos) { - DensityFunction densityFunction = switch (what) { + public static double sampleNoise(final NoiseRouter router, final ServerLevel level, final String what, final BlockPos pos) + { + final DensityFunction densityFunction = switch (what) + { case "barrier_noise" -> router.barrierNoise(); case "fluid_level_floodedness_noise" -> router.fluidLevelFloodednessNoise(); case "fluid_level_spread_noise" -> router.fluidLevelSpreadNoise(); @@ -1672,21 +1762,6 @@ public static double sampleNoise(NoiseRouter router, ServerLevel level, String w case "vein_ridged" -> router.veinRidged(); case "vein_gap" -> router.veinGap(); default -> stupidWorldgenNoiseCacheGetter.apply(Pair.of(level, what)); - /*ResourceLocation densityFunctionKey = InputValidator.identifierOf(what); - Registry densityFunctionRegistry = level.registryAccess().registryOrThrow(Registries.DENSITY_FUNCTION); - if (densityFunctionRegistry.containsKey(densityFunctionKey) && level.getChunkSource().getGenerator() instanceof NoiseBasedChunkGenerator noiseBasedChunkGenerator) { - DensityFunction densityFunction1 = densityFunctionRegistry.get(densityFunctionKey); - RandomState randomState = RandomState.create( - noiseBasedChunkGenerator.generatorSettings().value(), - level.registryAccess().lookupOrThrow(Registries.NOISE), level.getSeed() - ); - DensityFunction.Visitor visitor = ((RandomStateVisitorAccessor) (Object) randomState).getVisitor(); - - DensityFunction temp = densityFunction.mapAll(visitor); - } - - throw new InternalExpressionException("Density function '" + what + "' is not defined in the registies.");*/ - }; return densityFunction.compute(new DensityFunction.SinglePointContext(pos.getX(), pos.getY(), pos.getZ())); } @@ -1697,35 +1772,38 @@ public static double sampleNoise(NoiseRouter router, ServerLevel level, String w String densityFunctionQuery = pair.getValue(); ChunkGenerator generator = level.getChunkSource().getGenerator(); - if (generator instanceof NoiseBasedChunkGenerator noiseBasedChunkGenerator) { + if (generator instanceof final NoiseBasedChunkGenerator noiseBasedChunkGenerator) + { Registry densityFunctionRegistry = level.registryAccess().registryOrThrow(Registries.DENSITY_FUNCTION); final NoiseRouter router = noiseBasedChunkGenerator.generatorSettings().value().noiseRouter(); - DensityFunction densityFunction = switch (densityFunctionQuery) { - case "barrier_noise" -> router.barrierNoise(); - case "fluid_level_floodedness_noise" -> router.fluidLevelFloodednessNoise(); - case "fluid_level_spread_noise" -> router.fluidLevelSpreadNoise(); - case "lava_noise" -> router.lavaNoise(); - case "temperature" -> router.temperature(); - case "vegetation" -> router.vegetation(); - case "continents" -> router.continents(); - case "erosion" -> router.erosion(); - case "depth" -> router.depth(); - case "ridges" -> router.ridges(); - case "initial_density_without_jaggedness" -> router.initialDensityWithoutJaggedness(); - case "final_density" -> router.finalDensity(); - case "vein_toggle" -> router.veinToggle(); - case "vein_ridged" -> router.veinRidged(); - case "vein_gap" -> router.veinGap(); - default -> { - ResourceLocation densityFunctionKey = InputValidator.identifierOf(densityFunctionQuery); - - if (densityFunctionRegistry.containsKey(densityFunctionKey)) { - yield densityFunctionRegistry.get(densityFunctionKey); - } + DensityFunction densityFunction = switch (densityFunctionQuery) + { + case "barrier_noise" -> router.barrierNoise(); + case "fluid_level_floodedness_noise" -> router.fluidLevelFloodednessNoise(); + case "fluid_level_spread_noise" -> router.fluidLevelSpreadNoise(); + case "lava_noise" -> router.lavaNoise(); + case "temperature" -> router.temperature(); + case "vegetation" -> router.vegetation(); + case "continents" -> router.continents(); + case "erosion" -> router.erosion(); + case "depth" -> router.depth(); + case "ridges" -> router.ridges(); + case "initial_density_without_jaggedness" -> router.initialDensityWithoutJaggedness(); + case "final_density" -> router.finalDensity(); + case "vein_toggle" -> router.veinToggle(); + case "vein_ridged" -> router.veinRidged(); + case "vein_gap" -> router.veinGap(); + default -> { + ResourceLocation densityFunctionKey = InputValidator.identifierOf(densityFunctionQuery); + + if (densityFunctionRegistry.containsKey(densityFunctionKey)) + { + yield densityFunctionRegistry.get(densityFunctionKey); + } - throw new InternalExpressionException("Density function '" + densityFunctionQuery + "' is not defined in the registies."); - } - }; + throw new InternalExpressionException("Density function '" + densityFunctionQuery + "' is not defined in the registies."); + } + }; RandomState randomState = RandomState.create( noiseBasedChunkGenerator.generatorSettings().value(), @@ -1733,9 +1811,7 @@ public static double sampleNoise(NoiseRouter router, ServerLevel level, String w ); DensityFunction.Visitor visitor = ((RandomStateVisitorAccessor) (Object) randomState).getVisitor(); - DensityFunction temp = densityFunction.mapAll(visitor); - - return temp; + return densityFunction.mapAll(visitor); } return DensityFunctions.zero(); }); diff --git a/src/main/java/carpet/script/argument/Argument.java b/src/main/java/carpet/script/argument/Argument.java index 1a9dbd4176..4fac0a370f 100644 --- a/src/main/java/carpet/script/argument/Argument.java +++ b/src/main/java/carpet/script/argument/Argument.java @@ -3,6 +3,7 @@ public abstract class Argument { public int offset; + protected Argument(int offset) { this.offset = offset; diff --git a/src/main/java/carpet/script/argument/BlockArgument.java b/src/main/java/carpet/script/argument/BlockArgument.java index b2e66c9300..4641b48de5 100644 --- a/src/main/java/carpet/script/argument/BlockArgument.java +++ b/src/main/java/carpet/script/argument/BlockArgument.java @@ -7,48 +7,52 @@ import carpet.script.value.NumericValue; import carpet.script.value.StringValue; import carpet.script.value.Value; + import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; + import net.minecraft.core.BlockPos; public class BlockArgument extends Argument { public final BlockValue block; public final String replacement; - private BlockArgument(BlockValue b, int o) + + private BlockArgument(final BlockValue b, final int o) { super(o); block = b; replacement = null; } - private BlockArgument(BlockValue b, int o, String replacement) + + private BlockArgument(final BlockValue b, final int o, final String replacement) { super(o); block = b; this.replacement = replacement; } - public static BlockArgument findIn(CarpetContext c, List params, int offset) + public static BlockArgument findIn(final CarpetContext c, final List params, final int offset) { - return findIn(c, params,offset, false, false, false); + return findIn(c, params, offset, false, false, false); } - public static BlockArgument findIn(CarpetContext c, List params, int offset, boolean acceptString) + public static BlockArgument findIn(final CarpetContext c, final List params, final int offset, final boolean acceptString) { - return findIn(c, params,offset, acceptString, false, false); + return findIn(c, params, offset, acceptString, false, false); } - public static BlockArgument findIn(CarpetContext c, List params, int offset, boolean acceptString, boolean optional, boolean anyString) + public static BlockArgument findIn(final CarpetContext c, final List params, final int offset, final boolean acceptString, final boolean optional, final boolean anyString) { return findIn(c, params.listIterator(offset), offset, acceptString, optional, anyString); } - public static BlockArgument findIn(CarpetContext c, Iterator params, int offset, boolean acceptString, boolean optional, boolean anyString) + public static BlockArgument findIn(final CarpetContext c, final Iterator params, final int offset, final boolean acceptString, final boolean optional, final boolean anyString) { try { - Value v1 = params.next(); + final Value v1 = params.next(); //add conditional from string name if (optional && v1.isNull()) { @@ -69,10 +73,10 @@ public static BlockArgument findIn(CarpetContext c, Iterator params, int final BlockPos pos = c.origin(); if (v1 instanceof ListValue) { - List args = ((ListValue) v1).getItems(); - int xpos = (int) NumericValue.asNumber(args.get(0)).getLong(); - int ypos = (int) NumericValue.asNumber(args.get(1)).getLong(); - int zpos = (int) NumericValue.asNumber(args.get(2)).getLong(); + final List args = ((ListValue) v1).getItems(); + final int xpos = (int) NumericValue.asNumber(args.get(0)).getLong(); + final int ypos = (int) NumericValue.asNumber(args.get(1)).getLong(); + final int zpos = (int) NumericValue.asNumber(args.get(2)).getLong(); return new BlockArgument( new BlockValue( @@ -82,9 +86,9 @@ public static BlockArgument findIn(CarpetContext c, Iterator params, int ), 1 + offset); } - int xpos = (int) NumericValue.asNumber(v1).getLong(); - int ypos = (int) NumericValue.asNumber( params.next()).getLong(); - int zpos = (int) NumericValue.asNumber( params.next()).getLong(); + final int xpos = (int) NumericValue.asNumber(v1).getLong(); + final int ypos = (int) NumericValue.asNumber(params.next()).getLong(); + final int zpos = (int) NumericValue.asNumber(params.next()).getLong(); return new BlockArgument( new BlockValue( null, @@ -100,13 +104,17 @@ public static BlockArgument findIn(CarpetContext c, Iterator params, int } } - private static InternalExpressionException handleError(boolean optional, boolean acceptString) + private static InternalExpressionException handleError(final boolean optional, final boolean acceptString) { String message = "Block-type argument should be defined either by three coordinates (a triple or by three arguments), or a block value"; if (acceptString) - message+=", or a string with block description"; + { + message += ", or a string with block description"; + } if (optional) - message+=", or null"; + { + message += ", or null"; + } return new InternalExpressionException(message); } diff --git a/src/main/java/carpet/script/argument/FileArgument.java b/src/main/java/carpet/script/argument/FileArgument.java index e95ec6f84d..835c61ab1d 100644 --- a/src/main/java/carpet/script/argument/FileArgument.java +++ b/src/main/java/carpet/script/argument/FileArgument.java @@ -59,14 +59,19 @@ public class FileArgument private FileSystem zfs; private Path zipPath; - public final static Object writeIOSync = new Object(); + public static final Object writeIOSync = new Object(); - public void close() { - if (zfs != null && zfs.isOpen()) { - try { + public void close() + { + if (zfs != null && zfs.isOpen()) + { + try + { zfs.close(); - } catch (IOException e) { - throw new InternalExpressionException("Unable to close zip container: "+zipContainer); + } + catch (final IOException e) + { + throw new InternalExpressionException("Unable to close zip container: " + zipContainer); } zfs = null; } @@ -86,10 +91,10 @@ public enum Type public static Map of = Arrays.stream(values()).collect(Collectors.toMap(t -> t.id, t -> t)); - Type(String id, String extension) + Type(final String id, final String extension) { - this.id = id; - this.extension = extension; + this.id = id; + this.extension = extension; } } @@ -98,7 +103,7 @@ public enum Reason READ, CREATE, DELETE } - public FileArgument(String resource, Type type, String zipContainer, boolean isFolder, boolean isShared, Reason reason) + public FileArgument(final String resource, final Type type, final String zipContainer, final boolean isFolder, final boolean isShared, final Reason reason) { this.resource = resource; this.type = type; @@ -111,48 +116,68 @@ public FileArgument(String resource, Type type, String zipContainer, boolean isF } @Override - public String toString() { - return "path: "+resource+" zip: "+zipContainer+" type: "+type.id+" folder: "+isFolder+" shared: "+isShared+" reason: "+reason.toString(); + public String toString() + { + return "path: " + resource + " zip: " + zipContainer + " type: " + type.id + " folder: " + isFolder + " shared: " + isShared + " reason: " + reason.toString(); } - public static FileArgument from(List lv, boolean isFolder, Reason reason) + public static FileArgument from(final List lv, final boolean isFolder, final Reason reason) { - if (lv.size() < 2) throw new InternalExpressionException("File functions require path and type as first two arguments"); - String origtype = lv.get(1).getString().toLowerCase(Locale.ROOT); - boolean shared = origtype.startsWith("shared_"); - String typeString = shared ? origtype.substring(7) : origtype; //len(shared_) - Type type = Type.of.get(typeString); - Pair resource = recognizeResource(lv.get(0).getString(), isFolder, type); - if (type==null) - throw new InternalExpressionException("Unsupported file type: "+origtype); - if (type==Type.FOLDER && !isFolder) + if (lv.size() < 2) + { + throw new InternalExpressionException("File functions require path and type as first two arguments"); + } + final String origtype = lv.get(1).getString().toLowerCase(Locale.ROOT); + final boolean shared = origtype.startsWith("shared_"); + final String typeString = shared ? origtype.substring(7) : origtype; //len(shared_) + final Type type = Type.of.get(typeString); + final Pair resource = recognizeResource(lv.get(0).getString(), isFolder, type); + if (type == null) + { + throw new InternalExpressionException("Unsupported file type: " + origtype); + } + if (type == Type.FOLDER && !isFolder) + { throw new InternalExpressionException("Folder types are no supported for this IO function"); - return new FileArgument(resource.getLeft(), type,resource.getRight(), isFolder, shared, reason); + } + return new FileArgument(resource.getLeft(), type, resource.getRight(), isFolder, shared, reason); } - public static FileArgument resourceFromPath(String path, Reason reason, boolean shared) + public static FileArgument resourceFromPath(final String path, final Reason reason, final boolean shared) { - Pair resource = recognizeResource(path, false, Type.ANY); - return new FileArgument(resource.getLeft(), Type.ANY,resource.getRight(), false, shared, reason); + final Pair resource = recognizeResource(path, false, Type.ANY); + return new FileArgument(resource.getLeft(), Type.ANY, resource.getRight(), false, shared, reason); } - public static Pair recognizeResource(String origfile, boolean isFolder, Type type) + public static Pair recognizeResource(final String origfile, final boolean isFolder, final Type type) { - String[] pathElements = origfile.split("[/\\\\]+"); - List path = new ArrayList<>(); + final String[] pathElements = origfile.split("[/\\\\]+"); + final List path = new ArrayList<>(); String zipPath = null; - for (int i =0; i < pathElements.length; i++ ) + for (int i = 0; i < pathElements.length; i++) { String token = pathElements[i]; - boolean isZip = token.endsWith(".zip") && (isFolder || (i < pathElements.length-1)); - if (zipPath != null && isZip) throw new InternalExpressionException(token+" indicates zip access in an already zipped location "+zipPath); - if (isZip) token = token.substring(0, token.length()-4); - token = (type==Type.ANY && i == pathElements.length-1)? // sloppy really, but should work - token.replaceAll("[^A-Za-z0-9\\-+_.]", ""): + final boolean isZip = token.endsWith(".zip") && (isFolder || (i < pathElements.length - 1)); + if (zipPath != null && isZip) + { + throw new InternalExpressionException(token + " indicates zip access in an already zipped location " + zipPath); + } + if (isZip) + { + token = token.substring(0, token.length() - 4); + } + token = (type == Type.ANY && i == pathElements.length - 1) ? // sloppy really, but should work + token.replaceAll("[^A-Za-z0-9\\-+_.]", "") : token.replaceAll("[^A-Za-z0-9\\-+_]", ""); - if (token.isEmpty()) continue; - if (isZip) token = token + ".zip"; + if (token.isEmpty()) + { + continue; + } + if (isZip) + { + token = token + ".zip"; + } path.add(token); if (isZip) { @@ -161,80 +186,106 @@ public static Pair recognizeResource(String origfile, boolean isF } } if (path.isEmpty() && !isFolder) + { throw new InternalExpressionException( - "Cannot use "+origfile+" as resource name: indicated path is empty"+((zipPath==null)?"":" in zip container "+zipPath) + "Cannot use " + origfile + " as resource name: indicated path is empty" + ((zipPath == null) ? "" : " in zip container " + zipPath) ); + } return Pair.of(String.join("/", path), zipPath); } - private Path resolve(String suffix) + private Path resolve(final String suffix) { if (CarpetServer.minecraft_server == null) + { throw new InternalExpressionException("Accessing world files without server running"); - return CarpetServer.minecraft_server.getWorldPath(LevelResource.ROOT).resolve("scripts/"+suffix); + } + return CarpetServer.minecraft_server.getWorldPath(LevelResource.ROOT).resolve("scripts/" + suffix); } - private Path toPath(Module module) + private Path toPath(final Module module) { - if (!isShared && module == null) return null; + if (!isShared && module == null) + { + return null; + } if (zipContainer == null) - return resolve(getDescriptor(module, resource)+(isFolder?"":type.extension)); + { + return resolve(getDescriptor(module, resource) + (isFolder ? "" : type.extension)); + } else { if (zfs == null) { - Map env = new HashMap<>(); - if (reason == Reason.CREATE) env.put("create", "true"); + final Map env = new HashMap<>(); + if (reason == Reason.CREATE) + { + env.put("create", "true"); + } zipPath = resolve(getDescriptor(module, zipContainer)); - if (!Files.exists(zipPath) && reason != Reason.CREATE) return null; // no zip file - try { - if (!Files.exists(zipPath.getParent())) Files.createDirectories(zipPath.getParent()); - zfs = FileSystems.newFileSystem(URI.create("jar:"+ zipPath.toUri().toString()), env); + if (!Files.exists(zipPath) && reason != Reason.CREATE) + { + return null; // no zip file + } + try + { + if (!Files.exists(zipPath.getParent())) + { + Files.createDirectories(zipPath.getParent()); + } + zfs = FileSystems.newFileSystem(URI.create("jar:" + zipPath.toUri()), env); } - catch (FileSystemNotFoundException | IOException e) + catch (final FileSystemNotFoundException | IOException e) { CarpetScriptServer.LOG.warn("Exception when opening zip file", e); - throw new ThrowStatement("Unable to open zip file: "+zipContainer, Throwables.IO_EXCEPTION); + throw new ThrowStatement("Unable to open zip file: " + zipContainer, Throwables.IO_EXCEPTION); } } - return zfs.getPath(resource+(isFolder?"/":type.extension)); + return zfs.getPath(resource + (isFolder ? "/" : type.extension)); } } - private Path moduleRootPath(Module module) + private Path moduleRootPath(final Module module) { - if (!isShared && module == null) return null; - return resolve(isShared?"shared":module.name()+".data"); + return !isShared && module == null + ? null + : resolve(isShared ? "shared" : module.name() + ".data"); } public String getDisplayPath() { - return (isShared?"shared/":"")+(zipContainer!=null?zipContainer+"/":"")+resource+type.extension; + return (isShared ? "shared/" : "") + (zipContainer != null ? zipContainer + "/" : "") + resource + type.extension; } - private String getDescriptor(Module module, String res) + private String getDescriptor(final Module module, final String res) { if (isShared) { - return res.isEmpty()?"shared":"shared/"+res; + return res.isEmpty() ? "shared" : "shared/" + res; } if (module != null) // appdata { - return module.name()+".data"+(res==null || res.isEmpty()?"":"/"+res); + return module.name() + ".data" + (res == null || res.isEmpty() ? "" : "/" + res); } - throw new InternalExpressionException("Invalid file descriptor: "+res); + throw new InternalExpressionException("Invalid file descriptor: " + res); } - public boolean findPathAndApply(Module module, Consumer action) + public boolean findPathAndApply(final Module module, final Consumer action) { - try { synchronized (writeIOSync) + try { - Path dataFile = toPath(module);//, resourceName, supportedTypes.get(type), isShared); - if (dataFile == null) return false; - createPaths(dataFile); - action.accept(dataFile); - } } + synchronized (writeIOSync) + { + final Path dataFile = toPath(module);//, resourceName, supportedTypes.get(type), isShared); + if (dataFile == null) + { + return false; + } + createPaths(dataFile); + action.accept(dataFile); + } + } finally { close(); @@ -242,83 +293,109 @@ public boolean findPathAndApply(Module module, Consumer action) return true; } - public Stream listFiles(Module module) + public Stream listFiles(final Module module) { - Path dir = toPath(module); - if (dir == null || !Files.exists(dir)) return null; - String ext = type.extension; + final Path dir = toPath(module); + if (dir == null || !Files.exists(dir)) + { + return null; + } + final String ext = type.extension; try { - return Files.list(dir).filter(path -> (type==Type.FOLDER) - ?Files.isDirectory(path) - :(Files.isRegularFile(path) && path.toString().endsWith(ext)) + return Files.list(dir).filter(path -> (type == Type.FOLDER) + ? Files.isDirectory(path) + : (Files.isRegularFile(path) && path.toString().endsWith(ext)) ); } - catch (IOException ignored) + catch (final IOException ignored) { return null; } } - public Stream listFolder(Module module) + public Stream listFolder(final Module module) { Stream strings; - try (Stream result = listFiles(module)) { synchronized (writeIOSync) - { - if (result == null) return null; - Path rootPath = moduleRootPath(module); - if (rootPath == null) return null; - String zipComponent = (zipContainer != null) ? rootPath.relativize(zipPath).toString() : null; - // need to evaluate the stream before exiting try-with-resources else there'll be no data to stream - strings = (zipContainer == null) - ? result.map(p -> rootPath.relativize(p).toString().replaceAll("[\\\\/]+", "/")).toList().stream() - : result.map(p -> (zipComponent + '/'+ p.toString()).replaceAll("[\\\\/]+", "/")).toList().stream(); - } } + try (final Stream result = listFiles(module)) + { + synchronized (writeIOSync) + { + if (result == null) + { + return null; + } + final Path rootPath = moduleRootPath(module); + if (rootPath == null) + { + return null; + } + final String zipComponent = (zipContainer != null) ? rootPath.relativize(zipPath).toString() : null; + // need to evaluate the stream before exiting try-with-resources else there'll be no data to stream + strings = (zipContainer == null) + ? result.map(p -> rootPath.relativize(p).toString().replaceAll("[\\\\/]+", "/")).toList().stream() + : result.map(p -> (zipComponent + '/' + p.toString()).replaceAll("[\\\\/]+", "/")).toList().stream(); + } + } finally { close(); } - if (type == Type.FOLDER) - // java 8 paths are inconsistent. in java 16 they all should not have trailing slashes - return strings.map(s -> s.endsWith("/")?s.substring(0, s.length()-1):s); - return strings.map(FilenameUtils::removeExtension); + // java 8 paths are inconsistent. in java 16 they all should not have trailing slashes + return type == Type.FOLDER + ? strings.map(s -> s.endsWith("/") ? s.substring(0, s.length() - 1) : s) + : strings.map(FilenameUtils::removeExtension); } - private void createPaths(Path file) + private void createPaths(final Path file) { - try { + try + { if ((zipContainer == null || file.getParent() != null) && !Files.exists(file.getParent()) && Files.createDirectories(file.getParent()) == null - ) throw new IOException(); - } catch (IOException e) { + ) + { + throw new IOException(); + } + } + catch (final IOException e) + { CarpetScriptServer.LOG.warn("IOException when creating paths", e); - throw new ThrowStatement("Unable to create paths for "+file.toString(), Throwables.IO_EXCEPTION); + throw new ThrowStatement("Unable to create paths for " + file, Throwables.IO_EXCEPTION); } - } - public boolean appendToTextFile(Module module, List message) + public boolean appendToTextFile(final Module module, final List message) { - try { synchronized (writeIOSync) + try { - Path dataFile = toPath(module);//, resourceName, supportedTypes.get(type), isShared); - if (dataFile == null) return false; - createPaths(dataFile); - OutputStream out = Files.newOutputStream(dataFile, StandardOpenOption.APPEND, StandardOpenOption.CREATE); - try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8))) + synchronized (writeIOSync) { - for (String line: message) + final Path dataFile = toPath(module); + if (dataFile == null) { - writer.append(line); - if (type == Type.TEXT) writer.newLine(); + return false; + } + createPaths(dataFile); + final OutputStream out = Files.newOutputStream(dataFile, StandardOpenOption.APPEND, StandardOpenOption.CREATE); + try (final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8))) + { + for (final String line : message) + { + writer.append(line); + if (type == Type.TEXT) + { + writer.newLine(); + } + } } } - } } - catch (IOException e) + } + catch (final IOException e) { CarpetScriptServer.LOG.warn("IOException when appending to text file", e); - throw new ThrowStatement("Error when writing to the file: "+e, Throwables.IO_EXCEPTION); + throw new ThrowStatement("Error when writing to the file: " + e, Throwables.IO_EXCEPTION); } finally { @@ -327,76 +404,91 @@ public boolean appendToTextFile(Module module, List message) return true; } - public Tag getNbtData(Module module) // aka getData + public Tag getNbtData(final Module module) // aka getData { - try { synchronized (writeIOSync) { - Path dataFile = toPath(module); - if (dataFile == null || !Files.exists(dataFile)) return null; - return readTag(dataFile); - } } - finally { + try + { + synchronized (writeIOSync) + { + final Path dataFile = toPath(module); + if (dataFile == null || !Files.exists(dataFile)) + { + return null; + } + return readTag(dataFile); + } + } + finally + { close(); } } //copied private method from net.minecraft.nbt.NbtIo.read() // to read non-compound tags - these won't be compressed - public static Tag readTag(Path path) + public static Tag readTag(final Path path) { try { return NbtIo.readCompressed(Files.newInputStream(path)); } - catch (IOException e) + catch (final IOException e) { // Copy of NbtIo.read(File) because that's now client-side only if (!Files.exists(path)) { return null; } - try (DataInputStream in = new DataInputStream(new BufferedInputStream(Files.newInputStream(path)))) + try (final DataInputStream in = new DataInputStream(new BufferedInputStream(Files.newInputStream(path)))) { return NbtIo.read(in); } - catch (IOException ioException) + catch (final IOException ioException) { // not compressed compound tag neither uncompressed compound tag - trying any type of a tag - try (DataInputStream dataInput_1 = new DataInputStream(new BufferedInputStream(Files.newInputStream(path)))) + try (final DataInputStream dataInputStream = new DataInputStream(new BufferedInputStream(Files.newInputStream(path)))) { - byte byte_1 = dataInput_1.readByte(); - if (byte_1 == 0) + final byte b = dataInputStream.readByte(); + if (b == 0) { return null; } else { - dataInput_1.readUTF(); - return TagTypes.getType(byte_1).load(dataInput_1, 0, NbtAccounter.UNLIMITED); + dataInputStream.readUTF(); + return TagTypes.getType(b).load(dataInputStream, 0, NbtAccounter.UNLIMITED); } } - catch (IOException secondIO) + catch (final IOException secondIO) { CarpetScriptServer.LOG.warn("IOException when trying to read nbt file, something may have gone wrong with the fs", e); CarpetScriptServer.LOG.warn("", ioException); CarpetScriptServer.LOG.warn("", secondIO); - throw new ThrowStatement("Not a valid NBT tag in "+path.toString(), Throwables.NBT_ERROR); + throw new ThrowStatement("Not a valid NBT tag in " + path, Throwables.NBT_ERROR); } } } - catch (ReportedException e) + catch (final ReportedException e) { - throw new ThrowStatement("Error when reading NBT file "+path.toString(), Throwables.NBT_ERROR); + throw new ThrowStatement("Error when reading NBT file " + path.toString(), Throwables.NBT_ERROR); } } - public boolean saveNbtData(Module module, Tag tag) // aka saveData + public boolean saveNbtData(final Module module, final Tag tag) // aka saveData { - try { synchronized (writeIOSync) { - Path dataFile = toPath(module); - if (dataFile == null) return false; - createPaths(dataFile); - return writeTagDisk(tag, dataFile, zipContainer != null); - } } + try + { + synchronized (writeIOSync) + { + final Path dataFile = toPath(module); + if (dataFile == null) + { + return false; + } + createPaths(dataFile); + return writeTagDisk(tag, dataFile, zipContainer != null); + } + } finally { close(); @@ -404,9 +496,9 @@ public boolean saveNbtData(Module module, Tag tag) // aka saveData } //copied private method from net.minecraft.nbt.NbtIo.write() and client method safe_write - public static boolean writeTagDisk(Tag tag_1, Path path, boolean zipped) + public static boolean writeTagDisk(final Tag tag, Path path, final boolean zipped) { - Path original = path; + final Path original = path; try { if (!zipped) @@ -415,19 +507,19 @@ public static boolean writeTagDisk(Tag tag_1, Path path, boolean zipped) Files.deleteIfExists(path); } - if (tag_1 instanceof CompoundTag) + if (tag instanceof final CompoundTag cTag) { - NbtIo.writeCompressed((CompoundTag) tag_1, Files.newOutputStream(path)); + NbtIo.writeCompressed(cTag, Files.newOutputStream(path)); } else { - try (DataOutputStream dataOutputStream_1 = new DataOutputStream(Files.newOutputStream(path))) + try (final DataOutputStream dataOutputStream = new DataOutputStream(Files.newOutputStream(path))) { - dataOutputStream_1.writeByte(tag_1.getId()); - if (tag_1.getId() != 0) + dataOutputStream.writeByte(tag.getId()); + if (tag.getId() != 0) { - dataOutputStream_1.writeUTF(""); - tag_1.write(dataOutputStream_1); + dataOutputStream.writeUTF(""); + tag.write(dataOutputStream); } } } @@ -438,26 +530,31 @@ public static boolean writeTagDisk(Tag tag_1, Path path, boolean zipped) } return true; } - catch (IOException e) + catch (final IOException e) { CarpetScriptServer.LOG.warn("IO Exception when writing nbt file", e); - throw new ThrowStatement("Unable to write tag to "+original.toString(), Throwables.IO_EXCEPTION); + throw new ThrowStatement("Unable to write tag to " + original, Throwables.IO_EXCEPTION); } } - public boolean dropExistingFile(Module module) + public boolean dropExistingFile(final Module module) { - - try { synchronized (writeIOSync) + try { - Path dataFile = toPath(module); - if (dataFile == null) return false; - return Files.deleteIfExists(dataFile); - } } - catch (IOException e) + synchronized (writeIOSync) + { + final Path dataFile = toPath(module); + if (dataFile == null) + { + return false; + } + return Files.deleteIfExists(dataFile); + } + } + catch (final IOException e) { CarpetScriptServer.LOG.warn("IOException when removing file", e); - throw new ThrowStatement("Error while removing file: "+getDisplayPath(), Throwables.IO_EXCEPTION); + throw new ThrowStatement("Error while removing file: " + getDisplayPath(), Throwables.IO_EXCEPTION); } finally { @@ -465,69 +562,95 @@ public boolean dropExistingFile(Module module) } } - public List listFile(Module module) + public List listFile(final Module module) { - try { synchronized (writeIOSync) { - Path dataFile = toPath(module); - if (dataFile == null) return null; - if (!Files.exists(dataFile)) return null; - return listFileContent(dataFile); - } } - finally { + try + { + synchronized (writeIOSync) + { + final Path dataFile = toPath(module); + if (dataFile == null) + { + return null; + } + if (!Files.exists(dataFile)) + { + return null; + } + return listFileContent(dataFile); + } + } + finally + { close(); } } - public static List listFileContent(Path filePath) + public static List listFileContent(final Path filePath) { - try (BufferedReader reader = Files.newBufferedReader(filePath, StandardCharsets.UTF_8)) { - List result = new ArrayList<>(); - for (;;) { - String line = reader.readLine(); + try (final BufferedReader reader = Files.newBufferedReader(filePath, StandardCharsets.UTF_8)) + { + final List result = new ArrayList<>(); + for (; ; ) + { + final String line = reader.readLine(); if (line == null) + { break; - result.add(line.replaceAll("[\n\r]+","")); + } + result.add(line.replaceAll("[\n\r]+", "")); } return result; } - catch (IOException e) + catch (final IOException e) { CarpetScriptServer.LOG.warn("IOException when reading text file", e); - throw new ThrowStatement("Failed to read text file "+filePath.toString(), Throwables.IO_EXCEPTION); + throw new ThrowStatement("Failed to read text file " + filePath, Throwables.IO_EXCEPTION); } } - public JsonElement readJsonFile(Module module) { - try { synchronized (writeIOSync) { - Path dataFile = toPath(module); - if (dataFile == null || !Files.exists(dataFile)) return null; - return readJsonContent(dataFile); - } } - finally { + public JsonElement readJsonFile(final Module module) + { + try + { + synchronized (writeIOSync) + { + final Path dataFile = toPath(module); + if (dataFile == null || !Files.exists(dataFile)) + { + return null; + } + return readJsonContent(dataFile); + } + } + finally + { close(); } } - public static JsonElement readJsonContent(Path filePath) + public static JsonElement readJsonContent(final Path filePath) { - try (BufferedReader reader = Files.newBufferedReader(filePath, StandardCharsets.UTF_8)) + try (final BufferedReader reader = Files.newBufferedReader(filePath, StandardCharsets.UTF_8)) { return JsonParser.parseReader(reader); } - catch (JsonParseException e) + catch (final JsonParseException e) { Throwable exc = e; - if(e.getCause() != null) + if (e.getCause() != null) + { exc = e.getCause(); + } throw new ThrowStatement(MapValue.wrap(Map.of( StringValue.of("error"), StringValue.of(exc.getMessage()), StringValue.of("path"), StringValue.of(filePath.toString()) )), Throwables.JSON_ERROR); } - catch (IOException e) + catch (final IOException e) { CarpetScriptServer.LOG.warn("IOException when reading JSON file", e); - throw new ThrowStatement("Failed to read json file content "+filePath.toString(), Throwables.IO_EXCEPTION); + throw new ThrowStatement("Failed to read json file content " + filePath, Throwables.IO_EXCEPTION); } } diff --git a/src/main/java/carpet/script/argument/FunctionArgument.java b/src/main/java/carpet/script/argument/FunctionArgument.java index 387cc66edc..eb19526fb0 100644 --- a/src/main/java/carpet/script/argument/FunctionArgument.java +++ b/src/main/java/carpet/script/argument/FunctionArgument.java @@ -19,7 +19,7 @@ public class FunctionArgument extends Argument public FunctionValue function; public List args; - private FunctionArgument(FunctionValue function, int offset, List args) + private FunctionArgument(final FunctionValue function, final int offset, final List args) { super(offset); this.function = function; @@ -27,10 +27,10 @@ private FunctionArgument(FunctionValue function, int offset, List args) } /** - * @param c context - * @param module module - * @param params list of params - * @param offset offset where to start looking for functional argument + * @param c context + * @param module module + * @param params list of params + * @param offset offset where to start looking for functional argument * @param allowNone none indicates no function present, otherwise it will croak * @param checkArgs whether the caller expects trailing parameters to fully resolve function argument list * if not - argument count check will not be performed and its up to the caller to verify @@ -38,63 +38,85 @@ private FunctionArgument(FunctionValue function, int offset, List args) * @return argument data */ public static FunctionArgument findIn( - Context c, - Module module, - List params, - int offset, - boolean allowNone, - boolean checkArgs) + final Context c, + final Module module, + final List params, + final int offset, + final boolean allowNone, + final boolean checkArgs) { Value functionValue = params.get(offset); if (functionValue.isNull()) { - if (allowNone) return new FunctionArgument(null, offset+1, Collections.emptyList()); + if (allowNone) + { + return new FunctionArgument(null, offset + 1, Collections.emptyList()); + } throw new InternalExpressionException("function argument cannot be null"); } if (!(functionValue instanceof FunctionValue)) { - String name = functionValue.getString(); + final String name = functionValue.getString(); functionValue = c.host.getAssertFunction(module, name); } - FunctionValue fun = (FunctionValue)functionValue; - int argsize = fun.getArguments().size(); + final FunctionValue fun = (FunctionValue) functionValue; + final int argsize = fun.getArguments().size(); if (checkArgs) { - int extraargs = params.size() - argsize - offset - 1; + final int extraargs = params.size() - argsize - offset - 1; if (extraargs < 0) + { throw new InternalExpressionException("Function " + fun.getPrettyString() + " requires at least " + fun.getArguments().size() + " arguments"); + } if (extraargs > 0 && fun.getVarArgs() == null) + { throw new InternalExpressionException("Function " + fun.getPrettyString() + " requires " + fun.getArguments().size() + " arguments"); + } + } + final List lvargs = new ArrayList<>(); + for (int i = offset + 1, mx = params.size(); i < mx; i++) + { + lvargs.add(params.get(i)); } - List lvargs = new ArrayList<>(); - for (int i = offset+1, mx = params.size(); i < mx; i++) lvargs.add(params.get(i)); return new FunctionArgument(fun, offset + 1 + argsize, lvargs); } - public static FunctionArgument fromCommandSpec(ScriptHost host, Value funSpec) throws CommandSyntaxException { - FunctionValue function; + public static FunctionArgument fromCommandSpec(final ScriptHost host, Value funSpec) throws CommandSyntaxException + { + final FunctionValue function; List args = Collections.emptyList(); if (!(funSpec instanceof ListValue)) + { funSpec = ListValue.of(funSpec); - List params = ((ListValue) funSpec).getItems(); - if (params.isEmpty()) throw CommandArgument.error("Function has empty spec"); - Value first = params.get(0); + } + final List params = ((ListValue) funSpec).getItems(); + if (params.isEmpty()) + { + throw CommandArgument.error("Function has empty spec"); + } + final Value first = params.get(0); if (first instanceof FunctionValue) { - function = (FunctionValue)first; + function = (FunctionValue) first; } else { - String name = first.getString(); + final String name = first.getString(); function = host.getFunction(name); - if (function == null) throw CommandArgument.error("Function "+name+" is not defined yet"); + if (function == null) + { + throw CommandArgument.error("Function " + name + " is not defined yet"); + } + } + if (params.size() > 1) + { + args = params.subList(1, params.size()); } - if (params.size() > 1) args = params.subList(1,params.size()); - return new FunctionArgument(function, 0, args); } - public List checkedArgs() { + public List checkedArgs() + { function.checkArgs(args.size()); return args; } diff --git a/src/main/java/carpet/script/argument/Vector3Argument.java b/src/main/java/carpet/script/argument/Vector3Argument.java index c19bb479f5..f46068e8fe 100644 --- a/src/main/java/carpet/script/argument/Vector3Argument.java +++ b/src/main/java/carpet/script/argument/Vector3Argument.java @@ -6,9 +6,11 @@ import carpet.script.value.ListValue; import carpet.script.value.NumericValue; import carpet.script.value.Value; + import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; + import net.minecraft.world.entity.Entity; import net.minecraft.world.phys.Vec3; @@ -19,14 +21,16 @@ public class Vector3Argument extends Argument public final double pitch; public boolean fromBlock = false; public Entity entity = null; - private Vector3Argument(Vec3 v, int o) + + private Vector3Argument(final Vec3 v, final int o) { super(o); this.vec = v; this.yaw = 0.0D; this.pitch = 0.0D; } - private Vector3Argument(Vec3 v, int o, double y, double p) + + private Vector3Argument(final Vec3 v, final int o, final double y, final double p) { super(o); this.vec = v; @@ -40,52 +44,53 @@ private Vector3Argument fromBlock() return this; } - private Vector3Argument withEntity(Entity e) + private Vector3Argument withEntity(final Entity e) { entity = e; return this; } - public static Vector3Argument findIn(List params, int offset) + public static Vector3Argument findIn(final List params, final int offset) { return findIn(params, offset, false, false); } - public static Vector3Argument findIn(List params, int offset, boolean optionalDirection, boolean optionalEntity) { + public static Vector3Argument findIn(final List params, final int offset, final boolean optionalDirection, final boolean optionalEntity) + { return findIn(params.listIterator(offset), offset, optionalDirection, optionalEntity); } - public static Vector3Argument findIn(Iterator params, int offset, boolean optionalDirection, boolean optionalEntity) + public static Vector3Argument findIn(final Iterator params, final int offset, final boolean optionalDirection, final boolean optionalEntity) { try { - Value v1 = params.next(); + final Value v1 = params.next(); if (v1 instanceof BlockValue) { - return (new Vector3Argument(Vec3.atCenterOf(((BlockValue) v1).getPos()), 1+offset)).fromBlock(); + return (new Vector3Argument(Vec3.atCenterOf(((BlockValue) v1).getPos()), 1 + offset)).fromBlock(); } if (optionalEntity && v1 instanceof EntityValue) { - Entity e = ((EntityValue) v1).getEntity(); - return new Vector3Argument(e.position(), 1+offset).withEntity(e); + final Entity e = ((EntityValue) v1).getEntity(); + return new Vector3Argument(e.position(), 1 + offset).withEntity(e); } if (v1 instanceof ListValue) { - List args = ((ListValue) v1).getItems(); - Vec3 pos = new Vec3( + final List args = ((ListValue) v1).getItems(); + final Vec3 pos = new Vec3( NumericValue.asNumber(args.get(0)).getDouble(), NumericValue.asNumber(args.get(1)).getDouble(), NumericValue.asNumber(args.get(2)).getDouble()); double yaw = 0.0D; double pitch = 0.0D; - if (args.size()>3 && optionalDirection) + if (args.size() > 3 && optionalDirection) { yaw = NumericValue.asNumber(args.get(3)).getDouble(); pitch = NumericValue.asNumber(args.get(4)).getDouble(); } - return new Vector3Argument(pos,offset+1, yaw, pitch); + return new Vector3Argument(pos, offset + 1, yaw, pitch); } - Vec3 pos = new Vec3( + final Vec3 pos = new Vec3( NumericValue.asNumber(v1).getDouble(), NumericValue.asNumber(params.next()).getDouble(), NumericValue.asNumber(params.next()).getDouble()); @@ -99,9 +104,9 @@ public static Vector3Argument findIn(Iterator params, int offset, boolean eatenLength = 5; } - return new Vector3Argument(pos, offset+eatenLength, yaw, pitch); + return new Vector3Argument(pos, offset + eatenLength, yaw, pitch); } - catch (IndexOutOfBoundsException | NoSuchElementException e) + catch (final IndexOutOfBoundsException | NoSuchElementException e) { throw new InternalExpressionException("Position argument should be defined either by three coordinates (a triple or by three arguments), or a positioned block value"); } diff --git a/src/main/java/carpet/script/command/CommandArgument.java b/src/main/java/carpet/script/command/CommandArgument.java index 5fcd34ba24..f0619c7430 100644 --- a/src/main/java/carpet/script/command/CommandArgument.java +++ b/src/main/java/carpet/script/command/CommandArgument.java @@ -39,6 +39,7 @@ import com.mojang.brigadier.suggestion.SuggestionsBuilder; import com.mojang.brigadier.tree.ArgumentCommandNode; import com.mojang.brigadier.tree.CommandNode; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -53,6 +54,7 @@ import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; + import net.minecraft.ChatFormatting; import net.minecraft.advancements.Advancement; import net.minecraft.advancements.critereon.MinMaxBounds; @@ -110,36 +112,33 @@ public abstract class CommandArgument { - public static CommandSyntaxException error(String text) + public static CommandSyntaxException error(final String text) { return new SimpleCommandExceptionType(Component.literal(text)).create(); } - private static final DynamicCommandExceptionType ERROR_BIOME_INVALID = new DynamicCommandExceptionType(v -> Component.translatable("commands.locate.biome.invalid", v)); - - private static final List baseTypes = Lists.newArrayList( // default new StringArgument(), // vanilla arguments as per https://minecraft.gamepedia.com/Argument_types - new VanillaUnconfigurableArgument( "bool", BoolArgumentType::bool, + new VanillaUnconfigurableArgument("bool", BoolArgumentType::bool, (c, p) -> BooleanValue.of(BoolArgumentType.getBool(c, p)), false ), new FloatArgument(), new IntArgument(), new WordArgument(), new GreedyStringArgument(), - new VanillaUnconfigurableArgument( "yaw", AngleArgument::angle, // angle + new VanillaUnconfigurableArgument("yaw", AngleArgument::angle, // angle (c, p) -> new NumericValue(AngleArgument.getAngle(c, p)), true ), new BlockPosArgument(), - new VanillaUnconfigurableArgument( "block", BlockStateArgument::block, + new VanillaUnconfigurableArgument("block", BlockStateArgument::block, (c, p) -> { BlockInput result = BlockStateArgument.getBlock(c, p); - return new BlockValue(result.getState(), c.getSource().getLevel(), null, ((BlockStateArgumentInterface)result).getCMTag() ); + return new BlockValue(result.getState(), c.getSource().getLevel(), null, ((BlockStateArgumentInterface) result).getCMTag()); }, param -> (ctx, builder) -> ctx.getArgument(param, BlockStateArgument.class).listSuggestions(ctx, builder) ), - new VanillaUnconfigurableArgument( "blockpredicate", BlockPredicateArgument::blockPredicate, + new VanillaUnconfigurableArgument("blockpredicate", BlockPredicateArgument::blockPredicate, (c, p) -> ValueConversions.ofBlockPredicate(c.getSource().getServer().registryAccess(), BlockPredicateArgument.getBlockPredicate(c, p)), param -> (ctx, builder) -> ctx.getArgument(param, BlockPredicateArgument.class).listSuggestions(ctx, builder) ), @@ -204,21 +203,21 @@ public static CommandSyntaxException error(String text) // resource / identifier section new VanillaUnconfigurableArgument("recipe", ResourceLocationArgument::id, - (c, p) -> ValueConversions.of( ResourceLocationArgument.getRecipe(c, p).getId()), SuggestionProviders.ALL_RECIPES + (c, p) -> ValueConversions.of(ResourceLocationArgument.getRecipe(c, p).getId()), SuggestionProviders.ALL_RECIPES ), new VanillaUnconfigurableArgument("advancement", ResourceLocationArgument::id, - (c, p) -> ValueConversions.of( ResourceLocationArgument.getAdvancement(c, p).getId()), (ctx, builder) -> SharedSuggestionProvider.suggestResource(ctx.getSource().getServer().getAdvancements().getAllAdvancements().stream().map(Advancement::getId), builder) + (c, p) -> ValueConversions.of(ResourceLocationArgument.getAdvancement(c, p).getId()), (ctx, builder) -> SharedSuggestionProvider.suggestResource(ctx.getSource().getServer().getAdvancements().getAllAdvancements().stream().map(Advancement::getId), builder) ), new VanillaUnconfigurableArgument("lootcondition", ResourceLocationArgument::id, - (c, p) -> ValueConversions.of( c.getSource().registryAccess().registryOrThrow(Registries.LOOT_CONDITION_TYPE).getKey(ResourceLocationArgument.getPredicate(c, p).getType())), (ctx, builder) -> SharedSuggestionProvider.suggestResource(ctx.getSource().getServer().getPredicateManager().getKeys(), builder) + (c, p) -> ValueConversions.of(c.getSource().registryAccess().registryOrThrow(Registries.LOOT_CONDITION_TYPE).getKey(ResourceLocationArgument.getPredicate(c, p).getType())), (ctx, builder) -> SharedSuggestionProvider.suggestResource(ctx.getSource().getServer().getPredicateManager().getKeys(), builder) ), new VanillaUnconfigurableArgument("loottable", ResourceLocationArgument::id, - (c, p) -> ValueConversions.of( ResourceLocationArgument.getId(c, p)), (ctx, builder) -> SharedSuggestionProvider.suggestResource(ctx.getSource().getServer().getLootTables().getIds(), builder) + (c, p) -> ValueConversions.of(ResourceLocationArgument.getId(c, p)), (ctx, builder) -> SharedSuggestionProvider.suggestResource(ctx.getSource().getServer().getLootTables().getIds(), builder) ), new VanillaUnconfigurableArgument("attribute", Registries.ATTRIBUTE), new VanillaUnconfigurableArgument("boss", ResourceLocationArgument::id, - (c, p) -> ValueConversions.of( ResourceLocationArgument.getId(c, p)), BossBarCommands.SUGGEST_BOSS_BAR + (c, p) -> ValueConversions.of(ResourceLocationArgument.getId(c, p)), BossBarCommands.SUGGEST_BOSS_BAR ), new VanillaUnconfigurableArgument("biome", (c) -> ResourceOrTagArgument.resourceOrTag(c, Registries.BIOME), @@ -237,10 +236,10 @@ public static CommandSyntaxException error(String text) }, (ctx, builder) -> SharedSuggestionProvider.suggestResource(ctx.getSource().getServer().registryAccess().registryOrThrow(Registries.BIOME).keySet(), builder) ), new VanillaUnconfigurableArgument("sound", ResourceLocationArgument::id, - (c, p) -> ValueConversions.of( ResourceLocationArgument.getId(c, p)), SuggestionProviders.AVAILABLE_SOUNDS + (c, p) -> ValueConversions.of(ResourceLocationArgument.getId(c, p)), SuggestionProviders.AVAILABLE_SOUNDS ), new VanillaUnconfigurableArgument("storekey", ResourceLocationArgument::id, - (c, p) -> ValueConversions.of( ResourceLocationArgument.getId(c, p)), (ctx, builder) -> SharedSuggestionProvider.suggestResource(ctx.getSource().getServer().getCommandStorage().keys(), builder) + (c, p) -> ValueConversions.of(ResourceLocationArgument.getId(c, p)), (ctx, builder) -> SharedSuggestionProvider.suggestResource(ctx.getSource().getServer().getCommandStorage().keys(), builder) ), // default @@ -286,29 +285,41 @@ public static CommandSyntaxException error(String text) public static final CommandArgument DEFAULT = baseTypes.get(0); - public static CommandArgument getTypeForArgument(String argument, CarpetScriptHost host) + public static CommandArgument getTypeForArgument(final String argument, final CarpetScriptHost host) { - String[] components = argument.split("_"); + final String[] components = argument.split("_"); CommandArgument arg; for (int i = 0; i < components.length; i++) { - String candidate = String.join("_", Arrays.asList(components).subList(i, components.length)); + final String candidate = String.join("_", Arrays.asList(components).subList(i, components.length)); arg = host.appArgTypes.get(candidate); - if (arg != null) return arg; + if (arg != null) + { + return arg; + } arg = builtIns.get(candidate); - if (arg != null) return arg; + if (arg != null) + { + return arg; + } } return DEFAULT; } - public static RequiredArgumentBuilder argumentNode(String param, CarpetScriptHost host) throws CommandSyntaxException + public static RequiredArgumentBuilder argumentNode(final String param, final CarpetScriptHost host) throws CommandSyntaxException { - CommandArgument arg = getTypeForArgument(param, host); - if (arg.suggestionProvider != null) return argument(param, arg.getArgumentType(host)).suggests(arg.suggestionProvider.apply(param)); - if (!arg.needsMatching) return argument(param, arg.getArgumentType(host)); - String hostName = host.getName(); + final CommandArgument arg = getTypeForArgument(param, host); + if (arg.suggestionProvider != null) + { + return argument(param, arg.getArgumentType(host)).suggests(arg.suggestionProvider.apply(param)); + } + if (!arg.needsMatching) + { + return argument(param, arg.getArgumentType(host)); + } + final String hostName = host.getName(); return argument(param, arg.getArgumentType(host)).suggests((ctx, b) -> { - CarpetScriptHost cHost = CarpetServer.scriptServer.modules.get(hostName).retrieveOwnForExecution(ctx.getSource()); + final CarpetScriptHost cHost = CarpetServer.scriptServer.modules.get(hostName).retrieveOwnForExecution(ctx.getSource()); return arg.suggest(ctx, b, cHost); }); } @@ -322,9 +333,9 @@ public static CommandArgument getTypeForArgument(String argument, CarpetScriptHo protected CommandArgument( - String suffix, - Collection examples, - boolean suggestFromExamples) + final String suffix, + final Collection examples, + final boolean suggestFromExamples) { this.suffix = suffix; this.examples = examples; @@ -334,7 +345,7 @@ protected CommandArgument( protected abstract ArgumentType getArgumentType(CarpetScriptHost host) throws CommandSyntaxException; - public static Value getValue(CommandContext context, String param, CarpetScriptHost host) throws CommandSyntaxException + public static Value getValue(final CommandContext context, final String param, final CarpetScriptHost host) throws CommandSyntaxException { return getTypeForArgument(param, host).getValueFromContext(context, param); } @@ -346,20 +357,24 @@ public String getTypeSuffix() return suffix; } - public static CommandArgument buildFromConfig(String suffix, Map config, CarpetScriptHost host) throws CommandSyntaxException + public static CommandArgument buildFromConfig(final String suffix, final Map config, final CarpetScriptHost host) throws CommandSyntaxException { if (!config.containsKey("type")) - throw CommandArgument.error("Custom type "+suffix+" should at least specify the type"); - String baseType = config.get("type").getString(); + { + throw CommandArgument.error("Custom type " + suffix + " should at least specify the type"); + } + final String baseType = config.get("type").getString(); if (!builtIns.containsKey(baseType)) - throw CommandArgument.error("Unknown base type "+baseType+" for custom type "+suffix); - CommandArgument variant = builtIns.get(baseType).factory(host.scriptServer().server).get(); + { + throw CommandArgument.error("Unknown base type " + baseType + " for custom type " + suffix); + } + final CommandArgument variant = builtIns.get(baseType).factory(host.scriptServer().server).get(); variant.suffix = suffix; variant.configure(config, host); return variant; } - protected void configure(Map config, CarpetScriptHost host) throws CommandSyntaxException + protected void configure(final Map config, final CarpetScriptHost host) throws CommandSyntaxException { caseSensitive = config.getOrDefault("case_sensitive", Value.TRUE).getBoolean(); if (config.containsKey("suggester")) @@ -368,74 +383,87 @@ protected void configure(Map config, CarpetScriptHost host) throw } if (config.containsKey("suggest")) { - if (config.containsKey("suggester")) throw error("Attempted to provide 'suggest' list while 'suggester' is present"+" for custom type "+suffix); - Value suggestionValue = config.get("suggest"); - if (!(suggestionValue instanceof ListValue)) throw error("Argument suggestions needs to be a list"+" for custom type "+suffix); + if (config.containsKey("suggester")) + { + throw error("Attempted to provide 'suggest' list while 'suggester' is present" + " for custom type " + suffix); + } + final Value suggestionValue = config.get("suggest"); + if (!(suggestionValue instanceof ListValue)) + { + throw error("Argument suggestions needs to be a list" + " for custom type " + suffix); + } examples = ((ListValue) suggestionValue).getItems().stream() .map(Value::getString) .collect(Collectors.toSet()); - if (!examples.isEmpty()) needsMatching = true; + if (!examples.isEmpty()) + { + needsMatching = true; + } } } public CompletableFuture suggest( - CommandContext context, - SuggestionsBuilder suggestionsBuilder, - CarpetScriptHost host + final CommandContext context, + final SuggestionsBuilder suggestionsBuilder, + final CarpetScriptHost host ) throws CommandSyntaxException { String prefix = suggestionsBuilder.getRemaining(); - if (!caseSensitive) prefix = prefix.toLowerCase(Locale.ROOT); + if (!caseSensitive) + { + prefix = prefix.toLowerCase(Locale.ROOT); + } suggestFor(context, prefix, host).forEach(suggestionsBuilder::suggest); return suggestionsBuilder.buildFuture(); } - protected List suggestFor(CommandContext context, String prefix, CarpetScriptHost host) throws CommandSyntaxException + protected List suggestFor(final CommandContext context, final String prefix, final CarpetScriptHost host) throws CommandSyntaxException { return getOptions(context, host).stream().filter(s -> optionMatchesPrefix(prefix, s)).collect(Collectors.toList()); } - protected Collection getOptions(CommandContext context, CarpetScriptHost host) throws CommandSyntaxException + protected Collection getOptions(final CommandContext context, final CarpetScriptHost host) throws CommandSyntaxException { if (customSuggester != null) { - CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet command", CarpetProfiler.TYPE.GENERAL); - Map params = new HashMap<>(); - for(ParsedCommandNode pnode : context.getNodes()) + final CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet command", CarpetProfiler.TYPE.GENERAL); + final Map params = new HashMap<>(); + for (final ParsedCommandNode pnode : context.getNodes()) { - CommandNode node = pnode.getNode(); + final CommandNode node = pnode.getNode(); if (node instanceof ArgumentCommandNode) { params.put(StringValue.of(node.getName()), CommandArgument.getValue(context, node.getName(), host)); } } - List args = new ArrayList<>(customSuggester.args.size()+1); + final List args = new ArrayList<>(customSuggester.args.size() + 1); args.add(MapValue.wrap(params)); args.addAll(customSuggester.args); - Value response = host.handleCommand(context.getSource(), customSuggester.function, args); - if (!(response instanceof ListValue)) throw error("Custom suggester should return a list of options"+" for custom type "+suffix); - Collection res = ((ListValue) response).getItems().stream().map(Value::getString).collect(Collectors.toList()); + final Value response = host.handleCommand(context.getSource(), customSuggester.function, args); + if (!(response instanceof ListValue)) + { + throw error("Custom suggester should return a list of options" + " for custom type " + suffix); + } + final Collection res = ((ListValue) response).getItems().stream().map(Value::getString).collect(Collectors.toList()); CarpetProfiler.end_current_section(currentSection); return res; } - if (needsMatching) return examples; - //return Lists.newArrayList(""); - // better than nothing I guess - // nothing is such a bad default. - return Collections.singletonList("... "+getTypeSuffix()); + return needsMatching ? examples : Collections.singletonList("... " + getTypeSuffix()); } - protected boolean optionMatchesPrefix(String prefix, String option) + protected boolean optionMatchesPrefix(final String prefix, String option) { if (!caseSensitive) { - //prefix = prefix.toLowerCase(Locale.ROOT); option = option.toLowerCase(Locale.ROOT); } - for(int i = 0; !option.startsWith(prefix, i); ++i) + for (int i = 0; !option.startsWith(prefix, i); ++i) { i = option.indexOf('_', i); - if (i < 0) return false; + if (i < 0) + { + return false; + } } return true; } @@ -445,69 +473,105 @@ protected boolean optionMatchesPrefix(String prefix, String option) private static class StringArgument extends CommandArgument { Set validOptions = Collections.emptySet(); + private StringArgument() { super("string", StringArgumentType.StringType.QUOTABLE_PHRASE.getExamples(), true); } @Override - public ArgumentType getArgumentType(CarpetScriptHost host) + public ArgumentType getArgumentType(final CarpetScriptHost host) { return StringArgumentType.string(); } @Override - public Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException + public Value getValueFromContext(final CommandContext context, final String param) throws CommandSyntaxException { String choseValue = StringArgumentType.getString(context, param); - if (!caseSensitive) choseValue = choseValue.toLowerCase(Locale.ROOT); + if (!caseSensitive) + { + choseValue = choseValue.toLowerCase(Locale.ROOT); + } if (!validOptions.isEmpty() && !validOptions.contains(choseValue)) { - throw new SimpleCommandExceptionType(Component.literal("Incorrect value for "+param+": "+choseValue+" for custom type "+suffix)).create(); + throw new SimpleCommandExceptionType(Component.literal("Incorrect value for " + param + ": " + choseValue + " for custom type " + suffix)).create(); } return StringValue.of(choseValue); } @Override - protected void configure(Map config, CarpetScriptHost host) throws CommandSyntaxException + protected void configure(final Map config, final CarpetScriptHost host) throws CommandSyntaxException { super.configure(config, host); if (config.containsKey("options")) { - Value optionsValue = config.get("options"); - if (!(optionsValue instanceof ListValue)) throw error("Custom string type requires options passed as a list"+" for custom type "+suffix); + final Value optionsValue = config.get("options"); + if (!(optionsValue instanceof ListValue)) + { + throw error("Custom string type requires options passed as a list" + " for custom type " + suffix); + } validOptions = ((ListValue) optionsValue).getItems().stream() - .map(v -> caseSensitive?v.getString():(v.getString().toLowerCase(Locale.ROOT))) + .map(v -> caseSensitive ? v.getString() : (v.getString().toLowerCase(Locale.ROOT))) .collect(Collectors.toSet()); } } @Override - protected Collection getOptions(CommandContext context, CarpetScriptHost host) throws CommandSyntaxException + protected Collection getOptions(final CommandContext context, final CarpetScriptHost host) throws CommandSyntaxException { - return validOptions.isEmpty()?super.getOptions(context, host):validOptions; + return validOptions.isEmpty() ? super.getOptions(context, host) : validOptions; } @Override - protected Supplier factory(MinecraftServer server) { return StringArgument::new; } + protected Supplier factory(final MinecraftServer server) + { + return StringArgument::new; + } } private static class WordArgument extends StringArgument { - private WordArgument() { super(); suffix = "term"; examples = StringArgumentType.StringType.SINGLE_WORD.getExamples(); } + private WordArgument() + { + super(); + suffix = "term"; + examples = StringArgumentType.StringType.SINGLE_WORD.getExamples(); + } + @Override - public ArgumentType getArgumentType(CarpetScriptHost host) { return StringArgumentType.word(); } + public ArgumentType getArgumentType(final CarpetScriptHost host) + { + return StringArgumentType.word(); + } + @Override - protected Supplier factory(MinecraftServer server) { return WordArgument::new; } + protected Supplier factory(final MinecraftServer server) + { + return WordArgument::new; + } } private static class GreedyStringArgument extends StringArgument { - private GreedyStringArgument() { super();suffix = "text"; examples = StringArgumentType.StringType.GREEDY_PHRASE.getExamples(); } + private GreedyStringArgument() + { + super(); + suffix = "text"; + examples = StringArgumentType.StringType.GREEDY_PHRASE.getExamples(); + } + @Override - public ArgumentType getArgumentType(CarpetScriptHost host) { return StringArgumentType.greedyString(); } + public ArgumentType getArgumentType(final CarpetScriptHost host) + { + return StringArgumentType.greedyString(); + } + @Override - protected Supplier factory(MinecraftServer server) { return GreedyStringArgument::new; } + protected Supplier factory(final MinecraftServer server) + { + return GreedyStringArgument::new; + } } private static class BlockPosArgument extends CommandArgument @@ -520,29 +584,29 @@ private BlockPosArgument() } @Override - public ArgumentType getArgumentType(CarpetScriptHost host) + public ArgumentType getArgumentType(final CarpetScriptHost host) { return net.minecraft.commands.arguments.coordinates.BlockPosArgument.blockPos(); } @Override - public Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException + public Value getValueFromContext(final CommandContext context, final String param) throws CommandSyntaxException { - BlockPos pos = mustBeLoaded + final BlockPos pos = mustBeLoaded ? net.minecraft.commands.arguments.coordinates.BlockPosArgument.getLoadedBlockPos(context, param) : net.minecraft.commands.arguments.coordinates.BlockPosArgument.getSpawnablePos(context, param); return ValueConversions.of(pos); } @Override - protected void configure(Map config, CarpetScriptHost host) throws CommandSyntaxException + protected void configure(final Map config, final CarpetScriptHost host) throws CommandSyntaxException { super.configure(config, host); mustBeLoaded = config.getOrDefault("loaded", Value.FALSE).getBoolean(); } @Override - protected Supplier factory(MinecraftServer server) + protected Supplier factory(final MinecraftServer server) { return BlockPosArgument::new; } @@ -557,27 +621,28 @@ private LocationArgument() super("location", Vec3Argument.vec3().getExamples(), false); blockCentered = true; } + @Override - protected ArgumentType getArgumentType(CarpetScriptHost host) + protected ArgumentType getArgumentType(final CarpetScriptHost host) { return Vec3Argument.vec3(blockCentered); } @Override - protected Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException + protected Value getValueFromContext(final CommandContext context, final String param) throws CommandSyntaxException { return ValueConversions.of(Vec3Argument.getVec3(context, param)); } @Override - protected void configure(Map config, CarpetScriptHost host) throws CommandSyntaxException + protected void configure(final Map config, final CarpetScriptHost host) throws CommandSyntaxException { super.configure(config, host); blockCentered = config.getOrDefault("block_centered", Value.TRUE).getBoolean(); } @Override - protected Supplier factory(MinecraftServer server) + protected Supplier factory(final MinecraftServer server) { return LocationArgument::new; } @@ -594,31 +659,38 @@ private EntityArgument() onlyFans = false; single = false; } + @Override - protected ArgumentType getArgumentType(CarpetScriptHost host) + protected ArgumentType getArgumentType(final CarpetScriptHost host) { if (onlyFans) { - return single?net.minecraft.commands.arguments.EntityArgument.player():net.minecraft.commands.arguments.EntityArgument.players(); - } - else - { - return single?net.minecraft.commands.arguments.EntityArgument.entity():net.minecraft.commands.arguments.EntityArgument.entities(); + return single ? net.minecraft.commands.arguments.EntityArgument.player() : net.minecraft.commands.arguments.EntityArgument.players(); } + return single ? net.minecraft.commands.arguments.EntityArgument.entity() : net.minecraft.commands.arguments.EntityArgument.entities(); } @Override - protected Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException + protected Value getValueFromContext(final CommandContext context, final String param) throws CommandSyntaxException { - Collection founds = net.minecraft.commands.arguments.EntityArgument.getOptionalEntities(context, param); - if (!single) return ListValue.wrap(founds.stream().map(EntityValue::new)); - if (founds.size() == 0) return Value.NULL; - if (founds.size() == 1) return new EntityValue(founds.iterator().next()); - throw new SimpleCommandExceptionType(Component.literal("Multiple entities returned while only one was requested"+" for custom type "+suffix)).create(); + final Collection founds = net.minecraft.commands.arguments.EntityArgument.getOptionalEntities(context, param); + if (!single) + { + return ListValue.wrap(founds.stream().map(EntityValue::new)); + } + if (founds.size() == 0) + { + return Value.NULL; + } + if (founds.size() == 1) + { + return new EntityValue(founds.iterator().next()); + } + throw new SimpleCommandExceptionType(Component.literal("Multiple entities returned while only one was requested" + " for custom type " + suffix)).create(); } @Override - protected void configure(Map config, CarpetScriptHost host) throws CommandSyntaxException + protected void configure(final Map config, final CarpetScriptHost host) throws CommandSyntaxException { super.configure(config, host); onlyFans = config.getOrDefault("players", Value.FALSE).getBoolean(); @@ -626,7 +698,7 @@ protected void configure(Map config, CarpetScriptHost host) throw } @Override - protected Supplier factory(MinecraftServer server) + protected Supplier factory(final MinecraftServer server) { return EntityArgument::new; } @@ -641,32 +713,42 @@ private PlayerProfileArgument() super("players", GameProfileArgument.gameProfile().getExamples(), false); single = false; } + @Override - protected ArgumentType getArgumentType(CarpetScriptHost host) + protected ArgumentType getArgumentType(final CarpetScriptHost host) { return GameProfileArgument.gameProfile(); } @Override - protected Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException + protected Value getValueFromContext(final CommandContext context, final String param) throws CommandSyntaxException { - Collection profiles = GameProfileArgument.getGameProfiles(context, param); - if (!single) return ListValue.wrap(profiles.stream().map(p -> StringValue.of(p.getName()))); - int size = profiles.size(); - if (size == 0) return Value.NULL; - if (size == 1) return StringValue.of(profiles.iterator().next().getName()); - throw new SimpleCommandExceptionType(Component.literal("Multiple game profiles returned while only one was requested"+" for custom type "+suffix)).create(); + final Collection profiles = GameProfileArgument.getGameProfiles(context, param); + if (!single) + { + return ListValue.wrap(profiles.stream().map(p -> StringValue.of(p.getName()))); + } + final int size = profiles.size(); + if (size == 0) + { + return Value.NULL; + } + if (size == 1) + { + return StringValue.of(profiles.iterator().next().getName()); + } + throw new SimpleCommandExceptionType(Component.literal("Multiple game profiles returned while only one was requested" + " for custom type " + suffix)).create(); } @Override - protected void configure(Map config, CarpetScriptHost host) throws CommandSyntaxException + protected void configure(final Map config, final CarpetScriptHost host) throws CommandSyntaxException { super.configure(config, host); single = config.getOrDefault("single", Value.FALSE).getBoolean(); } @Override - protected Supplier factory(MinecraftServer server) + protected Supplier factory(final MinecraftServer server) { return PlayerProfileArgument::new; } @@ -682,32 +764,42 @@ private ScoreholderArgument() single = false; suggestionProvider = param -> ScoreHolderArgument.SUGGEST_SCORE_HOLDERS; } + @Override - protected ArgumentType getArgumentType(CarpetScriptHost host) + protected ArgumentType getArgumentType(final CarpetScriptHost host) { - return single?ScoreHolderArgument.scoreHolder():ScoreHolderArgument.scoreHolders(); + return single ? ScoreHolderArgument.scoreHolder() : ScoreHolderArgument.scoreHolders(); } @Override - protected Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException + protected Value getValueFromContext(final CommandContext context, final String param) throws CommandSyntaxException { - Collection holders = ScoreHolderArgument.getNames(context, param); - if (!single) return ListValue.wrap(holders.stream().map(StringValue::of)); - int size = holders.size(); - if (size == 0) return Value.NULL; - if (size == 1) return StringValue.of(holders.iterator().next()); - throw new SimpleCommandExceptionType(Component.literal("Multiple score holders returned while only one was requested"+" for custom type "+suffix)).create(); + final Collection holders = ScoreHolderArgument.getNames(context, param); + if (!single) + { + return ListValue.wrap(holders.stream().map(StringValue::of)); + } + final int size = holders.size(); + if (size == 0) + { + return Value.NULL; + } + if (size == 1) + { + return StringValue.of(holders.iterator().next()); + } + throw new SimpleCommandExceptionType(Component.literal("Multiple score holders returned while only one was requested" + " for custom type " + suffix)).create(); } @Override - protected void configure(Map config, CarpetScriptHost host) throws CommandSyntaxException + protected void configure(final Map config, final CarpetScriptHost host) throws CommandSyntaxException { super.configure(config, host); single = config.getOrDefault("single", Value.FALSE).getBoolean(); } @Override - protected Supplier factory(MinecraftServer server) + protected Supplier factory(final MinecraftServer server) { return PlayerProfileArgument::new; } @@ -716,35 +808,36 @@ protected Supplier factory(MinecraftServer server) private static class TagArgument extends CommandArgument { boolean mapRequired; + private TagArgument() { super("tag", CompoundTagArgument.compoundTag().getExamples(), false); mapRequired = true; } + @Override - protected ArgumentType getArgumentType(CarpetScriptHost host) + protected ArgumentType getArgumentType(final CarpetScriptHost host) { - return mapRequired?CompoundTagArgument.compoundTag(): NbtTagArgument.nbtTag(); + return mapRequired ? CompoundTagArgument.compoundTag() : NbtTagArgument.nbtTag(); } @Override - protected Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException + protected Value getValueFromContext(final CommandContext context, final String param) throws CommandSyntaxException { - if (mapRequired) - return new NBTSerializableValue(CompoundTagArgument.getCompoundTag(context, param)); - else - return new NBTSerializableValue(NbtTagArgument.getNbtTag(context, param)); + return mapRequired + ? new NBTSerializableValue(CompoundTagArgument.getCompoundTag(context, param)) + : new NBTSerializableValue(NbtTagArgument.getNbtTag(context, param)); } @Override - protected void configure(Map config, CarpetScriptHost host) throws CommandSyntaxException + protected void configure(final Map config, final CarpetScriptHost host) throws CommandSyntaxException { super.configure(config, host); mapRequired = !config.getOrDefault("allow_element", Value.FALSE).getBoolean(); } @Override - protected Supplier factory(MinecraftServer server) + protected Supplier factory(final MinecraftServer server) { return TagArgument::new; } @@ -760,36 +853,39 @@ protected CustomIdentifierArgument() } @Override - protected ArgumentType getArgumentType(CarpetScriptHost host) + protected ArgumentType getArgumentType(final CarpetScriptHost host) { return ResourceLocationArgument.id(); } @Override - protected Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException + protected Value getValueFromContext(final CommandContext context, final String param) throws CommandSyntaxException { - ResourceLocation choseValue = ResourceLocationArgument.getId(context, param); + final ResourceLocation choseValue = ResourceLocationArgument.getId(context, param); if (!validOptions.isEmpty() && !validOptions.contains(choseValue)) { - throw new SimpleCommandExceptionType(Component.literal("Incorrect value for "+param+": "+choseValue+" for custom type "+suffix)).create(); + throw new SimpleCommandExceptionType(Component.literal("Incorrect value for " + param + ": " + choseValue + " for custom type " + suffix)).create(); } return ValueConversions.of(choseValue); } @Override - protected Supplier factory(MinecraftServer server) + protected Supplier factory(final MinecraftServer server) { return CustomIdentifierArgument::new; } @Override - protected void configure(Map config, CarpetScriptHost host) throws CommandSyntaxException + protected void configure(final Map config, final CarpetScriptHost host) throws CommandSyntaxException { super.configure(config, host); if (config.containsKey("options")) { - Value optionsValue = config.get("options"); - if (!(optionsValue instanceof ListValue)) throw error("Custom sting type requires options passed as a list"+" for custom type "+suffix); + final Value optionsValue = config.get("options"); + if (!(optionsValue instanceof ListValue)) + { + throw error("Custom sting type requires options passed as a list" + " for custom type " + suffix); + } validOptions = ((ListValue) optionsValue).getItems().stream().map(v -> new ResourceLocation(v.getString())).collect(Collectors.toSet()); } } @@ -799,13 +895,14 @@ private static class FloatArgument extends CommandArgument { private Double min = null; private Double max = null; + private FloatArgument() { super("float", DoubleArgumentType.doubleArg().getExamples(), true); } @Override - public ArgumentType getArgumentType(CarpetScriptHost host) + public ArgumentType getArgumentType(final CarpetScriptHost host) { if (min != null) { @@ -819,13 +916,13 @@ public ArgumentType getArgumentType(CarpetScriptHost host) } @Override - public Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException + public Value getValueFromContext(final CommandContext context, final String param) throws CommandSyntaxException { return new NumericValue(DoubleArgumentType.getDouble(context, param)); } @Override - protected void configure(Map config, CarpetScriptHost host) throws CommandSyntaxException + protected void configure(final Map config, final CarpetScriptHost host) throws CommandSyntaxException { super.configure(config, host); if (config.containsKey("min")) @@ -836,11 +933,14 @@ protected void configure(Map config, CarpetScriptHost host) throw { max = NumericValue.asNumber(config.get("max"), "max").getDouble(); } - if (max != null && min == null) throw error("Double types cannot be only upper-bounded"+" for custom type "+suffix); + if (max != null && min == null) + { + throw error("Double types cannot be only upper-bounded" + " for custom type " + suffix); + } } @Override - protected Supplier factory(MinecraftServer server) + protected Supplier factory(final MinecraftServer server) { return FloatArgument::new; } @@ -850,13 +950,14 @@ private static class IntArgument extends CommandArgument { private Long min = null; private Long max = null; + private IntArgument() { super("int", LongArgumentType.longArg().getExamples(), true); } @Override - public ArgumentType getArgumentType(CarpetScriptHost host) + public ArgumentType getArgumentType(final CarpetScriptHost host) { if (min != null) { @@ -870,13 +971,13 @@ public ArgumentType getArgumentType(CarpetScriptHost host) } @Override - public Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException + public Value getValueFromContext(final CommandContext context, final String param) throws CommandSyntaxException { return new NumericValue(LongArgumentType.getLong(context, param)); } @Override - protected void configure(Map config, CarpetScriptHost host) throws CommandSyntaxException + protected void configure(final Map config, final CarpetScriptHost host) throws CommandSyntaxException { super.configure(config, host); if (config.containsKey("min")) @@ -887,57 +988,112 @@ protected void configure(Map config, CarpetScriptHost host) throw { max = NumericValue.asNumber(config.get("max"), "max").getLong(); } - if (max != null && min == null) throw error("Double types cannot be only upper-bounded"+" for custom type "+suffix); + if (max != null && min == null) + { + throw error("Double types cannot be only upper-bounded" + " for custom type " + suffix); + } } @Override - protected Supplier factory(MinecraftServer server) + protected Supplier factory(final MinecraftServer server) { return IntArgument::new; } } + private static class SlotArgument extends CommandArgument { - private static record ContainerIds(IntSet numericalIds, Set commandIds) {} + private record ContainerIds(IntSet numericalIds, Set commandIds) + { + } + private String restrict; - private static final Map RESTRICTED_CONTAINERS = new HashMap(){{ + private static final Map RESTRICTED_CONTAINERS = new HashMap<>() + {{ int i; - for (String source : Arrays.asList("player", "enderchest", "equipment", "armor", "weapon", "container", "villager", "horse")) + for (final String source : Arrays.asList("player", "enderchest", "equipment", "armor", "weapon", "container", "villager", "horse")) + { put(source, new ContainerIds(new IntOpenHashSet(), new HashSet<>())); - for (i = 0; i < 41; i++) get("player").numericalIds().add(i); - for(i = 0; i < 41; i++) get("player").commandIds().add("container." + i); - for(i = 0; i < 9; i++) get("player").commandIds().add("hotbar." + i); - for(i = 0; i < 27; i++) get("player").commandIds().add("inventory." + i); - for (String place : Arrays.asList("weapon", "weapon.mainhand", "weapon.offhand")) + } + for (i = 0; i < 41; i++) + { + get("player").numericalIds().add(i); + } + for (i = 0; i < 41; i++) + { + get("player").commandIds().add("container." + i); + } + for (i = 0; i < 9; i++) + { + get("player").commandIds().add("hotbar." + i); + } + for (i = 0; i < 27; i++) + { + get("player").commandIds().add("inventory." + i); + } + for (final String place : Arrays.asList("weapon", "weapon.mainhand", "weapon.offhand")) { get("player").commandIds().add(place); get("equipment").commandIds().add(place); get("weapon").commandIds().add(place); } - for (String place : Arrays.asList("armor.feet","armor.legs", "armor.chest","armor.head")) + for (final String place : Arrays.asList("armor.feet", "armor.legs", "armor.chest", "armor.head")) { get("player").commandIds().add(place); get("equipment").commandIds().add(place); get("armor").commandIds().add(place); } - for (i = 0; i < 27; i++) get("enderchest").numericalIds().add(200+i); - for(i = 0; i < 27; i++) get("enderchest").commandIds().add("enderchest." + i); + for (i = 0; i < 27; i++) + { + get("enderchest").numericalIds().add(200 + i); + } + for (i = 0; i < 27; i++) + { + get("enderchest").commandIds().add("enderchest." + i); + } - for (i = 0; i < 6; i++) get("equipment").numericalIds().add(98+i); + for (i = 0; i < 6; i++) + { + get("equipment").numericalIds().add(98 + i); + } - for (i = 0; i < 4; i++) get("armor").numericalIds().add(100+i); + for (i = 0; i < 4; i++) + { + get("armor").numericalIds().add(100 + i); + } - for (i = 0; i < 2; i++) get("weapon").numericalIds().add(98+i); + for (i = 0; i < 2; i++) + { + get("weapon").numericalIds().add(98 + i); + } - for (i = 0; i < 54; i++) get("container").numericalIds().add(i); - for(i = 0; i < 41; i++) get("container").commandIds().add("container." + i); + for (i = 0; i < 54; i++) + { + get("container").numericalIds().add(i); + } + for (i = 0; i < 41; i++) + { + get("container").commandIds().add("container." + i); + } - for (i = 0; i < 8; i++) get("villager").numericalIds().add(i); - for(i = 0; i < 8; i++) get("villager").commandIds().add("villager." + i); + for (i = 0; i < 8; i++) + { + get("villager").numericalIds().add(i); + } + for (i = 0; i < 8; i++) + { + get("villager").commandIds().add("villager." + i); + } - for (i = 0; i < 15; i++) get("horse").numericalIds().add(500+i); - for(i = 0; i < 15; i++) get("horse").commandIds().add("horse." + i); + for (i = 0; i < 15; i++) + { + get("horse").numericalIds().add(500 + i); + } + for (i = 0; i < 15; i++) + { + get("horse").commandIds().add("horse." + i); + } get("horse").numericalIds().add(400); get("horse").commandIds().add("horse.saddle"); get("horse").numericalIds().add(401); @@ -950,24 +1106,24 @@ protected SlotArgument() } @Override - protected ArgumentType getArgumentType(CarpetScriptHost host) throws CommandSyntaxException + protected ArgumentType getArgumentType(final CarpetScriptHost host) throws CommandSyntaxException { return net.minecraft.commands.arguments.SlotArgument.slot(); } @Override - protected Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException + protected Value getValueFromContext(final CommandContext context, final String param) throws CommandSyntaxException { - int slot = net.minecraft.commands.arguments.SlotArgument.getSlot(context, param); + final int slot = net.minecraft.commands.arguments.SlotArgument.getSlot(context, param); if (restrict != null && !RESTRICTED_CONTAINERS.get(restrict).numericalIds().contains(slot)) { - throw new SimpleCommandExceptionType(Component.literal("Incorrect slot restricted to "+restrict+" for custom type "+suffix)).create(); + throw new SimpleCommandExceptionType(Component.literal("Incorrect slot restricted to " + restrict + " for custom type " + suffix)).create(); } return ValueConversions.ofVanillaSlotResult(slot); } @Override - protected void configure(Map config, CarpetScriptHost host) throws CommandSyntaxException + protected void configure(final Map config, final CarpetScriptHost host) throws CommandSyntaxException { super.configure(config, host); if (config.containsKey("restrict")) @@ -975,18 +1131,20 @@ protected void configure(Map config, CarpetScriptHost host) throw restrict = config.get("restrict").getString().toLowerCase(Locale.ROOT); needsMatching = true; if (!RESTRICTED_CONTAINERS.containsKey(restrict)) - throw error("Incorrect slot restriction "+restrict+" for custom type "+suffix); + { + throw error("Incorrect slot restriction " + restrict + " for custom type " + suffix); + } } } @Override - protected Collection getOptions(CommandContext context, CarpetScriptHost host) throws CommandSyntaxException + protected Collection getOptions(final CommandContext context, final CarpetScriptHost host) throws CommandSyntaxException { - return restrict==null?super.getOptions(context, host):RESTRICTED_CONTAINERS.get(restrict).commandIds(); + return restrict == null ? super.getOptions(context, host) : RESTRICTED_CONTAINERS.get(restrict).commandIds(); } @Override - protected Supplier factory(MinecraftServer server) + protected Supplier factory(final MinecraftServer server) { return SlotArgument::new; } @@ -1010,7 +1168,7 @@ private interface ArgumentProviderEx ArgumentType get(CommandBuildContext regAccess) throws CommandSyntaxException; } - public static class VanillaUnconfigurableArgument extends CommandArgument + public static class VanillaUnconfigurableArgument extends CommandArgument { private final ArgumentProvider argumentTypeSupplier; private final ArgumentProviderEx argumentTypeSupplierEx; @@ -1018,18 +1176,18 @@ public static class VanillaUnconfigurableArgument extends CommandArgument private final boolean providesExamples; public VanillaUnconfigurableArgument( - String suffix, - ArgumentProvider argumentTypeSupplier, - ValueExtractor valueExtractor, - boolean suggestFromExamples - ) + final String suffix, + final ArgumentProvider argumentTypeSupplier, + final ValueExtractor valueExtractor, + final boolean suggestFromExamples + ) { super(suffix, null, suggestFromExamples); try { this.examples = argumentTypeSupplier.get().getExamples(); } - catch (CommandSyntaxException e) + catch (final CommandSyntaxException e) { this.examples = Collections.emptyList(); } @@ -1038,11 +1196,12 @@ public VanillaUnconfigurableArgument( this.valueExtractor = valueExtractor; this.argumentTypeSupplierEx = null; } + public VanillaUnconfigurableArgument( - String suffix, - ArgumentProvider argumentTypeSupplier, - ValueExtractor valueExtractor, - SuggestionProvider suggester + final String suffix, + final ArgumentProvider argumentTypeSupplier, + final ValueExtractor valueExtractor, + final SuggestionProvider suggester ) { super(suffix, Collections.emptyList(), false); @@ -1052,12 +1211,13 @@ public VanillaUnconfigurableArgument( this.valueExtractor = valueExtractor; this.argumentTypeSupplierEx = null; } + public VanillaUnconfigurableArgument( - String suffix, - ArgumentProviderEx argumentTypeSupplier, - ValueExtractor valueExtractor, - boolean suggestFromExamples, - MinecraftServer server) + final String suffix, + final ArgumentProviderEx argumentTypeSupplier, + final ValueExtractor valueExtractor, + final boolean suggestFromExamples, + final MinecraftServer server) { super(suffix, null, suggestFromExamples); try @@ -1065,7 +1225,7 @@ public VanillaUnconfigurableArgument( final CommandBuildContext context = CommandBuildContext.simple(server.registryAccess(), server.getWorldData().enabledFeatures()); this.examples = argumentTypeSupplier.get(context).getExamples(); } - catch (CommandSyntaxException e) + catch (final CommandSyntaxException e) { this.examples = Collections.emptyList(); } @@ -1076,10 +1236,10 @@ public VanillaUnconfigurableArgument( } public VanillaUnconfigurableArgument( - String suffix, - ArgumentProviderEx argumentTypeSupplier, - ValueExtractor valueExtractor, - SuggestionProvider suggester + final String suffix, + final ArgumentProviderEx argumentTypeSupplier, + final ValueExtractor valueExtractor, + final SuggestionProvider suggester ) { super(suffix, Collections.emptyList(), false); @@ -1091,10 +1251,10 @@ public VanillaUnconfigurableArgument( } public VanillaUnconfigurableArgument( - String suffix, - ArgumentProviderEx argumentTypeSupplier, - ValueExtractor valueExtractor, - Function> suggesterGen + final String suffix, + final ArgumentProviderEx argumentTypeSupplier, + final ValueExtractor valueExtractor, + final Function> suggesterGen ) { super(suffix, Collections.emptyList(), false); @@ -1106,8 +1266,8 @@ public VanillaUnconfigurableArgument( } public VanillaUnconfigurableArgument( - String suffix, - ResourceKey> registry + final String suffix, + final ResourceKey> registry ) { this( @@ -1119,24 +1279,25 @@ public VanillaUnconfigurableArgument( } @Override - protected ArgumentType getArgumentType(CarpetScriptHost host) throws CommandSyntaxException + protected ArgumentType getArgumentType(final CarpetScriptHost host) throws CommandSyntaxException { - if (argumentTypeSupplier != null) return argumentTypeSupplier.get(); - CommandBuildContext registryAccess = CommandBuildContext.simple(host.scriptServer().server.registryAccess(), host.scriptServer().server.getWorldData().enabledFeatures()); - return argumentTypeSupplierEx.get(registryAccess); + return argumentTypeSupplier != null + ? argumentTypeSupplier.get() + : argumentTypeSupplierEx.get(CommandBuildContext.simple(host.scriptServer().server.registryAccess(), host.scriptServer().server.getWorldData().enabledFeatures())); } @Override - protected Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException + protected Value getValueFromContext(final CommandContext context, final String param) throws CommandSyntaxException { return valueExtractor.apply(context, param); } @Override - protected Supplier factory(MinecraftServer server) + protected Supplier factory(final MinecraftServer server) { - if (argumentTypeSupplier != null) return () -> new VanillaUnconfigurableArgument(getTypeSuffix(), argumentTypeSupplier, valueExtractor, providesExamples); - return () -> new VanillaUnconfigurableArgument(getTypeSuffix(), argumentTypeSupplierEx, valueExtractor, providesExamples, server); + return argumentTypeSupplier != null + ? (() -> new VanillaUnconfigurableArgument(getTypeSuffix(), argumentTypeSupplier, valueExtractor, providesExamples)) + : (() -> new VanillaUnconfigurableArgument(getTypeSuffix(), argumentTypeSupplierEx, valueExtractor, providesExamples, server)); } } } diff --git a/src/main/java/carpet/script/command/CommandToken.java b/src/main/java/carpet/script/command/CommandToken.java index 257ac8c2a0..7f028ee99e 100644 --- a/src/main/java/carpet/script/command/CommandToken.java +++ b/src/main/java/carpet/script/command/CommandToken.java @@ -5,11 +5,13 @@ import com.google.common.collect.Lists; import com.mojang.brigadier.builder.ArgumentBuilder; import com.mojang.brigadier.exceptions.CommandSyntaxException; + import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Objects; + import net.minecraft.commands.CommandSourceStack; import static net.minecraft.commands.Commands.literal; @@ -20,41 +22,46 @@ public class CommandToken implements Comparable public boolean isArgument; public CommandArgument type; - private CommandToken(String surface, CommandArgument type ) + private CommandToken(final String surface, final CommandArgument type) { this.surface = surface; this.type = type; isArgument = type != null; } - public static CommandToken getToken(String source, CarpetScriptHost host) + public static CommandToken getToken(String source, final CarpetScriptHost host) { // todo add more type checking and return null if (!source.startsWith("<")) { - if (!source.matches("[_a-zA-Z]+")) return null; - return new CommandToken(source, null); + return source.matches("[_a-zA-Z]+") ? new CommandToken(source, null) : null; } - source = source.substring(1, source.length()-1); - if (!source.matches("[_a-zA-Z]+")) return null; - CommandArgument arg = CommandArgument.getTypeForArgument(source, host); - return new CommandToken(source, arg); + source = source.substring(1, source.length() - 1); + return source.matches("[_a-zA-Z]+") ? new CommandToken(source, CommandArgument.getTypeForArgument(source, host)) : null; } - public static List parseSpec(String spec, CarpetScriptHost host) throws CommandSyntaxException + public static List parseSpec(String spec, final CarpetScriptHost host) throws CommandSyntaxException { spec = spec.trim(); - if (spec.isEmpty()) return Collections.emptyList(); - List elements = new ArrayList<>(); - HashSet seenArgs = new HashSet<>(); - for (String el: spec.split("\\s+")) + if (spec.isEmpty()) { - CommandToken tok = CommandToken.getToken(el, host); - if (tok == null) throw CommandArgument.error("Unrecognized command token: "+ el); + return Collections.emptyList(); + } + final List elements = new ArrayList<>(); + final HashSet seenArgs = new HashSet<>(); + for (final String el : spec.split("\\s+")) + { + final CommandToken tok = CommandToken.getToken(el, host); + if (tok == null) + { + throw CommandArgument.error("Unrecognized command token: " + el); + } if (tok.isArgument) { if (seenArgs.contains(tok.surface)) - throw CommandArgument.error("Repeated command argument: "+tok.surface+", for '"+spec+"'. Argument names have to be unique"); + { + throw CommandArgument.error("Repeated command argument: " + tok.surface + ", for '" + spec + "'. Argument names have to be unique"); + } seenArgs.add(tok.surface); } elements.add(tok); @@ -62,28 +69,33 @@ public static List parseSpec(String spec, CarpetScriptHost host) t return elements; } - public static String specFromSignature(FunctionValue function) + public static String specFromSignature(final FunctionValue function) { - List tokens = Lists.newArrayList(function.getString()); - for (String arg : function.getArguments()) tokens.add("<"+arg+">"); + final List tokens = Lists.newArrayList(function.getString()); + for (final String arg : function.getArguments()) + { + tokens.add("<" + arg + ">"); + } return String.join(" ", tokens); } - - public ArgumentBuilder getCommandNode(CarpetScriptHost host) throws CommandSyntaxException + public ArgumentBuilder getCommandNode(final CarpetScriptHost host) throws CommandSyntaxException { - if (isArgument) - return CommandArgument.argumentNode(surface, host); - return literal(surface); - + return isArgument ? CommandArgument.argumentNode(surface, host) : literal(surface); } @Override - public boolean equals(Object o) + public boolean equals(final Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - CommandToken that = (CommandToken) o; + if (this == o) + { + return true; + } + if (o == null || getClass() != o.getClass()) + { + return false; + } + final CommandToken that = (CommandToken) o; return surface.equals(that.surface) && Objects.equals(type, that.type); } @@ -95,10 +107,16 @@ public int hashCode() } @Override - public int compareTo(CommandToken o) + public int compareTo(final CommandToken o) { - if (isArgument && !o.isArgument) return 1; - if (!isArgument && o.isArgument) return -1; + if (isArgument && !o.isArgument) + { + return 1; + } + if (!isArgument && o.isArgument) + { + return -1; + } return surface.compareTo(o.surface); } } diff --git a/src/main/java/carpet/script/exception/BreakStatement.java b/src/main/java/carpet/script/exception/BreakStatement.java index 8705d12418..76c69a7a8c 100644 --- a/src/main/java/carpet/script/exception/BreakStatement.java +++ b/src/main/java/carpet/script/exception/BreakStatement.java @@ -4,7 +4,7 @@ public class BreakStatement extends ExitStatement { - public BreakStatement(Value value) + public BreakStatement(final Value value) { super(value); } diff --git a/src/main/java/carpet/script/exception/CarpetExpressionException.java b/src/main/java/carpet/script/exception/CarpetExpressionException.java index 849e99ad76..4ca5d115b6 100644 --- a/src/main/java/carpet/script/exception/CarpetExpressionException.java +++ b/src/main/java/carpet/script/exception/CarpetExpressionException.java @@ -2,25 +2,28 @@ import carpet.script.value.FunctionValue; import carpet.utils.Messenger; + import java.util.List; + import net.minecraft.commands.CommandSourceStack; public class CarpetExpressionException extends StacklessRuntimeException implements ResolvedException { public final List stack; - public CarpetExpressionException(String message, List stack) + public CarpetExpressionException(final String message, final List stack) { super(message); this.stack = stack; } - public void printStack(CommandSourceStack source) + + public void printStack(final CommandSourceStack source) { if (stack != null && !stack.isEmpty()) { - for (FunctionValue fun : stack) + for (final FunctionValue fun : stack) { - Messenger.m(source, "e ... in "+fun.fullName(), "e /"+(fun.getToken().lineno+1)+":"+(fun.getToken().linepos+1)); + Messenger.m(source, "e ... in " + fun.fullName(), "e /" + (fun.getToken().lineno + 1) + ":" + (fun.getToken().linepos + 1)); } } } diff --git a/src/main/java/carpet/script/exception/ContinueStatement.java b/src/main/java/carpet/script/exception/ContinueStatement.java index f31c5af335..a471d4f4e2 100644 --- a/src/main/java/carpet/script/exception/ContinueStatement.java +++ b/src/main/java/carpet/script/exception/ContinueStatement.java @@ -4,7 +4,7 @@ public class ContinueStatement extends ExitStatement { - public ContinueStatement(Value value) + public ContinueStatement(final Value value) { super(value); } diff --git a/src/main/java/carpet/script/exception/ExitStatement.java b/src/main/java/carpet/script/exception/ExitStatement.java index eb258d6f1b..744ec9f630 100644 --- a/src/main/java/carpet/script/exception/ExitStatement.java +++ b/src/main/java/carpet/script/exception/ExitStatement.java @@ -6,7 +6,8 @@ public class ExitStatement extends StacklessRuntimeException { public final Value retval; - public ExitStatement(Value value) + + public ExitStatement(final Value value) { retval = value; } diff --git a/src/main/java/carpet/script/exception/ExpressionException.java b/src/main/java/carpet/script/exception/ExpressionException.java index 64d97af231..7104858976 100644 --- a/src/main/java/carpet/script/exception/ExpressionException.java +++ b/src/main/java/carpet/script/exception/ExpressionException.java @@ -19,20 +19,23 @@ public class ExpressionException extends StacklessRuntimeException implements Re public final List stack = new ArrayList<>(); private final Supplier lazyMessage; private String cachedMessage = null; - public static void prepareForDoom(){ + + public static void prepareForDoom() + { Messenger.c("foo bar"); } - public ExpressionException(Context c, Expression e, String message) + public ExpressionException(final Context c, final Expression e, final String message) { this(c, e, Tokenizer.Token.NONE, message); } - public ExpressionException(Context c, Expression e, Tokenizer.Token t, String message) + public ExpressionException(final Context c, final Expression e, final Tokenizer.Token t, final String message) { this(c, e, t, message, Collections.emptyList()); } - public ExpressionException(Context c, Expression e, Tokenizer.Token t, String message, List stack) + + public ExpressionException(final Context c, final Expression e, final Tokenizer.Token t, final String message, final List stack) { super("Error"); this.stack.addAll(stack); @@ -41,7 +44,7 @@ public ExpressionException(Context c, Expression e, Tokenizer.Token t, String me context = c; } - public ExpressionException(Context c, Expression e, Tokenizer.Token t, Supplier messageSupplier, List stack) + public ExpressionException(final Context c, final Expression e, final Tokenizer.Token t, final Supplier messageSupplier, final List stack) { super("Error"); this.stack.addAll(stack); @@ -50,13 +53,13 @@ public ExpressionException(Context c, Expression e, Tokenizer.Token t, Supplier< context = c; } - private static List makeError(Expression expr, /*Nullable*/Tokenizer.Token token, String errmessage) + private static List makeError(final Expression expr, /*Nullable*/final Tokenizer.Token token, String errmessage) { - List errMsg = new ArrayList<>(); - errmessage += expr.getModuleName() == null?"":(" in "+expr.getModuleName()); + final List errMsg = new ArrayList<>(); + errmessage += expr.getModuleName() == null ? "" : (" in " + expr.getModuleName()); if (token != null) { - List snippet = expr.getExpressionSnippet(token); + final List snippet = expr.getExpressionSnippet(token); errMsg.addAll(snippet); if (snippet.size() != 1) @@ -72,11 +75,11 @@ private static List makeError(Expression expr, /*Nullable*/Tokenizer.Tok return errMsg; } - synchronized static String makeMessage(Context c, Expression e, Tokenizer.Token t, String message) throws ExpressionException + static synchronized String makeMessage(final Context c, final Expression e, final Tokenizer.Token t, final String message) throws ExpressionException { if (c.getErrorSnooper() != null) { - List alternative = c.getErrorSnooper().apply(e, t, c, message); + final List alternative = c.getErrorSnooper().apply(e, t, c, message); if (alternative != null) { return String.join("\n", alternative); @@ -84,12 +87,13 @@ synchronized static String makeMessage(Context c, Expression e, Tokenizer.Token } return String.join("\n", makeError(e, t, message)); } - + @Override - public String getMessage() { + public String getMessage() + { if (cachedMessage == null) { - cachedMessage = lazyMessage.get(); + cachedMessage = lazyMessage.get(); } return cachedMessage; } diff --git a/src/main/java/carpet/script/exception/IntegrityException.java b/src/main/java/carpet/script/exception/IntegrityException.java index 262c57f9e7..7aee600b9c 100644 --- a/src/main/java/carpet/script/exception/IntegrityException.java +++ b/src/main/java/carpet/script/exception/IntegrityException.java @@ -2,7 +2,7 @@ public class IntegrityException extends RuntimeException { - public IntegrityException(String message) + public IntegrityException(final String message) { super(message); } diff --git a/src/main/java/carpet/script/exception/InternalExpressionException.java b/src/main/java/carpet/script/exception/InternalExpressionException.java index 8706f71046..dec1b9c5c8 100644 --- a/src/main/java/carpet/script/exception/InternalExpressionException.java +++ b/src/main/java/carpet/script/exception/InternalExpressionException.java @@ -12,23 +12,25 @@ public class InternalExpressionException extends StacklessRuntimeException { public List stack = new ArrayList<>(); - public InternalExpressionException(String message) + + public InternalExpressionException(final String message) { super(message); } - + /** *

Promotes this simple exception into one with context and extra information. - * + * *

Provides a cleaner way of handling similar exceptions, in this case - * {@link InternalExpressionException} and {@link ThrowStatement} - * @param c Context - * @param e Expression + * {@link InternalExpressionException} and {@link ThrowStatement} + * + * @param c Context + * @param e Expression * @param token Token * @return The new {@link ExpressionException} (or {@link ProcessedThrowStatement}), - * depending on the implementation. + * depending on the implementation. */ - public ExpressionException promote(Context c, Expression e, Tokenizer.Token token) + public ExpressionException promote(final Context c, final Expression e, final Tokenizer.Token token) { return new ExpressionException(c, e, token, getMessage(), stack); } diff --git a/src/main/java/carpet/script/exception/LoadException.java b/src/main/java/carpet/script/exception/LoadException.java index 740a04b196..bdbd41491e 100644 --- a/src/main/java/carpet/script/exception/LoadException.java +++ b/src/main/java/carpet/script/exception/LoadException.java @@ -2,18 +2,18 @@ /** * A Scarpet exception that indicates that load of the app has failed. - * + *

* Goes up the stack to the point of app load and gets caught there, preventing the app from loading with * the given message. - * */ -public class LoadException extends RuntimeException implements ResolvedException { - - public LoadException() { +public class LoadException extends RuntimeException implements ResolvedException +{ + public LoadException() + { super(); } - - public LoadException(String message) { + public LoadException(final String message) + { super(message); } } diff --git a/src/main/java/carpet/script/exception/ProcessedThrowStatement.java b/src/main/java/carpet/script/exception/ProcessedThrowStatement.java index 977cf51f3f..45c990be52 100644 --- a/src/main/java/carpet/script/exception/ProcessedThrowStatement.java +++ b/src/main/java/carpet/script/exception/ProcessedThrowStatement.java @@ -8,12 +8,14 @@ import carpet.script.value.FunctionValue; import carpet.script.value.Value; -public class ProcessedThrowStatement extends ExpressionException { +public class ProcessedThrowStatement extends ExpressionException +{ public final Throwables thrownExceptionType; public final Value data; - - public ProcessedThrowStatement(Context c, Expression e, Token token, List stack, Throwables thrownExceptionType, Value data) { - super(c, e, token, () -> "Unhandled "+thrownExceptionType.getId()+" exception: "+data.getString(), stack); + + public ProcessedThrowStatement(final Context c, final Expression e, final Token token, final List stack, final Throwables thrownExceptionType, final Value data) + { + super(c, e, token, () -> "Unhandled " + thrownExceptionType.getId() + " exception: " + data.getString(), stack); this.thrownExceptionType = thrownExceptionType; this.data = data; } diff --git a/src/main/java/carpet/script/exception/ReturnStatement.java b/src/main/java/carpet/script/exception/ReturnStatement.java index b2124d5678..e275efb915 100644 --- a/src/main/java/carpet/script/exception/ReturnStatement.java +++ b/src/main/java/carpet/script/exception/ReturnStatement.java @@ -4,8 +4,7 @@ public class ReturnStatement extends ExitStatement { - - public ReturnStatement(Value value) + public ReturnStatement(final Value value) { super(value); } diff --git a/src/main/java/carpet/script/exception/StacklessRuntimeException.java b/src/main/java/carpet/script/exception/StacklessRuntimeException.java index e200d0654d..5f0f473e34 100644 --- a/src/main/java/carpet/script/exception/StacklessRuntimeException.java +++ b/src/main/java/carpet/script/exception/StacklessRuntimeException.java @@ -3,17 +3,21 @@ /** * A type of {@link RuntimeException} that doesn't spend time producing and filling a stacktrace */ -abstract class StacklessRuntimeException extends RuntimeException { - public StacklessRuntimeException() { +abstract class StacklessRuntimeException extends RuntimeException +{ + public StacklessRuntimeException() + { super(); } - public StacklessRuntimeException(String message) { + public StacklessRuntimeException(final String message) + { super(message); } @Override - public Throwable fillInStackTrace() { + public Throwable fillInStackTrace() + { return this; } } diff --git a/src/main/java/carpet/script/exception/ThrowStatement.java b/src/main/java/carpet/script/exception/ThrowStatement.java index c61470cbfa..f413246dd2 100644 --- a/src/main/java/carpet/script/exception/ThrowStatement.java +++ b/src/main/java/carpet/script/exception/ThrowStatement.java @@ -10,21 +10,22 @@ public class ThrowStatement extends InternalExpressionException { private final Throwables type; private final Value data; - + /** * Creates a throw exception from a value, and assigns it a specified message. *

To be used when throwing from Scarpet's {@code throw} function + * * @param data The value to pass * @param type Exception type */ - public ThrowStatement(Value data, Throwables type) + public ThrowStatement(final Value data, final Throwables type) { super(type.getId()); this.data = data; this.type = type; } - public ThrowStatement(Value data, Throwables parent, String subtype) + public ThrowStatement(final Value data, final Throwables parent, final String subtype) { super(subtype); this.data = data; @@ -35,20 +36,22 @@ public ThrowStatement(Value data, Throwables parent, String subtype) * Creates a throw exception.
* Conveniently creates a value from the {@code value} String * to be used easily in Java code + * * @param message The message to display when not handled - * @param type An {@link Throwables} containing the inheritance data - * for this exception. When throwing from Java, - * those exceptions should be pre-registered. + * @param type An {@link Throwables} containing the inheritance data + * for this exception. When throwing from Java, + * those exceptions should be pre-registered. */ - public ThrowStatement(String message, Throwables type) + public ThrowStatement(final String message, final Throwables type) { super(type.getId()); this.data = StringValue.of(message); this.type = type; } - + @Override - public ExpressionException promote(Context c, Expression e, Token token) { + public ExpressionException promote(final Context c, final Expression e, final Token token) + { return new ProcessedThrowStatement(c, e, token, stack, type, data); } } diff --git a/src/main/java/carpet/script/exception/Throwables.java b/src/main/java/carpet/script/exception/Throwables.java index a0a85cb1be..48e3d278a8 100644 --- a/src/main/java/carpet/script/exception/Throwables.java +++ b/src/main/java/carpet/script/exception/Throwables.java @@ -7,41 +7,43 @@ * This class contains default Scarpet catchable types, as well as their inheritance and * methods to check whether filters are compatible with those. */ -public class Throwables { +public class Throwables +{ private final String id; private final Throwables parent; private static final Map byId = new HashMap<>(); public static final Throwables THROWN_EXCEPTION_TYPE = register("exception", null); - public static final Throwables VALUE_EXCEPTION = register("value_exception", THROWN_EXCEPTION_TYPE); - public static final Throwables UNKNOWN_ITEM = register("unknown_item", VALUE_EXCEPTION); - public static final Throwables UNKNOWN_BLOCK = register("unknown_block", VALUE_EXCEPTION); - public static final Throwables UNKNOWN_BIOME = register("unknown_biome", VALUE_EXCEPTION); - public static final Throwables UNKNOWN_SOUND = register("unknown_sound", VALUE_EXCEPTION); - public static final Throwables UNKNOWN_PARTICLE = register("unknown_particle", VALUE_EXCEPTION); - public static final Throwables UNKNOWN_POI = register("unknown_poi", VALUE_EXCEPTION); - public static final Throwables UNKNOWN_DIMENSION = register("unknown_dimension", VALUE_EXCEPTION); - public static final Throwables UNKNOWN_STRUCTURE = register("unknown_structure", VALUE_EXCEPTION); - public static final Throwables UNKNOWN_CRITERION = register("unknown_criterion", VALUE_EXCEPTION); - public static final Throwables UNKNOWN_SCREEN = register("unknown_screen", VALUE_EXCEPTION); - public static final Throwables IO_EXCEPTION = register("io_exception", THROWN_EXCEPTION_TYPE); - public static final Throwables NBT_ERROR = register("nbt_error", IO_EXCEPTION); - public static final Throwables JSON_ERROR = register("json_error", IO_EXCEPTION); - public static final Throwables B64_ERROR = register("b64_error", IO_EXCEPTION); - public static final Throwables USER_DEFINED = register("user_exception", THROWN_EXCEPTION_TYPE); + public static final Throwables VALUE_EXCEPTION = register("value_exception", THROWN_EXCEPTION_TYPE); + public static final Throwables UNKNOWN_ITEM = register("unknown_item", VALUE_EXCEPTION); + public static final Throwables UNKNOWN_BLOCK = register("unknown_block", VALUE_EXCEPTION); + public static final Throwables UNKNOWN_BIOME = register("unknown_biome", VALUE_EXCEPTION); + public static final Throwables UNKNOWN_SOUND = register("unknown_sound", VALUE_EXCEPTION); + public static final Throwables UNKNOWN_PARTICLE = register("unknown_particle", VALUE_EXCEPTION); + public static final Throwables UNKNOWN_POI = register("unknown_poi", VALUE_EXCEPTION); + public static final Throwables UNKNOWN_DIMENSION = register("unknown_dimension", VALUE_EXCEPTION); + public static final Throwables UNKNOWN_STRUCTURE = register("unknown_structure", VALUE_EXCEPTION); + public static final Throwables UNKNOWN_CRITERION = register("unknown_criterion", VALUE_EXCEPTION); + public static final Throwables UNKNOWN_SCREEN = register("unknown_screen", VALUE_EXCEPTION); + public static final Throwables IO_EXCEPTION = register("io_exception", THROWN_EXCEPTION_TYPE); + public static final Throwables NBT_ERROR = register("nbt_error", IO_EXCEPTION); + public static final Throwables JSON_ERROR = register("json_error", IO_EXCEPTION); + public static final Throwables B64_ERROR = register("b64_error", IO_EXCEPTION); + public static final Throwables USER_DEFINED = register("user_exception", THROWN_EXCEPTION_TYPE); /** * Creates an exception and registers it to be used as parent for * user defined exceptions in Scarpet's throw function. *

Scarpet exceptions should have a top-level parent being {@link Throwables#THROWN_EXCEPTION_TYPE} - * @param id The value for the exception as a {@link String}. + * + * @param id The value for the exception as a {@link String}. * @param parent The parent of the exception being created, or null if top-level * @return The created exception */ - public static Throwables register(String id, Throwables parent) + public static Throwables register(final String id, final Throwables parent) { - Throwables exc = new Throwables(id, parent); + final Throwables exc = new Throwables(id, parent); byId.put(id, exc); return exc; } @@ -50,28 +52,33 @@ public static Throwables register(String id, Throwables parent) * Creates a new exception. *

Not suitable for creating exceptions that can't be caught. * Use an {@link InternalExpressionException} for that + * * @param id The exception's value as a {@link String} */ - public Throwables(String id, Throwables parent) + public Throwables(final String id, final Throwables parent) { this.id = id; this.parent = parent; } - public static Throwables getTypeForException(String type) + public static Throwables getTypeForException(final String type) { - Throwables properType = byId.get(type); - if (properType == null) throw new InternalExpressionException("Unknown exception type: "+type); + final Throwables properType = byId.get(type); + if (properType == null) + { + throw new InternalExpressionException("Unknown exception type: " + type); + } return properType; } /** * Checks whether the given filter matches an instance of this exception, by checking equality * with itself and possible parents. + * * @param filter The type to check against * @return Whether or not the given value matches this exception's hierarchy */ - public boolean isRelevantFor(String filter) + public boolean isRelevantFor(final String filter) { return (id.equals(filter) || (parent != null && parent.isRelevantFor(filter))); } @@ -83,9 +90,11 @@ public boolean isUserException() /** * Returns the throwable type + * * @return The type of this exception */ - public String getId() { + public String getId() + { return id; } } diff --git a/src/main/java/carpet/script/language/Arithmetic.java b/src/main/java/carpet/script/language/Arithmetic.java index c664db8c43..4b9c3df530 100644 --- a/src/main/java/carpet/script/language/Arithmetic.java +++ b/src/main/java/carpet/script/language/Arithmetic.java @@ -8,16 +8,17 @@ import carpet.script.value.NumericValue; import carpet.script.value.Value; -public class Arithmetic { +public class Arithmetic +{ public static final Value PI = new NumericValue(Math.PI); public static final Value euler = new NumericValue(Math.E); - public static void apply(Expression expression) + public static void apply(final Expression expression) { - expression.addTypedContextFunction("not", 1, Context.Type.BOOLEAN, (c, t, lv) -> BooleanValue.of(lv.get(0).getBoolean()) ); + expression.addTypedContextFunction("not", 1, Context.Type.BOOLEAN, (c, t, lv) -> BooleanValue.of(lv.get(0).getBoolean())); expression.addUnaryFunction("fact", (v) -> { - long number = NumericValue.asNumber(v).getLong(); + final long number = NumericValue.asNumber(v).getLong(); if (number < 21) { long factorial = 1; @@ -40,72 +41,81 @@ else if (number > 170) return new NumericValue(factorial); }); - expression.addMathematicalUnaryFunction("sin", (d) -> Math.sin(Math.toRadians(d))); - expression.addMathematicalUnaryFunction("cos", (d) -> Math.cos(Math.toRadians(d))); - expression.addMathematicalUnaryFunction("tan", (d) -> Math.tan(Math.toRadians(d))); - expression.addMathematicalUnaryFunction("asin", (d) -> Math.toDegrees(Math.asin(d))); - expression.addMathematicalUnaryFunction("acos", (d) -> Math.toDegrees(Math.acos(d))); - expression.addMathematicalUnaryFunction("atan", (d) -> Math.toDegrees(Math.atan(d))); - expression.addMathematicalBinaryFunction("atan2", (d, d2) -> Math.toDegrees(Math.atan2(d, d2)) ); - expression.addMathematicalUnaryFunction("sinh", Math::sinh ); - expression.addMathematicalUnaryFunction("cosh", Math::cosh ); - expression.addMathematicalUnaryFunction("tanh", Math::tanh ); - expression.addMathematicalUnaryFunction("sec", (d) -> 1.0 / Math.cos(Math.toRadians(d)) ); // Formula: sec(x) = 1 / cos(x) - expression.addMathematicalUnaryFunction("csc", (d) -> 1.0 / Math.sin(Math.toRadians(d)) ); // Formula: csc(x) = 1 / sin(x) - expression.addMathematicalUnaryFunction("sech", (d) -> 1.0 / Math.cosh(d) ); // Formula: sech(x) = 1 / cosh(x) - expression.addMathematicalUnaryFunction("csch", (d) -> 1.0 / Math.sinh(d) ); // Formula: csch(x) = 1 / sinh(x) - expression.addMathematicalUnaryFunction("cot", (d) -> 1.0 / Math.tan(Math.toRadians(d)) ); // Formula: cot(x) = cos(x) / sin(x) = 1 / tan(x) - expression.addMathematicalUnaryFunction("acot", (d) -> Math.toDegrees(Math.atan(1.0 / d)) );// Formula: acot(x) = atan(1/x) - expression.addMathematicalUnaryFunction("coth", (d) -> 1.0 / Math.tanh(d) ); // Formula: coth(x) = 1 / tanh(x) - expression.addMathematicalUnaryFunction("asinh", (d) -> Math.log(d + (Math.sqrt(Math.pow(d, 2) + 1)))); // Formula: asinh(x) = ln(x + sqrt(x^2 + 1)) - expression.addMathematicalUnaryFunction("acosh", (d) -> Math.log(d + (Math.sqrt(Math.pow(d, 2) - 1)))); // Formula: acosh(x) = ln(x + sqrt(x^2 - 1)) - expression.addMathematicalUnaryFunction("atanh", (d) -> // Formula: atanh(x) = 0.5*ln((1 + x)/(1 - x)) + expression.addMathematicalUnaryFunction("sin", d -> Math.sin(Math.toRadians(d))); + expression.addMathematicalUnaryFunction("cos", d -> Math.cos(Math.toRadians(d))); + expression.addMathematicalUnaryFunction("tan", d -> Math.tan(Math.toRadians(d))); + expression.addMathematicalUnaryFunction("asin", d -> Math.toDegrees(Math.asin(d))); + expression.addMathematicalUnaryFunction("acos", d -> Math.toDegrees(Math.acos(d))); + expression.addMathematicalUnaryFunction("atan", d -> Math.toDegrees(Math.atan(d))); + expression.addMathematicalBinaryFunction("atan2", (d, d2) -> Math.toDegrees(Math.atan2(d, d2))); + expression.addMathematicalUnaryFunction("sinh", Math::sinh); + expression.addMathematicalUnaryFunction("cosh", Math::cosh); + expression.addMathematicalUnaryFunction("tanh", Math::tanh); + expression.addMathematicalUnaryFunction("sec", d -> 1.0 / Math.cos(Math.toRadians(d))); // Formula: sec(x) = 1 / cos(x) + expression.addMathematicalUnaryFunction("csc", d -> 1.0 / Math.sin(Math.toRadians(d))); // Formula: csc(x) = 1 / sin(x) + expression.addMathematicalUnaryFunction("sech", d -> 1.0 / Math.cosh(d)); // Formula: sech(x) = 1 / cosh(x) + expression.addMathematicalUnaryFunction("csch", d -> 1.0 / Math.sinh(d)); // Formula: csch(x) = 1 / sinh(x) + expression.addMathematicalUnaryFunction("cot", d -> 1.0 / Math.tan(Math.toRadians(d))); // Formula: cot(x) = cos(x) / sin(x) = 1 / tan(x) + expression.addMathematicalUnaryFunction("acot", d -> Math.toDegrees(Math.atan(1.0 / d)));// Formula: acot(x) = atan(1/x) + expression.addMathematicalUnaryFunction("coth", d -> 1.0 / Math.tanh(d)); // Formula: coth(x) = 1 / tanh(x) + expression.addMathematicalUnaryFunction("asinh", d -> Math.log(d + (Math.sqrt(Math.pow(d, 2) + 1)))); // Formula: asinh(x) = ln(x + sqrt(x^2 + 1)) + expression.addMathematicalUnaryFunction("acosh", d -> Math.log(d + (Math.sqrt(Math.pow(d, 2) - 1)))); // Formula: acosh(x) = ln(x + sqrt(x^2 - 1)) + expression.addMathematicalUnaryFunction("atanh", d -> // Formula: atanh(x) = 0.5*ln((1 + x)/(1 - x)) { if (Math.abs(d) > 1 || Math.abs(d) == 1) + { throw new InternalExpressionException("Number must be |x| < 1"); + } return 0.5 * Math.log((1 + d) / (1 - d)); }); - expression.addMathematicalUnaryFunction("rad", Math::toRadians); + expression.addMathematicalUnaryFunction("rad", Math::toRadians); expression.addMathematicalUnaryFunction("deg", Math::toDegrees); expression.addMathematicalUnaryFunction("ln", Math::log); expression.addMathematicalUnaryFunction("ln1p", Math::log1p); expression.addMathematicalUnaryFunction("log10", Math::log10); - expression.addMathematicalUnaryFunction("log", a -> Math.log(a)/Math.log(2)); - expression.addMathematicalUnaryFunction("log1p", x -> Math.log1p(x)/Math.log(2)); + expression.addMathematicalUnaryFunction("log", a -> Math.log(a) / Math.log(2)); + expression.addMathematicalUnaryFunction("log1p", x -> Math.log1p(x) / Math.log(2)); expression.addMathematicalUnaryFunction("sqrt", Math::sqrt); expression.addMathematicalUnaryFunction("abs", Math::abs); expression.addMathematicalUnaryIntFunction("round", Math::round); - expression.addMathematicalUnaryIntFunction("floor", n -> (long)Math.floor(n)); - expression.addMathematicalUnaryIntFunction("ceil", n -> (long)Math.ceil(n)); + expression.addMathematicalUnaryIntFunction("floor", n -> (long) Math.floor(n)); + expression.addMathematicalUnaryIntFunction("ceil", n -> (long) Math.ceil(n)); expression.addContextFunction("mandelbrot", 3, (c, t, lv) -> { - double a0 = NumericValue.asNumber(lv.get(0)).getDouble(); - double b0 = NumericValue.asNumber(lv.get(1)).getDouble(); - long maxiter = NumericValue.asNumber(lv.get(2)).getLong(); + final double a0 = NumericValue.asNumber(lv.get(0)).getDouble(); + final double b0 = NumericValue.asNumber(lv.get(1)).getDouble(); + final long maxiter = NumericValue.asNumber(lv.get(2)).getLong(); double a = 0.0D; double b = 0.0D; long iter = 0; - while(a*a+b*b<4 && iter < maxiter) + while (a * a + b * b < 4 && iter < maxiter) { - double temp = a*a-b*b+a0; - b = 2*a*b+b0; + final double temp = a * a - b * b + a0; + b = 2 * a * b + b0; a = temp; iter++; } - long iFinal = iter; + final long iFinal = iter; return new NumericValue(iFinal); }); expression.addFunction("max", (lv) -> { if (lv.size() == 0) + { throw new InternalExpressionException("'max' requires at least one parameter"); + } Value max = null; - if (lv.size()==1 && lv.get(0) instanceof ListValue) + if (lv.size() == 1 && lv.get(0) instanceof ListValue) + { lv = ((ListValue) lv.get(0)).getItems(); - for (Value parameter : lv) + } + for (final Value parameter : lv) { - if (max == null || parameter.compareTo(max) > 0) max = parameter; + if (max == null || parameter.compareTo(max) > 0) + { + max = parameter; + } } return max; }); @@ -113,17 +123,24 @@ else if (number > 170) expression.addFunction("min", (lv) -> { if (lv.size() == 0) + { throw new InternalExpressionException("'min' requires at least one parameter"); + } Value min = null; - if (lv.size()==1 && lv.get(0) instanceof ListValue) + if (lv.size() == 1 && lv.get(0) instanceof ListValue) + { lv = ((ListValue) lv.get(0)).getItems(); - for (Value parameter : lv) + } + for (final Value parameter : lv) { - if (min == null || parameter.compareTo(min) < 0) min = parameter; + if (min == null || parameter.compareTo(min) < 0) + { + min = parameter; + } } return min; }); - expression.addUnaryFunction("relu", (v) -> v.compareTo(Value.ZERO) < 0 ? Value.ZERO : v); + expression.addUnaryFunction("relu", v -> v.compareTo(Value.ZERO) < 0 ? Value.ZERO : v); } } diff --git a/src/main/java/carpet/script/language/ControlFlow.java b/src/main/java/carpet/script/language/ControlFlow.java index 21fa410638..eb0aa5db85 100644 --- a/src/main/java/carpet/script/language/ControlFlow.java +++ b/src/main/java/carpet/script/language/ControlFlow.java @@ -17,21 +17,25 @@ import java.util.Map; import java.util.stream.Collectors; -public class ControlFlow { - public static void apply(Expression expression) // public just to get the javadoc right +public class ControlFlow +{ + public static void apply(final Expression expression) // public just to get the javadoc right { // needs to be lazy cause of custom contextualization expression.addLazyBinaryOperator(";", Operators.precedence.get("nextop;"), true, true, t -> Context.Type.VOID, (c, t, lv1, lv2) -> { lv1.evalValue(c, Context.VOID); - Value v2 = lv2.evalValue(c, t); + final Value v2 = lv2.evalValue(c, t); return (cc, tt) -> v2; }); expression.addPureLazyFunction("then", -1, t -> Context.Type.VOID, (c, t, lv) -> { - int imax = lv.size()-1; - for (int i = 0; i < imax; i++) lv.get(i).evalValue(c, Context.VOID); - Value v = lv.get(imax).evalValue(c, t); + final int imax = lv.size() - 1; + for (int i = 0; i < imax; i++) + { + lv.get(i).evalValue(c, Context.VOID); + } + final Value v = lv.get(imax).evalValue(c, t); return (cc, tt) -> v; }); expression.addFunctionalEquivalence(";", "then"); @@ -40,78 +44,80 @@ public static void apply(Expression expression) // public just to get the javado // obvious lazy due to conditional evaluation of arguments expression.addLazyFunction("if", (c, t, lv) -> { - if ( lv.size() < 2 ) + if (lv.size() < 2) + { throw new InternalExpressionException("'if' statement needs to have at least one condition and one case"); - for (int i=0; i ret; } } - if (lv.size()%2 == 1) + if (lv.size() % 2 == 1) { - Value ret = lv.get(lv.size() - 1).evalValue(c, t); + final Value ret = lv.get(lv.size() - 1).evalValue(c, t); return (cc, tt) -> ret; } return (cc, tt) -> Value.NULL; }); - expression.addImpureFunction("exit", (lv) -> { throw new ExitStatement(lv.size()==0?Value.NULL:lv.get(0)); }); + expression.addImpureFunction("exit", (lv) -> { + throw new ExitStatement(lv.size() == 0 ? Value.NULL : lv.get(0)); + }); - expression.addImpureFunction("throw", lv-> + expression.addImpureFunction("throw", lv -> { - switch (lv.size()) + switch (lv.size()) { - case 0: - throw new ThrowStatement(Value.NULL, Throwables.USER_DEFINED); - case 1: - throw new ThrowStatement(lv.get(0), Throwables.USER_DEFINED ); - case 2: - throw new ThrowStatement(lv.get(1), Throwables.getTypeForException(lv.get(0).getString())); - case 3: - throw new ThrowStatement(lv.get(2), Throwables.getTypeForException(lv.get(1).getString()), lv.get(0).getString()); - default: - throw new InternalExpressionException("throw() can't accept more than 3 parameters"); + case 0 -> throw new ThrowStatement(Value.NULL, Throwables.USER_DEFINED); + case 1 -> throw new ThrowStatement(lv.get(0), Throwables.USER_DEFINED); + case 2 -> throw new ThrowStatement(lv.get(1), Throwables.getTypeForException(lv.get(0).getString())); + case 3 -> throw new ThrowStatement(lv.get(2), Throwables.getTypeForException(lv.get(1).getString()), lv.get(0).getString()); + default -> throw new InternalExpressionException("throw() can't accept more than 3 parameters"); } }); // needs to be lazy since execution of parameters but first one are conditional expression.addLazyFunction("try", (c, t, lv) -> { - if (lv.size()==0) + if (lv.size() == 0) + { throw new InternalExpressionException("'try' needs at least an expression block, and either a catch_epr, or a number of pairs of filters and catch_expr"); + } try { - Value retval = lv.get(0).evalValue(c, t); + final Value retval = lv.get(0).evalValue(c, t); return (c_, t_) -> retval; } - catch (ProcessedThrowStatement ret) + catch (final ProcessedThrowStatement ret) { if (lv.size() == 1) { if (!ret.thrownExceptionType.isUserException()) + { throw ret; + } return (c_, t_) -> Value.NULL; } if (lv.size() > 3 && lv.size() % 2 == 0) { throw new InternalExpressionException("Try-catch block needs the code to run, and either a catch expression for user thrown exceptions, or a number of pairs of filters and catch expressions"); } - + Value val = null; // This is always assigned at some point, just the compiler doesn't know - - LazyValue __ = c.getVariable("_"); + + final LazyValue __ = c.getVariable("_"); c.setVariable("_", (__c, __t) -> ret.data.reboundedTo("_")); - LazyValue _trace = c.getVariable("_trace"); + final LazyValue _trace = c.getVariable("_trace"); c.setVariable("_trace", (__c, __t) -> MapValue.wrap(Map.of( StringValue.of("stack"), ListValue.wrap(ret.stack.stream().map(f -> ListValue.of( StringValue.of(f.getModule().name()), StringValue.of(f.getString()), - NumericValue.of(f.getToken().lineno+1), - NumericValue.of(f.getToken().linepos+1) + NumericValue.of(f.getToken().lineno + 1), + NumericValue.of(f.getToken().linepos + 1) ))), StringValue.of("locals"), MapValue.wrap(ret.context.variables.entrySet().stream().filter(e -> !e.getKey().equals("_trace")).collect(Collectors.toMap( @@ -120,20 +126,22 @@ public static void apply(Expression expression) // public just to get the javado ))), StringValue.of("token"), ListValue.of( StringValue.of(ret.token.surface), - NumericValue.of(ret.token.lineno+1), - NumericValue.of(ret.token.linepos+1) + NumericValue.of(ret.token.lineno + 1), + NumericValue.of(ret.token.linepos + 1) ) ))); if (lv.size() == 2) { if (ret.thrownExceptionType.isUserException()) + { val = lv.get(1).evalValue(c, t); + } } else { int pointer = 1; - while (pointer < lv.size() -1) + while (pointer < lv.size() - 1) { if (ret.thrownExceptionType.isRelevantFor(lv.get(pointer).evalValue(c).getString())) { @@ -145,14 +153,18 @@ public static void apply(Expression expression) // public just to get the javado } c.setVariable("_", __); if (_trace != null) + { c.setVariable("_trace", _trace); + } else + { c.delVariable("_trace"); + } if (val == null) // not handled { throw ret; } - Value retval = val; + final Value retval = val; return (c_, t_) -> retval; } }); diff --git a/src/main/java/carpet/script/language/DataStructures.java b/src/main/java/carpet/script/language/DataStructures.java index 1b9ed5e488..b70dd079fa 100644 --- a/src/main/java/carpet/script/language/DataStructures.java +++ b/src/main/java/carpet/script/language/DataStructures.java @@ -25,42 +25,42 @@ import java.util.List; import java.util.stream.Collectors; -public class DataStructures { - public static void apply(Expression expression) +public class DataStructures +{ + public static void apply(final Expression expression) { expression.addFunction("l", lv -> - { - if (lv.size() == 1 && lv.get(0) instanceof LazyListValue) - return ListValue.wrap(((LazyListValue) lv.get(0)).unroll()); - return new ListValue.ListConstructorValue(lv); - }); + lv.size() == 1 && lv.get(0) instanceof final LazyListValue llv + ? ListValue.wrap(llv.unroll()) + : new ListValue.ListConstructorValue(lv)); expression.addFunction("join", (lv) -> { if (lv.size() < 2) + { throw new InternalExpressionException("'join' takes at least 2 arguments"); - String delimiter = lv.get(0).getString(); - List toJoin; - if (lv.size()==2 && lv.get(1) instanceof LazyListValue) + } + final String delimiter = lv.get(0).getString(); + final List toJoin; + if (lv.size() == 2 && lv.get(1) instanceof final LazyListValue llv) { - toJoin = ((LazyListValue) lv.get(1)).unroll(); - + toJoin = llv.unroll(); } - else if (lv.size() == 2 && lv.get(1) instanceof ListValue) + else if (lv.size() == 2 && lv.get(1) instanceof final ListValue llv) { - toJoin = new ArrayList<>(((ListValue)lv.get(1)).getItems()); + toJoin = new ArrayList<>(llv.getItems()); } else { - toJoin = lv.subList(1,lv.size()); + toJoin = lv.subList(1, lv.size()); } return new StringValue(toJoin.stream().map(Value::getString).collect(Collectors.joining(delimiter))); }); expression.addFunction("split", (lv) -> { - Value delimiter; - Value hwat; + final Value delimiter; + final Value hwat; if (lv.size() == 1) { hwat = lv.get(0); @@ -80,23 +80,26 @@ else if (lv.size() == 2) expression.addFunction("slice", (lv) -> { - if (lv.size() != 2 && lv.size() != 3) + { throw new InternalExpressionException("'slice' takes 2 or 3 arguments"); - Value hwat = lv.get(0); - long from = NumericValue.asNumber(lv.get(1)).getLong(); + } + final Value hwat = lv.get(0); + final long from = NumericValue.asNumber(lv.get(1)).getLong(); Long to = null; - if (lv.size()== 3) + if (lv.size() == 3) + { to = NumericValue.asNumber(lv.get(2)).getLong(); + } return hwat.slice(from, to); }); expression.addFunction("sort", (lv) -> { List toSort = lv; - if (lv.size()==1 && lv.get(0) instanceof ListValue) + if (lv.size() == 1 && lv.get(0) instanceof final ListValue llv) { - toSort = new ArrayList<>(((ListValue)lv.get(0)).getItems()); + toSort = new ArrayList<>(llv.getItems()); } Collections.sort(toSort); return ListValue.wrap(toSort); @@ -106,30 +109,34 @@ else if (lv.size() == 2) expression.addLazyFunction("sort_key", (c, t, lv) -> //get working with iterators { if (lv.size() == 0) + { throw new InternalExpressionException("First argument for 'sort_key' should be a List"); - Value v = lv.get(0).evalValue(c); - if (!(v instanceof ListValue)) + } + final Value v = lv.get(0).evalValue(c); + if (!(v instanceof final ListValue list)) + { throw new InternalExpressionException("First argument for 'sort_key' should be a List"); - List toSort = new ArrayList<>(((ListValue) v).getItems()); - if (lv.size()==1) + } + final List toSort = new ArrayList<>(list.getItems()); + if (lv.size() == 1) { Collections.shuffle(toSort); - Value ret = ListValue.wrap(toSort); + final Value ret = ListValue.wrap(toSort); return (_c, _t) -> ret; } - LazyValue sortKey = lv.get(1); + final LazyValue sortKey = lv.get(1); //scoping - LazyValue __ = c.getVariable("_"); - Collections.sort(toSort,(v1, v2) -> { - c.setVariable("_",(cc, tt) -> v1); - Value ev1 = sortKey.evalValue(c); - c.setVariable("_",(cc, tt) -> v2); - Value ev2 = sortKey.evalValue(c); + final LazyValue __ = c.getVariable("_"); + toSort.sort((v1, v2) -> { + c.setVariable("_", (cc, tt) -> v1); + final Value ev1 = sortKey.evalValue(c); + c.setVariable("_", (cc, tt) -> v2); + final Value ev2 = sortKey.evalValue(c); return ev1.compareTo(ev2); }); //revering scope c.setVariable("_", __); - Value ret = ListValue.wrap(toSort); + final Value ret = ListValue.wrap(toSort); return (cc, tt) -> ret; }); @@ -138,9 +145,11 @@ else if (lv.size() == 2) NumericValue from = Value.ZERO; NumericValue to; NumericValue step = Value.ONE; - int argsize = lv.size(); + final int argsize = lv.size(); if (argsize == 0 || argsize > 3) - throw new InternalExpressionException("'range' accepts from 1 to 3 arguments, not "+argsize); + { + throw new InternalExpressionException("'range' accepts from 1 to 3 arguments, not " + argsize); + } to = NumericValue.asNumber(lv.get(0)); if (lv.size() > 1) { @@ -157,79 +166,84 @@ else if (lv.size() == 2) }); expression.addTypedContextFunction("m", -1, Context.MAPDEF, (c, t, lv) -> - { - Value ret; - if (lv.size() == 1 && lv.get(0) instanceof LazyListValue) - ret = new MapValue(((LazyListValue) lv.get(0)).unroll()); - else - ret = new MapValue(lv); - return ret; - }); + lv.size() == 1 && lv.get(0) instanceof final LazyListValue llv + ? new MapValue(llv.unroll()) + : new MapValue(lv) + ); expression.addUnaryFunction("keys", v -> - { - if (v instanceof MapValue) - return new ListValue(((MapValue) v).getMap().keySet()); - return Value.NULL; - }); + v instanceof final MapValue map + ? new ListValue(map.getMap().keySet()) + : Value.NULL + ); expression.addUnaryFunction("values", v -> - { - if (v instanceof MapValue) - return new ListValue(((MapValue) v).getMap().values()); - return Value.NULL; - }); + v instanceof final MapValue map + ? new ListValue(map.getMap().values()) + : Value.NULL + ); expression.addUnaryFunction("pairs", v -> - { - if (v instanceof MapValue) - return ListValue.wrap(((MapValue) v).getMap().entrySet().stream().map( - (p) -> ListValue.of(p.getKey(), p.getValue()) - )); - return Value.NULL; - }); + v instanceof final MapValue map + ? ListValue.wrap(map.getMap().entrySet().stream().map(p -> ListValue.of(p.getKey(), p.getValue()))) + : Value.NULL); - expression.addBinaryContextOperator(":", Operators.precedence.get("attribute~:"),true, true, false, (ctx, t, container, address) -> + expression.addBinaryContextOperator(":", Operators.precedence.get("attribute~:"), true, true, false, (ctx, t, container, address) -> { - if (container instanceof LContainerValue) + if (container instanceof final LContainerValue lcv) { - ContainerValueInterface outerContainer = ((LContainerValue) container).getContainer(); - if (outerContainer == null) return LContainerValue.NULL_CONTAINER; - Value innerContainer = outerContainer.get(((LContainerValue) container).getAddress()); - if (!(innerContainer instanceof ContainerValueInterface)) return LContainerValue.NULL_CONTAINER; - return new LContainerValue((ContainerValueInterface) innerContainer, address); + final ContainerValueInterface outerContainer = lcv.container(); + if (outerContainer == null) + { + return LContainerValue.NULL_CONTAINER; + } + return outerContainer.get(lcv.address()) instanceof final ContainerValueInterface cvi + ? new LContainerValue(cvi, address) + : LContainerValue.NULL_CONTAINER; } - if (!(container instanceof ContainerValueInterface)) + if (!(container instanceof final ContainerValueInterface cvi)) + { return t == Context.LVALUE ? LContainerValue.NULL_CONTAINER : Value.NULL; - if (t != Context.LVALUE) return ((ContainerValueInterface) container).get(address); - return new LContainerValue((ContainerValueInterface) container, address); + } + return t != Context.LVALUE ? cvi.get(address) : new LContainerValue(cvi, address); }); // lazy cause conditional typing - questionable expression.addLazyFunction("get", (c, t, lv) -> { if (lv.size() == 0) + { throw new InternalExpressionException("'get' requires parameters"); + } if (lv.size() == 1) { - Value v = lv.get(0).evalValue(c, Context.LVALUE); - if (!(v instanceof LContainerValue)) + final Value v = lv.get(0).evalValue(c, Context.LVALUE); + if (!(v instanceof final LContainerValue lcv)) + { return LazyValue.NULL; - ContainerValueInterface container = ((LContainerValue) v).getContainer(); + } + final ContainerValueInterface container = lcv.container(); if (container == null) + { return LazyValue.NULL; - Value ret = container.get(((LContainerValue) v).getAddress()); + } + final Value ret = container.get(lcv.address()); return (cc, tt) -> ret; } Value container = lv.get(0).evalValue(c); for (int i = 1; i < lv.size(); i++) { - if (!(container instanceof ContainerValueInterface)) return (cc, tt) -> Value.NULL; - container = ((ContainerValueInterface) container).get(lv.get(i).evalValue(c)); + if (!(container instanceof final ContainerValueInterface cvi)) + { + return (cc, tt) -> Value.NULL; + } + container = cvi.get(lv.get(i).evalValue(c)); } if (container == null) + { return (cc, tt) -> Value.NULL; - Value finalContainer = container; + } + final Value finalContainer = container; return (cc, tt) -> finalContainer; }); @@ -237,66 +251,77 @@ else if (lv.size() == 2) expression.addLazyFunction("has", (c, t, lv) -> { if (lv.size() == 0) + { throw new InternalExpressionException("'has' requires parameters"); + } if (lv.size() == 1) { - Value v = lv.get(0).evalValue(c, Context.LVALUE); - if (!(v instanceof LContainerValue)) + final Value v = lv.get(0).evalValue(c, Context.LVALUE); + if (!(v instanceof final LContainerValue lcv)) + { return LazyValue.NULL; - ContainerValueInterface container = ((LContainerValue) v).getContainer(); + } + final ContainerValueInterface container = lcv.container(); if (container == null) + { return LazyValue.NULL; - Value ret = BooleanValue.of(container.has(((LContainerValue) v).getAddress())); + } + final Value ret = BooleanValue.of(container.has(lcv.address())); return (cc, tt) -> ret; } Value container = lv.get(0).evalValue(c); - for (int i = 1; i < lv.size()-1; i++) + for (int i = 1; i < lv.size() - 1; i++) { - if (!(container instanceof ContainerValueInterface)) return LazyValue.NULL; - container = ((ContainerValueInterface) container).get(lv.get(i).evalValue(c)); + if (!(container instanceof final ContainerValueInterface cvi)) + { + return LazyValue.NULL; + } + container = cvi.get(lv.get(i).evalValue(c)); } - if (!(container instanceof ContainerValueInterface)) + if (!(container instanceof final ContainerValueInterface cvi)) + { return LazyValue.NULL; - Value ret = BooleanValue.of(((ContainerValueInterface) container).has(lv.get(lv.size()-1).evalValue(c))); + } + final Value ret = BooleanValue.of(cvi.has(lv.get(lv.size() - 1).evalValue(c))); return (cc, tt) -> ret; }); // same as `get` expression.addLazyFunction("put", (c, t, lv) -> { - if(lv.size()<2) + if (lv.size() < 2) { throw new InternalExpressionException("'put' takes at least three arguments, a container, address, and values to insert at that index"); } - Value container = lv.get(0).evalValue(c, Context.LVALUE); - if (container instanceof LContainerValue) + final Value container = lv.get(0).evalValue(c, Context.LVALUE); + if (container instanceof final LContainerValue lcv) { - ContainerValueInterface internalContainer = ((LContainerValue) container).getContainer(); + final ContainerValueInterface internalContainer = lcv.container(); if (internalContainer == null) { return LazyValue.NULL; } - Value address = ((LContainerValue) container).getAddress(); - Value what = lv.get(1).evalValue(c); - Value retVal = BooleanValue.of((lv.size() > 2) + final Value address = lcv.address(); + final Value what = lv.get(1).evalValue(c); + final Value retVal = BooleanValue.of((lv.size() > 2) ? internalContainer.put(address, what, lv.get(2).evalValue(c)) : internalContainer.put(address, what)); return (cc, tt) -> retVal; } - if(lv.size()<3) + if (lv.size() < 3) { throw new InternalExpressionException("'put' takes at least three arguments, a container, address, and values to insert at that index"); } - if (!(container instanceof ContainerValueInterface)) + if (!(container instanceof final ContainerValueInterface cvi)) { return LazyValue.NULL; } - Value where = lv.get(1).evalValue(c); - Value what = lv.get(2).evalValue(c); - Value retVal = BooleanValue.of((lv.size()>3) - ? ((ContainerValueInterface) container).put(where, what, lv.get(3).evalValue(c)) - : ((ContainerValueInterface) container).put(where, what)); + final Value where = lv.get(1).evalValue(c); + final Value what = lv.get(2).evalValue(c); + final Value retVal = BooleanValue.of((lv.size() > 3) + ? cvi.put(where, what, lv.get(3).evalValue(c)) + : cvi.put(where, what)); return (cc, tt) -> retVal; }); @@ -304,44 +329,61 @@ else if (lv.size() == 2) expression.addLazyFunction("delete", (c, t, lv) -> { if (lv.size() == 0) + { throw new InternalExpressionException("'delete' requires parameters"); + } if (lv.size() == 1) { - Value v = lv.get(0).evalValue(c, Context.LVALUE); - if (!(v instanceof LContainerValue)) + final Value v = lv.get(0).evalValue(c, Context.LVALUE); + if (!(v instanceof final LContainerValue lcv)) + { return LazyValue.NULL; - ContainerValueInterface container = ((LContainerValue) v).getContainer(); + } + final ContainerValueInterface container = lcv.container(); if (container == null) + { return LazyValue.NULL; - Value ret = BooleanValue.of(container.delete(((LContainerValue) v).getAddress())); + } + final Value ret = BooleanValue.of(container.delete(lcv.address())); return (cc, tt) -> ret; } Value container = lv.get(0).evalValue(c); - for (int i = 1; i < lv.size()-1; i++) + for (int i = 1; i < lv.size() - 1; i++) { - if (!(container instanceof ContainerValueInterface)) return LazyValue.NULL; - container = ((ContainerValueInterface) container).get(lv.get(i).evalValue(c)); + if (!(container instanceof final ContainerValueInterface cvi)) + { + return LazyValue.NULL; + } + container = cvi.get(lv.get(i).evalValue(c)); } - if (!(container instanceof ContainerValueInterface)) + if (!(container instanceof final ContainerValueInterface cvi)) + { return LazyValue.NULL; - Value ret = BooleanValue.of(((ContainerValueInterface) container).delete(lv.get(lv.size()-1).evalValue(c))); + } + final Value ret = BooleanValue.of(cvi.delete(lv.get(lv.size() - 1).evalValue(c))); return (cc, tt) -> ret; }); expression.addUnaryFunction("encode_b64", v -> StringValue.of(Base64.getEncoder().encodeToString(v.getString().getBytes(StandardCharsets.UTF_8)))); expression.addUnaryFunction("decode_b64", v -> { - try { + try + { return StringValue.of(new String(Base64.getDecoder().decode(v.getString()), StandardCharsets.UTF_8)); - } catch (IllegalArgumentException iae){ + } + catch (final IllegalArgumentException iae) + { throw new ThrowStatement("Invalid b64 string: " + v.getString(), Throwables.B64_ERROR); } }); expression.addUnaryFunction("encode_json", v -> StringValue.of(v.toJson().toString())); expression.addUnaryFunction("decode_json", v -> { - try { + try + { return Auxiliary.GSON.fromJson(v.getString(), Value.class); - } catch (JsonParseException jpe){ + } + catch (final JsonParseException jpe) + { throw new ThrowStatement("Invalid json string: " + v.getString(), Throwables.JSON_ERROR); } }); diff --git a/src/main/java/carpet/script/language/Functions.java b/src/main/java/carpet/script/language/Functions.java index 28953ed776..93e1196eae 100644 --- a/src/main/java/carpet/script/language/Functions.java +++ b/src/main/java/carpet/script/language/Functions.java @@ -19,61 +19,70 @@ import java.util.List; import java.util.Locale; -public class Functions { - public static void apply(Expression expression) // public just to get the javadoc right +public class Functions +{ + public static void apply(final Expression expression) // public just to get the javadoc right { // artificial construct to handle user defined functions and function definitions expression.addContextFunction("import", -1, (c, t, lv) -> { - if (lv.size() < 1) throw new InternalExpressionException("'import' needs at least a module name to import, and list of values to import"); + if (lv.size() < 1) + { + throw new InternalExpressionException("'import' needs at least a module name to import, and list of values to import"); + } String moduleName = lv.get(0).getString(); c.host.importModule(c, moduleName); moduleName = moduleName.toLowerCase(Locale.ROOT); if (lv.size() > 1) + { c.host.importNames(c, expression.module, moduleName, lv.subList(1, lv.size()).stream().map(Value::getString).toList()); - if (t == Context.VOID) - return Value.NULL; - return ListValue.wrap(c.host.availableImports(moduleName).map(StringValue::new)); + } + return t == Context.VOID ? Value.NULL : ListValue.wrap(c.host.availableImports(moduleName).map(StringValue::new)); }); // needs to be lazy because of custom context of execution of arguments as a signature - expression.addCustomFunction("call", new Fluff.AbstractLazyFunction(-1, "call") { + expression.addCustomFunction("call", new Fluff.AbstractLazyFunction(-1, "call") + { @Override - public LazyValue lazyEval(Context c, Context.Type t, Expression expr, Tokenizer.Token tok, List lv) + public LazyValue lazyEval(final Context c, final Context.Type t, final Expression expr, final Tokenizer.Token tok, final List lv) { if (lv.size() == 0) + { throw new InternalExpressionException("'call' expects at least function name to call"); + } //lv.remove(lv.size()-1); // aint gonna cut it // maybe it will because of the eager eval changes if (t != Context.SIGNATURE) // just call the function { - List args = Fluff.AbstractFunction.unpackLazy(lv, c, Context.NONE); - FunctionArgument functionArgument = FunctionArgument.findIn(c, expression.module, args, 0, false, true); - FunctionValue fun = functionArgument.function; + final List args = Fluff.AbstractFunction.unpackLazy(lv, c, Context.NONE); + final FunctionArgument functionArgument = FunctionArgument.findIn(c, expression.module, args, 0, false, true); + final FunctionValue fun = functionArgument.function; return fun.callInContext(c, t, functionArgument.args); } // gimme signature - String name = lv.get(0).evalValue(c, Context.NONE).getString(); - List args = new ArrayList<>(); - List globals = new ArrayList<>(); + final String name = lv.get(0).evalValue(c, Context.NONE).getString(); + final List args = new ArrayList<>(); + final List globals = new ArrayList<>(); String varArgs = null; for (int i = 1; i < lv.size(); i++) { - Value v = lv.get(i).evalValue(c, Context.LOCALIZATION); + final Value v = lv.get(i).evalValue(c, Context.LOCALIZATION); if (!v.isBound()) { throw new InternalExpressionException("Only variables can be used in function signature, not " + v.getString()); } - if (v instanceof FunctionAnnotationValue) + if (v instanceof final FunctionAnnotationValue fav) { - if (((FunctionAnnotationValue) v).type == FunctionAnnotationValue.Type.GLOBAL) + if (fav.type == FunctionAnnotationValue.Type.GLOBAL) { globals.add(v.boundVariable); } else { if (varArgs != null) - throw new InternalExpressionException("Variable argument identifier is already defined as "+varArgs+", trying to overwrite with "+v.boundVariable); + { + throw new InternalExpressionException("Variable argument identifier is already defined as " + varArgs + ", trying to overwrite with " + v.boundVariable); + } varArgs = v.boundVariable; } } @@ -82,7 +91,7 @@ public LazyValue lazyEval(Context c, Context.Type t, Expression expr, Tokenizer. args.add(v.boundVariable); } } - Value retval = new FunctionSignatureValue(name, args, varArgs, globals); + final Value retval = new FunctionSignatureValue(name, args, varArgs, globals); return (cc, tt) -> retval; } @@ -93,14 +102,15 @@ public boolean pure() } @Override - public boolean transitive() { + public boolean transitive() + { return false; } @Override - public Context.Type staticType(Context.Type outerType) + public Context.Type staticType(final Context.Type outerType) { - return outerType==Context.SIGNATURE?Context.LOCALIZATION:Context.NONE; + return outerType == Context.SIGNATURE ? Context.LOCALIZATION : Context.NONE; } }); @@ -108,7 +118,9 @@ public Context.Type staticType(Context.Type outerType) expression.addContextFunction("outer", 1, (c, t, lv) -> { if (t != Context.LOCALIZATION) + { throw new InternalExpressionException("Outer scoping of variables is only possible in function signatures."); + } return new FunctionAnnotationValue(lv.get(0), FunctionAnnotationValue.Type.GLOBAL); }); @@ -118,16 +130,20 @@ public Context.Type staticType(Context.Type outerType) { if (type == Context.MAPDEF) { - Value result = ListValue.of(lv1.evalValue(c), lv2.evalValue(c)); + final Value result = ListValue.of(lv1.evalValue(c), lv2.evalValue(c)); return (cc, tt) -> result; } - Value v1 = lv1.evalValue(c, Context.SIGNATURE); - if (!(v1 instanceof FunctionSignatureValue sign)) + final Value v1 = lv1.evalValue(c, Context.SIGNATURE); + if (!(v1 instanceof final FunctionSignatureValue sign)) + { throw new InternalExpressionException("'->' operator requires a function signature on the LHS"); - Value result = expression.createUserDefinedFunction(c, sign.getName(), e, t, sign.getArgs(), sign.getVarArgs(), sign.getGlobals(), lv2); + } + final Value result = expression.createUserDefinedFunction(c, sign.identifier(), e, t, sign.arguments(), sign.varArgs(), sign.globals(), lv2); return (cc, tt) -> result; }); - expression.addImpureFunction("return", (lv) -> { throw new ReturnStatement(lv.size()==0?Value.NULL:lv.get(0));} ); + expression.addImpureFunction("return", (lv) -> { + throw new ReturnStatement(lv.size() == 0 ? Value.NULL : lv.get(0)); + }); } } diff --git a/src/main/java/carpet/script/language/Loops.java b/src/main/java/carpet/script/language/Loops.java index 4261bb6130..36e4b626c3 100644 --- a/src/main/java/carpet/script/language/Loops.java +++ b/src/main/java/carpet/script/language/Loops.java @@ -15,55 +15,74 @@ import java.util.Iterator; import java.util.List; -public class Loops { - public static void apply(Expression expression) +public class Loops +{ + public static void apply(final Expression expression) { // condition and expression will get a bound '_i' // returns last successful expression or false // while(cond, limit, expr) => ?? expression.addImpureFunction("break", lv -> { - if (lv.size()==0) throw new BreakStatement(null); - if (lv.size()==1) throw new BreakStatement(lv.get(0)); + if (lv.size() == 0) + { + throw new BreakStatement(null); + } + if (lv.size() == 1) + { + throw new BreakStatement(lv.get(0)); + } throw new InternalExpressionException("'break' can only be called with zero or one argument"); }); expression.addImpureFunction("continue", lv -> { - if (lv.size()==0) throw new ContinueStatement(null); - if (lv.size()==1) throw new ContinueStatement(lv.get(0)); + if (lv.size() == 0) + { + throw new ContinueStatement(null); + } + if (lv.size() == 1) + { + throw new ContinueStatement(lv.get(0)); + } throw new InternalExpressionException("'continue' can only be called with zero or one argument"); }); // lazy expression.addLazyFunction("while", 3, (c, t, lv) -> { - long limit = NumericValue.asNumber(lv.get(1).evalValue(c)).getLong(); - LazyValue condition = lv.get(0); - LazyValue expr = lv.get(2); + final long limit = NumericValue.asNumber(lv.get(1).evalValue(c)).getLong(); + final LazyValue condition = lv.get(0); + final LazyValue expr = lv.get(2); long i = 0; Value lastOne = Value.NULL; //scoping - LazyValue _val = c.getVariable("_"); - c.setVariable("_",(cc, tt) -> new NumericValue(0).bindTo("_")); - while (i new NumericValue(0).bindTo("_")); + while (i < limit && condition.evalValue(c, Context.BOOLEAN).getBoolean()) { try { lastOne = expr.evalValue(c, t); } - catch (BreakStatement | ContinueStatement stmt) + catch (final BreakStatement | ContinueStatement stmt) { - if (stmt.retval != null) lastOne = stmt.retval; - if (stmt instanceof BreakStatement) break; + if (stmt.retval != null) + { + lastOne = stmt.retval; + } + if (stmt instanceof BreakStatement) + { + break; + } } i++; - long seriously = i; + final long seriously = i; c.setVariable("_", (cc, tt) -> new NumericValue(seriously).bindTo("_")); } //revering scope c.setVariable("_", _val); - Value lastValueNoKidding = lastOne; + final Value lastValueNoKidding = lastOne; return (cc, tt) -> lastValueNoKidding; }); @@ -71,28 +90,34 @@ public static void apply(Expression expression) // expr receives bounded variable '_' indicating iteration expression.addLazyFunction("loop", 2, (c, t, lv) -> { - long limit = NumericValue.asNumber(lv.get(0).evalValue(c, Context.NONE)).getLong(); + final long limit = NumericValue.asNumber(lv.get(0).evalValue(c, Context.NONE)).getLong(); Value lastOne = Value.NULL; - LazyValue expr = lv.get(1); + final LazyValue expr = lv.get(1); //scoping - LazyValue _val = c.getVariable("_"); - for (long i=0; i < limit; i++) + final LazyValue _val = c.getVariable("_"); + for (long i = 0; i < limit; i++) { - long whyYouAsk = i; + final long whyYouAsk = i; c.setVariable("_", (cc, tt) -> new NumericValue(whyYouAsk).bindTo("_")); try { lastOne = expr.evalValue(c, t); } - catch (BreakStatement | ContinueStatement stmt) + catch (final BreakStatement | ContinueStatement stmt) { - if (stmt.retval != null) lastOne = stmt.retval; - if (stmt instanceof BreakStatement) break; + if (stmt.retval != null) + { + lastOne = stmt.retval; + } + if (stmt instanceof BreakStatement) + { + break; + } } } //revering scope c.setVariable("_", _val); - Value trulyLastOne = lastOne; + final Value trulyLastOne = lastOne; return (cc, tt) -> trulyLastOne; }); @@ -100,31 +125,39 @@ public static void apply(Expression expression) // receives bounded variable '_' with the expression expression.addLazyFunction("map", 2, (c, t, lv) -> { - Value rval= lv.get(0).evalValue(c, Context.NONE); - if (rval.isNull()) return ListValue.lazyEmpty(); - if (!(rval instanceof AbstractListValue)) + final Value rval = lv.get(0).evalValue(c, Context.NONE); + if (rval.isNull()) + { + return ListValue.lazyEmpty(); + } + if (!(rval instanceof final AbstractListValue alv)) + { throw new InternalExpressionException("First argument of 'map' function should be a list or iterator"); - Iterator iterator = ((AbstractListValue) rval).iterator(); - LazyValue expr = lv.get(1); + } + final Iterator iterator = alv.iterator(); + final LazyValue expr = lv.get(1); //scoping - LazyValue _val = c.getVariable("_"); - LazyValue _iter = c.getVariable("_i"); - List result = new ArrayList<>(); - for (int i=0; iterator.hasNext(); i++) + final LazyValue _val = c.getVariable("_"); + final LazyValue _iter = c.getVariable("_i"); + final List result = new ArrayList<>(); + for (int i = 0; iterator.hasNext(); i++) { - Value next = iterator.next(); - String var = next.boundVariable; + final Value next = iterator.next(); + final String var = next.boundVariable; next.bindTo("_"); - int doYouReally = i; + final int doYouReally = i; c.setVariable("_", (cc, tt) -> next); c.setVariable("_i", (cc, tt) -> new NumericValue(doYouReally).bindTo("_i")); try { result.add(expr.evalValue(c, t)); } - catch (BreakStatement | ContinueStatement stmt) + catch (final BreakStatement | ContinueStatement stmt) { - if (stmt.retval != null) result.add(stmt.retval); + if (stmt.retval != null) + { + result.add(stmt.retval); + } if (stmt instanceof BreakStatement) { next.boundVariable = var; @@ -134,11 +167,11 @@ public static void apply(Expression expression) next.boundVariable = var; } ((AbstractListValue) rval).fatality(); - Value ret = ListValue.wrap(result); + final Value ret = ListValue.wrap(result); //revering scope c.setVariable("_", _val); c.setVariable("_i", _iter); - return (cc, tt) -> ret; + return (cc, tt) -> ret; }); // grep(list or num, expr) => list @@ -146,32 +179,42 @@ public static void apply(Expression expression) // produces list of values for which the expression is true expression.addLazyFunction("filter", 2, (c, t, lv) -> { - Value rval= lv.get(0).evalValue(c, Context.NONE); - if (rval.isNull()) return ListValue.lazyEmpty(); - if (!(rval instanceof AbstractListValue)) + final Value rval = lv.get(0).evalValue(c, Context.NONE); + if (rval.isNull()) + { + return ListValue.lazyEmpty(); + } + if (!(rval instanceof final AbstractListValue alv)) + { throw new InternalExpressionException("First argument of 'filter' function should be a list or iterator"); - Iterator iterator = ((AbstractListValue) rval).iterator(); - LazyValue expr = lv.get(1); + } + final Iterator iterator = alv.iterator(); + final LazyValue expr = lv.get(1); //scoping - LazyValue _val = c.getVariable("_"); - LazyValue _iter = c.getVariable("_i"); - List result = new ArrayList<>(); - for (int i=0; iterator.hasNext(); i++) + final LazyValue _val = c.getVariable("_"); + final LazyValue _iter = c.getVariable("_i"); + final List result = new ArrayList<>(); + for (int i = 0; iterator.hasNext(); i++) { - Value next = iterator.next(); - String var = next.boundVariable; + final Value next = iterator.next(); + final String var = next.boundVariable; next.bindTo("_"); - int seriously = i; + final int seriously = i; c.setVariable("_", (cc, tt) -> next); c.setVariable("_i", (cc, tt) -> new NumericValue(seriously).bindTo("_i")); try { - if(expr.evalValue(c, Context.BOOLEAN).getBoolean()) + if (expr.evalValue(c, Context.BOOLEAN).getBoolean()) + { result.add(next); + } } - catch (BreakStatement | ContinueStatement stmt) + catch (final BreakStatement | ContinueStatement stmt) { - if (stmt.retval != null && stmt.retval.getBoolean()) result.add(next); + if (stmt.retval != null && stmt.retval.getBoolean()) + { + result.add(next); + } if (stmt instanceof BreakStatement) { next.boundVariable = var; @@ -181,7 +224,7 @@ public static void apply(Expression expression) next.boundVariable = var; } ((AbstractListValue) rval).fatality(); - Value ret = ListValue.wrap(result); + final Value ret = ListValue.wrap(result); //revering scope c.setVariable("_", _val); c.setVariable("_i", _iter); @@ -193,41 +236,45 @@ public static void apply(Expression expression) // returns first element on the list for which the expr is true expression.addLazyFunction("first", 2, (c, t, lv) -> { - - Value rval= lv.get(0).evalValue(c, Context.NONE); - if (rval.isNull()) return LazyValue.NULL; - if (!(rval instanceof AbstractListValue)) + final Value rval = lv.get(0).evalValue(c, Context.NONE); + if (rval.isNull()) + { + return LazyValue.NULL; + } + if (!(rval instanceof final AbstractListValue alv)) + { throw new InternalExpressionException("First argument of 'first' function should be a list or iterator"); - Iterator iterator = ((AbstractListValue) rval).iterator(); - LazyValue expr = lv.get(1); + } + final Iterator iterator = alv.iterator(); + final LazyValue expr = lv.get(1); //scoping - LazyValue _val = c.getVariable("_"); - LazyValue _iter = c.getVariable("_i"); + final LazyValue _val = c.getVariable("_"); + final LazyValue _iter = c.getVariable("_i"); Value result = Value.NULL; - for (int i=0; iterator.hasNext(); i++) + for (int i = 0; iterator.hasNext(); i++) { - Value next = iterator.next(); - String var = next.boundVariable; + final Value next = iterator.next(); + final String var = next.boundVariable; next.bindTo("_"); - int seriously = i; + final int seriously = i; c.setVariable("_", (cc, tt) -> next); c.setVariable("_i", (cc, tt) -> new NumericValue(seriously).bindTo("_i")); try { - if(expr.evalValue(c, Context.BOOLEAN).getBoolean()) + if (expr.evalValue(c, Context.BOOLEAN).getBoolean()) { result = next; next.boundVariable = var; break; } } - catch (BreakStatement stmt) + catch (final BreakStatement stmt) { - result = stmt.retval == null? next : stmt.retval; + result = stmt.retval == null ? next : stmt.retval; next.boundVariable = var; break; } - catch (ContinueStatement ignored) + catch (final ContinueStatement ignored) { throw new InternalExpressionException("'continue' inside 'first' function has no sense"); } @@ -235,7 +282,7 @@ public static void apply(Expression expression) } //revering scope ((AbstractListValue) rval).fatality(); - Value whyWontYouTrustMeJava = result; + final Value whyWontYouTrustMeJava = result; c.setVariable("_", _val); c.setVariable("_i", _iter); return (cc, tt) -> whyWontYouTrustMeJava; @@ -246,25 +293,30 @@ public static void apply(Expression expression) // returns true if expr is true for all items expression.addLazyFunction("all", 2, (c, t, lv) -> { - Value rval= lv.get(0).evalValue(c, Context.NONE); - if (rval.isNull()) return LazyValue.TRUE; - if (!(rval instanceof AbstractListValue)) + final Value rval = lv.get(0).evalValue(c, Context.NONE); + if (rval.isNull()) + { + return LazyValue.TRUE; + } + if (!(rval instanceof final AbstractListValue alv)) + { throw new InternalExpressionException("First argument of 'all' function should be a list or iterator"); - Iterator iterator = ((AbstractListValue) rval).iterator(); - LazyValue expr = lv.get(1); + } + final Iterator iterator = alv.iterator(); + final LazyValue expr = lv.get(1); //scoping - LazyValue _val = c.getVariable("_"); - LazyValue _iter = c.getVariable("_i"); + final LazyValue _val = c.getVariable("_"); + final LazyValue _iter = c.getVariable("_i"); LazyValue result = LazyValue.TRUE; - for (int i=0; iterator.hasNext(); i++) + for (int i = 0; iterator.hasNext(); i++) { - Value next = iterator.next(); - String var = next.boundVariable; + final Value next = iterator.next(); + final String var = next.boundVariable; next.bindTo("_"); - int seriously = i; + final int seriously = i; c.setVariable("_", (cc, tt) -> next); c.setVariable("_i", (cc, tt) -> new NumericValue(seriously).bindTo("_i")); - if(!expr.evalValue(c, Context.BOOLEAN).getBoolean()) + if (!expr.evalValue(c, Context.BOOLEAN).getBoolean()) { result = LazyValue.FALSE; next.boundVariable = var; @@ -282,10 +334,10 @@ public static void apply(Expression expression) // runs traditional for(init, condition, increment, body) tri-argument for loop with body in between expression.addLazyFunction("c_for", 4, (c, t, lv) -> { - LazyValue initial = lv.get(0); - LazyValue condition = lv.get(1); - LazyValue increment = lv.get(2); - LazyValue body = lv.get(3); + final LazyValue initial = lv.get(0); + final LazyValue condition = lv.get(1); + final LazyValue increment = lv.get(2); + final LazyValue body = lv.get(3); int iterations = 0; for (initial.evalValue(c, Context.VOID); condition.evalValue(c, Context.BOOLEAN).getBoolean(); increment.evalValue(c, Context.VOID)) { @@ -293,16 +345,16 @@ public static void apply(Expression expression) { body.evalValue(c, Context.VOID); } - catch (BreakStatement stmt) + catch (final BreakStatement stmt) { break; } - catch (ContinueStatement ignored) + catch (final ContinueStatement ignored) { } iterations++; } - int finalIterations = iterations; + final int finalIterations = iterations; return (cc, tt) -> new NumericValue(finalIterations); }); @@ -311,22 +363,27 @@ public static void apply(Expression expression) // can be substituted for first and all, but first is more efficient and all doesn't require knowing list size expression.addLazyFunction("for", 2, (c, t, lv) -> { - Value rval= lv.get(0).evalValue(c, Context.NONE); - if (rval.isNull()) return LazyValue.ZERO; - if (!(rval instanceof AbstractListValue)) + final Value rval = lv.get(0).evalValue(c, Context.NONE); + if (rval.isNull()) + { + return LazyValue.ZERO; + } + if (!(rval instanceof final AbstractListValue alv)) + { throw new InternalExpressionException("First argument of 'for' function should be a list or iterator"); - Iterator iterator = ((AbstractListValue) rval).iterator(); - LazyValue expr = lv.get(1); + } + final Iterator iterator = alv.iterator(); + final LazyValue expr = lv.get(1); //scoping - LazyValue _val = c.getVariable("_"); - LazyValue _ite = c.getVariable("_i"); + final LazyValue _val = c.getVariable("_"); + final LazyValue _ite = c.getVariable("_i"); int successCount = 0; - for (int i=0; iterator.hasNext(); i++) + for (int i = 0; iterator.hasNext(); i++) { - Value next = iterator.next(); - String var = next.boundVariable; + final Value next = iterator.next(); + final String var = next.boundVariable; next.bindTo("_"); - int seriously = i; + final int seriously = i; c.setVariable("_", (cc, tt) -> next); c.setVariable("_i", (cc, tt) -> new NumericValue(seriously).bindTo("_i")); Value result = Value.FALSE; @@ -334,24 +391,29 @@ public static void apply(Expression expression) { result = expr.evalValue(c, t); } - catch (BreakStatement | ContinueStatement stmt) + catch (final BreakStatement | ContinueStatement stmt) { - if (stmt.retval != null) result = stmt.retval; + if (stmt.retval != null) + { + result = stmt.retval; + } if (stmt instanceof BreakStatement) { next.boundVariable = var; break; } } - if(t != Context.VOID && result.getBoolean()) + if (t != Context.VOID && result.getBoolean()) + { successCount++; + } next.boundVariable = var; } //revering scope ((AbstractListValue) rval).fatality(); c.setVariable("_", _val); c.setVariable("_i", _ite); - long promiseWontChange = successCount; + final long promiseWontChange = successCount; return (cc, tt) -> new NumericValue(promiseWontChange); }); @@ -363,32 +425,37 @@ public static void apply(Expression expression) expression.addLazyFunction("reduce", 3, (c, t, lv) -> { - Value rval= lv.get(0).evalValue(c, Context.NONE); - if (rval.isNull()) return ListValue.lazyEmpty(); - if (!(rval instanceof AbstractListValue)) + final Value rval = lv.get(0).evalValue(c, Context.NONE); + if (rval.isNull()) + { + return ListValue.lazyEmpty(); + } + if (!(rval instanceof final AbstractListValue alv)) + { throw new InternalExpressionException("First argument of 'reduce' should be a list or iterator"); - LazyValue expr = lv.get(1); + } + final LazyValue expr = lv.get(1); Value acc = lv.get(2).evalValue(c, Context.NONE); - Iterator iterator = ((AbstractListValue) rval).iterator(); + final Iterator iterator = alv.iterator(); if (!iterator.hasNext()) { - Value seriouslyWontChange = acc; + final Value seriouslyWontChange = acc; return (cc, tt) -> seriouslyWontChange; } //scoping - LazyValue _val = c.getVariable("_"); - LazyValue _acc = c.getVariable("_a"); - LazyValue _ite = c.getVariable("_i"); + final LazyValue _val = c.getVariable("_"); + final LazyValue _acc = c.getVariable("_a"); + final LazyValue _ite = c.getVariable("_i"); - for (int i=0; iterator.hasNext(); i++) + for (int i = 0; iterator.hasNext(); i++) { - Value next = iterator.next(); - String var = next.boundVariable; + final Value next = iterator.next(); + final String var = next.boundVariable; next.bindTo("_"); - Value promiseWontChangeYou = acc; - int seriously = i; + final Value promiseWontChangeYou = acc; + final int seriously = i; c.setVariable("_a", (cc, tt) -> promiseWontChangeYou.bindTo("_a")); c.setVariable("_", (cc, tt) -> next); c.setVariable("_i", (cc, tt) -> new NumericValue(seriously).bindTo("_i")); @@ -396,9 +463,12 @@ public static void apply(Expression expression) { acc = expr.evalValue(c, t); } - catch (BreakStatement | ContinueStatement stmt) + catch (final BreakStatement | ContinueStatement stmt) { - if (stmt.retval != null) acc = stmt.retval; + if (stmt.retval != null) + { + acc = stmt.retval; + } if (stmt instanceof BreakStatement) { next.boundVariable = var; @@ -413,7 +483,7 @@ public static void apply(Expression expression) c.setVariable("_", _val); c.setVariable("_i", _ite); - Value hopeItsEnoughPromise = acc; + final Value hopeItsEnoughPromise = acc; return (cc, tt) -> hopeItsEnoughPromise; }); } diff --git a/src/main/java/carpet/script/language/Operators.java b/src/main/java/carpet/script/language/Operators.java index a2c7a46b56..539ed3fc6e 100644 --- a/src/main/java/carpet/script/language/Operators.java +++ b/src/main/java/carpet/script/language/Operators.java @@ -21,8 +21,10 @@ import java.util.List; import java.util.Map; -public class Operators { - public static final Map precedence = new HashMap() {{ +public class Operators +{ + public static final Map precedence = new HashMap<>() + {{ put("attribute~:", 80); put("unary+-!...", 60); put("exponent^", 40); @@ -37,44 +39,68 @@ public class Operators { put("nextop;", 1); }}; - public static void apply(Expression expression) + public static void apply(final Expression expression) { expression.addBinaryOperator("+", precedence.get("addition+-"), true, Value::add); expression.addFunction("sum", lv -> { - int size = lv.size(); - if (size == 0) return Value.NULL; + final int size = lv.size(); + if (size == 0) + { + return Value.NULL; + } Value accumulator = lv.get(0); - for (Value v: lv.subList(1, size)) accumulator = accumulator.add(v); + for (final Value v : lv.subList(1, size)) + { + accumulator = accumulator.add(v); + } return accumulator; }); expression.addFunctionalEquivalence("+", "sum"); expression.addBinaryOperator("-", precedence.get("addition+-"), true, Value::subtract); expression.addFunction("difference", lv -> { - int size = lv.size(); - if (size == 0) return Value.NULL; + final int size = lv.size(); + if (size == 0) + { + return Value.NULL; + } Value accumulator = lv.get(0); - for (Value v: lv.subList(1, size)) accumulator = accumulator.subtract(v); + for (final Value v : lv.subList(1, size)) + { + accumulator = accumulator.subtract(v); + } return accumulator; }); expression.addFunctionalEquivalence("-", "difference"); expression.addBinaryOperator("*", precedence.get("multiplication*/%"), true, Value::multiply); expression.addFunction("product", lv -> { - int size = lv.size(); - if (size == 0) return Value.NULL; + final int size = lv.size(); + if (size == 0) + { + return Value.NULL; + } Value accumulator = lv.get(0); - for (Value v: lv.subList(1, size)) accumulator = accumulator.multiply(v); + for (final Value v : lv.subList(1, size)) + { + accumulator = accumulator.multiply(v); + } return accumulator; }); expression.addFunctionalEquivalence("*", "product"); expression.addBinaryOperator("/", precedence.get("multiplication*/%"), true, Value::divide); expression.addFunction("quotient", lv -> { - int size = lv.size(); - if (size == 0) return Value.NULL; + final int size = lv.size(); + if (size == 0) + { + return Value.NULL; + } Value accumulator = lv.get(0); - for (Value v: lv.subList(1, size)) accumulator = accumulator.divide(v); + for (final Value v : lv.subList(1, size)) + { + accumulator = accumulator.divide(v); + } return accumulator; }); expression.addFunctionalEquivalence("/", "quotient"); @@ -85,51 +111,79 @@ public static void apply(Expression expression) new NumericValue(java.lang.Math.pow(NumericValue.asNumber(v1).getDouble(), NumericValue.asNumber(v2).getDouble()))); expression.addFunction("bitwise_and", lv -> { - int size = lv.size(); - if (size == 0) return Value.NULL; + final int size = lv.size(); + if (size == 0) + { + return Value.NULL; + } long accumulator = NumericValue.asNumber(lv.get(0)).getLong(); - for (Value v: lv.subList(1, size)) accumulator = accumulator & NumericValue.asNumber(v).getLong(); + for (final Value v : lv.subList(1, size)) + { + accumulator = accumulator & NumericValue.asNumber(v).getLong(); + } return new NumericValue(accumulator); }); expression.addFunction("bitwise_xor", lv -> { - int size = lv.size(); - if (size == 0) return Value.NULL; + final int size = lv.size(); + if (size == 0) + { + return Value.NULL; + } long accumulator = NumericValue.asNumber(lv.get(0)).getLong(); - for (Value v: lv.subList(1, size)) accumulator = accumulator ^ NumericValue.asNumber(v).getLong(); + for (final Value v : lv.subList(1, size)) + { + accumulator = accumulator ^ NumericValue.asNumber(v).getLong(); + } return new NumericValue(accumulator); }); expression.addFunction("bitwise_or", lv -> { - int size = lv.size(); - if (size == 0) return Value.NULL; + final int size = lv.size(); + if (size == 0) + { + return Value.NULL; + } long accumulator = NumericValue.asNumber(lv.get(0)).getLong(); - for (Value v: lv.subList(1, size)) accumulator = accumulator | NumericValue.asNumber(v).getLong(); + for (final Value v : lv.subList(1, size)) + { + accumulator = accumulator | NumericValue.asNumber(v).getLong(); + } return new NumericValue(accumulator); }); // lazy cause RHS is only conditional expression.addLazyBinaryOperator("&&", precedence.get("and&&"), false, true, t -> Context.Type.BOOLEAN, (c, t, lv1, lv2) -> { // todo check how is optimizations going - Value v1 = lv1.evalValue(c, Context.BOOLEAN); - if (!v1.getBoolean()) return (cc, tt) -> v1; - return lv2; + final Value v1 = lv1.evalValue(c, Context.BOOLEAN); + return v1.getBoolean() ? lv2 : ((cc, tt) -> v1); }); expression.addPureLazyFunction("and", -1, t -> Context.Type.BOOLEAN, (c, t, lv) -> { - int last = lv.size()-1; - if (last == -1) return LazyValue.TRUE; - for (LazyValue l: lv.subList(0, last)) + final int last = lv.size() - 1; + if (last == -1) + { + return LazyValue.TRUE; + } + for (final LazyValue l : lv.subList(0, last)) { - Value val = l.evalValue(c, Context.Type.BOOLEAN); - if (val instanceof FunctionUnpackedArgumentsValue) + final Value val = l.evalValue(c, Context.Type.BOOLEAN); + if (val instanceof final FunctionUnpackedArgumentsValue fuav) { - for (Value it : (FunctionUnpackedArgumentsValue) val) - if (!it.getBoolean()) return (cc, tt) -> it; + for (final Value it : fuav) + { + if (!it.getBoolean()) + { + return (cc, tt) -> it; + } + } } else { - if (!val.getBoolean()) return (cc, tt) -> val; + if (!val.getBoolean()) + { + return (cc, tt) -> val; + } } } return lv.get(last); @@ -139,25 +193,35 @@ public static void apply(Expression expression) // lazy cause RHS is only conditional expression.addLazyBinaryOperator("||", precedence.get("or||"), false, true, t -> Context.Type.BOOLEAN, (c, t, lv1, lv2) -> { - Value v1 = lv1.evalValue(c, Context.BOOLEAN); - if (v1.getBoolean()) return (cc, tt) -> v1; - return lv2; + final Value v1 = lv1.evalValue(c, Context.BOOLEAN); + return v1.getBoolean() ? ((cc, tt) -> v1) : lv2; }); expression.addPureLazyFunction("or", -1, t -> Context.Type.BOOLEAN, (c, t, lv) -> { - int last = lv.size()-1; - if (last == -1) return LazyValue.FALSE; - for (LazyValue l: lv.subList(0, last)) + final int last = lv.size() - 1; + if (last == -1) { - Value val = l.evalValue(c, Context.Type.BOOLEAN); - if (val instanceof FunctionUnpackedArgumentsValue) + return LazyValue.FALSE; + } + for (final LazyValue l : lv.subList(0, last)) + { + final Value val = l.evalValue(c, Context.Type.BOOLEAN); + if (val instanceof final FunctionUnpackedArgumentsValue fuav) { - for (Value it : (FunctionUnpackedArgumentsValue) val) - if (it.getBoolean()) return (cc, tt) -> it; + for (final Value it : fuav) + { + if (it.getBoolean()) + { + return (cc, tt) -> it; + } + } } else { - if (val.getBoolean()) return (cc, tt) -> val; + if (val.getBoolean()) + { + return (cc, tt) -> val; + } } } return lv.get(last); @@ -169,12 +233,18 @@ public static void apply(Expression expression) expression.addBinaryOperator(">", precedence.get("compare>=><=<"), false, (v1, v2) -> BooleanValue.of(v1.compareTo(v2) > 0)); expression.addFunction("decreasing", lv -> { - int size = lv.size(); - if (size < 2) return Value.TRUE; + final int size = lv.size(); + if (size < 2) + { + return Value.TRUE; + } Value prev = lv.get(0); - for (Value next: lv.subList(1, size)) + for (final Value next : lv.subList(1, size)) { - if (prev.compareTo(next) <= 0) return Value.FALSE; + if (prev.compareTo(next) <= 0) + { + return Value.FALSE; + } prev = next; } return Value.TRUE; @@ -184,12 +254,18 @@ public static void apply(Expression expression) expression.addBinaryOperator(">=", precedence.get("compare>=><=<"), false, (v1, v2) -> BooleanValue.of(v1.compareTo(v2) >= 0)); expression.addFunction("nonincreasing", lv -> { - int size = lv.size(); - if (size < 2) return Value.TRUE; + final int size = lv.size(); + if (size < 2) + { + return Value.TRUE; + } Value prev = lv.get(0); - for (Value next: lv.subList(1, size)) + for (final Value next : lv.subList(1, size)) { - if (prev.compareTo(next) < 0) return Value.FALSE; + if (prev.compareTo(next) < 0) + { + return Value.FALSE; + } prev = next; } return Value.TRUE; @@ -199,12 +275,18 @@ public static void apply(Expression expression) expression.addBinaryOperator("<", precedence.get("compare>=><=<"), false, (v1, v2) -> BooleanValue.of(v1.compareTo(v2) < 0)); expression.addFunction("increasing", lv -> { - int size = lv.size(); - if (size < 2) return Value.TRUE; + final int size = lv.size(); + if (size < 2) + { + return Value.TRUE; + } Value prev = lv.get(0); - for (Value next: lv.subList(1, size)) + for (final Value next : lv.subList(1, size)) { - if (prev.compareTo(next) >= 0) return Value.FALSE; + if (prev.compareTo(next) >= 0) + { + return Value.FALSE; + } prev = next; } return Value.TRUE; @@ -214,79 +296,84 @@ public static void apply(Expression expression) expression.addBinaryOperator("<=", precedence.get("compare>=><=<"), false, (v1, v2) -> BooleanValue.of(v1.compareTo(v2) <= 0)); expression.addFunction("nondecreasing", lv -> { - int size = lv.size(); - if (size < 2) return Value.TRUE; + final int size = lv.size(); + if (size < 2) + { + return Value.TRUE; + } Value prev = lv.get(0); - for (Value next: lv.subList(1, size)) + for (final Value next : lv.subList(1, size)) { - if (prev.compareTo(next) > 0) return Value.FALSE; + if (prev.compareTo(next) > 0) + { + return Value.FALSE; + } prev = next; } return Value.TRUE; }); expression.addFunctionalEquivalence("<=", "nondecreasing"); - - expression.addMathematicalBinaryIntFunction("bitwise_shift_left", (num, amount) -> { - return num << amount; - }); - expression.addMathematicalBinaryIntFunction("bitwise_shift_right", (num, amount) -> { - return num >> amount; - }); + expression.addMathematicalBinaryIntFunction("bitwise_shift_left", (num, amount) -> num << amount); + expression.addMathematicalBinaryIntFunction("bitwise_shift_right", (num, amount) -> num >> amount); expression.addMathematicalBinaryIntFunction("bitwise_roll_left", (num, num2) -> { - long amount = num2 % 64; - - long amountToRoll = 64 - amount; - long rolledBits = ((-1L) >> amountToRoll) << amountToRoll; - long rolledAmount = (num & rolledBits) >> amountToRoll; + final long amount = num2 % 64; + final long amountToRoll = 64 - amount; + final long rolledBits = ((-1L) >> amountToRoll) << amountToRoll; + final long rolledAmount = (num & rolledBits) >> amountToRoll; return num << amount | rolledAmount; }); expression.addMathematicalBinaryIntFunction("bitwise_roll_right", (num, num2) -> { - long amount = num2 % 64; - - long amountToRoll = 64 - amount; - long rolledBits = ((-1L) << amountToRoll) >> amountToRoll; - long rolledAmount = (num & rolledBits) << amountToRoll; + final long amount = num2 % 64; + final long amountToRoll = 64 - amount; + final long rolledBits = ((-1L) << amountToRoll) >> amountToRoll; + final long rolledAmount = (num & rolledBits) << amountToRoll; return num >> amount | rolledAmount; }); expression.addMathematicalUnaryIntFunction("bitwise_not", d -> { - long num = d.longValue(); - return num ^ (-1L); + final long num = (long) d; + return ~num; }); - expression.addMathematicalUnaryIntFunction("bitwise_popcount", d -> Long.valueOf(Long.bitCount(d.longValue()))); - + expression.addMathematicalUnaryIntFunction("bitwise_popcount", d -> (long) Long.bitCount((long)d)); expression.addMathematicalUnaryIntFunction("double_to_long_bits", Double::doubleToLongBits); - expression.addUnaryFunction("long_to_double_bits", v -> { - return new NumericValue(Double.longBitsToDouble(NumericValue.asNumber(v).getLong())); - }); - - + expression.addUnaryFunction("long_to_double_bits", v -> + new NumericValue(Double.longBitsToDouble(NumericValue.asNumber(v).getLong()))); expression.addBinaryOperator("==", precedence.get("equal==!="), false, (v1, v2) -> v1.equals(v2) ? Value.TRUE : Value.FALSE); expression.addFunction("equal", lv -> { - int size = lv.size(); - if (size < 2) return Value.TRUE; + final int size = lv.size(); + if (size < 2) + { + return Value.TRUE; + } Value prev = lv.get(0); - for (Value next: lv.subList(1, size)) + for (final Value next : lv.subList(1, size)) { - if (!prev.equals(next)) return Value.FALSE; + if (!prev.equals(next)) + { + return Value.FALSE; + } prev = next; } return Value.TRUE; }); expression.addFunctionalEquivalence("==", "equal"); - - expression.addBinaryOperator("!=", precedence.get("equal==!="), false, (v1, v2) -> v1.equals(v2) ? Value.FALSE : Value.TRUE); expression.addFunction("unique", lv -> { - int size = lv.size(); - if (size < 2) return Value.TRUE; + final int size = lv.size(); + if (size < 2) + { + return Value.TRUE; + } // need to order them so same obejects will be next to each other. lv.sort(Comparator.comparingInt(Value::hashCode)); Value prev = lv.get(0); - for (Value next: lv.subList(1, size)) + for (final Value next : lv.subList(1, size)) { - if (prev.equals(next)) return Value.FALSE; + if (prev.equals(next)) + { + return Value.FALSE; + } prev = next; } return Value.TRUE; @@ -296,38 +383,52 @@ public static void apply(Expression expression) // lazy cause of assignment which is non-trivial expression.addLazyBinaryOperator("=", precedence.get("assign=<>"), false, false, t -> Context.Type.LVALUE, (c, t, lv1, lv2) -> { - Value v1 = lv1.evalValue(c, Context.LVALUE); - Value v2 = lv2.evalValue(c); - if (v1 instanceof ListValue.ListConstructorValue && v2 instanceof ListValue) - { - List ll = ((ListValue)v1).getItems(); - List rl = ((ListValue)v2).getItems(); - if (ll.size() < rl.size()) throw new InternalExpressionException("Too many values to unpack"); - if (ll.size() > rl.size()) throw new InternalExpressionException("Too few values to unpack"); - for (Value v: ll) v.assertAssignable(); - Iterator li = ll.iterator(); - Iterator ri = rl.iterator(); - while(li.hasNext()) + final Value v1 = lv1.evalValue(c, Context.LVALUE); + final Value v2 = lv2.evalValue(c); + if (v1 instanceof final ListValue.ListConstructorValue lcv && v2 instanceof final ListValue list) + { + final List ll = lcv.getItems(); + final List rl = list.getItems(); + if (ll.size() < rl.size()) + { + throw new InternalExpressionException("Too many values to unpack"); + } + if (ll.size() > rl.size()) + { + throw new InternalExpressionException("Too few values to unpack"); + } + for (final Value v : ll) + { + v.assertAssignable(); + } + final Iterator li = ll.iterator(); + final Iterator ri = rl.iterator(); + while (li.hasNext()) { - String lname = li.next().getVariable(); - Value vval = ri.next().reboundedTo(lname); + final String lname = li.next().getVariable(); + final Value vval = ri.next().reboundedTo(lname); expression.setAnyVariable(c, lname, (cc, tt) -> vval); } return (cc, tt) -> Value.TRUE; } - if (v1 instanceof LContainerValue) + if (v1 instanceof final LContainerValue lcv) { - ContainerValueInterface container = ((LContainerValue) v1).getContainer(); + final ContainerValueInterface container = lcv.container(); if (container == null) + { + return (cc, tt) -> Value.NULL; + } + final Value address = lcv.address(); + if (!(container.put(address, v2))) + { return (cc, tt) -> Value.NULL; - Value address = ((LContainerValue) v1).getAddress(); - if (!(container.put(address, v2))) return (cc, tt) -> Value.NULL; + } return (cc, tt) -> v2; } v1.assertAssignable(); - String varname = v1.getVariable(); - Value copy = v2.reboundedTo(varname); - LazyValue boundedLHS = (cc, tt) -> copy; + final String varname = v1.getVariable(); + final Value copy = v2.reboundedTo(varname); + final LazyValue boundedLHS = (cc, tt) -> copy; expression.setAnyVariable(c, varname, boundedLHS); return boundedLHS; }); @@ -335,35 +436,44 @@ public static void apply(Expression expression) // lazy due to assignment expression.addLazyBinaryOperator("+=", precedence.get("assign=<>"), false, false, t -> Context.Type.LVALUE, (c, t, lv1, lv2) -> { - Value v1 = lv1.evalValue(c, Context.LVALUE); - Value v2 = lv2.evalValue(c); - if (v1 instanceof ListValue.ListConstructorValue && v2 instanceof ListValue) - { - List ll = ((ListValue)v1).getItems(); - List rl = ((ListValue)v2).getItems(); - if (ll.size() < rl.size()) throw new InternalExpressionException("Too many values to unpack"); - if (ll.size() > rl.size()) throw new InternalExpressionException("Too few values to unpack"); - for (Value v: ll) v.assertAssignable(); - Iterator li = ll.iterator(); - Iterator ri = rl.iterator(); - while(li.hasNext()) + final Value v1 = lv1.evalValue(c, Context.LVALUE); + final Value v2 = lv2.evalValue(c); + if (v1 instanceof final ListValue.ListConstructorValue lcv && v2 instanceof final ListValue list) + { + final List ll = lcv.getItems(); + final List rl = list.getItems(); + if (ll.size() < rl.size()) { - Value lval = li.next(); - String lname = lval.getVariable(); - Value result = lval.add(ri.next()).bindTo(lname); + throw new InternalExpressionException("Too many values to unpack"); + } + if (ll.size() > rl.size()) + { + throw new InternalExpressionException("Too few values to unpack"); + } + for (final Value v : ll) + { + v.assertAssignable(); + } + final Iterator li = ll.iterator(); + final Iterator ri = rl.iterator(); + while (li.hasNext()) + { + final Value lval = li.next(); + final String lname = lval.getVariable(); + final Value result = lval.add(ri.next()).bindTo(lname); expression.setAnyVariable(c, lname, (cc, tt) -> result); } return (cc, tt) -> Value.TRUE; } - if (v1 instanceof LContainerValue) + if (v1 instanceof final LContainerValue lcv) { - ContainerValueInterface cvi = ((LContainerValue) v1).getContainer(); + final ContainerValueInterface cvi = lcv.container(); if (cvi == null) { throw new InternalExpressionException("Failed to resolve left hand side of the += operation"); } - Value key = ((LContainerValue) v1).getAddress(); - Value value = cvi.get(key); + final Value key = lcv.address(); + final Value value = cvi.get(key); if (value instanceof ListValue || value instanceof MapValue) { ((AbstractListValue) value).append(v2); @@ -371,22 +481,22 @@ public static void apply(Expression expression) } else { - Value res = value.add(v2); + final Value res = value.add(v2); cvi.put(key, res); return (cc, tt) -> res; } } v1.assertAssignable(); - String varname = v1.getVariable(); - LazyValue boundedLHS; + final String varname = v1.getVariable(); + final LazyValue boundedLHS; if (v1 instanceof ListValue || v1 instanceof MapValue) { ((AbstractListValue) v1).append(v2); - boundedLHS = (cc, tt)-> v1; + boundedLHS = (cc, tt) -> v1; } else { - Value result = v1.add(v2).bindTo(varname); + final Value result = v1.add(v2).bindTo(varname); boundedLHS = (cc, tt) -> result; } expression.setAnyVariable(c, varname, boundedLHS); @@ -395,22 +505,34 @@ public static void apply(Expression expression) expression.addBinaryContextOperator("<>", precedence.get("assign=<>"), false, false, false, (c, t, v1, v2) -> { - if (v1 instanceof ListValue.ListConstructorValue && v2 instanceof ListValue.ListConstructorValue) - { - List ll = ((ListValue)v1).getItems(); - List rl = ((ListValue)v2).getItems(); - if (ll.size() < rl.size()) throw new InternalExpressionException("Too many values to unpack"); - if (ll.size() > rl.size()) throw new InternalExpressionException("Too few values to unpack"); - for (Value v: ll) v.assertAssignable(); - for (Value v: rl) v.assertAssignable(); - Iterator li = ll.iterator(); - Iterator ri = rl.iterator(); - while(li.hasNext()) + if (v1 instanceof final ListValue.ListConstructorValue lcv1 && v2 instanceof final ListValue.ListConstructorValue lcv2) + { + final List ll = lcv1.getItems(); + final List rl = lcv2.getItems(); + if (ll.size() < rl.size()) { - Value lval = li.next(); - Value rval = ri.next(); - String lname = lval.getVariable(); - String rname = rval.getVariable(); + throw new InternalExpressionException("Too many values to unpack"); + } + if (ll.size() > rl.size()) + { + throw new InternalExpressionException("Too few values to unpack"); + } + for (final Value v : ll) + { + v.assertAssignable(); + } + for (final Value v : rl) + { + v.assertAssignable(); + } + final Iterator li = ll.iterator(); + final Iterator ri = rl.iterator(); + while (li.hasNext()) + { + final Value lval = li.next(); + final Value rval = ri.next(); + final String lname = lval.getVariable(); + final String rname = rval.getVariable(); lval.reboundedTo(rname); rval.reboundedTo(lname); expression.setAnyVariable(c, lname, (cc, tt) -> rval); @@ -420,36 +542,37 @@ public static void apply(Expression expression) } v1.assertAssignable(); v2.assertAssignable(); - String lvalvar = v1.getVariable(); - String rvalvar = v2.getVariable(); - Value lval = v2.reboundedTo(lvalvar); - Value rval = v1.reboundedTo(rvalvar); + final String lvalvar = v1.getVariable(); + final String rvalvar = v2.getVariable(); + final Value lval = v2.reboundedTo(lvalvar); + final Value rval = v1.reboundedTo(rvalvar); expression.setAnyVariable(c, lvalvar, (cc, tt) -> lval); expression.setAnyVariable(c, rvalvar, (cc, tt) -> rval); return lval; }); - expression.addUnaryOperator("-", false, v -> NumericValue.asNumber(v).opposite()); + expression.addUnaryOperator("-", false, v -> NumericValue.asNumber(v).opposite()); expression.addUnaryOperator("+", false, NumericValue::asNumber); // could be non-lazy, but who cares - its a small one. expression.addLazyUnaryOperator("!", precedence.get("unary+-!..."), false, true, x -> Context.Type.BOOLEAN, (c, t, lv) -> - lv.evalValue(c, Context.BOOLEAN).getBoolean() ? (cc, tt)-> Value.FALSE : (cc, tt) -> Value.TRUE + lv.evalValue(c, Context.BOOLEAN).getBoolean() ? (cc, tt) -> Value.FALSE : (cc, tt) -> Value.TRUE ); // might need context boolean // lazy because of typed evaluation of the argument - expression.addLazyUnaryOperator("...", Operators.precedence.get("unary+-!..."), false, true, t -> t== Context.Type.LOCALIZATION?Context.NONE:t, (c, t, lv) -> + expression.addLazyUnaryOperator("...", Operators.precedence.get("unary+-!..."), false, true, t -> t == Context.Type.LOCALIZATION ? Context.NONE : t, (c, t, lv) -> { if (t == Context.LOCALIZATION) + { return (cc, tt) -> new FunctionAnnotationValue(lv.evalValue(c), FunctionAnnotationValue.Type.VARARG); - - Value params = lv.evalValue(c, t); - if (!(params instanceof AbstractListValue)) + } + if (!(lv.evalValue(c, t) instanceof final AbstractListValue alv)) + { throw new InternalExpressionException("Unable to unpack a non-list"); - FunctionUnpackedArgumentsValue fuaval = new FunctionUnpackedArgumentsValue( ((AbstractListValue) params).unpack()); + } + final FunctionUnpackedArgumentsValue fuaval = new FunctionUnpackedArgumentsValue(alv.unpack()); return (cc, tt) -> fuaval; - //throw new InternalExpressionException("That functionality has not been implemented yet."); }); } diff --git a/src/main/java/carpet/script/language/Sys.java b/src/main/java/carpet/script/language/Sys.java index b9efebde8d..475aac724b 100644 --- a/src/main/java/carpet/script/language/Sys.java +++ b/src/main/java/carpet/script/language/Sys.java @@ -3,7 +3,6 @@ import carpet.script.Context; import carpet.script.Expression; import carpet.script.LazyValue; -import carpet.script.ScriptHost; import carpet.script.exception.InternalExpressionException; import carpet.script.utils.PerlinNoiseSampler; import carpet.script.utils.SimplexNoiseSampler; @@ -27,12 +26,13 @@ import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; -public class Sys { +public class Sys +{ public static final Random randomizer = new Random(); // %[argument_index$][flags][width][.precision][t]conversion private static final Pattern formatPattern = Pattern.compile("%(\\d+\\$)?([-#+ 0,(<]*)?(\\d+)?(\\.\\d+)?([tT])?([a-zA-Z%])"); - public static void apply(Expression expression) + public static void apply(final Expression expression) { expression.addUnaryFunction("hash_code", v -> new NumericValue(v.hashCode())); @@ -40,21 +40,23 @@ public static void apply(Expression expression) expression.addTypedContextFunction("bool", 1, Context.BOOLEAN, (c, t, lv) -> { - Value v = lv.get(0); + final Value v = lv.get(0); if (v instanceof StringValue) { - String str = v.getString().toLowerCase(Locale.ROOT); - if ("false".equals(str) || "null".equals(str)) return Value.FALSE; + final String str = v.getString().toLowerCase(Locale.ROOT); + if ("false".equals(str) || "null".equals(str)) + { + return Value.FALSE; + } } return BooleanValue.of(v.getBoolean()); }); expression.addUnaryFunction("number", v -> { - if (v instanceof NumericValue num) + if (v instanceof final NumericValue num) { - if (num.isInteger()) return new NumericValue(num.getLong()); - return new NumericValue(num.getDouble()); + return new NumericValue(num.isInteger() ? num.getLong() : num.getDouble()); } if (v instanceof ListValue || v instanceof MapValue) { @@ -64,7 +66,7 @@ public static void apply(Expression expression) { return new NumericValue(v.getString()); } - catch (NumberFormatException format) + catch (final NumberFormatException format) { return Value.NULL; } @@ -73,51 +75,65 @@ public static void apply(Expression expression) expression.addFunction("str", lv -> { if (lv.size() == 0) + { throw new InternalExpressionException("'str' requires at least one argument"); - String format = lv.get(0).getString(); + } + final String format = lv.get(0).getString(); if (lv.size() == 1) + { return new StringValue(format); + } int argIndex = 1; - if (lv.get(1) instanceof ListValue && lv.size() == 2) + if (lv.get(1) instanceof final ListValue list && lv.size() == 2) { - lv = ((ListValue) lv.get(1)).getItems(); + lv = list.getItems(); argIndex = 0; } - List args = new ArrayList<>(); - Matcher m = formatPattern.matcher(format); + final List args = new ArrayList<>(); + final Matcher m = formatPattern.matcher(format); - for (int i = 0, len = format.length(); i < len; ) { - if (m.find(i)) { + for (int i = 0, len = format.length(); i < len; ) + { + if (m.find(i)) + { // Anything between the start of the string and the beginning // of the format specifier is either fixed text or contains // an invalid format string. // [[scarpet]] but we skip it and let the String.format fail - char fmt = m.group(6).toLowerCase().charAt(0); + final char fmt = m.group(6).toLowerCase().charAt(0); if (fmt == 's') { if (argIndex >= lv.size()) - throw new InternalExpressionException("Not enough arguments for "+m.group(0)); + { + throw new InternalExpressionException("Not enough arguments for " + m.group(0)); + } args.add(lv.get(argIndex).getString()); argIndex++; } else if (fmt == 'd' || fmt == 'o' || fmt == 'x') { if (argIndex >= lv.size()) - throw new InternalExpressionException("Not enough arguments for "+m.group(0)); + { + throw new InternalExpressionException("Not enough arguments for " + m.group(0)); + } args.add(lv.get(argIndex).readInteger()); argIndex++; } else if (fmt == 'a' || fmt == 'e' || fmt == 'f' || fmt == 'g') { if (argIndex >= lv.size()) - throw new InternalExpressionException("Not enough arguments for "+m.group(0)); + { + throw new InternalExpressionException("Not enough arguments for " + m.group(0)); + } args.add(lv.get(argIndex).readDoubleNumber()); argIndex++; } else if (fmt == 'b') { if (argIndex >= lv.size()) - throw new InternalExpressionException("Not enough arguments for "+m.group(0)); + { + throw new InternalExpressionException("Not enough arguments for " + m.group(0)); + } args.add(lv.get(argIndex).getBoolean()); argIndex++; } @@ -127,11 +143,13 @@ else if (fmt == '%') } else { - throw new InternalExpressionException("Format not supported: "+m.group(6)); + throw new InternalExpressionException("Format not supported: " + m.group(6)); } i = m.end(); - } else { + } + else + { // No more valid format specifiers. Check for possible invalid // format specifiers. // [[scarpet]] but we skip it and let the String.format fail @@ -142,9 +160,9 @@ else if (fmt == '%') { return new StringValue(String.format(Locale.ROOT, format, args.toArray())); } - catch (IllegalFormatException ife) + catch (final IllegalFormatException ife) { - throw new InternalExpressionException("Illegal string format: "+ife.getMessage()); + throw new InternalExpressionException("Illegal string format: " + ife.getMessage()); } }); @@ -156,32 +174,40 @@ else if (fmt == '%') expression.addFunction("replace", (lv) -> { - if (lv.size() != 3 && lv.size() !=2) + if (lv.size() != 3 && lv.size() != 2) + { throw new InternalExpressionException("'replace' expects string to read, pattern regex, and optional replacement string"); - String data = lv.get(0).getString(); - String regex = lv.get(1).getString(); + } + final String data = lv.get(0).getString(); + final String regex = lv.get(1).getString(); String replacement = ""; if (lv.size() == 3) + { replacement = lv.get(2).getString(); + } try { return new StringValue(data.replaceAll(regex, replacement)); } - catch (PatternSyntaxException pse) + catch (final PatternSyntaxException pse) { - throw new InternalExpressionException("Incorrect pattern for 'replace': "+pse.getMessage()); + throw new InternalExpressionException("Incorrect pattern for 'replace': " + pse.getMessage()); } }); expression.addFunction("replace_first", (lv) -> { - if (lv.size() != 3 && lv.size() !=2) + if (lv.size() != 3 && lv.size() != 2) + { throw new InternalExpressionException("'replace_first' expects string to read, pattern regex, and optional replacement string"); - String data = lv.get(0).getString(); - String regex = lv.get(1).getString(); + } + final String data = lv.get(0).getString(); + final String regex = lv.get(1).getString(); String replacement = ""; if (lv.size() == 3) + { replacement = lv.get(2).getString(); + } return new StringValue(data.replaceFirst(regex, replacement)); }); @@ -189,31 +215,36 @@ else if (fmt == '%') expression.addUnaryFunction("length", v -> new NumericValue(v.length())); expression.addContextFunction("rand", -1, (c, t, lv) -> { - int argsize = lv.size(); + final int argsize = lv.size(); Random randomizer = Sys.randomizer; if (argsize != 1 && argsize != 2) + { throw new InternalExpressionException("'rand' takes one (range) or two arguments (range and seed)"); - if (argsize == 2) randomizer = c.host.getRandom(NumericValue.asNumber(lv.get(1)).getLong()); - Value argument = lv.get(0); - if (argument instanceof ListValue) + } + if (argsize == 2) { - List list = ((ListValue) argument).getItems(); + randomizer = c.host.getRandom(NumericValue.asNumber(lv.get(1)).getLong()); + } + final Value argument = lv.get(0); + if (argument instanceof final ListValue listValue) + { + final List list = listValue.getItems(); return list.get(randomizer.nextInt(list.size())); } - double value = NumericValue.asNumber(argument).getDouble()*randomizer.nextDouble(); - if (t == Context.BOOLEAN) - return BooleanValue.of(value >= 1.0D); - return new NumericValue(value); + final double value = NumericValue.asNumber(argument).getDouble() * randomizer.nextDouble(); + return t == Context.BOOLEAN ? BooleanValue.of(value >= 1.0D) : new NumericValue(value); }); expression.addContextFunction("reset_seed", 1, (c, t, lv) -> { - boolean gotIt = c.host.resetRandom(NumericValue.asNumber(lv.get(0)).getLong()); + final boolean gotIt = c.host.resetRandom(NumericValue.asNumber(lv.get(0)).getLong()); return BooleanValue.of(gotIt); }); expression.addFunction("perlin", lv -> { - PerlinNoiseSampler sampler; - Value x, y, z; + final PerlinNoiseSampler sampler; + final Value x; + Value y; + Value z; if (lv.size() >= 4) { @@ -227,36 +258,45 @@ else if (fmt == '%') sampler = PerlinNoiseSampler.instance; y = Value.NULL; z = Value.NULL; - if (lv.size() == 0 ) + if (lv.size() == 0) + { throw new InternalExpressionException("'perlin' requires at least one dimension to sample from"); + } x = NumericValue.asNumber(lv.get(0)); if (lv.size() > 1) { y = NumericValue.asNumber(lv.get(1)); if (lv.size() > 2) + { z = NumericValue.asNumber(lv.get(2)); + } } } - double result; + final double result; if (z.isNull()) - if (y.isNull()) - result = sampler.sample1d(NumericValue.asNumber(x).getDouble()); - else - result = sampler.sample2d(NumericValue.asNumber(x).getDouble(), NumericValue.asNumber(y).getDouble()); + { + result = y.isNull() + ? sampler.sample1d(NumericValue.asNumber(x).getDouble()) + : sampler.sample2d(NumericValue.asNumber(x).getDouble(), NumericValue.asNumber(y).getDouble()); + } else + { result = sampler.sample3d( NumericValue.asNumber(x).getDouble(), NumericValue.asNumber(y).getDouble(), NumericValue.asNumber(z).getDouble()); + } return new NumericValue(result); }); expression.addFunction("simplex", lv -> { - SimplexNoiseSampler sampler; - Value x, y, z; + final SimplexNoiseSampler sampler; + final Value x; + final Value y; + Value z; if (lv.size() >= 4) { @@ -269,22 +309,30 @@ else if (fmt == '%') { sampler = SimplexNoiseSampler.instance; z = Value.NULL; - if (lv.size() < 2 ) + if (lv.size() < 2) + { throw new InternalExpressionException("'simplex' requires at least two dimensions to sample from"); + } x = NumericValue.asNumber(lv.get(0)); y = NumericValue.asNumber(lv.get(1)); if (lv.size() > 2) + { z = NumericValue.asNumber(lv.get(2)); + } } - double result; + final double result; if (z.isNull()) + { result = sampler.sample2d(NumericValue.asNumber(x).getDouble(), NumericValue.asNumber(y).getDouble()); + } else + { result = sampler.sample3d( NumericValue.asNumber(x).getDouble(), NumericValue.asNumber(y).getDouble(), NumericValue.asNumber(z).getDouble()); + } return new NumericValue(result); }); @@ -303,17 +351,23 @@ else if (fmt == '%') expression.addFunction("convert_date", lv -> { int argsize = lv.size(); - if (lv.size() == 0) throw new InternalExpressionException("'convert_date' requires at least one parameter"); - Value value = lv.get(0); + if (lv.size() == 0) + { + throw new InternalExpressionException("'convert_date' requires at least one parameter"); + } + final Value value = lv.get(0); if (argsize == 1 && !(value instanceof ListValue)) { - Calendar cal = new GregorianCalendar(Locale.ROOT); + final Calendar cal = new GregorianCalendar(Locale.ROOT); cal.setTimeInMillis(NumericValue.asNumber(value, "timestamp").getLong()); - int weekday = cal.get(Calendar.DAY_OF_WEEK)-1; - if (weekday == 0) weekday = 7; + int weekday = cal.get(Calendar.DAY_OF_WEEK) - 1; + if (weekday == 0) + { + weekday = 7; + } return ListValue.ofNums( cal.get(Calendar.YEAR), - cal.get(Calendar.MONTH)+1, + cal.get(Calendar.MONTH) + 1, cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), @@ -323,18 +377,18 @@ else if (fmt == '%') cal.get(Calendar.WEEK_OF_YEAR) ); } - else if(value instanceof ListValue) + else if (value instanceof final ListValue list) { - lv = ((ListValue) value).getItems(); + lv = list.getItems(); argsize = lv.size(); } - Calendar cal = new GregorianCalendar(0, 0, 0, 0, 0, 0); + final Calendar cal = new GregorianCalendar(0, 0, 0, 0, 0, 0); if (argsize == 3) { cal.set( NumericValue.asNumber(lv.get(0)).getInt(), - NumericValue.asNumber(lv.get(1)).getInt()-1, + NumericValue.asNumber(lv.get(1)).getInt() - 1, NumericValue.asNumber(lv.get(2)).getInt() ); } @@ -342,29 +396,32 @@ else if (argsize == 6) { cal.set( NumericValue.asNumber(lv.get(0)).getInt(), - NumericValue.asNumber(lv.get(1)).getInt()-1, + NumericValue.asNumber(lv.get(1)).getInt() - 1, NumericValue.asNumber(lv.get(2)).getInt(), NumericValue.asNumber(lv.get(3)).getInt(), NumericValue.asNumber(lv.get(4)).getInt(), NumericValue.asNumber(lv.get(5)).getInt() ); } - else throw new InternalExpressionException("Date conversion requires 3 arguments for Dates or 6 arguments, for time"); + else + { + throw new InternalExpressionException("Date conversion requires 3 arguments for Dates or 6 arguments, for time"); + } return new NumericValue(cal.getTimeInMillis()); }); // lazy cause evaluates expression multiple times expression.addLazyFunction("profile_expr", 1, (c, t, lv) -> { - LazyValue lazy = lv.get(0); - long end = System.nanoTime()+50000000L; + final LazyValue lazy = lv.get(0); + final long end = System.nanoTime() + 50000000L; long it = 0; - while (System.nanoTime() res; }); @@ -373,16 +430,18 @@ else if (argsize == 6) expression.addContextFunction("undef", 1, (c, t, lv) -> { - Value remove = lv.get(0); + final Value remove = lv.get(0); if (remove instanceof FunctionValue) { c.host.delFunction(expression.module, remove.getString()); return Value.NULL; } String varname = remove.getString(); - boolean isPrefix = varname.endsWith("*"); + final boolean isPrefix = varname.endsWith("*"); if (isPrefix) + { varname = varname.replaceAll("\\*+$", ""); + } if (isPrefix) { c.host.delFunctionWithPrefix(expression.module, varname); @@ -413,8 +472,8 @@ else if (!varname.startsWith("_")) //deprecate expression.addContextFunction("vars", 1, (c, t, lv) -> { - String prefix = lv.get(0).getString(); - List values = new ArrayList<>(); + final String prefix = lv.get(0).getString(); + final List values = new ArrayList<>(); if (prefix.startsWith("global")) { c.host.globalVariableNames(expression.module, (s) -> s.startsWith(prefix)).forEach(s -> values.add(new StringValue(s))); @@ -429,19 +488,23 @@ else if (!varname.startsWith("_")) // lazy cause default expression may not be executed if not needed expression.addLazyFunction("system_variable_get", (c, t, lv) -> { - if (lv.size() == 0) throw new InternalExpressionException("'system_variable_get' expects at least a key to be fetched"); - Value key = lv.get(0).evalValue(c); - if (lv.size() > 1) c.host.scriptServer().systemGlobals.computeIfAbsent(key, k -> lv.get(1).evalValue(c)); - Value res = c.host.scriptServer().systemGlobals.get(key); - if (res!=null) return (cc, tt) -> res; - return LazyValue.NULL; + if (lv.size() == 0) + { + throw new InternalExpressionException("'system_variable_get' expects at least a key to be fetched"); + } + final Value key = lv.get(0).evalValue(c); + if (lv.size() > 1) + { + c.host.scriptServer().systemGlobals.computeIfAbsent(key, k -> lv.get(1).evalValue(c)); + } + final Value res = c.host.scriptServer().systemGlobals.get(key); + return res == null ? LazyValue.NULL : ((cc, tt) -> res); }); expression.addContextFunction("system_variable_set", 2, (c, t, lv) -> { - Value res = c.host.scriptServer().systemGlobals.put(lv.get(0), lv.get(1)); - if (res!=null) return res; - return Value.NULL; + final Value res = c.host.scriptServer().systemGlobals.put(lv.get(0), lv.get(1)); + return res == null ? Value.NULL : res; }); } } diff --git a/src/main/java/carpet/script/language/Threading.java b/src/main/java/carpet/script/language/Threading.java index 52f3c1a5c7..b61448d67b 100644 --- a/src/main/java/carpet/script/language/Threading.java +++ b/src/main/java/carpet/script/language/Threading.java @@ -11,14 +11,16 @@ public class Threading { - public static void apply(Expression expression) + public static void apply(final Expression expression) { expression.addFunctionWithDelegation("task", -1, false, false, (c, t, expr, tok, lv) -> { if (lv.size() == 0) + { throw new InternalExpressionException("'task' requires at least function to call as a parameter"); - FunctionArgument functionArgument = FunctionArgument.findIn(c, expression.module, lv, 0, false, true); - ThreadValue thread = new ThreadValue(Value.NULL, functionArgument.function, expr, tok, c, functionArgument.checkedArgs()); + } + final FunctionArgument functionArgument = FunctionArgument.findIn(c, expression.module, lv, 0, false, true); + final ThreadValue thread = new ThreadValue(Value.NULL, functionArgument.function, expr, tok, c, functionArgument.checkedArgs()); Thread.yield(); return thread; }); @@ -26,30 +28,36 @@ public static void apply(Expression expression) expression.addFunctionWithDelegation("task_thread", -1, false, false, (c, t, expr, tok, lv) -> { if (lv.size() < 2) + { throw new InternalExpressionException("'task' requires at least function to call as a parameter"); - Value queue = lv.get(0); - FunctionArgument functionArgument = FunctionArgument.findIn(c, expression.module, lv, 1, false, true); - ThreadValue thread = new ThreadValue(queue, functionArgument.function, expr, tok, c, functionArgument.checkedArgs()); + } + final Value queue = lv.get(0); + final FunctionArgument functionArgument = FunctionArgument.findIn(c, expression.module, lv, 1, false, true); + final ThreadValue thread = new ThreadValue(queue, functionArgument.function, expr, tok, c, functionArgument.checkedArgs()); Thread.yield(); return thread; }); expression.addContextFunction("task_count", -1, (c, t, lv) -> - (lv.size() > 0)? new NumericValue(c.host.taskCount(lv.get(0))):new NumericValue(c.host.taskCount())); + (lv.size() > 0) ? new NumericValue(c.host.taskCount(lv.get(0))) : new NumericValue(c.host.taskCount())); expression.addUnaryFunction("task_value", (v) -> { - if (!(v instanceof ThreadValue)) + if (!(v instanceof final ThreadValue tv)) + { throw new InternalExpressionException("'task_value' could only be used with a task value"); - return ((ThreadValue) v).getValue(); + } + return tv.getValue(); }); expression.addUnaryFunction("task_join", (v) -> { - if (!(v instanceof ThreadValue)) + if (!(v instanceof final ThreadValue tv)) + { throw new InternalExpressionException("'task_join' could only be used with a task value"); - return ((ThreadValue) v).join(); + } + return tv.join(); }); expression.addLazyFunction("task_dock", 1, (c, t, lv) -> @@ -61,15 +69,20 @@ public static void apply(Expression expression) expression.addUnaryFunction("task_completed", (v) -> { - if (!(v instanceof ThreadValue)) + if (!(v instanceof final ThreadValue tv)) + { throw new InternalExpressionException("'task_completed' could only be used with a task value"); - return BooleanValue.of(((ThreadValue) v).isFinished()); + } + return BooleanValue.of(tv.isFinished()); }); // lazy cause expr is evaluated in the same type expression.addLazyFunction("synchronize", (c, t, lv) -> { - if (lv.size() == 0) throw new InternalExpressionException("'synchronize' require at least an expression to synchronize"); + if (lv.size() == 0) + { + throw new InternalExpressionException("'synchronize' require at least an expression to synchronize"); + } Value lockValue = Value.NULL; int ind = 0; if (lv.size() == 2) @@ -79,7 +92,7 @@ public static void apply(Expression expression) } synchronized (c.host.getLock(lockValue)) { - Value ret = lv.get(ind).evalValue(c, t); + final Value ret = lv.get(ind).evalValue(c, t); return (_c, _t) -> ret; } }); @@ -87,15 +100,21 @@ public static void apply(Expression expression) // lazy since exception expression is very conditional expression.addLazyFunction("sleep", (c, t, lv) -> { - long time = lv.isEmpty()?0L:NumericValue.asNumber(lv.get(0).evalValue(c)).getLong(); + final long time = lv.isEmpty() ? 0L : NumericValue.asNumber(lv.get(0).evalValue(c)).getLong(); boolean interrupted = false; try { - if (Thread.interrupted()) interrupted = true; - if (time > 0) Thread.sleep(time); + if (Thread.interrupted()) + { + interrupted = true; + } + if (time > 0) + { + Thread.sleep(time); + } Thread.yield(); } - catch (InterruptedException ignored) + catch (final InterruptedException ignored) { interrupted = true; } diff --git a/src/main/java/carpet/script/utils/AppStoreManager.java b/src/main/java/carpet/script/utils/AppStoreManager.java index 2b410247fb..1f3314760f 100644 --- a/src/main/java/carpet/script/utils/AppStoreManager.java +++ b/src/main/java/carpet/script/utils/AppStoreManager.java @@ -18,6 +18,7 @@ import net.minecraft.commands.CommandRuntimeException; import net.minecraft.commands.CommandSourceStack; import net.minecraft.world.level.storage.LevelResource; + import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; @@ -40,22 +41,28 @@ */ public class AppStoreManager { - /** A local copy of the scarpet repo's file structure, to avoid multiple queries to github.com while typing out the + /** + * A local copy of the scarpet repo's file structure, to avoid multiple queries to github.com while typing out the * {@code /script download} command and getting the suggestions. */ private static StoreNode APP_STORE_ROOT = StoreNode.folder(null, ""); - /** This is the base link to the scarpet app repo from the github api. + /** + * This is the base link to the scarpet app repo from the github api. */ private static String scarpetRepoLink = "https://api.github.com/repos/gnembon/scarpet/contents/programs/"; - private static record AppInfo(String name, String url, StoreNode source) {} + private record AppInfo(String name, String url, StoreNode source) + { + } public static class ScarpetAppStoreValidator extends Validator { - @Override public String validate(CommandSourceStack source, CarpetRule currentRule, String newValue, String stringInput) + @Override + public String validate(final CommandSourceStack source, final CarpetRule currentRule, String newValue, final String stringInput) { - if (newValue.equals(currentRule.value())) { + if (newValue.equals(currentRule.value())) + { // Don't refresh the local repo if it's the same (world change), helps preventing hitting rate limits from github when // getting suggestions. Pending is a way to invalidate the cache when it gets old, and investigating api usage further return newValue; @@ -66,12 +73,19 @@ public static class ScarpetAppStoreValidator extends Validator scarpetRepoLink = null; return newValue; } - if (newValue.endsWith("/")) newValue = newValue.replaceAll("/$", ""); - scarpetRepoLink = "https://api.github.com/repos/"+newValue+"/"; + if (newValue.endsWith("/")) + { + newValue = newValue.replaceAll("/$", ""); + } + scarpetRepoLink = "https://api.github.com/repos/" + newValue + "/"; return newValue; } + @Override - public String description() { return "Appstore link should point to a valid github repository";} + public String description() + { + return "Appstore link should point to a valid github repository"; + } } public static class StoreNode @@ -81,18 +95,19 @@ public static class StoreNode public Map children; public boolean sealed; public String value; - public static StoreNode folder(StoreNode parent, String name) + + public static StoreNode folder(final StoreNode parent, final String name) { - StoreNode node = new StoreNode(parent, name); + final StoreNode node = new StoreNode(parent, name); node.children = new HashMap<>(); node.value = null; node.sealed = false; return node; } - public static StoreNode scriptFile(StoreNode parent, String name, String value) + public static StoreNode scriptFile(final StoreNode parent, final String name, final String value) { - StoreNode node = new StoreNode(parent, name); + final StoreNode node = new StoreNode(parent, name); node.children = null; node.value = value; node.sealed = true; @@ -103,19 +118,23 @@ public boolean isLeaf() { return value != null; } + public String pathElement() { - return name+(isLeaf()?"":"/"); + return name + (isLeaf() ? "" : "/"); } + public String getPath() { return createPrePath().toString(); } + private StringBuilder createPrePath() { return this == APP_STORE_ROOT ? new StringBuilder() : parent.createPrePath().append(pathElement()); } - private StoreNode(StoreNode parent, String name) + + private StoreNode(final StoreNode parent, final String name) { this.parent = parent; this.name = name; @@ -124,32 +143,38 @@ private StoreNode(StoreNode parent, String name) public synchronized void fillChildren() throws IOException { - if (sealed) return; - if (scarpetRepoLink == null) throw new IOException("Accessing scarpet app repo is disabled"); + if (sealed) + { + return; + } + if (scarpetRepoLink == null) + { + throw new IOException("Accessing scarpet app repo is disabled"); + } - String queryPath = scarpetRepoLink + getPath(); - String response; + final String queryPath = scarpetRepoLink + getPath(); + final String response; try { response = IOUtils.toString(new URL(queryPath), StandardCharsets.UTF_8); } - catch (IOException e) + catch (final IOException e) { // Not sealing to allow retrying throw new IOException("Problems fetching " + queryPath, e); } - JsonArray files = JsonParser.parseString(response).getAsJsonArray(); - for(JsonElement je : files) + final JsonArray files = JsonParser.parseString(response).getAsJsonArray(); + for (final JsonElement je : files) { - JsonObject jo = je.getAsJsonObject(); - String name = jo.get("name").getAsString(); + final JsonObject jo = je.getAsJsonObject(); + final String name = jo.get("name").getAsString(); if (jo.get("type").getAsString().equals("dir")) { children.put(name, folder(this, name)); } else// if (name.matches("(\\w+\\.scl?)")) { - String value = jo.get("download_url").getAsString(); + final String value = jo.get("download_url").getAsString(); children.put(name, scriptFile(this, name, value)); } } @@ -159,12 +184,16 @@ public synchronized void fillChildren() throws IOException /** * Returns true if doing down the directory structire cannot continue since the matching element is either a leaf or * a string not matching of any node. + * * @param pathElement * @return */ - public boolean cannotContinueFor(String pathElement) throws IOException + public boolean cannotContinueFor(final String pathElement) throws IOException { - if (isLeaf()) return true; + if (isLeaf()) + { + return true; + } fillChildren(); return !children.containsKey(pathElement); } @@ -173,120 +202,140 @@ public List createPathSuggestions() throws IOException { if (isLeaf()) { - if (name.endsWith(".sc")) - return Collections.singletonList(getPath()); - return Collections.emptyList(); + return name.endsWith(".sc") ? Collections.singletonList(getPath()) : Collections.emptyList(); } fillChildren(); - String prefix = getPath(); + final String prefix = getPath(); return children.values().stream(). filter(n -> (!n.isLeaf() || n.name.endsWith(".sc"))). - map(s -> prefix+s.pathElement().replaceAll("/$", "")). + map(s -> prefix + s.pathElement().replaceAll("/$", "")). collect(Collectors.toList()); } - public StoreNode drillDown(String pathElement) throws IOException + public StoreNode drillDown(final String pathElement) throws IOException { - if (isLeaf()) throw new IOException(pathElement+" is not a folder"); + if (isLeaf()) + { + throw new IOException(pathElement + " is not a folder"); + } fillChildren(); - if (!children.containsKey(pathElement)) throw new IOException("Folder "+pathElement+" is not present"); + if (!children.containsKey(pathElement)) + { + throw new IOException("Folder " + pathElement + " is not present"); + } return children.get(pathElement); } - public String getValue(String file) throws IOException + public String getValue(final String file) throws IOException { - StoreNode leaf = drillDown(file); - if (!leaf.isLeaf()) throw new IOException(file+" is not a file"); + final StoreNode leaf = drillDown(file); + if (!leaf.isLeaf()) + { + throw new IOException(file + " is not a file"); + } return leaf.value; } } - /** This method searches for valid file names from the user-inputted string, e.g if the user has thus far typed + /** + * This method searches for valid file names from the user-inputted string, e.g if the user has thus far typed * {@code survival/a} then it will return all the files in the {@code survival} directory of the scarpet repo (and * will automatically highlight those starting with a), and the string {@code survival/} as the current most valid path. * * @param currentPath The path down which we want to search for files * @return A pair of the current valid path, as well as the set of all the file/directory names at the end of that path */ - public static List suggestionsFromPath(String currentPath) throws IOException + public static List suggestionsFromPath(final String currentPath) throws IOException { - String[] path = currentPath.split("/"); + final String[] path = currentPath.split("/"); StoreNode appKiosk = APP_STORE_ROOT; - for(String pathElement : path) + for (final String pathElement : path) { - if (appKiosk.cannotContinueFor(pathElement)) break; + if (appKiosk.cannotContinueFor(pathElement)) + { + break; + } appKiosk = appKiosk.children.get(pathElement); } - List filteredSuggestions = appKiosk.createPathSuggestions().stream().filter(s -> s.startsWith(currentPath)).collect(Collectors.toList()); - if (filteredSuggestions.size() == 1) { + final List filteredSuggestions = appKiosk.createPathSuggestions().stream().filter(s -> s.startsWith(currentPath)).collect(Collectors.toList()); + if (filteredSuggestions.size() == 1) + { if (!appKiosk.isLeaf()) + { return suggestionsFromPath(filteredSuggestions.get(0)); // Start suggesting directory contents + } } return filteredSuggestions; } - - /** Downloads script and saves it to appropriate place. + /** + * Downloads script and saves it to appropriate place. * * @param path The user-inputted path to the script * @return {@code 1} if we succesfully saved the script, {@code 0} otherwise */ - public static int downloadScript(CommandSourceStack source, String path) + public static int downloadScript(final CommandSourceStack source, final String path) { - AppInfo nodeInfo = getFileNode(path); + final AppInfo nodeInfo = getFileNode(path); return downloadScript(source, path, nodeInfo, false); } - private static int downloadScript(CommandSourceStack source, String path, AppInfo nodeInfo, boolean useTrash) + private static int downloadScript(final CommandSourceStack source, final String path, final AppInfo nodeInfo, final boolean useTrash) { - String code; + final String code; try { code = IOUtils.toString(new URL(nodeInfo.url()), StandardCharsets.UTF_8); } - catch (IOException e) + catch (final IOException e) { - throw new CommandRuntimeException(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()); - return success?1:0; + if (!saveScriptToFile(source, path, nodeInfo.name(), code, false, useTrash)) + { + return 0; + } + final boolean success = CarpetServer.scriptServer.addScriptHost(source, nodeInfo.name().replaceFirst("\\.sc$", ""), null, true, false, false, nodeInfo.source()); + return success ? 1 : 0; } - /** Gets the code once the user inputs the command. + /** + * Gets the code once the user inputs the command. * * @param appPath The user inputted path to the scarpet script * @return Pair of app file name and content */ - public static AppInfo getFileNode(String appPath) + public static AppInfo getFileNode(final String appPath) { return getFileNodeFrom(APP_STORE_ROOT, appPath); } - public static AppInfo getFileNodeFrom(StoreNode start, String appPath) + public static AppInfo getFileNodeFrom(final StoreNode start, final String appPath) { - String[] path = appPath.split("/"); + final String[] path = appPath.split("/"); StoreNode appKiosk = start; try { - for(String pathElement : Arrays.copyOfRange(path, 0, path.length-1)) + for (final String pathElement : Arrays.copyOfRange(path, 0, path.length - 1)) + { appKiosk = appKiosk.drillDown(pathElement); - String appName = path[path.length-1]; + } + final String appName = path[path.length - 1]; appKiosk.getValue(appName); return new AppInfo(appName, appKiosk.getValue(appName), appKiosk); } - catch (IOException e) + catch (final IOException e) { - throw new CommandRuntimeException(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(CommandSourceStack source, String path, String appFileName, String code, boolean globalSavePath, boolean useTrash) + public static boolean saveScriptToFile(final CommandSourceStack source, final String path, final String appFileName, final String code, final boolean globalSavePath, final boolean useTrash) { - Path scriptLocation; + final Path scriptLocation; 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); @@ -307,29 +356,29 @@ public static boolean saveScriptToFile(CommandSourceStack source, String path, S int i = 0; while (Files.exists(trashPath)) { - String[] nameAndExtension = appFileName.split("\\."); - String newFileName = String.format(nameAndExtension[0] + "%02d." + nameAndExtension[1],i); + final String[] nameAndExtension = appFileName.split("\\."); + final String newFileName = String.format(nameAndExtension[0] + "%02d." + nameAndExtension[1], i); trashPath = trashPath.getParent().resolve(newFileName); i++; } Files.move(scriptLocation, trashPath); } - Messenger.m(source, String.format("gi Note: replaced existing app '%s'"+(useTrash ? " (old moved to /trash folder)" : ""), appFileName)); + Messenger.m(source, String.format("gi Note: replaced existing app '%s'" + (useTrash ? " (old moved to /trash folder)" : ""), appFileName)); } - BufferedWriter writer = Files.newBufferedWriter(scriptLocation); + final BufferedWriter writer = Files.newBufferedWriter(scriptLocation); writer.write(code); writer.close(); } - catch (IOException e) + catch (final IOException e) { - Messenger.m(source, "r Error while downloading app: " + e.toString()); + Messenger.m(source, "r Error while downloading app: " + e); CarpetScriptServer.LOG.warn("Error while downloading app", e); return false; } return true; } - public static void writeUrlToFile(String url, Path destination) throws IOException + public static void writeUrlToFile(final String url, final Path destination) throws IOException { try (final InputStream in = new URL(url).openStream()) { @@ -337,88 +386,112 @@ public static void writeUrlToFile(String url, Path destination) throws IOExcepti } } - private static String getFullContentUrl(String original, StoreNode storeSource) + private static String getFullContentUrl(final String original, final StoreNode storeSource) { if (original.matches("^https?://.*$")) // We've got a full url here: Just use it + { return original; + } if (original.charAt(0) == '/') // We've got an absolute path: Use app store root + { return getFileNode(original.substring(1)).url(); + } return getFileNodeFrom(storeSource, original).url(); // Relative path: Use download location } - public static void addResource(CarpetScriptHost carpetScriptHost, StoreNode storeSource, Value resource) + public static void addResource(final CarpetScriptHost carpetScriptHost, final StoreNode storeSource, final Value resource) { - if (!(resource instanceof MapValue)) - throw new InternalExpressionException("This is not a valid resource map: "+resource.getString()); - Map resourceMap = ((MapValue) resource).getMap().entrySet().stream().collect(Collectors.toMap(e -> e.getKey().getString(), Map.Entry::getValue)); - if (!resourceMap.containsKey("source")) throw new InternalExpressionException("Missing 'source' field in resource descriptor: "+resource.getString()); - String source = resourceMap.get("source").getString(); - String contentUrl = getFullContentUrl(source, storeSource); - String target = resourceMap.computeIfAbsent("target", k -> new StringValue(contentUrl.substring(contentUrl.lastIndexOf('/') + 1))).getString(); - boolean shared = resourceMap.getOrDefault("shared", Value.FALSE).getBoolean(); + if (!(resource instanceof final MapValue map)) + { + throw new InternalExpressionException("This is not a valid resource map: " + resource.getString()); + } + final Map resourceMap = map.getMap().entrySet().stream().collect(Collectors.toMap(e -> e.getKey().getString(), Map.Entry::getValue)); + if (!resourceMap.containsKey("source")) + { + throw new InternalExpressionException("Missing 'source' field in resource descriptor: " + resource.getString()); + } + final String source = resourceMap.get("source").getString(); + final String contentUrl = getFullContentUrl(source, storeSource); + final String target = resourceMap.computeIfAbsent("target", k -> new StringValue(contentUrl.substring(contentUrl.lastIndexOf('/') + 1))).getString(); + final boolean shared = resourceMap.getOrDefault("shared", Value.FALSE).getBoolean(); if (!carpetScriptHost.applyActionForResource(target, shared, p -> { - try { + try + { writeUrlToFile(contentUrl, p); - } catch (IOException e) { - throw new InternalExpressionException("Unable to write resource "+target+": "+e.toString()); + } + catch (final IOException e) + { + throw new InternalExpressionException("Unable to write resource " + target + ": " + e); } })) { - throw new InternalExpressionException("Unable to write resource "+target); + throw new InternalExpressionException("Unable to write resource " + target); } - CarpetScriptServer.LOG.info("Downloaded resource "+target+" from "+contentUrl); + CarpetScriptServer.LOG.info("Downloaded resource " + target + " from " + contentUrl); } /** * Gets a new StoreNode for an app's dependency with proper relativeness. Will be null if it comes from an external URL + * * @param originalSource The StoreNode from the container's app - * @param sourceString The string the app specified as source - * @param contentUrl The full content URL, from {@link #getFullContentUrl(String, StoreNode)} + * @param sourceString The string the app specified as source + * @param contentUrl The full content URL, from {@link #getFullContentUrl(String, StoreNode)} * @return A {@link StoreNode} that can be used in an app that came from the provided source */ - private static StoreNode getNewStoreNode(StoreNode originalSource, String sourceString, String contentUrl) + private static StoreNode getNewStoreNode(final StoreNode originalSource, String sourceString, final String contentUrl) { StoreNode next = originalSource; if (sourceString == contentUrl) // External URL (check getFullUrlContent) + { return null; + } if (sourceString.charAt(0) == '/') // Absolute URL { next = APP_STORE_ROOT; sourceString = sourceString.substring(1); } - String[] dirs = sourceString.split("/"); + final String[] dirs = sourceString.split("/"); try { for (int i = 0; i < dirs.length - 1; i++) + { next = next.drillDown(dirs[i]); + } } - catch (IOException e) + catch (final IOException e) { return null; // Should never happen, but let's not give a potentially incorrect node just in case } return next; } - public static void addLibrary(CarpetScriptHost carpetScriptHost, StoreNode storeSource, Value library) { - if (!(library instanceof MapValue)) - throw new InternalExpressionException("This is not a valid library map: "+library.getString()); - Map libraryMap = ((MapValue) library).getMap().entrySet().stream().collect(Collectors.toMap(e -> e.getKey().getString(), e -> e.getValue().getString())); - String source = libraryMap.get("source"); - String contentUrl = getFullContentUrl(source, storeSource); - String target = libraryMap.computeIfAbsent("target", k -> contentUrl.substring(contentUrl.lastIndexOf('/') + 1)); + public static void addLibrary(final CarpetScriptHost carpetScriptHost, final StoreNode storeSource, final Value library) + { + if (!(library instanceof final MapValue map)) + { + throw new InternalExpressionException("This is not a valid library map: " + library.getString()); + } + final Map libraryMap = map.getMap().entrySet().stream().collect(Collectors.toMap(e -> e.getKey().getString(), e -> e.getValue().getString())); + final String source = libraryMap.get("source"); + final String contentUrl = getFullContentUrl(source, storeSource); + final String target = libraryMap.computeIfAbsent("target", k -> contentUrl.substring(contentUrl.lastIndexOf('/') + 1)); if (!(contentUrl.endsWith(".sc") || contentUrl.endsWith(".scl"))) + { throw new InternalExpressionException("App resource type must download a scarpet app or library."); + } if (target.indexOf('/') != -1) + { throw new InternalExpressionException("App resource tried to leave script reserved space"); + } try { downloadScript(carpetScriptHost.responsibleSource, target, new AppInfo(target, contentUrl, getNewStoreNode(storeSource, source, contentUrl)), true); } - catch (CommandRuntimeException e) + catch (final CommandRuntimeException e) { - throw new InternalExpressionException("Error when installing app dependencies: " + e.toString()); + throw new InternalExpressionException("Error when installing app dependencies: " + e); } - CarpetScriptServer.LOG.info("Downloaded app "+target+" from "+contentUrl); + CarpetScriptServer.LOG.info("Downloaded app " + target + " from " + contentUrl); } } diff --git a/src/main/java/carpet/script/utils/BiomeInfo.java b/src/main/java/carpet/script/utils/BiomeInfo.java index f36054a1a6..5870848c02 100644 --- a/src/main/java/carpet/script/utils/BiomeInfo.java +++ b/src/main/java/carpet/script/utils/BiomeInfo.java @@ -6,6 +6,7 @@ import carpet.script.value.StringValue; import carpet.script.value.Value; import carpet.script.value.ValueConversions; + import java.util.HashMap; import java.util.Locale; import java.util.Map; @@ -20,12 +21,9 @@ public class BiomeInfo { - public final static Map> biomeFeatures = new HashMap>(){{ - //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(Biome.getBiomeCategory(Holder.direct(b)).getName())); + public static final Map> biomeFeatures = new HashMap<>() + {{ put("tags", (w, b) -> ListValue.wrap(w.registryAccess().registryOrThrow(Registries.BIOME).getTags().filter(p -> p.getSecond().stream().anyMatch(h -> h.value() == b)).map(p -> p.getFirst().location()).map(ValueConversions::of))); - 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 @@ -34,11 +32,8 @@ public class BiomeInfo put("water_fog_color", (w, b) -> ValueConversions.ofRGB(b.getSpecialEffects().getWaterFogColor())); put("humidity", (w, b) -> NumericValue.of(((BiomeInterface) (Object) b).getClimateSettings().downfall())); put("precipitation", (w, b) -> StringValue.of(b.getPrecipitationAt(new BlockPos(0, w.getSeaLevel(), 0)).name().toLowerCase(Locale.ROOT))); - //put("depth", (w, b) -> NumericValue.of(b.getDepth())); - //put("scale", (w, b) -> NumericValue.of(b.getScale())); put("features", (w, b) -> { - - Registry> registry = w.registryAccess().registryOrThrow(Registries.CONFIGURED_FEATURE); + final Registry> registry = w.registryAccess().registryOrThrow(Registries.CONFIGURED_FEATURE); return ListValue.wrap( b.getGenerationSettings().features().stream().map(step -> ListValue.wrap(step.stream().map(cfp -> @@ -47,9 +42,5 @@ public class BiomeInfo ) ); }); - //put("structures", (w, b) -> { - // Registry> registry = w.getRegistryManager().get(Registry.CONFIGURED_STRUCTURE_FEATURE_KEY); - // return ListValue.wrap(b.getGenerationSettings().getStructureFeatures().stream().map(str -> ValueConversions.of(registry.getId(str.get())))); - //}); }}; } diff --git a/src/main/java/carpet/script/utils/EquipmentInventory.java b/src/main/java/carpet/script/utils/EquipmentInventory.java index 0554362535..a4021a189f 100644 --- a/src/main/java/carpet/script/utils/EquipmentInventory.java +++ b/src/main/java/carpet/script/utils/EquipmentInventory.java @@ -2,6 +2,7 @@ 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; @@ -17,7 +18,8 @@ public class EquipmentInventory implements Container ); LivingEntity mob; - public EquipmentInventory(LivingEntity mob) + + public EquipmentInventory(final LivingEntity mob) { this.mob = mob; } @@ -31,20 +33,25 @@ public int getContainerSize() @Override public boolean isEmpty() { - for (EquipmentSlot slot: slotToSlot) - if (!mob.getItemBySlot(slot).isEmpty()) return false; + for (final EquipmentSlot slot : slotToSlot) + { + if (!mob.getItemBySlot(slot).isEmpty()) + { + return false; + } + } return true; } @Override - public ItemStack getItem(int slot) + public ItemStack getItem(final int slot) { - EquipmentSlot slotSlot; + final EquipmentSlot slotSlot; try { slotSlot = slotToSlot.get(slot); } - catch (IndexOutOfBoundsException ignored) + catch (final IndexOutOfBoundsException ignored) { //going out of the index should be really exceptional return ItemStack.EMPTY; @@ -53,14 +60,14 @@ public ItemStack getItem(int slot) } @Override - public ItemStack removeItem(int slot, int amount) + public ItemStack removeItem(final int slot, final int amount) { - EquipmentSlot slotSlot; + final EquipmentSlot slotSlot; try { slotSlot = slotToSlot.get(slot); } - catch (IndexOutOfBoundsException ignored) + catch (final IndexOutOfBoundsException ignored) { //going out of the index should be really exceptional return ItemStack.EMPTY; @@ -69,32 +76,32 @@ public ItemStack removeItem(int slot, int amount) } @Override - public ItemStack removeItemNoUpdate(int slot) + public ItemStack removeItemNoUpdate(final int slot) { - EquipmentSlot slotSlot; + final EquipmentSlot slotSlot; try { slotSlot = slotToSlot.get(slot); } - catch (IndexOutOfBoundsException ignored) + catch (final IndexOutOfBoundsException ignored) { //going out of the index should be really exceptional return ItemStack.EMPTY; } - ItemStack previous = mob.getItemBySlot(slotSlot); + final ItemStack previous = mob.getItemBySlot(slotSlot); mob.setItemSlot(slotSlot, ItemStack.EMPTY); return previous; } @Override - public void setItem(int slot, ItemStack stack) + public void setItem(final int slot, final ItemStack stack) { - EquipmentSlot slotSlot; + final EquipmentSlot slotSlot; try { slotSlot = slotToSlot.get(slot); } - catch (IndexOutOfBoundsException ignored) + catch (final IndexOutOfBoundsException ignored) { //going out of the index should be really exceptional return; @@ -109,7 +116,7 @@ public void setChanged() } @Override - public boolean stillValid(Player player) + public boolean stillValid(final Player player) { return false; } @@ -117,7 +124,9 @@ public boolean stillValid(Player player) @Override public void clearContent() { - for (EquipmentSlot slot: slotToSlot) + for (final EquipmentSlot slot : slotToSlot) + { mob.setItemSlot(slot, ItemStack.EMPTY); + } } } diff --git a/src/main/java/carpet/script/utils/GlocalFlag.java b/src/main/java/carpet/script/utils/GlocalFlag.java index 3a7a0c3033..52aa05c340 100644 --- a/src/main/java/carpet/script/utils/GlocalFlag.java +++ b/src/main/java/carpet/script/utils/GlocalFlag.java @@ -6,7 +6,7 @@ public class GlocalFlag extends ThreadLocal { private final boolean initial; - public GlocalFlag(boolean initial) + public GlocalFlag(final boolean initial) { this.initial = initial; } @@ -19,19 +19,20 @@ public Boolean initialValue() /** * Allows to thread-safely wrap a call while disabling a global flag and setting it back up right after. + * * @param action - callback to invoke when the wrapping is all setup - * @param - returned value of that action, whatever that might be + * @param - returned value of that action, whatever that might be * @return result of the action */ - public T getWhileDisabled(Supplier action) + public T getWhileDisabled(final Supplier action) { return whileValueReturn(!initial, action); } - private T whileValueReturn(boolean what, Supplier action) + private T whileValueReturn(final boolean what, final Supplier action) { T result; - boolean previous; + final boolean previous; synchronized (this) { previous = get(); @@ -48,11 +49,14 @@ private T whileValueReturn(boolean what, Supplier action) return result; } - public T runIfEnabled(Supplier action) + public T runIfEnabled(final Supplier action) { synchronized (this) { - if (get() != initial) return null; + if (get() != initial) + { + return null; + } set(!initial); } T result; diff --git a/src/main/java/carpet/script/utils/InputValidator.java b/src/main/java/carpet/script/utils/InputValidator.java index 520b9e5dd3..2f71b30f82 100644 --- a/src/main/java/carpet/script/utils/InputValidator.java +++ b/src/main/java/carpet/script/utils/InputValidator.java @@ -3,27 +3,31 @@ import carpet.script.exception.InternalExpressionException; import java.util.Locale; + import net.minecraft.ResourceLocationException; import net.minecraft.resources.ResourceLocation; -public class InputValidator { - public static String validateSimpleString(String input, boolean strict) +public class InputValidator +{ + public static String validateSimpleString(final String input, final boolean strict) { - String simplified = input.toLowerCase(Locale.ROOT).replaceAll("[^A-Za-z0-9+_]", ""); + final String simplified = input.toLowerCase(Locale.ROOT).replaceAll("[^A-Za-z0-9+_]", ""); if (simplified.isEmpty() || (strict && !simplified.equals(input))) + { throw new InternalExpressionException("simple name can only contain numbers, letter and _"); + } return simplified; } - public static ResourceLocation identifierOf(String string) + public static ResourceLocation identifierOf(final String string) { try { return new ResourceLocation(string); } - catch (ResourceLocationException iie) + catch (final ResourceLocationException iie) { - throw new InternalExpressionException("Incorrect identifier format '"+string+"': "+iie.getMessage()); + throw new InternalExpressionException("Incorrect identifier format '" + string + "': " + iie.getMessage()); } } diff --git a/src/main/java/carpet/script/utils/PerlinNoiseSampler.java b/src/main/java/carpet/script/utils/PerlinNoiseSampler.java index c57973d9c9..4fdb3f1a82 100644 --- a/src/main/java/carpet/script/utils/PerlinNoiseSampler.java +++ b/src/main/java/carpet/script/utils/PerlinNoiseSampler.java @@ -6,7 +6,8 @@ import java.util.Random; // extracted from import net.minecraft.util.math.noise.PerlinNoiseSampler -public class PerlinNoiseSampler { +public class PerlinNoiseSampler +{ protected static final int[][] gradients3d = new int[][]{ {1, 1, 0}, {-1, 1, 0}, {1, -1, 0}, {-1, -1, 0}, {1, 0, 1}, {-1, 0, 1}, {1, 0, -1}, {-1, 0, -1}, @@ -23,49 +24,50 @@ public class PerlinNoiseSampler { public static PerlinNoiseSampler instance = new PerlinNoiseSampler(new Random(0)); public static Map samplers = new Long2ObjectOpenHashMap<>(); - public static PerlinNoiseSampler getPerlin(long aLong) + public static PerlinNoiseSampler getPerlin(final long aLong) { if (samplers.size() > 256) + { samplers.clear(); + } return samplers.computeIfAbsent(aLong, seed -> new PerlinNoiseSampler(new Random(seed))); } - public PerlinNoiseSampler(Random random) { + public PerlinNoiseSampler(final Random random) + { this.originX = random.nextDouble() * 256.0D; this.originY = random.nextDouble() * 256.0D; this.originZ = random.nextDouble() * 256.0D; this.permutations = new byte[256]; int j; - for(j = 0; j < 256; ++j) { - this.permutations[j] = (byte)j; + for (j = 0; j < 256; ++j) + { + this.permutations[j] = (byte) j; } - - for(j = 0; j < 256; ++j) { - int k = random.nextInt(256 - j); - byte b = this.permutations[j]; + for (j = 0; j < 256; ++j) + { + final int k = random.nextInt(256 - j); + final byte b = this.permutations[j]; this.permutations[j] = this.permutations[j + k]; this.permutations[j + k] = b; } - } - - - //3D - public double sample3d(double x, double y, double z) {//, double d, double e) { - double f = x + this.originX; - double g = y + this.originY; - double h = z + this.originZ; - int i = floor(f); - int j = floor(g); - int k = floor(h); - double l = f - (double)i; - double m = g - (double)j; - double n = h - (double)k; - double o = perlinFade(l); - double p = perlinFade(m); - double q = perlinFade(n); + public double sample3d(final double x, final double y, final double z) + {//, double d, double e) { + final double f = x + this.originX; + final double g = y + this.originY; + final double h = z + this.originZ; + final int i = floor(f); + final int j = floor(g); + final int k = floor(h); + final double l = f - (double) i; + final double m = g - (double) j; + final double n = h - (double) k; + final double o = perlinFade(l); + final double p = perlinFade(m); + final double q = perlinFade(n); //double t; /* if (d != 0.0D) { @@ -75,110 +77,127 @@ public double sample3d(double x, double y, double z) {//, double d, double e) { t = 0.0D; }*/ //return this.sample(i, j, k, l, m - t, n, o, p, q); - return this.sample3d(i, j, k, l, m, n, o, p, q)/2+0.5; - } - - private double sample3d(int sectionX, int sectionY, int sectionZ, double localX, double localY, double localZ, double fadeLocalX, double fadeLocalY, double fadeLocalZ) { - int i = this.getGradient(sectionX) + sectionY; - int j = this.getGradient(i) + sectionZ; - int k = this.getGradient(i + 1) + sectionZ; - int l = this.getGradient(sectionX + 1) + sectionY; - int m = this.getGradient(l) + sectionZ; - int n = this.getGradient(l + 1) + sectionZ; - double d = grad3d(this.getGradient(j), localX, localY, localZ); - double e = grad3d(this.getGradient(m), localX - 1.0D, localY, localZ); - double f = grad3d(this.getGradient(k), localX, localY - 1.0D, localZ); - double g = grad3d(this.getGradient(n), localX - 1.0D, localY - 1.0D, localZ); - double h = grad3d(this.getGradient(j + 1), localX, localY, localZ - 1.0D); - double o = grad3d(this.getGradient(m + 1), localX - 1.0D, localY, localZ - 1.0D); - double p = grad3d(this.getGradient(k + 1), localX, localY - 1.0D, localZ - 1.0D); - double q = grad3d(this.getGradient(n + 1), localX - 1.0D, localY - 1.0D, localZ - 1.0D); + return this.sample3d(i, j, k, l, m, n, o, p, q) / 2 + 0.5; + } + + private double sample3d(final int sectionX, final int sectionY, final int sectionZ, final double localX, final double localY, final double localZ, final double fadeLocalX, final double fadeLocalY, final double fadeLocalZ) + { + final int i = this.getGradient(sectionX) + sectionY; + final int j = this.getGradient(i) + sectionZ; + final int k = this.getGradient(i + 1) + sectionZ; + final int l = this.getGradient(sectionX + 1) + sectionY; + final int m = this.getGradient(l) + sectionZ; + final int n = this.getGradient(l + 1) + sectionZ; + final double d = grad3d(this.getGradient(j), localX, localY, localZ); + final double e = grad3d(this.getGradient(m), localX - 1.0D, localY, localZ); + final double f = grad3d(this.getGradient(k), localX, localY - 1.0D, localZ); + final double g = grad3d(this.getGradient(n), localX - 1.0D, localY - 1.0D, localZ); + final double h = grad3d(this.getGradient(j + 1), localX, localY, localZ - 1.0D); + final double o = grad3d(this.getGradient(m + 1), localX - 1.0D, localY, localZ - 1.0D); + final double p = grad3d(this.getGradient(k + 1), localX, localY - 1.0D, localZ - 1.0D); + final double q = grad3d(this.getGradient(n + 1), localX - 1.0D, localY - 1.0D, localZ - 1.0D); return lerp3(fadeLocalX, fadeLocalY, fadeLocalZ, d, e, f, g, h, o, p, q); } - private static double grad3d(int hash, double x, double y, double z) { - int i = hash & 15; + private static double grad3d(final int hash, final double x, final double y, final double z) + { + final int i = hash & 15; return dot3d(gradients3d[i], x, y, z); } - protected static double dot3d(int[] gArr, double x, double y, double z) { - return (double)gArr[0] * x + (double)gArr[1] * y + (double)gArr[2] * z; + protected static double dot3d(final int[] gArr, final double x, final double y, final double z) + { + return gArr[0] * x + gArr[1] * y + gArr[2] * z; } - public static double lerp3(double deltaX, double deltaY, double deltaZ, double d, double e, double f, double g, double h, double i, double j, double k) { + public static double lerp3(final double deltaX, final double deltaY, final double deltaZ, final double d, final double e, final double f, final double g, final double h, final double i, final double j, final double k) + { return lerp(deltaZ, lerp2(deltaX, deltaY, d, e, f, g), lerp2(deltaX, deltaY, h, i, j, k)); } //2D - public double sample2d(double x, double y) {//, double d, double e) { - double f = x + this.originX; - double g = y + this.originY; - int i = floor(f); - int j = floor(g); - double l = f - (double)i; - double m = g - (double)j; - double o = perlinFade(l); - double p = perlinFade(m); - return this.sample2d(i, j, l, m, o, p)/2+0.5; - } - - private double sample2d(int sectionX, int sectionY, double localX, double localY, double fadeLocalX, double fadeLocalY) { - int j = this.getGradient(sectionX) + sectionY; - int m = this.getGradient(sectionX + 1) + sectionY; - double d = grad2d(this.getGradient(j), localX, localY); - double e = grad2d(this.getGradient(m), localX - 1.0D, localY); - double f = grad2d(this.getGradient(j+1), localX, localY - 1.0D); - double g = grad2d(this.getGradient(m+1), localX - 1.0D, localY - 1.0D); + public double sample2d(final double x, final double y) + { + final double f = x + this.originX; + final double g = y + this.originY; + final int i = floor(f); + final int j = floor(g); + final double l = f - (double) i; + final double m = g - (double) j; + final double o = perlinFade(l); + final double p = perlinFade(m); + return this.sample2d(i, j, l, m, o, p) / 2 + 0.5; + } + + private double sample2d(final int sectionX, final int sectionY, final double localX, final double localY, final double fadeLocalX, final double fadeLocalY) + { + final int j = this.getGradient(sectionX) + sectionY; + final int m = this.getGradient(sectionX + 1) + sectionY; + final double d = grad2d(this.getGradient(j), localX, localY); + final double e = grad2d(this.getGradient(m), localX - 1.0D, localY); + final double f = grad2d(this.getGradient(j + 1), localX, localY - 1.0D); + final double g = grad2d(this.getGradient(m + 1), localX - 1.0D, localY - 1.0D); return lerp2(fadeLocalX, fadeLocalY, d, e, f, g); } - private static double grad2d(int hash, double x, double y) { - int i = hash & 3; + private static double grad2d(final int hash, final double x, final double y) + { + final int i = hash & 3; return dot2d(gradients2d[i], x, y); } - protected static double dot2d(int[] gArr, double x, double y) { - return (double)gArr[0] * x + (double)gArr[1] * y; + protected static double dot2d(final int[] gArr, final double x, final double y) + { + return gArr[0] * x + gArr[1] * y; } - public static double lerp2(double deltaX, double deltaY, double d, double e, double f, double g) { + public static double lerp2(final double deltaX, final double deltaY, final double d, final double e, final double f, final double g) + { return lerp(deltaY, lerp(deltaX, d, e), lerp(deltaX, f, g)); } // 1D - public double sample1d(double x) {//, double d, double e) { - double f = x + this.originX; - int i = floor(f); - double l = f - (double)i; - double o = perlinFade(l); - return this.sample1d(i, l, o)+0.5; - } - private double sample1d(int sectionX, double localX, double fadeLocalX) { - double d = grad1d(this.getGradient(sectionX), localX); - double e = grad1d(this.getGradient(sectionX+1), localX - 1.0D); + public double sample1d(final double x) + { + final double f = x + this.originX; + final int i = floor(f); + final double l = f - i; + final double o = perlinFade(l); + return this.sample1d(i, l, o) + 0.5; + } + + private double sample1d(final int sectionX, final double localX, final double fadeLocalX) + { + final double d = grad1d(this.getGradient(sectionX), localX); + final double e = grad1d(this.getGradient(sectionX + 1), localX - 1.0D); return lerp(fadeLocalX, d, e); } - private static double grad1d(int hash, double x) { - return ((hash & 1) == 0)? x:-x; + private static double grad1d(final int hash, final double x) + { + return ((hash & 1) == 0) ? x : -x; } - public static double lerp(double delta, double first, double second) { + public static double lerp(final double delta, final double first, final double second) + { return first + delta * (second - first); } // shared - public int getGradient(int hash) { + public int getGradient(final int hash) + { return this.permutations[hash & 255] & 255; } - public static double perlinFade(double d) { + public static double perlinFade(final double d) + { return d * d * d * (d * (d * 6.0D - 15.0D) + 10.0D); } - public static int floor(double d) { - int i = (int)d; - return d < (double)i ? i - 1 : i; + public static int floor(final double d) + { + final int i = (int) d; + return d < i ? i - 1 : i; } } \ No newline at end of file diff --git a/src/main/java/carpet/script/utils/ScarpetJsonDeserializer.java b/src/main/java/carpet/script/utils/ScarpetJsonDeserializer.java index 9b13ddc5c2..c6af60039e 100644 --- a/src/main/java/carpet/script/utils/ScarpetJsonDeserializer.java +++ b/src/main/java/carpet/script/utils/ScarpetJsonDeserializer.java @@ -20,15 +20,17 @@ import carpet.script.value.StringValue; import carpet.script.value.Value; -public class ScarpetJsonDeserializer implements JsonDeserializer{ +public class ScarpetJsonDeserializer implements JsonDeserializer +{ @Override - public Value deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) - throws JsonParseException { + public Value deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException + { return parseElement(json); } - - private Value parseElement(JsonElement element) throws JsonParseException { + + private Value parseElement(final JsonElement element) throws JsonParseException + { if (element.isJsonObject()) { return parseMap(element.getAsJsonObject()); @@ -44,23 +46,22 @@ else if (element.isJsonPrimitive()) return Value.NULL; } - private Value parseMap(JsonObject jsonMap) throws JsonParseException { - Map map = new HashMap(); - jsonMap.entrySet().forEach(entry -> { - map.put(new StringValue(entry.getKey()), parseElement(entry.getValue())); - }); + private Value parseMap(final JsonObject jsonMap) throws JsonParseException + { + final Map map = new HashMap<>(); + jsonMap.entrySet().forEach(entry -> map.put(new StringValue(entry.getKey()), parseElement(entry.getValue()))); return MapValue.wrap(map); } - private Value parseList(JsonArray jsonList) throws JsonParseException { - List list = new ArrayList(); - jsonList.forEach(elem -> { - list.add(parseElement(elem)); - }); + private Value parseList(final JsonArray jsonList) throws JsonParseException + { + final List list = new ArrayList<>(); + jsonList.forEach(elem -> list.add(parseElement(elem))); return new ListValue(list); } - - private Value parsePrimitive(JsonPrimitive primitive) throws JsonParseException { + + private Value parsePrimitive(final JsonPrimitive primitive) throws JsonParseException + { if (primitive.isString()) { return new StringValue(primitive.getAsString()); diff --git a/src/main/java/carpet/script/utils/ShapeDispatcher.java b/src/main/java/carpet/script/utils/ShapeDispatcher.java index 787c24a651..7bf3ffa0fd 100644 --- a/src/main/java/carpet/script/utils/ShapeDispatcher.java +++ b/src/main/java/carpet/script/utils/ShapeDispatcher.java @@ -52,6 +52,7 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.Vec3; + import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -70,36 +71,47 @@ public class ShapeDispatcher { - public static record ShapeWithConfig(ExpiringShape shape, Map config) {} + public record ShapeWithConfig(ExpiringShape shape, Map config) + { + } public static ShapeWithConfig fromFunctionArgs( - MinecraftServer server, ServerLevel world, - List lv, - Set playerSet + final MinecraftServer server, final ServerLevel world, + final List lv, + final Set playerSet ) { - if (lv.size() < 3) throw new InternalExpressionException("'draw_shape' takes at least three parameters, shape name, duration, and its params"); - String shapeType = lv.get(0).getString(); - Value duration = NumericValue.asNumber(lv.get(1), "duration"); - Map params; + if (lv.size() < 3) + { + throw new InternalExpressionException("'draw_shape' takes at least three parameters, shape name, duration, and its params"); + } + final String shapeType = lv.get(0).getString(); + final Value duration = NumericValue.asNumber(lv.get(1), "duration"); + final Map params; if (lv.size() == 3) { - Value paramValue = lv.get(2); - if (paramValue instanceof MapValue) + final Value paramValue = lv.get(2); + if (paramValue instanceof final MapValue map) { params = new HashMap<>(); - ((MapValue) paramValue).getMap().entrySet().forEach(e -> params.put(e.getKey().getString(),e.getValue())); + map.getMap().entrySet().forEach(e -> params.put(e.getKey().getString(), e.getValue())); + } + else if (paramValue instanceof final ListValue list) + { + params = parseParams(list.getItems()); } - else if (paramValue instanceof ListValue) + else { - params = parseParams(((ListValue) paramValue).getItems()); + throw new InternalExpressionException("Parameters for 'draw_shape' need to be defined either in a list or a map"); } - else throw new InternalExpressionException("Parameters for 'draw_shape' need to be defined either in a list or a map"); } else { - List paramList = new ArrayList<>(); - for (int i=2; i < lv.size(); i++) paramList.add(lv.get(i)); + final List paramList = new ArrayList<>(); + for (int i = 2; i < lv.size(); i++) + { + paramList.add(lv.get(i)); + } params = ShapeDispatcher.parseParams(paramList); } params.putIfAbsent("dim", new StringValue(world.dimension().location().toString())); @@ -107,17 +119,23 @@ else if (paramValue instanceof ListValue) if (params.containsKey("player")) { - Value players = params.get("player"); - List playerVals; - if (players instanceof ListValue) - playerVals = ((ListValue) players).getItems(); + final Value players = params.get("player"); + final List playerVals; + if (players instanceof final ListValue list) + { + playerVals = list.getItems(); + } else + { playerVals = Collections.singletonList(players); - for (Value pVal : playerVals) + } + for (final Value pVal : playerVals) { - ServerPlayer player = EntityValue.getPlayerByValue(server, pVal); + final ServerPlayer player = EntityValue.getPlayerByValue(server, pVal); if (player == null) - throw new InternalExpressionException("'player' parameter needs to represent an existing player, not "+pVal.getString()); + { + throw new InternalExpressionException("'player' parameter needs to represent an existing player, not " + pVal.getString()); + } playerSet.add(player); } params.remove("player"); @@ -125,121 +143,125 @@ else if (paramValue instanceof ListValue) return new ShapeWithConfig(ShapeDispatcher.create(server, shapeType, params), params); } - public static void sendShape(Collection players, List shapes) + public static void sendShape(final Collection players, final List shapes) { - List clientPlayers = new ArrayList<>(); - List alternativePlayers = new ArrayList<>(); - for (ServerPlayer player : players) + final List clientPlayers = new ArrayList<>(); + final List alternativePlayers = new ArrayList<>(); + for (final ServerPlayer player : players) { - if (ServerNetworkHandler.isValidCarpetPlayer(player)) - { - clientPlayers.add(player); - } - else - { - alternativePlayers.add(player); - } + (ServerNetworkHandler.isValidCarpetPlayer(player) ? clientPlayers : alternativePlayers).add(player); } if (!clientPlayers.isEmpty()) { - ListTag tag = new ListTag(); int tagcount = 0; - for (ShapeWithConfig s : shapes) + for (final ShapeWithConfig s : shapes) { tag.add(ExpiringShape.toTag(s.config())); // 4000 shapes limit boxes - if (tagcount++>1000) + if (tagcount++ > 1000) { tagcount = 0; - Tag finalTag = tag; - clientPlayers.forEach( p -> ServerNetworkHandler.sendCustomCommand(p, "scShapes", finalTag)); + final Tag finalTag = tag; + clientPlayers.forEach(p -> ServerNetworkHandler.sendCustomCommand(p, "scShapes", finalTag)); tag = new ListTag(); } } - Tag finalTag = tag; - if (tag.size() > 0) clientPlayers.forEach( p -> ServerNetworkHandler.sendCustomCommand(p, "scShapes", finalTag)); + final Tag finalTag = tag; + if (!tag.isEmpty()) + { + clientPlayers.forEach(p -> ServerNetworkHandler.sendCustomCommand(p, "scShapes", finalTag)); + } } if (!alternativePlayers.isEmpty()) { - List> alternatives = new ArrayList<>(); + final List> alternatives = new ArrayList<>(); shapes.forEach(s -> alternatives.add(s.shape().alternative())); - alternativePlayers.forEach(p -> alternatives.forEach( a -> a.accept(p))); + alternativePlayers.forEach(p -> alternatives.forEach(a -> a.accept(p))); } } - public static ParticleOptions getParticleData(String name, RegistryAccess regs) + public static ParticleOptions getParticleData(final String name, final RegistryAccess regs) { try { return ParticleDisplay.getEffect(name, regs.lookupOrThrow(Registries.PARTICLE_TYPE)); } - catch (IllegalArgumentException e) + catch (final IllegalArgumentException e) { throw new ThrowStatement(name, Throwables.UNKNOWN_PARTICLE); } } - public static Map parseParams(List items) + public static Map parseParams(final List items) { // parses params from API function - if (items.size()%2 == 1) throw new InternalExpressionException("Shape parameters list needs to be of even size"); - Map param = new HashMap<>(); + if (items.size() % 2 == 1) + { + throw new InternalExpressionException("Shape parameters list needs to be of even size"); + } + final Map param = new HashMap<>(); int i = 0; - while(i < items.size()) + while (i < items.size()) { - String name = items.get(i).getString(); - Value val = items.get(i+1); + final String name = items.get(i).getString(); + final Value val = items.get(i + 1); param.put(name, val); i += 2; } return param; } - public static ExpiringShape create(MinecraftServer server, String shapeType, Map userParams) + public static ExpiringShape create(final MinecraftServer server, final String shapeType, final Map userParams) { userParams.put("shape", new StringValue(shapeType)); userParams.keySet().forEach(key -> { - Param param = Param.of.get(key); - if (param==null) throw new InternalExpressionException("Unknown feature for shape: "+key); + final Param param = Param.of.get(key); + if (param == null) + { + throw new InternalExpressionException("Unknown feature for shape: " + key); + } userParams.put(key, param.validate(userParams, server, userParams.get(key))); }); - BiFunction, RegistryAccess, ExpiringShape> factory = ExpiringShape.shapeProviders.get(shapeType); - if (factory == null) throw new InternalExpressionException("Unknown shape: "+shapeType); + final BiFunction, RegistryAccess, ExpiringShape> factory = ExpiringShape.shapeProviders.get(shapeType); + if (factory == null) + { + throw new InternalExpressionException("Unknown shape: " + shapeType); + } return factory.apply(userParams, server.registryAccess()); } // client - public static ExpiringShape fromTag(CompoundTag tag, Level level) + public static ExpiringShape fromTag(final CompoundTag tag, final Level level) { - Map options = new HashMap<>(); - for (String key : tag.getAllKeys()) + final Map options = new HashMap<>(); + for (final String key : tag.getAllKeys()) { - Param decoder = Param.of.get(key); - if (decoder==null) + final Param decoder = Param.of.get(key); + if (decoder == null) { - CarpetSettings.LOG.info("Unknown parameter for shape: "+key); + CarpetSettings.LOG.info("Unknown parameter for shape: " + key); return null; } - Value decodedValue = decoder.decode(tag.get(key), level); + final Value decodedValue = decoder.decode(tag.get(key), level); options.put(key, decodedValue); } - Value shapeValue = options.get("shape"); + final Value shapeValue = options.get("shape"); if (shapeValue == null) { - CarpetSettings.LOG.info("Shape id missing in "+ String.join(", ", tag.getAllKeys())); + CarpetSettings.LOG.info("Shape id missing in " + String.join(", ", tag.getAllKeys())); return null; } - BiFunction, RegistryAccess, ExpiringShape> factory = ExpiringShape.shapeProviders.get(shapeValue.getString()); + final BiFunction, RegistryAccess, ExpiringShape> factory = ExpiringShape.shapeProviders.get(shapeValue.getString()); if (factory == null) { - CarpetSettings.LOG.info("Unknown shape: "+shapeValue.getString()); + CarpetSettings.LOG.info("Unknown shape: " + shapeValue.getString()); return null; } try { return factory.apply(options, level.registryAccess()); } - catch (InternalExpressionException exc) + catch (final InternalExpressionException exc) { CarpetSettings.LOG.info(exc.getMessage()); } @@ -248,20 +270,22 @@ public static ExpiringShape fromTag(CompoundTag tag, Level level) public abstract static class ExpiringShape { - public static final Map, RegistryAccess, ExpiringShape>> shapeProviders = new HashMap<>(){{ + public static final Map, RegistryAccess, ExpiringShape>> shapeProviders = new HashMap<>() + {{ put("line", creator(Line::new)); put("box", creator(Box::new)); put("sphere", creator(Sphere::new)); put("cylinder", creator(Cylinder::new)); put("label", creator(DisplayedText::new)); - put("polygon",creator(Polyface::new)); - put("block",creator(()->new DisplayedSprite(false))); - put("item",creator(()->new DisplayedSprite(true))); + put("polygon", creator(Polyface::new)); + put("block", creator(() -> new DisplayedSprite(false))); + put("item", creator(() -> new DisplayedSprite(true))); }}; - private static BiFunction, RegistryAccess, ExpiringShape> creator(Supplier shapeFactory) + + private static BiFunction, RegistryAccess, ExpiringShape> creator(final Supplier shapeFactory) { return (o, regs) -> { - ExpiringShape shape = shapeFactory.get(); + final ExpiringShape shape = shapeFactory.get(); shape.fromOptions(o, regs); return shape; }; @@ -282,37 +306,47 @@ private static BiFunction, RegistryAccess, ExpiringShape> cre protected boolean debug; - protected ExpiringShape() { } + protected ExpiringShape() + { + } - public static CompoundTag toTag(Map params) + public static CompoundTag toTag(final Map params) { - CompoundTag tag = new CompoundTag(); + final CompoundTag tag = new CompoundTag(); params.forEach((k, v) -> { - Tag valTag = Param.of.get(k).toTag(v); - if (valTag != null) tag.put(k, valTag); + final Tag valTag = Param.of.get(k).toTag(v); + if (valTag != null) + { + tag.put(k, valTag); + } }); return tag; } - private void fromOptions(Map options, RegistryAccess regs) + private void fromOptions(final Map options, final RegistryAccess regs) { - Set optional = optionalParams(); - Set required = requiredParams(); - Set all = Sets.union(optional, required); + final Set optional = optionalParams(); + final Set required = requiredParams(); + final Set all = Sets.union(optional, required); if (!all.containsAll(options.keySet())) - throw new InternalExpressionException("Received unexpected parameters for shape: "+Sets.difference(options.keySet(), all)); + { + throw new InternalExpressionException("Received unexpected parameters for shape: " + Sets.difference(options.keySet(), all)); + } if (!options.keySet().containsAll(required)) - throw new InternalExpressionException("Missing required parameters for shape: "+Sets.difference(required, options.keySet())); - options.keySet().forEach(k ->{ + { + throw new InternalExpressionException("Missing required parameters for shape: " + Sets.difference(required, options.keySet())); + } + options.keySet().forEach(k -> { if (!this.canTake(k)) - throw new InternalExpressionException("Parameter "+k+" doesn't apply for shape "+options.get("shape").getString()); + { + throw new InternalExpressionException("Parameter " + k + " doesn't apply for shape " + options.get("shape").getString()); + } }); init(options, regs); } - - protected void init(Map options, RegistryAccess regs) + protected void init(final Map options, final RegistryAccess regs) { duration = NumericValue.asNumber(options.get("duration")).getInt(); @@ -320,19 +354,20 @@ protected void init(Map options, RegistryAccess regs) lineWidth = NumericValue.asNumber(options.getOrDefault("line", optional.get("line"))).getFloat(); fillColor = NumericValue.asNumber(options.getOrDefault("fill", optional.get("fill"))).getInt(); - this.fr = (float)(fillColor >> 24 & 0xFF) / 255.0F; - this.fg = (float)(fillColor >> 16 & 0xFF) / 255.0F; - this.fb = (float)(fillColor >> 8 & 0xFF) / 255.0F; - this.fa = (float)(fillColor & 0xFF) / 255.0F; + this.fr = (fillColor >> 24 & 0xFF) / 255.0F; + this.fg = (fillColor >> 16 & 0xFF) / 255.0F; + this.fb = (fillColor >> 8 & 0xFF) / 255.0F; + this.fa = (fillColor & 0xFF) / 255.0F; color = NumericValue.asNumber(options.getOrDefault("color", optional.get("color"))).getInt(); - this.r = (float)(color >> 24 & 0xFF) / 255.0F; - this.g = (float)(color >> 16 & 0xFF) / 255.0F; - this.b = (float)(color >> 8 & 0xFF) / 255.0F; - this.a = (float)(color & 0xFF) / 255.0F; + this.r = (color >> 24 & 0xFF) / 255.0F; + this.g = (color >> 16 & 0xFF) / 255.0F; + this.b = (color >> 8 & 0xFF) / 255.0F; + this.a = (color & 0xFF) / 255.0F; debug = false; - if (options.containsKey("debug")) { + if (options.containsKey("debug")) + { debug = options.get("debug").getBoolean(); } @@ -351,68 +386,101 @@ protected void init(Map options, RegistryAccess regs) discreteZ = snapTo.contains("dz"); } } - public int getExpiry() { return duration; } - public Vec3 toAbsolute(Entity e, Vec3 vec, float partialTick) + + public int getExpiry() + { + return duration; + } + + public Vec3 toAbsolute(final Entity e, final Vec3 vec, final float partialTick) { return vec.add( - 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 + 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 Vec3 relativiseRender(Level world, Vec3 vec, float partialTick) + + public Vec3 relativiseRender(final Level world, final Vec3 vec, final float partialTick) { - if (followEntity < 0) return vec; - Entity e = world.getEntity(followEntity); - if (e == null) return vec; + if (followEntity < 0) + { + return vec; + } + final Entity e = world.getEntity(followEntity); + if (e == null) + { + return vec; + } return toAbsolute(e, vec, partialTick); } - public Vec3 vecFromValue(Value value) + public Vec3 vecFromValue(final Value value) { - if (!(value instanceof ListValue)) throw new InternalExpressionException("decoded value of "+value.getPrettyString()+" is not a triple"); - List elements = ((ListValue) value).getItems(); + if (!(value instanceof final ListValue list)) + { + throw new InternalExpressionException("decoded value of " + value.getPrettyString() + " is not a triple"); + } + final List elements = list.getItems(); return new Vec3( - NumericValue.asNumber( elements.get(0)).getDouble(), - NumericValue.asNumber( elements.get(1)).getDouble(), - NumericValue.asNumber( elements.get(2)).getDouble() + NumericValue.asNumber(elements.get(0)).getDouble(), + NumericValue.asNumber(elements.get(1)).getDouble(), + NumericValue.asNumber(elements.get(2)).getDouble() ); } - protected ParticleOptions replacementParticle(RegistryAccess regs) + + protected ParticleOptions replacementParticle(final RegistryAccess regs) { - String particleName = fa ==0 ? - String.format(Locale.ROOT , "dust %.1f %.1f %.1f 1.0", r, g, b): - String.format(Locale.ROOT , "dust %.1f %.1f %.1f 1.0", fr, fg, fb); + final String particleName = fa == 0 ? + String.format(Locale.ROOT, "dust %.1f %.1f %.1f 1.0", r, g, b) : + String.format(Locale.ROOT, "dust %.1f %.1f %.1f 1.0", fr, fg, fb); return getParticleData(particleName, regs); } public abstract Consumer alternative(); + public long key(final RegistryAccess regs) { - if (key!=0) return key; + if (key != 0) + { + return key; + } key = calcKey(regs); return key; } + protected long calcKey(final RegistryAccess regs) { // using FNV-1a algorithm long hash = -3750763034362895579L; - hash ^= shapeDimension.hashCode(); hash *= 1099511628211L; - hash ^= color; hash *= 1099511628211L; - hash ^= followEntity; hash *= 1099511628211L; - hash ^= Boolean.hashCode(debug); hash *= 1099511628211L; + hash ^= shapeDimension.hashCode(); + hash *= 1099511628211L; + hash ^= color; + hash *= 1099511628211L; + hash ^= followEntity; + hash *= 1099511628211L; + hash ^= Boolean.hashCode(debug); + hash *= 1099511628211L; if (followEntity >= 0) { - hash ^= snapTo.hashCode(); hash *= 1099511628211L; + hash ^= snapTo.hashCode(); + hash *= 1099511628211L; + } + hash ^= Float.hashCode(lineWidth); + hash *= 1099511628211L; + if (fa != 0.0) + { + hash = 31 * hash + fillColor; + hash *= 1099511628211L; } - hash ^= Float.hashCode(lineWidth); hash *= 1099511628211L; - if (fa != 0.0) { hash = 31*hash + fillColor; hash *= 1099511628211L; } return hash; } + 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(Vec3 vec) + + int vec3dhash(final Vec3 vec) { return vec.add(xdif, ydif, zdif).hashCode(); } @@ -427,11 +495,19 @@ int vec3dhash(Vec3 vec) "fill", new NumericValue(0xffffff00), "snap", new StringValue("xyz") ); - protected Set requiredParams() {return required;} + + protected Set requiredParams() + { + return required; + } + // list of params that can be there, with defaults - protected Set optionalParams() {return optional.keySet();} + protected Set optionalParams() + { + return optional.keySet(); + } - private boolean canTake(String param) + private boolean canTake(final String param) { return requiredParams().contains(param) || optionalParams().contains(param); } @@ -452,11 +528,22 @@ public static class DisplayedText extends ExpiringShape entry("size", new NumericValue(10)), entry("value", Value.NULL), entry("doublesided", new NumericValue(0))); + @Override - protected Set requiredParams() { return Sets.union(super.requiredParams(), required); } + protected Set requiredParams() + { + return Sets.union(super.requiredParams(), required); + } + @Override - protected Set optionalParams() { return Sets.union(super.optionalParams(), optional.keySet()); } - public DisplayedText() { } + protected Set optionalParams() + { + return Sets.union(super.optionalParams(), optional.keySet()); + } + + public DisplayedText() + { + } Vec3 pos; String text; @@ -476,28 +563,32 @@ public DisplayedText() { } boolean doublesided; @Override - protected void init(Map options, RegistryAccess regs) + protected void init(final Map options, final RegistryAccess regs) { super.init(options, regs); pos = vecFromValue(options.get("pos")); - value = ((FormattedTextValue)options.get("text")).getText(); + value = ((FormattedTextValue) options.get("text")).getText(); text = value.getString(); if (options.containsKey("value")) { - value = ((FormattedTextValue)options.get("value")).getText(); + value = ((FormattedTextValue) options.get("value")).getText(); } textcolor = rgba2argb(color); textbck = rgba2argb(fillColor); - String dir = options.getOrDefault("facing", optional.get("facing")).getString(); + final String dir = options.getOrDefault("facing", optional.get("facing")).getString(); facing = ShapeDirection.fromString(dir); align = 0; if (options.containsKey("align")) { - String alignStr = options.get("align").getString(); + final String alignStr = options.get("align").getString(); if ("right".equalsIgnoreCase(alignStr)) + { align = 1; + } else if ("left".equalsIgnoreCase(alignStr)) + { align = -1; + } } doublesided = false; if (options.containsKey("doublesided")) @@ -515,63 +606,86 @@ else if ("left".equalsIgnoreCase(alignStr)) size = NumericValue.asNumber(options.getOrDefault("size", optional.get("size"))).getFloat(); } - private int rgba2argb(int color) + private int rgba2argb(final int color) { - int r = Math.max(1, color >> 24 & 0xFF); - int g = Math.max(1, color >> 16 & 0xFF); - int b = Math.max(1, color >> 8 & 0xFF); - int a = color & 0xFF; + final int r = Math.max(1, color >> 24 & 0xFF); + final int g = Math.max(1, color >> 16 & 0xFF); + final int b = Math.max(1, color >> 8 & 0xFF); + final int a = color & 0xFF; return (a << 24) + (r << 16) + (g << 8) + b; } - @Override public Consumer alternative() { - return s -> {}; + return s -> { + }; } @Override public long calcKey(final RegistryAccess regs) { long hash = super.calcKey(regs); - hash ^= 5; hash *= 1099511628211L; - hash ^= vec3dhash(pos); hash *= 1099511628211L; - hash ^= text.hashCode(); hash *= 1099511628211L; - if (facing!= null) hash ^= facing.hashCode(); hash *= 1099511628211L; - hash ^= Float.hashCode(raise); hash *= 1099511628211L; - hash ^= Float.hashCode(tilt); hash *= 1099511628211L; - hash ^= Float.hashCode(lean); hash *= 1099511628211L; - hash ^= Float.hashCode(turn); hash *= 1099511628211L; - hash ^= Float.hashCode(indent); hash *= 1099511628211L; - hash ^= Float.hashCode(height); hash *= 1099511628211L; - hash ^= Float.hashCode(size); hash *= 1099511628211L; - hash ^= Integer.hashCode(align); hash *= 1099511628211L; - hash ^= Boolean.hashCode(doublesided); hash *= 1099511628211L; + hash ^= 5; + hash *= 1099511628211L; + hash ^= vec3dhash(pos); + hash *= 1099511628211L; + hash ^= text.hashCode(); + hash *= 1099511628211L; + if (facing != null) + { + hash ^= facing.hashCode(); + } + hash *= 1099511628211L; + hash ^= Float.hashCode(raise); + hash *= 1099511628211L; + hash ^= Float.hashCode(tilt); + hash *= 1099511628211L; + hash ^= Float.hashCode(lean); + hash *= 1099511628211L; + hash ^= Float.hashCode(turn); + hash *= 1099511628211L; + hash ^= Float.hashCode(indent); + hash *= 1099511628211L; + hash ^= Float.hashCode(height); + hash *= 1099511628211L; + hash ^= Float.hashCode(size); + hash *= 1099511628211L; + hash ^= Integer.hashCode(align); + hash *= 1099511628211L; + hash ^= Boolean.hashCode(doublesided); + hash *= 1099511628211L; return hash; } } - public static class DisplayedSprite extends ExpiringShape { + public static class DisplayedSprite extends ExpiringShape + { private final Set required = Set.of("pos"); private final Map optional = Map.ofEntries( entry("facing", new StringValue("north")), entry("tilt", new NumericValue(0)), entry("lean", new NumericValue(0)), entry("turn", new NumericValue(0)), - entry("scale", ListValue.fromTriple(1,1,1)), + entry("scale", ListValue.fromTriple(1, 1, 1)), entry("blocklight", new NumericValue(-1)), entry("skylight", new NumericValue(-1))); - private boolean isitem; + private final boolean isitem; @Override - protected Set requiredParams() { return Sets.union(Sets.union(super.requiredParams(), required), Set.of(isitem ? "item" : "block"));} + protected Set requiredParams() + { + return Sets.union(Sets.union(super.requiredParams(), required), Set.of(isitem ? "item" : "block")); + } @Override - protected Set optionalParams() { return Sets.union(Sets.union(super.optionalParams(), optional.keySet()),isitem ? Set.of("variant") : Set.of()); } + protected Set optionalParams() + { + return Sets.union(Sets.union(super.optionalParams(), optional.keySet()), isitem ? Set.of("variant") : Set.of()); + } - public DisplayedSprite(boolean i) + public DisplayedSprite(final boolean i) { isitem = i; } @@ -596,13 +710,13 @@ public DisplayedSprite(boolean i) String itemTransformType; @Override - protected void init(Map options, RegistryAccess regs) + protected void init(final Map options, final RegistryAccess regs) { super.init(options, regs); pos = vecFromValue(options.get("pos")); if (!this.isitem) { - final BlockValue block = (BlockValue)options.get("block"); + final BlockValue block = (BlockValue) options.get("block"); blockState = block.getBlockState(); blockEntity = block.getData(); } @@ -611,9 +725,15 @@ protected void init(Map options, RegistryAccess regs) this.item = ItemStack.of(((NBTSerializableValue) options.get("item")).getCompoundTag()); } blockLight = NumericValue.asNumber(options.getOrDefault("blocklight", optional.get("blocklight"))).getInt(); - if (blockLight > 15) blockLight = 15; + if (blockLight > 15) + { + blockLight = 15; + } skyLight = NumericValue.asNumber(options.getOrDefault("skylight", optional.get("skylight"))).getInt(); - if (skyLight > 15) skyLight = 15; + if (skyLight > 15) + { + skyLight = 15; + } itemTransformType = "none"; if (options.containsKey("variant")) @@ -621,26 +741,30 @@ protected void init(Map options, RegistryAccess regs) itemTransformType = options.get("variant").getString().toLowerCase(Locale.ROOT); } - String dir = options.getOrDefault("facing", optional.get("facing")).getString(); + final String dir = options.getOrDefault("facing", optional.get("facing")).getString(); facing = ShapeDirection.fromString(dir); tilt = NumericValue.asNumber(options.getOrDefault("tilt", optional.get("tilt"))).getFloat(); lean = NumericValue.asNumber(options.getOrDefault("lean", optional.get("lean"))).getFloat(); turn = NumericValue.asNumber(options.getOrDefault("turn", optional.get("turn"))).getFloat(); - List scale = ((ListValue) options.getOrDefault("scale", optional.get("scale"))).unpack(); + final List scale = ((ListValue) options.getOrDefault("scale", optional.get("scale"))).unpack(); scaleY = NumericValue.asNumber(scale.get(1)).getFloat(); scaleX = NumericValue.asNumber(scale.get(0)).getFloat(); scaleZ = NumericValue.asNumber(scale.get(2)).getFloat(); } @Override - public Consumer alternative() { + public Consumer alternative() + { return p -> { - ParticleOptions particle; + final ParticleOptions particle; final Registry blocks = p.getServer().registryAccess().registryOrThrow(Registries.BLOCK); - if(this.isitem) + if (this.isitem) { - if (Block.byItem(this.item.getItem()).defaultBlockState().isAir()) return; + if (Block.byItem(this.item.getItem()).defaultBlockState().isAir()) + { + return; + } particle = getParticleData("block_marker " + blocks.getKey(Block.byItem(this.item.getItem())), p.level.registryAccess()); } else @@ -648,30 +772,56 @@ public Consumer alternative() { particle = getParticleData("block_marker " + blocks.getKey(this.blockState.getBlock()), p.level.registryAccess()); } - Vec3 v = relativiseRender(p.level, this.pos, 0); - p.getLevel().sendParticles(p, particle , true, v.x, v.y, v.z, 1,0.0, 0.0, 0.0, 0.0); + final Vec3 v = relativiseRender(p.level, this.pos, 0); + p.getLevel().sendParticles(p, particle, true, v.x, v.y, v.z, 1, 0.0, 0.0, 0.0, 0.0); }; } @Override - public long calcKey(final RegistryAccess regs) { + public long calcKey(final RegistryAccess regs) + { long hash = super.calcKey(regs); - hash ^= 7; hash *= 1099511628211L; - hash ^= Boolean.hashCode(isitem); hash *= 1099511628211L; - hash ^= vec3dhash(pos); hash *= 1099511628211L; - if (facing!= null) hash ^= facing.hashCode(); hash *= 1099511628211L; - hash ^= Float.hashCode(tilt); hash *= 1099511628211L; - hash ^= Float.hashCode(lean); hash *= 1099511628211L; - hash ^= Float.hashCode(turn); hash *= 1099511628211L; - hash ^= Float.hashCode(scaleY); hash *= 1099511628211L; - hash ^= Float.hashCode(scaleZ); hash *= 1099511628211L; - hash ^= Float.hashCode(scaleX); hash *= 1099511628211L; - hash ^= Float.hashCode(skyLight); hash *= 1099511628211L; - hash ^= Float.hashCode(blockLight); hash *= 1099511628211L; - if (blockEntity!= null) hash ^= blockEntity.toString().hashCode(); hash *= 1099511628211L; - if (blockState!= null) hash ^= blockState.hashCode(); hash *= 1099511628211L; - hash ^= ValueConversions.of(item, regs).getString().hashCode(); hash *= 1099511628211L; - hash ^= itemTransformType.hashCode(); hash *= 1099511628211L; + hash ^= 7; + hash *= 1099511628211L; + hash ^= Boolean.hashCode(isitem); + hash *= 1099511628211L; + hash ^= vec3dhash(pos); + hash *= 1099511628211L; + if (facing != null) + { + hash ^= facing.hashCode(); + } + hash *= 1099511628211L; + hash ^= Float.hashCode(tilt); + hash *= 1099511628211L; + hash ^= Float.hashCode(lean); + hash *= 1099511628211L; + hash ^= Float.hashCode(turn); + hash *= 1099511628211L; + hash ^= Float.hashCode(scaleY); + hash *= 1099511628211L; + hash ^= Float.hashCode(scaleZ); + hash *= 1099511628211L; + hash ^= Float.hashCode(scaleX); + hash *= 1099511628211L; + hash ^= Float.hashCode(skyLight); + hash *= 1099511628211L; + hash ^= Float.hashCode(blockLight); + hash *= 1099511628211L; + if (blockEntity != null) + { + hash ^= blockEntity.toString().hashCode(); + } + hash *= 1099511628211L; + if (blockState != null) + { + hash ^= blockState.hashCode(); + } + hash *= 1099511628211L; + hash ^= ValueConversions.of(item, regs).getString().hashCode(); + hash *= 1099511628211L; + hash ^= itemTransformType.hashCode(); + hash *= 1099511628211L; return hash; } @@ -682,17 +832,28 @@ public static class Box extends ExpiringShape { private final Set required = Set.of("from", "to"); private final Map optional = Map.of(); + @Override - protected Set requiredParams() { return Sets.union(super.requiredParams(), required); } + protected Set requiredParams() + { + return Sets.union(super.requiredParams(), required); + } + @Override - protected Set optionalParams() { return Sets.union(super.optionalParams(), optional.keySet()); } - public Box() { } + protected Set optionalParams() + { + return Sets.union(super.optionalParams(), optional.keySet()); + } + + public Box() + { + } Vec3 from; Vec3 to; @Override - protected void init(Map options, RegistryAccess regs) + protected void init(final Map options, final RegistryAccess regs) { super.init(options, regs); from = vecFromValue(options.get("from")); @@ -702,7 +863,7 @@ protected void init(Map options, RegistryAccess regs) @Override public Consumer alternative() { - double density = Math.max(2.0, from.distanceTo(to) /50/ (a+0.1)) ; + final double density = Math.max(2.0, from.distanceTo(to) / 50 / (a + 0.1)); return p -> { if (p.level.dimension() == shapeDimension) @@ -722,215 +883,285 @@ public Consumer alternative() public long calcKey(final RegistryAccess regs) { long hash = super.calcKey(regs); - hash ^= 1; hash *= 1099511628211L; - hash ^= vec3dhash(from); hash *= 1099511628211L; - hash ^= vec3dhash(to); hash *= 1099511628211L; + hash ^= 1; + hash *= 1099511628211L; + hash ^= vec3dhash(from); + hash *= 1099511628211L; + hash ^= vec3dhash(to); + hash *= 1099511628211L; return hash; } - public static int particleMesh(List playerList, ParticleOptions particle, double density, - Vec3 from, Vec3 to) + public static int particleMesh(final List playerList, final ParticleOptions particle, final double density, + final Vec3 from, final Vec3 to) { - double x1 = from.x; - double y1 = from.y; - double z1 = from.z; - double x2 = to.x; - double y2 = to.y; - double z2 = to.z; + final double x1 = from.x; + final double y1 = from.y; + final double z1 = from.z; + final double x2 = to.x; + final double y2 = to.y; + final double z2 = to.z; return - 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 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 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 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 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); + 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); } } public static class Polyface extends ExpiringShape { @Override - public long calcKey(final RegistryAccess regs){ + public long calcKey(final RegistryAccess regs) + { long hash = super.calcKey(regs); - hash ^= 6; hash *= 1099511628211L; - hash ^= mode; hash *= 1099511628211L; - hash ^= relative.hashCode(); hash *= 1099511628211L; - for (Vec3 i :vertex_list){ + hash ^= 6; + hash *= 1099511628211L; + hash ^= mode; + hash *= 1099511628211L; + hash ^= relative.hashCode(); + hash *= 1099511628211L; + for (final Vec3 i : vertex_list) + { hash ^= vec3dhash(i); hash *= 1099511628211L; } - hash ^= Boolean.hashCode(doublesided); hash *= 1099511628211L; - hash ^= Integer.hashCode(vertex_list.size()); hash *= 1099511628211L; - hash ^= Boolean.hashCode(inneredges); hash *= 1099511628211L; + hash ^= Boolean.hashCode(doublesided); + hash *= 1099511628211L; + hash ^= Integer.hashCode(vertex_list.size()); + hash *= 1099511628211L; + hash ^= Boolean.hashCode(inneredges); + hash *= 1099511628211L; return hash; } - ArrayList alter_point=null; - final Random random=new Random(); + + ArrayList alter_point = null; + final Random random = new Random(); boolean doublesided; - ArrayList alter_point(ServerPlayer p){ - if (alter_point!=null){ + ArrayList alter_point(final ServerPlayer p) + { + if (alter_point != null) + { return alter_point; } - alter_point=new ArrayList<>(); - switch (mode) { + alter_point = new ArrayList<>(); + switch (mode) + { case 4: - for (int i=0;i alternative() { - return p->{ - if(p.level.dimension() != this.shapeDimension){return;} - if(!(fa>0.0f)){return;} - final ParticleOptions locparticledata = getParticleData(String.format(Locale.ROOT ,"dust %.1f %.1f %.1f %.1f", fr, fg, fb, fa), p.level.registryAccess()); - for(Vec3 v : alter_point(p)){ - p.getLevel().sendParticles(p,locparticledata , true, - v.x, v.y, v.z, 1, - 0.0, 0.0, 0.0, 0.0); + public Consumer alternative() + { + return p -> { + if (p.level.dimension() != this.shapeDimension) + { + return; + } + if (!(fa > 0.0f)) + { + return; + } + final ParticleOptions locparticledata = getParticleData(String.format(Locale.ROOT, "dust %.1f %.1f %.1f %.1f", fr, fg, fb, fa), p.level.registryAccess()); + for (final Vec3 v : alter_point(p)) + { + p.getLevel().sendParticles(p, locparticledata, true, + v.x, v.y, v.z, 1, + 0.0, 0.0, 0.0, 0.0); } }; } + private final Set required = Set.of("points"); private final Map optional = Map.ofEntries( - entry("relative",Value.NULL), - entry("mode", new StringValue("polygon")), - entry("inner", Value.TRUE), - entry("doublesided", Value.TRUE) + entry("relative", Value.NULL), + entry("mode", new StringValue("polygon")), + entry("inner", Value.TRUE), + entry("doublesided", Value.TRUE) ); + @Override - protected Set requiredParams() { return Sets.union(super.requiredParams(), required); } + protected Set requiredParams() + { + return Sets.union(super.requiredParams(), required); + } + @Override - protected Set optionalParams() { return Sets.union(super.optionalParams(), optional.keySet()); } - ArrayList vertex_list=new ArrayList<>(); + protected Set optionalParams() + { + return Sets.union(super.optionalParams(), optional.keySet()); + } + + ArrayList vertex_list = new ArrayList<>(); int mode; - ArrayList relative=new ArrayList<>(); + ArrayList relative = new ArrayList<>(); boolean inneredges; + @Override - protected void init(Map options, RegistryAccess regs) + protected void init(final Map options, final RegistryAccess regs) { super.init(options, regs); - doublesided=options.getOrDefault("doublesided",optional.get("doublesided")).getBoolean(); - - if (options.get("points") instanceof AbstractListValue abl){ - abl.forEach(x->vertex_list.add(vecFromValue(x))); + doublesided = options.getOrDefault("doublesided", optional.get("doublesided")).getBoolean(); + + if (options.get("points") instanceof final AbstractListValue abl) + { + abl.forEach(x -> vertex_list.add(vecFromValue(x))); } - String _mode = options.getOrDefault("mode",optional.get("mode")).getString(); - inneredges = options.getOrDefault("inner",optional.get("inner")).getBoolean(); - if(vertex_list.size()<3){ + final String _mode = options.getOrDefault("mode", optional.get("mode")).getString(); + inneredges = options.getOrDefault("inner", optional.get("inner")).getBoolean(); + if (vertex_list.size() < 3) + { throw new IllegalArgumentException("Unexpected vertex list size: " + vertex_list.size()); - }else if(vertex_list.size()<4){ - inneredges=false; - } - if("polygon".equals(_mode)){ - mode=6; - }else if("strip".equals(_mode)){ - mode=5; - }else if("triangles".equals(_mode)){ - mode=4; - if(vertex_list.size()%3!=0){ + } + else if (vertex_list.size() < 4) + { + inneredges = false; + } + if ("polygon".equals(_mode)) + { + mode = 6; + } + else if ("strip".equals(_mode)) + { + mode = 5; + } + else if ("triangles".equals(_mode)) + { + mode = 4; + if (vertex_list.size() % 3 != 0) + { throw new IllegalArgumentException("Unexpected vertex list size: " + vertex_list.size()); } } - if (options.getOrDefault("relative",optional.get("relative")) instanceof AbstractListValue abl){ - Iterator it = abl.iterator(); - for(long i=0L;i it = abl.iterator(); + for (long i = 0L; i < vertex_list.size(); i++) + { + relative.add(it.hasNext() && it.next().getBoolean());//if part of it got defined. } } - else if(options.getOrDefault("relative",optional.get("relative")) instanceof BooleanValue boolv){ - for(long i=0L;i required = Set.of("from", "to"); private final Map optional = Map.of(); + @Override - protected Set requiredParams() { return Sets.union(super.requiredParams(), required); } + protected Set requiredParams() + { + return Sets.union(super.requiredParams(), required); + } + @Override - protected Set optionalParams() { return Sets.union(super.optionalParams(), optional.keySet()); } + protected Set optionalParams() + { + return Sets.union(super.optionalParams(), optional.keySet()); + } private Line() { @@ -952,7 +1191,7 @@ private Line() Vec3 to; @Override - protected void init(Map options, RegistryAccess regs) + protected void init(final Map options, final RegistryAccess regs) { super.init(options, regs); from = vecFromValue(options.get("from")); @@ -962,16 +1201,19 @@ protected void init(Map options, RegistryAccess regs) @Override public Consumer alternative() { - double density = Math.max(2.0, from.distanceTo(to) /50) / (a+0.1); + final double density = Math.max(2.0, from.distanceTo(to) / 50) / (a + 0.1); return p -> { - if (p.level.dimension() == shapeDimension) drawParticleLine( - Collections.singletonList(p), - replacementParticle(p.level.registryAccess()), - relativiseRender(p.level, from, 0), - relativiseRender(p.level, to, 0), - density - ); + if (p.level.dimension() == shapeDimension) + { + drawParticleLine( + Collections.singletonList(p), + replacementParticle(p.level.registryAccess()), + relativiseRender(p.level, from, 0), + relativiseRender(p.level, to, 0), + density + ); + } }; } @@ -979,9 +1221,12 @@ public Consumer alternative() public long calcKey(final RegistryAccess regs) { long hash = super.calcKey(regs); - hash ^= 2; hash *= 1099511628211L; - hash ^= vec3dhash(from); hash *= 1099511628211L; - hash ^= vec3dhash(to); hash *= 1099511628211L; + hash ^= 2; + hash *= 1099511628211L; + hash ^= vec3dhash(from); + hash *= 1099511628211L; + hash ^= vec3dhash(to); + hash *= 1099511628211L; return hash; } } @@ -990,10 +1235,18 @@ public static class Sphere extends ExpiringShape { private final Set required = Set.of("center", "radius"); private final Map optional = Map.of("level", Value.ZERO); + @Override - protected Set requiredParams() { return Sets.union(super.requiredParams(), required); } + protected Set requiredParams() + { + return Sets.union(super.requiredParams(), required); + } + @Override - protected Set optionalParams() { return Sets.union(super.optionalParams(), optional.keySet()); } + protected Set optionalParams() + { + return Sets.union(super.optionalParams(), optional.keySet()); + } private Sphere() { @@ -1006,7 +1259,7 @@ private Sphere() int subdivisions; @Override - protected void init(Map options, RegistryAccess regs) + protected void init(final Map options, final RegistryAccess regs) { super.init(options, regs); center = vecFromValue(options.get("center")); @@ -1015,50 +1268,57 @@ protected void init(Map options, RegistryAccess regs) subdivisions = level; if (subdivisions <= 0) { - subdivisions = Math.max(10, (int)(10*Math.sqrt(radius))); + subdivisions = Math.max(10, (int) (10 * Math.sqrt(radius))); } } @Override - public Consumer alternative() { return p -> + public Consumer alternative() { + return p -> + { + final int partno = Math.min(1000, 20 * subdivisions); + final RandomSource rand = p.level.getRandom(); + final ServerLevel world = p.getLevel(); + final ParticleOptions particle = replacementParticle(world.registryAccess()); - int partno = Math.min(1000,20*subdivisions); - RandomSource rand = p.level.getRandom(); - ServerLevel world = p.getLevel(); - ParticleOptions particle = replacementParticle(world.registryAccess()); - - Vec3 ccenter = relativiseRender(world, center, 0 ); - - double ccx = ccenter.x; - double ccy = ccenter.y; - double ccz = ccenter.z; + final Vec3 ccenter = relativiseRender(world, center, 0); - for (int i=0; i required = Set.of("center", "radius"); @@ -1067,10 +1327,18 @@ public static class Cylinder extends ExpiringShape "height", Value.ZERO, "axis", new StringValue("y") ); + @Override - protected Set requiredParams() { return Sets.union(super.requiredParams(), required); } + protected Set requiredParams() + { + return Sets.union(super.requiredParams(), required); + } + @Override - protected Set optionalParams() { return Sets.union(super.optionalParams(), optional.keySet()); } + protected Set optionalParams() + { + return Sets.union(super.optionalParams(), optional.keySet()); + } Vec3 center; float height; @@ -1079,10 +1347,13 @@ public static class Cylinder extends ExpiringShape int subdivisions; Direction.Axis axis; - private Cylinder() { super(); } + private Cylinder() + { + super(); + } @Override - protected void init(Map options, RegistryAccess regs) + protected void init(final Map options, final RegistryAccess regs) { super.init(options, regs); center = vecFromValue(options.get("center")); @@ -1091,7 +1362,7 @@ protected void init(Map options, RegistryAccess regs) subdivisions = level; if (subdivisions <= 0) { - subdivisions = Math.max(10, (int)(10*Math.sqrt(radius))); + subdivisions = Math.max(10, (int) (10 * Math.sqrt(radius))); } height = NumericValue.asNumber(options.getOrDefault("height", optional.get("height"))).getFloat(); axis = Direction.Axis.byName(options.getOrDefault("axis", optional.get("axis")).getString()); @@ -1099,84 +1370,92 @@ protected void init(Map options, RegistryAccess regs) @Override - public Consumer alternative() { return p -> + public Consumer alternative() { + return p -> + { + final int partno = (int) Math.min(1000, Math.sqrt(20 * subdivisions * (1 + height))); + final RandomSource rand = p.level.getRandom(); + final ServerLevel world = p.getLevel(); + final ParticleOptions particle = replacementParticle(world.registryAccess()); - int partno = (int)Math.min(1000,Math.sqrt(20*subdivisions*(1+height))); - RandomSource rand = p.level.getRandom(); - ServerLevel world = p.getLevel(); - ParticleOptions particle = replacementParticle(world.registryAccess()); - - Vec3 ccenter = relativiseRender(world, center, 0 ); + final Vec3 ccenter = relativiseRender(world, center, 0); - double ccx = ccenter.x; - double ccy = ccenter.y; - double ccz = ccenter.z; + final double ccx = ccenter.x; + final double ccy = ccenter.y; + final double ccz = ccenter.z; - if (axis == Direction.Axis.Y) - { - for (int i=0; i of = new HashMap(){{ - put("mode",new StringChoiceParam("mode","polygon","strip","triangles")); - put("relative",new OptionalBoolListParam("relative")); + public static Map of = new HashMap() + {{ + put("mode", new StringChoiceParam("mode", "polygon", "strip", "triangles")); + put("relative", new OptionalBoolListParam("relative")); put("inner", new BoolParam("inner")); put("shape", new ShapeParam()); put("dim", new DimensionParam()); put("duration", new NonNegativeIntParam("duration")); put("color", new ColorParam("color")); put("follow", new EntityParam("follow")); - put("variant",new StringChoiceParam("variant", + put("variant", new StringChoiceParam("variant", "NONE", "THIRD_PERSON_LEFT_HAND", "THIRD_PERSON_RIGHT_HAND", @@ -1186,18 +1465,19 @@ public static abstract class Param "GUI", "GROUND", "FIXED") - { - public Value validate(Map o, MinecraftServer s, Value v) - { - return super.validate(o, s ,new StringValue(v.getString().toUpperCase(Locale.ROOT))); - } - }); + { + @Override + public Value validate(final Map o, final MinecraftServer s, final Value v) + { + return super.validate(o, s, new StringValue(v.getString().toUpperCase(Locale.ROOT))); + } + }); put("snap", new StringChoiceParam("snap", "xyz", "xz", "yz", "xy", "x", "y", "z", "dxdydz", "dxdz", "dydz", "dxdy", "dx", "dy", "dz", "xdz", "dxz", "ydz", "dyz", "xdy", "dxy", "xydz", "xdyz", "xdydz", "dxyz", "dxydz", "dxdyz" - )); + )); put("line", new PositiveFloatParam("line")); put("fill", new ColorParam("fill")); @@ -1209,13 +1489,18 @@ public Value validate(Map o, MinecraftServer s, Value v) put("level", new PositiveIntParam("level")); put("height", new FloatParam("height")); put("width", new FloatParam("width")); - put("scale", new Vec3Param("scale", false){ - public Value validate(java.util.Map options, MinecraftServer server, Value value) { - if (value instanceof NumericValue vn){ - value = ListValue.of(vn,vn,vn); + put("scale", new Vec3Param("scale", false) + { + @Override + public Value validate(final java.util.Map options, final MinecraftServer server, Value value) + { + if (value instanceof final NumericValue vn) + { + value = ListValue.of(vn, vn, vn); } return super.validate(options, server, value); - }; + } + }); put("axis", new StringChoiceParam("axis", "x", "y", "z")); put("points", new PointsParam("points")); @@ -1239,71 +1524,106 @@ public Value validate(java.util.Map options, MinecraftServer serve }}; protected String id; - protected Param(String id) + + protected Param(final String id) { this.id = id; } public abstract Tag toTag(Value value); //validates value, returning null if not necessary to keep it and serialize + public abstract Value validate(Map options, MinecraftServer server, Value value); // makes sure the value is proper + public abstract Value decode(Tag tag, Level level); } + public static class OptionalBoolListParam extends Param { - public OptionalBoolListParam(String id) { super(id); } + public OptionalBoolListParam(final String id) + { + super(id); + } @Override - public Tag toTag(Value value) { return value.toTag(true);} + public Tag toTag(final Value value) + { + return value.toTag(true); + } + @Override - public Value decode(Tag tag, Level level) { - if(tag instanceof ListTag){ - return ListValue.wrap(((ListTag)tag).stream().map(x->BooleanValue.of(((NumericTag)x).getAsNumber().doubleValue()!=0))); + public Value decode(final Tag tag, final Level level) + { + if (tag instanceof final ListTag list) + { + return ListValue.wrap(list.stream().map(x -> BooleanValue.of(((NumericTag) x).getAsNumber().doubleValue() != 0))); } - if(tag instanceof ByteTag booltag){ - return BooleanValue.of(booltag.getAsByte()!=0); + if (tag instanceof final ByteTag booltag) + { + return BooleanValue.of(booltag.getAsByte() != 0); } return Value.NULL; } @Override - public Value validate(Map options, MinecraftServer server, Value value) { - if(value instanceof AbstractListValue lv){ + public Value validate(final Map options, final MinecraftServer server, final Value value) + { + if (value instanceof final AbstractListValue lv) + { return ListValue.wrap(lv.unpack().stream().map(Value::getBoolean).map(BooleanValue::of)); } - if(value instanceof BooleanValue || value.isNull()){ + if (value instanceof BooleanValue || value.isNull()) + { return value; } return BooleanValue.of(value.getBoolean()); } } + public abstract static class StringParam extends Param { - protected StringParam(String id) { super(id); } + protected StringParam(final String id) + { + super(id); + } @Override - public Tag toTag(Value value) { return StringTag.valueOf(value.getString()); } + public Tag toTag(final Value value) + { + return StringTag.valueOf(value.getString()); + } + @Override - public Value decode(Tag tag, Level level) { return new StringValue(tag.getAsString()); } + public Value decode(final Tag tag, final Level level) + { + return new StringValue(tag.getAsString()); + } } + public static class BlockParam extends Param { - - protected BlockParam(String id) { + + protected BlockParam(final String id) + { super(id); } + @Override - public Value validate(Map options, MinecraftServer server, Value value) + public Value validate(final Map options, final MinecraftServer server, final Value value) { - if(value instanceof BlockValue blv){ + if (value instanceof BlockValue) + { return value; } return BlockValue.fromString(value.getString(), server.overworld()); } + @Override - public Tag toTag(Value value) { - if(value instanceof BlockValue blv){ - CompoundTag com = NbtUtils.writeBlockState(blv.getBlockState()); - CompoundTag dataTag = blv.getData(); + public Tag toTag(final Value value) + { + if (value instanceof final BlockValue blv) + { + final CompoundTag com = NbtUtils.writeBlockState(blv.getBlockState()); + final CompoundTag dataTag = blv.getData(); if (dataTag != null) { com.put("TileEntityData", dataTag); @@ -1314,60 +1634,75 @@ public Tag toTag(Value value) { } @Override - public Value decode(Tag tag, Level level) { - BlockState bs = NbtUtils.readBlockState(level.holderLookup(Registries.BLOCK), (CompoundTag) tag); + public Value decode(final Tag tag, final Level level) + { + final BlockState bs = NbtUtils.readBlockState(level.holderLookup(Registries.BLOCK), (CompoundTag) tag); CompoundTag compoundTag2 = null; - if (((CompoundTag) tag).contains("TileEntityData", 10)) { - compoundTag2 = ((CompoundTag) tag).getCompound("TileEntityData"); + if (((CompoundTag) tag).contains("TileEntityData", 10)) + { + compoundTag2 = ((CompoundTag) tag).getCompound("TileEntityData"); } return new BlockValue(bs, level, null, compoundTag2); } } + public static class ItemParam extends Param { - - protected ItemParam(String id) { + + protected ItemParam(final String id) + { super(id); } + @Override - public Value validate(Map options, MinecraftServer server, Value value) + public Value validate(final Map options, final MinecraftServer server, final Value value) { - ItemStack item=ValueConversions.getItemStackFromValue(value, true, server.registryAccess()); + final ItemStack item = ValueConversions.getItemStackFromValue(value, true, server.registryAccess()); return new NBTSerializableValue(item.save(new CompoundTag())); } + @Override - public Tag toTag(Value value) { - return ((NBTSerializableValue)value).getTag(); + public Tag toTag(final Value value) + { + return ((NBTSerializableValue) value).getTag(); } + @Override - public Value decode(Tag tag, Level level) { + public Value decode(final Tag tag, final Level level) + { return new NBTSerializableValue(tag); } } + public static class TextParam extends StringParam { - protected TextParam(String id) + protected TextParam(final String id) { super(id); } + @Override - public Value validate(Map options, MinecraftServer server, Value value) + public Value validate(final Map options, final MinecraftServer server, final Value value) { return value; } } + public static class FormattedTextParam extends StringParam { - protected FormattedTextParam(String id) + protected FormattedTextParam(final String id) { super(id); } + @Override - public Value validate(Map options, MinecraftServer server, Value value) + public Value validate(final Map options, final MinecraftServer server, Value value) { if (!(value instanceof FormattedTextValue)) + { value = new FormattedTextValue(Component.literal(value.getString())); + } return value; } @@ -1375,12 +1710,14 @@ public Value validate(Map options, MinecraftServer server, Value public Tag toTag(Value value) { if (!(value instanceof FormattedTextValue)) + { value = new FormattedTextValue(Component.literal(value.getString())); - return StringTag.valueOf(((FormattedTextValue)value).serialize()); + } + return StringTag.valueOf(((FormattedTextValue) value).serialize()); } @Override - public Value decode(Tag tag, Level level) + public Value decode(final Tag tag, final Level level) { return FormattedTextValue.deserialize(tag.getAsString()); } @@ -1389,8 +1726,9 @@ public Value decode(Tag tag, Level level) public static class StringChoiceParam extends StringParam { - private Set options; - public StringChoiceParam(String id, String ... options) + private final Set options; + + public StringChoiceParam(final String id, final String... options) { super(id); this.options = Sets.newHashSet(options); @@ -1398,201 +1736,312 @@ public StringChoiceParam(String id, String ... options) @Override - public Value validate(Map options, MinecraftServer server, Value value) + public Value validate(final Map options, final MinecraftServer server, final Value value) { - if (this.options.contains(value.getString())) return value; + if (this.options.contains(value.getString())) + { + return value; + } return null; } } public static class DimensionParam extends StringParam { - protected DimensionParam() { super("dim"); } + protected DimensionParam() + { + super("dim"); + } @Override - public Value validate(Map options, MinecraftServer server, Value value) { return value; } + public Value validate(final Map options, final MinecraftServer server, final Value value) + { + return value; + } } + public static class ShapeParam extends StringParam { - protected ShapeParam() { super("shape"); } + protected ShapeParam() + { + super("shape"); + } @Override - public Value validate(Map options, MinecraftServer server, Value value) + public Value validate(final Map options, final MinecraftServer server, final Value value) { - String shape = value.getString(); + final String shape = value.getString(); if (!ExpiringShape.shapeProviders.containsKey(shape)) - throw new InternalExpressionException("Unknown shape: "+shape); + { + throw new InternalExpressionException("Unknown shape: " + shape); + } return value; } } - public static abstract class NumericParam extends Param + + public abstract static class NumericParam extends Param { - protected NumericParam(String id) { super(id); } + protected NumericParam(final String id) + { + super(id); + } @Override - public Value validate(Map options, MinecraftServer server, Value value) + public Value validate(final Map options, final MinecraftServer server, final Value value) { if (!(value instanceof NumericValue)) + { throw new InternalExpressionException("'" + id + "' needs to be a number"); + } return value; } } + public static class BoolParam extends NumericParam { - protected BoolParam(String id) + protected BoolParam(final String id) { super(id); } @Override - public Tag toTag(Value value) + public Tag toTag(final Value value) { return ByteTag.valueOf(value.getBoolean()); } @Override - public Value decode(Tag tag, Level level) + public Value decode(final Tag tag, final Level level) { return BooleanValue.of(((ByteTag) tag).getAsByte() > 0); } } + public static class FloatParam extends NumericParam { - protected FloatParam(String id) { super(id); } + protected FloatParam(final String id) + { + super(id); + } + @Override - public Value decode(Tag tag, Level level) { return new NumericValue(((FloatTag)tag).getAsFloat()); } + public Value decode(final Tag tag, final Level level) + { + return new NumericValue(((FloatTag) tag).getAsFloat()); + } + @Override - public Tag toTag(Value value) { return FloatTag.valueOf(NumericValue.asNumber(value, id).getFloat()); } + public Tag toTag(final Value value) + { + return FloatTag.valueOf(NumericValue.asNumber(value, id).getFloat()); + } } - public static abstract class PositiveParam extends NumericParam + public abstract static class PositiveParam extends NumericParam { - protected PositiveParam(String id) { super(id); } - @Override public Value validate(Map options, MinecraftServer server, Value value) + protected PositiveParam(final String id) + { + super(id); + } + + @Override + public Value validate(final Map options, final MinecraftServer server, final Value value) { - Value ret = super.validate(options, server, value); - if (((NumericValue)ret).getDouble()<=0) throw new InternalExpressionException("'"+id+"' should be positive"); + final Value ret = super.validate(options, server, value); + if (((NumericValue) ret).getDouble() <= 0) + { + throw new InternalExpressionException("'" + id + "' should be positive"); + } return ret; } } + public static class PositiveFloatParam extends PositiveParam { - protected PositiveFloatParam(String id) { super(id); } + protected PositiveFloatParam(final String id) + { + super(id); + } + @Override - public Value decode(Tag tag, Level level) { return new NumericValue(((FloatTag)tag).getAsFloat()); } + public Value decode(final Tag tag, final Level level) + { + return new NumericValue(((FloatTag) tag).getAsFloat()); + } + @Override - public Tag toTag(Value value) { return FloatTag.valueOf(NumericValue.asNumber(value, id).getFloat()); } + public Tag toTag(final Value value) + { + return FloatTag.valueOf(NumericValue.asNumber(value, id).getFloat()); + } } + public static class PositiveIntParam extends PositiveParam { - protected PositiveIntParam(String id) { super(id); } + protected PositiveIntParam(final String id) + { + super(id); + } + @Override - public Value decode(Tag tag, Level level) { return new NumericValue(((IntTag)tag).getAsInt()); } + public Value decode(final Tag tag, final Level level) + { + return new NumericValue(((IntTag) tag).getAsInt()); + } + @Override - public Tag toTag(Value value) { return IntTag.valueOf(NumericValue.asNumber(value, id).getInt()); } + public Tag toTag(final Value value) + { + return IntTag.valueOf(NumericValue.asNumber(value, id).getInt()); + } } + public static class NonNegativeIntParam extends NumericParam { - protected NonNegativeIntParam(String id) { super(id); } + protected NonNegativeIntParam(final String id) + { + super(id); + } + @Override - public Value decode(Tag tag, Level level) { return new NumericValue(((IntTag)tag).getAsInt()); } + public Value decode(final Tag tag, final Level level) + { + return new NumericValue(((IntTag) tag).getAsInt()); + } + + @Override + public Tag toTag(final Value value) + { + return IntTag.valueOf(NumericValue.asNumber(value, id).getInt()); + } + @Override - public Tag toTag(Value value) { return IntTag.valueOf(NumericValue.asNumber(value, id).getInt()); } - @Override public Value validate(Map options, MinecraftServer server, Value value) + public Value validate(final Map options, final MinecraftServer server, final Value value) { - Value ret = super.validate(options, server, value); - if (((NumericValue)ret).getDouble()<0) throw new InternalExpressionException("'"+id+"' should be non-negative"); + final Value ret = super.validate(options, server, value); + if (((NumericValue) ret).getDouble() < 0) + { + throw new InternalExpressionException("'" + id + "' should be non-negative"); + } return ret; } } + public static class NonNegativeFloatParam extends NumericParam { - protected NonNegativeFloatParam(String id) { super(id); } + protected NonNegativeFloatParam(final String id) + { + super(id); + } + @Override - public Value decode(Tag tag, Level level) { return new NumericValue(((FloatTag)tag).getAsFloat()); } + public Value decode(final Tag tag, final Level level) + { + return new NumericValue(((FloatTag) tag).getAsFloat()); + } + + @Override + public Tag toTag(final Value value) + { + return FloatTag.valueOf(NumericValue.asNumber(value, id).getFloat()); + } + @Override - public Tag toTag(Value value) { return FloatTag.valueOf(NumericValue.asNumber(value, id).getFloat()); } - @Override public Value validate(Map options, MinecraftServer server, Value value) + public Value validate(final Map options, final MinecraftServer server, final Value value) { - Value ret = super.validate(options, server, value); - if (((NumericValue)ret).getDouble()<0) throw new InternalExpressionException("'"+id+"' should be non-negative"); + final Value ret = super.validate(options, server, value); + if (((NumericValue) ret).getDouble() < 0) + { + throw new InternalExpressionException("'" + id + "' should be non-negative"); + } return ret; } } - - public static class Vec3Param extends Param { - private boolean roundsUpForBlocks; - protected Vec3Param(String id, boolean doesRoundUpForBlocks) + private final boolean roundsUpForBlocks; + + protected Vec3Param(final String id, final boolean doesRoundUpForBlocks) { super(id); roundsUpForBlocks = doesRoundUpForBlocks; } + @Override - public Value validate(Map options, MinecraftServer server, Value value) + public Value validate(final Map options, final MinecraftServer server, final Value value) { return validate(this, options, value, roundsUpForBlocks); } - public static Value validate(Param p, Map options, Value value, boolean roundsUp) + + public static Value validate(final Param p, final Map options, final Value value, final boolean roundsUp) { - if (value instanceof BlockValue) + if (value instanceof final BlockValue bv) { if (options.containsKey("follow")) - throw new InternalExpressionException(p.id+" parameter cannot use blocks as positions for relative positioning due to 'follow' attribute being present"); - BlockPos pos = ((BlockValue) value).getPos(); - int offset = roundsUp?1:0; + { + throw new InternalExpressionException(p.id + " parameter cannot use blocks as positions for relative positioning due to 'follow' attribute being present"); + } + final BlockPos pos = bv.getPos(); + final int offset = roundsUp ? 1 : 0; return ListValue.of( - new NumericValue(pos.getX()+offset), - new NumericValue(pos.getY()+offset), - new NumericValue(pos.getZ()+offset) + new NumericValue(pos.getX() + offset), + new NumericValue(pos.getY() + offset), + new NumericValue(pos.getZ() + offset) ); } - if (value instanceof ListValue) + if (value instanceof final ListValue list) { - List values = ((ListValue) value).getItems(); - if (values.size()!=3) throw new InternalExpressionException("'"+p.id+"' requires 3 numerical values"); - for (Value component : values) + final List values = list.getItems(); + if (values.size() != 3) + { + throw new InternalExpressionException("'" + p.id + "' requires 3 numerical values"); + } + for (final Value component : values) { if (!(component instanceof NumericValue)) - throw new InternalExpressionException("'"+p.id+"' requires 3 numerical values"); + { + throw new InternalExpressionException("'" + p.id + "' requires 3 numerical values"); + } } return value; } - if (value instanceof EntityValue) + if (value instanceof final EntityValue ev) { if (options.containsKey("follow")) - throw new InternalExpressionException(p.id+" parameter cannot use entity as positions for relative positioning due to 'follow' attribute being present"); - Entity e = ((EntityValue) value).getEntity(); + { + throw new InternalExpressionException(p.id + " parameter cannot use entity as positions for relative positioning due to 'follow' attribute being present"); + } + final Entity e = ev.getEntity(); return ListValue.of( new NumericValue(e.getX()), new NumericValue(e.getY()), new NumericValue(e.getZ()) ); } - CarpetSettings.LOG.error("Value: "+value.getString()); - throw new InternalExpressionException("'"+p.id+"' requires a triple, block or entity to indicate position"); + CarpetSettings.LOG.error("Value: " + value.getString()); + throw new InternalExpressionException("'" + p.id + "' requires a triple, block or entity to indicate position"); } @Override - public Value decode(Tag tag, Level level) + public Value decode(final Tag tag, final Level level) { - ListTag ctag = (ListTag)tag; + final ListTag ctag = (ListTag) tag; return ListValue.of( new NumericValue(ctag.getDouble(0)), new NumericValue(ctag.getDouble(1)), new NumericValue(ctag.getDouble(2)) ); } + @Override - public Tag toTag(Value value) + public Tag toTag(final Value value) { - List lv = ((ListValue)value).getItems(); - ListTag tag = new ListTag(); + final List lv = ((ListValue) value).getItems(); + final 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())); @@ -1602,29 +2051,34 @@ public Tag toTag(Value value) public static class PointsParam extends Param { - public PointsParam(String id) + public PointsParam(final String id) { super(id); } + @Override - public Value validate(Map options, MinecraftServer server, Value value) + public Value validate(final Map options, final MinecraftServer server, final Value value) { - if (!(value instanceof ListValue)) - throw new InternalExpressionException(id+ " parameter should be a list"); - List points = new ArrayList<>(); - for (Value point: ((ListValue) value).getItems()) + if (!(value instanceof final ListValue list)) + { + throw new InternalExpressionException(id + " parameter should be a list"); + } + final List points = new ArrayList<>(); + for (final Value point : list.getItems()) + { points.add(Vec3Param.validate(this, options, point, false)); + } return ListValue.wrap(points); } @Override - public Value decode(Tag tag, Level level) + public Value decode(final Tag tag, final Level level) { - ListTag ltag = (ListTag)tag; - List points = new ArrayList<>(); - for (int i=0, ll = ltag.size(); i points = new ArrayList<>(); + for (int i = 0, ll = ltag.size(); i < ll; i++) { - ListTag ptag = ltag.getList(i); + final ListTag ptag = ltag.getList(i); points.add(ListValue.of( new NumericValue(ptag.getDouble(0)), new NumericValue(ptag.getDouble(1)), @@ -1633,15 +2087,16 @@ public Value decode(Tag tag, Level level) } return ListValue.wrap(points); } + @Override - public Tag toTag(Value pointsValue) + public Tag toTag(final Value pointsValue) { - List lv = ((ListValue)pointsValue).getItems(); - ListTag ltag = new ListTag(); - for (Value value : lv) + final List lv = ((ListValue) pointsValue).getItems(); + final ListTag ltag = new ListTag(); + for (final Value value : lv) { - List coords = ((ListValue)value).getItems(); - ListTag tag = new ListTag(); + final List coords = ((ListValue) value).getItems(); + final ListTag tag = new ListTag(); tag.add(DoubleTag.valueOf(NumericValue.asNumber(coords.get(0), "x").getDouble())); tag.add(DoubleTag.valueOf(NumericValue.asNumber(coords.get(1), "y").getDouble())); tag.add(DoubleTag.valueOf(NumericValue.asNumber(coords.get(2), "z").getDouble())); @@ -1654,125 +2109,151 @@ public Tag toTag(Value pointsValue) public static class ColorParam extends NumericParam { - protected ColorParam(String id) + protected ColorParam(final String id) { super(id); } @Override - public Value decode(Tag tag, Level level) { return new NumericValue(((IntTag)tag).getAsInt()); } + public Value decode(final Tag tag, final Level level) + { + return new NumericValue(((IntTag) tag).getAsInt()); + } + @Override - public Tag toTag(Value value) { return IntTag.valueOf(NumericValue.asNumber(value, id).getInt()); } + public Tag toTag(final Value value) + { + return IntTag.valueOf(NumericValue.asNumber(value, id).getInt()); + } } public static class EntityParam extends Param { - protected EntityParam(String id) { super(id); } + protected EntityParam(final String id) + { + super(id); + } @Override - public Tag toTag(Value value) + public Tag toTag(final Value value) { return IntTag.valueOf(NumericValue.asNumber(value, id).getInt()); } @Override - public Value validate(Map options, MinecraftServer server, Value value) + public Value validate(final Map options, final MinecraftServer server, final Value value) { - if (value instanceof EntityValue) return new NumericValue(((EntityValue) value).getEntity().getId()); - ServerPlayer player = EntityValue.getPlayerByValue(server, value); + if (value instanceof final EntityValue ev) + { + return new NumericValue(ev.getEntity().getId()); + } + final ServerPlayer player = EntityValue.getPlayerByValue(server, value); if (player == null) - throw new InternalExpressionException(id+" parameter needs to represent an entity or player"); + { + throw new InternalExpressionException(id + " parameter needs to represent an entity or player"); + } return new NumericValue(player.getId()); } @Override - public Value decode(Tag tag, Level level) { return new NumericValue(((IntTag)tag).getAsInt()); } + public Value decode(final Tag tag, final Level level) + { + return new NumericValue(((IntTag) tag).getAsInt()); + } } - private static boolean isStraight(Vec3 from, Vec3 to, double density) + private static boolean isStraight(final Vec3 from, final Vec3 to, final 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)) + 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 playerList, ParticleOptions particle, Vec3 from, Vec3 to, double density) + private static int drawOptimizedParticleLine(final List playerList, final ParticleOptions particle, final Vec3 from, final Vec3 to, final double density) { - double distance = from.distanceTo(to); - int particles = (int)(distance/density); - Vec3 towards = to.subtract(from); + final double distance = from.distanceTo(to); + final int particles = (int) (distance / density); + final Vec3 towards = to.subtract(from); int parts = 0; - for (ServerPlayer player : playerList) + for (final ServerPlayer player : playerList) { - ServerLevel world = player.getLevel(); + final 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); + (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.sendParticles(player, particle, true, - from.x, from.y, from.z,1,0.0,0.0,0.0,0.0); + from.x, from.y, from.z, 1, 0.0, 0.0, 0.0, 0.0); world.sendParticles(player, particle, true, - to.x, to.y, to.z,1,0.0,0.0,0.0,0.0); - parts += particles/3+2; + to.x, to.y, to.z, 1, 0.0, 0.0, 0.0, 0.0); + parts += particles / 3 + 2; } int divider = 6; - while (particles/divider > 1) + while (particles / divider > 1) { - int center = (divider*2)/3; - int dev = 2*divider; - for (ServerPlayer player : playerList) + final int center = (divider * 2) / 3; + final int dev = 2 * divider; + for (final ServerPlayer player : playerList) { - ServerLevel world = player.getLevel(); + final 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); + (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.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); + (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); } - parts += 2*particles/divider; - divider = 2*divider; + parts += 2 * particles / divider; + divider = 2 * divider; } return parts; } - public static int drawParticleLine(List players, ParticleOptions particle, Vec3 from, Vec3 to, double density) + public static int drawParticleLine(final List players, final ParticleOptions particle, final Vec3 from, final Vec3 to, final double density) { - double distance = from.distanceToSqr(to); - if (distance == 0) return 0; + final double distance = from.distanceToSqr(to); + if (distance == 0) + { + return 0; + } int pcount = 0; if (distance < 100) { - RandomSource rand = players.get(0).level.random; - int particles = (int)(distance/density)+1; - Vec3 towards = to.subtract(from); + final RandomSource rand = players.get(0).level.random; + final int particles = (int) (distance / density) + 1; + final Vec3 towards = to.subtract(from); for (int i = 0; i < particles; i++) { - Vec3 at = from.add(towards.scale( rand.nextDouble())); - for (ServerPlayer player : players) + final Vec3 at = from.add(towards.scale(rand.nextDouble())); + for (final ServerPlayer player : players) { player.getLevel().sendParticles(player, particle, true, at.x, at.y, at.z, 1, 0.0, 0.0, 0.0, 0.0); - pcount ++; + pcount++; } } return pcount; } - if (isStraight(from, to, density)) return drawOptimizedParticleLine(players, particle, from, to, density); - Vec3 incvec = to.subtract(from).scale(2*density/Math.sqrt(distance)); + if (isStraight(from, to, density)) + { + return drawOptimizedParticleLine(players, particle, from, to, density); + } + final Vec3 incvec = to.subtract(from).scale(2 * density / Math.sqrt(distance)); - for (Vec3 delta = new Vec3(0.0,0.0,0.0); - delta.lengthSqr(), Long2ObjectOpenHashMap>> shapes; private final Map, Long2ObjectOpenHashMap>> labels; - private Minecraft client; + private final Minecraft client; - private Map>> renderedShapes - = new HashMap<>() {{ + private final Map>> renderedShapes + = new HashMap<>() + {{ put("line", RenderedLine::new); put("box", RenderedBox::new); put("sphere", RenderedSphere::new); @@ -71,22 +73,25 @@ public class ShapesRenderer put("item", (c, s) -> new RenderedSprite(c, s, true)); }}; - public ShapesRenderer(Minecraft minecraftClient) + public ShapesRenderer(final Minecraft minecraftClient) { this.client = minecraftClient; shapes = new HashMap<>(); labels = new HashMap<>(); } - public void render(PoseStack matrices, Camera camera, float partialTick) + public void render(final PoseStack matrices, final Camera camera, final float partialTick) { - CarpetProfiler.ProfilerToken token = CarpetProfiler.start_section(null, "Scarpet client", CarpetProfiler.TYPE.GENERAL); + final CarpetProfiler.ProfilerToken token = CarpetProfiler.start_section(null, "Scarpet client", CarpetProfiler.TYPE.GENERAL); //Camera camera = this.client.gameRenderer.getCamera(); - ClientLevel iWorld = this.client.level; - ResourceKey dimensionType = iWorld.dimension(); + final ClientLevel iWorld = this.client.level; + final ResourceKey dimensionType = iWorld.dimension(); if ((shapes.get(dimensionType) == null || shapes.get(dimensionType).isEmpty()) && - (labels.get(dimensionType) == null || labels.get(dimensionType).isEmpty())) return; - long currentTime = client.level.getGameTime(); + (labels.get(dimensionType) == null || labels.get(dimensionType).isEmpty())) + { + return; + } + final long currentTime = client.level.getGameTime(); RenderSystem.enableDepthTest(); RenderSystem.setShader(GameRenderer::getPositionColorShader); RenderSystem.depthFunc(515); @@ -102,45 +107,56 @@ public void render(PoseStack matrices, Camera camera, float partialTick) //RenderSystem.polygonOffset(-3f, -3f); //RenderSystem.enablePolygonOffset(); - Tesselator tessellator = Tesselator.getInstance(); - BufferBuilder bufferBuilder = tessellator.getBuilder(); + final Tesselator tessellator = Tesselator.getInstance(); + final BufferBuilder bufferBuilder = tessellator.getBuilder(); // render - double cameraX = camera.getPosition().x; - double cameraY = camera.getPosition().y; - double cameraZ = camera.getPosition().z; - boolean entityBoxes = client.getEntityRenderDispatcher().shouldRenderHitBoxes(); + final double cameraX = camera.getPosition().x; + final double cameraY = camera.getPosition().y; + final double cameraZ = camera.getPosition().z; + final boolean entityBoxes = client.getEntityRenderDispatcher().shouldRenderHitBoxes(); - if (shapes.size() != 0) { + if (shapes.size() != 0) + { shapes.get(dimensionType).long2ObjectEntrySet().removeIf( entry -> entry.getValue().isExpired(currentTime) ); - PoseStack matrixStack = RenderSystem.getModelViewStack(); + final PoseStack matrixStack = RenderSystem.getModelViewStack(); matrixStack.pushPose(); matrixStack.mulPoseMatrix(matrices.last().pose()); RenderSystem.applyModelViewMatrix(); // lines RenderSystem.lineWidth(0.5F); - shapes.get(dimensionType).values().forEach( s -> { - if ( (!s.shape.debug ||entityBoxes ) && s.shouldRender(dimensionType)) s.renderLines(matrices, tessellator, bufferBuilder, cameraX, cameraY, cameraZ, partialTick); + shapes.get(dimensionType).values().forEach(s -> { + if ((!s.shape.debug || entityBoxes) && s.shouldRender(dimensionType)) + { + s.renderLines(matrices, tessellator, bufferBuilder, cameraX, cameraY, cameraZ, partialTick); + } }); // faces RenderSystem.lineWidth(0.1F); shapes.get(dimensionType).values().forEach(s -> { - if ( (!s.shape.debug ||entityBoxes ) && s.shouldRender(dimensionType)) s.renderFaces(tessellator, bufferBuilder, cameraX, cameraY, cameraZ, partialTick); + if ((!s.shape.debug || entityBoxes) && s.shouldRender(dimensionType)) + { + s.renderFaces(tessellator, bufferBuilder, cameraX, cameraY, cameraZ, partialTick); + } }); RenderSystem.lineWidth(1.0F); matrixStack.popPose(); RenderSystem.applyModelViewMatrix(); } - if (labels.size() != 0) { + if (labels.size() != 0) + { labels.get(dimensionType).long2ObjectEntrySet().removeIf( entry -> entry.getValue().isExpired(currentTime) ); labels.get(dimensionType).values().forEach(s -> { - if ( (!s.shape.debug || entityBoxes) && s.shouldRender(dimensionType)) s.renderLines(matrices, tessellator, bufferBuilder, cameraX, cameraY, cameraZ, partialTick); + if ((!s.shape.debug || entityBoxes) && s.shouldRender(dimensionType)) + { + s.renderLines(matrices, tessellator, bufferBuilder, cameraX, cameraY, cameraZ, partialTick); + } }); } RenderSystem.enableCull(); @@ -150,34 +166,37 @@ public void render(PoseStack matrices, Camera camera, float partialTick) CarpetProfiler.end_current_section(token); } - public void addShapes(ListTag tag) + public void addShapes(final ListTag tag) { - CarpetProfiler.ProfilerToken token = CarpetProfiler.start_section(null, "Scarpet client", CarpetProfiler.TYPE.GENERAL); - for (int i=0, count = tag.size(); i < count; i++) + final CarpetProfiler.ProfilerToken token = CarpetProfiler.start_section(null, "Scarpet client", CarpetProfiler.TYPE.GENERAL); + for (int i = 0, count = tag.size(); i < count; i++) { addShape(tag.getCompound(i)); } CarpetProfiler.end_current_section(token); } - public void addShape(CompoundTag tag) + public void addShape(final CompoundTag tag) { - ShapeDispatcher.ExpiringShape shape = ShapeDispatcher.fromTag(tag, client.level); - if (shape == null) return; - BiFunction> shapeFactory; + final ShapeDispatcher.ExpiringShape shape = ShapeDispatcher.fromTag(tag, client.level); + if (shape == null) + { + return; + } + final BiFunction> shapeFactory; shapeFactory = renderedShapes.get(tag.getString("shape")); if (shapeFactory == null) { - CarpetSettings.LOG.info("Unrecognized shape: "+tag.getString("shape")); + CarpetSettings.LOG.info("Unrecognized shape: " + tag.getString("shape")); } else { - RenderedShape rshape = shapeFactory.apply(client, shape); - ResourceKey dim = shape.shapeDimension; - long key = rshape.key(); - Map, Long2ObjectOpenHashMap>> container = - rshape.stageDeux()?labels:shapes; - RenderedShape existing = container.computeIfAbsent(dim, d -> new Long2ObjectOpenHashMap<>()).get(key); + final RenderedShape rshape = shapeFactory.apply(client, shape); + final ResourceKey dim = shape.shapeDimension; + final long key = rshape.key(); + final Map, Long2ObjectOpenHashMap>> container = + rshape.stageDeux() ? labels : shapes; + final RenderedShape existing = container.computeIfAbsent(dim, d -> new Long2ObjectOpenHashMap<>()).get(key); if (existing != null) { // promoting previous shape existing.promoteWith(rshape); @@ -189,6 +208,7 @@ public void addShape(CompoundTag tag) } } + public void reset() { shapes.values().forEach(Long2ObjectOpenHashMap::clear); @@ -197,7 +217,7 @@ public void reset() public void renewShapes() { - CarpetProfiler.ProfilerToken token = CarpetProfiler.start_section(null, "Scarpet client", CarpetProfiler.TYPE.GENERAL); + final CarpetProfiler.ProfilerToken token = CarpetProfiler.start_section(null, "Scarpet client", CarpetProfiler.TYPE.GENERAL); shapes.values().forEach(el -> el.values().forEach(shape -> shape.expiryTick++)); labels.values().forEach(el -> el.values().forEach(shape -> shape.expiryTick++)); @@ -210,43 +230,61 @@ public abstract static class RenderedShape dim) + } + + public boolean shouldRender(final ResourceKey dim) { - if (shape.followEntity <=0 ) return true; - if (client.level == null) return false; - if (client.level.dimension() != dim) return false; + if (shape.followEntity <= 0) + { + return true; + } + if (client.level == null) + { + return false; + } + if (client.level.dimension() != dim) + { + return false; + } return client.level.getEntity(shape.followEntity) != null; } + public boolean stageDeux() { return false; } - public void promoteWith(RenderedShape rshape) + public void promoteWith(final RenderedShape rshape) { expiryTick = rshape.expiryTick; } } - public static class RenderedSprite extends RenderedShape { + public static class RenderedSprite extends RenderedShape + { private final boolean isitem; private ItemTransforms.TransformType transformType = ItemTransforms.TransformType.NONE; @@ -255,23 +293,27 @@ public static class RenderedSprite extends RenderedShape> 16 & 0xFF) / 255.0F; - float green = (color >> 8 & 0xFF) / 255.0F; - float blue = (color & 0xFF) / 255.0F; + final float red = (color >> 16 & 0xFF) / 255.0F; + final float green = (color >> 8 & 0xFF) / 255.0F; + final float blue = (color & 0xFF) / 255.0F; client.getBlockRenderer().getModelRenderer().renderModel(matrices.last(), immediate.getBuffer(ItemBlockRenderTypes.getRenderType(blockState, false)), blockState, bakedModel, red, green, blue, light, OverlayTexture.NO_OVERLAY); } @@ -335,21 +390,25 @@ public void renderLines(PoseStack matrices, Tesselator tessellator, BufferBuilde if (BlockEntity != null) { BlockEntity.setLevel(client.level); - if (shape.blockEntity != null) BlockEntity.load(shape.blockEntity); + if (shape.blockEntity != null) + { + BlockEntity.load(shape.blockEntity); + } } } } if (BlockEntity instanceof ShulkerBoxBlockEntity sbBlockEntity) { sbrender(sbBlockEntity, partialTick, - matrices, immediate, light, OverlayTexture.NO_OVERLAY); + matrices, immediate, light, OverlayTexture.NO_OVERLAY); } else { if (BlockEntity != null) { final BlockEntityRenderer blockEntityRenderer = client.getBlockEntityRenderDispatcher().getRenderer(BlockEntity); - if (blockEntityRenderer != null) { + if (blockEntityRenderer != null) + { blockEntityRenderer.render(BlockEntity, partialTick, matrices, immediate, light, OverlayTexture.NO_OVERLAY); @@ -375,24 +434,25 @@ public void renderLines(PoseStack matrices, Tesselator tessellator, BufferBuilde } @Override - public boolean stageDeux() { + public boolean stageDeux() + { return true; } // copy and modifiy a bit from net.minecraft.client.renderer.blockentity.ShulkerBoxRenderer.render - public void sbrender(ShulkerBoxBlockEntity shulkerBoxBlockEntity, float f, PoseStack poseStack, MultiBufferSource multiBufferSource, int i, int j) + public void sbrender(final ShulkerBoxBlockEntity shulkerBoxBlockEntity, final float f, final PoseStack poseStack, final MultiBufferSource multiBufferSource, final int i, final int j) { Direction direction = Direction.UP; if (shulkerBoxBlockEntity.hasLevel()) { - BlockState blockState = shulkerBoxBlockEntity.getBlockState(); + final BlockState blockState = shulkerBoxBlockEntity.getBlockState(); if (blockState.getBlock() instanceof ShulkerBoxBlock) { direction = blockState.getValue(ShulkerBoxBlock.FACING); } } - DyeColor dyeColor = shulkerBoxBlockEntity.getColor(); - Material material; + final DyeColor dyeColor = shulkerBoxBlockEntity.getColor(); + final Material material; if (dyeColor == null) { material = Sheets.DEFAULT_SHULKER_TEXTURE_LOCATION; @@ -401,18 +461,18 @@ public void sbrender(ShulkerBoxBlockEntity shulkerBoxBlockEntity, float f, PoseS { material = Sheets.SHULKER_TEXTURE_LOCATION.get(dyeColor.getId()); } - + poseStack.pushPose(); poseStack.translate(0.5, 0.5, 0.5); poseStack.scale(0.9995F, 0.9995F, 0.9995F); poseStack.mulPose(direction.getRotation()); poseStack.scale(1.0F, -1.0F, -1.0F); poseStack.translate(0.0, -1.0, 0.0); - ShulkerModel model = ((ShulkerBoxAccessMixin) client.getBlockEntityRenderDispatcher().getRenderer(BlockEntity)).getModel(); - ModelPart modelPart = model.getLid(); + final ShulkerModel model = ((ShulkerBoxAccessMixin) client.getBlockEntityRenderDispatcher().getRenderer(BlockEntity)).getModel(); + final ModelPart modelPart = model.getLid(); modelPart.setPos(0.0F, 24.0F - shulkerBoxBlockEntity.getProgress(f) * 0.5F * 16.0F, 0.0F); modelPart.yRot = 270.0F * shulkerBoxBlockEntity.getProgress(f) * (float) (Math.PI / 180.0); - VertexConsumer vertexConsumer = material.buffer(multiBufferSource, RenderType::entityCutoutNoCull); + final VertexConsumer vertexConsumer = material.buffer(multiBufferSource, RenderType::entityCutoutNoCull); model.renderToBuffer(poseStack, vertexConsumer, i, j, 1.0F, 1.0F, 1.0F, 1.0F); poseStack.popPose(); } @@ -422,33 +482,49 @@ public void sbrender(ShulkerBoxBlockEntity shulkerBoxBlockEntity, float f, PoseS public static class RenderedText extends RenderedShape { - protected RenderedText(Minecraft client, ShapeDispatcher.ExpiringShape shape) + protected RenderedText(final Minecraft client, final ShapeDispatcher.ExpiringShape shape) { - super(client, (ShapeDispatcher.DisplayedText)shape); + super(client, (ShapeDispatcher.DisplayedText) shape); } @Override - public void renderLines(PoseStack matrices, Tesselator tessellator, BufferBuilder builder, double cx, double cy, double cz, float partialTick) + public void renderLines(final PoseStack matrices, final Tesselator tessellator, final BufferBuilder builder, final double cx, final double cy, final double cz, final float partialTick) { - if (shape.a == 0.0) return; - Vec3 v1 = shape.relativiseRender(client.level, shape.pos, partialTick); - Camera camera1 = client.gameRenderer.getMainCamera(); - Font textRenderer = client.font; + if (shape.a == 0.0) + { + return; + } + final Vec3 v1 = shape.relativiseRender(client.level, shape.pos, partialTick); + final Camera camera1 = client.gameRenderer.getMainCamera(); + final Font textRenderer = client.font; if (shape.doublesided) + { RenderSystem.disableCull(); + } else + { RenderSystem.enableCull(); + } matrices.pushPose(); - matrices.translate(v1.x - cx,v1.y - cy,v1.z - cz); + matrices.translate(v1.x - cx, v1.y - cy, v1.z - cz); ShapeDirection.rotatePoseStackByShapeDirection(matrices, shape.facing, camera1, v1); - matrices.scale(shape.size* 0.0025f, -shape.size*0.0025f, shape.size*0.0025f); + matrices.scale(shape.size * 0.0025f, -shape.size * 0.0025f, shape.size * 0.0025f); //RenderSystem.scalef(shape.size* 0.0025f, -shape.size*0.0025f, shape.size*0.0025f); - if (shape.tilt!=0.0f) matrices.mulPose(Axis.ZP.rotationDegrees(shape.tilt)); - if (shape.lean!=0.0f) matrices.mulPose(Axis.XP.rotationDegrees(shape.lean)); - if (shape.turn!=0.0f) matrices.mulPose(Axis.YP.rotationDegrees(shape.turn)); - matrices.translate(-10*shape.indent, -10*shape.height-9, (-10*renderEpsilon)-10*shape.raise); + if (shape.tilt != 0.0f) + { + matrices.mulPose(Axis.ZP.rotationDegrees(shape.tilt)); + } + if (shape.lean != 0.0f) + { + matrices.mulPose(Axis.XP.rotationDegrees(shape.lean)); + } + if (shape.turn != 0.0f) + { + matrices.mulPose(Axis.YP.rotationDegrees(shape.turn)); + } + matrices.translate(-10 * shape.indent, -10 * shape.height - 9, (-10 * renderEpsilon) - 10 * shape.raise); //if (visibleThroughWalls) RenderSystem.disableDepthTest(); matrices.scale(-1, 1, 1); //RenderSystem.applyModelViewMatrix(); // passed matrix directly to textRenderer.draw, not AffineTransformation.identity().getMatrix(), @@ -456,13 +532,13 @@ public void renderLines(PoseStack matrices, Tesselator tessellator, BufferBuilde float text_x = 0; if (shape.align == 0) { - text_x = (float)(-textRenderer.width(shape.value.getString())) / 2.0F; + text_x = (float) (-textRenderer.width(shape.value.getString())) / 2.0F; } else if (shape.align == 1) { - text_x = (float)(-textRenderer.width(shape.value.getString())); + text_x = (float) (-textRenderer.width(shape.value.getString())); } - MultiBufferSource.BufferSource immediate = MultiBufferSource.immediate(builder); + final MultiBufferSource.BufferSource immediate = MultiBufferSource.immediate(builder); textRenderer.drawInBatch(shape.value, text_x, 0.0F, shape.textcolor, false, matrices.last().pose(), immediate, false, shape.textbck, 15728880); immediate.endBatch(); matrices.popPose(); @@ -476,16 +552,16 @@ public boolean stageDeux() } @Override - public void promoteWith(RenderedShape rshape) + public void promoteWith(final RenderedShape rshape) { super.promoteWith(rshape); try { this.shape.value = ((ShapeDispatcher.DisplayedText) rshape.shape).value; } - catch (ClassCastException ignored) + catch (final ClassCastException ignored) { - CarpetSettings.LOG.error("shape "+rshape.shape.getClass()+" cannot cast to a Label"); + CarpetSettings.LOG.error("shape " + rshape.shape.getClass() + " cannot cast to a Label"); } } } @@ -493,251 +569,312 @@ public void promoteWith(RenderedShape rshape) public static class RenderedBox extends RenderedShape { - private RenderedBox(Minecraft client, ShapeDispatcher.ExpiringShape shape) + private RenderedBox(final Minecraft client, final ShapeDispatcher.ExpiringShape shape) { - super(client, (ShapeDispatcher.Box)shape); - + super(client, (ShapeDispatcher.Box) shape); } + @Override - public void renderLines(PoseStack matrices, Tesselator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) + public void renderLines(final PoseStack matrices, final Tesselator tessellator, final BufferBuilder bufferBuilder, final double cx, final double cy, final double cz, final float partialTick) { - if (shape.a == 0.0) return; - Vec3 v1 = shape.relativiseRender(client.level, shape.from, partialTick); - Vec3 v2 = shape.relativiseRender(client.level, shape.to, partialTick); + if (shape.a == 0.0) + { + return; + } + final Vec3 v1 = shape.relativiseRender(client.level, shape.from, partialTick); + final Vec3 v2 = shape.relativiseRender(client.level, shape.to, partialTick); drawBoxWireGLLines(tessellator, bufferBuilder, - (float)(v1.x-cx-renderEpsilon), (float)(v1.y-cy-renderEpsilon), (float)(v1.z-cz-renderEpsilon), - (float)(v2.x-cx+renderEpsilon), (float)(v2.y-cy+renderEpsilon), (float)(v2.z-cz+renderEpsilon), - v1.x!=v2.x, v1.y!=v2.y, v1.z!=v2.z, + (float) (v1.x - cx - renderEpsilon), (float) (v1.y - cy - renderEpsilon), (float) (v1.z - cz - renderEpsilon), + (float) (v2.x - cx + renderEpsilon), (float) (v2.y - cy + renderEpsilon), (float) (v2.z - cz + renderEpsilon), + v1.x != v2.x, v1.y != v2.y, v1.z != v2.z, shape.r, shape.g, shape.b, shape.a, shape.r, shape.g, shape.b ); } + @Override - public void renderFaces(Tesselator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) + public void renderFaces(final Tesselator tessellator, final BufferBuilder bufferBuilder, final double cx, final double cy, final double cz, final float partialTick) { - if (shape.fa == 0.0) return; - Vec3 v1 = shape.relativiseRender(client.level, shape.from, partialTick); - Vec3 v2 = shape.relativiseRender(client.level, shape.to, partialTick); + if (shape.fa == 0.0) + { + return; + } + final Vec3 v1 = shape.relativiseRender(client.level, shape.from, partialTick); + final Vec3 v2 = shape.relativiseRender(client.level, shape.to, partialTick); // consider using built-ins //DebugRenderer.drawBox(new Box(v1.x, v1.y, v1.z, v2.x, v2.y, v2.z), 0.5f, 0.5f, 0.5f, 0.5f);//shape.r, shape.g, shape.b, shape.a); drawBoxFaces(tessellator, bufferBuilder, - (float)(v1.x-cx-renderEpsilon), (float)(v1.y-cy-renderEpsilon), (float)(v1.z-cz-renderEpsilon), - (float)(v2.x-cx+renderEpsilon), (float)(v2.y-cy+renderEpsilon), (float)(v2.z-cz+renderEpsilon), - v1.x!=v2.x, v1.y!=v2.y, v1.z!=v2.z, + (float) (v1.x - cx - renderEpsilon), (float) (v1.y - cy - renderEpsilon), (float) (v1.z - cz - renderEpsilon), + (float) (v2.x - cx + renderEpsilon), (float) (v2.y - cy + renderEpsilon), (float) (v2.z - cz + renderEpsilon), + v1.x != v2.x, v1.y != v2.y, v1.z != v2.z, shape.fr, shape.fg, shape.fb, shape.fa ); } - } public static class RenderedLine extends RenderedShape { - public RenderedLine(Minecraft client, ShapeDispatcher.ExpiringShape shape) + public RenderedLine(final Minecraft client, final ShapeDispatcher.ExpiringShape shape) { - super(client, (ShapeDispatcher.Line)shape); + super(client, (ShapeDispatcher.Line) shape); } + @Override - public void renderLines(PoseStack matrices, Tesselator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) + public void renderLines(final PoseStack matrices, final Tesselator tessellator, final BufferBuilder bufferBuilder, final double cx, final double cy, final double cz, final float partialTick) { - Vec3 v1 = shape.relativiseRender(client.level, shape.from, partialTick); - Vec3 v2 = shape.relativiseRender(client.level, shape.to, partialTick); + final Vec3 v1 = shape.relativiseRender(client.level, shape.from, partialTick); + final Vec3 v2 = shape.relativiseRender(client.level, shape.to, partialTick); drawLine(tessellator, bufferBuilder, - (float)(v1.x-cx-renderEpsilon), (float)(v1.y-cy-renderEpsilon), (float)(v1.z-cz-renderEpsilon), - (float)(v2.x-cx+renderEpsilon), (float)(v2.y-cy+renderEpsilon), (float)(v2.z-cz+renderEpsilon), + (float) (v1.x - cx - renderEpsilon), (float) (v1.y - cy - renderEpsilon), (float) (v1.z - cz - renderEpsilon), + (float) (v2.x - cx + renderEpsilon), (float) (v2.y - cy + renderEpsilon), (float) (v2.z - cz + renderEpsilon), shape.r, shape.g, shape.b, shape.a ); } } + public static class RenderedPolyface extends RenderedShape { private static final VertexFormat.Mode[] faceIndices = new VertexFormat.Mode[]{ Mode.LINES, Mode.LINE_STRIP, Mode.DEBUG_LINES, Mode.DEBUG_LINE_STRIP, Mode.TRIANGLES, Mode.TRIANGLE_STRIP, Mode.TRIANGLE_FAN, Mode.QUADS}; - public RenderedPolyface(Minecraft client, ShapeDispatcher.ExpiringShape shape) + public RenderedPolyface(final Minecraft client, final ShapeDispatcher.ExpiringShape shape) { - super(client, (ShapeDispatcher.Polyface)shape); + super(client, (ShapeDispatcher.Polyface) shape); } + @Override - public void renderFaces(Tesselator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) - { - if(shape.fa==0){return;} + public void renderFaces(final Tesselator tessellator, final BufferBuilder bufferBuilder, final double cx, final double cy, final double cz, final float partialTick) + { + if (shape.fa == 0) + { + return; + } if (shape.doublesided) + { RenderSystem.disableCull(); + } else + { RenderSystem.enableCull(); - + } + bufferBuilder.begin(faceIndices[shape.mode], DefaultVertexFormat.POSITION_COLOR); - for(int i=0;i0;i-=2){ - vec=shape.vertex_list.get(i); - if(shape.relative.get(i)){ - vec=shape.relativiseRender(client.level, vec, partialTick); - } - builder.vertex(vec.x()-cx, vec.y()-cy, vec.z()-cz).color(shape.r, shape.g, shape.b, shape.a).endVertex(); + if (i == 0) + { + vec0 = vec; + } + builder.vertex(vec.x() - cx, vec.y() - cy, vec.z() - cz).color(shape.r, shape.g, shape.b, shape.a).endVertex(); + } + builder.vertex(vec0.x() - cx, vec0.y() - cy, vec0.z() - cz).color(shape.r, shape.g, shape.b, shape.a).endVertex(); + tessellator.end(); + if (shape.inneredges) + { + builder.begin(VertexFormat.Mode.DEBUG_LINES, DefaultVertexFormat.POSITION_COLOR); + for (int i = 1; i < shape.vertex_list.size() - 1; i++) + { + Vec3 vec = shape.vertex_list.get(i); + if (shape.relative.get(i)) + { + vec = shape.relativiseRender(client.level, vec, partialTick); } - if(shape.inneredges){ - for(i=2;i 0; i -= 2) + { + vec = shape.vertex_list.get(i); + if (shape.relative.get(i)) + { + vec = shape.relativiseRender(client.level, vec, partialTick); + } + builder.vertex(vec.x() - cx, vec.y() - cy, vec.z() - cz).color(shape.r, shape.g, shape.b, shape.a).endVertex(); + } + if (shape.inneredges) + { + for (i = 2; i < shape.vertex_list.size() - 1; i++) + { + vec = shape.vertex_list.get(i); + if (shape.relative.get(i)) + { + vec = shape.relativiseRender(client.level, vec, partialTick); } - tessellator.end(); - return; + builder.vertex(vec.x() - cx, vec.y() - cy, vec.z() - cz).color(shape.r, shape.g, shape.b, shape.a).endVertex(); } - if (shape.mode==4){ - builder.begin(VertexFormat.Mode.DEBUG_LINES, DefaultVertexFormat.POSITION_COLOR); - for (int i=0;i { - public RenderedSphere(Minecraft client, ShapeDispatcher.ExpiringShape shape) + public RenderedSphere(final Minecraft client, final ShapeDispatcher.ExpiringShape shape) { - super(client, (ShapeDispatcher.Sphere)shape); + super(client, (ShapeDispatcher.Sphere) shape); } + @Override - public void renderLines(PoseStack matrices, Tesselator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) + public void renderLines(final PoseStack matrices, final Tesselator tessellator, final BufferBuilder bufferBuilder, final double cx, final double cy, final double cz, final float partialTick) { - if (shape.a == 0.0) return; - Vec3 vc = shape.relativiseRender(client.level, shape.center, partialTick); + if (shape.a == 0.0) + { + return; + } + final Vec3 vc = shape.relativiseRender(client.level, shape.center, partialTick); drawSphereWireframe(tessellator, bufferBuilder, - (float)(vc.x-cx), (float)(vc.y-cy), (float)(vc.z-cz), - (float)(shape.radius+renderEpsilon), shape.subdivisions, + (float) (vc.x - cx), (float) (vc.y - cy), (float) (vc.z - cz), + (float) (shape.radius + renderEpsilon), shape.subdivisions, shape.r, shape.g, shape.b, shape.a); } + @Override - public void renderFaces(Tesselator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) + public void renderFaces(final Tesselator tessellator, final BufferBuilder bufferBuilder, final double cx, final double cy, final double cz, final float partialTick) { - if (shape.fa == 0.0) return; - Vec3 vc = shape.relativiseRender(client.level, shape.center, partialTick); + if (shape.fa == 0.0) + { + return; + } + final Vec3 vc = shape.relativiseRender(client.level, shape.center, partialTick); drawSphereFaces(tessellator, bufferBuilder, - (float)(vc.x-cx), (float)(vc.y-cy), (float)(vc.z-cz), - (float)(shape.radius+renderEpsilon), shape.subdivisions, + (float) (vc.x - cx), (float) (vc.y - cy), (float) (vc.z - cz), + (float) (shape.radius + renderEpsilon), shape.subdivisions, shape.fr, shape.fg, shape.fb, shape.fa); } } public static class RenderedCylinder extends RenderedShape { - public RenderedCylinder(Minecraft client, ShapeDispatcher.ExpiringShape shape) + public RenderedCylinder(final Minecraft client, final ShapeDispatcher.ExpiringShape shape) { - super(client, (ShapeDispatcher.Cylinder)shape); + super(client, (ShapeDispatcher.Cylinder) shape); } + @Override - public void renderLines(PoseStack matrices, Tesselator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) + public void renderLines(final PoseStack matrices, final Tesselator tessellator, final BufferBuilder bufferBuilder, final double cx, final double cy, final double cz, final float partialTick) { - if (shape.a == 0.0) return; - Vec3 vc = shape.relativiseRender(client.level, shape.center, partialTick); - double dir = Mth.sign(shape.height); + if (shape.a == 0.0) + { + return; + } + final Vec3 vc = shape.relativiseRender(client.level, shape.center, partialTick); + final double dir = Mth.sign(shape.height); drawCylinderWireframe(tessellator, bufferBuilder, (float) (vc.x - cx - dir * renderEpsilon), (float) (vc.y - cy - dir * renderEpsilon), (float) (vc.z - cz - dir * renderEpsilon), - (float) (shape.radius + renderEpsilon), (float) (shape.height + 2*dir*renderEpsilon), shape.axis, + (float) (shape.radius + renderEpsilon), (float) (shape.height + 2 * dir * renderEpsilon), shape.axis, shape.subdivisions, shape.radius == 0, shape.r, shape.g, shape.b, shape.a); } + @Override - public void renderFaces(Tesselator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) + public void renderFaces(final Tesselator tessellator, final BufferBuilder bufferBuilder, final double cx, final double cy, final double cz, final float partialTick) { - if (shape.fa == 0.0) return; - Vec3 vc = shape.relativiseRender(client.level, shape.center, partialTick); - double dir = Mth.sign(shape.height); + if (shape.fa == 0.0) + { + return; + } + final Vec3 vc = shape.relativiseRender(client.level, shape.center, partialTick); + final double dir = Mth.sign(shape.height); drawCylinderFaces(tessellator, bufferBuilder, (float) (vc.x - cx - dir * renderEpsilon), (float) (vc.y - cy - dir * renderEpsilon), (float) (vc.z - cz - dir * renderEpsilon), - (float) (shape.radius + renderEpsilon), (float) (shape.height + 2*dir*renderEpsilon), shape.axis, + (float) (shape.radius + renderEpsilon), (float) (shape.height + 2 * dir * renderEpsilon), shape.axis, shape.subdivisions, shape.radius == 0, shape.fr, shape.fg, shape.fb, shape.fa); } @@ -745,7 +882,8 @@ public void renderFaces(Tesselator tessellator, BufferBuilder bufferBuilder, dou // some raw shit - public static void drawLine(Tesselator tessellator, BufferBuilder builder, float x1, float y1, float z1, float x2, float y2, float z2, float red1, float grn1, float blu1, float alpha) { + public static void drawLine(final Tesselator tessellator, final BufferBuilder builder, final float x1, final float y1, final float z1, final float x2, final float y2, final float z2, final float red1, final float grn1, final float blu1, final float alpha) + { builder.begin(VertexFormat.Mode.DEBUG_LINES, DefaultVertexFormat.POSITION_COLOR); builder.vertex(x1, y1, z1).color(red1, grn1, blu1, alpha).endVertex(); builder.vertex(x2, y2, z2).color(red1, grn1, blu1, alpha).endVertex(); @@ -753,11 +891,11 @@ public static void drawLine(Tesselator tessellator, BufferBuilder builder, float } public static void drawBoxWireGLLines( - Tesselator tessellator, BufferBuilder builder, - float x1, float y1, float z1, - float x2, float y2, float z2, - boolean xthick, boolean ythick, boolean zthick, - float red1, float grn1, float blu1, float alpha, float red2, float grn2, float blu2) + final Tesselator tessellator, final BufferBuilder builder, + final float x1, final float y1, final float z1, + final float x2, final float y2, final float z2, + final boolean xthick, final boolean ythick, final boolean zthick, + final float red1, final float grn1, final float blu1, final float alpha, final float red2, final float grn2, final float blu2) { builder.begin(VertexFormat.Mode.DEBUG_LINES, DefaultVertexFormat.POSITION_COLOR); if (xthick) @@ -806,11 +944,11 @@ public static void drawBoxWireGLLines( } public static void drawBoxFaces( - Tesselator tessellator, BufferBuilder builder, - float x1, float y1, float z1, - float x2, float y2, float z2, - boolean xthick, boolean ythick, boolean zthick, - float red1, float grn1, float blu1, float alpha) + final Tesselator tessellator, final BufferBuilder builder, + final float x1, final float y1, final float z1, + final float x2, final float y2, final float z2, + final boolean xthick, final boolean ythick, final boolean zthick, + final float red1, final float grn1, final float blu1, final float alpha) { builder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); @@ -866,14 +1004,14 @@ public static void drawBoxFaces( tessellator.end(); } - public static void drawCylinderWireframe(Tesselator tessellator, BufferBuilder builder, - float cx, float cy, float cz, - float r, float h, Direction.Axis axis, int subd, boolean isFlat, - float red, float grn, float blu, float alpha) + public static void drawCylinderWireframe(final Tesselator tessellator, final BufferBuilder builder, + final float cx, final float cy, final float cz, + final float r, final float h, final Direction.Axis axis, final int subd, final boolean isFlat, + final float red, final float grn, final float blu, final float alpha) { - float step = (float)Math.PI / (subd/2); - int num_steps180 = (int)(Math.PI / step)+1; - int num_steps360 = (int)(2*Math.PI / step); + final float step = (float) Math.PI / (subd / 2); + final int num_steps180 = (int) (Math.PI / step) + 1; + final int num_steps360 = (int) (2 * Math.PI / step); int hsteps = 1; float hstep = 1.0f; if (!isFlat) @@ -886,14 +1024,14 @@ public static void drawCylinderWireframe(Tesselator tessellator, BufferBuilder b { for (int dh = 0; dh < hsteps; dh++) { - float hh = dh*hstep; + final float hh = dh * hstep; builder.begin(VertexFormat.Mode.DEBUG_LINE_STRIP, DefaultVertexFormat.POSITION_COLOR); // line loop to line strip - for (int i = 0; i <= num_steps360+1; i++) + for (int i = 0; i <= num_steps360 + 1; i++) { - float theta = step * i; - float x = r * Mth.cos(theta); - float y = hh; - float z = r * Mth.sin(theta); + final float theta = step * i; + final float x = r * Mth.cos(theta); + final float y = hh; + final float z = r * Mth.sin(theta); builder.vertex(x + cx, y + cy, z + cz).color(red, grn, blu, alpha).endVertex(); } tessellator.end(); @@ -904,10 +1042,10 @@ public static void drawCylinderWireframe(Tesselator tessellator, BufferBuilder b for (int i = 0; i <= num_steps180; i++) { builder.begin(VertexFormat.Mode.DEBUG_LINE_STRIP, DefaultVertexFormat.POSITION_COLOR); // line loop to line strip - float theta = step * i; - float x = r * Mth.cos(theta); + final float theta = step * i; + final float x = r * Mth.cos(theta); - float z = r * Mth.sin(theta); + final float z = r * Mth.sin(theta); builder.vertex(cx - x, cy + 0, cz + z).color(red, grn, blu, alpha).endVertex(); builder.vertex(cx + x, cy + 0, cz - z).color(red, grn, blu, alpha).endVertex(); @@ -922,9 +1060,9 @@ public static void drawCylinderWireframe(Tesselator tessellator, BufferBuilder b builder.begin(VertexFormat.Mode.DEBUG_LINES, DefaultVertexFormat.POSITION_COLOR); for (int i = 0; i <= num_steps180; i++) { - float theta = step * i; - float x = r * Mth.cos(theta); - float z = r * Mth.sin(theta); + final float theta = step * i; + final float x = r * Mth.cos(theta); + final float z = r * Mth.sin(theta); builder.vertex(cx - x, cy, cz + z).color(red, grn, blu, alpha).endVertex(); builder.vertex(cx + x, cy, cz - z).color(red, grn, blu, alpha).endVertex(); } @@ -936,14 +1074,14 @@ else if (axis == Direction.Axis.X) { for (int dh = 0; dh < hsteps; dh++) { - float hh = dh * hstep; + final float hh = dh * hstep; builder.begin(VertexFormat.Mode.DEBUG_LINE_STRIP, DefaultVertexFormat.POSITION_COLOR); // line loop to line strip for (int i = 0; i <= num_steps360; i++) { - float theta = step * i; - float z = r * Mth.cos(theta); - float x = hh; - float y = r * Mth.sin(theta); + final float theta = step * i; + final float z = r * Mth.cos(theta); + final float x = hh; + final float y = r * Mth.sin(theta); builder.vertex(x + cx, y + cy, z + cz).color(red, grn, blu, alpha).endVertex(); } tessellator.end(); @@ -954,10 +1092,10 @@ else if (axis == Direction.Axis.X) for (int i = 0; i <= num_steps180; i++) { builder.begin(VertexFormat.Mode.DEBUG_LINE_STRIP, DefaultVertexFormat.POSITION_COLOR); // line loop to line strip - float theta = step * i; - float y = r * Mth.cos(theta); + final float theta = step * i; + final float y = r * Mth.cos(theta); - float z = r * Mth.sin(theta); + final float z = r * Mth.sin(theta); builder.vertex(cx + 0, cy - y, cz + z).color(red, grn, blu, alpha).endVertex(); builder.vertex(cx + 0, cy + y, cz - z).color(red, grn, blu, alpha).endVertex(); @@ -971,9 +1109,9 @@ else if (axis == Direction.Axis.X) builder.begin(VertexFormat.Mode.DEBUG_LINES, DefaultVertexFormat.POSITION_COLOR); for (int i = 0; i <= num_steps180; i++) { - float theta = step * i; - float y = r * Mth.cos(theta); - float z = r * Mth.sin(theta); + final float theta = step * i; + final float y = r * Mth.cos(theta); + final float z = r * Mth.sin(theta); builder.vertex(cx, cy - y, cz + z).color(red, grn, blu, alpha).endVertex(); builder.vertex(cx, cy + y, cz - z).color(red, grn, blu, alpha).endVertex(); } @@ -984,14 +1122,14 @@ else if (axis == Direction.Axis.Z) { for (int dh = 0; dh < hsteps; dh++) { - float hh = dh * hstep; + final float hh = dh * hstep; builder.begin(VertexFormat.Mode.DEBUG_LINE_STRIP, DefaultVertexFormat.POSITION_COLOR); // line loop to line strip for (int i = 0; i <= num_steps360; i++) { - float theta = step * i; - float y = r * Mth.cos(theta); - float z = hh; - float x = r * Mth.sin(theta); + final float theta = step * i; + final float y = r * Mth.cos(theta); + final float z = hh; + final float x = r * Mth.sin(theta); builder.vertex(x + cx, y + cy, z + cz).color(red, grn, blu, alpha).endVertex(); } tessellator.end(); @@ -1001,10 +1139,10 @@ else if (axis == Direction.Axis.Z) for (int i = 0; i <= num_steps180; i++) { builder.begin(VertexFormat.Mode.DEBUG_LINE_STRIP, DefaultVertexFormat.POSITION_COLOR); // line loop to line strip - float theta = step * i; - float x = r * Mth.cos(theta); + final float theta = step * i; + final float x = r * Mth.cos(theta); - float y = r * Mth.sin(theta); + final float y = r * Mth.sin(theta); builder.vertex(cx + x, cy - y, cz + 0).color(red, grn, blu, alpha).endVertex(); builder.vertex(cx - x, cy + y, cz + 0).color(red, grn, blu, alpha).endVertex(); @@ -1018,9 +1156,9 @@ else if (axis == Direction.Axis.Z) builder.begin(VertexFormat.Mode.DEBUG_LINES, DefaultVertexFormat.POSITION_COLOR); for (int i = 0; i <= num_steps180; i++) { - float theta = step * i; - float x = r * Mth.cos(theta); - float y = r * Mth.sin(theta); + final float theta = step * i; + final float x = r * Mth.cos(theta); + final float y = r * Mth.sin(theta); builder.vertex(cx + x, cy - y, cz).color(red, grn, blu, alpha).endVertex(); builder.vertex(cx - x, cy + y, cz).color(red, grn, blu, alpha).endVertex(); } @@ -1030,14 +1168,14 @@ else if (axis == Direction.Axis.Z) } } - public static void drawCylinderFaces(Tesselator tessellator, BufferBuilder builder, - float cx, float cy, float cz, - float r, float h, Direction.Axis axis, int subd, boolean isFlat, - float red, float grn, float blu, float alpha) + public static void drawCylinderFaces(final Tesselator tessellator, final BufferBuilder builder, + final float cx, final float cy, final float cz, + final float r, final float h, final Direction.Axis axis, final int subd, final boolean isFlat, + final float red, final float grn, final float blu, final float alpha) { - float step = (float)Math.PI / (subd/2); - int num_steps180 = (int)(Math.PI / step)+1; - int num_steps360 = (int)(2*Math.PI / step)+1; + final float step = (float) Math.PI / (subd / 2); + //final int num_steps180 = (int) (Math.PI / step) + 1; + final int num_steps360 = (int) (2 * Math.PI / step) + 1; if (axis == Direction.Axis.Y) { @@ -1046,22 +1184,22 @@ public static void drawCylinderFaces(Tesselator tessellator, BufferBuilder build builder.vertex(cx, cy, cz).color(red, grn, blu, alpha).endVertex(); for (int i = 0; i <= num_steps360; i++) { - float theta = step * i; - float x = r * Mth.cos(theta); - float z = r * Mth.sin(theta); + final float theta = step * i; + final float x = r * Mth.cos(theta); + final float z = r * Mth.sin(theta); builder.vertex(x + cx, cy, z + cz).color(red, grn, blu, alpha).endVertex(); } tessellator.end(); if (!isFlat) { builder.begin(VertexFormat.Mode.TRIANGLE_FAN, DefaultVertexFormat.POSITION_COLOR); - builder.vertex(cx, cy+h, cz).color(red, grn, blu, alpha).endVertex(); + builder.vertex(cx, cy + h, cz).color(red, grn, blu, alpha).endVertex(); for (int i = 0; i <= num_steps360; i++) { - float theta = step * i; - float x = r * Mth.cos(theta); - float z = r * Mth.sin(theta); - builder.vertex(x + cx, cy+h, z + cz).color(red, grn, blu, alpha).endVertex(); + final float theta = step * i; + final float x = r * Mth.cos(theta); + final float z = r * Mth.sin(theta); + builder.vertex(x + cx, cy + h, z + cz).color(red, grn, blu, alpha).endVertex(); } tessellator.end(); @@ -1070,9 +1208,9 @@ public static void drawCylinderFaces(Tesselator tessellator, BufferBuilder build float zp = r * 0; for (int i = 1; i <= num_steps360; i++) { - float theta = step * i; - float x = r * Mth.cos(theta); - float z = r * Mth.sin(theta); + final float theta = step * i; + final float x = r * Mth.cos(theta); + final float z = r * Mth.sin(theta); builder.vertex(cx + xp, cy + 0, cz + zp).color(red, grn, blu, alpha).endVertex(); builder.vertex(cx + xp, cy + h, cz + zp).color(red, grn, blu, alpha).endVertex(); builder.vertex(cx + x, cy + h, cz + z).color(red, grn, blu, alpha).endVertex(); @@ -1090,22 +1228,22 @@ else if (axis == Direction.Axis.X) builder.vertex(cx, cy, cz).color(red, grn, blu, alpha).endVertex(); for (int i = 0; i <= num_steps360; i++) { - float theta = step * i; - float y = r * Mth.cos(theta); - float z = r * Mth.sin(theta); + final float theta = step * i; + final float y = r * Mth.cos(theta); + final float z = r * Mth.sin(theta); builder.vertex(cx, cy + y, z + cz).color(red, grn, blu, alpha).endVertex(); } tessellator.end(); if (!isFlat) { builder.begin(VertexFormat.Mode.TRIANGLE_FAN, DefaultVertexFormat.POSITION_COLOR); - builder.vertex(cx+h, cy, cz).color(red, grn, blu, alpha).endVertex(); + builder.vertex(cx + h, cy, cz).color(red, grn, blu, alpha).endVertex(); for (int i = 0; i <= num_steps360; i++) { - float theta = step * i; - float y = r * Mth.cos(theta); - float z = r * Mth.sin(theta); - builder.vertex(cx+h, cy + y, cz + z).color(red, grn, blu, alpha).endVertex(); + final float theta = step * i; + final float y = r * Mth.cos(theta); + final float z = r * Mth.sin(theta); + builder.vertex(cx + h, cy + y, cz + z).color(red, grn, blu, alpha).endVertex(); } tessellator.end(); @@ -1114,9 +1252,9 @@ else if (axis == Direction.Axis.X) float zp = r * 0; for (int i = 1; i <= num_steps360; i++) { - float theta = step * i; - float y = r * Mth.cos(theta); - float z = r * Mth.sin(theta); + final float theta = step * i; + final float y = r * Mth.cos(theta); + final float z = r * Mth.sin(theta); builder.vertex(cx + 0, cy + yp, cz + zp).color(red, grn, blu, alpha).endVertex(); builder.vertex(cx + h, cy + yp, cz + zp).color(red, grn, blu, alpha).endVertex(); builder.vertex(cx + h, cy + y, cz + z).color(red, grn, blu, alpha).endVertex(); @@ -1133,22 +1271,22 @@ else if (axis == Direction.Axis.Z) builder.vertex(cx, cy, cz).color(red, grn, blu, alpha).endVertex(); for (int i = 0; i <= num_steps360; i++) { - float theta = step * i; - float x = r * Mth.cos(theta); - float y = r * Mth.sin(theta); - builder.vertex(x + cx, cy+y, cz).color(red, grn, blu, alpha).endVertex(); + final float theta = step * i; + final float x = r * Mth.cos(theta); + final float y = r * Mth.sin(theta); + builder.vertex(x + cx, cy + y, cz).color(red, grn, blu, alpha).endVertex(); } tessellator.end(); if (!isFlat) { builder.begin(VertexFormat.Mode.TRIANGLE_FAN, DefaultVertexFormat.POSITION_COLOR); - builder.vertex(cx, cy, cz+h).color(red, grn, blu, alpha).endVertex(); + builder.vertex(cx, cy, cz + h).color(red, grn, blu, alpha).endVertex(); for (int i = 0; i <= num_steps360; i++) { - float theta = step * i; - float x = r * Mth.cos(theta); - float y = r * Mth.sin(theta); - builder.vertex(x + cx, cy+y, cz+h).color(red, grn, blu, alpha).endVertex(); + final float theta = step * i; + final float x = r * Mth.cos(theta); + final float y = r * Mth.sin(theta); + builder.vertex(x + cx, cy + y, cz + h).color(red, grn, blu, alpha).endVertex(); } tessellator.end(); @@ -1157,9 +1295,9 @@ else if (axis == Direction.Axis.Z) float yp = 0; for (int i = 1; i <= num_steps360; i++) { - float theta = step * i; - float x = r * Mth.cos(theta); - float y = r * Mth.sin(theta); + final float theta = step * i; + final float x = r * Mth.cos(theta); + final float y = r * Mth.sin(theta); builder.vertex(cx + xp, cy + yp, cz + 0).color(red, grn, blu, alpha).endVertex(); builder.vertex(cx + xp, cy + yp, cz + h).color(red, grn, blu, alpha).endVertex(); builder.vertex(cx + x, cy + y, cz + h).color(red, grn, blu, alpha).endVertex(); @@ -1172,59 +1310,59 @@ else if (axis == Direction.Axis.Z) } } - public static void drawSphereWireframe(Tesselator tessellator, BufferBuilder builder, - float cx, float cy, float cz, - float r, int subd, - float red, float grn, float blu, float alpha) + public static void drawSphereWireframe(final Tesselator tessellator, final BufferBuilder builder, + final float cx, final float cy, final float cz, + final float r, final int subd, + final float red, final float grn, final float blu, final float alpha) { - float step = (float)Math.PI / (subd/2); - int num_steps180 = (int)(Math.PI / step)+1; - int num_steps360 = (int)(2*Math.PI / step)+1; + final float step = (float) Math.PI / (subd / 2); + final int num_steps180 = (int) (Math.PI / step) + 1; + final int num_steps360 = (int) (2 * Math.PI / step) + 1; for (int i = 0; i <= num_steps360; i++) { builder.begin(VertexFormat.Mode.DEBUG_LINE_STRIP, DefaultVertexFormat.POSITION_COLOR); - float theta = step * i ; + final float theta = step * i; for (int j = 0; j <= num_steps180; j++) { - float phi = step * j ; - float x = r * Mth.sin(phi) * Mth.cos(theta); - float z = r * Mth.sin(phi) * Mth.sin(theta); - float y = r * Mth.cos(phi); - builder.vertex(x+cx, y+cy, z+cz).color(red, grn, blu, alpha).endVertex(); + final float phi = step * j; + final float x = r * Mth.sin(phi) * Mth.cos(theta); + final float z = r * Mth.sin(phi) * Mth.sin(theta); + final float y = r * Mth.cos(phi); + builder.vertex(x + cx, y + cy, z + cz).color(red, grn, blu, alpha).endVertex(); } tessellator.end(); } for (int j = 0; j <= num_steps180; j++) { builder.begin(VertexFormat.Mode.DEBUG_LINE_STRIP, DefaultVertexFormat.POSITION_COLOR); // line loop to line strip - float phi = step * j ; + final float phi = step * j; for (int i = 0; i <= num_steps360; i++) { - float theta = step * i; - float x = r * Mth.sin(phi) * Mth.cos(theta); - float z = r * Mth.sin(phi) * Mth.sin(theta); - float y = r * Mth.cos(phi); - builder.vertex(x+cx, y+cy, z+cz).color(red, grn, blu, alpha).endVertex(); + final float theta = step * i; + final float x = r * Mth.sin(phi) * Mth.cos(theta); + final float z = r * Mth.sin(phi) * Mth.sin(theta); + final float y = r * Mth.cos(phi); + builder.vertex(x + cx, y + cy, z + cz).color(red, grn, blu, alpha).endVertex(); } tessellator.end(); } } - public static void drawSphereFaces(Tesselator tessellator, BufferBuilder builder, - float cx, float cy, float cz, - float r, int subd, - float red, float grn, float blu, float alpha) + public static void drawSphereFaces(final Tesselator tessellator, final BufferBuilder builder, + final float cx, final float cy, final float cz, + final float r, final int subd, + final float red, final float grn, final float blu, final float alpha) { - float step = (float)Math.PI / (subd/2); - int num_steps180 = (int)(Math.PI / step)+1; - int num_steps360 = (int)(2*Math.PI / step); + final float step = (float) Math.PI / (subd / 2); + final int num_steps180 = (int) (Math.PI / step) + 1; + final int num_steps360 = (int) (2 * Math.PI / step); for (int i = 0; i <= num_steps360; i++) { - float theta = i * step; - float thetaprime = theta+step; + final float theta = i * step; + final float thetaprime = theta + step; builder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); // quad strip to quads float xb = 0; float zb = 0; @@ -1233,12 +1371,12 @@ public static void drawSphereFaces(Tesselator tessellator, BufferBuilder builder float yp = r; for (int j = 0; j <= num_steps180; j++) { - float phi = j * step; - float x = r * Mth.sin(phi) * Mth.cos(theta); - float z = r * Mth.sin(phi) * Mth.sin(theta); - float y = r * Mth.cos(phi); - float xp = r * Mth.sin(phi) * Mth.cos(thetaprime); - float zp = r * Mth.sin(phi) * Mth.sin(thetaprime); + final float phi = j * step; + final float x = r * Mth.sin(phi) * Mth.cos(theta); + final float z = r * Mth.sin(phi) * Mth.sin(theta); + final float y = r * Mth.cos(phi); + final float xp = r * Mth.sin(phi) * Mth.cos(thetaprime); + final float zp = r * Mth.sin(phi) * Mth.sin(thetaprime); builder.vertex(xb + cx, yp + cy, zb + cz).color(red, grn, blu, alpha).endVertex(); builder.vertex(xbp + cx, yp + cy, zbp + cz).color(red, grn, blu, alpha).endVertex(); builder.vertex(xp + cx, y + cy, zp + cz).color(red, grn, blu, alpha).endVertex(); diff --git a/src/main/java/carpet/script/utils/SimplexNoiseSampler.java b/src/main/java/carpet/script/utils/SimplexNoiseSampler.java index b9832c80df..c56f955a26 100644 --- a/src/main/java/carpet/script/utils/SimplexNoiseSampler.java +++ b/src/main/java/carpet/script/utils/SimplexNoiseSampler.java @@ -6,7 +6,8 @@ import java.util.Random; // extracted from import net.minecraft.util.math.noise.SimplexNoiseSampler -public class SimplexNoiseSampler extends PerlinNoiseSampler { +public class SimplexNoiseSampler extends PerlinNoiseSampler +{ private static final double sqrt3 = Math.sqrt(3.0D); private static final double SKEW_FACTOR_2D; private static final double UNSKEW_FACTOR_2D; @@ -14,23 +15,30 @@ public class SimplexNoiseSampler extends PerlinNoiseSampler { public static SimplexNoiseSampler instance = new SimplexNoiseSampler(new Random(0)); public static Map samplers = new Long2ObjectOpenHashMap<>(); - public static SimplexNoiseSampler getSimplex(long aLong) + public static SimplexNoiseSampler getSimplex(final long aLong) { if (samplers.size() > 256) + { samplers.clear(); + } return samplers.computeIfAbsent(aLong, seed -> new SimplexNoiseSampler(new Random(seed))); } - public SimplexNoiseSampler(Random random) { + public SimplexNoiseSampler(final Random random) + { super(random); } - private double grad(int hash, double x, double y, double z, double d) { + private double grad(final int hash, final double x, final double y, final double z, final double d) + { double e = d - x * x - y * y - z * z; - double g; - if (e < 0.0D) { + final double g; + if (e < 0.0D) + { g = 0.0D; - } else { + } + else + { e *= e; g = e * e * PerlinNoiseSampler.dot3d(PerlinNoiseSampler.gradients3d[hash], x, y, z); } @@ -39,83 +47,94 @@ private double grad(int hash, double x, double y, double z, double d) { } @Override - public double sample2d(double x, double y) { - x = x/2; - y = y/2; - double d = (x + y) * SKEW_FACTOR_2D; - int i = PerlinNoiseSampler.floor(x + d); - int j = PerlinNoiseSampler.floor(y + d); - double e = (double)(i + j) * UNSKEW_FACTOR_2D; - double f = (double)i - e; - double g = (double)j - e; - double h = x - f; - double k = y - g; - byte n; - byte o; - if (h > k) { + public double sample2d(double x, double y) + { + x = x / 2; + y = y / 2; + final double d = (x + y) * SKEW_FACTOR_2D; + final int i = PerlinNoiseSampler.floor(x + d); + final int j = PerlinNoiseSampler.floor(y + d); + final double e = (i + j) * UNSKEW_FACTOR_2D; + final double f = i - e; + final double g = j - e; + final double h = x - f; + final double k = y - g; + final byte n; + final byte o; + if (h > k) + { n = 1; o = 0; - } else { + } + else + { n = 0; o = 1; } - double p = h - (double)n + UNSKEW_FACTOR_2D; - double q = k - (double)o + UNSKEW_FACTOR_2D; - double r = h - 1.0D + 2.0D * UNSKEW_FACTOR_2D; - double s = k - 1.0D + 2.0D * UNSKEW_FACTOR_2D; - int t = i & 255; - int u = j & 255; - int v = this.getGradient(t + this.getGradient(u)) % 12; - int w = this.getGradient(t + n + this.getGradient(u + o)) % 12; - int z = this.getGradient(t + 1 + this.getGradient(u + 1)) % 12; - double aa = this.grad(v, h, k, 0.0D, 0.5D); - double ab = this.grad(w, p, q, 0.0D, 0.5D); - double ac = this.grad(z, r, s, 0.0D, 0.5D); + final double p = h - n + UNSKEW_FACTOR_2D; + final double q = k - o + UNSKEW_FACTOR_2D; + final double r = h - 1.0D + 2.0D * UNSKEW_FACTOR_2D; + final double s = k - 1.0D + 2.0D * UNSKEW_FACTOR_2D; + final int t = i & 255; + final int u = j & 255; + final int v = this.getGradient(t + this.getGradient(u)) % 12; + final int w = this.getGradient(t + n + this.getGradient(u + o)) % 12; + final int z = this.getGradient(t + 1 + this.getGradient(u + 1)) % 12; + final double aa = this.grad(v, h, k, 0.0D, 0.5D); + final double ab = this.grad(w, p, q, 0.0D, 0.5D); + final double ac = this.grad(z, r, s, 0.0D, 0.5D); //return 70.0D * (aa + ab + ac); - return 35.0D * (aa + ab + ac)+0.5; + return 35.0D * (aa + ab + ac) + 0.5; } @Override - public double sample3d(double d, double e, double f) { - d = d/2; - e = e/2; - f = f/2; - double g = 0.3333333333333333D; - double h = (d + e + f) * 0.3333333333333333D; - int i = floor(d + h); - int j = floor(e + h); - int k = floor(f + h); - double l = 0.16666666666666666D; - double m = (double)(i + j + k) * 0.16666666666666666D; - double n = (double)i - m; - double o = (double)j - m; - double p = (double)k - m; - double q = d - n; - double r = e - o; - double s = f - p; - byte z; - byte aa; - byte ab; - byte ac; - byte ad; - byte bc; - if (q >= r) { - if (r >= s) { + public double sample3d(double d, double e, double f) + { + d = d / 2; + e = e / 2; + f = f / 2; + //final double g = 0.3333333333333333D; + final double h = (d + e + f) * 0.3333333333333333D; + final int i = floor(d + h); + final int j = floor(e + h); + final int k = floor(f + h); + //final double l = 0.16666666666666666D; + final double m = (i + j + k) * 0.16666666666666666D; + final double n = i - m; + final double o = j - m; + final double p = k - m; + final double q = d - n; + final double r = e - o; + final double s = f - p; + final byte z; + final byte aa; + final byte ab; + final byte ac; + final byte ad; + final byte bc; + if (q >= r) + { + if (r >= s) + { z = 1; aa = 0; ab = 0; ac = 1; ad = 1; bc = 0; - } else if (q >= s) { + } + else if (q >= s) + { z = 1; aa = 0; ab = 0; ac = 1; ad = 0; bc = 1; - } else { + } + else + { z = 0; aa = 0; ab = 1; @@ -123,21 +142,27 @@ public double sample3d(double d, double e, double f) { ad = 0; bc = 1; } - } else if (r < s) { + } + else if (r < s) + { z = 0; aa = 0; ab = 1; ac = 0; ad = 1; bc = 1; - } else if (q < s) { + } + else if (q < s) + { z = 0; aa = 1; ab = 0; ac = 0; ad = 1; bc = 1; - } else { + } + else + { z = 0; aa = 1; ab = 0; @@ -146,30 +171,31 @@ public double sample3d(double d, double e, double f) { bc = 0; } - double bd = q - (double)z + 0.16666666666666666D; - double be = r - (double)aa + 0.16666666666666666D; - double bf = s - (double)ab + 0.16666666666666666D; - double bg = q - (double)ac + 0.3333333333333333D; - double bh = r - (double)ad + 0.3333333333333333D; - double bi = s - (double)bc + 0.3333333333333333D; - double bj = q - 1.0D + 0.5D; - double bk = r - 1.0D + 0.5D; - double bl = s - 1.0D + 0.5D; - int bm = i & 255; - int bn = j & 255; - int bo = k & 255; - int bp = this.getGradient(bm + this.getGradient(bn + this.getGradient(bo))) % 12; - int bq = this.getGradient(bm + z + this.getGradient(bn + aa + this.getGradient(bo + ab))) % 12; - int br = this.getGradient(bm + ac + this.getGradient(bn + ad + this.getGradient(bo + bc))) % 12; - int bs = this.getGradient(bm + 1 + this.getGradient(bn + 1 + this.getGradient(bo + 1))) % 12; - double bt = this.grad(bp, q, r, s, 0.6D); - double bu = this.grad(bq, bd, be, bf, 0.6D); - double bv = this.grad(br, bg, bh, bi, 0.6D); - double bw = this.grad(bs, bj, bk, bl, 0.6D); + final double bd = q - z + 0.16666666666666666D; + final double be = r - aa + 0.16666666666666666D; + final double bf = s - ab + 0.16666666666666666D; + final double bg = q - ac + 0.3333333333333333D; + final double bh = r - ad + 0.3333333333333333D; + final double bi = s - bc + 0.3333333333333333D; + final double bj = q - 1.0D + 0.5D; + final double bk = r - 1.0D + 0.5D; + final double bl = s - 1.0D + 0.5D; + final int bm = i & 255; + final int bn = j & 255; + final int bo = k & 255; + final int bp = this.getGradient(bm + this.getGradient(bn + this.getGradient(bo))) % 12; + final int bq = this.getGradient(bm + z + this.getGradient(bn + aa + this.getGradient(bo + ab))) % 12; + final int br = this.getGradient(bm + ac + this.getGradient(bn + ad + this.getGradient(bo + bc))) % 12; + final int bs = this.getGradient(bm + 1 + this.getGradient(bn + 1 + this.getGradient(bo + 1))) % 12; + final double bt = this.grad(bp, q, r, s, 0.6D); + final double bu = this.grad(bq, bd, be, bf, 0.6D); + final double bv = this.grad(br, bg, bh, bi, 0.6D); + final double bw = this.grad(bs, bj, bk, bl, 0.6D); return 16.0D * (bt + bu + bv + bw) + 0.5; } - static { + static + { SKEW_FACTOR_2D = 0.5D * (sqrt3 - 1.0D); UNSKEW_FACTOR_2D = (3.0D - sqrt3) / 6.0D; } diff --git a/src/main/java/carpet/script/utils/SnoopyCommandSource.java b/src/main/java/carpet/script/utils/SnoopyCommandSource.java index 9e7709844e..03f5bec3bf 100644 --- a/src/main/java/carpet/script/utils/SnoopyCommandSource.java +++ b/src/main/java/carpet/script/utils/SnoopyCommandSource.java @@ -40,11 +40,12 @@ public class SnoopyCommandSource extends CommandSourceStack private final List chatOutput; private final CommandSigningContext signingContext; - public SnoopyCommandSource(CommandSourceStack original, Component[] error, List chatOutput) + public SnoopyCommandSource(final CommandSourceStack original, final Component[] error, final List chatOutput) { 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, CommandSigningContext.ANONYMOUS, TaskChainer.immediate(original.getServer())); + (ctx, succ, res) -> { + }, EntityAnchorArgument.Anchor.FEET, CommandSigningContext.ANONYMOUS, TaskChainer.immediate(original.getServer())); this.output = CommandSource.NULL; this.position = original.getPosition(); this.world = original.getLevel(); @@ -53,7 +54,8 @@ public SnoopyCommandSource(CommandSourceStack original, Component[] error, List< this.name = original.getDisplayName(); this.server = original.getServer(); this.entity = original.getEntity(); - this.resultConsumer = (ctx, succ, res) -> { }; + this.resultConsumer = (ctx, succ, res) -> { + }; this.entityAnchor = original.getAnchor(); this.rotation = original.getRotation(); this.error = error; @@ -61,20 +63,22 @@ public SnoopyCommandSource(CommandSourceStack original, Component[] error, List< this.signingContext = original.getSigningContext(); } - public SnoopyCommandSource(ServerPlayer player, Component[] error, List output) { + public SnoopyCommandSource(final ServerPlayer player, final Component[] error, final List output) + { super(player, player.position(), player.getRotationVector(), - player.level instanceof ServerLevel ? (ServerLevel) player.level : null, + player.level instanceof final ServerLevel serverLevel ? serverLevel : null, player.server.getProfilePermissions(player.getGameProfile()), player.getName().getString(), player.getDisplayName(), player.level.getServer(), player); this.output = player; this.position = player.position(); - this.world = player.level instanceof ServerLevel ? (ServerLevel) player.level : null; + this.world = player.level instanceof final ServerLevel serverLevel ? serverLevel : null; this.level = player.server.getProfilePermissions(player.getGameProfile()); this.simpleName = player.getName().getString(); this.name = player.getDisplayName(); this.server = player.level.getServer(); this.entity = player; - this.resultConsumer = (ctx, succ, res) -> { }; + this.resultConsumer = (ctx, succ, res) -> { + }; this.entityAnchor = EntityAnchorArgument.Anchor.FEET; this.rotation = player.getRotationVector(); // not a client call really this.error = error; @@ -82,9 +86,10 @@ public SnoopyCommandSource(ServerPlayer player, Component[] error, List consumer, EntityAnchorArgument.Anchor entityAnchor, CommandSigningContext context, - Component[] error, List chatOutput - ) { + private SnoopyCommandSource(final CommandSource output, final Vec3 pos, final Vec2 rot, final ServerLevel world, final int level, final String simpleName, final Component name, final MinecraftServer server, @Nullable final Entity entity, final ResultConsumer consumer, final EntityAnchorArgument.Anchor entityAnchor, final CommandSigningContext context, + final Component[] error, final List chatOutput + ) + { super(output, pos, rot, world, level, simpleName, name, server, entity, false, consumer, entityAnchor, context, TaskChainer.immediate(server)); @@ -105,33 +110,33 @@ private SnoopyCommandSource(CommandSource output, Vec3 pos, Vec2 rot, ServerLeve } @Override - public CommandSourceStack withEntity(Entity entity) + public CommandSourceStack withEntity(final Entity entity) { return new SnoopyCommandSource(output, position, rotation, world, level, entity.getName().getString(), entity.getDisplayName(), server, entity, resultConsumer, entityAnchor, signingContext, error, chatOutput); } @Override - public CommandSourceStack withPosition(Vec3 position) + public CommandSourceStack withPosition(final Vec3 position) { return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, resultConsumer, entityAnchor, signingContext, error, chatOutput); } @Override - public CommandSourceStack withRotation(Vec2 rotation) + public CommandSourceStack withRotation(final Vec2 rotation) { return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, resultConsumer, entityAnchor, signingContext, error, chatOutput); } @Override - public CommandSourceStack withCallback(ResultConsumer consumer) + public CommandSourceStack withCallback(final ResultConsumer consumer) { return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, consumer, entityAnchor, signingContext, error, chatOutput); } @Override - public CommandSourceStack withCallback(ResultConsumer consumer, BinaryOperator> binaryOperator) + public CommandSourceStack withCallback(final ResultConsumer consumer, final BinaryOperator> binaryOperator) { - ResultConsumer resultConsumer = binaryOperator.apply(this.resultConsumer, consumer); + final ResultConsumer resultConsumer = binaryOperator.apply(this.resultConsumer, consumer); return this.withCallback(resultConsumer); } @@ -140,56 +145,58 @@ public CommandSourceStack withCallback(ResultConsumer consum //public ServerCommandSource withSilent() { return this; } @Override - public CommandSourceStack withPermission(int level) + public CommandSourceStack withPermission(final int level) { return this; } @Override - public CommandSourceStack withMaximumPermission(int level) + public CommandSourceStack withMaximumPermission(final int level) { return this; } @Override - public CommandSourceStack withAnchor(EntityAnchorArgument.Anchor anchor) + public CommandSourceStack withAnchor(final EntityAnchorArgument.Anchor anchor) { return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, resultConsumer, anchor, signingContext, error, chatOutput); } @Override - public CommandSourceStack withSigningContext(CommandSigningContext commandSigningContext) { + public CommandSourceStack withSigningContext(final CommandSigningContext commandSigningContext) + { return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, resultConsumer, entityAnchor, commandSigningContext, error, chatOutput); } @Override - public CommandSourceStack withLevel(ServerLevel world) + public CommandSourceStack withLevel(final ServerLevel world) { - double d = DimensionType.getTeleportationScale(this.world.dimensionType(), world.dimensionType()); - Vec3 position = new Vec3(this.position.x * d, this.position.y, this.position.z * d); + final double d = DimensionType.getTeleportationScale(this.world.dimensionType(), world.dimensionType()); + final 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, signingContext, error, chatOutput); } @Override - public CommandSourceStack facing(Vec3 position) - { - 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 = Mth.wrapDegrees((float)(-(Mth.atan2(e, g) * 57.2957763671875D))); - float i = Mth.wrapDegrees((float)(Mth.atan2(f, d) * 57.2957763671875D) - 90.0F); + public CommandSourceStack facing(final Vec3 position) + { + final Vec3 vec3d = this.entityAnchor.apply(this); + final double d = position.x - vec3d.x; + final double e = position.y - vec3d.y; + final double f = position.z - vec3d.z; + final double g = Math.sqrt(d * d + f * f); + final float h = Mth.wrapDegrees((float) (-(Mth.atan2(e, g) * 57.2957763671875D))); + final float i = Mth.wrapDegrees((float) (Mth.atan2(f, d) * 57.2957763671875D) - 90.0F); return this.withRotation(new Vec2(h, i)); } @Override - public void sendFailure(Component message) + public void sendFailure(final Component message) { error[0] = message; } + @Override - public void sendSuccess(Component message, boolean broadcastToOps) + public void sendSuccess(final Component message, final boolean broadcastToOps) { chatOutput.add(message); } diff --git a/src/main/java/carpet/script/utils/SystemInfo.java b/src/main/java/carpet/script/utils/SystemInfo.java index 02cb4ebc2e..dabf724094 100644 --- a/src/main/java/carpet/script/utils/SystemInfo.java +++ b/src/main/java/carpet/script/utils/SystemInfo.java @@ -25,6 +25,7 @@ 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; @@ -36,15 +37,17 @@ import java.util.Objects; import java.util.function.Function; -public class SystemInfo { - private static final Map> options = new HashMap<>(){{ +public class SystemInfo +{ + private static final Map> options = new HashMap<>() + {{ put("app_name", c -> { - String name = c.host.getName(); - return name == null?Value.NULL:new StringValue(name); + final String name = c.host.getName(); + return name == null ? Value.NULL : new StringValue(name); }); - put("app_list", c -> ListValue.wrap(((CarpetScriptHost)c.host).scriptServer().modules.keySet().stream().filter(Objects::nonNull).map(StringValue::new))); - put("app_scope", c -> StringValue.of((c.host).isPerUser()?"player":"global")); + put("app_list", c -> ListValue.wrap(((CarpetScriptHost) c.host).scriptServer().modules.keySet().stream().filter(Objects::nonNull).map(StringValue::new))); + put("app_scope", c -> StringValue.of((c.host).isPerUser() ? "player" : "global")); put("app_players", c -> ListValue.wrap(c.host.getUserList().stream().map(StringValue::new))); put("world_name", c -> new StringValue(c.server().getWorldData().getLevelName())); @@ -52,30 +55,33 @@ public class SystemInfo { put("server_motd", c -> StringValue.of(c.server().getMotd())); put("world_path", c -> StringValue.of(c.server().getWorldPath(LevelResource.ROOT).toString())); put("world_folder", c -> { - Path serverPath = c.server().getWorldPath(LevelResource.ROOT); - int nodeCount = serverPath.getNameCount(); - if (nodeCount < 2) return Value.NULL; - String tlf = serverPath.getName(nodeCount-2).toString(); + final Path serverPath = c.server().getWorldPath(LevelResource.ROOT); + final int nodeCount = serverPath.getNameCount(); + if (nodeCount < 2) + { + return Value.NULL; + } + final String tlf = serverPath.getName(nodeCount - 2).toString(); return StringValue.of(tlf); }); put("world_dimensions", c -> ListValue.wrap(c.server().levelKeys().stream().map(k -> ValueConversions.of(k.location())))); put("world_spawn_point", c -> { - LevelData prop = c.server().overworld().getLevelData(); + final LevelData prop = c.server().overworld().getLevelData(); return ListValue.of(NumericValue.of(prop.getXSpawn()), NumericValue.of(prop.getYSpawn()), NumericValue.of(prop.getZSpawn())); }); - put("world_bottom", c-> new NumericValue(c.level().getMinBuildHeight())); + put("world_bottom", c -> new NumericValue(c.level().getMinBuildHeight())); - put("world_top", c-> new NumericValue(c.level().getMaxBuildHeight())); + put("world_top", c -> new NumericValue(c.level().getMaxBuildHeight())); - put("world_center", c-> { - WorldBorder worldBorder = c.level().getWorldBorder(); + put("world_center", c -> { + final WorldBorder worldBorder = c.level().getWorldBorder(); return ListValue.fromTriple(worldBorder.getCenterX(), 0, worldBorder.getCenterZ()); }); put("world_size", c -> new NumericValue(c.level().getWorldBorder().getSize() / 2)); - put("world_max_size", c-> new NumericValue( c.level().getWorldBorder().getAbsoluteMaxSize())); + put("world_max_size", c -> new NumericValue(c.level().getWorldBorder().getAbsoluteMaxSize())); put("world_time", c -> new NumericValue(c.level().getGameTime())); @@ -90,133 +96,137 @@ public class SystemInfo { put("game_target", c -> StringValue.of(CarpetSettings.releaseTarget)); put("game_protocol", c -> NumericValue.of(SharedConstants.getProtocolVersion())); put("game_major_target", c -> { - String [] vers = CarpetSettings.releaseTarget.split("\\."); - return NumericValue.of((vers.length > 1)?Integer.parseInt(vers[1]):0); + final String[] vers = CarpetSettings.releaseTarget.split("\\."); + return NumericValue.of((vers.length > 1) ? Integer.parseInt(vers[1]) : 0); }); put("game_minor_target", c -> { - String [] vers = CarpetSettings.releaseTarget.split("\\."); - return NumericValue.of((vers.length > 2)?Integer.parseInt(vers[2]):0); + final String[] vers = CarpetSettings.releaseTarget.split("\\."); + return NumericValue.of((vers.length > 2) ? Integer.parseInt(vers[2]) : 0); }); put("game_stable", c -> BooleanValue.of(SharedConstants.getCurrentVersion().isStable())); - put("game_data_version", c->NumericValue.of(SharedConstants.getCurrentVersion().getDataVersion().getVersion())); - put("game_pack_version", c->NumericValue.of(SharedConstants.getCurrentVersion().getPackVersion(PackType.SERVER_DATA))); + put("game_data_version", c -> NumericValue.of(SharedConstants.getCurrentVersion().getDataVersion().getVersion())); + put("game_pack_version", c -> NumericValue.of(SharedConstants.getCurrentVersion().getPackVersion(PackType.SERVER_DATA))); put("server_ip", c -> StringValue.of(c.server().getLocalIp())); put("server_whitelisted", c -> BooleanValue.of(c.server().isEnforceWhitelist())); put("server_whitelist", c -> { - MapValue whitelist = new MapValue(Collections.emptyList()); - for (String s: c.server().getPlayerList().getWhiteListNames()) + final MapValue whitelist = new MapValue(Collections.emptyList()); + for (final String s : c.server().getPlayerList().getWhiteListNames()) { whitelist.append(StringValue.of(s)); } return whitelist; }); put("server_banned_players", c -> { - MapValue whitelist = new MapValue(Collections.emptyList()); - for (String s: c.server().getPlayerList().getBans().getUserList()) + final MapValue whitelist = new MapValue(Collections.emptyList()); + for (final String s : c.server().getPlayerList().getBans().getUserList()) { whitelist.append(StringValue.of(s)); } return whitelist; }); put("server_banned_ips", c -> { - MapValue whitelist = new MapValue(Collections.emptyList()); - for (String s: c.server().getPlayerList().getIpBans().getUserList()) + final MapValue whitelist = new MapValue(Collections.emptyList()); + for (final String s : c.server().getPlayerList().getIpBans().getUserList()) { whitelist.append(StringValue.of(s)); } return whitelist; }); - put("server_dev_environment", c-> BooleanValue.of(FabricLoader.getInstance().isDevelopmentEnvironment())); + put("server_dev_environment", c -> BooleanValue.of(FabricLoader.getInstance().isDevelopmentEnvironment())); put("server_mods", c -> { - Map ret = new HashMap<>(); - for (ModContainer mod : FabricLoader.getInstance().getAllMods()) + final Map ret = new HashMap<>(); + for (final ModContainer mod : FabricLoader.getInstance().getAllMods()) + { ret.put(new StringValue(mod.getMetadata().getId()), new StringValue(mod.getMetadata().getVersion().getFriendlyString())); + } return MapValue.wrap(ret); }); put("server_last_tick_times", c -> { - //assuming we are in the tick world section + //assuming we are in the tick world section // might be off one tick when run in the off tasks or asynchronously. - int currentReportedTick = c.server().getTickCount()-1; - List ticks = new ArrayList<>(100); + final int currentReportedTick = c.server().getTickCount() - 1; + final List ticks = new ArrayList<>(100); final long[] tickArray = c.server().tickTimes; - for (int i=currentReportedTick+100; i > currentReportedTick; i--) + for (int i = currentReportedTick + 100; i > currentReportedTick; i--) { - ticks.add(new NumericValue((tickArray[i % 100])/1000000.0)); + ticks.add(new NumericValue((tickArray[i % 100]) / 1000000.0)); } return ListValue.wrap(ticks); }); put("java_max_memory", c -> new NumericValue(Runtime.getRuntime().maxMemory())); put("java_allocated_memory", c -> new NumericValue(Runtime.getRuntime().totalMemory())); - put("java_used_memory", c -> new NumericValue(Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory())); + put("java_used_memory", c -> new NumericValue(Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())); put("java_cpu_count", c -> new NumericValue(Runtime.getRuntime().availableProcessors())); put("java_version", c -> StringValue.of(System.getProperty("java.version"))); put("java_bits", c -> { - for (String property : new String[]{"sun.arch.data.model", "com.ibm.vm.bitmode", "os.arch"}) + for (final String property : new String[]{"sun.arch.data.model", "com.ibm.vm.bitmode", "os.arch"}) { - String value = System.getProperty(property); + final String value = System.getProperty(property); if (value != null && value.contains("64")) + { return new NumericValue(64); - + } } return new NumericValue(32); }); put("java_system_cpu_load", c -> { - OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean( + final OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean( OperatingSystemMXBean.class); return new NumericValue(osBean.getCpuLoad()); }); put("java_process_cpu_load", c -> { - OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean( + final OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean( OperatingSystemMXBean.class); return new NumericValue(osBean.getProcessCpuLoad()); }); put("world_carpet_rules", c -> { - Collection> rules = CarpetServer.settingsManager.getCarpetRules(); - MapValue carpetRules = new MapValue(Collections.emptyList()); - rules.forEach(rule -> { - carpetRules.put(new StringValue(rule.name()), new StringValue(RuleHelper.toRuleString(rule.value()))); - }); + final Collection> rules = CarpetServer.settingsManager.getCarpetRules(); + final MapValue carpetRules = new MapValue(Collections.emptyList()); + rules.forEach(rule -> carpetRules.put(new StringValue(rule.name()), new StringValue(RuleHelper.toRuleString(rule.value())))); CarpetServer.extensions.forEach(e -> { - SettingsManager manager = e.extensionSettingsManager(); - if (manager == null) return; - - Collection> extensionRules = manager.getCarpetRules(); - extensionRules.forEach(rule -> { - carpetRules.put(new StringValue(manager.identifier()+":"+rule.name()), new StringValue(RuleHelper.toRuleString(rule.value()))); - }); + final SettingsManager manager = e.extensionSettingsManager(); + if (manager == null) + { + return; + } + manager.getCarpetRules().forEach(rule -> carpetRules.put(new StringValue(manager.identifier() + ":" + rule.name()), new StringValue(RuleHelper.toRuleString(rule.value())))); }); return carpetRules; }); - put("world_gamerules", c->{ - Map rules = new HashMap<>(); + put("world_gamerules", c -> { + final Map rules = new HashMap<>(); final GameRules gameRules = c.level().getGameRules(); - GameRules.visitGameRuleTypes(new GameRules.GameRuleTypeVisitor() { + GameRules.visitGameRuleTypes(new GameRules.GameRuleTypeVisitor() + { @Override - public > void visit(GameRules.Key key, GameRules.Type type) { + public > void visit(final GameRules.Key key, final GameRules.Type type) + { rules.put(StringValue.of(key.getId()), StringValue.of(gameRules.getRule(key).toString())); } }); return MapValue.wrap(rules); }); - put("world_min_spawning_light", c-> NumericValue.of(c.level().dimensionType().monsterSpawnBlockLightLimit())); + put("world_min_spawning_light", c -> NumericValue.of(c.level().dimensionType().monsterSpawnBlockLightLimit())); put("source_entity", c -> EntityValue.of(c.source().getEntity())); put("source_position", c -> ValueConversions.of(c.source().getPosition())); put("source_dimension", c -> ValueConversions.of(c.level())); put("source_rotation", c -> { - Vec2 rotation = c.source().getRotation(); + final Vec2 rotation = c.source().getRotation(); return ListValue.of(new NumericValue(rotation.x), new NumericValue(rotation.y)); }); - + put("scarpet_version", c -> StringValue.of(CarpetSettings.carpetVersion)); }}; - public static Value get(String what, CarpetContext cc) + + public static Value get(final String what, final CarpetContext cc) { return options.getOrDefault(what, c -> null).apply(cc); } + public static Value getAll() { return ListValue.wrap(options.keySet().stream().map(StringValue::of)); diff --git a/src/main/java/carpet/script/utils/WorldTools.java b/src/main/java/carpet/script/utils/WorldTools.java index 1c9c0543df..4235d43e8e 100644 --- a/src/main/java/carpet/script/utils/WorldTools.java +++ b/src/main/java/carpet/script/utils/WorldTools.java @@ -32,6 +32,7 @@ import net.minecraft.world.level.levelgen.WorldGenSettings; import net.minecraft.world.level.storage.DerivedLevelData; import net.minecraft.world.level.storage.ServerLevelData; + import java.io.IOException; import java.nio.file.Path; import java.util.List; @@ -42,32 +43,48 @@ public class WorldTools { - public static boolean canHasChunk(ServerLevel world, ChunkPos chpos, Map regionCache, boolean deepcheck) + public static boolean canHasChunk(final ServerLevel world, final ChunkPos chpos, final Map regionCache, final boolean deepcheck) { if (world.getChunk(chpos.x, chpos.z, ChunkStatus.STRUCTURE_STARTS, false) != null) + { return true; - String currentRegionName = "r." + chpos.getRegionX() + "." + chpos.getRegionZ() + ".mca"; + } + final String currentRegionName = "r." + chpos.getRegionX() + "." + chpos.getRegionZ() + ".mca"; if (regionCache != null && regionCache.containsKey(currentRegionName)) { - RegionFile region = regionCache.get(currentRegionName); - if (region == null) return false; + final RegionFile region = regionCache.get(currentRegionName); + if (region == null) + { + return false; + } return region.hasChunk(chpos); } - Path regionsFolder = ((MinecraftServerInterface)world.getServer()).getCMSession().getDimensionPath(world.dimension()).resolve("region"); - Path regionPath = regionsFolder.resolve(currentRegionName); + final Path regionsFolder = ((MinecraftServerInterface) world.getServer()).getCMSession().getDimensionPath(world.dimension()).resolve("region"); + final Path regionPath = regionsFolder.resolve(currentRegionName); if (!regionPath.toFile().exists()) { - if (regionCache != null) regionCache.put(currentRegionName, null); + if (regionCache != null) + { + regionCache.put(currentRegionName, null); + } return false; } - if (!deepcheck) return true; // not using cache in this case. + if (!deepcheck) + { + return true; // not using cache in this case. + } try { - RegionFile region = new RegionFile(regionPath, regionsFolder, true); - if (regionCache != null) regionCache.put(currentRegionName, region); + final RegionFile region = new RegionFile(regionPath, regionsFolder, true); + if (regionCache != null) + { + regionCache.put(currentRegionName, region); + } return region.hasChunk(chpos); } - catch (IOException ignored) { } + catch (final IOException ignored) + { + } return true; } /* @@ -137,16 +154,16 @@ public static boolean createWorld(MinecraftServer server, String worldKey, Long return true; }*/ - public static void forceChunkUpdate(BlockPos pos, ServerLevel world) + public static void forceChunkUpdate(final BlockPos pos, final ServerLevel world) { - ChunkPos chunkPos = new ChunkPos(pos); - LevelChunk worldChunk = world.getChunkSource().getChunk(chunkPos.x, chunkPos.z, false); + final ChunkPos chunkPos = new ChunkPos(pos); + final LevelChunk worldChunk = world.getChunkSource().getChunk(chunkPos.x, chunkPos.z, false); if (worldChunk != null) { - List players = world.getChunkSource().chunkMap.getPlayers(chunkPos, false); + final List players = world.getChunkSource().chunkMap.getPlayers(chunkPos, false); if (!players.isEmpty()) { - ClientboundLevelChunkWithLightPacket packet = new ClientboundLevelChunkWithLightPacket(worldChunk, world.getLightEngine(), null, null, false); // false seems to update neighbours as well. + final ClientboundLevelChunkWithLightPacket packet = new ClientboundLevelChunkWithLightPacket(worldChunk, world.getLightEngine(), null, null, false); // false seems to update neighbours as well. players.forEach(p -> p.connection.send(packet)); } } @@ -155,11 +172,26 @@ public static void forceChunkUpdate(BlockPos pos, ServerLevel world) private static class NoopWorldGenerationProgressListener implements ChunkProgressListener { - @Override public void updateSpawnPos(ChunkPos spawnPos) { } - @Override public void onStatusChange(ChunkPos pos, ChunkStatus status) { } + @Override + public void updateSpawnPos(final ChunkPos spawnPos) + { + } + + @Override + public void onStatusChange(final ChunkPos pos, final ChunkStatus status) + { + } + @Environment(EnvType.CLIENT) - @Override public void start() { } - @Override public void stop() { } + @Override + public void start() + { + } + + @Override + public void stop() + { + } } public static final ChunkProgressListener NOOP_LISTENER = new NoopWorldGenerationProgressListener(); diff --git a/src/main/java/carpet/script/utils/shapes/ShapeDirection.java b/src/main/java/carpet/script/utils/shapes/ShapeDirection.java index 1836c3b97d..9b7f33334f 100644 --- a/src/main/java/carpet/script/utils/shapes/ShapeDirection.java +++ b/src/main/java/carpet/script/utils/shapes/ShapeDirection.java @@ -7,7 +7,8 @@ import java.util.Locale; -public enum ShapeDirection { +public enum ShapeDirection +{ NORTH, SOUTH, EAST, @@ -17,8 +18,10 @@ public enum ShapeDirection { CAMERA, PLAYER; - public static ShapeDirection fromString(String direction) { - return switch (direction.toLowerCase(Locale.ROOT)) { + public static ShapeDirection fromString(final String direction) + { + return switch (direction.toLowerCase(Locale.ROOT)) + { case "north" -> NORTH; case "south" -> SOUTH; case "east" -> EAST; @@ -31,8 +34,10 @@ public static ShapeDirection fromString(String direction) { }; } - public static void rotatePoseStackByShapeDirection(PoseStack poseStack, ShapeDirection shapeDirection, Camera camera, Vec3 objectPos) { - switch (shapeDirection) { + public static void rotatePoseStackByShapeDirection(final PoseStack poseStack, final ShapeDirection shapeDirection, final Camera camera, final Vec3 objectPos) + { + switch (shapeDirection) + { case NORTH -> {} case SOUTH -> poseStack.mulPose(Axis.YP.rotationDegrees(180)); case EAST -> poseStack.mulPose(Axis.YP.rotationDegrees(270)); diff --git a/src/main/java/carpet/script/value/AbstractListValue.java b/src/main/java/carpet/script/value/AbstractListValue.java index 2bdf3f37d1..b8e60d0800 100644 --- a/src/main/java/carpet/script/value/AbstractListValue.java +++ b/src/main/java/carpet/script/value/AbstractListValue.java @@ -8,21 +8,25 @@ public abstract class AbstractListValue extends Value implements Iterable { - @Override public abstract Iterator iterator(); public List unpack() { - List retVal = Lists.newArrayList(iterator()); + final List retVal = Lists.newArrayList(iterator()); fatality(); return retVal; } - public void fatality() { } - public void append(Value v) + + public void fatality() + { + } + + public void append(final Value v) { throw new InternalExpressionException("Cannot append a value to an abstract list"); } @Override - public Value fromConstant() { + public Value fromConstant() + { return this.deepcopy(); } } diff --git a/src/main/java/carpet/script/value/BlockValue.java b/src/main/java/carpet/script/value/BlockValue.java index f42cee845a..c4ec4df3a3 100644 --- a/src/main/java/carpet/script/value/BlockValue.java +++ b/src/main/java/carpet/script/value/BlockValue.java @@ -7,12 +7,14 @@ import com.mojang.brigadier.StringReader; import com.mojang.brigadier.exceptions.CommandSyntaxException; + import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.stream.Collectors; + import net.minecraft.commands.arguments.blocks.BlockStateParser; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -44,42 +46,51 @@ public class BlockValue extends Value { private BlockState blockState; private final BlockPos pos; - @NotNull private final Level world; + @NotNull + private final Level world; private CompoundTag data; - public static BlockValue fromCoords(CarpetContext c, int x, int y, int z) + public static BlockValue fromCoords(final CarpetContext c, final int x, final int y, final int z) { - BlockPos pos = locateBlockPos(c, x,y,z); + final BlockPos pos = locateBlockPos(c, x, y, z); return new BlockValue(null, c.level(), pos); } - private static final Map bvCache= new HashMap<>(); - public static BlockValue fromString(String str, Level level) + private static final Map bvCache = new HashMap<>(); + + public static BlockValue fromString(final String str, final Level level) { try { BlockValue bv = bvCache.get(str); // [SCARY SHIT] persistent caches over server reloads - if (bv != null) return bv; - BlockStateParser.BlockResult foo = BlockStateParser.parseForBlock(level.registryAccess().lookupOrThrow(Registries.BLOCK), new StringReader(str), true ); + if (bv != null) + { + return bv; + } + final BlockStateParser.BlockResult foo = BlockStateParser.parseForBlock(level.registryAccess().lookupOrThrow(Registries.BLOCK), new StringReader(str), true); if (foo.blockState() != null) { CompoundTag bd = foo.nbt(); if (bd == null) + { bd = new CompoundTag(); - bv = new BlockValue(foo.blockState(), level, null, bd ); - if (bvCache.size()>10000) + } + bv = new BlockValue(foo.blockState(), level, null, bd); + if (bvCache.size() > 10000) + { bvCache.clear(); + } bvCache.put(str, bv); return bv; } } - catch (CommandSyntaxException ignored) + catch (final CommandSyntaxException ignored) { } throw new ThrowStatement(str, Throwables.UNKNOWN_BLOCK); } - public static BlockPos locateBlockPos(CarpetContext c, int xpos, int ypos, int zpos) + public static BlockPos locateBlockPos(final CarpetContext c, final int xpos, final int ypos, final int zpos) { final BlockPos pos = c.origin(); return new BlockPos(pos.getX() + xpos, pos.getY() + ypos, pos.getZ() + zpos); @@ -99,13 +110,13 @@ public BlockState getBlockState() throw new InternalExpressionException("Attempted to fetch block state without world or stored block state"); } - public static BlockEntity getBlockEntity(Level level, BlockPos pos) + public static BlockEntity getBlockEntity(final Level level, final BlockPos pos) { - if (level instanceof ServerLevel serverLevel) { - if (serverLevel.getServer().isSameThread()) - return serverLevel.getBlockEntity(pos); - else - return serverLevel.getChunkAt(pos).getBlockEntity(pos, LevelChunk.EntityCreationType.IMMEDIATE); + if (level instanceof final ServerLevel serverLevel) + { + return serverLevel.getServer().isSameThread() + ? serverLevel.getBlockEntity(pos) + : serverLevel.getChunkAt(pos).getBlockEntity(pos, LevelChunk.EntityCreationType.IMMEDIATE); } return null; } @@ -115,13 +126,11 @@ public CompoundTag getData() { if (data != null) { - if (data.isEmpty()) - return null; - return data; + return data.isEmpty() ? null : data; } if (pos != null) { - BlockEntity be = getBlockEntity(world, pos); + final BlockEntity be = getBlockEntity(world, pos); if (be == null) { data = new CompoundTag(); @@ -134,7 +143,7 @@ public CompoundTag getData() } - public BlockValue(BlockState state, @NotNull Level world, BlockPos position) + public BlockValue(final BlockState state, @NotNull final Level world, final BlockPos position) { this.world = world; blockState = state; @@ -142,7 +151,7 @@ public BlockValue(BlockState state, @NotNull Level world, BlockPos position) data = null; } - public BlockValue(BlockState state, @NotNull Level world, BlockPos position, CompoundTag nbt) + public BlockValue(final BlockState state, @NotNull final Level world, final BlockPos position, final CompoundTag nbt) { this.world = world; blockState = state; @@ -154,7 +163,7 @@ public BlockValue(BlockState state, @NotNull Level world, BlockPos position, Com @Override public String getString() { - Registry blockRegistry = world.registryAccess().registryOrThrow(Registries.BLOCK); + final Registry blockRegistry = world.registryAccess().registryOrThrow(Registries.BLOCK); return nameFromRegistryId(blockRegistry.getKey(getBlockState().getBlock())); } @@ -179,9 +188,9 @@ public Value clone() @Override public int hashCode() { - if (pos != null ) - return GlobalPos.of(world.dimension() , pos).hashCode(); //getDimension().getType() - return ("b"+getString()).hashCode(); + return pos != null + ? GlobalPos.of(world.dimension(), pos).hashCode() + : ("b" + getString()).hashCode(); } public BlockPos getPos() @@ -189,29 +198,35 @@ public BlockPos getPos() return pos; } - public Level getWorld() { return world;} + public Level getWorld() + { + return world; + } @Override - public Tag toTag(boolean force) + public Tag toTag(final boolean force) { - if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this); + if (!force) + { + throw new NBTSerializableValue.IncompatibleTypeException(this); + } // follows falling block convertion - CompoundTag tag = new CompoundTag(); - CompoundTag state = new CompoundTag(); - BlockState s = getBlockState(); + final CompoundTag tag = new CompoundTag(); + final CompoundTag state = new CompoundTag(); + final BlockState s = getBlockState(); state.put("Name", StringTag.valueOf(world.registryAccess().registryOrThrow(Registries.BLOCK).getKey(s.getBlock()).toString())); - Collection> properties = s.getProperties(); + final Collection> properties = s.getProperties(); if (!properties.isEmpty()) { - CompoundTag props = new CompoundTag(); - for (Property p: properties) + final CompoundTag props = new CompoundTag(); + for (final Property p : properties) { props.put(p.getName(), StringTag.valueOf(s.getValue(p).toString().toLowerCase(Locale.ROOT))); } state.put("Properties", props); } tag.put("BlockState", state); - CompoundTag dataTag = getData(); + final CompoundTag dataTag = getData(); if (dataTag != null) { tag.put("TileEntityData", dataTag); @@ -219,29 +234,30 @@ public Tag toTag(boolean force) return tag; } - public enum SpecificDirection { - UP("up",0.5, 0.0, 0.5, Direction.UP), + public enum SpecificDirection + { + UP("up", 0.5, 0.0, 0.5, Direction.UP), - UPNORTH ("up-north", 0.5, 0.0, 0.4, Direction.UP), - UPSOUTH ("up-south", 0.5, 0.0, 0.6, Direction.UP), + UPNORTH("up-north", 0.5, 0.0, 0.4, Direction.UP), + UPSOUTH("up-south", 0.5, 0.0, 0.6, Direction.UP), UPEAST("up-east", 0.6, 0.0, 0.5, Direction.UP), UPWEST("up-west", 0.4, 0.0, 0.5, Direction.UP), DOWN("down", 0.5, 1.0, 0.5, Direction.DOWN), - DOWNNORTH ("down-north", 0.5, 1.0, 0.4, Direction.DOWN), - DOWNSOUTH ("down-south", 0.5, 1.0, 0.6, Direction.DOWN), + DOWNNORTH("down-north", 0.5, 1.0, 0.4, Direction.DOWN), + DOWNSOUTH("down-south", 0.5, 1.0, 0.6, Direction.DOWN), DOWNEAST("down-east", 0.6, 1.0, 0.5, Direction.DOWN), DOWNWEST("down-west", 0.4, 1.0, 0.5, Direction.DOWN), - NORTH ("north", 0.5, 0.4, 1.0, Direction.NORTH), - SOUTH ("south", 0.5, 0.4, 0.0, Direction.SOUTH), + NORTH("north", 0.5, 0.4, 1.0, Direction.NORTH), + SOUTH("south", 0.5, 0.4, 0.0, Direction.SOUTH), EAST("east", 0.0, 0.4, 0.5, Direction.EAST), WEST("west", 1.0, 0.4, 0.5, Direction.WEST), - NORTHUP ("north-up", 0.5, 0.6, 1.0, Direction.NORTH), - SOUTHUP ("south-up", 0.5, 0.6, 0.0, Direction.SOUTH), + NORTHUP("north-up", 0.5, 0.6, 1.0, Direction.NORTH), + SOUTHUP("south-up", 0.5, 0.6, 0.0, Direction.SOUTH), EASTUP("east-up", 0.0, 0.6, 0.5, Direction.EAST), WESTUP("west-up", 1.0, 0.6, 0.5, Direction.WEST); @@ -252,87 +268,94 @@ public enum SpecificDirection { private static final Map DIRECTION_MAP = Arrays.stream(values()).collect(Collectors.toMap(SpecificDirection::getName, d -> d)); - SpecificDirection(String name, double hitx, double hity, double hitz, Direction blockFacing) + SpecificDirection(final String name, final double hitx, final double hity, final double hitz, final Direction blockFacing) { this.name = name; this.hitOffset = new Vec3(hitx, hity, hitz); this.facing = blockFacing; } + private String getName() { return name; } } - public static class PlacementContext extends BlockPlaceContext { + public static class PlacementContext extends BlockPlaceContext + { private final Direction facing; private final boolean sneakPlace; - public static PlacementContext from(Level world, BlockPos pos, String direction, boolean sneakPlace, ItemStack itemStack) + public static PlacementContext from(final Level world, final BlockPos pos, final String direction, final boolean sneakPlace, final ItemStack itemStack) { - SpecificDirection dir = SpecificDirection.DIRECTION_MAP.get(direction); + final SpecificDirection dir = SpecificDirection.DIRECTION_MAP.get(direction); if (dir == null) - throw new InternalExpressionException("unknown block placement direction: "+direction); - BlockHitResult hitres = new BlockHitResult(Vec3.atLowerCornerOf(pos).add(dir.hitOffset), dir.facing, pos, false); + { + throw new InternalExpressionException("unknown block placement direction: " + direction); + } + final BlockHitResult hitres = new BlockHitResult(Vec3.atLowerCornerOf(pos).add(dir.hitOffset), dir.facing, pos, false); return new PlacementContext(world, dir.facing, sneakPlace, itemStack, hitres); } - private PlacementContext(Level world_1, Direction direction_1, boolean sneakPlace, ItemStack itemStack_1, BlockHitResult hitres) { + + private PlacementContext(final Level world_1, final Direction direction_1, final boolean sneakPlace, final ItemStack itemStack_1, final BlockHitResult hitres) + { super(world_1, null, InteractionHand.MAIN_HAND, itemStack_1, hitres); this.facing = direction_1; this.sneakPlace = sneakPlace; } @Override - public BlockPos getClickedPos() { - boolean prevcanReplaceExisting = replaceClicked; + public BlockPos getClickedPos() + { + final boolean prevcanReplaceExisting = replaceClicked; replaceClicked = true; - BlockPos ret = super.getClickedPos(); + final BlockPos ret = super.getClickedPos(); replaceClicked = prevcanReplaceExisting; return ret; } @Override - public Direction getNearestLookingDirection() { + public Direction getNearestLookingDirection() + { return facing.getOpposite(); } @Override - public Direction[] getNearestLookingDirections() { - switch(this.facing) { - case DOWN: - default: - return new Direction[]{Direction.DOWN, Direction.NORTH, Direction.EAST, Direction.SOUTH, Direction.WEST, Direction.UP}; - case UP: - return new Direction[]{Direction.DOWN, Direction.UP, Direction.NORTH, Direction.EAST, Direction.SOUTH, Direction.WEST}; - case NORTH: - return new Direction[]{Direction.DOWN, Direction.NORTH, Direction.EAST, Direction.WEST, Direction.UP, Direction.SOUTH}; - case SOUTH: - return new Direction[]{Direction.DOWN, Direction.SOUTH, Direction.EAST, Direction.WEST, Direction.UP, Direction.NORTH}; - case WEST: - return new Direction[]{Direction.DOWN, Direction.WEST, Direction.SOUTH, Direction.UP, Direction.NORTH, Direction.EAST}; - case EAST: - return new Direction[]{Direction.DOWN, Direction.EAST, Direction.SOUTH, Direction.UP, Direction.NORTH, Direction.WEST}; - } + public Direction[] getNearestLookingDirections() + { + return switch (this.facing) + { + case DOWN -> new Direction[]{Direction.DOWN, Direction.NORTH, Direction.EAST, Direction.SOUTH, Direction.WEST, Direction.UP}; + case UP -> new Direction[]{Direction.DOWN, Direction.UP, Direction.NORTH, Direction.EAST, Direction.SOUTH, Direction.WEST}; + case NORTH -> new Direction[]{Direction.DOWN, Direction.NORTH, Direction.EAST, Direction.WEST, Direction.UP, Direction.SOUTH}; + case SOUTH -> new Direction[]{Direction.DOWN, Direction.SOUTH, Direction.EAST, Direction.WEST, Direction.UP, Direction.NORTH}; + case WEST -> new Direction[]{Direction.DOWN, Direction.WEST, Direction.SOUTH, Direction.UP, Direction.NORTH, Direction.EAST}; + case EAST -> new Direction[]{Direction.DOWN, Direction.EAST, Direction.SOUTH, Direction.UP, Direction.NORTH, Direction.WEST}; + }; } @Override - public Direction getHorizontalDirection() { + public Direction getHorizontalDirection() + { return this.facing.getAxis() == Direction.Axis.Y ? Direction.NORTH : this.facing; } @Override - public Direction getNearestLookingVerticalDirection() { + public Direction getNearestLookingVerticalDirection() + { return facing.getAxis() == Axis.Y ? facing : Direction.UP; } @Override - public boolean isSecondaryUseActive() { + public boolean isSecondaryUseActive() + { return sneakPlace; } @Override - public float getRotation() { - return (float)(this.facing.get2DDataValue() * 90); + public float getRotation() + { + return (float) (this.facing.get2DDataValue() * 90); } } } diff --git a/src/main/java/carpet/script/value/BooleanValue.java b/src/main/java/carpet/script/value/BooleanValue.java index 66c29bd0e1..d869590d21 100644 --- a/src/main/java/carpet/script/value/BooleanValue.java +++ b/src/main/java/carpet/script/value/BooleanValue.java @@ -11,53 +11,63 @@ public class BooleanValue extends NumericValue public static final BooleanValue TRUE = new BooleanValue(true); boolean boolValue; - private BooleanValue(boolean boolval) { + + private BooleanValue(final boolean boolval) + { super(boolval ? 1L : 0L); boolValue = boolval; } - public static BooleanValue of(boolean value) + public static BooleanValue of(final boolean value) { return value ? TRUE : FALSE; } @Override - public String getString() { - return boolValue?"true":"false"; + public String getString() + { + return boolValue ? "true" : "false"; } @Override - public String getPrettyString() { + public String getPrettyString() + { return getString(); } @Override - public String getTypeString() { + public String getTypeString() + { return "bool"; } @Override - public Value clone() { + public Value clone() + { return new BooleanValue(boolValue); } @Override - public int hashCode() { + public int hashCode() + { return Boolean.hashCode(boolValue); } @Override - public Tag toTag(boolean force) { + public Tag toTag(final boolean force) + { return ByteTag.valueOf(boolValue); } @Override - public JsonElement toJson() { + public JsonElement toJson() + { return new JsonPrimitive(boolValue); } @Override - public boolean isInteger() { + public boolean isInteger() + { return true; } } diff --git a/src/main/java/carpet/script/value/ContainerValueInterface.java b/src/main/java/carpet/script/value/ContainerValueInterface.java index 6e05554ae7..55bbfc4e2e 100644 --- a/src/main/java/carpet/script/value/ContainerValueInterface.java +++ b/src/main/java/carpet/script/value/ContainerValueInterface.java @@ -3,11 +3,15 @@ public interface ContainerValueInterface { boolean put(Value where, Value value); - default boolean put(Value where, Value value, Value conditions) + + default boolean put(final Value where, final Value value, final Value conditions) { return put(where, value); } + Value get(Value where); + boolean has(Value where); + boolean delete(Value where); } diff --git a/src/main/java/carpet/script/value/EntityValue.java b/src/main/java/carpet/script/value/EntityValue.java index 037a918dac..4576f73512 100644 --- a/src/main/java/carpet/script/value/EntityValue.java +++ b/src/main/java/carpet/script/value/EntityValue.java @@ -30,7 +30,6 @@ import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.StringTag; -import net.minecraft.network.protocol.game.ClientboundPlayerPositionPacket; import net.minecraft.network.protocol.game.ClientboundSetCarriedItemPacket; import net.minecraft.network.protocol.game.ClientboundSetExperiencePacket; import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; @@ -79,6 +78,7 @@ import net.minecraft.world.phys.EntityHitResult; import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.Vec3; + import java.util.ArrayList; import java.util.Collection; import java.util.EnumSet; @@ -103,19 +103,19 @@ public class EntityValue extends Value { private Entity entity; - public EntityValue(Entity e) + public EntityValue(final Entity e) { entity = e; } - public static Value of(Entity e) + public static Value of(final Entity e) { - if (e == null) return Value.NULL; - return new EntityValue(e); + return e == null ? Value.NULL : new EntityValue(e); } private static final Map selectorCache = new HashMap<>(); - public static Collection getEntitiesFromSelector(CommandSourceStack source, String selector) + + public static Collection getEntitiesFromSelector(final CommandSourceStack source, final String selector) { try { @@ -128,65 +128,50 @@ public static Collection getEntitiesFromSelector(CommandSourc selectorCache.put(selector, entitySelector); return entitySelector.findEntities(source.withMaximumPermission(4)); } - catch (CommandSyntaxException e) + catch (final CommandSyntaxException e) { - throw new InternalExpressionException("Cannot select entities from "+selector); + throw new InternalExpressionException("Cannot select entities from " + selector); } } public Entity getEntity() { - if (entity instanceof ServerPlayer && ((ServerPlayerEntityInterface)entity).isInvalidEntityObject()) + if (entity instanceof ServerPlayer && ((ServerPlayerEntityInterface) entity).isInvalidEntityObject()) { - ServerPlayer newPlayer = entity.getServer().getPlayerList().getPlayer(entity.getUUID()); - if (newPlayer != null) entity = newPlayer; + final ServerPlayer newPlayer = entity.getServer().getPlayerList().getPlayer(entity.getUUID()); + if (newPlayer != null) + { + entity = newPlayer; + } } return entity; } - public static ServerPlayer getPlayerByValue(MinecraftServer server, Value value) + public static ServerPlayer getPlayerByValue(final MinecraftServer server, final Value value) { - ServerPlayer player = null; - if (value instanceof EntityValue) + if (value instanceof final EntityValue ev && ev.getEntity() instanceof final ServerPlayer sp) { - Entity e = ((EntityValue) value).getEntity(); - if (e instanceof ServerPlayer) - { - player = (ServerPlayer) e; - } + return sp; } - else if (value.isNull()) + if (value.isNull()) { return null; } - else - { - String playerName = value.getString(); - player = server.getPlayerList().getPlayerByName(playerName); - } - return player; + final String playerName = value.getString(); + return server.getPlayerList().getPlayerByName(playerName); } - public static String getPlayerNameByValue(Value value) + public static String getPlayerNameByValue(final Value value) { - String playerName = null; - if (value instanceof EntityValue) + if (value instanceof final EntityValue ev && ev.getEntity() instanceof final ServerPlayer sp) { - Entity e = ((EntityValue) value).getEntity(); - if (e instanceof ServerPlayer) - { - playerName = e.getScoreboardName(); - } + return sp.getScoreboardName(); } - else if (value.isNull()) + if (value.isNull()) { return null; } - else - { - playerName = value.getString(); - } - return playerName; + return value.getString(); } @Override @@ -202,22 +187,22 @@ public boolean getBoolean() } @Override - public boolean equals(Object v) + public boolean equals(final Object v) { - if (v instanceof EntityValue) + if (v instanceof final EntityValue ev) { - return getEntity().getId()==((EntityValue) v).getEntity().getId(); + return getEntity().getId() == ev.getEntity().getId(); } - return super.equals((Value)v); + return super.equals(v); } @Override - public Value in(Value v) + public Value in(final Value v) { - if (v instanceof ListValue) + if (v instanceof final ListValue lv) { - List values = ((ListValue) v).getItems(); - String what = values.get(0).getString(); + final List values = lv.getItems(); + final String what = values.get(0).getString(); Value arg = null; if (values.size() == 2) { @@ -225,11 +210,11 @@ public Value in(Value v) } else if (values.size() > 2) { - arg = ListValue.wrap(values.subList(1,values.size())); + arg = ListValue.wrap(values.subList(1, values.size())); } return this.get(what, arg); } - String what = v.getString(); + final String what = v.getString(); return this.get(what, null); } @@ -247,9 +232,9 @@ public int hashCode() public static final EntityTypeTest ANY = EntityTypeTest.forClass(Entity.class); - public static EntityClassDescriptor getEntityDescriptor(String who, MinecraftServer server) + public static EntityClassDescriptor getEntityDescriptor(String who, final MinecraftServer server) { - EntityClassDescriptor eDesc = EntityClassDescriptor.byName.get(who); + final EntityClassDescriptor eDesc = EntityClassDescriptor.byName.get(who); if (eDesc == null) { boolean positive = true; @@ -258,16 +243,16 @@ public static EntityClassDescriptor getEntityDescriptor(String who, MinecraftSer positive = false; who = who.substring(1); } - String booWho = who; - HolderSet.Named> eTagValue = server.registryAccess().registryOrThrow(Registries.ENTITY_TYPE) + final String booWho = who; + final HolderSet.Named> eTagValue = server.registryAccess().registryOrThrow(Registries.ENTITY_TYPE) .getTag(TagKey.create(Registries.ENTITY_TYPE, InputValidator.identifierOf(who))) - .orElseThrow( () -> new InternalExpressionException(booWho+" is not a valid entity descriptor")); - Set> eTag = eTagValue.stream().map(Holder::value).collect(Collectors.toUnmodifiableSet()); + .orElseThrow(() -> new InternalExpressionException(booWho + " is not a valid entity descriptor")); + final Set> eTag = eTagValue.stream().map(Holder::value).collect(Collectors.toUnmodifiableSet()); if (positive) { if (eTag.size() == 1) { - EntityType type = eTag.iterator().next(); + final EntityType type = eTag.iterator().next(); return new EntityClassDescriptor(type, Entity::isAlive, eTag.stream()); } else @@ -291,34 +276,36 @@ public static class EntityClassDescriptor public final Predicate filteringPredicate; public final List> types; - EntityClassDescriptor(EntityTypeTest type, Predicate predicate, List> types) + EntityClassDescriptor(final EntityTypeTest type, final Predicate predicate, final List> types) { this.directType = type; this.filteringPredicate = predicate; this.types = types; } - EntityClassDescriptor(EntityTypeTest type, Predicate predicate, Stream> types) + EntityClassDescriptor(final EntityTypeTest type, final Predicate predicate, final Stream> types) { this(type, predicate, types.toList()); } - public Value listValue(RegistryAccess regs) { + public Value listValue(final RegistryAccess regs) + { final Registry entityRegs = regs.registryOrThrow(Registries.ENTITY_TYPE); return ListValue.wrap(types.stream().map(et -> StringValue.of(nameFromRegistryId(entityRegs.getKey(et))))); } - public final static Map byName = new HashMap<>() {{ - List> allTypes = BuiltInRegistries.ENTITY_TYPE.stream().toList(); + public static final Map byName = new HashMap<>() + {{ + final List> allTypes = BuiltInRegistries.ENTITY_TYPE.stream().toList(); // nonliving types - Set> projectiles = Set.of( + final Set> projectiles = Set.of( EntityType.ARROW, EntityType.DRAGON_FIREBALL, EntityType.FIREWORK_ROCKET, EntityType.FIREBALL, EntityType.LLAMA_SPIT, EntityType.SMALL_FIREBALL, EntityType.SNOWBALL, EntityType.SPECTRAL_ARROW, EntityType.EGG, EntityType.ENDER_PEARL, EntityType.EXPERIENCE_BOTTLE, EntityType.POTION, EntityType.TRIDENT, EntityType.WITHER_SKULL, EntityType.FISHING_BOBBER, EntityType.SHULKER_BULLET ); - Set> deads = Set.of( + final Set> deads = Set.of( EntityType.AREA_EFFECT_CLOUD, EntityType.MARKER, EntityType.BOAT, EntityType.END_CRYSTAL, EntityType.EVOKER_FANGS, EntityType.EXPERIENCE_ORB, EntityType.EYE_OF_ENDER, EntityType.FALLING_BLOCK, EntityType.ITEM, EntityType.ITEM_FRAME, EntityType.GLOW_ITEM_FRAME, @@ -326,47 +313,47 @@ public Value listValue(RegistryAccess regs) { EntityType.TNT, EntityType.ARMOR_STAND, EntityType.CHEST_BOAT ); - Set> minecarts = Set.of( - EntityType.MINECART, EntityType.CHEST_MINECART, EntityType.COMMAND_BLOCK_MINECART, + final Set> minecarts = Set.of( + EntityType.MINECART, EntityType.CHEST_MINECART, EntityType.COMMAND_BLOCK_MINECART, EntityType.FURNACE_MINECART, EntityType.HOPPER_MINECART, EntityType.SPAWNER_MINECART, EntityType.TNT_MINECART ); // living mob groups - non-defeault - Set> undeads = Set.of( + final Set> undeads = Set.of( EntityType.STRAY, EntityType.SKELETON, EntityType.WITHER_SKELETON, EntityType.ZOMBIE, EntityType.DROWNED, EntityType.ZOMBIE_VILLAGER, EntityType.ZOMBIE_HORSE, EntityType.SKELETON_HORSE, EntityType.PHANTOM, EntityType.WITHER, EntityType.ZOGLIN, EntityType.HUSK, EntityType.ZOMBIFIED_PIGLIN ); - Set> arthropods = Set.of( + final Set> arthropods = Set.of( EntityType.BEE, EntityType.ENDERMITE, EntityType.SILVERFISH, EntityType.SPIDER, EntityType.CAVE_SPIDER ); - Set> aquatique = Set.of( + final Set> aquatique = Set.of( EntityType.GUARDIAN, EntityType.TURTLE, EntityType.COD, EntityType.DOLPHIN, EntityType.PUFFERFISH, EntityType.SALMON, EntityType.SQUID, EntityType.TROPICAL_FISH ); - Set> illagers = Set.of( + final Set> illagers = Set.of( EntityType.PILLAGER, EntityType.ILLUSIONER, EntityType.VINDICATOR, EntityType.EVOKER, EntityType.RAVAGER, EntityType.WITCH ); - Set> living = allTypes.stream().filter(et -> + final Set> living = allTypes.stream().filter(et -> !deads.contains(et) && !projectiles.contains(et) && !minecarts.contains(et) ).collect(Collectors.toSet()); - Set> regular = allTypes.stream().filter(et -> + final Set> regular = allTypes.stream().filter(et -> living.contains(et) && !undeads.contains(et) && !arthropods.contains(et) && !aquatique.contains(et) && !illagers.contains(et) ).collect(Collectors.toSet()); - put("*", new EntityClassDescriptor(ANY, e -> true, allTypes) ); + put("*", new EntityClassDescriptor(ANY, e -> true, allTypes)); put("valid", new EntityClassDescriptor(ANY, net.minecraft.world.entity.EntitySelector.ENTITY_STILL_ALIVE, allTypes)); put("!valid", new EntityClassDescriptor(ANY, e -> !e.isAlive(), allTypes)); - put("living", new EntityClassDescriptor(EntityTypeTest.forClass(LivingEntity.class), net.minecraft.world.entity.EntitySelector.ENTITY_STILL_ALIVE, allTypes.stream().filter(living::contains))); - put("!living", new EntityClassDescriptor(ANY, (e) -> (!(e instanceof LivingEntity) && e.isAlive()), allTypes.stream().filter(et -> !living.contains(et)))); + put("living", new EntityClassDescriptor(EntityTypeTest.forClass(LivingEntity.class), net.minecraft.world.entity.EntitySelector.ENTITY_STILL_ALIVE, allTypes.stream().filter(living::contains))); + put("!living", new EntityClassDescriptor(ANY, (e) -> (!(e instanceof LivingEntity) && e.isAlive()), allTypes.stream().filter(et -> !living.contains(et)))); put("projectile", new EntityClassDescriptor(EntityTypeTest.forClass(Projectile.class), net.minecraft.world.entity.EntitySelector.ENTITY_STILL_ALIVE, allTypes.stream().filter(projectiles::contains))); put("!projectile", new EntityClassDescriptor(ANY, (e) -> (!(e instanceof Projectile) && e.isAlive()), allTypes.stream().filter(et -> !projectiles.contains(et) && !living.contains(et)))); @@ -392,49 +379,53 @@ public Value listValue(RegistryAccess regs) { put("regular", new EntityClassDescriptor(EntityTypeTest.forClass(LivingEntity.class), e -> (((LivingEntity) e).getMobType() == MobType.UNDEFINED && e.isAlive()), allTypes.stream().filter(regular::contains))); put("!regular", new EntityClassDescriptor(EntityTypeTest.forClass(LivingEntity.class), e -> (((LivingEntity) e).getMobType() != MobType.UNDEFINED && e.isAlive()), allTypes.stream().filter(et -> !regular.contains(et) && living.contains(et)))); - for (ResourceLocation typeId : BuiltInRegistries.ENTITY_TYPE.keySet()) + for (final ResourceLocation typeId : BuiltInRegistries.ENTITY_TYPE.keySet()) { - EntityType type = BuiltInRegistries.ENTITY_TYPE.get(typeId); - String mobType = ValueConversions.simplify(typeId); - put( mobType, new EntityClassDescriptor(type, net.minecraft.world.entity.EntitySelector.ENTITY_STILL_ALIVE, Stream.of(type))); - put("!"+mobType, new EntityClassDescriptor(ANY, (e) -> e.getType() != type && e.isAlive(), allTypes.stream().filter(et -> et != type))); + final EntityType type = BuiltInRegistries.ENTITY_TYPE.get(typeId); + final String mobType = ValueConversions.simplify(typeId); + put(mobType, new EntityClassDescriptor(type, net.minecraft.world.entity.EntitySelector.ENTITY_STILL_ALIVE, Stream.of(type))); + put("!" + mobType, new EntityClassDescriptor(ANY, (e) -> e.getType() != type && e.isAlive(), allTypes.stream().filter(et -> et != type))); } - for (MobCategory catId : MobCategory.values()) + for (final MobCategory catId : MobCategory.values()) { - String catStr = catId.getName(); - put( catStr, new EntityClassDescriptor(ANY, e -> ((e.getType().getCategory() == catId) && e.isAlive()), allTypes.stream().filter(et -> et.getCategory() == catId))); - put("!"+catStr, new EntityClassDescriptor(ANY, e -> ((e.getType().getCategory() != catId) && e.isAlive()), allTypes.stream().filter(et -> et.getCategory() != catId))); + final String catStr = catId.getName(); + put(catStr, new EntityClassDescriptor(ANY, e -> ((e.getType().getCategory() == catId) && e.isAlive()), allTypes.stream().filter(et -> et.getCategory() == catId))); + put("!" + catStr, new EntityClassDescriptor(ANY, e -> ((e.getType().getCategory() != catId) && e.isAlive()), allTypes.stream().filter(et -> et.getCategory() != catId))); } }}; } - public Value get(String what, Value arg) + public Value get(final String what, final Value arg) { if (!(featureAccessors.containsKey(what))) - throw new InternalExpressionException("Unknown entity feature: "+what); + { + throw new InternalExpressionException("Unknown entity feature: " + what); + } try { return featureAccessors.get(what).apply(getEntity(), arg); } - catch (NullPointerException npe) + catch (final NullPointerException npe) { - throw new InternalExpressionException("Cannot fetch '"+what+"' with these arguments"); + throw new InternalExpressionException("Cannot fetch '" + what + "' with these arguments"); } } + private static final Map inventorySlots = Map.of( - "mainhand", EquipmentSlot.MAINHAND, - "offhand", EquipmentSlot.OFFHAND, - "head", EquipmentSlot.HEAD, - "chest", EquipmentSlot.CHEST, - "legs", EquipmentSlot.LEGS, - "feet", EquipmentSlot.FEET + "mainhand", EquipmentSlot.MAINHAND, + "offhand", EquipmentSlot.OFFHAND, + "head", EquipmentSlot.HEAD, + "chest", EquipmentSlot.CHEST, + "legs", EquipmentSlot.LEGS, + "feet", EquipmentSlot.FEET ); - private static final Map> featureAccessors = new HashMap>() {{ + private static final Map> featureAccessors = new HashMap>() + {{ //put("test", (e, a) -> a == null ? Value.NULL : new StringValue(a.getString())); put("removed", (entity, arg) -> BooleanValue.of(entity.isRemoved())); - put("uuid",(e, a) -> new StringValue(e.getStringUUID())); - put("id",(e, a) -> new NumericValue(e.getId())); + put("uuid", (e, a) -> new StringValue(e.getStringUUID())); + put("id", (e, a) -> new NumericValue(e.getId())); put("pos", (e, a) -> ListValue.of(new NumericValue(e.getX()), new NumericValue(e.getY()), new NumericValue(e.getZ()))); put("location", (e, a) -> ListValue.of(new NumericValue(e.getX()), new NumericValue(e.getY()), new NumericValue(e.getZ()), new NumericValue(e.getYRot()), new NumericValue(e.getXRot()))); put("x", (e, a) -> new NumericValue(e.getX())); @@ -442,7 +433,7 @@ public Value get(String what, Value arg) put("z", (e, a) -> new NumericValue(e.getZ())); put("motion", (e, a) -> { - Vec3 velocity = e.getDeltaMovement(); + final Vec3 velocity = e.getDeltaMovement(); return ListValue.of(new NumericValue(velocity.x), new NumericValue(velocity.y), new NumericValue(velocity.z)); }); put("motion_x", (e, a) -> new NumericValue(e.getDeltaMovement().x)); @@ -452,61 +443,52 @@ public Value get(String what, Value arg) put("name", (e, a) -> new StringValue(e.getName().getString())); put("display_name", (e, a) -> new FormattedTextValue(e.getDisplayName())); put("command_name", (e, a) -> new StringValue(e.getScoreboardName())); - put("custom_name", (e, a) -> e.hasCustomName()?new StringValue(e.getCustomName().getString()):Value.NULL); + put("custom_name", (e, a) -> e.hasCustomName() ? new StringValue(e.getCustomName().getString()) : Value.NULL); put("type", (e, a) -> new StringValue(nameFromRegistryId(e.getLevel().registryAccess().registryOrThrow(Registries.ENTITY_TYPE).getKey(e.getType())))); put("is_riding", (e, a) -> BooleanValue.of(e.isPassenger())); put("is_ridden", (e, a) -> BooleanValue.of(e.isVehicle())); put("passengers", (e, a) -> ListValue.wrap(e.getPassengers().stream().map(EntityValue::new))); - put("mount", (e, a) -> (e.getVehicle()!=null)?new EntityValue(e.getVehicle()):Value.NULL); - put("unmountable", (e, a) -> BooleanValue.of(((EntityInterface)e).isPermanentVehicle())); + put("mount", (e, a) -> (e.getVehicle() != null) ? new EntityValue(e.getVehicle()) : Value.NULL); + put("unmountable", (e, a) -> BooleanValue.of(((EntityInterface) e).isPermanentVehicle())); // deprecated put("tags", (e, a) -> ListValue.wrap(e.getTags().stream().map(StringValue::new))); put("scoreboard_tags", (e, a) -> ListValue.wrap(e.getTags().stream().map(StringValue::new))); put("entity_tags", (e, a) -> { - EntityType type = e.getType(); - return ListValue.wrap(e.getServer().registryAccess().registryOrThrow(Registries.ENTITY_TYPE).getTags().filter(entry -> entry.getSecond().stream().anyMatch(h -> h.value()==type)).map(entry -> ValueConversions.of(entry.getFirst()))); + final EntityType type = e.getType(); + return ListValue.wrap(e.getServer().registryAccess().registryOrThrow(Registries.ENTITY_TYPE).getTags().filter(entry -> entry.getSecond().stream().anyMatch(h -> h.value() == type)).map(entry -> ValueConversions.of(entry.getFirst()))); }); // deprecated put("has_tag", (e, a) -> BooleanValue.of(e.getTags().contains(a.getString()))); put("has_scoreboard_tag", (e, a) -> BooleanValue.of(e.getTags().contains(a.getString()))); put("has_entity_tag", (e, a) -> { - Optional>> tag = e.getServer().registryAccess().registryOrThrow(Registries.ENTITY_TYPE).getTag(TagKey.create(Registries.ENTITY_TYPE, InputValidator.identifierOf(a.getString()))); - if (tag.isEmpty()) return Value.NULL; + final Optional>> tag = e.getServer().registryAccess().registryOrThrow(Registries.ENTITY_TYPE).getTag(TagKey.create(Registries.ENTITY_TYPE, InputValidator.identifierOf(a.getString()))); + if (tag.isEmpty()) + { + return Value.NULL; + } //Tag> tag = e.getServer().getTags().getOrEmpty(Registry.ENTITY_TYPE_REGISTRY).getTag(InputValidator.identifierOf(a.getString())); //if (tag == null) return Value.NULL; //return BooleanValue.of(e.getType().is(tag)); - EntityType type = e.getType(); + final EntityType type = e.getType(); return BooleanValue.of(tag.get().stream().anyMatch(h -> h.value() == type)); }); - put("yaw", (e, a)-> new NumericValue(e.getYRot())); - put("head_yaw", (e, a)-> { - if (e instanceof LivingEntity) - { - return new NumericValue(e.getYHeadRot()); - } - return Value.NULL; - }); - put("body_yaw", (e, a)-> { - if (e instanceof LivingEntity) - { - return new NumericValue(((LivingEntity) e).yBodyRot); - } - return Value.NULL; - }); + put("yaw", (e, a) -> new NumericValue(e.getYRot())); + put("head_yaw", (e, a) -> e instanceof LivingEntity ? new NumericValue(e.getYHeadRot()) : Value.NULL); + put("body_yaw", (e, a) -> e instanceof final LivingEntity le ? new NumericValue(le.yBodyRot) : Value.NULL); - put("pitch", (e, a)-> new NumericValue(e.getXRot())); + put("pitch", (e, a) -> new NumericValue(e.getXRot())); put("look", (e, a) -> { - Vec3 look = e.getLookAngle(); - return ListValue.of(new NumericValue(look.x),new NumericValue(look.y),new NumericValue(look.z)); + final Vec3 look = e.getLookAngle(); + return ListValue.of(new NumericValue(look.x), new NumericValue(look.y), new NumericValue(look.z)); }); put("is_burning", (e, a) -> BooleanValue.of(e.isOnFire())); put("fire", (e, a) -> new NumericValue(e.getRemainingFireTicks())); put("is_freezing", (e, a) -> BooleanValue.of(e.isFullyFrozen())); put("frost", (e, a) -> new NumericValue(e.getTicksFrozen())); - put("silent", (e, a)-> BooleanValue.of(e.isSilent())); + put("silent", (e, a) -> BooleanValue.of(e.isSilent())); put("gravity", (e, a) -> BooleanValue.of(!e.isNoGravity())); put("immune_to_fire", (e, a) -> BooleanValue.of(e.fireImmune())); put("immune_to_frost", (e, a) -> BooleanValue.of(!e.canFreeze())); @@ -517,37 +499,21 @@ public Value get(String what, Value arg) put("width", (e, a) -> new NumericValue(e.getDimensions(Pose.STANDING).width)); put("eye_height", (e, a) -> new NumericValue(e.getEyeHeight())); put("age", (e, a) -> new NumericValue(e.tickCount)); - put("breeding_age", (e, a) -> e instanceof AgeableMob?new NumericValue(((AgeableMob) e).getAge()):Value.NULL); - put("despawn_timer", (e, a) -> e instanceof LivingEntity?new NumericValue(((LivingEntity) e).getNoActionTime()):Value.NULL); - put("blue_skull",(e,a)->{ - if (e instanceof WitherSkull w){ - return BooleanValue.of(w.isDangerous()); - } - return Value.NULL; - }); - put("offering_flower",(e,a)->{ - if (e instanceof IronGolem ig){ - return BooleanValue.of(ig.getOfferFlowerTick()>0); - } - return Value.NULL; - }); - put("item", (e, a) -> { - if(e instanceof ItemEntity) - return ValueConversions.of(((ItemEntity) e).getItem(), e.getServer().registryAccess()); - if(e instanceof ItemFrame) - return ValueConversions.of(((ItemFrame) e).getItem(), e.getServer().registryAccess()); - return Value.NULL; - }); - put("count", (e, a) -> (e instanceof ItemEntity)?new NumericValue(((ItemEntity) e).getItem().getCount()):Value.NULL); - put("pickup_delay", (e, a) -> (e instanceof ItemEntity)?new NumericValue(((ItemEntityInterface) e).getPickupDelayCM()):Value.NULL); - put("portal_cooldown", (e , a) ->new NumericValue(((EntityInterface)e).getPublicNetherPortalCooldown())); - put("portal_timer", (e , a) ->new NumericValue(((EntityInterface)e).getPortalTimer())); + put("breeding_age", (e, a) -> e instanceof final AgeableMob am ? new NumericValue(am.getAge()) : Value.NULL); + put("despawn_timer", (e, a) -> e instanceof final LivingEntity le ? new NumericValue(le.getNoActionTime()) : Value.NULL); + put("blue_skull", (e, a) -> e instanceof final WitherSkull w ? BooleanValue.of(w.isDangerous()) : Value.NULL); + put("offering_flower", (e, a) -> e instanceof final IronGolem ig ? BooleanValue.of(ig.getOfferFlowerTick() > 0) : Value.NULL); + put("item", (e, a) -> e instanceof final ItemEntity ie ? ValueConversions.of(ie.getItem(), e.getServer().registryAccess()) : e instanceof final ItemFrame frame ? ValueConversions.of(frame.getItem(), e.getServer().registryAccess()) : Value.NULL); + put("count", (e, a) -> (e instanceof final ItemEntity ie) ? new NumericValue(ie.getItem().getCount()) : Value.NULL); + put("pickup_delay", (e, a) -> (e instanceof ItemEntity) ? new NumericValue(((ItemEntityInterface) e).getPickupDelayCM()) : Value.NULL); + put("portal_cooldown", (e, a) -> new NumericValue(((EntityInterface) e).getPublicNetherPortalCooldown())); + put("portal_timer", (e, a) -> new NumericValue(((EntityInterface) e).getPortalTimer())); // ItemEntity -> despawn timer via ssGetAge - put("is_baby", (e, a) -> (e instanceof LivingEntity)?BooleanValue.of(((LivingEntity) e).isBaby()):Value.NULL); + put("is_baby", (e, a) -> (e instanceof final LivingEntity le) ? BooleanValue.of(le.isBaby()) : Value.NULL); put("target", (e, a) -> { - if (e instanceof Mob) + if (e instanceof final Mob mob) { - LivingEntity target = ((Mob) e).getTarget(); // there is also getAttacking in living.... + final LivingEntity target = mob.getTarget(); // there is also getAttacking in living.... if (target != null) { return new EntityValue(target); @@ -555,140 +521,85 @@ public Value get(String what, Value arg) } return Value.NULL; }); - put("home", (e, a) -> { - if (e instanceof Mob) - { - return (((Mob) e).getRestrictRadius () > 0)?new BlockValue(null, e.getCommandSenderWorld(), ((PathfinderMob) e).getRestrictCenter()):Value.FALSE; - } - return Value.NULL; - }); + put("home", (e, a) -> e instanceof final Mob mob ? (mob.getRestrictRadius() > 0) ? new BlockValue(null, e.getCommandSenderWorld(), mob.getRestrictCenter()) : Value.FALSE : Value.NULL); put("spawn_point", (e, a) -> { - if (e instanceof ServerPlayer spe) + if (e instanceof final ServerPlayer spe) { - if (spe.getRespawnPosition() == null) return Value.FALSE; + if (spe.getRespawnPosition() == null) + { + return Value.FALSE; + } return ListValue.of( ValueConversions.of(spe.getRespawnPosition()), ValueConversions.of(spe.getRespawnDimension()), new NumericValue(spe.getRespawnAngle()), BooleanValue.of(spe.isRespawnForced()) - ); + ); } return Value.NULL; }); put("pose", (e, a) -> new StringValue(e.getPose().name().toLowerCase(Locale.ROOT))); - put("sneaking", (e, a) -> e.isShiftKeyDown()?Value.TRUE:Value.FALSE); - put("sprinting", (e, a) -> e.isSprinting()?Value.TRUE:Value.FALSE); - put("swimming", (e, a) -> e.isSwimming()?Value.TRUE:Value.FALSE); - put("swinging", (e, a) -> { - if (e instanceof LivingEntity) return BooleanValue.of(((LivingEntity) e).swinging); - return Value.NULL; - }); - + put("sneaking", (e, a) -> e.isShiftKeyDown() ? Value.TRUE : Value.FALSE); + put("sprinting", (e, a) -> e.isSprinting() ? Value.TRUE : Value.FALSE); + put("swimming", (e, a) -> e.isSwimming() ? Value.TRUE : Value.FALSE); + put("swinging", (e, a) -> e instanceof final LivingEntity le ? BooleanValue.of(le.swinging) : Value.NULL); put("air", (e, a) -> new NumericValue(e.getAirSupply())); - put("language", (e, a)->{ - if(!(e instanceof ServerPlayer)) - return NULL; - String lang = ((ServerPlayerEntityInterface) e).getLanguage(); - return StringValue.of(lang); - }); - put("persistence", (e, a) -> { - if (e instanceof Mob) return BooleanValue.of(((Mob) e).isPersistenceRequired()); - return Value.NULL; - }); - put("hunger", (e, a) -> { - if(e instanceof Player) return new NumericValue(((Player) e).getFoodData().getFoodLevel()); - return Value.NULL; - }); - put("saturation", (e, a) -> { - if(e instanceof Player) return new NumericValue(((Player) e).getFoodData().getSaturationLevel()); - return Value.NULL; - }); - - put("exhaustion",(e, a)->{ - if(e instanceof Player) return new NumericValue(((Player) e).getFoodData().getExhaustionLevel()); - return Value.NULL; - }); - - put("absorption",(e, a)->{ - if(e instanceof Player) return new NumericValue(((Player) e).getAbsorptionAmount()); - return Value.NULL; - }); - - put("xp",(e, a)->{ - if(e instanceof Player) return new NumericValue(((Player) e).totalExperience); - return Value.NULL; - }); - - put("xp_level", (e, a)->{ - if(e instanceof Player) return new NumericValue(((Player) e).experienceLevel); - return Value.NULL; - }); - - put("xp_progress", (e, a)->{ - if(e instanceof Player) return new NumericValue(((Player) e).experienceProgress); - return Value.NULL; - }); - - put("score", (e, a)->{ - if(e instanceof Player) return new NumericValue(((Player) e).getScore()); - return Value.NULL; - }); - - put("jumping", (e, a) -> { - if (e instanceof LivingEntity) - { - return ((LivingEntityInterface) e).isJumpingCM()?Value.TRUE:Value.FALSE; - } - return Value.NULL; - }); - put("gamemode", (e, a) -> { - if (e instanceof ServerPlayer) - { - return new StringValue(((ServerPlayer) e).gameMode.getGameModeForPlayer().getName()); - } - return Value.NULL; - }); - + put("language", (e, a) -> !(e instanceof ServerPlayer) ? NULL : StringValue.of(((ServerPlayerEntityInterface) e).getLanguage())); + put("persistence", (e, a) -> e instanceof final Mob mob ? BooleanValue.of(mob.isPersistenceRequired()) : Value.NULL); + put("hunger", (e, a) -> e instanceof final Player player ? new NumericValue(player.getFoodData().getFoodLevel()) : Value.NULL); + put("saturation", (e, a) -> e instanceof final Player player ? new NumericValue(player.getFoodData().getSaturationLevel()) : Value.NULL); + put("exhaustion", (e, a) -> e instanceof final Player player ? new NumericValue(player.getFoodData().getExhaustionLevel()) : Value.NULL); + put("absorption", (e, a) -> e instanceof final Player player ? new NumericValue(player.getAbsorptionAmount()) : Value.NULL); + put("xp", (e, a) -> e instanceof final Player player ? new NumericValue(player.totalExperience) : Value.NULL); + put("xp_level", (e, a) -> e instanceof final Player player ? new NumericValue(player.experienceLevel) : Value.NULL); + put("xp_progress", (e, a) -> e instanceof final Player player ? new NumericValue(player.experienceProgress) : Value.NULL); + put("score", (e, a) -> e instanceof final Player player ? new NumericValue(player.getScore()) : Value.NULL); + put("jumping", (e, a) -> e instanceof LivingEntity ? ((LivingEntityInterface) e).isJumpingCM() ? Value.TRUE : Value.FALSE : Value.NULL); + put("gamemode", (e, a) -> e instanceof final ServerPlayer sp ? new StringValue(sp.gameMode.getGameModeForPlayer().getName()) : Value.NULL); put("path", (e, a) -> { - if (e instanceof Mob) + if (e instanceof final Mob mob) { - Path path = ((Mob)e).getNavigation().getPath(); - if (path == null) return Value.NULL; - return ValueConversions.fromPath((ServerLevel)e.getCommandSenderWorld(), path); + final Path path = mob.getNavigation().getPath(); + if (path == null) + { + return Value.NULL; + } + return ValueConversions.fromPath((ServerLevel) e.getCommandSenderWorld(), path); } return Value.NULL; }); put("brain", (e, a) -> { - String module = a.getString(); - MemoryModuleType moduleType = e.getLevel().registryAccess().registryOrThrow(Registries.MEMORY_MODULE_TYPE).get(InputValidator.identifierOf(module)); - if (moduleType == MemoryModuleType.DUMMY) return Value.NULL; - if (e instanceof LivingEntity livingEntity) - { - Brain brain = livingEntity.getBrain(); - Map, Optional>> memories = brain.getMemories(); - Optional> optmemory = memories.get(moduleType); - if (optmemory==null || !optmemory.isPresent()) return Value.NULL; - ExpirableValue memory = optmemory.get(); - return ValueConversions.fromTimedMemory(e, memory.getTimeToLive(), memory.getValue()); + final String module = a.getString(); + final MemoryModuleType moduleType = e.getLevel().registryAccess().registryOrThrow(Registries.MEMORY_MODULE_TYPE).get(InputValidator.identifierOf(module)); + if (moduleType == MemoryModuleType.DUMMY) + { + return Value.NULL; } - return Value.NULL; - }); - put("gamemode_id", (e, a) -> { - if (e instanceof ServerPlayer) + if (e instanceof final LivingEntity livingEntity) { - return new NumericValue(((ServerPlayer) e).gameMode.getGameModeForPlayer().getId()); + final Brain brain = livingEntity.getBrain(); + final Map, Optional>> memories = brain.getMemories(); + final Optional> optmemory = memories.get(moduleType); + if (optmemory == null || !optmemory.isPresent()) + { + return Value.NULL; + } + final ExpirableValue memory = optmemory.get(); + return ValueConversions.fromTimedMemory(e, memory.getTimeToLive(), memory.getValue()); } return Value.NULL; }); - + put("gamemode_id", (e, a) -> e instanceof final ServerPlayer sp ? new NumericValue(sp.gameMode.getGameModeForPlayer().getId()) : Value.NULL); put("permission_level", (e, a) -> { - if (e instanceof ServerPlayer spe) + if (e instanceof final ServerPlayer spe) { - for (int i=4; i>=0; i--) + for (int i = 4; i >= 0; i--) { if (spe.hasPermissions(i)) + { return new NumericValue(i); + } } return new NumericValue(0); @@ -697,161 +608,118 @@ public Value get(String what, Value arg) }); put("player_type", (e, a) -> { - if (e instanceof Player p) - { - if (e instanceof EntityPlayerMPFake) return new StringValue(((EntityPlayerMPFake) e).isAShadow?"shadow":"fake"); - MinecraftServer server = p.getCommandSenderWorld().getServer(); - if (server.isDedicatedServer()) return new StringValue("multiplayer"); - boolean runningLan = server.isPublished(); - if (!runningLan) return new StringValue("singleplayer"); - boolean isowner = server.isSingleplayerOwner(p.getGameProfile()); - if (isowner) return new StringValue("lan_host"); + if (e instanceof final Player p) + { + if (e instanceof final EntityPlayerMPFake fake) + { + return new StringValue(fake.isAShadow ? "shadow" : "fake"); + } + final MinecraftServer server = p.getCommandSenderWorld().getServer(); + if (server.isDedicatedServer()) + { + return new StringValue("multiplayer"); + } + final boolean runningLan = server.isPublished(); + if (!runningLan) + { + return new StringValue("singleplayer"); + } + final boolean isowner = server.isSingleplayerOwner(p.getGameProfile()); + if (isowner) + { + return new StringValue("lan_host"); + } return new StringValue("lan player"); // realms? } return Value.NULL; }); - put("client_brand", (e, a) -> { - if (e instanceof ServerPlayer) - { - return StringValue.of(ServerNetworkHandler.getPlayerStatus((ServerPlayer) e)); - } - return Value.NULL; - }); - - put("team", (e, a) -> e.getTeam()==null?Value.NULL:new StringValue(e.getTeam().getName())); - - put("ping", (e, a) -> { - if (e instanceof ServerPlayer) - { - ServerPlayer spe = (ServerPlayer) e; - return new NumericValue(spe.latency); - } - return Value.NULL; - }); + put("client_brand", (e, a) -> e instanceof final ServerPlayer sp ? StringValue.of(ServerNetworkHandler.getPlayerStatus(sp)) : Value.NULL); + put("team", (e, a) -> e.getTeam() == null ? Value.NULL : new StringValue(e.getTeam().getName())); + put("ping", (e, a) -> e instanceof final ServerPlayer sp ? new NumericValue(sp.latency) : Value.NULL); //spectating_entity // isGlowing put("effect", (e, a) -> { - if (!(e instanceof LivingEntity)) + if (!(e instanceof final LivingEntity le)) { return Value.NULL; } if (a == null) { - List effects = new ArrayList<>(); - for (MobEffectInstance p : ((LivingEntity) e).getActiveEffects()) + final List effects = new ArrayList<>(); + for (final MobEffectInstance p : le.getActiveEffects()) { effects.add(ListValue.of( - new StringValue(p.getDescriptionId().replaceFirst("^effect\\.minecraft\\.", "")), - new NumericValue(p.getAmplifier()), - new NumericValue(p.getDuration()) + new StringValue(p.getDescriptionId().replaceFirst("^effect\\.minecraft\\.", "")), + new NumericValue(p.getAmplifier()), + new NumericValue(p.getDuration()) )); } return ListValue.wrap(effects); } - String effectName = a.getString(); - MobEffect potion = BuiltInRegistries.MOB_EFFECT.get(InputValidator.identifierOf(effectName)); + final String effectName = a.getString(); + final MobEffect potion = BuiltInRegistries.MOB_EFFECT.get(InputValidator.identifierOf(effectName)); if (potion == null) - throw new InternalExpressionException("No such an effect: "+effectName); - if (!((LivingEntity) e).hasEffect(potion)) - return Value.NULL; - MobEffectInstance pe = ((LivingEntity) e).getEffect(potion); - return ListValue.of( new NumericValue(pe.getAmplifier()), new NumericValue(pe.getDuration()) ); - }); - - put("health", (e, a) -> - { - if (e instanceof LivingEntity) { - return new NumericValue(((LivingEntity) e).getHealth()); - } - //if (e instanceof ItemEntity) - //{ - // e.h consider making item health public - //} - return Value.NULL; - }); - - put("may_fly", (e, a) -> { - if (e instanceof ServerPlayer player) { - return BooleanValue.of(player.getAbilities().mayfly); - } - return Value.NULL; - }); - - put("flying", (e, v) -> { - if (e instanceof ServerPlayer player) { - return BooleanValue.of(player.getAbilities().flying); + throw new InternalExpressionException("No such an effect: " + effectName); } - return Value.NULL; - }); - - put("may_build", (e, v) -> { - if (e instanceof ServerPlayer player) { - return BooleanValue.of(player.getAbilities().mayBuild); - } - return Value.NULL; - }); - - put("insta_build", (e, v) -> { - if (e instanceof ServerPlayer player) { - return BooleanValue.of(player.getAbilities().instabuild); - } - return Value.NULL; - }); - - put("fly_speed", (e, v) -> { - if (e instanceof ServerPlayer player) { - return NumericValue.of(player.getAbilities().getFlyingSpeed()); - } - return Value.NULL; - }); - - put("walk_speed", (e, v) -> { - if (e instanceof ServerPlayer player) { - return NumericValue.of(player.getAbilities().getWalkingSpeed()); + if (!le.hasEffect(potion)) + { + return Value.NULL; } - return Value.NULL; + final MobEffectInstance pe = le.getEffect(potion); + return ListValue.of(new NumericValue(pe.getAmplifier()), new NumericValue(pe.getDuration())); }); + put("health", (e, a) -> e instanceof final LivingEntity le ? new NumericValue(le.getHealth()) : Value.NULL); + put("may_fly", (e, a) -> e instanceof final ServerPlayer player ? BooleanValue.of(player.getAbilities().mayfly) : Value.NULL); + put("flying", (e, v) -> e instanceof final ServerPlayer player ? BooleanValue.of(player.getAbilities().flying) : Value.NULL); + put("may_build", (e, v) -> e instanceof final ServerPlayer player ? BooleanValue.of(player.getAbilities().mayBuild) : Value.NULL); + put("insta_build", (e, v) -> e instanceof final ServerPlayer player ? BooleanValue.of(player.getAbilities().instabuild) : Value.NULL); + put("fly_speed", (e, v) -> e instanceof final ServerPlayer player ? NumericValue.of(player.getAbilities().getFlyingSpeed()) : Value.NULL); + put("walk_speed", (e, v) -> e instanceof final ServerPlayer player ? NumericValue.of(player.getAbilities().getWalkingSpeed()) : Value.NULL); put("holds", (e, a) -> { EquipmentSlot where = EquipmentSlot.MAINHAND; if (a != null) + { where = inventorySlots.get(a.getString()); + } if (where == null) - throw new InternalExpressionException("Unknown inventory slot: "+a.getString()); - if (e instanceof LivingEntity) - return ValueConversions.of(((LivingEntity)e).getItemBySlot(where), e.getServer().registryAccess()); + { + throw new InternalExpressionException("Unknown inventory slot: " + a.getString()); + } + if (e instanceof final LivingEntity le) + { + return ValueConversions.of(le.getItemBySlot(where), e.getServer().registryAccess()); + } return Value.NULL; }); - put("selected_slot", (e, a) -> { - if (e instanceof Player) - return new NumericValue(((Player) e).getInventory().selected); //getInventory - return Value.NULL; - }); + put("selected_slot", (e, a) -> e instanceof final Player p ? new NumericValue(p.getInventory().selected) : Value.NULL); put("active_block", (e, a) -> { - if (e instanceof ServerPlayer) + if (e instanceof final ServerPlayer sp) { - ServerPlayerInteractionManagerInterface manager = (ServerPlayerInteractionManagerInterface) (((ServerPlayer) e).gameMode); - BlockPos pos = manager.getCurrentBreakingBlock(); - if (pos == null) return Value.NULL; + final ServerPlayerInteractionManagerInterface manager = (ServerPlayerInteractionManagerInterface) (sp.gameMode); + final BlockPos pos = manager.getCurrentBreakingBlock(); + if (pos == null) + { + return Value.NULL; + } return new BlockValue(null, e.level, pos); } return Value.NULL; }); put("breaking_progress", (e, a) -> { - if (e instanceof ServerPlayer) + if (e instanceof final ServerPlayer sp) { - ServerPlayerInteractionManagerInterface manager = (ServerPlayerInteractionManagerInterface) (((ServerPlayer) e).gameMode); - int progress = manager.getCurrentBlockBreakingProgress(); - if (progress < 0) return Value.NULL; - return new NumericValue(progress); + final ServerPlayerInteractionManagerInterface manager = (ServerPlayerInteractionManagerInterface) (sp.gameMode); + final int progress = manager.getCurrentBlockBreakingProgress(); + return progress < 0 ? Value.NULL : new NumericValue(progress); } return Value.NULL; }); @@ -860,9 +728,13 @@ public Value get(String what, Value arg) put("facing", (e, a) -> { int index = 0; if (a != null) - index = (6+(int)NumericValue.asNumber(a).getLong())%6; + { + index = (6 + (int) NumericValue.asNumber(a).getLong()) % 6; + } if (index < 0 || index > 5) + { throw new InternalExpressionException("Facing order should be between -6 and 5"); + } return new StringValue(Direction.orderedByNearest(e)[index].getSerializedName()); }); @@ -875,17 +747,19 @@ public Value get(String what, Value arg) boolean blocks = true; boolean exact = false; - if (a!=null) + if (a != null) { - if (!(a instanceof ListValue)) + if (!(a instanceof final ListValue lv)) { reach = (float) NumericValue.asNumber(a).getDouble(); } else { - List args = ((ListValue) a).getItems(); - if (args.size()==0) + final List args = lv.getItems(); + if (args.size() == 0) + { throw new InternalExpressionException("'trace' needs more arguments"); + } reach = (float) NumericValue.asNumber(args.get(0)).getDouble(); if (args.size() > 1) { @@ -893,114 +767,153 @@ public Value get(String what, Value arg) blocks = false; for (int i = 1; i < args.size(); i++) { - String what = args.get(i).getString(); + final String what = args.get(i).getString(); if (what.equalsIgnoreCase("entities")) + { entities = true; + } else if (what.equalsIgnoreCase("blocks")) + { blocks = true; + } else if (what.equalsIgnoreCase("liquids")) + { liquids = true; + } else if (what.equalsIgnoreCase("exact")) + { exact = true; + } - else throw new InternalExpressionException("Incorrect tracing: "+what); + else + { + throw new InternalExpressionException("Incorrect tracing: " + what); + } } } } } - else if (e instanceof ServerPlayer && ((ServerPlayer) e).gameMode.isCreative()) + else if (e instanceof final ServerPlayer sp && sp.gameMode.isCreative()) { reach = 5.0f; } - HitResult hitres; + final HitResult hitres; if (entities && !blocks) - hitres = Tracer.rayTraceEntities(e, 1, reach, reach*reach); + { + hitres = Tracer.rayTraceEntities(e, 1, reach, reach * reach); + } else if (entities) + { hitres = Tracer.rayTrace(e, 1, reach, liquids); + } else + { hitres = Tracer.rayTraceBlocks(e, 1, reach, liquids); + } - if (hitres == null) return Value.NULL; - if (exact && hitres.getType() != HitResult.Type.MISS) return ValueConversions.of(hitres.getLocation()); + if (hitres == null) + { + return Value.NULL; + } + if (exact && hitres.getType() != HitResult.Type.MISS) + { + return ValueConversions.of(hitres.getLocation()); + } switch (hitres.getType()) { - case MISS: return Value.NULL; - case BLOCK: return new BlockValue(null, e.getCommandSenderWorld(), ((BlockHitResult)hitres).getBlockPos() ); - case ENTITY: return new EntityValue(((EntityHitResult)hitres).getEntity()); + case MISS: + return Value.NULL; + case BLOCK: + return new BlockValue(null, e.getCommandSenderWorld(), ((BlockHitResult) hitres).getBlockPos()); + case ENTITY: + return new EntityValue(((EntityHitResult) hitres).getEntity()); } return Value.NULL; }); - put("attribute", (e, a) ->{ - if (!(e instanceof LivingEntity)) return Value.NULL; - LivingEntity el = (LivingEntity)e; + put("attribute", (e, a) -> { + if (!(e instanceof final LivingEntity el)) + { + return Value.NULL; + } final Registry attributes = e.getLevel().registryAccess().registryOrThrow(Registries.ATTRIBUTE); if (a == null) { - AttributeMap container = el.getAttributes(); + final AttributeMap container = el.getAttributes(); return MapValue.wrap(attributes.stream().filter(container::hasAttribute).collect(Collectors.toMap(aa -> ValueConversions.of(attributes.getKey(aa)), aa -> NumericValue.of(container.getValue(aa))))); } - ResourceLocation id = InputValidator.identifierOf(a.getString()); - Attribute attrib = attributes.getOptional(id).orElseThrow( - () -> new InternalExpressionException("Unknown attribute: "+a.getString()) + final ResourceLocation id = InputValidator.identifierOf(a.getString()); + final Attribute attrib = attributes.getOptional(id).orElseThrow( + () -> new InternalExpressionException("Unknown attribute: " + a.getString()) ); - if (!el.getAttributes().hasAttribute(attrib)) return Value.NULL; + if (!el.getAttributes().hasAttribute(attrib)) + { + return Value.NULL; + } return NumericValue.of(el.getAttributeValue(attrib)); }); - put("nbt",(e, a) -> { - CompoundTag nbttagcompound = e.saveWithoutId((new CompoundTag())); - if (a==null) + put("nbt", (e, a) -> { + final CompoundTag nbttagcompound = e.saveWithoutId((new CompoundTag())); + if (a == null) + { return new NBTSerializableValue(nbttagcompound); + } return new NBTSerializableValue(nbttagcompound).get(a); }); - put("category",(e,a)->{return new StringValue(e.getType().getCategory().toString().toLowerCase(Locale.ROOT));}); + put("category", (e, a) -> { + return new StringValue(e.getType().getCategory().toString().toLowerCase(Locale.ROOT)); + }); }}; - public void set(String what, Value toWhat) + public void set(final String what, final Value toWhat) { if (!(featureModifiers.containsKey(what))) + { throw new InternalExpressionException("Unknown entity action: " + what); + } try { featureModifiers.get(what).accept(getEntity(), toWhat); } - catch (NullPointerException npe) + catch (final NullPointerException npe) { - throw new InternalExpressionException("'modify' for '"+what+"' expects a value"); + throw new InternalExpressionException("'modify' for '" + what + "' expects a value"); } - catch (IndexOutOfBoundsException ind) + catch (final IndexOutOfBoundsException ind) { - throw new InternalExpressionException("Wrong number of arguments for `modify` option: "+what); + throw new InternalExpressionException("Wrong number of arguments for `modify` option: " + what); } } - private static void updatePosition(Entity e, double x, double y, double z, float yaw, float pitch) + private static void updatePosition(final Entity e, final double x, final double y, final double z, final float yaw, final float pitch) { if ( !Double.isFinite(x) || Double.isNaN(x) || - !Double.isFinite(y) || Double.isNaN(y) || - !Double.isFinite(z) || Double.isNaN(z) || - !Float.isFinite(yaw) || Float.isNaN(yaw) || - !Float.isFinite(pitch) || Float.isNaN(pitch) + !Double.isFinite(y) || Double.isNaN(y) || + !Double.isFinite(z) || Double.isNaN(z) || + !Float.isFinite(yaw) || Float.isNaN(yaw) || + !Float.isFinite(pitch) || Float.isNaN(pitch) ) + { return; - if (e instanceof ServerPlayer) + } + if (e instanceof final ServerPlayer sp) { // this forces position but doesn't angles for some reason. Need both in the API in the future. - EnumSet set = EnumSet.noneOf(RelativeMovement.class); + final EnumSet set = EnumSet.noneOf(RelativeMovement.class); set.add(RelativeMovement.X_ROT); set.add(RelativeMovement.Y_ROT); - ((ServerPlayer)e).connection.teleport(x, y, z, yaw, pitch, set ); + sp.connection.teleport(x, y, z, yaw, pitch, set); } else { e.moveTo(x, y, z, yaw, pitch); // we were sending to players for not-living entites, that were untracked. Living entities should be tracked. //((ServerWorld) e.getEntityWorld()).getChunkManager().sendToNearbyPlayers(e, new EntityS2CPacket.(e)); - if (e instanceof LivingEntity le) + if (e instanceof final LivingEntity le) { le.yBodyRotO = le.yRotO = yaw; le.yHeadRotO = le.yHeadRot = yaw; @@ -1015,20 +928,22 @@ private static void updatePosition(Entity e, double x, double y, double z, float } } - private static void updateVelocity(Entity e, double scale) + private static void updateVelocity(final Entity e, final double scale) { e.hurtMarked = true; if (Math.abs(scale) > 10000) - CarpetScriptServer.LOG.warn("Moved entity "+e.getScoreboardName()+" "+e.getName()+" at " +e.position()+" extremely fast: "+e.getDeltaMovement()); - //((ServerWorld)e.getEntityWorld()).method_14178().sendToNearbyPlayers(e, new EntityVelocityUpdateS2CPacket(e)); + { + CarpetScriptServer.LOG.warn("Moved entity " + e.getScoreboardName() + " " + e.getName() + " at " + e.position() + " extremely fast: " + e.getDeltaMovement()); + } } - private static final Map> featureModifiers = new HashMap>() {{ + private static final Map> featureModifiers = new HashMap>() + {{ put("remove", (entity, value) -> entity.discard()); // using discard here - will see other options if valid - put("age", (e, v) -> e.tickCount = Math.abs((int)NumericValue.asNumber(v).getLong()) ); + put("age", (e, v) -> e.tickCount = Math.abs((int) NumericValue.asNumber(v).getLong())); put("health", (e, v) -> { - float health = (float) NumericValue.asNumber(v).getDouble(); - if (health <= 0f && e instanceof ServerPlayer player) + final float health = (float) NumericValue.asNumber(v).getDouble(); + if (health <= 0f && e instanceof final ServerPlayer player) { if (player.containerMenu != null) { @@ -1039,14 +954,19 @@ private static void updateVelocity(Entity e, double scale) } ((LivingEntity) e).setHealth(health); } - if (e instanceof LivingEntity) ((LivingEntity) e).setHealth(health); + if (e instanceof final LivingEntity le) + { + le.setHealth(health); + } }); put("may_fly", (e, v) -> { - boolean mayFly = v.getBoolean(); - if (e instanceof ServerPlayer player) { + final boolean mayFly = v.getBoolean(); + if (e instanceof final ServerPlayer player) + { player.getAbilities().mayfly = mayFly; - if (!mayFly && player.getAbilities().flying) { + if (!mayFly && player.getAbilities().flying) + { player.getAbilities().flying = false; } player.onUpdateAbilities(); @@ -1054,40 +974,45 @@ private static void updateVelocity(Entity e, double scale) }); put("flying", (e, v) -> { - boolean flying = v.getBoolean(); - if (e instanceof ServerPlayer player) { + final boolean flying = v.getBoolean(); + if (e instanceof final ServerPlayer player) + { player.getAbilities().flying = flying; player.onUpdateAbilities(); } }); put("may_build", (e, v) -> { - boolean mayBuild = v.getBoolean(); - if (e instanceof ServerPlayer player) { + final boolean mayBuild = v.getBoolean(); + if (e instanceof final ServerPlayer player) + { player.getAbilities().mayBuild = mayBuild; player.onUpdateAbilities(); } }); put("insta_build", (e, v) -> { - boolean instaBuild = v.getBoolean(); - if (e instanceof ServerPlayer player) { + final boolean instaBuild = v.getBoolean(); + if (e instanceof final ServerPlayer player) + { player.getAbilities().instabuild = instaBuild; player.onUpdateAbilities(); } }); put("fly_speed", (e, v) -> { - float flySpeed = NumericValue.asNumber(v).getFloat(); - if (e instanceof ServerPlayer player) { + final float flySpeed = NumericValue.asNumber(v).getFloat(); + if (e instanceof final ServerPlayer player) + { player.getAbilities().setFlyingSpeed(flySpeed); player.onUpdateAbilities(); } }); put("walk_speed", (e, v) -> { - float walkSpeed = NumericValue.asNumber(v).getFloat(); - if (e instanceof ServerPlayer player) { + final float walkSpeed = NumericValue.asNumber(v).getFloat(); + if (e instanceof final ServerPlayer player) + { player.getAbilities().setWalkingSpeed(walkSpeed); player.onUpdateAbilities(); } @@ -1095,9 +1020,9 @@ private static void updateVelocity(Entity e, double scale) put("selected_slot", (e, v) -> { - if (e instanceof ServerPlayer player) + if (e instanceof final ServerPlayer player) { - int slot = NumericValue.asNumber(v).getInt(); + final int slot = NumericValue.asNumber(v).getInt(); player.connection.send(new ClientboundSetCarriedItemPacket(slot)); } }); @@ -1106,9 +1031,9 @@ private static void updateVelocity(Entity e, double scale) /*put("damage", (e, v) -> { float dmgPoints; DamageSource source; - if (v instanceof ListValue && ((ListValue) v).getItems().size() > 1) + if (v instanceof final ListValue lv && lv.getItems().size() > 1) { - List vals = ((ListValue) v).getItems(); + List vals = lv.getItems(); dmgPoints = (float) NumericValue.asNumber(v).getDouble(); source = DamageSource ... yeah... } @@ -1120,11 +1045,11 @@ private static void updateVelocity(Entity e, double scale) put("kill", (e, v) -> e.kill()); put("location", (e, v) -> { - if (!(v instanceof ListValue)) + if (!(v instanceof final ListValue lv)) { throw new InternalExpressionException("Expected a list of 5 parameters as a second argument"); } - List coords = ((ListValue) v).getItems(); + final List coords = lv.getItems(); updatePosition(e, NumericValue.asNumber(coords.get(0)).getDouble(), NumericValue.asNumber(coords.get(1)).getDouble(), @@ -1135,11 +1060,11 @@ private static void updateVelocity(Entity e, double scale) }); put("pos", (e, v) -> { - if (!(v instanceof ListValue)) + if (!(v instanceof final ListValue lv)) { throw new InternalExpressionException("Expected a list of 3 parameters as a second argument"); } - List coords = ((ListValue) v).getItems(); + final List coords = lv.getItems(); updatePosition(e, NumericValue.asNumber(coords.get(0)).getDouble(), NumericValue.asNumber(coords.get(1)).getDouble(), @@ -1148,55 +1073,46 @@ private static void updateVelocity(Entity e, double scale) e.getXRot() ); }); - put("x", (e, v) -> - { - updatePosition(e, NumericValue.asNumber(v).getDouble(), e.getY(), e.getZ(), e.getYRot(), e.getXRot()); - }); - put("y", (e, v) -> - { - updatePosition(e, e.getX(), NumericValue.asNumber(v).getDouble(), e.getZ(), e.getYRot(), e.getXRot()); - }); - put("z", (e, v) -> - { - updatePosition(e, e.getX(), e.getY(), NumericValue.asNumber(v).getDouble(), e.getYRot(), e.getXRot()); - }); - put("yaw", (e, v) -> - { - updatePosition(e, e.getX(), e.getY(), e.getZ(), ((float)NumericValue.asNumber(v).getDouble()) % 360, e.getXRot()); - }); + put("x", (e, v) -> updatePosition(e, NumericValue.asNumber(v).getDouble(), e.getY(), e.getZ(), e.getYRot(), e.getXRot())); + put("y", (e, v) -> updatePosition(e, e.getX(), NumericValue.asNumber(v).getDouble(), e.getZ(), e.getYRot(), e.getXRot())); + put("z", (e, v) -> updatePosition(e, e.getX(), e.getY(), NumericValue.asNumber(v).getDouble(), e.getYRot(), e.getXRot())); + put("yaw", (e, v) -> updatePosition(e, e.getX(), e.getY(), e.getZ(), ((float) NumericValue.asNumber(v).getDouble()) % 360, e.getXRot())); put("head_yaw", (e, v) -> { if (e instanceof LivingEntity) { - e.setYHeadRot((float)NumericValue.asNumber(v).getDouble() % 360); + e.setYHeadRot((float) NumericValue.asNumber(v).getDouble() % 360); } }); put("body_yaw", (e, v) -> { if (e instanceof LivingEntity) { - e.setYRot((float)NumericValue.asNumber(v).getDouble() % 360); + e.setYRot((float) NumericValue.asNumber(v).getDouble() % 360); } }); - put("pitch", (e, v) -> - { - updatePosition(e, e.getX(), e.getY(), e.getZ(), e.getYRot(), Mth.clamp((float)NumericValue.asNumber(v).getDouble(), -90, 90)); - }); + put("pitch", (e, v) -> updatePosition(e, e.getX(), e.getY(), e.getZ(), e.getYRot(), Mth.clamp((float) NumericValue.asNumber(v).getDouble(), -90, 90))); put("look", (e, v) -> { - if (!(v instanceof ListValue)) throw new InternalExpressionException("Expected a list of 3 parameters as a second argument"); - List vec = ((ListValue)v).getItems(); + if (!(v instanceof final ListValue lv)) + { + throw new InternalExpressionException("Expected a list of 3 parameters as a second argument"); + } + final List vec = lv.getItems(); float x = NumericValue.asNumber(vec.get(0)).getFloat(); float y = NumericValue.asNumber(vec.get(1)).getFloat(); float z = NumericValue.asNumber(vec.get(2)).getFloat(); - float l = Mth.sqrt(x*x + y*y + z*z); - if(l==0) return; + final float l = Mth.sqrt(x * x + y * y + z * z); + if (l == 0) + { + return; + } x /= l; y /= l; z /= l; - float pitch = (float) -Math.asin(y) / 0.017453292F; - float yaw = (float) (x==0 && z==0 ? e.getYRot() : Mth.atan2(-x,z) / 0.017453292F); + final float pitch = (float) -Math.asin(y) / 0.017453292F; + final float yaw = (float) (x == 0 && z == 0 ? e.getYRot() : Mth.atan2(-x, z) / 0.017453292F); updatePosition(e, e.getX(), e.getY(), e.getZ(), yaw, pitch); }); @@ -1205,11 +1121,11 @@ private static void updateVelocity(Entity e, double scale) put("move", (e, v) -> { - if (!(v instanceof ListValue)) + if (!(v instanceof final ListValue lv)) { throw new InternalExpressionException("Expected a list of 3 parameters as a second argument"); } - List coords = ((ListValue) v).getItems(); + final List coords = lv.getItems(); updatePosition(e, e.getX() + NumericValue.asNumber(coords.get(0)).getDouble(), e.getY() + NumericValue.asNumber(coords.get(1)).getDouble(), @@ -1221,46 +1137,46 @@ private static void updateVelocity(Entity e, double scale) put("motion", (e, v) -> { - if (!(v instanceof ListValue)) + if (!(v instanceof final ListValue lv)) { throw new InternalExpressionException("Expected a list of 3 parameters as a second argument"); } - List coords = ((ListValue) v).getItems(); - double dx = NumericValue.asNumber(coords.get(0)).getDouble(); - double dy = NumericValue.asNumber(coords.get(1)).getDouble(); - double dz = NumericValue.asNumber(coords.get(2)).getDouble(); + final List coords = lv.getItems(); + final double dx = NumericValue.asNumber(coords.get(0)).getDouble(); + final double dy = NumericValue.asNumber(coords.get(1)).getDouble(); + final double dz = NumericValue.asNumber(coords.get(2)).getDouble(); e.setDeltaMovement(dx, dy, dz); updateVelocity(e, Mth.absMax(Mth.absMax(dx, dy), dz)); }); put("motion_x", (e, v) -> { - Vec3 velocity = e.getDeltaMovement(); - double dv = NumericValue.asNumber(v).getDouble(); + final Vec3 velocity = e.getDeltaMovement(); + final double dv = NumericValue.asNumber(v).getDouble(); e.setDeltaMovement(dv, velocity.y, velocity.z); updateVelocity(e, dv); }); put("motion_y", (e, v) -> { - Vec3 velocity = e.getDeltaMovement(); - double dv = NumericValue.asNumber(v).getDouble(); + final Vec3 velocity = e.getDeltaMovement(); + final double dv = NumericValue.asNumber(v).getDouble(); e.setDeltaMovement(velocity.x, dv, velocity.z); updateVelocity(e, dv); }); put("motion_z", (e, v) -> { - Vec3 velocity = e.getDeltaMovement(); - double dv = NumericValue.asNumber(v).getDouble(); + final Vec3 velocity = e.getDeltaMovement(); + final double dv = NumericValue.asNumber(v).getDouble(); e.setDeltaMovement(velocity.x, velocity.y, dv); updateVelocity(e, dv); }); put("accelerate", (e, v) -> { - if (!(v instanceof ListValue)) + if (!(v instanceof final ListValue lv)) { throw new InternalExpressionException("Expected a list of 3 parameters as a second argument"); } - List coords = ((ListValue) v).getItems(); + final List coords = lv.getItems(); e.push( NumericValue.asNumber(coords.get(0)).getDouble(), NumericValue.asNumber(coords.get(1)).getDouble(), @@ -1277,10 +1193,10 @@ private static void updateVelocity(Entity e, double scale) return; } boolean showName = false; - if (v instanceof ListValue) + if (v instanceof final ListValue lv) { - showName = ((ListValue) v).getItems().get(1).getBoolean(); - v = ((ListValue) v).getItems().get(0); + showName = lv.getItems().get(1).getBoolean(); + v = lv.getItems().get(0); } e.setCustomNameVisible(showName); e.setCustomName(FormattedTextValue.getTextByValue(v)); @@ -1288,54 +1204,83 @@ private static void updateVelocity(Entity e, double scale) put("persistence", (e, v) -> { - if (!(e instanceof Mob)) return; - if (v == null) v = Value.TRUE; - ((MobEntityInterface)e).setPersistence(v.getBoolean()); + if (!(e instanceof Mob)) + { + return; + } + if (v == null) + { + v = Value.TRUE; + } + ((MobEntityInterface) e).setPersistence(v.getBoolean()); }); - put("dismount", (e, v) -> e.stopRiding() ); + put("dismount", (e, v) -> e.stopRiding()); put("mount", (e, v) -> { - if (v instanceof EntityValue) + if (v instanceof final EntityValue ev) { - e.startRiding(((EntityValue) v).getEntity(),true); + e.startRiding(ev.getEntity(), true); } - if (e instanceof ServerPlayer) + if (e instanceof final ServerPlayer sp) { - ((ServerPlayer)e).connection.send(new ClientboundSetPassengersPacket(e)); - //... + sp.connection.send(new ClientboundSetPassengersPacket(e)); } }); - put("unmountable", (e, v) ->{ - if (v == null) - v = Value.TRUE; - ((EntityInterface)e).setPermanentVehicle(v.getBoolean()); - }); + put("unmountable", (e, v) -> ((EntityInterface) e).setPermanentVehicle(v == null || v.getBoolean())); put("drop_passengers", (e, v) -> e.ejectPassengers()); put("mount_passengers", (e, v) -> { - if (v==null) + if (v == null) + { throw new InternalExpressionException("'mount_passengers' needs entities to ride"); - if (v instanceof EntityValue) - ((EntityValue) v).getEntity().startRiding(e); - else if (v instanceof ListValue) - for (Value element : ((ListValue) v).getItems()) - if (element instanceof EntityValue) - ((EntityValue) element).getEntity().startRiding(e); + } + if (v instanceof final EntityValue ev) + { + ev.getEntity().startRiding(e); + } + else if (v instanceof final ListValue lv) + { + for (final Value element : lv.getItems()) + { + if (element instanceof final EntityValue ev) + { + ev.getEntity().startRiding(e); + } + } + } }); put("tag", (e, v) -> { - if (v==null) + if (v == null) + { throw new InternalExpressionException("'tag' requires parameters"); - if (v instanceof ListValue) - for (Value element : ((ListValue) v).getItems()) e.addTag(element.getString()); + } + if (v instanceof final ListValue lv) + { + for (final Value element : lv.getItems()) + { + e.addTag(element.getString()); + } + } else + { e.addTag(v.getString()); + } }); put("clear_tag", (e, v) -> { - if (v==null) + if (v == null) + { throw new InternalExpressionException("'clear_tag' requires parameters"); - if (v instanceof ListValue) - for (Value element : ((ListValue) v).getItems()) e.removeTag(element.getString()); + } + if (v instanceof final ListValue lv) + { + for (final Value element : lv.getItems()) + { + e.removeTag(element.getString()); + } + } else + { e.removeTag(v.getString()); + } }); //put("target", (e, v) -> { // // attacks indefinitely - might need to do it through tasks @@ -1347,96 +1292,110 @@ else if (v instanceof ListValue) //}); put("breeding_age", (e, v) -> { - if (e instanceof AgeableMob) + if (e instanceof final AgeableMob am) { - ((AgeableMob) e).setAge((int)NumericValue.asNumber(v).getLong()); + am.setAge((int) NumericValue.asNumber(v).getLong()); } }); put("talk", (e, v) -> { // attacks indefinitely - if (e instanceof Mob) + if (e instanceof final Mob mob) { - ((Mob) e).playAmbientSound(); + mob.playAmbientSound(); } }); put("home", (e, v) -> { - if (!(e instanceof PathfinderMob)) + if (!(e instanceof final PathfinderMob ec)) + { return; - PathfinderMob ec = (PathfinderMob)e; + } if (v == null) + { throw new InternalExpressionException("'home' requires at least one position argument, and optional distance, or null to cancel"); + } if (v.isNull()) { ec.restrictTo(BlockPos.ZERO, -1); - Map tasks = ((MobEntityInterface)ec).getTemporaryTasks(); - ((MobEntityInterface)ec).getAI(false).removeGoal(tasks.get("home")); + final Map tasks = ((MobEntityInterface) ec).getTemporaryTasks(); + ((MobEntityInterface) ec).getAI(false).removeGoal(tasks.get("home")); tasks.remove("home"); return; } - BlockPos pos; + final BlockPos pos; int distance = 16; - if (v instanceof BlockValue) + if (v instanceof final BlockValue bv) { - pos = ((BlockValue) v).getPos(); - if (pos == null) throw new InternalExpressionException("Block is not positioned in the world"); + pos = bv.getPos(); + if (pos == null) + { + throw new InternalExpressionException("Block is not positioned in the world"); + } } - else if (v instanceof ListValue) + else if (v instanceof final ListValue lv) { - List lv = ((ListValue) v).getItems(); - Vector3Argument locator = Vector3Argument.findIn(lv, 0, false, false); + final List list = lv.getItems(); + final Vector3Argument locator = Vector3Argument.findIn(list, 0, false, false); pos = new BlockPos(locator.vec.x, locator.vec.y, locator.vec.z); - if (lv.size() > locator.offset) + if (list.size() > locator.offset) { - distance = (int) NumericValue.asNumber(lv.get(locator.offset)).getLong(); + distance = (int) NumericValue.asNumber(list.get(locator.offset)).getLong(); } } - else throw new InternalExpressionException("'home' requires at least one position argument, and optional distance"); + else + { + throw new InternalExpressionException("'home' requires at least one position argument, and optional distance"); + } ec.restrictTo(pos, distance); - Map tasks = ((MobEntityInterface)ec).getTemporaryTasks(); + final Map tasks = ((MobEntityInterface) ec).getTemporaryTasks(); if (!tasks.containsKey("home")) { - Goal task = new MoveTowardsRestrictionGoal(ec, 1.0D); + final Goal task = new MoveTowardsRestrictionGoal(ec, 1.0D); tasks.put("home", task); - ((MobEntityInterface)ec).getAI(false).addGoal(10, task); + ((MobEntityInterface) ec).getAI(false).addGoal(10, task); } }); //requires mixing put("spawn_point", (e, a) -> { - if (!(e instanceof ServerPlayer spe)) return; + if (!(e instanceof final ServerPlayer spe)) + { + return; + } if (a == null) { spe.setRespawnPosition(null, null, 0, false, false); } - else if (a instanceof ListValue) + else if (a instanceof final ListValue lv) { - List params= ((ListValue) a).getItems(); - Vector3Argument blockLocator = Vector3Argument.findIn(params, 0, false, false); - BlockPos pos = new BlockPos(blockLocator.vec); + final List params = lv.getItems(); + final Vector3Argument blockLocator = Vector3Argument.findIn(params, 0, false, false); + final BlockPos pos = new BlockPos(blockLocator.vec); ResourceKey world = spe.getCommandSenderWorld().dimension(); float angle = spe.getYHeadRot(); boolean forced = false; if (params.size() > blockLocator.offset) { - Value worldValue = params.get(blockLocator.offset+0); + final Value worldValue = params.get(blockLocator.offset + 0); world = ValueConversions.dimFromValue(worldValue, spe.getServer()).dimension(); - if (params.size() > blockLocator.offset+1) + if (params.size() > blockLocator.offset + 1) { - angle = NumericValue.asNumber(params.get(blockLocator.offset+1), "angle").getFloat(); - if (params.size() > blockLocator.offset+2) + angle = NumericValue.asNumber(params.get(blockLocator.offset + 1), "angle").getFloat(); + if (params.size() > blockLocator.offset + 2) { - forced = params.get(blockLocator.offset+2).getBoolean(); + forced = params.get(blockLocator.offset + 2).getBoolean(); } } } spe.setRespawnPosition(world, pos, angle, forced, false); } - else if (a instanceof BlockValue bv) + else if (a instanceof final BlockValue bv) { - if (bv.getPos()==null || bv.getWorld() == null) + if (bv.getPos() == null || bv.getWorld() == null) + { throw new InternalExpressionException("block for spawn modification should be localised in the world"); + } spe.setRespawnPosition(bv.getWorld().dimension(), bv.getPos(), e.getYRot(), true, false); // yaw } else if (a.isNull()) @@ -1446,128 +1405,159 @@ else if (a.isNull()) else { throw new InternalExpressionException("modifying player respawn point requires a block position, optional world, optional angle, and optional force"); - } }); put("pickup_delay", (e, v) -> { - if (e instanceof ItemEntity) + if (e instanceof final ItemEntity ie) { - ((ItemEntity) e).setPickUpDelay((int)NumericValue.asNumber(v).getLong()); + ie.setPickUpDelay((int) NumericValue.asNumber(v).getLong()); } }); put("despawn_timer", (e, v) -> { - if (e instanceof LivingEntity) + if (e instanceof final LivingEntity le) { - ((LivingEntity) e).setNoActionTime((int)NumericValue.asNumber(v).getLong()); + le.setNoActionTime((int) NumericValue.asNumber(v).getLong()); } }); - put("portal_cooldown", (e , v) -> + put("portal_cooldown", (e, v) -> { - if (v==null) + if (v == null) + { throw new InternalExpressionException("'portal_cooldown' requires a value to set"); - ((EntityInterface)e).setPublicNetherPortalCooldown(NumericValue.asNumber(v).getInt()); + } + ((EntityInterface) e).setPublicNetherPortalCooldown(NumericValue.asNumber(v).getInt()); }); - put("portal_timer", (e , v) -> + put("portal_timer", (e, v) -> { - if (v==null) + if (v == null) + { throw new InternalExpressionException("'portal_timer' requires a value to set"); + } ((EntityInterface) e).setPortalTimer(NumericValue.asNumber(v).getInt()); }); put("ai", (e, v) -> { - if (e instanceof Mob) + if (e instanceof final Mob mob) { - ((Mob) e).setNoAi(!v.getBoolean()); + mob.setNoAi(!v.getBoolean()); } }); put("no_clip", (e, v) -> { if (v == null) + { e.noPhysics = true; + } else + { e.noPhysics = v.getBoolean(); + } }); put("effect", (e, v) -> { - if (!(e instanceof LivingEntity le)) return; + if (!(e instanceof final LivingEntity le)) + { + return; + } if (v == null) { le.removeAllEffects(); return; } - else if (v instanceof ListValue) + else if (v instanceof final ListValue lv) { - List lv = ((ListValue) v).getItems(); - if (lv.size() >= 1 && lv.size() <= 6) + final List list = lv.getItems(); + if (list.size() >= 1 && list.size() <= 6) { - String effectName = lv.get(0).getString(); - MobEffect effect = BuiltInRegistries.MOB_EFFECT.get(InputValidator.identifierOf(effectName)); + final String effectName = list.get(0).getString(); + final MobEffect effect = BuiltInRegistries.MOB_EFFECT.get(InputValidator.identifierOf(effectName)); if (effect == null) - throw new InternalExpressionException("Wrong effect name: "+effectName); - if (lv.size() == 1) + { + throw new InternalExpressionException("Wrong effect name: " + effectName); + } + if (list.size() == 1) { le.removeEffect(effect); return; } - int duration = (int)NumericValue.asNumber(lv.get(1)).getLong(); + final int duration = (int) NumericValue.asNumber(list.get(1)).getLong(); if (duration <= 0) { le.removeEffect(effect); return; } int amplifier = 0; - if (lv.size() > 2) - amplifier = (int)NumericValue.asNumber(lv.get(2)).getLong(); + if (list.size() > 2) + { + amplifier = (int) NumericValue.asNumber(list.get(2)).getLong(); + } boolean showParticles = true; - if (lv.size() > 3) - showParticles = lv.get(3).getBoolean(); + if (list.size() > 3) + { + showParticles = list.get(3).getBoolean(); + } boolean showIcon = true; - if (lv.size() > 4) - showIcon = lv.get(4).getBoolean(); + if (list.size() > 4) + { + showIcon = list.get(4).getBoolean(); + } boolean ambient = false; - if (lv.size() > 5) - ambient = lv.get(5).getBoolean(); + if (list.size() > 5) + { + ambient = list.get(5).getBoolean(); + } le.addEffect(new MobEffectInstance(effect, duration, amplifier, ambient, showParticles, showIcon)); return; } } else { - String effectName = v.getString(); - MobEffect effect = BuiltInRegistries.MOB_EFFECT.get(InputValidator.identifierOf(effectName)); + final String effectName = v.getString(); + final MobEffect effect = BuiltInRegistries.MOB_EFFECT.get(InputValidator.identifierOf(effectName)); if (effect == null) - throw new InternalExpressionException("Wrong effect name: "+effectName); + { + throw new InternalExpressionException("Wrong effect name: " + effectName); + } le.removeEffect(effect); return; } throw new InternalExpressionException("'effect' needs either no arguments (clear) or effect name, duration, and optional amplifier, show particles, show icon and ambient"); }); - put("gamemode", (e,v)->{ - if(!(e instanceof ServerPlayer)) return; - GameType toSet = v instanceof NumericValue ? - GameType.byId(((NumericValue) v).getInt()) : + put("gamemode", (e, v) -> { + if (!(e instanceof final ServerPlayer sp)) + { + return; + } + final GameType toSet = v instanceof final NumericValue number ? + GameType.byId(number.getInt()) : GameType.byName(v.getString().toLowerCase(Locale.ROOT), null); - if (toSet != null) ((ServerPlayer) e).setGameMode(toSet); + if (toSet != null) + { + sp.setGameMode(toSet); + } }); - put("jumping",(e,v)->{ - if(!(e instanceof LivingEntity)) return; - ((LivingEntity) e).setJumping(v.getBoolean()); + put("jumping", (e, v) -> { + if (!(e instanceof final LivingEntity le)) + { + return; + } + le.setJumping(v.getBoolean()); }); - put("jump",(e,v)->{ + put("jump", (e, v) -> { if (e instanceof LivingEntity) { - ((LivingEntityInterface)e).doJumpCM(); + ((LivingEntityInterface) e).doJumpCM(); } else { @@ -1576,83 +1566,112 @@ else if (v instanceof ListValue) }); put("swing", (e, v) -> { - if (e instanceof LivingEntity) + if (e instanceof final LivingEntity le) { InteractionHand hand = InteractionHand.MAIN_HAND; if (v != null) { - String handString = v.getString().toLowerCase(Locale.ROOT); - if (handString.equals("offhand") || handString.equals("off_hand")) hand = InteractionHand.OFF_HAND; + final String handString = v.getString().toLowerCase(Locale.ROOT); + if (handString.equals("offhand") || handString.equals("off_hand")) + { + hand = InteractionHand.OFF_HAND; + } } - ((LivingEntity)e).swing(hand, true); + le.swing(hand, true); } }); - put("silent",(e,v)-> e.setSilent(v.getBoolean())); + put("silent", (e, v) -> e.setSilent(v.getBoolean())); - put("gravity",(e,v)-> e.setNoGravity(!v.getBoolean())); + put("gravity", (e, v) -> e.setNoGravity(!v.getBoolean())); - put("invulnerable",(e,v)-> { - boolean invulnerable = v.getBoolean(); - if (e instanceof ServerPlayer player) { + put("invulnerable", (e, v) -> { + final boolean invulnerable = v.getBoolean(); + if (e instanceof final ServerPlayer player) + { player.getAbilities().invulnerable = invulnerable; player.onUpdateAbilities(); - } else { + } + else + { e.setInvulnerable(invulnerable); } }); - put("fire",(e,v)-> e.setRemainingFireTicks((int)NumericValue.asNumber(v).getLong())); - put("frost",(e,v)-> e.setTicksFrozen((int)NumericValue.asNumber(v).getLong())); + put("fire", (e, v) -> e.setRemainingFireTicks((int) NumericValue.asNumber(v).getLong())); + put("frost", (e, v) -> e.setTicksFrozen((int) NumericValue.asNumber(v).getLong())); - put("hunger", (e, v)-> { - if(e instanceof Player) ((Player) e).getFoodData().setFoodLevel((int) NumericValue.asNumber(v).getLong()); + put("hunger", (e, v) -> { + if (e instanceof final Player p) + { + p.getFoodData().setFoodLevel((int) NumericValue.asNumber(v).getLong()); + } }); - put("exhaustion", (e, v)-> { - if(e instanceof Player) ((Player) e).getFoodData().setExhaustion(NumericValue.asNumber(v).getFloat()); + put("exhaustion", (e, v) -> { + if (e instanceof final Player p) + { + p.getFoodData().setExhaustion(NumericValue.asNumber(v).getFloat()); + } }); - put("add_exhaustion", (e, v)-> { - if (e instanceof Player) ((Player) e).getFoodData().addExhaustion(NumericValue.asNumber(v).getFloat()); + put("add_exhaustion", (e, v) -> { + if (e instanceof final Player p) + { + p.getFoodData().addExhaustion(NumericValue.asNumber(v).getFloat()); + } }); put("absorption", (e, v) -> { - if (e instanceof Player) ((Player) e).setAbsorptionAmount(NumericValue.asNumber(v, "absorbtion").getFloat()); + if (e instanceof final Player p) + { + p.setAbsorptionAmount(NumericValue.asNumber(v, "absorbtion").getFloat()); + } }); put("add_xp", (e, v) -> { - if (e instanceof Player) ((Player) e).giveExperiencePoints(NumericValue.asNumber(v, "add_xp").getInt()); + if (e instanceof final Player p) + { + p.giveExperiencePoints(NumericValue.asNumber(v, "add_xp").getInt()); + } }); put("xp_level", (e, v) -> { - if (e instanceof Player) ((Player) e).giveExperienceLevels(NumericValue.asNumber(v, "xp_level").getInt()-((Player) e).experienceLevel); + if (e instanceof final Player p) + { + p.giveExperienceLevels(NumericValue.asNumber(v, "xp_level").getInt() - p.experienceLevel); + } }); put("xp_progress", (e, v) -> { - if (e instanceof ServerPlayer) + if (e instanceof final ServerPlayer p) { - ServerPlayer p = (ServerPlayer) e; p.experienceProgress = NumericValue.asNumber(v, "xp_progress").getFloat(); p.connection.send(new ClientboundSetExperiencePacket(p.experienceProgress, p.totalExperience, p.experienceLevel)); } }); put("xp_score", (e, v) -> { - if (e instanceof Player) ((Player) e).setScore(NumericValue.asNumber(v, "xp_score").getInt()); + if (e instanceof final Player p) + { + p.setScore(NumericValue.asNumber(v, "xp_score").getInt()); + } }); - put("saturation", (e, v)-> { - if(e instanceof Player) ((Player) e).getFoodData().setSaturation(NumericValue.asNumber(v, "saturation").getFloat()); + put("saturation", (e, v) -> { + if (e instanceof final Player p) + { + p.getFoodData().setSaturation(NumericValue.asNumber(v, "saturation").getFloat()); + } }); put("air", (e, v) -> e.setAirSupply(NumericValue.asNumber(v, "air").getInt())); put("breaking_progress", (e, a) -> { - if (e instanceof ServerPlayer) + if (e instanceof final ServerPlayer sp) { - int progress = (a == null || a.isNull())?-1:NumericValue.asNumber(a).getInt(); - ServerPlayerInteractionManagerInterface manager = (ServerPlayerInteractionManagerInterface) (((ServerPlayer) e).gameMode); + final int progress = (a == null || a.isNull()) ? -1 : NumericValue.asNumber(a).getInt(); + final ServerPlayerInteractionManagerInterface manager = (ServerPlayerInteractionManagerInterface) (sp.gameMode); manager.setBlockBreakingProgress(progress); } }); @@ -1660,11 +1679,11 @@ else if (v instanceof ListValue) put("nbt", (e, v) -> { if (!(e instanceof Player)) { - UUID uUID = e.getUUID(); - Value tagValue = NBTSerializableValue.fromValue(v); - if (tagValue instanceof NBTSerializableValue) + final UUID uUID = e.getUUID(); + final Value tagValue = NBTSerializableValue.fromValue(v); + if (tagValue instanceof final NBTSerializableValue nbtsv) { - e.load(((NBTSerializableValue) tagValue).getCompoundTag()); + e.load(nbtsv.getCompoundTag()); e.setUUID(uUID); } } @@ -1672,56 +1691,67 @@ else if (v instanceof ListValue) put("nbt_merge", (e, v) -> { if (!(e instanceof Player)) { - UUID uUID = e.getUUID(); - Value tagValue = NBTSerializableValue.fromValue(v); - if (tagValue instanceof NBTSerializableValue) + final UUID uUID = e.getUUID(); + final Value tagValue = NBTSerializableValue.fromValue(v); + if (tagValue instanceof final NBTSerializableValue nbtsv) { - CompoundTag nbttagcompound = e.saveWithoutId((new CompoundTag())); - nbttagcompound.merge(((NBTSerializableValue) tagValue).getCompoundTag()); + final CompoundTag nbttagcompound = e.saveWithoutId((new CompoundTag())); + nbttagcompound.merge(nbtsv.getCompoundTag()); e.load(nbttagcompound); e.setUUID(uUID); } } }); - put("blue_skull",(e,v)->{ - if (e instanceof WitherSkull w){ + put("blue_skull", (e, v) -> { + if (e instanceof final WitherSkull w) + { w.setDangerous(v.getBoolean()); } - + }); - put("offering_flower",(e,v)->{ - if (e instanceof IronGolem ig){ + put("offering_flower", (e, v) -> { + if (e instanceof final IronGolem ig) + { ig.offerFlower(v.getBoolean()); } - + }); put("item", (e, v) -> { - ItemStack item=ValueConversions.getItemStackFromValue(v, true, e.level.registryAccess()); - if(e instanceof ItemEntity itementity) - itementity.setItem(item); - if(e instanceof ItemFrame itemframe) - itemframe.setItem(item); + final ItemStack item = ValueConversions.getItemStackFromValue(v, true, e.level.registryAccess()); + if (e instanceof final ItemEntity itementity) + { + itementity.setItem(item); + } + if (e instanceof final ItemFrame itemframe) + { + itemframe.setItem(item); + } }); // "dimension" [] // "count", [] // "effect_"name [] }}; - public void setEvent(CarpetContext cc, String eventName, FunctionValue fun, List args) + public void setEvent(final CarpetContext cc, final String eventName, final FunctionValue fun, final List args) { - EntityEventsGroup.Event event = EntityEventsGroup.Event.byName.get(eventName); + final EntityEventsGroup.Event event = EntityEventsGroup.Event.byName.get(eventName); if (event == null) + { throw new InternalExpressionException("Unknown entity event: " + eventName); - ((EntityInterface)getEntity()).getEventContainer().addEvent(event, cc.host, fun, args); + } + ((EntityInterface) getEntity()).getEventContainer().addEvent(event, cc.host, fun, args); } @Override - public net.minecraft.nbt.Tag toTag(boolean force) + public net.minecraft.nbt.Tag toTag(final boolean force) { - if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this); - CompoundTag tag = new CompoundTag(); - tag.put("Data", getEntity().saveWithoutId( new CompoundTag())); + if (!force) + { + throw new NBTSerializableValue.IncompatibleTypeException(this); + } + final CompoundTag tag = new CompoundTag(); + tag.put("Data", getEntity().saveWithoutId(new CompoundTag())); final Registry> reg = getEntity().level.registryAccess().registryOrThrow(Registries.ENTITY_TYPE); tag.put("Name", StringTag.valueOf(reg.getKey(getEntity().getType()).toString())); return tag; diff --git a/src/main/java/carpet/script/value/FormattedTextValue.java b/src/main/java/carpet/script/value/FormattedTextValue.java index 815ad318eb..d55e3190ab 100644 --- a/src/main/java/carpet/script/value/FormattedTextValue.java +++ b/src/main/java/carpet/script/value/FormattedTextValue.java @@ -9,51 +9,56 @@ public class FormattedTextValue extends StringValue { Component text; - public FormattedTextValue(Component text) + + public FormattedTextValue(final Component text) { super(null); this.text = text; } - public static Value combine(Value left, Value right) { - MutableComponent text; - if (left instanceof FormattedTextValue) + public static Value combine(final Value left, final Value right) + { + final MutableComponent text; + if (left instanceof final FormattedTextValue ftv) { - text = ((FormattedTextValue) left).getText().copy(); + text = ftv.getText().copy(); } else { if (left.isNull()) + { return right; + } text = Component.literal(left.getString()); } - - if (right instanceof FormattedTextValue) + + if (right instanceof final FormattedTextValue ftv) { - text.append(((FormattedTextValue) right).getText().copy()); + text.append(ftv.getText().copy()); return new FormattedTextValue(text); } - else + if (right.isNull()) { - if (right.isNull()) - return left; - text.append(right.getString()); - return new FormattedTextValue(text); + return left; } + text.append(right.getString()); + return new FormattedTextValue(text); } - public static Value of(Component text) { - if (text == null) return Value.NULL; - return new FormattedTextValue(text); + public static Value of(final Component text) + { + return text == null ? Value.NULL : new FormattedTextValue(text); } @Override - public String getString() { + public String getString() + { return text.getString(); } @Override - public boolean getBoolean() { + public boolean getBoolean() + { return !text.getString().isEmpty(); } @@ -75,19 +80,24 @@ public Component getText() } @Override - public Tag toTag(boolean force) + public Tag toTag(final boolean force) { - if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this); + if (!force) + { + throw new NBTSerializableValue.IncompatibleTypeException(this); + } return StringTag.valueOf(Component.Serializer.toJson(text)); } @Override - public JsonElement toJson() { + public JsonElement toJson() + { return Component.Serializer.toJsonTree(text); } @Override - public Value add(Value o) { + public Value add(final Value o) + { return combine(this, o); } @@ -96,13 +106,14 @@ public String serialize() return Component.Serializer.toJson(text); } - public static FormattedTextValue deserialize(String serialized) + public static FormattedTextValue deserialize(final String serialized) { return new FormattedTextValue(Component.Serializer.fromJson(serialized)); } - public static Component getTextByValue(Value value) { - return (value instanceof FormattedTextValue) ? ((FormattedTextValue) value).getText() : Component.literal(value.getString()); + public static Component getTextByValue(final Value value) + { + return (value instanceof final FormattedTextValue ftv) ? ftv.getText() : Component.literal(value.getString()); } } diff --git a/src/main/java/carpet/script/value/FrameworkValue.java b/src/main/java/carpet/script/value/FrameworkValue.java index a432974e5c..c1987711f2 100644 --- a/src/main/java/carpet/script/value/FrameworkValue.java +++ b/src/main/java/carpet/script/value/FrameworkValue.java @@ -29,7 +29,7 @@ public int hashCode() } @Override - public Tag toTag(boolean force) + public Tag toTag(final boolean force) { throw new UnsupportedOperationException("Scarpet language component cannot be serialized to the tag"); } diff --git a/src/main/java/carpet/script/value/FunctionAnnotationValue.java b/src/main/java/carpet/script/value/FunctionAnnotationValue.java index 41ba79142f..83b8f2f16e 100644 --- a/src/main/java/carpet/script/value/FunctionAnnotationValue.java +++ b/src/main/java/carpet/script/value/FunctionAnnotationValue.java @@ -9,11 +9,15 @@ public enum Type { GLOBAL, VARARG } + public Type type; - public FunctionAnnotationValue(Value variable, Type type) + + public FunctionAnnotationValue(final Value variable, final Type type) { if (variable.boundVariable == null) + { throw new InternalExpressionException("You can only borrow variables from the outer scope"); + } this.boundVariable = variable.boundVariable; this.type = type; } @@ -37,7 +41,7 @@ public int hashCode() } @Override - public Tag toTag(boolean force) + public Tag toTag(final boolean force) { throw new UnsupportedOperationException("Global value cannot be serialized to the tag"); } diff --git a/src/main/java/carpet/script/value/FunctionSignatureValue.java b/src/main/java/carpet/script/value/FunctionSignatureValue.java index e1c2f14852..59ed5290a9 100644 --- a/src/main/java/carpet/script/value/FunctionSignatureValue.java +++ b/src/main/java/carpet/script/value/FunctionSignatureValue.java @@ -9,23 +9,21 @@ public class FunctionSignatureValue extends FrameworkValue private List globals; private String varArgs; - public FunctionSignatureValue(String name, List args, String varArgs, List globals) + public FunctionSignatureValue(final String name, final List args, final String varArgs, final List globals) { this.identifier = name; this.arguments = args; this.varArgs = varArgs; this.globals = globals; } - public String getName() + public String identifier() { return identifier; } - public List getArgs() + public List arguments() { return arguments; } - public List getGlobals() {return globals;} - - - public String getVarArgs() { return varArgs;} + public List globals() {return globals;} + public String varArgs() { return varArgs;} } diff --git a/src/main/java/carpet/script/value/FunctionUnpackedArgumentsValue.java b/src/main/java/carpet/script/value/FunctionUnpackedArgumentsValue.java index e33a64eb06..4e00ecc94f 100644 --- a/src/main/java/carpet/script/value/FunctionUnpackedArgumentsValue.java +++ b/src/main/java/carpet/script/value/FunctionUnpackedArgumentsValue.java @@ -4,7 +4,8 @@ public class FunctionUnpackedArgumentsValue extends ListValue { - public FunctionUnpackedArgumentsValue(List list) { + public FunctionUnpackedArgumentsValue(final List list) + { super(list); } @@ -17,7 +18,6 @@ public Value clone() @Override public Value deepcopy() { - ListValue copy = (ListValue)super.deepcopy(); - return new FunctionUnpackedArgumentsValue(copy.items); + return new FunctionUnpackedArgumentsValue(((ListValue) super.deepcopy()).items); } } diff --git a/src/main/java/carpet/script/value/FunctionValue.java b/src/main/java/carpet/script/value/FunctionValue.java index d714713726..8ee3780ddf 100644 --- a/src/main/java/carpet/script/value/FunctionValue.java +++ b/src/main/java/carpet/script/value/FunctionValue.java @@ -12,12 +12,14 @@ import carpet.script.exception.ExpressionException; import carpet.script.exception.InternalExpressionException; import carpet.script.exception.ReturnStatement; + import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.stream.Collectors; + import net.minecraft.nbt.StringTag; import net.minecraft.nbt.Tag; @@ -33,7 +35,7 @@ public class FunctionValue extends Value implements Fluff.ILazyFunction private static long variantCounter = 1; private long variant; - private FunctionValue(Expression expression, Tokenizer.Token token, String name, LazyValue body, List args, String varArgs) + private FunctionValue(final Expression expression, final Tokenizer.Token token, final String name, final LazyValue body, final List args, final String varArgs) { this.expression = expression; this.token = token; @@ -45,7 +47,7 @@ private FunctionValue(Expression expression, Tokenizer.Token token, String name, variant = 0L; } - public FunctionValue(Expression expression, Tokenizer.Token token, String name, LazyValue body, List args, String varArgs, Map outerState) + public FunctionValue(final Expression expression, final Tokenizer.Token token, final String name, final LazyValue body, final List args, final String varArgs, final Map outerState) { this.expression = expression; this.token = token; @@ -63,19 +65,27 @@ public String getString() return name; } - public Module getModule() {return expression.module;} + public Module getModule() + { + return expression.module; + } @Override public String getPrettyString() { - List stringArgs= new ArrayList<>(args); + final List stringArgs = new ArrayList<>(args); if (outerState != null) + { stringArgs.addAll(outerState.entrySet().stream().map(e -> - "outer("+e.getKey()+") = "+e.getValue().evalValue(null).getPrettyString()).collect(Collectors.toList())); - return (name.equals("_")?"":name) +"("+String.join(", ",stringArgs)+")"; + "outer(" + e.getKey() + ") = " + e.getValue().evalValue(null).getPrettyString()).toList()); + } + return (name.equals("_") ? "" : name) + "(" + String.join(", ", stringArgs) + ")"; } - public String fullName() {return (name.equals("_")?"":name)+(expression.module == null?"":"["+expression.module.name()+"]");} + public String fullName() + { + return (name.equals("_") ? "" : name) + (expression.module == null ? "" : "[" + expression.module.name() + "]"); + } @Override public boolean getBoolean() @@ -86,7 +96,7 @@ public boolean getBoolean() @Override protected Value clone() { - FunctionValue ret = new FunctionValue(expression, token, name, body, args, varArgs); + final FunctionValue ret = new FunctionValue(expression, token, name, body, args, varArgs); ret.outerState = this.outerState; ret.variant = this.variant; return ret; @@ -95,26 +105,22 @@ protected Value clone() @Override public int hashCode() { - return name.hashCode()+(int)variant; + return name.hashCode() + (int) variant; } @Override - public boolean equals(Object o) + public boolean equals(final Object o) { - if (o instanceof FunctionValue) - return name.equals(((FunctionValue) o).name) && variant == ((FunctionValue) o).variant; - return false; + return o instanceof final FunctionValue fv && name.equals(fv.name) && variant == fv.variant; } @Override public int compareTo(final Value o) { - if (o instanceof FunctionValue) + if (o instanceof final FunctionValue fv) { - int nameSame = this.name.compareTo(((FunctionValue) o).name); - if (nameSame != 0) - return nameSame; - return (int) (variant-((FunctionValue) o).variant); + final int nameSame = this.name.compareTo(fv.name); + return nameSame != 0 ? nameSame : (int) (variant - fv.variant); } return getString().compareTo(o.getString()); } @@ -132,7 +138,7 @@ public String getTypeString() } @Override - public Value slice(long from, Long to) + public Value slice(final long from, final Long to) { throw new InternalExpressionException("Cannot slice a function"); } @@ -149,46 +155,49 @@ public boolean numParamsVaries() return varArgs != null; } - public LazyValue callInContext(Context c, Context.Type type, List params) + public LazyValue callInContext(final Context c, final Context.Type type, final List params) { try { return execute(c, type, expression, token, params); } - catch (ExpressionException exc) + catch (final ExpressionException exc) { exc.stack.add(this); throw exc; } - catch (InternalExpressionException exc) + catch (final InternalExpressionException exc) { exc.stack.add(this); throw new ExpressionException(c, expression, token, exc.getMessage(), exc.stack); } - - catch (ArithmeticException exc) + catch (final ArithmeticException exc) { - throw new ExpressionException(c, expression, token, "Your math is wrong, "+exc.getMessage(), Collections.singletonList(this)); + throw new ExpressionException(c, expression, token, "Your math is wrong, " + exc.getMessage(), Collections.singletonList(this)); } } - public void checkArgs(int candidates) + public void checkArgs(final int candidates) { - int actual = getArguments().size(); + final int actual = getArguments().size(); if (candidates < actual) + { throw new InternalExpressionException("Function " + getPrettyString() + " requires at least " + actual + " arguments"); + } if (candidates > actual && getVarArgs() == null) + { throw new InternalExpressionException("Function " + getPrettyString() + " requires " + actual + " arguments"); + } } - public static List unpackArgs(List lazyParams, Context c) + public static List unpackArgs(final List lazyParams, final Context c) { // TODO we shoudn't need that if all fuctions are not lazy really - List params = new ArrayList<>(); - for (LazyValue lv : lazyParams) + final List params = new ArrayList<>(); + for (final LazyValue lv : lazyParams) { - Value param = lv.evalValue(c, Context.NONE); + final Value param = lv.evalValue(c, Context.NONE); if (param instanceof FunctionUnpackedArgumentsValue) { CarpetSettings.LOG.error("How did we get here?"); @@ -203,48 +212,51 @@ public static List unpackArgs(List lazyParams, Context c) } @Override - public LazyValue lazyEval(Context c, Context.Type type, Expression e, Tokenizer.Token t, List lazyParams) { - List resolvedParams = unpackArgs(lazyParams, c); + public LazyValue lazyEval(final Context c, final Context.Type type, final Expression e, final Tokenizer.Token t, final List lazyParams) + { + final List resolvedParams = unpackArgs(lazyParams, c); return execute(c, type, e, t, resolvedParams); } - public LazyValue execute(Context c, Context.Type type, Expression e, Tokenizer.Token t, List params) + public LazyValue execute(final Context c, final Context.Type type, final Expression e, final Tokenizer.Token t, final List params) { - assertArgsOk(params, (fixedArgs) ->{ + assertArgsOk(params, fixedArgs -> { if (fixedArgs) // wrong number of args for fixed args { throw new ExpressionException(c, e, t, - "Incorrect number of arguments for function "+name+ - ". Should be "+args.size()+", not "+params.size()+" like "+args - ); - } - else // too few args for varargs - { - List argList = new ArrayList<>(args); - argList.add("... "+varArgs); - throw new ExpressionException(c, e, t, - "Incorrect number of arguments for function "+name+ - ". Should be at least "+args.size()+", not "+params.size()+" like "+argList + "Incorrect number of arguments for function " + name + + ". Should be " + args.size() + ", not " + params.size() + " like " + args ); } + // too few args for varargs + + final List argList = new ArrayList<>(args); + argList.add("... " + varArgs); + throw new ExpressionException(c, e, t, + "Incorrect number of arguments for function " + name + + ". Should be at least " + args.size() + ", not " + params.size() + " like " + argList + ); }); - Context newFrame = c.recreate(); + final Context newFrame = c.recreate(); - if (outerState != null) outerState.forEach(newFrame::setVariable); - for (int i=0; i val); } if (varArgs != null) { - List extraParams = new ArrayList<>(); + final List extraParams = new ArrayList<>(); for (int i = args.size(), mx = params.size(); i < mx; i++) { extraParams.add(params.get(i).reboundedTo(null)); // copy by value I guess } - Value rest = ListValue.wrap(extraParams).bindTo(varArgs); // didn't we just copied that? + final Value rest = ListValue.wrap(extraParams).bindTo(varArgs); // didn't we just copied that? newFrame.setVariable(varArgs, (cc, tt) -> rest); } @@ -253,15 +265,15 @@ public LazyValue execute(Context c, Context.Type type, Expression e, Tokenizer.T { retVal = body.evalValue(newFrame, type); // todo not sure if we need to propagete type / consider boolean context in defined functions - answer seems ye } - catch (BreakStatement | ContinueStatement exc) + catch (final BreakStatement | ContinueStatement exc) { throw new ExpressionException(c, e, t, "'continue' and 'break' can only be called inside loop function bodies"); } - catch (ReturnStatement returnStatement) + catch (final ReturnStatement returnStatement) { retVal = returnStatement.retval; } - Value otherRetVal = retVal; + final Value otherRetVal = retVal; return (cc, tt) -> otherRetVal; } @@ -269,30 +281,38 @@ public Expression getExpression() { return expression; } + public Tokenizer.Token getToken() { return token; } + public List getArguments() { return args; } - public String getVarArgs() {return varArgs; } + + public String getVarArgs() + { + return varArgs; + } @Override - public Tag toTag(boolean force) + public Tag toTag(final boolean force) { - if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this); + if (!force) + { + throw new NBTSerializableValue.IncompatibleTypeException(this); + } return StringTag.valueOf(getString()); } - public void assertArgsOk(List list, Consumer feedback) + public void assertArgsOk(final List list, final Consumer feedback) { - int size = list.size(); + final int size = list.size(); if (varArgs == null && args.size() != size) // wrong number of args for fixed args { feedback.accept(true); - } else if (varArgs != null && args.size() > size) // too few args for varargs { @@ -301,12 +321,14 @@ else if (varArgs != null && args.size() > size) // too few args for varargs } @Override - public boolean pure() { + public boolean pure() + { return false; } @Override - public boolean transitive() { + public boolean transitive() + { return false; } } diff --git a/src/main/java/carpet/script/value/LContainerValue.java b/src/main/java/carpet/script/value/LContainerValue.java index 2c46ee5567..6047126475 100644 --- a/src/main/java/carpet/script/value/LContainerValue.java +++ b/src/main/java/carpet/script/value/LContainerValue.java @@ -2,16 +2,23 @@ public class LContainerValue extends FrameworkValue { - private ContainerValueInterface container; - private Value address; + private final ContainerValueInterface container; + private final Value address; public static final LContainerValue NULL_CONTAINER = new LContainerValue(null, null); - public LContainerValue(ContainerValueInterface c, Value v) + public LContainerValue(final ContainerValueInterface c, final Value v) { container = c; address = v; } - public ContainerValueInterface getContainer() {return container; } - public Value getAddress() {return address; } + public ContainerValueInterface container() + { + return container; + } + + public Value address() + { + return address; + } } diff --git a/src/main/java/carpet/script/value/LazyListValue.java b/src/main/java/carpet/script/value/LazyListValue.java index 9c93139de1..00dc9cf0fb 100644 --- a/src/main/java/carpet/script/value/LazyListValue.java +++ b/src/main/java/carpet/script/value/LazyListValue.java @@ -1,35 +1,41 @@ package carpet.script.value; import carpet.script.exception.InternalExpressionException; + import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Locale; + import net.minecraft.nbt.StringTag; import net.minecraft.nbt.Tag; public abstract class LazyListValue extends AbstractListValue implements Iterator { - public static LazyListValue rangeDouble(double from, double to, double step) + public static LazyListValue rangeDouble(final double from, final double to, final double step) { return new LazyListValue() { { if (step == 0) + { throw new InternalExpressionException("Range will never end with a zero step"); + } this.start = from; this.current = this.start; this.limit = to; this.stepp = step; } + private final double start; private double current; private final double limit; private final double stepp; + @Override public Value next() { - Value val = new NumericValue(current); + final Value val = new NumericValue(current); current += stepp; return val; } @@ -43,36 +49,41 @@ public void reset() @Override public boolean hasNext() { - return stepp > 0?(current < limit):(current > limit); + return stepp > 0 ? (current < limit) : (current > limit); } @Override public String getString() { - return String.format(Locale.ROOT, "[%s, %s, ..., %s)",NumericValue.of(start).getString(), NumericValue.of(start+stepp).getString(), NumericValue.of( limit).getString()); + return String.format(Locale.ROOT, "[%s, %s, ..., %s)", NumericValue.of(start).getString(), NumericValue.of(start + stepp).getString(), NumericValue.of(limit).getString()); } }; } - public static LazyListValue rangeLong(long from, long to, long step) + + public static LazyListValue rangeLong(final long from, final long to, final long step) { return new LazyListValue() { { if (step == 0) + { throw new InternalExpressionException("Range will never end with a zero step"); + } this.start = from; this.current = this.start; this.limit = to; this.stepp = step; } + private final long start; private long current; private final long limit; private final long stepp; + @Override public Value next() { - Value val = new NumericValue(current); + final Value val = new NumericValue(current); current += stepp; return val; } @@ -86,13 +97,13 @@ public void reset() @Override public boolean hasNext() { - return stepp > 0?(current < limit):(current > limit); + return stepp > 0 ? (current < limit) : (current > limit); } @Override public String getString() { - return String.format(Locale.ROOT, "[%s, %s, ..., %s)",NumericValue.of(start).getString(), NumericValue.of(start+stepp).getString(), NumericValue.of( limit).getString()); + return String.format(Locale.ROOT, "[%s, %s, ..., %s)", NumericValue.of(start).getString(), NumericValue.of(start + stepp).getString(), NumericValue.of(limit).getString()); } }; } @@ -108,20 +119,24 @@ public boolean getBoolean() { return hasNext(); } - @Override public abstract boolean hasNext(); - - @Override public abstract Value next(); @Override - public void fatality() {reset();} + public void fatality() + { + reset(); + } + public abstract void reset(); @Override - public Iterator iterator() {return this;} + public Iterator iterator() + { + return this; + } public List unroll() { - List result = new ArrayList<>(); + final List result = new ArrayList<>(); this.forEachRemaining(result::add); fatality(); return result; @@ -130,26 +145,38 @@ public List unroll() @Override public Value slice(long from, Long to) { - if (to == null || to < 0) to = (long) Integer.MAX_VALUE; - if (from < 0) from = 0; + if (to == null || to < 0) + { + to = (long) Integer.MAX_VALUE; + } + if (from < 0) + { + from = 0; + } if (from > to) + { return ListValue.of(); - List result = new ArrayList<>(); + } + final List result = new ArrayList<>(); int i; for (i = 0; i < from; i++) { if (hasNext()) + { next(); + } else { fatality(); return ListValue.wrap(result); } } - for (i = (int)from; i < to; i++) + for (i = (int) from; i < to; i++) { if (hasNext()) + { result.add(next()); + } else { fatality(); @@ -158,8 +185,9 @@ public Value slice(long from, Long to) } return ListValue.wrap(result); } + @Override - public Value add(Value other) + public Value add(final Value other) { throw new InternalExpressionException("Cannot add to iterators"); } @@ -175,37 +203,42 @@ public String getTypeString() { return "iterator"; } + @Override public Object clone() { - Object copy; + final Object copy; try { copy = super.clone(); } - catch (CloneNotSupportedException e) + catch (final CloneNotSupportedException e) { throw new InternalExpressionException("Cannot copy iterators"); } - ((LazyListValue)copy).reset(); + ((LazyListValue) copy).reset(); return copy; } @Override - public Value fromConstant() { - return (Value)clone(); + public Value fromConstant() + { + return (Value) clone(); } @Override public int hashCode() { - return ("i"+getString()).hashCode(); + return ("i" + getString()).hashCode(); } @Override - public Tag toTag(boolean force) + public Tag toTag(final boolean force) { - if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this); + if (!force) + { + throw new NBTSerializableValue.IncompatibleTypeException(this); + } return StringTag.valueOf(getString()); } } diff --git a/src/main/java/carpet/script/value/ListValue.java b/src/main/java/carpet/script/value/ListValue.java index 3fd16e3a47..f31fa11160 100644 --- a/src/main/java/carpet/script/value/ListValue.java +++ b/src/main/java/carpet/script/value/ListValue.java @@ -4,6 +4,7 @@ import carpet.script.exception.InternalExpressionException; import com.google.gson.JsonArray; import com.google.gson.JsonElement; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -14,6 +15,7 @@ import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; + import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.DoubleTag; import net.minecraft.nbt.IntTag; @@ -28,23 +30,24 @@ public class ListValue extends AbstractListValue implements ContainerValueInterface { protected final List items; + @Override public String getString() { - return "["+items.stream().map(Value::getString).collect(Collectors.joining(", "))+"]"; + return "[" + items.stream().map(Value::getString).collect(Collectors.joining(", ")) + "]"; } @Override public String getPrettyString() { - if (items.size()<8) - return "["+items.stream().map(Value::getPrettyString).collect(Collectors.joining(", "))+"]"; - return "["+items.get(0).getPrettyString()+", "+items.get(1).getPrettyString()+", ..., "+ - items.get(items.size()-2).getPrettyString()+", "+items.get(items.size()-1).getPrettyString()+"]"; + return items.size() < 8 + ? "[" + items.stream().map(Value::getPrettyString).collect(Collectors.joining(", ")) + "]" + : "[" + items.get(0).getPrettyString() + ", " + items.get(1).getPrettyString() + ", ..., " + items.get(items.size() - 2).getPrettyString() + ", " + items.get(items.size() - 1).getPrettyString() + "]"; } @Override - public boolean getBoolean() { + public boolean getBoolean() + { return !items.isEmpty(); } @@ -57,56 +60,63 @@ public Value clone() @Override public Value deepcopy() { - List copyItems = new ArrayList<>(items.size()); - for (Value entry: items) copyItems.add(entry.deepcopy()); + final List copyItems = new ArrayList<>(items.size()); + for (final Value entry : items) + { + copyItems.add(entry.deepcopy()); + } return new ListValue(copyItems); } - public ListValue(Collection list) + public ListValue(final Collection list) { items = new ArrayList<>(list); } - protected ListValue(List list) + protected ListValue(final List list) { items = list; } - public static Value fromTriple(double a, double b, double c) + public static Value fromTriple(final double a, final double b, final double c) { return ListValue.of(new NumericValue(a), new NumericValue(b), new NumericValue(c)); } - public static Value fromTriple(int a, int b, int c) + public static Value fromTriple(final int a, final int b, final int c) { return fromTriple((double) a, b, c); } - public static ListValue wrap(Stream stream) + public static ListValue wrap(final Stream stream) { return wrap(stream.collect(Collectors.toList())); } - public static ListValue wrap(List list) + public static ListValue wrap(final List list) { return new ListValue(list); } - public static ListValue of(Value ... list) + + public static ListValue of(final Value... list) { return new ListValue(new ArrayList<>(Arrays.asList(list))); } - public static ListValue ofNums(Number ... list) + + public static ListValue ofNums(final Number... list) { - List valList = new ArrayList<>(); - for (Number i : list) + final List valList = new ArrayList<>(); + for (final Number i : list) + { valList.add(new NumericValue(i.doubleValue())); + } return new ListValue(valList); } public static LazyValue lazyEmpty() { - Value ret = new ListValue(); + final Value ret = new ListValue(); return (c, t) -> ret; } @@ -116,16 +126,17 @@ private ListValue() } @Override - public Value add(Value other) { - ListValue output = new ListValue(); - if (other instanceof ListValue) + public Value add(final Value other) + { + final ListValue output = new ListValue(); + if (other instanceof final ListValue list) { - List other_list = ((ListValue) other).items; - if (other_list.size() == items.size()) + final List otherItems = list.items; + if (otherItems.size() == items.size()) { - for(int i = 0, size = items.size(); i < size; i++) + for (int i = 0, size = items.size(); i < size; i++) { - output.items.add(items.get(i).add(other_list.get(i))); + output.items.add(items.get(i).add(otherItems.get(i))); } } else @@ -135,31 +146,32 @@ public Value add(Value other) { } else { - for (Value v : items) + for (final Value v : items) { output.items.add(v.add(other)); } } return output; } + @Override - public void append(Value v) + public void append(final Value v) { items.add(v); } @Override - public Value subtract(Value other) + public Value subtract(final Value other) { - ListValue output = new ListValue(); - if (other instanceof ListValue) + final ListValue output = new ListValue(); + if (other instanceof final ListValue list) { - List other_list = ((ListValue) other).items; - if (other_list.size() == items.size()) + final List otherItems = list.items; + if (otherItems.size() == items.size()) { - for(int i = 0, size = items.size(); i < size; i++) + for (int i = 0, size = items.size(); i < size; i++) { - output.items.add(items.get(i).subtract(other_list.get(i))); + output.items.add(items.get(i).subtract(otherItems.get(i))); } } else @@ -169,31 +181,32 @@ public Value subtract(Value other) } else { - for (Value v : items) + for (final Value v : items) { output.items.add(v.subtract(other)); } } return output; } - public void subtractFrom(Value v) // if I ever do -= then it wouod remove items + + public void subtractFrom(final Value v) // if I ever do -= then it wouod remove items { throw new UnsupportedOperationException(); // TODO } @Override - public Value multiply(Value other) + public Value multiply(final Value other) { - ListValue output = new ListValue(); - if (other instanceof ListValue) + final ListValue output = new ListValue(); + if (other instanceof final ListValue list) { - List other_list = ((ListValue) other).items; - if (other_list.size() == items.size()) + final List otherItems = list.items; + if (otherItems.size() == items.size()) { - for(int i = 0, size = items.size(); i < size; i++) + for (int i = 0, size = items.size(); i < size; i++) { - output.items.add(items.get(i).multiply(other_list.get(i))); + output.items.add(items.get(i).multiply(otherItems.get(i))); } } else @@ -203,7 +216,7 @@ public Value multiply(Value other) } else { - for (Value v : items) + for (final Value v : items) { output.items.add(v.multiply(other)); } @@ -212,17 +225,17 @@ public Value multiply(Value other) } @Override - public Value divide(Value other) + public Value divide(final Value other) { - ListValue output = new ListValue(); - if (other instanceof ListValue) + final ListValue output = new ListValue(); + if (other instanceof final ListValue list) { - List other_list = ((ListValue) other).items; - if (other_list.size() == items.size()) + final List otherItems = list.items; + if (otherItems.size() == items.size()) { - for(int i = 0, size = items.size(); i < size; i++) + for (int i = 0, size = items.size(); i < size; i++) { - output.items.add(items.get(i).divide(other_list.get(i))); + output.items.add(items.get(i).divide(otherItems.get(i))); } } else @@ -232,7 +245,7 @@ public Value divide(Value other) } else { - for (Value v : items) + for (final Value v : items) { output.items.add(v.divide(other)); } @@ -241,19 +254,27 @@ public Value divide(Value other) } @Override - public int compareTo(Value o) + public int compareTo(final Value o) { - if (o instanceof ListValue) + if (o instanceof final ListValue ol) { - ListValue ol = (ListValue)o; - int this_size = this.getItems().size(); - int o_size = ol.getItems().size(); - if (this_size != o_size) return this_size - o_size; - if (this_size == 0) return 0; - for (int i = 0; i < this_size; i++) + final int size = this.getItems().size(); + final int otherSize = ol.getItems().size(); + if (size != otherSize) { - int res = this.items.get(i).compareTo(ol.items.get(i)); - if (res != 0) return res; + return size - otherSize; + } + if (size == 0) + { + return 0; + } + for (int i = 0; i < size; i++) + { + final int res = this.items.get(i).compareTo(ol.items.get(i)); + if (res != 0) + { + return res; + } } return 0; } @@ -263,11 +284,7 @@ public int compareTo(Value o) @Override public boolean equals(final Object o) { - if (o instanceof ListValue) - { - return getItems().equals(((ListValue) o).getItems()); - } - return false; + return o instanceof final ListValue list && getItems().equals(list.getItems()); } public List getItems() @@ -276,7 +293,10 @@ public List getItems() } @Override - public Iterator iterator() { return new ArrayList<>(items).iterator(); } // should be thread safe + public Iterator iterator() + { + return new ArrayList<>(items).iterator(); + } // should be thread safe @Override public List unpack() @@ -284,7 +304,7 @@ public List unpack() return new ArrayList<>(items); } - public void extend(List subList) + public void extend(final List subList) { items.addAll(subList); } @@ -296,18 +316,21 @@ public void extend(List subList) * @param len * @return */ - public static int normalizeIndex(long idx, int len) + public static int normalizeIndex(long idx, final int len) { - if (idx >=0 && idx < len) return (int)idx; - long range = abs(idx)/len; - idx += (range+2)*len; + if (idx >= 0 && idx < len) + { + return (int) idx; + } + final long range = abs(idx) / len; + idx += (range + 2) * len; idx = idx % len; - return (int)idx; + return (int) idx; } public static class ListConstructorValue extends ListValue { - public ListConstructorValue(Collection list) + public ListConstructorValue(final Collection list) { super(list); } @@ -320,11 +343,11 @@ public int length() } @Override - public Value in(Value value1) + public Value in(final Value value1) { for (int i = 0; i < items.size(); i++) { - Value v = items.get(i); + final Value v = items.get(i); if (v.equals(value1)) { return new NumericValue(i); @@ -334,22 +357,27 @@ public Value in(Value value1) } @Override - public Value slice(long fromDesc, Long toDesc) + public Value slice(final long fromDesc, final Long toDesc) { - List items = getItems(); - int size = items.size(); - int from = normalizeIndex(fromDesc, size); + final List items = getItems(); + final int size = items.size(); + final int from = normalizeIndex(fromDesc, size); if (toDesc == null) + { return new ListValue(new ArrayList<>(getItems().subList(from, size))); - int to = normalizeIndex(toDesc, size+1); + } + final int to = normalizeIndex(toDesc, size + 1); if (from > to) + { return ListValue.of(); + } return new ListValue(new ArrayList<>(getItems().subList(from, to))); } @Override - public Value split(Value delimiter) { - ListValue result = new ListValue(); + public Value split(final Value delimiter) + { + final ListValue result = new ListValue(); if (delimiter == null) { this.forEach(item -> result.items.add(of(item))); @@ -357,12 +385,12 @@ public Value split(Value delimiter) { } int startIndex = 0; int index = 0; - for (Value val : this.items) + for (final Value val : this.items) { index++; if (val.equals(delimiter)) { - result.items.add(new ListValue(new ArrayList<>(this.items.subList(startIndex, index-1)))); + result.items.add(new ListValue(new ArrayList<>(this.items.subList(startIndex, index - 1)))); startIndex = index; } } @@ -373,35 +401,41 @@ public Value split(Value delimiter) { @Override public double readDoubleNumber() { - return (double)items.size(); + return items.size(); } @Override - public boolean put(Value where, Value value, Value conditionValue) + public boolean put(final Value where, final Value value, final Value conditionValue) { - String condition = conditionValue.getString(); + final String condition = conditionValue.getString(); if (condition.equalsIgnoreCase("insert")) + { return put(where, value, false, false); + } if (condition.equalsIgnoreCase("extend")) + { return put(where, value, false, true); + } if (condition.equalsIgnoreCase("replace")) + { return put(where, value, true, false); - throw new InternalExpressionException("List 'put' modifier could be either 'insert', 'replace', or extend"); + } + throw new InternalExpressionException("List 'put' modifier could be either 'insert', 'replace', or extend"); } @Override - public boolean put(Value ind, Value value) + public boolean put(final Value ind, final Value value) { return put(ind, value, true, false); } - private boolean put(Value ind, Value value, boolean replace, boolean extend) + private boolean put(final Value ind, final Value value, final boolean replace, final boolean extend) { if (ind.isNull()) { if (extend && value instanceof AbstractListValue) { - ((AbstractListValue) value).iterator().forEachRemaining((v)-> items.add(v)); + ((AbstractListValue) value).iterator().forEachRemaining(items::add); } else { @@ -410,27 +444,35 @@ private boolean put(Value ind, Value value, boolean replace, boolean extend) } else { - int numitems = items.size(); + final int numitems = items.size(); if (!(ind instanceof NumericValue)) + { return false; - int index = (int)((NumericValue) ind).getLong(); + } + int index = (int) ((NumericValue) ind).getLong(); if (index < 0) {// only for values < 0 index = normalizeIndex(index, numitems); } if (replace) { - while (index >= items.size()) items.add(Value.NULL); + while (index >= items.size()) + { + items.add(Value.NULL); + } items.set(index, value); return true; } - while (index > items.size()) items.add(Value.NULL); + while (index > items.size()) + { + items.add(Value.NULL); + } if (extend && value instanceof AbstractListValue) { - Iterable iterable = ((AbstractListValue) value)::iterator; - List appendix = StreamSupport.stream( iterable.spliterator(), false).collect(Collectors.toList()); - items.addAll(index, appendix ); + final Iterable iterable = ((AbstractListValue) value)::iterator; + final List appendix = StreamSupport.stream(iterable.spliterator(), false).collect(Collectors.toList()); + items.addAll(index, appendix); return true; } items.add(index, value); @@ -439,25 +481,27 @@ private boolean put(Value ind, Value value, boolean replace, boolean extend) } @Override - public Value get(Value value) + public Value get(final Value value) { - int size = items.size(); - if (size == 0) return Value.NULL; - return items.get(normalizeIndex(NumericValue.asNumber(value, "'address' to a list index").getLong(), size)); + final int size = items.size(); + return size == 0 ? Value.NULL : items.get(normalizeIndex(NumericValue.asNumber(value, "'address' to a list index").getLong(), size)); } @Override - public boolean has(Value where) + public boolean has(final Value where) { - long index = NumericValue.asNumber(where, "'address' to a list index").getLong(); + final long index = NumericValue.asNumber(where, "'address' to a list index").getLong(); return index >= 0 && index < items.size(); } @Override - public boolean delete(Value where) + public boolean delete(final Value where) { - if (!(where instanceof NumericValue) || items.isEmpty()) return false; - long index = ((NumericValue) where).getLong(); + if (!(where instanceof NumericValue) || items.isEmpty()) + { + return false; + } + final long index = ((NumericValue) where).getLong(); items.remove(normalizeIndex(index, items.size())); return true; } @@ -482,35 +526,54 @@ private enum TagTypeCompat LIST, MAP, STRING; - private static TagTypeCompat getType(Tag tag) + + private static TagTypeCompat getType(final Tag tag) { - if (tag instanceof IntTag) return INT; - if (tag instanceof LongTag) return LONG; - if (tag instanceof DoubleTag) return DBL; - if (tag instanceof ListTag) return LIST; - if (tag instanceof CompoundTag) return MAP; + if (tag instanceof IntTag) + { + return INT; + } + if (tag instanceof LongTag) + { + return LONG; + } + if (tag instanceof DoubleTag) + { + return DBL; + } + if (tag instanceof ListTag) + { + return LIST; + } + if (tag instanceof CompoundTag) + { + return MAP; + } return STRING; } } @Override - public Tag toTag(boolean force) + public Tag toTag(final boolean force) { - int argSize = items.size(); - if (argSize == 0) return new ListTag(); - ListTag tag = new ListTag(); - if (argSize ==1) + final int argSize = items.size(); + if (argSize == 0) + { + return new ListTag(); + } + final ListTag tag = new ListTag(); + if (argSize == 1) { tag.add(items.get(0).toTag(force)); return tag; } // figuring out the types - List tags= new ArrayList<>(); + final List tags = new ArrayList<>(); items.forEach(v -> tags.add(v.toTag(force))); - Set cases = EnumSet.noneOf(TagTypeCompat.class); + final Set cases = EnumSet.noneOf(TagTypeCompat.class); tags.forEach(t -> cases.add(TagTypeCompat.getType(t))); - if (cases.size()==1) // well, one type of items + if (cases.size() == 1) // well, one type of items { tag.addAll(tags); return tag; @@ -519,28 +582,28 @@ public Tag toTag(boolean force) || cases.contains(TagTypeCompat.MAP) || cases.contains(TagTypeCompat.STRING)) // incompatible types { - if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this); + if (!force) + { + throw new NBTSerializableValue.IncompatibleTypeException(this); + } tags.forEach(t -> tag.add(StringTag.valueOf(t.getAsString()))); return tag; } // only numbers / mixed types - if (cases.contains(TagTypeCompat.DBL)) - { - tags.forEach(t -> tag.add(DoubleTag.valueOf(((NumericTag)t).getAsDouble()))); - } - else - { - tags.forEach(t -> tag.add(LongTag.valueOf(((NumericTag)t).getAsLong()))); - } + tags.forEach(cases.contains(TagTypeCompat.DBL) + ? (t -> tag.add(DoubleTag.valueOf(((NumericTag) t).getAsDouble()))) + : (t -> tag.add(LongTag.valueOf(((NumericTag) t).getAsLong())))); return tag; } @Override public JsonElement toJson() { - JsonArray array = new JsonArray(); - for (Value el: items) + final JsonArray array = new JsonArray(); + for (final Value el : items) + { array.add(el.toJson()); + } return array; } } diff --git a/src/main/java/carpet/script/value/MapValue.java b/src/main/java/carpet/script/value/MapValue.java index d9f173b9ca..95f7513192 100644 --- a/src/main/java/carpet/script/value/MapValue.java +++ b/src/main/java/carpet/script/value/MapValue.java @@ -3,6 +3,7 @@ import carpet.script.exception.InternalExpressionException; import com.google.gson.JsonElement; import com.google.gson.JsonObject; + import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -11,6 +12,7 @@ import java.util.Map; import java.util.Set; import java.util.stream.Collectors; + import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.Tag; @@ -23,22 +25,16 @@ private MapValue() map = new HashMap<>(); } - public MapValue(List kvPairs) + public MapValue(final List kvPairs) { this(); - for (Value v : kvPairs) - { - put(v); - } + kvPairs.forEach(this::put); } - public MapValue(Set keySet) + public MapValue(final Set keySet) { this(); - for (Value v : keySet) - { - map.put(v, Value.NULL); - } + keySet.forEach(v -> map.put(v, Value.NULL)); } @Override @@ -56,20 +52,22 @@ public List unpack() @Override public String getString() { - return "{"+map.entrySet().stream().map((p) -> p.getKey().getString()+": "+p.getValue().getString()).collect(Collectors.joining(", "))+"}"; + return "{" + map.entrySet().stream().map(p -> p.getKey().getString() + ": " + p.getValue().getString()).collect(Collectors.joining(", ")) + "}"; } @Override public String getPrettyString() { - if (map.size()<6) - return "{"+map.entrySet().stream().map((p) -> p.getKey().getPrettyString()+": "+p.getValue().getPrettyString()).collect(Collectors.joining(", "))+"}"; - List keys = new ArrayList<>(map.keySet()); - int max = keys.size(); - return "{"+keys.get(0).getPrettyString()+": "+map.get(keys.get(0)).getPrettyString()+", "+ - keys.get(1).getPrettyString()+": "+map.get(keys.get(1)).getPrettyString()+", ..., "+ - keys.get(max-2).getPrettyString()+": "+map.get(keys.get(max-2)).getPrettyString()+", "+ - keys.get(max-1).getPrettyString()+": "+map.get(keys.get(max-1)).getPrettyString()+"}"; + if (map.size() < 6) + { + return "{" + map.entrySet().stream().map(p -> p.getKey().getPrettyString() + ": " + p.getValue().getPrettyString()).collect(Collectors.joining(", ")) + "}"; + } + final List keys = new ArrayList<>(map.keySet()); + final int max = keys.size(); + return "{" + keys.get(0).getPrettyString() + ": " + map.get(keys.get(0)).getPrettyString() + ", " + + keys.get(1).getPrettyString() + ": " + map.get(keys.get(1)).getPrettyString() + ", ..., " + + keys.get(max - 2).getPrettyString() + ": " + map.get(keys.get(max - 2)).getPrettyString() + ", " + + keys.get(max - 1).getPrettyString() + ": " + map.get(keys.get(max - 1)).getPrettyString() + "}"; } @Override @@ -87,35 +85,34 @@ public Value clone() @Override public Value deepcopy() { - Map copyMap = new HashMap<>(); + final Map copyMap = new HashMap<>(); map.forEach((key, value) -> copyMap.put(key.deepcopy(), value.deepcopy())); return new MapValue(copyMap); } - private MapValue(Map other) + private MapValue(final Map other) { map = other; } - public static MapValue wrap(Map other) + public static MapValue wrap(final Map other) { return new MapValue(other); } @Override - public Value add(Value o) + public Value add(final Value o) { - Map newItems = new HashMap<>(map); - if (o instanceof MapValue) + final Map newItems = new HashMap<>(map); + if (o instanceof final MapValue mapValue) { - newItems.putAll(((MapValue) o).map); + newItems.putAll(mapValue.map); } - else if (o instanceof AbstractListValue) + else if (o instanceof final AbstractListValue alv) { - Iterator it = ((AbstractListValue) o).iterator(); - while (it.hasNext()) + for (final Value value : alv) { - newItems.put(it.next(), Value.NULL); + newItems.put(value, Value.NULL); } } else @@ -126,31 +123,30 @@ else if (o instanceof AbstractListValue) } @Override - public Value subtract(Value v) + public Value subtract(final Value v) { throw new InternalExpressionException("Cannot subtract from a map value"); } @Override - public Value multiply(Value v) + public Value multiply(final Value v) { throw new InternalExpressionException("Cannot multiply with a map value"); } @Override - public Value divide(Value v) + public Value divide(final Value v) { throw new InternalExpressionException("Cannot divide a map value"); } - public void put(Value v) + public void put(final Value v) { - if (!(v instanceof ListValue)) + if (!(v instanceof final ListValue pair)) { map.put(v, Value.NULL); return; } - ListValue pair = (ListValue)v; if (pair.getItems().size() != 2) { throw new InternalExpressionException("Map constructor requires elements that have two items"); @@ -159,13 +155,13 @@ public void put(Value v) } @Override - public void append(Value v) + public void append(final Value v) { map.put(v, Value.NULL); } @Override - public int compareTo(Value o) + public int compareTo(final Value o) { throw new InternalExpressionException("Cannot compare with a map value"); } @@ -173,11 +169,7 @@ public int compareTo(Value o) @Override public boolean equals(final Object o) { - if (o instanceof MapValue) - { - return map.equals(((MapValue) o).map); - } - return false; + return o instanceof final MapValue mapValue && map.equals(mapValue.map); } public Map getMap() @@ -185,9 +177,9 @@ public Map getMap() return map; } - public void extend(List subList) + public void extend(final List subList) { - for (Value v: subList) put(v); + subList.forEach(this::put); } @Override @@ -197,53 +189,51 @@ public int length() } @Override - public Value in(Value value1) + public Value in(final Value value) { - if (map.containsKey(value1)) return value1; - return Value.NULL; + return map.containsKey(value) ? value : Value.NULL; } @Override - public Value slice(long from, Long to) + public Value slice(final long from, final Long to) { throw new InternalExpressionException("Cannot slice a map value"); } @Override - public Value split(Value delimiter) { - throw new InternalExpressionException("Cannot split a map value"); + public Value split(final Value delimiter) + { + throw new InternalExpressionException("Cannot split a map value"); } @Override public double readDoubleNumber() { - return (double)map.size(); + return map.size(); } @Override - public Value get(Value v2) + public Value get(final Value v2) { return map.getOrDefault(v2, Value.NULL); } @Override - public boolean has(Value where) + public boolean has(final Value where) { return map.containsKey(where); } @Override - public boolean delete(Value where) + public boolean delete(final Value where) { - Value ret = map.remove(where); - return ret != null; + return map.remove(where) != null; } @Override - public boolean put(Value key, Value value) + public boolean put(final Value key, final Value value) { - Value ret = map.put(key, value); - return ret != null; + return map.put(key, value) != null; } @Override @@ -259,12 +249,15 @@ public int hashCode() } @Override - public Tag toTag(boolean force) + public Tag toTag(final boolean force) { - CompoundTag tag = new CompoundTag() ; - map.forEach( (k, v) -> + final CompoundTag tag = new CompoundTag(); + map.forEach((k, v) -> { - if (!force && !(k instanceof StringValue)) throw new NBTSerializableValue.IncompatibleTypeException(k); + if (!force && !(k instanceof StringValue)) + { + throw new NBTSerializableValue.IncompatibleTypeException(k); + } tag.put(k.getString(), v.toTag(force)); }); return tag; @@ -273,10 +266,10 @@ public Tag toTag(boolean force) @Override public JsonElement toJson() { - JsonObject jsonMap = new JsonObject(); - List keys = new ArrayList<>(map.keySet()); + final JsonObject jsonMap = new JsonObject(); + final List keys = new ArrayList<>(map.keySet()); Collections.sort(keys); - keys.forEach( k -> jsonMap.add(k.getString(), map.get(k).toJson())); + keys.forEach(k -> jsonMap.add(k.getString(), map.get(k).toJson())); return jsonMap; } } diff --git a/src/main/java/carpet/script/value/NBTSerializableValue.java b/src/main/java/carpet/script/value/NBTSerializableValue.java index 272f3fb1d9..32cce9ddda 100644 --- a/src/main/java/carpet/script/value/NBTSerializableValue.java +++ b/src/main/java/carpet/script/value/NBTSerializableValue.java @@ -8,6 +8,7 @@ import carpet.script.utils.EquipmentInventory; import com.mojang.brigadier.StringReader; import com.mojang.brigadier.exceptions.CommandSyntaxException; + import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; @@ -17,6 +18,7 @@ import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; + import net.minecraft.commands.arguments.NbtPathArgument; import net.minecraft.commands.arguments.item.ItemInput; import net.minecraft.commands.arguments.item.ItemParser; @@ -59,9 +61,11 @@ public class NBTSerializableValue extends Value implements ContainerValueInterfa private Supplier nbtSupplier = null; private boolean owned = false; - private NBTSerializableValue() {} + private NBTSerializableValue() + { + } - public NBTSerializableValue(String nbtString) + public NBTSerializableValue(final String nbtString) { nbtSupplier = () -> { @@ -69,64 +73,70 @@ public NBTSerializableValue(String nbtString) { return (new TagParser(new StringReader(nbtString))).readValue(); } - catch (CommandSyntaxException e) + catch (final CommandSyntaxException e) { - throw new InternalExpressionException("Incorrect NBT data: "+nbtString); + throw new InternalExpressionException("Incorrect NBT data: " + nbtString); } }; owned = true; } - public NBTSerializableValue(Tag tag) + public NBTSerializableValue(final Tag tag) { nbtTag = tag; owned = true; } - public static Value of(Tag tag) + public static Value of(final Tag tag) { - if (tag == null) return Value.NULL; + if (tag == null) + { + return Value.NULL; + } return new NBTSerializableValue(tag); } - public NBTSerializableValue(Supplier tagSupplier) + public NBTSerializableValue(final Supplier tagSupplier) { nbtSupplier = tagSupplier; } - public static Value fromStack(ItemStack stack) + public static Value fromStack(final ItemStack stack) { if (stack.hasTag()) { - NBTSerializableValue value = new NBTSerializableValue(); + final NBTSerializableValue value = new NBTSerializableValue(); value.nbtSupplier = stack::getTag; return value; } return Value.NULL; } - public static String nameFromRegistryId(ResourceLocation id) + public static String nameFromRegistryId(final ResourceLocation id) { if (id == null) // should be Value.NULL + { return ""; - if (id.getNamespace().equals("minecraft")) - return id.getPath(); - return id.toString(); + } + return id.getNamespace().equals("minecraft") ? id.getPath() : id.toString(); } - public static NBTSerializableValue parseString(String nbtString, boolean fail) + public static NBTSerializableValue parseString(final String nbtString, final boolean fail) { - Tag tag; + final Tag tag; try { tag = (new TagParser(new StringReader(nbtString))).readValue(); } - catch (CommandSyntaxException e) + catch (final CommandSyntaxException e) { - if (fail) throw new InternalExpressionException("Incorrect NBT tag: "+ nbtString); + if (fail) + { + throw new InternalExpressionException("Incorrect NBT tag: " + nbtString); + } return null; } - NBTSerializableValue value = new NBTSerializableValue(tag); + final NBTSerializableValue value = new NBTSerializableValue(tag); value.nbtString = null; return value; } @@ -136,7 +146,7 @@ public static NBTSerializableValue parseString(String nbtString, boolean fail) public Value clone() { // sets only nbttag, even if emtpy; - NBTSerializableValue copy = new NBTSerializableValue(nbtTag); + final NBTSerializableValue copy = new NBTSerializableValue(nbtTag); copy.nbtSupplier = this.nbtSupplier; copy.nbtString = this.nbtString; copy.owned = this.owned; @@ -146,59 +156,67 @@ public Value clone() @Override public Value deepcopy() { - NBTSerializableValue copy = (NBTSerializableValue) clone(); + final NBTSerializableValue copy = (NBTSerializableValue) clone(); copy.owned = false; ensureOwnership(); return copy; } @Override - public Value fromConstant() { + public Value fromConstant() + { return deepcopy(); } // stolen from HopperBlockEntity, adjusted for threaded operation - public static Container getInventoryAt(ServerLevel world, BlockPos blockPos) + public static Container getInventoryAt(final ServerLevel world, final BlockPos blockPos) { Container inventory = null; - BlockState blockState = world.getBlockState(blockPos); - Block block = blockState.getBlock(); - if (block instanceof WorldlyContainerHolder) { - inventory = ((WorldlyContainerHolder)block).getContainer(blockState, world, blockPos); - } else if (blockState.hasBlockEntity()) { - BlockEntity blockEntity = BlockValue.getBlockEntity(world, blockPos); - if (blockEntity instanceof Container) { - inventory = (Container)blockEntity; - if (inventory instanceof ChestBlockEntity && block instanceof ChestBlock) { - inventory = ChestBlock.getContainer((ChestBlock)block, blockState, world, blockPos, true); + final BlockState blockState = world.getBlockState(blockPos); + final Block block = blockState.getBlock(); + if (block instanceof final WorldlyContainerHolder containerHolder) + { + inventory = containerHolder.getContainer(blockState, world, blockPos); + } + else if (blockState.hasBlockEntity()) + { + final BlockEntity blockEntity = BlockValue.getBlockEntity(world, blockPos); + if (blockEntity instanceof final Container inventoryHolder) + { + inventory = inventoryHolder; + if (inventory instanceof ChestBlockEntity && block instanceof final ChestBlock chestBlock) + { + inventory = ChestBlock.getContainer(chestBlock, blockState, world, blockPos, true); } } } - if (inventory == null) { - List list = world.getEntities( - (Entity)null, //TODO check this matches the correct method + if (inventory == null) + { + final List list = world.getEntities( + (Entity) null, //TODO check this matches the correct method new AABB( blockPos.getX() - 0.5D, blockPos.getY() - 0.5D, blockPos.getZ() - 0.5D, blockPos.getX() + 0.5D, blockPos.getY() + 0.5D, blockPos.getZ() + 0.5D), EntitySelector.CONTAINER_ENTITY_SELECTOR ); - if (!list.isEmpty()) { - inventory = (Container)list.get(world.random.nextInt(list.size())); + if (!list.isEmpty()) + { + inventory = (Container) list.get(world.random.nextInt(list.size())); } } return inventory; } - public static InventoryLocator locateInventory(CarpetContext c, List params, int offset) + public static InventoryLocator locateInventory(final CarpetContext c, final List params, int offset) { try { Value v1 = params.get(offset); if (v1.isNull()) { - offset ++; + offset++; v1 = params.get(offset); } else if (v1 instanceof StringValue) @@ -206,23 +224,38 @@ else if (v1 instanceof StringValue) String strVal = v1.getString().toLowerCase(Locale.ROOT); if (strVal.equals("enderchest")) { - Value v2 = params.get(1 + offset); - ServerPlayer player = EntityValue.getPlayerByValue(c.server(), v2); - if (player == null) throw new InternalExpressionException("enderchest inventory requires player argument"); + final Value v2 = params.get(1 + offset); + final ServerPlayer player = EntityValue.getPlayerByValue(c.server(), v2); + if (player == null) + { + throw new InternalExpressionException("enderchest inventory requires player argument"); + } return new InventoryLocator(player, player.blockPosition(), player.getEnderChestInventory(), offset + 2, true); } if (strVal.equals("equipment")) { - Value v2 = params.get(1 + offset); - if (!(v2 instanceof EntityValue)) throw new InternalExpressionException("Equipment inventory requires a living entity argument"); - Entity e = ((EntityValue) v2).getEntity(); - if (!(e instanceof LivingEntity)) throw new InternalExpressionException("Equipment inventory requires a living entity argument"); - return new InventoryLocator(e, e.blockPosition(), new EquipmentInventory((LivingEntity) e), offset + 2); + final Value v2 = params.get(1 + offset); + if (!(v2 instanceof final EntityValue ev)) + { + throw new InternalExpressionException("Equipment inventory requires a living entity argument"); + } + final Entity e = ev.getEntity(); + if (!(e instanceof final LivingEntity le)) + { + throw new InternalExpressionException("Equipment inventory requires a living entity argument"); + } + return new InventoryLocator(e, e.blockPosition(), new EquipmentInventory(le), offset + 2); + } + final boolean isEnder = strVal.startsWith("enderchest_"); + if (isEnder) + { + strVal = strVal.substring(11); // len("enderchest_") + } + final ServerPlayer player = c.server().getPlayerList().getPlayerByName(strVal); + if (player == null) + { + throw new InternalExpressionException("String description of an inventory should either denote a player or player's enderchest"); } - boolean isEnder = strVal.startsWith("enderchest_"); - if (isEnder) strVal = strVal.substring(11); // len("enderchest_") - ServerPlayer player = c.server().getPlayerList().getPlayerByName(strVal); - if (player == null) throw new InternalExpressionException("String description of an inventory should either denote a player or player's enderchest"); return new InventoryLocator( player, player.blockPosition(), @@ -231,149 +264,150 @@ else if (v1 instanceof StringValue) isEnder ); } - if (v1 instanceof EntityValue) + if (v1 instanceof final EntityValue ev) { Container inv = null; - Entity e = ((EntityValue) v1).getEntity(); - if (e instanceof Player pe) inv = pe.getInventory(); - else if (e instanceof Container) inv = (Container) e; - else if (e instanceof InventoryCarrier io) inv = io.getInventory(); - else if (e instanceof InventoryBearerInterface ibi) inv = ibi.getCMInventory(); // horse only - else if (e instanceof LivingEntity le) return new InventoryLocator(e, e.blockPosition(), new EquipmentInventory(le), offset+1); - if (inv == null) - return null; - - return new InventoryLocator(e, e.blockPosition(), inv, offset+1); + final Entity e = ev.getEntity(); + if (e instanceof final Player pe) + { + inv = pe.getInventory(); + } + else if (e instanceof final Container container) + { + inv = container; + } + else if (e instanceof final InventoryCarrier io) + { + inv = io.getInventory(); + } + else if (e instanceof final InventoryBearerInterface ibi) + { + inv = ibi.getCMInventory(); // horse only + } + else if (e instanceof final LivingEntity le) + { + return new InventoryLocator(e, e.blockPosition(), new EquipmentInventory(le), offset + 1); + } + return inv == null ? null : new InventoryLocator(e, e.blockPosition(), inv, offset + 1); + } - if (v1 instanceof BlockValue) + if (v1 instanceof final BlockValue bv) { - BlockPos pos = ((BlockValue) v1).getPos(); + final BlockPos pos = bv.getPos(); if (pos == null) + { throw new InternalExpressionException("Block to access inventory needs to be positioned in the world"); - Container inv = getInventoryAt(c.level(), pos); - if (inv == null) - return null; - return new InventoryLocator(pos, pos, inv, offset+1); + } + final Container inv = getInventoryAt(c.level(), pos); + return inv == null ? null : new InventoryLocator(pos, pos, inv, offset + 1); } - if (v1 instanceof ListValue) + if (v1 instanceof final ListValue lv) { - List args = ((ListValue) v1).getItems(); - BlockPos pos = new BlockPos( + final List args = lv.getItems(); + final BlockPos pos = new BlockPos( NumericValue.asNumber(args.get(0)).getDouble(), NumericValue.asNumber(args.get(1)).getDouble(), NumericValue.asNumber(args.get(2)).getDouble()); - Container inv = getInventoryAt(c.level(), pos); - if (inv == null) - return null; - return new InventoryLocator(pos, pos, inv, offset+1); + final Container inv = getInventoryAt(c.level(), pos); + return inv == null ? null : new InventoryLocator(pos, pos, inv, offset + 1); } - if (v1 instanceof ScreenValue screenValue) + if (v1 instanceof final ScreenValue screenValue) { - if(!screenValue.isOpen()) return null; - return new InventoryLocator(screenValue.getPlayer(), screenValue.getPlayer().blockPosition(), screenValue.getInventory(), offset+1); + return !screenValue.isOpen() ? null : new InventoryLocator(screenValue.getPlayer(), screenValue.getPlayer().blockPosition(), screenValue.getInventory(), offset + 1); } - BlockPos pos = new BlockPos( + final BlockPos pos = new BlockPos( NumericValue.asNumber(v1).getDouble(), NumericValue.asNumber(params.get(1 + offset)).getDouble(), NumericValue.asNumber(params.get(2 + offset)).getDouble()); - Container inv = getInventoryAt(c.level(), pos); - if (inv == null) - return null; - return new InventoryLocator(pos, pos, inv, offset + 3); + final Container inv = getInventoryAt(c.level(), pos); + return inv == null ? null : new InventoryLocator(pos, pos, inv, offset + 3); } - catch (IndexOutOfBoundsException e) + catch (final IndexOutOfBoundsException e) { throw new InternalExpressionException("Inventory should be defined either by three coordinates, a block value, an entity, or a screen"); } } - private static final Map itemCache = new HashMap<>(); + private static final Map itemCache = new HashMap<>(); - public static ItemInput parseItem(String itemString, RegistryAccess regs) + public static ItemInput parseItem(final String itemString, final RegistryAccess regs) { return parseItem(itemString, null, regs); } - public static ItemInput parseItem(String itemString, CompoundTag customTag, RegistryAccess regs) + public static ItemInput parseItem(final String itemString, final CompoundTag customTag, final RegistryAccess regs) { try { ItemInput res = itemCache.get(itemString); // [SCARY SHIT] persistent caches over server reloads if (res != null) - if (customTag == null) - return res; - else - return new ItemInput(Holder.direct(res.getItem()), customTag); - ItemParser.ItemResult parser = ItemParser.parseForItem(regs.lookupOrThrow(Registries.ITEM), new StringReader(itemString)); + { + return customTag == null ? res : new ItemInput(Holder.direct(res.getItem()), customTag); + } + final ItemParser.ItemResult parser = ItemParser.parseForItem(regs.lookupOrThrow(Registries.ITEM), new StringReader(itemString)); res = new ItemInput(parser.item(), parser.nbt()); itemCache.put(itemString, res); - if (itemCache.size()>64000) + if (itemCache.size() > 64000) + { itemCache.clear(); - if (customTag == null) - return res; - else - return new ItemInput(Holder.direct(res.getItem()), customTag); + } + return customTag == null ? res : new ItemInput(Holder.direct(res.getItem()), customTag); } - catch (CommandSyntaxException e) + catch (final CommandSyntaxException e) { throw new ThrowStatement(itemString, Throwables.UNKNOWN_ITEM); } } - public static int validateSlot(int slot, Container inv) + public static int validateSlot(int slot, final Container inv) { - int invSize = inv.getContainerSize(); + final int invSize = inv.getContainerSize(); if (slot < 0) + { slot = invSize + slot; - if (slot < 0 || slot >= invSize) - return inv.getContainerSize(); // outside of inventory - return slot; + } + return slot < 0 || slot >= invSize ? inv.getContainerSize() : slot; // outside of inventory } - private static Value decodeSimpleTag(Tag t) + private static Value decodeSimpleTag(final Tag t) { - if (t instanceof NumericTag) + if (t instanceof final NumericTag number) { - if (t instanceof LongTag || t instanceof IntTag) // short and byte will never exceed float's precision, even int won't - { - return NumericValue.of(((NumericTag) t).getAsLong()); - } - return NumericValue.of(((NumericTag) t).getAsNumber()); + // short and byte will never exceed float's precision, even int won't + return t instanceof LongTag || t instanceof IntTag ? NumericValue.of(number.getAsLong()) : NumericValue.of(number.getAsNumber()); } if (t instanceof StringTag) + { return StringValue.of(t.getAsString()); + } if (t instanceof EndTag) + { return Value.NULL; - - throw new InternalExpressionException("How did we get here: Unknown nbt element class: "+t.getType().getName()); - + } + throw new InternalExpressionException("How did we get here: Unknown nbt element class: " + t.getType().getName()); } - private static Value decodeTag(Tag t) + private static Value decodeTag(final Tag t) { - if (t instanceof CompoundTag || t instanceof CollectionTag) - return new NBTSerializableValue(() -> t); - return decodeSimpleTag(t); + return t instanceof CompoundTag || t instanceof CollectionTag ? new NBTSerializableValue(() -> t) : decodeSimpleTag(t); } - private static Value decodeTagDeep(Tag t) + private static Value decodeTagDeep(final Tag t) { - if (t instanceof CompoundTag) + if (t instanceof final CompoundTag ctag) { - Map pairs = new HashMap<>(); - CompoundTag ctag = (CompoundTag)t; - for (String key: ctag.getAllKeys()) + final Map pairs = new HashMap<>(); + for (final String key : ctag.getAllKeys()) { pairs.put(new StringValue(key), decodeTagDeep(ctag.get(key))); } return MapValue.wrap(pairs); } - if (t instanceof CollectionTag) + if (t instanceof final CollectionTag ltag) { - List elems = new ArrayList<>(); - CollectionTag ltag = (CollectionTag)t; - for (Tag elem: ltag) + final List elems = new ArrayList<>(); + for (final Tag elem : ltag) { elems.add(decodeTagDeep(elem)); } @@ -387,50 +421,64 @@ public Value toValue() return decodeTagDeep(this.getTag()); } - public static Value fromValue(Value v) + public static Value fromValue(final Value v) { if (v instanceof NBTSerializableValue) + { return v; + } if (v.isNull()) + { return Value.NULL; + } return NBTSerializableValue.parseString(v.getString(), true); } public Tag getTag() { if (nbtTag == null) + { nbtTag = nbtSupplier.get(); + } return nbtTag; } @Override public boolean equals(final Object o) { - if (o instanceof NBTSerializableValue) - return getTag().equals(((NBTSerializableValue) o).getTag()); - return super.equals(o); + return o instanceof final NBTSerializableValue nbtsv ? getTag().equals(nbtsv.getTag()) : super.equals(o); } @Override public String getString() { if (nbtString == null) + { nbtString = getTag().toString(); + } return nbtString; } @Override public boolean getBoolean() { - Tag tag = getTag(); - if (tag instanceof CompoundTag) - return !((CompoundTag) tag).isEmpty(); - if (tag instanceof CollectionTag) - return !((CollectionTag) tag).isEmpty(); - if (tag instanceof NumericTag) - return ((NumericTag) tag).getAsDouble()!=0.0; + final Tag tag = getTag(); + if (tag instanceof final CompoundTag ctag) + { + return !(ctag).isEmpty(); + } + if (tag instanceof final CollectionTag ltag) + { + return !(ltag).isEmpty(); + } + if (tag instanceof final NumericTag number) + { + return number.getAsDouble() != 0.0; + } if (tag instanceof StringTag) + { return !tag.getAsString().isEmpty(); + } return true; } @@ -441,86 +489,89 @@ public CompoundTag getCompoundTag() ensureOwnership(); return (CompoundTag) getTag(); } - catch (ClassCastException e) + catch (final ClassCastException e) { - throw new InternalExpressionException(getString()+" is not a valid compound tag"); + throw new InternalExpressionException(getString() + " is not a valid compound tag"); } } @Override - public boolean put(Value where, Value value) + public boolean put(final Value where, final Value value) { return put(where, value, new StringValue("replace")); } @Override - public boolean put(Value where, Value value, Value conditions) + public boolean put(final Value where, final Value value, final Value conditions) { /// WIP ensureOwnership(); - NbtPathArgument.NbtPath path = cachePath(where.getString()); - Tag tagToInsert = value instanceof NBTSerializableValue ? - ((NBTSerializableValue) value).getTag() : - new NBTSerializableValue(value.getString()).getTag(); - boolean modifiedTag; - if (conditions instanceof NumericValue) + final NbtPathArgument.NbtPath path = cachePath(where.getString()); + final Tag tagToInsert = value instanceof final NBTSerializableValue nbtsv + ? nbtsv.getTag() + : new NBTSerializableValue(value.getString()).getTag(); + final boolean modifiedTag; + if (conditions instanceof final NumericValue number) { - modifiedTag = modify_insert((int)((NumericValue) conditions).getLong(), path, tagToInsert); + modifiedTag = modifyInsert((int) number.getLong(), path, tagToInsert); } else { - String ops = conditions.getString(); + final String ops = conditions.getString(); if (ops.equalsIgnoreCase("merge")) { - modifiedTag = modify_merge(path, tagToInsert); + modifiedTag = modifyMerge(path, tagToInsert); } else if (ops.equalsIgnoreCase("replace")) { - modifiedTag = modify_replace(path, tagToInsert); + modifiedTag = modifyReplace(path, tagToInsert); } else { return false; } } - if (modifiedTag) dirty(); + if (modifiedTag) + { + dirty(); + } return modifiedTag; } - - private boolean modify_insert(int index, NbtPathArgument.NbtPath nbtPath, Tag newElement) + private boolean modifyInsert(final int index, final NbtPathArgument.NbtPath nbtPath, final Tag newElement) { - return modify_insert(index, nbtPath, newElement, this.getTag()); + return modifyInsert(index, nbtPath, newElement, this.getTag()); } - private boolean modify_insert(int index, NbtPathArgument.NbtPath nbtPath, Tag newElement, Tag currentTag) + private boolean modifyInsert(final int index, final NbtPathArgument.NbtPath nbtPath, final Tag newElement, final Tag currentTag) { - Collection targets; + final Collection targets; try { targets = nbtPath.getOrCreate(currentTag, ListTag::new); } - catch (CommandSyntaxException e) + catch (final CommandSyntaxException e) { return false; } boolean modified = false; - for (Tag target : targets) + for (final Tag target : targets) { - if (!(target instanceof CollectionTag)) + if (!(target instanceof final CollectionTag targetList)) { continue; } try { - CollectionTag targetList = (CollectionTag) target; if (!targetList.addTag(index < 0 ? targetList.size() + index + 1 : index, newElement.copy())) + { return false; + } modified = true; } - catch (IndexOutOfBoundsException ignored) + catch (final IndexOutOfBoundsException ignored) { } } @@ -528,68 +579,72 @@ private boolean modify_insert(int index, NbtPathArgument.NbtPath nbtPath, Tag ne } - private boolean modify_merge(NbtPathArgument.NbtPath nbtPath, Tag replacement) //nbtPathArgumentType$NbtPath_1, list_1) + private boolean modifyMerge(final NbtPathArgument.NbtPath nbtPath, final Tag replacement) //nbtPathArgumentType$NbtPath_1, list_1) { - if (!(replacement instanceof CompoundTag)) + if (!(replacement instanceof final CompoundTag replacementCompound)) { return false; } - Tag ownTag = getTag(); + final Tag ownTag = getTag(); try { - for (Tag target : nbtPath.getOrCreate(ownTag, CompoundTag::new)) + for (final Tag target : nbtPath.getOrCreate(ownTag, CompoundTag::new)) { - if (!(target instanceof CompoundTag)) + if (!(target instanceof final CompoundTag targetCompound)) { continue; } - ((CompoundTag) target).merge((CompoundTag) replacement); + targetCompound.merge(replacementCompound); } } - catch (CommandSyntaxException ignored) + catch (final CommandSyntaxException ignored) { return false; } return true; } - private boolean modify_replace(NbtPathArgument.NbtPath nbtPath, Tag replacement) //nbtPathArgumentType$NbtPath_1, list_1) + private boolean modifyReplace(final NbtPathArgument.NbtPath nbtPath, final Tag replacement) //nbtPathArgumentType$NbtPath_1, list_1) { - Tag tag = getTag(); - String pathText = nbtPath.toString(); + final Tag tag = getTag(); + final String pathText = nbtPath.toString(); if (pathText.endsWith("]")) // workaround for array replacement or item in the array replacement { - if (nbtPath.remove(tag)==0) + if (nbtPath.remove(tag) == 0) + { return false; - Pattern pattern = Pattern.compile("\\[[^\\[]*]$"); - Matcher matcher = pattern.matcher(pathText); + } + final Pattern pattern = Pattern.compile("\\[[^\\[]*]$"); + final Matcher matcher = pattern.matcher(pathText); if (!matcher.find()) // malformed path { return false; } - String arrAccess = matcher.group(); - int pos; - if (arrAccess.length()==2) // we just removed entire array + final String arrAccess = matcher.group(); + final int pos; + if (arrAccess.length() == 2) // we just removed entire array + { pos = 0; + } else { try { pos = Integer.parseInt(arrAccess.substring(1, arrAccess.length() - 1)); } - catch (NumberFormatException e) + catch (final NumberFormatException e) { return false; } } - NbtPathArgument.NbtPath newPath = cachePath(pathText.substring(0, pathText.length()-arrAccess.length())); - return modify_insert(pos,newPath,replacement, tag); + final NbtPathArgument.NbtPath newPath = cachePath(pathText.substring(0, pathText.length() - arrAccess.length())); + return modifyInsert(pos, newPath, replacement, tag); } try { nbtPath.set(tag, replacement); } - catch (CommandSyntaxException e) + catch (final CommandSyntaxException e) { return false; } @@ -597,25 +652,31 @@ private boolean modify_replace(NbtPathArgument.NbtPath nbtPath, Tag replacement) } @Override - public Value get(Value value) + public Value get(final Value value) { - String valString = value.getString(); - NbtPathArgument.NbtPath path = cachePath(valString); + final String valString = value.getString(); + final NbtPathArgument.NbtPath path = cachePath(valString); try { - List tags = path.get(getTag()); - if (tags.size()==0) + final List tags = path.get(getTag()); + if (tags.isEmpty()) + { return Value.NULL; - if (tags.size()==1 && !valString.endsWith("[]")) + } + if (tags.size() == 1 && !valString.endsWith("[]")) + { return NBTSerializableValue.decodeTag(tags.get(0)); + } return ListValue.wrap(tags.stream().map(NBTSerializableValue::decodeTag)); } - catch (CommandSyntaxException ignored) { } + catch (final CommandSyntaxException ignored) + { + } return Value.NULL; } @Override - public boolean has(Value where) + public boolean has(final Value where) { return cachePath(where.getString()).countMatching(getTag()) > 0; } @@ -637,11 +698,11 @@ private void dirty() } @Override - public boolean delete(Value where) + public boolean delete(final Value where) { - NbtPathArgument.NbtPath path = cachePath(where.getString()); + final NbtPathArgument.NbtPath path = cachePath(where.getString()); ensureOwnership(); - int removed = path.remove(getTag()); + final int removed = path.remove(getTag()); if (removed > 0) { dirty(); @@ -650,30 +711,36 @@ public boolean delete(Value where) return false; } - public static record InventoryLocator(Object owner, BlockPos position, Container inventory, int offset, boolean isEnder) + public record InventoryLocator(Object owner, BlockPos position, Container inventory, int offset, + boolean isEnder) { - InventoryLocator(Object owner, BlockPos pos, Container i, int o) + InventoryLocator(final Object owner, final BlockPos pos, final Container i, final int o) { this(owner, pos, i, o, false); } } - private static Map pathCache = new HashMap<>(); - private static NbtPathArgument.NbtPath cachePath(String arg) + private static final Map pathCache = new HashMap<>(); + + private static NbtPathArgument.NbtPath cachePath(final String arg) { NbtPathArgument.NbtPath res = pathCache.get(arg); if (res != null) + { return res; + } try { res = NbtPathArgument.nbtPath().parse(new StringReader(arg)); } - catch (CommandSyntaxException exc) + catch (final CommandSyntaxException exc) { - throw new InternalExpressionException("Incorrect nbt path: "+arg); + throw new InternalExpressionException("Incorrect nbt path: " + arg); } if (pathCache.size() > 1024) + { pathCache.clear(); + } pathCache.put(arg, res); return res; } @@ -686,9 +753,12 @@ public String getTypeString() @Override - public Tag toTag(boolean force) + public Tag toTag(final boolean force) { - if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this); + if (!force) + { + throw new NBTSerializableValue.IncompatibleTypeException(this); + } ensureOwnership(); return getTag(); } @@ -696,9 +766,11 @@ public Tag toTag(boolean force) public static class IncompatibleTypeException extends RuntimeException { public final Value val; - public IncompatibleTypeException(Value val) + + public IncompatibleTypeException(final Value val) { this.val = val; } - }; + } + } diff --git a/src/main/java/carpet/script/value/NullValue.java b/src/main/java/carpet/script/value/NullValue.java index 9d68f02e9a..426a0f183f 100644 --- a/src/main/java/carpet/script/value/NullValue.java +++ b/src/main/java/carpet/script/value/NullValue.java @@ -1,6 +1,7 @@ package carpet.script.value; import java.util.ArrayList; + import net.minecraft.nbt.StringTag; import net.minecraft.nbt.Tag; import com.google.gson.JsonElement; @@ -9,6 +10,7 @@ public class NullValue extends NumericValue // TODO check nonsingleton code { public static final NullValue NULL = new NullValue(); + @Override public String getString() { @@ -32,41 +34,45 @@ public Value clone() { return new NullValue(); } - protected NullValue() {super(0);} + + protected NullValue() + { + super(0); + } @Override public boolean equals(final Object o) { - if (o instanceof Value value) - { - return value.isNull(); - } - return false; + return o instanceof Value value && value.isNull(); } @Override - public Value slice(long fromDesc, Long toDesc) { + public Value slice(final long fromDesc, final Long toDesc) + { return Value.NULL; } @Override - public NumericValue opposite() { + public NumericValue opposite() + { return Value.NULL; } @Override - public int length() { + public int length() + { return 0; } @Override - public int compareTo(Value o) + public int compareTo(final Value o) { - return o.isNull() ? 0 : -1; + return o.isNull() ? 0 : -1; } @Override - public Value in(Value value) { + public Value in(final Value value) + { return Value.NULL; } @@ -83,15 +89,19 @@ public int hashCode() } @Override - public Tag toTag(boolean force) + public Tag toTag(final boolean force) { - if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this); + if (!force) + { + throw new NBTSerializableValue.IncompatibleTypeException(this); + } return StringTag.valueOf("null"); } @Override - public Value split(Value delimiter) { - return ListValue.wrap(new ArrayList()); + public Value split(final Value delimiter) + { + return ListValue.wrap(new ArrayList<>()); } @Override @@ -101,7 +111,8 @@ public JsonElement toJson() } @Override - public boolean isNull() { + public boolean isNull() + { return true; } } diff --git a/src/main/java/carpet/script/value/NumericValue.java b/src/main/java/carpet/script/value/NumericValue.java index 2c4635e14d..9a1a1b5909 100644 --- a/src/main/java/carpet/script/value/NumericValue.java +++ b/src/main/java/carpet/script/value/NumericValue.java @@ -9,6 +9,7 @@ import java.math.MathContext; import java.math.RoundingMode; import java.util.Locale; + import net.minecraft.nbt.DoubleTag; import net.minecraft.nbt.IntTag; import net.minecraft.nbt.LongTag; @@ -21,28 +22,41 @@ public class NumericValue extends Value { private final double value; private Long longValue; - private final static double epsilon = abs(32*((7*0.1)*10-7)); - private final static MathContext displayRounding = new MathContext(12, RoundingMode.HALF_EVEN); + private static final double epsilon = abs(32 * ((7 * 0.1) * 10 - 7)); + private static final MathContext displayRounding = new MathContext(12, RoundingMode.HALF_EVEN); - public static NumericValue asNumber(Value v1, String id) + public static NumericValue asNumber(final Value v1, final String id) { - if (!(v1 instanceof NumericValue)) - throw new InternalExpressionException("Argument "+id+" has to be of a numeric type"); - return ((NumericValue) v1); + if (v1 instanceof final NumericValue nv) + { + return nv; + } + throw new InternalExpressionException("Argument " + id + " has to be of a numeric type"); } - public static NumericValue asNumber(Value v1) + public static NumericValue asNumber(final Value v1) { - if (!(v1 instanceof NumericValue)) - throw new InternalExpressionException("Operand has to be of a numeric type"); - return ((NumericValue) v1); + if (v1 instanceof final NumericValue nv) + { + return nv; + } + throw new InternalExpressionException("Operand has to be of a numeric type"); } - public static Value of(T value) + public static Value of(final T value) { - if (value == null) return Value.NULL; - if (value.doubleValue() == value.longValue()) return new NumericValue(value.longValue()); - if (value instanceof Float) return new NumericValue(0.000_001D * Math.round(1_000_000.0D*value.doubleValue())); + if (value == null) + { + return Value.NULL; + } + if (value.doubleValue() == value.longValue()) + { + return new NumericValue(value.longValue()); + } + if (value instanceof Float) + { + return new NumericValue(0.000_001D * Math.round(1_000_000.0D * value.doubleValue())); + } return new NumericValue(value.doubleValue()); } @@ -56,30 +70,33 @@ public String getString() } try { - if (Double.isInfinite(value)) return (value>0)?"INFINITY":"-INFINITY"; - if (Double.isNaN(value)) return "NaN"; - if (abs(value) < epsilon) return (signum(value) < 0)?"-0":"0"; //zero rounding fails with big decimals + if (Double.isInfinite(value)) + { + return (value > 0) ? "INFINITY" : "-INFINITY"; + } + if (Double.isNaN(value)) + { + return "NaN"; + } + if (abs(value) < epsilon) + { + return (signum(value) < 0) ? "-0" : "0"; //zero rounding fails with big decimals + } // dobules have 16 point precision, 12 is plenty to display return BigDecimal.valueOf(value).round(displayRounding).stripTrailingZeros().toPlainString(); } - catch (NumberFormatException exc) + catch (final NumberFormatException exc) { - throw new InternalExpressionException("Incorrect number format for "+value); + throw new InternalExpressionException("Incorrect number format for " + value); } } @Override public String getPrettyString() { - - if (longValue!= null || getDouble() == (double)getLong()) - { - return Long.toString(getLong()); - } - else - { - return String.format(Locale.ROOT, "%.1f..", getDouble()); - } + return longValue != null || getDouble() == getLong() + ? Long.toString(getLong()) + : String.format(Locale.ROOT, "%.1f..", getDouble()); } @Override @@ -87,80 +104,62 @@ public boolean getBoolean() { return abs(value) > epsilon; } + public double getDouble() { return value; } + public float getFloat() { return (float) value; } - private static long floor(double double_1) { - long int_1 = (long)double_1; - return double_1 < (double)int_1 ? int_1 - 1 : int_1; + private static long floor(final double v) + { + final long invValue = (long) v; + return v < invValue ? invValue - 1 : invValue; } public long getLong() { - if (longValue != null) return longValue; - return floor((value+epsilon)); + return longValue != null ? longValue : Long.valueOf(floor((value + epsilon))); } @Override - public Value add(Value v) + public Value add(final Value v) { // TODO test if definintn add(NumericVlaue) woud solve the casting - if (v instanceof NumericValue nv) + if (v instanceof final NumericValue nv) { - if (longValue != null && nv.longValue != null) - { - return new NumericValue(longValue+nv.longValue); - } - return new NumericValue(value + nv.value); + return new NumericValue(longValue != null && nv.longValue != null ? (longValue + nv.longValue) : (value + nv.value)); } return super.add(v); } @Override - public Value subtract(Value v) { // TODO test if definintn add(NumericVlaue) woud solve the casting - if (v instanceof NumericValue nv) + public Value subtract(final Value v) + { // TODO test if definintn add(NumericVlaue) woud solve the casting + if (v instanceof final NumericValue nv) { - if (longValue != null && nv.longValue != null) - { - return new NumericValue(longValue-nv.longValue); - } - return new NumericValue(value - nv.value); + return new NumericValue(longValue != null && nv.longValue != null ? (longValue - nv.longValue) : (value - nv.value)); } return super.subtract(v); } @Override - public Value multiply(Value v) + public Value multiply(final Value v) { - if (v instanceof NumericValue nv) - { - if (longValue != null && nv.longValue != null) - { - return new NumericValue(longValue*nv.longValue); - } - return new NumericValue(value * nv.value); - } - if (v instanceof ListValue) + if (v instanceof final NumericValue nv) { - return v.multiply(this); + return new NumericValue(longValue != null && nv.longValue != null ? (longValue * nv.longValue) : (value * nv.value)); } - return new StringValue(StringUtils.repeat(v.getString(), (int) getLong())); + return v instanceof ListValue ? v.multiply(this) : new StringValue(StringUtils.repeat(v.getString(), (int) getLong())); } @Override - public Value divide(Value v) + public Value divide(final Value v) { - //if (1+2==3) throw new ArithmeticException("Booyah"); - if (v instanceof NumericValue) - { - return new NumericValue(getDouble() / ((NumericValue) v).getDouble() ); - } - return super.divide(v); + return v instanceof final NumericValue nv ? new NumericValue(getDouble() / nv.getDouble()) : super.divide(v); } @Override @@ -170,64 +169,68 @@ public Value clone() } @Override - public int compareTo(Value o) + public int compareTo(final Value o) { if (o.isNull()) { return -o.compareTo(this); } - if (o instanceof NumericValue no) + if (o instanceof final NumericValue no) { - if (longValue != null && no.longValue != null) - return longValue.compareTo(no.longValue); - return Double.compare(value, no.value); + return longValue != null && no.longValue != null ? longValue.compareTo(no.longValue) : Double.compare(value, no.value); } return getString().compareTo(o.getString()); } + @Override - public boolean equals(Object o) + public boolean equals(final Object o) { - if (o instanceof Value value) { - if (value.isNull()) { + if (o instanceof final Value otherValue) + { + if (otherValue.isNull()) + { return o.equals(this); } - if (o instanceof NumericValue no) { - if (longValue != null && no.longValue != null) - return longValue.equals(no.longValue); - return !this.subtract(no).getBoolean(); + if (o instanceof final NumericValue no) + { + return longValue != null && no.longValue != null ? longValue.equals(no.longValue) : !this.subtract(no).getBoolean(); } return super.equals(o); } return false; } - public NumericValue(double value) + public NumericValue(final double value) { this.value = value; } - private NumericValue(double value, Long longValue) + + private NumericValue(final double value, final Long longValue) { this.value = value; this.longValue = longValue; } - public NumericValue(String value) + public NumericValue(final String value) { - BigDecimal decimal = new BigDecimal(value); + final BigDecimal decimal = new BigDecimal(value); if (decimal.stripTrailingZeros().scale() <= 0) { try { longValue = decimal.longValueExact(); } - catch (ArithmeticException ignored) {} + catch (final ArithmeticException ignored) + { + } } this.value = decimal.doubleValue(); } - public NumericValue(long value) + + public NumericValue(final long value) { this.longValue = value; - this.value = (double)value; + this.value = (double) value; } @Override @@ -257,31 +260,34 @@ public String getTypeString() @Override public int hashCode() { - if (longValue!= null || Math.abs(Math.floor(value + 0.5D)-value) < epsilon) // is sufficiently close to the integer value - return Long.hashCode(getLong()); - return Double.hashCode(value); + // is sufficiently close to the integer value + return longValue != null || Math.abs(Math.floor(value + 0.5D) - value) < epsilon ? Long.hashCode(getLong()) : Double.hashCode(value); } public int getInt() { - return (int)getLong(); + return (int) getLong(); } @Override - public Tag toTag(boolean force) + public Tag toTag(final boolean force) { if (longValue != null) { - if (abs(longValue) < Integer.MAX_VALUE-2) - return IntTag.valueOf((int)(long)longValue); + if (abs(longValue) < Integer.MAX_VALUE - 2) + { + return IntTag.valueOf((int) (long) longValue); + } return LongTag.valueOf(longValue); } - long lv = getLong(); - if (value == (double)lv) + final long lv = getLong(); + if (value == (double) lv) { - if (abs(value) < Integer.MAX_VALUE-2) - return IntTag.valueOf((int)lv); + if (abs(value) < Integer.MAX_VALUE - 2) + { + return IntTag.valueOf((int) lv); + } return LongTag.valueOf(getLong()); } else @@ -294,35 +300,35 @@ public Tag toTag(boolean force) public JsonElement toJson() { if (longValue != null) - return new JsonPrimitive(longValue); - long lv = getLong(); - if (value == (double)lv) { - return new JsonPrimitive(getLong()); - } - else - { - return new JsonPrimitive(value); + return new JsonPrimitive(longValue); } + final long lv = getLong(); + return new JsonPrimitive(value == lv ? getLong() : value); } - public NumericValue opposite() { - if (longValue != null) return new NumericValue(-longValue); - return new NumericValue(-value); + public NumericValue opposite() + { + return new NumericValue(longValue != null ? -longValue : -value); } public boolean isInteger() { - return longValue!= null || getDouble() == (double)getLong(); + return longValue != null || getDouble() == getLong(); } - public Value mod(NumericValue n2) + public Value mod(final NumericValue n2) { if (this.longValue != null && n2.longValue != null) + { return new NumericValue(Math.floorMod(longValue, n2.longValue)); - double x = value; - double y = n2.value; - if (y == 0) throw new ArithmeticException("Division by zero"); - return new NumericValue( x - Math.floor(x / y) * y); + } + final double x = value; + final double y = n2.value; + if (y == 0) + { + throw new ArithmeticException("Division by zero"); + } + return new NumericValue(x - Math.floor(x / y) * y); } } diff --git a/src/main/java/carpet/script/value/ScreenValue.java b/src/main/java/carpet/script/value/ScreenValue.java index 8ab0ab7885..0c144c524c 100644 --- a/src/main/java/carpet/script/value/ScreenValue.java +++ b/src/main/java/carpet/script/value/ScreenValue.java @@ -12,11 +12,13 @@ import carpet.script.exception.InvalidCallbackException; import carpet.script.exception.ThrowStatement; import carpet.script.exception.Throwables; + import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.OptionalInt; + import net.minecraft.commands.CommandSourceStack; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; @@ -29,37 +31,14 @@ import net.minecraft.world.SimpleMenuProvider; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; -import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.inventory.AbstractFurnaceMenu; -import net.minecraft.world.inventory.AnvilMenu; -import net.minecraft.world.inventory.BeaconMenu; -import net.minecraft.world.inventory.BlastFurnaceMenu; -import net.minecraft.world.inventory.BrewingStandMenu; -import net.minecraft.world.inventory.CartographyTableMenu; -import net.minecraft.world.inventory.ChestMenu; -import net.minecraft.world.inventory.ClickType; -import net.minecraft.world.inventory.ContainerListener; -import net.minecraft.world.inventory.CraftingMenu; -import net.minecraft.world.inventory.DataSlot; -import net.minecraft.world.inventory.EnchantmentMenu; -import net.minecraft.world.inventory.FurnaceMenu; -import net.minecraft.world.inventory.GrindstoneMenu; -import net.minecraft.world.inventory.HopperMenu; -import net.minecraft.world.inventory.LecternMenu; -import net.minecraft.world.inventory.LoomMenu; -import net.minecraft.world.inventory.MerchantMenu; -import net.minecraft.world.inventory.ShulkerBoxMenu; -import net.minecraft.world.inventory.SimpleContainerData; -import net.minecraft.world.inventory.Slot; -import net.minecraft.world.inventory.SmithingMenu; -import net.minecraft.world.inventory.SmokerMenu; -import net.minecraft.world.inventory.StonecutterMenu; +import net.minecraft.world.inventory.*; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Recipe; import static net.minecraft.world.inventory.MenuType.*; -public class ScreenValue extends Value { +public class ScreenValue extends Value +{ private AbstractContainerMenu screenHandler; private ScreenHandlerInventory inventory; @@ -69,83 +48,96 @@ public class ScreenValue extends Value { private final String hostname; private final ServerPlayer player; - - public static Map screenHandlerFactories; + public static Map screenHandlerFactories; static { screenHandlerFactories = new HashMap<>(); - - screenHandlerFactories.put("anvil",(syncId, playerInventory) -> new AnvilMenu(syncId,playerInventory)); - screenHandlerFactories.put("beacon",(syncId, playerInventory) -> new BeaconMenu(syncId,playerInventory)); - screenHandlerFactories.put("blast_furnace",(syncId, playerInventory) -> new BlastFurnaceMenu(syncId,playerInventory)); - screenHandlerFactories.put("brewing_stand",(syncId, playerInventory) -> new BrewingStandMenu(syncId,playerInventory,new SimpleContainer(5),new SimpleContainerData(2))); - screenHandlerFactories.put("cartography_table",(syncId, playerInventory) -> new CartographyTableMenu(syncId,playerInventory)); - screenHandlerFactories.put("crafting",(syncId, playerInventory) -> new CraftingMenu(syncId,playerInventory)); - screenHandlerFactories.put("enchantment",(syncId, playerInventory) -> new EnchantmentMenu(syncId,playerInventory)); - screenHandlerFactories.put("furnace",(syncId, playerInventory) -> new FurnaceMenu(syncId,playerInventory)); - screenHandlerFactories.put("generic_3x3",((syncId, playerInventory) -> new ChestMenu(GENERIC_3x3,syncId,playerInventory,new SimpleContainer(9),1))); - screenHandlerFactories.put("generic_9x1",((syncId, playerInventory) -> new ChestMenu(GENERIC_9x1,syncId,playerInventory,new SimpleContainer(9),1))); - screenHandlerFactories.put("generic_9x2",((syncId, playerInventory) -> new ChestMenu(GENERIC_9x2,syncId,playerInventory,new SimpleContainer(9*2),2))); - screenHandlerFactories.put("generic_9x3",((syncId, playerInventory) -> new ChestMenu(GENERIC_9x3,syncId,playerInventory,new SimpleContainer(9*3),3))); - screenHandlerFactories.put("generic_9x4",((syncId, playerInventory) -> new ChestMenu(GENERIC_9x4,syncId,playerInventory,new SimpleContainer(9*4),4))); - screenHandlerFactories.put("generic_9x5",((syncId, playerInventory) -> new ChestMenu(GENERIC_9x5,syncId,playerInventory,new SimpleContainer(9*5),5))); - screenHandlerFactories.put("generic_9x6",((syncId, playerInventory) -> new ChestMenu(GENERIC_9x6,syncId,playerInventory,new SimpleContainer(9*6),6))); - screenHandlerFactories.put("grindstone",(syncId, playerInventory) -> new GrindstoneMenu(syncId,playerInventory)); - screenHandlerFactories.put("hopper",(syncId, playerInventory) -> new HopperMenu(syncId,playerInventory)); - screenHandlerFactories.put("lectern",(syncId, playerInventory) -> new LecternMenu(syncId,new SimpleContainer(1),new SimpleContainerData(1))); - screenHandlerFactories.put("loom",(syncId, playerInventory) -> new LoomMenu(syncId,playerInventory)); - screenHandlerFactories.put("merchant",(syncId, playerInventory) -> new MerchantMenu(syncId,playerInventory)); - screenHandlerFactories.put("shulker_box",(syncId, playerInventory) -> new ShulkerBoxMenu(syncId,playerInventory,new SimpleContainer(9*3))); - screenHandlerFactories.put("smithing",(syncId, playerInventory) -> new SmithingMenu(syncId,playerInventory)); - screenHandlerFactories.put("smoker",(syncId, playerInventory) -> new SmokerMenu(syncId,playerInventory)); - screenHandlerFactories.put("stonecutter",(syncId, playerInventory) -> new StonecutterMenu(syncId,playerInventory)); + screenHandlerFactories.put("anvil", AnvilMenu::new); + screenHandlerFactories.put("beacon", BeaconMenu::new); + screenHandlerFactories.put("blast_furnace", BlastFurnaceMenu::new); + screenHandlerFactories.put("brewing_stand", (syncId, playerInventory) -> new BrewingStandMenu(syncId, playerInventory, new SimpleContainer(5), new SimpleContainerData(2))); + screenHandlerFactories.put("cartography_table", CartographyTableMenu::new); + screenHandlerFactories.put("crafting", CraftingMenu::new); + screenHandlerFactories.put("enchantment", EnchantmentMenu::new); + screenHandlerFactories.put("furnace", FurnaceMenu::new); + screenHandlerFactories.put("generic_3x3", ((syncId, playerInventory) -> new ChestMenu(GENERIC_3x3, syncId, playerInventory, new SimpleContainer(9), 1))); + screenHandlerFactories.put("generic_9x1", ((syncId, playerInventory) -> new ChestMenu(GENERIC_9x1, syncId, playerInventory, new SimpleContainer(9), 1))); + screenHandlerFactories.put("generic_9x2", ((syncId, playerInventory) -> new ChestMenu(GENERIC_9x2, syncId, playerInventory, new SimpleContainer(9 * 2), 2))); + screenHandlerFactories.put("generic_9x3", ((syncId, playerInventory) -> new ChestMenu(GENERIC_9x3, syncId, playerInventory, new SimpleContainer(9 * 3), 3))); + screenHandlerFactories.put("generic_9x4", ((syncId, playerInventory) -> new ChestMenu(GENERIC_9x4, syncId, playerInventory, new SimpleContainer(9 * 4), 4))); + screenHandlerFactories.put("generic_9x5", ((syncId, playerInventory) -> new ChestMenu(GENERIC_9x5, syncId, playerInventory, new SimpleContainer(9 * 5), 5))); + screenHandlerFactories.put("generic_9x6", ((syncId, playerInventory) -> new ChestMenu(GENERIC_9x6, syncId, playerInventory, new SimpleContainer(9 * 6), 6))); + screenHandlerFactories.put("grindstone", GrindstoneMenu::new); + screenHandlerFactories.put("hopper", HopperMenu::new); + screenHandlerFactories.put("lectern", (syncId, playerInventory) -> new LecternMenu(syncId, new SimpleContainer(1), new SimpleContainerData(1))); + screenHandlerFactories.put("loom", LoomMenu::new); + screenHandlerFactories.put("merchant", MerchantMenu::new); + screenHandlerFactories.put("shulker_box", (syncId, playerInventory) -> new ShulkerBoxMenu(syncId, playerInventory, new SimpleContainer(9 * 3))); + screenHandlerFactories.put("smithing_legacy", LegacySmithingMenu::new); + screenHandlerFactories.put("smithing", SmithingMenu::new); + screenHandlerFactories.put("smoker", SmokerMenu::new); + screenHandlerFactories.put("stonecutter", StonecutterMenu::new); } - protected interface ScarpetScreenHandlerFactory { + protected interface ScarpetScreenHandlerFactory + { AbstractContainerMenu create(int syncId, Inventory playerInventory); } - - - - public ScreenValue(ServerPlayer player, String type, Component name, FunctionValue callback, Context c) { + public ScreenValue(final ServerPlayer player, final String type, final Component name, final FunctionValue callback, final Context c) + { this.name = name; this.typestring = type.toLowerCase(); - if(callback != null) callback.checkArgs(4); + if (callback != null) + { + callback.checkArgs(4); + } this.callback = callback; this.hostname = c.host.getName(); this.player = player; - MenuProvider factory = this.createScreenHandlerFactory(); - if(factory == null) throw new ThrowStatement(type, Throwables.UNKNOWN_SCREEN); + final MenuProvider factory = this.createScreenHandlerFactory(); + if (factory == null) + { + throw new ThrowStatement(type, Throwables.UNKNOWN_SCREEN); + } this.openScreen(factory); this.inventory = new ScreenHandlerInventory(this.screenHandler); } - private MenuProvider createScreenHandlerFactory() { - if(!screenHandlerFactories.containsKey(this.typestring)) { + private MenuProvider createScreenHandlerFactory() + { + if (!screenHandlerFactories.containsKey(this.typestring)) + { return null; } return new SimpleMenuProvider((i, playerInventory, playerEntity) -> { - AbstractContainerMenu screen = screenHandlerFactories.get(ScreenValue.this.typestring).create(i,playerInventory); + final AbstractContainerMenu screen = screenHandlerFactories.get(ScreenValue.this.typestring).create(i, playerInventory); ScreenValue.this.addListenerCallback(screen); ScreenValue.this.screenHandler = screen; return screen; }, this.name); } - private void openScreen(MenuProvider factory) { - if(this.player == null) return; - OptionalInt optionalSyncId = this.player.openMenu(factory); - if(optionalSyncId.isPresent() && this.player.containerMenu.containerId == optionalSyncId.getAsInt()) { + private void openScreen(final MenuProvider factory) + { + if (this.player == null) + { + return; + } + final OptionalInt optionalSyncId = this.player.openMenu(factory); + if (optionalSyncId.isPresent() && this.player.containerMenu.containerId == optionalSyncId.getAsInt()) + { this.screenHandler = this.player.containerMenu; } } - public void close() { - if(this.player.containerMenu != this.player.inventoryMenu) { + public void close() + { + if (this.player.containerMenu != this.player.inventoryMenu) + { //prevent recursion when closing screen in closing screen callback by doing this before triggering event this.inventory = null; this.player.containerMenu = this.player.inventoryMenu; @@ -154,11 +146,14 @@ public void close() { } } - public boolean isOpen() { - if(this.screenHandler == null) { + public boolean isOpen() + { + if (this.screenHandler == null) + { return false; } - if(this.player.containerMenu.containerId == this.screenHandler.containerId) { + if (this.player.containerMenu.containerId == this.screenHandler.containerId) + { return true; } this.screenHandler = null; @@ -166,104 +161,124 @@ public boolean isOpen() { } - private boolean callListener(ServerPlayer player, String action, Map data) { - Value playerValue = EntityValue.of(player); - Value actionValue = StringValue.of(action); - Value dataValue = MapValue.wrap(data); - List args = Arrays.asList(this,playerValue,actionValue,dataValue); - CarpetScriptHost appHost = CarpetServer.scriptServer.getAppHostByName(this.hostname); - if(appHost == null) { + private boolean callListener(final ServerPlayer player, final String action, final Map data) + { + final Value playerValue = EntityValue.of(player); + final Value actionValue = StringValue.of(action); + final Value dataValue = MapValue.wrap(data); + final List args = Arrays.asList(this, playerValue, actionValue, dataValue); + final CarpetScriptHost appHost = CarpetServer.scriptServer.getAppHostByName(this.hostname); + if (appHost == null) + { this.close(); this.screenHandler = null; return false; } - CommandSourceStack source = player.createCommandSourceStack().withPermission(CarpetSettings.runPermissionLevel); - CarpetScriptHost executingHost = appHost.retrieveForExecution(source,player); + final CommandSourceStack source = player.createCommandSourceStack().withPermission(CarpetSettings.runPermissionLevel); + final CarpetScriptHost executingHost = appHost.retrieveForExecution(source, player); try { - Value cancelValue = executingHost.callUDF(source.withPermission(CarpetSettings.runPermissionLevel), callback, args); + final Value cancelValue = executingHost.callUDF(source.withPermission(CarpetSettings.runPermissionLevel), callback, args); return cancelValue.getString().equals("cancel"); } - catch (NullPointerException | InvalidCallbackException | IntegrityException error) + catch (final NullPointerException | InvalidCallbackException | IntegrityException error) { CarpetScriptServer.LOG.error("Got exception when running screen event call ", error); return false; } } - private void addListenerCallback(AbstractContainerMenu screenHandler) { - if(this.callback == null) return; + private void addListenerCallback(final AbstractContainerMenu screenHandler) + { + if (this.callback == null) + { + return; + } - screenHandler.addSlotListener(new ScarpetScreenHandlerListener() { + screenHandler.addSlotListener(new ScarpetScreenHandlerListener() + { @Override - public boolean onSlotClick(ServerPlayer player, ClickType actionType, int slot, int button) { - Map data = new HashMap<>(); - data.put(StringValue.of("slot"),slot == AbstractContainerMenu.SLOT_CLICKED_OUTSIDE ? Value.NULL : NumericValue.of(slot)); - if(actionType == ClickType.QUICK_CRAFT) { - data.put(StringValue.of("quick_craft_stage"),NumericValue.of(AbstractContainerMenu.getQuickcraftHeader(button))); + public boolean onSlotClick(final ServerPlayer player, final ClickType actionType, final int slot, int button) + { + final Map data = new HashMap<>(); + data.put(StringValue.of("slot"), slot == AbstractContainerMenu.SLOT_CLICKED_OUTSIDE ? Value.NULL : NumericValue.of(slot)); + if (actionType == ClickType.QUICK_CRAFT) + { + data.put(StringValue.of("quick_craft_stage"), NumericValue.of(AbstractContainerMenu.getQuickcraftHeader(button))); button = AbstractContainerMenu.getQuickcraftType(button); } - data.put(StringValue.of("button"),NumericValue.of(button)); - return ScreenValue.this.callListener(player,actionTypeToString(actionType),data); + data.put(StringValue.of("button"), NumericValue.of(button)); + return ScreenValue.this.callListener(player, actionTypeToString(actionType), data); } + @Override - public boolean onButtonClick(ServerPlayer player, int button) { - Map data = new HashMap<>(); - data.put(StringValue.of("button"),NumericValue.of(button)); - return ScreenValue.this.callListener(player,"button",data); + public boolean onButtonClick(final ServerPlayer player, final int button) + { + final Map data = new HashMap<>(); + data.put(StringValue.of("button"), NumericValue.of(button)); + return ScreenValue.this.callListener(player, "button", data); } + @Override - public void onClose(ServerPlayer player) { - Map data = new HashMap<>(); - ScreenValue.this.callListener(player,"close",data); + public void onClose(final ServerPlayer player) + { + final Map data = new HashMap<>(); + ScreenValue.this.callListener(player, "close", data); } + @Override - public boolean onSelectRecipe(ServerPlayer player, Recipe recipe, boolean craftAll) { - Map data = new HashMap<>(); - data.put(StringValue.of("recipe"),StringValue.of(recipe.getId().toString())); - data.put(StringValue.of("craft_all"),BooleanValue.of(craftAll)); - return ScreenValue.this.callListener(player,"select_recipe",data); + public boolean onSelectRecipe(final ServerPlayer player, final Recipe recipe, final boolean craftAll) + { + final Map data = new HashMap<>(); + data.put(StringValue.of("recipe"), StringValue.of(recipe.getId().toString())); + data.put(StringValue.of("craft_all"), BooleanValue.of(craftAll)); + return ScreenValue.this.callListener(player, "select_recipe", data); } + @Override - public void slotChanged(AbstractContainerMenu handler, int slotId, ItemStack stack) { - Map data = new HashMap<>(); - data.put(StringValue.of("slot"),NumericValue.of(slotId)); - data.put(StringValue.of("stack"),ValueConversions.of(stack, player.level.registryAccess())); - ScreenValue.this.callListener(ScreenValue.this.player,"slot_update",data); + public void slotChanged(final AbstractContainerMenu handler, final int slotId, final ItemStack stack) + { + final Map data = new HashMap<>(); + data.put(StringValue.of("slot"), NumericValue.of(slotId)); + data.put(StringValue.of("stack"), ValueConversions.of(stack, player.level.registryAccess())); + ScreenValue.this.callListener(ScreenValue.this.player, "slot_update", data); } + @Override - public void dataChanged(AbstractContainerMenu handler, int property, int value) {} + public void dataChanged(final AbstractContainerMenu handler, final int property, final int value) + { + } }); } - private DataSlot getPropertyForType(Class screenHandlerClass, String requiredType, int propertyIndex, String propertyName) { - if(screenHandlerClass.isInstance(this.screenHandler)) { + private DataSlot getPropertyForType(final Class screenHandlerClass, final String requiredType, final int propertyIndex, final String propertyName) + { + if (screenHandlerClass.isInstance(this.screenHandler)) + { return ((ScreenHandlerInterface) this.screenHandler).getProperty(propertyIndex); } - if(!this.isOpen()) { + if (!this.isOpen()) + { throw new InternalExpressionException("Screen property cannot be accessed, because the screen is already closed"); } throw new InternalExpressionException("Screen property " + propertyName + " expected a " + requiredType + " screen."); } - private DataSlot getProperty(String propertyName) { - return switch (propertyName) { + private DataSlot getProperty(final String propertyName) + { + return switch (propertyName) + { case "fuel_progress" -> getPropertyForType(AbstractFurnaceMenu.class, "furnace", 0, propertyName); case "max_fuel_progress" -> getPropertyForType(AbstractFurnaceMenu.class, "furnace", 1, propertyName); case "cook_progress" -> getPropertyForType(AbstractFurnaceMenu.class, "furnace", 2, propertyName); case "max_cook_progress" -> getPropertyForType(AbstractFurnaceMenu.class, "furnace", 3, propertyName); - case "level_cost" -> getPropertyForType(AnvilMenu.class, "anvil", 0, propertyName); - case "page" -> getPropertyForType(LecternMenu.class, "lectern", 0, propertyName); - case "beacon_level" -> getPropertyForType(BeaconMenu.class, "beacon", 0, propertyName); case "primary_effect" -> getPropertyForType(BeaconMenu.class, "beacon", 1, propertyName); case "secondary_effect" -> getPropertyForType(BeaconMenu.class, "beacon", 2, propertyName); - case "brew_time" -> getPropertyForType(BrewingStandMenu.class, "brewing_stand", 0, propertyName); case "brewing_fuel" -> getPropertyForType(BrewingStandMenu.class, "brewing_stand", 1, propertyName); - case "enchantment_power_1" -> getPropertyForType(EnchantmentMenu.class, "enchantment", 0, propertyName); case "enchantment_power_2" -> getPropertyForType(EnchantmentMenu.class, "enchantment", 1, propertyName); case "enchantment_power_3" -> getPropertyForType(EnchantmentMenu.class, "enchantment", 2, propertyName); @@ -274,50 +289,55 @@ private DataSlot getProperty(String propertyName) { case "enchantment_level_1" -> getPropertyForType(EnchantmentMenu.class, "enchantment", 7, propertyName); case "enchantment_level_2" -> getPropertyForType(EnchantmentMenu.class, "enchantment", 8, propertyName); case "enchantment_level_3" -> getPropertyForType(EnchantmentMenu.class, "enchantment", 9, propertyName); - case "banner_pattern" -> getPropertyForType(LoomMenu.class, "loom", 0, propertyName); - case "stonecutter_recipe" -> getPropertyForType(StonecutterMenu.class, "stonecutter", 0, propertyName); - default -> throw new InternalExpressionException("Invalid screen property: " + propertyName); }; } - public Value queryProperty(String propertyName) { - if(propertyName.equals("name")) return FormattedTextValue.of(this.name); - if(propertyName.equals("open")) return BooleanValue.of(this.isOpen()); - DataSlot property = getProperty(propertyName); + public Value queryProperty(final String propertyName) + { + if (propertyName.equals("name")) + { + return FormattedTextValue.of(this.name); + } + if (propertyName.equals("open")) + { + return BooleanValue.of(this.isOpen()); + } + final DataSlot property = getProperty(propertyName); return NumericValue.of(property.get()); } - public Value modifyProperty(String propertyName, List lv) { - DataSlot property = getProperty(propertyName); - int intValue = NumericValue.asNumber(lv.get(0)).getInt(); + public Value modifyProperty(final String propertyName, final List lv) + { + final DataSlot property = getProperty(propertyName); + final int intValue = NumericValue.asNumber(lv.get(0)).getInt(); property.set(intValue); this.screenHandler.sendAllDataToRemote(); return Value.TRUE; } - public AbstractContainerMenu getScreenHandler() { - return this.screenHandler; - } - - public ServerPlayer getPlayer() { + public ServerPlayer getPlayer() + { return this.player; } - public Container getInventory() { + public Container getInventory() + { return this.inventory; } @Override - public String getString() { + public String getString() + { return this.typestring + "_screen"; } @Override - public boolean getBoolean() { + public boolean getBoolean() + { return this.isOpen(); } @@ -328,92 +348,134 @@ public String getTypeString() } @Override - public Tag toTag(boolean force) { - if(this.screenHandler == null) { + public Tag toTag(final boolean force) + { + if (this.screenHandler == null) + { return Value.NULL.toTag(true); } - ListTag nbtList = new ListTag(); - for(int i = 0; i < this.screenHandler.slots.size(); i++) { - ItemStack itemStack = this.screenHandler.getSlot(i).getItem(); + final ListTag nbtList = new ListTag(); + for (int i = 0; i < this.screenHandler.slots.size(); i++) + { + final ItemStack itemStack = this.screenHandler.getSlot(i).getItem(); nbtList.add(itemStack.save(new CompoundTag())); } return nbtList; } - public interface ScarpetScreenHandlerListener extends ContainerListener { + public interface ScarpetScreenHandlerListener extends ContainerListener + { boolean onSlotClick(ServerPlayer player, ClickType actionType, int slot, int button); + boolean onButtonClick(ServerPlayer player, int button); + void onClose(ServerPlayer player); + boolean onSelectRecipe(ServerPlayer player, Recipe recipe, boolean craftAll); } - public static class ScreenHandlerInventory implements Container { - + public static class ScreenHandlerInventory implements Container + { protected AbstractContainerMenu screenHandler; - public ScreenHandlerInventory(AbstractContainerMenu screenHandler) { + public ScreenHandlerInventory(final AbstractContainerMenu screenHandler) + { this.screenHandler = screenHandler; } @Override - public int getContainerSize() { + public int getContainerSize() + { return this.screenHandler.slots.size() + 1; } @Override - public boolean isEmpty() { - for(Slot slot : this.screenHandler.slots) { - if(slot.hasItem() && !slot.getItem().isEmpty()) return false; + public boolean isEmpty() + { + for (final Slot slot : this.screenHandler.slots) + { + if (slot.hasItem() && !slot.getItem().isEmpty()) + { + return false; + } } return this.screenHandler.getCarried().isEmpty(); } @Override - public ItemStack getItem(int slot) { - if(slot == this.getContainerSize()-1) return this.screenHandler.getCarried(); + public ItemStack getItem(final int slot) + { + if (slot == this.getContainerSize() - 1) + { + return this.screenHandler.getCarried(); + } return slot >= -1 && slot < this.getContainerSize() ? this.screenHandler.slots.get(slot).getItem() : ItemStack.EMPTY; } @Override - public ItemStack removeItem(int slot, int amount) { - ItemStack itemStack; - if(slot == this.getContainerSize()-1) + public ItemStack removeItem(final int slot, final int amount) + { + final ItemStack itemStack; + if (slot == this.getContainerSize() - 1) + { itemStack = this.screenHandler.getCarried().split(amount); + } else + { itemStack = ScreenHandlerInventory.splitStack(this.screenHandler.slots, slot, amount); - if (!itemStack.isEmpty()) { + } + if (!itemStack.isEmpty()) + { this.setChanged(); } return itemStack; } @Override - public ItemStack removeItemNoUpdate(int slot) { - ItemStack itemStack; - if(slot == this.getContainerSize()-1) + public ItemStack removeItemNoUpdate(final int slot) + { + final ItemStack itemStack; + if (slot == this.getContainerSize() - 1) + { itemStack = this.screenHandler.getCarried(); + } else + { itemStack = this.screenHandler.slots.get(slot).getItem(); - if (itemStack.isEmpty()) { + } + if (itemStack.isEmpty()) + { return ItemStack.EMPTY; - } else { - if(slot == this.getContainerSize()-1) + } + else + { + if (slot == this.getContainerSize() - 1) + { this.screenHandler.setCarried(ItemStack.EMPTY); + } else + { this.screenHandler.slots.get(slot).set(ItemStack.EMPTY); + } return itemStack; } } @Override - public void setItem(int slot, ItemStack stack) { - if(slot == this.getContainerSize()-1) + public void setItem(final int slot, final ItemStack stack) + { + if (slot == this.getContainerSize() - 1) + { this.screenHandler.setCarried(stack); + } else + { this.screenHandler.slots.get(slot).set(stack); - if (!stack.isEmpty() && stack.getCount() > this.getMaxStackSize()) { + } + if (!stack.isEmpty() && stack.getCount() > this.getMaxStackSize()) + { stack.setCount(this.getMaxStackSize()); } @@ -421,18 +483,21 @@ public void setItem(int slot, ItemStack stack) { } @Override - public void setChanged() { - + public void setChanged() + { } @Override - public boolean stillValid(Player player) { + public boolean stillValid(final Player player) + { return true; } @Override - public void clearContent() { - for(Slot slot : this.screenHandler.slots) { + public void clearContent() + { + for (final Slot slot : this.screenHandler.slots) + { slot.set(ItemStack.EMPTY); } this.screenHandler.setCarried(ItemStack.EMPTY); @@ -440,13 +505,16 @@ public void clearContent() { } - public static ItemStack splitStack(List slots, int slot, int amount) { + public static ItemStack splitStack(final List slots, final int slot, final int amount) + { return slot >= 0 && slot < slots.size() && !slots.get(slot).getItem().isEmpty() && amount > 0 ? slots.get(slot).getItem().split(amount) : ItemStack.EMPTY; } } - private static String actionTypeToString(ClickType actionType) { - return switch (actionType) { + private static String actionTypeToString(final ClickType actionType) + { + return switch (actionType) + { case PICKUP -> "pickup"; case QUICK_MOVE -> "quick_move"; case SWAP -> "swap"; diff --git a/src/main/java/carpet/script/value/StringValue.java b/src/main/java/carpet/script/value/StringValue.java index c177aa8db4..65b7dc7ff0 100644 --- a/src/main/java/carpet/script/value/StringValue.java +++ b/src/main/java/carpet/script/value/StringValue.java @@ -7,15 +7,17 @@ public class StringValue extends Value { public static Value EMPTY = StringValue.of(""); - private String str; + private final String str; @Override - public String getString() { + public String getString() + { return str; } @Override - public boolean getBoolean() { + public boolean getBoolean() + { return str != null && !str.isEmpty(); } @@ -25,15 +27,14 @@ public Value clone() return new StringValue(str); } - public StringValue(String str) + public StringValue(final String str) { this.str = str; } - public static Value of(String value) + public static Value of(final String value) { - if (value == null) return Value.NULL; - return new StringValue(value); + return value == null ? Value.NULL : new StringValue(value); } @Override @@ -43,7 +44,7 @@ public String getTypeString() } @Override - public Tag toTag(boolean force) + public Tag toTag(final boolean force) { return StringTag.valueOf(str); } diff --git a/src/main/java/carpet/script/value/ThreadValue.java b/src/main/java/carpet/script/value/ThreadValue.java index d5b37683b4..5423194240 100644 --- a/src/main/java/carpet/script/value/ThreadValue.java +++ b/src/main/java/carpet/script/value/ThreadValue.java @@ -6,10 +6,12 @@ import carpet.script.exception.ExitStatement; import carpet.script.exception.ExpressionException; import carpet.script.exception.InternalExpressionException; + import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; + import net.minecraft.nbt.Tag; public class ThreadValue extends Value @@ -18,21 +20,21 @@ public class ThreadValue extends Value private final long id; private static long sequence = 0L; - public ThreadValue(CompletableFuture taskFuture) + public ThreadValue(final CompletableFuture taskFuture) { this.taskFuture = taskFuture; this.id = sequence++; } - public ThreadValue(Value pool, FunctionValue function, Expression expr, Tokenizer.Token token, Context ctx, List args) + public ThreadValue(final Value pool, final FunctionValue function, final Expression expr, final Tokenizer.Token token, final Context ctx, final List args) { this(getCompletableFutureFromFunction(pool, function, expr, token, ctx, args)); Thread.yield(); } - public static CompletableFuture getCompletableFutureFromFunction(Value pool, FunctionValue function, Expression expr, Tokenizer.Token token, Context ctx, List args) + public static CompletableFuture getCompletableFutureFromFunction(final Value pool, final FunctionValue function, final Expression expr, final Tokenizer.Token token, final Context ctx, final List args) { - ExecutorService executor = ctx.host.getExecutor(pool); + final ExecutorService executor = ctx.host.getExecutor(pool); if (executor == null) { // app is shutting down - no more threads can be spawned. @@ -40,27 +42,22 @@ public static CompletableFuture getCompletableFutureFromFunction(Value po } else { - return CompletableFuture.supplyAsync( - () -> - { - try - { - return function.execute(ctx, Context.NONE, expr, token, args).evalValue(ctx); - } - catch (ExitStatement exit) - { - // app stopped - return exit.retval; - } - catch (ExpressionException exc) - { - ctx.host.handleExpressionException("Thread failed\n", exc); - return Value.NULL; - } - - }, - ctx.host.getExecutor(pool) - ); + return CompletableFuture.supplyAsync(() -> { + try + { + return function.execute(ctx, Context.NONE, expr, token, args).evalValue(ctx); + } + catch (final ExitStatement exit) + { + // app stopped + return exit.retval; + } + catch (final ExpressionException exc) + { + ctx.host.handleExpressionException("Thread failed\n", exc); + return Value.NULL; + } + }, ctx.host.getExecutor(pool)); } } @@ -87,12 +84,12 @@ public Value join() { return taskFuture.get(); } - catch (ExitStatement exit) + catch (final ExitStatement exit) { taskFuture.complete(exit.retval); return exit.retval; } - catch (InterruptedException | ExecutionException e) + catch (final InterruptedException | ExecutionException e) { return Value.NULL; } @@ -104,19 +101,19 @@ public boolean isFinished() } @Override - public boolean equals(Object o) + public boolean equals(final Object o) { - if (!(o instanceof ThreadValue)) - return false; - return ((ThreadValue) o).id == this.id; + return o instanceof final ThreadValue tv && tv.id == this.id; } @Override - public int compareTo(Value o) + public int compareTo(final Value o) { - if (!(o instanceof ThreadValue)) + if (!(o instanceof final ThreadValue tv)) + { throw new InternalExpressionException("Cannot compare tasks to other types"); - return (int) (this.id - ((ThreadValue) o).id); + } + return (int) (this.id - tv.id); } @Override @@ -126,9 +123,12 @@ public int hashCode() } @Override - public Tag toTag(boolean force) + public Tag toTag(final boolean force) { - if (!force) throw new NBTSerializableValue.IncompatibleTypeException(this); + if (!force) + { + throw new NBTSerializableValue.IncompatibleTypeException(this); + } return getValue().toTag(true); } diff --git a/src/main/java/carpet/script/value/UndefValue.java b/src/main/java/carpet/script/value/UndefValue.java index 89c35c9776..b41ae53b48 100644 --- a/src/main/java/carpet/script/value/UndefValue.java +++ b/src/main/java/carpet/script/value/UndefValue.java @@ -4,14 +4,15 @@ import com.google.gson.JsonElement; import net.minecraft.nbt.Tag; -public class UndefValue extends NullValue { +public class UndefValue extends NullValue +{ public static final UndefValue UNDEF = new UndefValue(); - private RuntimeException getError() { - return new InternalExpressionException("variable "+boundVariable+" was used before initialization under 'strict' app config"); + private RuntimeException getError() + { + return new InternalExpressionException("variable " + boundVariable + " was used before initialization under 'strict' app config"); } - @Override public String getString() { @@ -43,28 +44,32 @@ public boolean equals(final Object o) } @Override - public Value slice(long fromDesc, Long toDesc) { + public Value slice(final long fromDesc, final Long toDesc) + { throw getError(); } @Override - public NumericValue opposite() { + public NumericValue opposite() + { throw getError(); } @Override - public int length() { + public int length() + { throw getError(); } @Override - public int compareTo(Value o) + public int compareTo(final Value o) { throw getError(); } @Override - public Value in(Value value) { + public Value in(final Value value) + { throw getError(); } @@ -81,13 +86,14 @@ public int hashCode() } @Override - public Tag toTag(boolean force) + public Tag toTag(final boolean force) { throw getError(); } @Override - public Value split(Value delimiter) { + public Value split(final Value delimiter) + { throw getError(); } @@ -98,29 +104,31 @@ public JsonElement toJson() } @Override - public boolean isNull() { + public boolean isNull() + { throw getError(); } @Override - public Value add(Value v) { + public Value add(final Value v) + { throw getError(); } @Override - public Value subtract(Value v) + public Value subtract(final Value v) { throw getError(); } @Override - public Value multiply(Value v) + public Value multiply(final Value v) { throw getError(); } @Override - public Value divide(Value v) + public Value divide(final Value v) { throw getError(); } diff --git a/src/main/java/carpet/script/value/Value.java b/src/main/java/carpet/script/value/Value.java index c2ed9544e7..cc0cab1d79 100644 --- a/src/main/java/carpet/script/value/Value.java +++ b/src/main/java/carpet/script/value/Value.java @@ -4,23 +4,25 @@ import carpet.script.exception.InternalExpressionException; import com.google.gson.JsonElement; import com.google.gson.JsonPrimitive; + import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; + import net.minecraft.nbt.Tag; public abstract class Value implements Comparable, Cloneable { - public static NumericValue FALSE = BooleanValue.FALSE; - public static NumericValue TRUE = BooleanValue.TRUE; - public static NumericValue ZERO = new NumericValue(0); - public static NumericValue ONE = new NumericValue(1); + public static final NumericValue FALSE = BooleanValue.FALSE; + public static final NumericValue TRUE = BooleanValue.TRUE; + public static final NumericValue ZERO = new NumericValue(0); + public static final NumericValue ONE = new NumericValue(1); - public static NullValue NULL = NullValue.NULL; - public static UndefValue UNDEF = UndefValue.UNDEF; + public static final NullValue NULL = NullValue.NULL; + public static final UndefValue UNDEF = UndefValue.UNDEF; public String boundVariable; @@ -28,29 +30,32 @@ public boolean isBound() { return boundVariable != null; } + public String getVariable() { return boundVariable; } - public Value reboundedTo(String var) + + public Value reboundedTo(final String value) { - Value copy; + final Value copy; try { - copy = (Value)clone(); + copy = (Value) clone(); } - catch (CloneNotSupportedException e) + catch (final CloneNotSupportedException e) { // should not happen CarpetSettings.LOG.error("Failed to clone variable", e); - throw new InternalExpressionException("Variable of type "+getTypeString()+" is not cloneable. Tell gnembon about it, this shoudn't happen"); + throw new InternalExpressionException("Variable of type " + getTypeString() + " is not cloneable. Tell gnembon about it, this shoudn't happen"); } - copy.boundVariable = var; + copy.boundVariable = value; return copy; } - public Value bindTo(String var) + + public Value bindTo(final String value) { - this.boundVariable = var; + this.boundVariable = value; return this; } @@ -64,35 +69,37 @@ public String getPrettyString() public abstract boolean getBoolean(); - public Value add(Value o) { + public Value add(final Value o) + { if (o instanceof FormattedTextValue) { return FormattedTextValue.combine(this, o); } - String leftStr = this.getString(); - String rightStr = o.getString(); + final String leftStr = this.getString(); + final String rightStr = o.getString(); return new StringValue(leftStr + rightStr); } - public Value subtract(Value v) + + public Value subtract(final Value v) { - return new StringValue(this.getString().replace(v.getString(),"")); + return new StringValue(this.getString().replace(v.getString(), "")); } - public Value multiply(Value v) + + public Value multiply(final Value v) { - if (v instanceof NumericValue || v instanceof ListValue) - { - return v.multiply(this); - } - return new StringValue(this.getString()+"."+v.getString()); + return v instanceof NumericValue || v instanceof ListValue + ? v.multiply(this) + : new StringValue(this.getString() + "." + v.getString()); } - public Value divide(Value v) + + public Value divide(final Value v) { - if (v instanceof NumericValue) + if (v instanceof final NumericValue number) { - String lstr = getString(); - return new StringValue(lstr.substring(0, (int)(lstr.length()/ ((NumericValue) v).getDouble()))); + final String lstr = getString(); + return new StringValue(lstr.substring(0, (int) (lstr.length() / number.getDouble()))); } - return new StringValue(getString()+"/"+v.getString()); + return new StringValue(getString() + "/" + v.getString()); } public Value() @@ -103,18 +110,18 @@ public Value() @Override public int compareTo(final Value o) { - if (o instanceof NumericValue || o instanceof ListValue || o instanceof ThreadValue) - { - return -o.compareTo(this); - } - return getString().compareTo(o.getString()); + return o instanceof NumericValue || o instanceof ListValue || o instanceof ThreadValue + ? -o.compareTo(this) + : getString().compareTo(o.getString()); } @Override // for hashmap key access, and == operator public boolean equals(final Object o) { - if (o instanceof Value) - return this.compareTo((Value) o)==0; + if (o instanceof final Value v) + { + return this.compareTo(v) == 0; + } return false; } @@ -126,50 +133,65 @@ public void assertAssignable() { throw new InternalExpressionException(boundVariable+ " cannot be assigned a new value"); }*/ - throw new InternalExpressionException(getString()+ " is not a variable"); - + throw new InternalExpressionException(getString() + " is not a variable"); } } - public Value in(Value value1) + public Value in(final Value value1) { final Pattern p; try { p = Pattern.compile(value1.getString()); } - catch (PatternSyntaxException pse) + catch (final PatternSyntaxException pse) { - throw new InternalExpressionException("Incorrect matching pattern: "+pse.getMessage()); + throw new InternalExpressionException("Incorrect matching pattern: " + pse.getMessage()); } final Matcher m = p.matcher(this.getString()); - if (!m.find()) return Value.NULL; - int gc = m.groupCount(); - if (gc == 0) return new StringValue(m.group()); - if (gc == 1) return StringValue.of(m.group(1)); - List groups = new ArrayList<>(gc); + if (!m.find()) + { + return Value.NULL; + } + final int gc = m.groupCount(); + if (gc == 0) + { + return new StringValue(m.group()); + } + if (gc == 1) + { + return StringValue.of(m.group(1)); + } + final List groups = new ArrayList<>(gc); for (int i = 1; i <= gc; i++) { groups.add(StringValue.of(m.group(i))); } return ListValue.wrap(groups); } + public int length() { return getString().length(); } - public Value slice(long fromDesc, Long toDesc) + public Value slice(final long fromDesc, final Long toDesc) { - String value = this.getString(); - int size = value.length(); - int from = ListValue.normalizeIndex(fromDesc, size); - if (toDesc == null) return new StringValue(value.substring(from)); - int to = ListValue.normalizeIndex(toDesc, size+1); - if (from > to) return StringValue.EMPTY; + final String value = this.getString(); + final int size = value.length(); + final int from = ListValue.normalizeIndex(fromDesc, size); + if (toDesc == null) + { + return new StringValue(value.substring(from)); + } + final int to = ListValue.normalizeIndex(toDesc, size + 1); + if (from > to) + { + return StringValue.EMPTY; + } return new StringValue(value.substring(from, to)); } - + public Value split(Value delimiter) { if (delimiter == null) @@ -180,20 +202,20 @@ public Value split(Value delimiter) { return ListValue.wrap(Arrays.stream(getString().split(delimiter.getString())).map(StringValue::new)); } - catch (PatternSyntaxException pse) + catch (final PatternSyntaxException pse) { - throw new InternalExpressionException("Incorrect pattern for 'split': "+pse.getMessage()); + throw new InternalExpressionException("Incorrect pattern for 'split': " + pse.getMessage()); } } - + public double readDoubleNumber() { - String s = getString(); + final String s = getString(); try { - return Double.valueOf(s); + return Double.parseDouble(s); } - catch (NumberFormatException e) + catch (final NumberFormatException e) { return Double.NaN; } @@ -212,21 +234,20 @@ public String getTypeString() @Override public int hashCode() { - String stringVal = getString(); - if (stringVal.isEmpty()) return 0; - return ("s"+stringVal).hashCode(); + final String stringVal = getString(); + return stringVal.isEmpty() ? 0 : ("s" + stringVal).hashCode(); } public Value deepcopy() { try { - return (Value)this.clone(); + return (Value) this.clone(); } - catch (CloneNotSupportedException e) + catch (final CloneNotSupportedException e) { // should never happen - throw new InternalExpressionException("Cannot make a copy of value: "+this); + throw new InternalExpressionException("Cannot make a copy of value: " + this); } } @@ -237,12 +258,18 @@ public JsonElement toJson() return new JsonPrimitive(getString()); } - public boolean isNull() { return false; } + public boolean isNull() + { + return false; + } /** * @return retrieves useful in-run value of an optimized code-base value. * For immutable values (most of them) it can return itself, * but for mutables, it needs to be its copy or deep copy. */ - public Value fromConstant() { return this; } + public Value fromConstant() + { + return this; + } } diff --git a/src/main/java/carpet/script/value/ValueConversions.java b/src/main/java/carpet/script/value/ValueConversions.java index 2535886d36..98ddd780f8 100644 --- a/src/main/java/carpet/script/value/ValueConversions.java +++ b/src/main/java/carpet/script/value/ValueConversions.java @@ -46,6 +46,7 @@ import net.minecraft.world.phys.Vec3; import net.minecraft.world.scores.Objective; import net.minecraft.world.scores.criteria.ObjectiveCriteria; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -60,58 +61,65 @@ public class ValueConversions { - public static Value of(BlockPos pos) + public static Value of(final BlockPos pos) { return ListValue.of(new NumericValue(pos.getX()), new NumericValue(pos.getY()), new NumericValue(pos.getZ())); } - public static Value of(Vec3 vec) + public static Value of(final Vec3 vec) { return ListValue.of(new NumericValue(vec.x), new NumericValue(vec.y), new NumericValue(vec.z)); } - public static Value of(ColumnPos cpos) { return ListValue.of(new NumericValue(cpos.x()), new NumericValue(cpos.z()));} + public static Value of(final ColumnPos cpos) + { + return ListValue.of(new NumericValue(cpos.x()), new NumericValue(cpos.z())); + } - public static Value of(ServerLevel world) + public static Value of(final ServerLevel world) { return of(world.dimension().location()); } - public static Value of(MaterialColor color) {return ListValue.of(StringValue.of(BlockInfo.mapColourName.get(color)), ofRGB(color.col));} + public static Value of(final MaterialColor color) + { + return ListValue.of(StringValue.of(BlockInfo.mapColourName.get(color)), ofRGB(color.col)); + } - public static Value of(MinMaxBounds range) { return ListValue.of(NumericValue.of(range.getMin()), NumericValue.of(range.getMax()));} + public static Value of(final MinMaxBounds range) + { + return ListValue.of(NumericValue.of(range.getMin()), NumericValue.of(range.getMax())); + } @Deprecated - public static Value of(ItemStack stack) + public static Value of(final ItemStack stack) { - if (stack == null || stack.isEmpty()) - return Value.NULL; - return ListValue.of( + return stack == null || stack.isEmpty() ? Value.NULL : ListValue.of( of(BuiltInRegistries.ITEM.getKey(stack.getItem())), new NumericValue(stack.getCount()), NBTSerializableValue.fromStack(stack) ); } - public static Value of(ItemStack stack, RegistryAccess regs) { - if (stack == null || stack.isEmpty()) - return Value.NULL; - return ListValue.of( + + public static Value of(final ItemStack stack, final RegistryAccess regs) + { + return stack == null || stack.isEmpty() ? Value.NULL : ListValue.of( of(regs.registryOrThrow(Registries.ITEM).getKey(stack.getItem())), new NumericValue(stack.getCount()), NBTSerializableValue.fromStack(stack) ); } - public static Value of(Objective objective) + public static Value of(final Objective objective) { return ListValue.of( StringValue.of(objective.getName()), StringValue.of(objective.getCriteria().getName()) - ); + ); } - public static Value of(ObjectiveCriteria criteria) + public static Value of(final ObjectiveCriteria criteria) { return ListValue.of( StringValue.of(criteria.getName()), @@ -120,20 +128,22 @@ public static Value of(ObjectiveCriteria criteria) } - public static Value of(ParticleOptions particle) + public static Value of(final ParticleOptions particle) { - String repr = particle.writeToString(); - if (repr.startsWith("minecraft:")) return StringValue.of(repr.substring(10)); - return StringValue.of(repr); + final String repr = particle.writeToString(); + return StringValue.of(repr.startsWith("minecraft:") ? repr.substring(10) : repr); } - public static Value ofRGB(int value) {return new NumericValue(value*256+255 );} + public static Value ofRGB(final int value) + { + return new NumericValue(value * 256 + 255); + } - public static Level dimFromValue(Value dimensionValue, MinecraftServer server) + public static Level dimFromValue(final Value dimensionValue, final MinecraftServer server) { if (dimensionValue instanceof EntityValue) { - return ((EntityValue)dimensionValue).getEntity().getCommandSenderWorld(); + return ((EntityValue) dimensionValue).getEntity().getCommandSenderWorld(); } else if (dimensionValue instanceof BlockValue bv) { @@ -148,23 +158,16 @@ else if (dimensionValue instanceof BlockValue bv) } else { - String dimString = dimensionValue.getString().toLowerCase(Locale.ROOT); - switch (dimString) - { - case "nether": - case "the_nether": - return server.getLevel(Level.NETHER); - case "end": - case "the_end": - return server.getLevel(Level.END); - case "overworld": - case "over_world": - return server.getLevel(Level.OVERWORLD); - default: + final String dimString = dimensionValue.getString().toLowerCase(Locale.ROOT); + return switch (dimString) { + case "nether", "the_nether" -> server.getLevel(Level.NETHER); + case "end", "the_end" -> server.getLevel(Level.END); + case "overworld", "over_world" -> server.getLevel(Level.OVERWORLD); + default -> { ResourceKey dim = null; - ResourceLocation id = new ResourceLocation(dimString); + final ResourceLocation id = new ResourceLocation(dimString); // not using RegistryKey.of since that one creates on check - for (ResourceKey world : (server.levelKeys())) + for (final ResourceKey world : (server.levelKeys())) { if (id.equals(world.location())) { @@ -173,36 +176,48 @@ else if (dimensionValue instanceof BlockValue bv) } } if (dim == null) + { throw new ThrowStatement(dimString, Throwables.UNKNOWN_DIMENSION); - return server.getLevel(dim); - } + } + yield server.getLevel(dim); + } + }; } } - public static Value of(ResourceKey dim) + public static Value of(final ResourceKey dim) { return of(dim.location()); } - public static Value of(TagKey tagKey) { return of(tagKey.location()); } + public static Value of(final TagKey tagKey) + { + return of(tagKey.location()); + } - public static Value of(ResourceLocation id) + public static Value of(final ResourceLocation id) { if (id == null) // should be Value.NULL + { return Value.NULL; + } return new StringValue(simplify(id)); } - public static String simplify(ResourceLocation id) + public static String simplify(final ResourceLocation id) { if (id == null) // should be Value.NULL + { return ""; + } if (id.getNamespace().equals("minecraft")) + { return id.getPath(); + } return id.toString(); } - public static Value of(GlobalPos pos) + public static Value of(final GlobalPos pos) { return ListValue.of( ValueConversions.of(pos.dimension()), @@ -210,14 +225,13 @@ public static Value of(GlobalPos pos) ); } - public static Value fromPath(ServerLevel world, Path path) + public static Value fromPath(final ServerLevel world, final Path path) { - List nodes = new ArrayList<>(); - //for (PathNode node: path.getNodes()) + final List nodes = new ArrayList<>(); for (int i = 0, len = path.getNodeCount(); i < len; i++) { - Node node = path.getNode(i); - nodes.add( ListValue.of( + final Node node = path.getNode(i); + nodes.add(ListValue.of( new BlockValue(null, world, node.asBlockPos()), new StringValue(node.type.name().toLowerCase(Locale.ROOT)), new NumericValue(node.costMalus), @@ -227,101 +241,106 @@ public static Value fromPath(ServerLevel world, Path path) return ListValue.wrap(nodes); } - public static Value fromTimedMemory(Entity e, long expiry, Object v) + public static Value fromTimedMemory(final Entity e, final long expiry, final Object v) { - Value ret = fromEntityMemory(e, v); - if (ret.isNull() || expiry == Long.MAX_VALUE) return ret; - return ListValue.of(ret, new NumericValue(expiry)); + final Value ret = fromEntityMemory(e, v); + return ret.isNull() || expiry == Long.MAX_VALUE ? ret : ListValue.of(ret, new NumericValue(expiry)); } - private static Value fromEntityMemory(Entity e, Object v) + private static Value fromEntityMemory(final Entity e, Object v) { if (v instanceof GlobalPos pos) { return of(pos); } - if (v instanceof Entity) + if (v instanceof final Entity entity) { - return new EntityValue((Entity)v); + return new EntityValue(entity); } - if (v instanceof BlockPos) + if (v instanceof final BlockPos pos) { - return new BlockValue(null, (ServerLevel) e.getCommandSenderWorld(), (BlockPos) v); + return new BlockValue(null, e.getCommandSenderWorld(), pos); } - if (v instanceof Number) + if (v instanceof final Number number) { - return new NumericValue(((Number) v).doubleValue()); + return new NumericValue(number.doubleValue()); } - if (v instanceof Boolean) + if (v instanceof final Boolean bool) { - return BooleanValue.of((Boolean) v); + return BooleanValue.of(bool); } - if (v instanceof UUID) + if (v instanceof final UUID uuid) { - return ofUUID( (ServerLevel) e.getCommandSenderWorld(), (UUID)v); + return ofUUID((ServerLevel) e.getCommandSenderWorld(), uuid); } - if (v instanceof DamageSource source) + if (v instanceof final DamageSource source) { return ListValue.of( new StringValue(source.getMsgId()), - source.getEntity()==null?Value.NULL:new EntityValue(source.getEntity()) + source.getEntity() == null ? Value.NULL : new EntityValue(source.getEntity()) ); } - if (v instanceof Path) + if (v instanceof final Path path) { - return fromPath((ServerLevel)e.getCommandSenderWorld(), (Path)v); + return fromPath((ServerLevel) e.getCommandSenderWorld(), path); } - if (v instanceof PositionTracker) + if (v instanceof final PositionTracker tracker) { - return new BlockValue(null, e.getCommandSenderWorld(), ((PositionTracker)v).currentBlockPosition()); + return new BlockValue(null, e.getCommandSenderWorld(), tracker.currentBlockPosition()); } - if (v instanceof WalkTarget) + if (v instanceof final WalkTarget target) { return ListValue.of( - new BlockValue(null, e.getCommandSenderWorld(), ((WalkTarget)v).getTarget().currentBlockPosition()), - new NumericValue(((WalkTarget) v).getSpeedModifier()), - new NumericValue(((WalkTarget) v).getCloseEnoughDist()) + new BlockValue(null, e.getCommandSenderWorld(), target.getTarget().currentBlockPosition()), + new NumericValue(target.getSpeedModifier()), + new NumericValue(target.getCloseEnoughDist()) ); } - if (v instanceof NearestVisibleLivingEntities nvle) { + if (v instanceof final NearestVisibleLivingEntities nvle) + { v = StreamSupport.stream(nvle.findAll(entity -> true).spliterator(), false).toList(); } - if (v instanceof Set) + if (v instanceof final Set set) { - v = new ArrayList<>(((Set) v)); + v = new ArrayList<>(set); } - if (v instanceof List l) + if (v instanceof final List l) { - if (l.isEmpty()) return ListValue.of(); - Object el = l.get(0); - if (el instanceof Entity) + if (l.isEmpty()) + { + return ListValue.of(); + } + final Object el = l.get(0); + if (el instanceof final Entity entity) { - return ListValue.wrap(l.stream().map(o -> new EntityValue((Entity)o))); + return ListValue.wrap(l.stream().map(o -> new EntityValue(entity))); } - if (el instanceof GlobalPos) + if (el instanceof final GlobalPos pos) { - return ListValue.wrap(l.stream().map(o -> of((GlobalPos) o))); + return ListValue.wrap(l.stream().map(o -> of(pos))); } } return Value.NULL; } - private static Value ofUUID(ServerLevel entityWorld, UUID uuid) + private static Value ofUUID(final ServerLevel entityWorld, final UUID uuid) { - Entity current = entityWorld.getEntity(uuid); + final Entity current = entityWorld.getEntity(uuid); return ListValue.of( - current == null?Value.NULL:new EntityValue(current), + current == null ? Value.NULL : new EntityValue(current), new StringValue(uuid.toString()) ); } - public static Value of(AABB box) + + public static Value of(final AABB box) { return ListValue.of( ListValue.fromTriple(box.minX, box.minY, box.minZ), ListValue.fromTriple(box.maxX, box.maxY, box.maxZ) ); } - public static Value of(BoundingBox box) + + public static Value of(final BoundingBox box) { return ListValue.of( ListValue.fromTriple(box.minX(), box.minY(), box.minZ()), @@ -329,17 +348,23 @@ public static Value of(BoundingBox box) ); } - public static Value of(StructureStart structure, final RegistryAccess regs) + public static Value of(final StructureStart structure, final RegistryAccess regs) { - if (structure == null || structure == StructureStart.INVALID_START) return Value.NULL; - BoundingBox boundingBox = structure.getBoundingBox(); - if (boundingBox.maxX() < boundingBox.minX() || boundingBox.maxY() < boundingBox.minY() || boundingBox.maxZ() < boundingBox.minZ()) return Value.NULL; - Map ret = new HashMap<>(); + if (structure == null || structure == StructureStart.INVALID_START) + { + return Value.NULL; + } + final BoundingBox boundingBox = structure.getBoundingBox(); + if (boundingBox.maxX() < boundingBox.minX() || boundingBox.maxY() < boundingBox.minY() || boundingBox.maxZ() < boundingBox.minZ()) + { + return Value.NULL; + } + final Map ret = new HashMap<>(); ret.put(new StringValue("box"), of(boundingBox)); - List pieces = new ArrayList<>(); - for (StructurePiece piece : structure.getPieces()) + final List pieces = new ArrayList<>(); + for (final StructurePiece piece : structure.getPieces()) { - BoundingBox box = piece.getBoundingBox(); + final BoundingBox box = piece.getBoundingBox(); if (box.maxX() >= box.minX() && box.maxY() >= box.minY() && box.maxZ() >= box.minZ()) { pieces.add(ListValue.of( @@ -354,41 +379,51 @@ public static Value of(StructureStart structure, final RegistryAccess regs) return MapValue.wrap(ret); } - public static Value fromProperty(BlockState state, Property p) + public static Value fromProperty(final BlockState state, final Property p) { - Comparable object = state.getValue(p); - if (object instanceof Boolean || object instanceof Number) return StringValue.of(object.toString()); - if (object instanceof StringRepresentable) + final Comparable object = state.getValue(p); + if (object instanceof Boolean || object instanceof Number) { - return StringValue.of(((StringRepresentable) object).getSerializedName()); + return StringValue.of(object.toString()); } - throw new InternalExpressionException("Unknown property type: "+p.getName()); + if (object instanceof final StringRepresentable stringRepresentable) + { + return StringValue.of(stringRepresentable.getSerializedName()); + } + throw new InternalExpressionException("Unknown property type: " + p.getName()); } - record SlotParam(/* Nullable */ String type, int id) { - public ListValue build() { + record SlotParam(/* Nullable */ String type, int id) + { + public ListValue build() + { return ListValue.of(StringValue.of(type), new NumericValue(id)); } } - private static final Int2ObjectMap slotIdsToSlotParams = new Int2ObjectOpenHashMap<>() {{ + private static final Int2ObjectMap slotIdsToSlotParams = new Int2ObjectOpenHashMap<>() + {{ int n; //covers blocks, player hotbar and inventory, and all default inventories - for(n = 0; n < 54; ++n) { + for (n = 0; n < 54; ++n) + { put(n, new SlotParam(null, n)); } - for(n = 0; n < 27; ++n) { + for (n = 0; n < 27; ++n) + { put(200 + n, new SlotParam("enderchest", n)); } // villager - for(n = 0; n < 8; ++n) { + for (n = 0; n < 8; ++n) + { put(300 + n, new SlotParam(null, n)); } // horse, llamas, donkeys, etc. // two first slots are for saddle and armour - for(n = 0; n < 15; ++n) { + for (n = 0; n < 15; ++n) + { put(500 + n, new SlotParam(null, n + 2)); } // weapon main hand @@ -396,7 +431,8 @@ public ListValue build() { // offhand put(99, new SlotParam("equipment", 5)); // feet, legs, chest, head - for(n = 0; n < 4; ++n) { + for (n = 0; n < 4; ++n) + { put(100 + n, new SlotParam("equipment", n + 1)); } //horse defaults saddle @@ -407,26 +443,25 @@ public ListValue build() { //hashMap.put("horse.chest", 499); }}; - public static Value ofVanillaSlotResult(int itemSlot) + public static Value ofVanillaSlotResult(final int itemSlot) { - SlotParam ret = slotIdsToSlotParams.get(itemSlot); - if (ret == null) return ListValue.of(Value.NULL, new NumericValue(itemSlot)); - return ret.build(); + final SlotParam ret = slotIdsToSlotParams.get(itemSlot); + return ret == null ? ListValue.of(Value.NULL, new NumericValue(itemSlot)) : ret.build(); } - public static Value ofBlockPredicate(RegistryAccess registryAccess, Predicate blockPredicate) + public static Value ofBlockPredicate(final RegistryAccess registryAccess, final Predicate blockPredicate) { - BlockPredicateInterface predicateData = (BlockPredicateInterface) blockPredicate; + final BlockPredicateInterface predicateData = (BlockPredicateInterface) blockPredicate; final Registry blocks = registryAccess.registryOrThrow(Registries.BLOCK); return ListValue.of( - predicateData.getCMBlockState()==null?Value.NULL:of(blocks.getKey(predicateData.getCMBlockState().getBlock())), - predicateData.getCMBlockTagKey()==null?Value.NULL:of(blocks.getTag(predicateData.getCMBlockTagKey()).get().key()), + predicateData.getCMBlockState() == null ? Value.NULL : of(blocks.getKey(predicateData.getCMBlockState().getBlock())), + predicateData.getCMBlockTagKey() == null ? Value.NULL : of(blocks.getTag(predicateData.getCMBlockTagKey()).get().key()), MapValue.wrap(predicateData.getCMProperties()), - predicateData.getCMDataTag() == null?Value.NULL:new NBTSerializableValue(predicateData.getCMDataTag()) + predicateData.getCMDataTag() == null ? Value.NULL : new NBTSerializableValue(predicateData.getCMDataTag()) ); } - public static ItemStack getItemStackFromValue(Value value, boolean withCount, RegistryAccess regs) + public static ItemStack getItemStackFromValue(final Value value, final boolean withCount, final RegistryAccess regs) { if (value.isNull()) { @@ -439,7 +474,7 @@ public static ItemStack getItemStackFromValue(Value value, boolean withCount, Re { if (list.length() != 3) { - throw new ThrowStatement("item definition from list of size "+list.length(), Throwables.UNKNOWN_ITEM); + throw new ThrowStatement("item definition from list of size " + list.length(), Throwables.UNKNOWN_ITEM); } final List items = list.getItems(); name = items.get(0).getString(); @@ -447,7 +482,7 @@ public static ItemStack getItemStackFromValue(Value value, boolean withCount, Re { count = NumericValue.asNumber(items.get(1)).getInt(); } - Value nbtValue = items.get(2); + final Value nbtValue = items.get(2); if (!nbtValue.isNull()) { nbtTag = ((NBTSerializableValue) NBTSerializableValue.fromValue(nbtValue)).getCompoundTag(); @@ -457,12 +492,12 @@ public static ItemStack getItemStackFromValue(Value value, boolean withCount, Re { name = value.getString(); } - ItemInput itemInput = NBTSerializableValue.parseItem(name, nbtTag, regs); + final ItemInput itemInput = NBTSerializableValue.parseItem(name, nbtTag, regs); try { - return itemInput.createItemStack(count,false); + return itemInput.createItemStack(count, false); } - catch (CommandSyntaxException cse) + catch (final CommandSyntaxException cse) { if (!withCount) { @@ -475,31 +510,56 @@ public static ItemStack getItemStackFromValue(Value value, boolean withCount, Re } } - public static Value guess(ServerLevel serverWorld, Object o) { + public static Value guess(final ServerLevel serverWorld, final Object o) + { if (o == null) + { return Value.NULL; - if (o instanceof List) - return ListValue.wrap(((List) o).stream().map(oo -> guess(serverWorld, oo))); - if (o instanceof BlockPos) - return new BlockValue(null, serverWorld, (BlockPos)o); - if (o instanceof Entity) - return EntityValue.of((Entity) o); - if (o instanceof Vec3) - return of((Vec3)o); - if (o instanceof Vec3i) - return of(new BlockPos((Vec3i)o)); - if (o instanceof AABB) - return of((AABB)o); - if (o instanceof BoundingBox) - return of((BoundingBox) o); - if (o instanceof ItemStack) - return of((ItemStack)o, serverWorld.registryAccess()); - if (o instanceof Boolean) - return BooleanValue.of((Boolean) o); - if (o instanceof Number) - return NumericValue.of((Number) o); - if (o instanceof ResourceLocation) - return of((ResourceLocation)o); + } + if (o instanceof final List list) + { + return ListValue.wrap(list.stream().map(oo -> guess(serverWorld, oo))); + } + if (o instanceof final BlockPos pos) + { + return new BlockValue(null, serverWorld, pos); + } + if (o instanceof final Entity e) + { + return EntityValue.of(e); + } + if (o instanceof final Vec3 vec3) + { + return of(vec3); + } + if (o instanceof final Vec3i vec3i) + { + return of(new BlockPos(vec3i)); + } + if (o instanceof final AABB aabb) + { + return of(aabb); + } + if (o instanceof final BoundingBox bb) + { + return of(bb); + } + if (o instanceof final ItemStack itemStack) + { + return of(itemStack, serverWorld.registryAccess()); + } + if (o instanceof final Boolean bool) + { + return BooleanValue.of(bool); + } + if (o instanceof final Number number) + { + return NumericValue.of(number); + } + if (o instanceof final ResourceLocation resourceLocation) + { + return of(resourceLocation); + } return StringValue.of(o.toString()); } } From 15f99b33890e9eb77d4f6786030e7b6da41fbac8 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Sat, 4 Feb 2023 23:48:55 +0100 Subject: [PATCH 043/233] fixing mahusive JVM crash --- src/main/java/carpet/script/value/EntityValue.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/carpet/script/value/EntityValue.java b/src/main/java/carpet/script/value/EntityValue.java index 4576f73512..c2a262e1ba 100644 --- a/src/main/java/carpet/script/value/EntityValue.java +++ b/src/main/java/carpet/script/value/EntityValue.java @@ -1537,8 +1537,8 @@ else if (v instanceof final ListValue lv) { return; } - final GameType toSet = v instanceof final NumericValue number ? - GameType.byId(number.getInt()) : + final GameType toSet = v instanceof NumericValue ? + GameType.byId(((NumericValue) v).getInt()) : GameType.byName(v.getString().toLowerCase(Locale.ROOT), null); if (toSet != null) { From fd93785feccd2a754a51e91c2f082f6a6cd73ed6 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Sun, 5 Feb 2023 12:56:06 +0100 Subject: [PATCH 044/233] added nonnull assertions --- build.gradle | 1 + gradle.properties | 1 + src/main/java/carpet/script/annotation/package-info.java | 8 ++++++++ src/main/java/carpet/script/api/package-info.java | 8 ++++++++ src/main/java/carpet/script/argument/package-info.java | 8 ++++++++ src/main/java/carpet/script/command/package-info.java | 8 ++++++++ src/main/java/carpet/script/exception/package-info.java | 8 ++++++++ src/main/java/carpet/script/language/package-info.java | 8 ++++++++ src/main/java/carpet/script/package-info.java | 8 ++++++++ src/main/java/carpet/script/utils/package-info.java | 8 ++++++++ .../java/carpet/script/utils/shapes/package-info.java | 8 ++++++++ src/main/java/carpet/script/value/package-info.java | 8 ++++++++ 12 files changed, 82 insertions(+) create mode 100644 src/main/java/carpet/script/annotation/package-info.java create mode 100644 src/main/java/carpet/script/api/package-info.java create mode 100644 src/main/java/carpet/script/argument/package-info.java create mode 100644 src/main/java/carpet/script/command/package-info.java create mode 100644 src/main/java/carpet/script/exception/package-info.java create mode 100644 src/main/java/carpet/script/language/package-info.java create mode 100644 src/main/java/carpet/script/package-info.java create mode 100644 src/main/java/carpet/script/utils/package-info.java create mode 100644 src/main/java/carpet/script/utils/shapes/package-info.java create mode 100644 src/main/java/carpet/script/value/package-info.java diff --git a/build.gradle b/build.gradle index 7e7d6460b8..3737e495a7 100644 --- a/build.gradle +++ b/build.gradle @@ -28,6 +28,7 @@ dependencies { // PSA: Some older mods, compiled on Loom 0.2.1, might have outdated Maven POMs. // You may need to force-disable transitiveness on them. + compileOnly "com.google.code.findbugs:jsr305:${project.jsr305_version}" } processResources { diff --git a/gradle.properties b/gradle.properties index cc97e2cb16..d3691f3d91 100644 --- a/gradle.properties +++ b/gradle.properties @@ -6,6 +6,7 @@ org.gradle.jvmargs=-Xmx1G # or better: https://modmuss50.me/fabric.html minecraft_version=23w05a loader_version=0.14.13 + jsr305_version=3.0.2 fabric_version=0.73.3+1.19.4 # Mod Properties diff --git a/src/main/java/carpet/script/annotation/package-info.java b/src/main/java/carpet/script/annotation/package-info.java new file mode 100644 index 0000000000..2624cd01d1 --- /dev/null +++ b/src/main/java/carpet/script/annotation/package-info.java @@ -0,0 +1,8 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package carpet.script.annotation; + +import net.minecraft.FieldsAreNonnullByDefault; +import net.minecraft.MethodsReturnNonnullByDefault; +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/carpet/script/api/package-info.java b/src/main/java/carpet/script/api/package-info.java new file mode 100644 index 0000000000..f919f794c7 --- /dev/null +++ b/src/main/java/carpet/script/api/package-info.java @@ -0,0 +1,8 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package carpet.script.api; + +import net.minecraft.FieldsAreNonnullByDefault; +import net.minecraft.MethodsReturnNonnullByDefault; +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/carpet/script/argument/package-info.java b/src/main/java/carpet/script/argument/package-info.java new file mode 100644 index 0000000000..88201df07f --- /dev/null +++ b/src/main/java/carpet/script/argument/package-info.java @@ -0,0 +1,8 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package carpet.script.argument; + +import net.minecraft.FieldsAreNonnullByDefault; +import net.minecraft.MethodsReturnNonnullByDefault; +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/carpet/script/command/package-info.java b/src/main/java/carpet/script/command/package-info.java new file mode 100644 index 0000000000..a49b08e917 --- /dev/null +++ b/src/main/java/carpet/script/command/package-info.java @@ -0,0 +1,8 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package carpet.script.command; + +import net.minecraft.FieldsAreNonnullByDefault; +import net.minecraft.MethodsReturnNonnullByDefault; +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/carpet/script/exception/package-info.java b/src/main/java/carpet/script/exception/package-info.java new file mode 100644 index 0000000000..cb4c4d3e83 --- /dev/null +++ b/src/main/java/carpet/script/exception/package-info.java @@ -0,0 +1,8 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package carpet.script.exception; + +import net.minecraft.FieldsAreNonnullByDefault; +import net.minecraft.MethodsReturnNonnullByDefault; +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/carpet/script/language/package-info.java b/src/main/java/carpet/script/language/package-info.java new file mode 100644 index 0000000000..812e4dc23d --- /dev/null +++ b/src/main/java/carpet/script/language/package-info.java @@ -0,0 +1,8 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package carpet.script.language; + +import net.minecraft.FieldsAreNonnullByDefault; +import net.minecraft.MethodsReturnNonnullByDefault; +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/carpet/script/package-info.java b/src/main/java/carpet/script/package-info.java new file mode 100644 index 0000000000..e2c4fe3a34 --- /dev/null +++ b/src/main/java/carpet/script/package-info.java @@ -0,0 +1,8 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package carpet.script; + +import net.minecraft.FieldsAreNonnullByDefault; +import net.minecraft.MethodsReturnNonnullByDefault; +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/carpet/script/utils/package-info.java b/src/main/java/carpet/script/utils/package-info.java new file mode 100644 index 0000000000..61a3a27cb1 --- /dev/null +++ b/src/main/java/carpet/script/utils/package-info.java @@ -0,0 +1,8 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package carpet.script.utils; + +import net.minecraft.FieldsAreNonnullByDefault; +import net.minecraft.MethodsReturnNonnullByDefault; +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/carpet/script/utils/shapes/package-info.java b/src/main/java/carpet/script/utils/shapes/package-info.java new file mode 100644 index 0000000000..1055bff05c --- /dev/null +++ b/src/main/java/carpet/script/utils/shapes/package-info.java @@ -0,0 +1,8 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package carpet.script.utils.shapes; + +import net.minecraft.FieldsAreNonnullByDefault; +import net.minecraft.MethodsReturnNonnullByDefault; +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/carpet/script/value/package-info.java b/src/main/java/carpet/script/value/package-info.java new file mode 100644 index 0000000000..8d3b588ee6 --- /dev/null +++ b/src/main/java/carpet/script/value/package-info.java @@ -0,0 +1,8 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package carpet.script.value; + +import net.minecraft.FieldsAreNonnullByDefault; +import net.minecraft.MethodsReturnNonnullByDefault; +import javax.annotation.ParametersAreNonnullByDefault; From 75d94b0570751e6ef319016cd5797ccf3737a12f Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Mon, 6 Feb 2023 02:57:38 +0100 Subject: [PATCH 045/233] cleanup of scarpet dependencies --- src/main/java/carpet/CarpetServer.java | 17 +- src/main/java/carpet/CarpetSettings.java | 4 +- .../carpet/api/settings/SettingsManager.java | 31 +- .../java/carpet/commands/MobAICommand.java | 2 +- .../java/carpet/commands/PlayerCommand.java | 7 +- ...va => AbstractContainerMenuInterface.java} | 5 +- .../carpet/fakes/ChunkGeneratorInterface.java | 13 - .../fakes/MinecraftServerInterface.java | 4 + ...erface.java => ServerPlayerInterface.java} | 2 +- .../helpers/EntityPlayerActionPack.java | 12 +- .../java/carpet/helpers/ParticleDisplay.java | 33 +- ...tContainerMenuSubclasses_scarpetMixin.java | 4 +- .../AbstractContainerMenu_scarpetMixin.java | 7 +- .../mixins/ChunkGenerator_scarpetMixin.java | 26 - src/main/java/carpet/mixins/EntityMixin.java | 1 + .../mixins/Ingredient_scarpetMixin.java | 4 +- .../mixins/MinecraftServer_scarpetMixin.java | 26 +- .../mixins/PlayerList_scarpetEventsMixin.java | 4 +- .../mixins/RecipeBookMenu_scarpetMixin.java | 4 +- .../mixins/ServerLevel_scarpetMixin.java | 1 + .../mixins/ServerPlayer_actionPackMixin.java | 5 +- .../ServerPlayer_scarpetEventMixin.java | 4 +- .../carpet/patches/EntityPlayerMPFake.java | 4 +- .../java/carpet/script/CarpetEventServer.java | 245 +++++----- .../java/carpet/script/CarpetExpression.java | 14 +- .../java/carpet/script/CarpetScriptHost.java | 71 ++- .../carpet/script/CarpetScriptServer.java | 74 ++- src/main/java/carpet/script/Context.java | 5 + .../java/carpet/script/EntityEventsGroup.java | 13 +- src/main/java/carpet/script/Expression.java | 51 +- src/main/java/carpet/script/Fluff.java | 3 +- src/main/java/carpet/script/Module.java | 15 +- .../{commands => script}/ScriptCommand.java | 455 ++++++++++-------- src/main/java/carpet/script/ScriptHost.java | 6 + src/main/java/carpet/script/ScriptServer.java | 5 +- .../java/carpet/script/api/Auxiliary.java | 57 ++- .../java/carpet/script/api/Inventories.java | 7 +- .../java/carpet/script/api/Monitoring.java | 6 +- .../java/carpet/script/api/Scoreboards.java | 15 +- .../java/carpet/script/api/WorldAccess.java | 70 ++- .../carpet/script/argument/FileArgument.java | 22 +- .../script/command/CommandArgument.java | 16 +- .../exception/CarpetExpressionException.java | 4 +- .../script/exception/ExpressionException.java | 4 +- .../exception/StacklessRuntimeException.java | 2 +- .../java/carpet/script/external/Carpet.java | 181 +++++++ .../java/carpet/script/external/Vanilla.java | 364 ++++++++++++++ .../carpet/script/external/VanillaClient.java | 13 + .../carpet/script/external/package-info.java | 8 + .../carpet/script/utils/AppStoreManager.java | 53 +- .../java/carpet/script/utils/BiomeInfo.java | 4 +- .../java/carpet/script/utils/EntityTools.java | 34 ++ .../carpet/script/utils/Experimental.java | 4 +- .../utils}/FeatureGenerator.java | 204 ++++---- .../carpet/script/utils/ParticleParser.java | 42 ++ .../carpet/script/utils/ShapeDispatcher.java | 24 +- .../carpet/script/utils/ShapesRenderer.java | 24 +- .../script/utils/SnoopyCommandSource.java | 6 +- .../java/carpet/script/utils/SystemInfo.java | 46 +- .../{helpers => script/utils}/Tracer.java | 42 +- .../java/carpet/script/utils/WorldTools.java | 15 +- .../script/value/AbstractListValue.java | 1 - .../java/carpet/script/value/BlockValue.java | 7 +- .../java/carpet/script/value/EntityValue.java | 70 ++- .../carpet/script/value/FunctionValue.java | 5 +- .../script/value/NBTSerializableValue.java | 7 +- .../java/carpet/script/value/ScreenValue.java | 43 +- src/main/java/carpet/script/value/Value.java | 4 +- .../carpet/script/value/ValueConversions.java | 16 +- src/main/java/carpet/utils/MobAI.java | 27 +- src/main/resources/carpet.mixins.json | 1 - 71 files changed, 1617 insertions(+), 1008 deletions(-) rename src/main/java/carpet/fakes/{ScreenHandlerInterface.java => AbstractContainerMenuInterface.java} (81%) delete mode 100644 src/main/java/carpet/fakes/ChunkGeneratorInterface.java rename src/main/java/carpet/fakes/{ServerPlayerEntityInterface.java => ServerPlayerInterface.java} (83%) delete mode 100644 src/main/java/carpet/mixins/ChunkGenerator_scarpetMixin.java rename src/main/java/carpet/{commands => script}/ScriptCommand.java (56%) create mode 100644 src/main/java/carpet/script/external/Carpet.java create mode 100644 src/main/java/carpet/script/external/Vanilla.java create mode 100644 src/main/java/carpet/script/external/VanillaClient.java create mode 100644 src/main/java/carpet/script/external/package-info.java create mode 100644 src/main/java/carpet/script/utils/EntityTools.java rename src/main/java/carpet/{helpers => script/utils}/FeatureGenerator.java (67%) create mode 100644 src/main/java/carpet/script/utils/ParticleParser.java rename src/main/java/carpet/{helpers => script/utils}/Tracer.java (55%) diff --git a/src/main/java/carpet/CarpetServer.java b/src/main/java/carpet/CarpetServer.java index ea0f34c3b1..2b9aa05ea8 100644 --- a/src/main/java/carpet/CarpetServer.java +++ b/src/main/java/carpet/CarpetServer.java @@ -14,19 +14,19 @@ import carpet.commands.PerimeterInfoCommand; import carpet.commands.PlayerCommand; import carpet.commands.ProfileCommand; -import carpet.commands.ScriptCommand; +import carpet.script.ScriptCommand; import carpet.commands.SpawnCommand; import carpet.commands.TestCommand; import carpet.commands.TickCommand; import carpet.network.ServerNetworkHandler; import carpet.helpers.HopperCounter; -import carpet.helpers.ParticleDisplay; import carpet.helpers.TickSpeed; import carpet.logging.LoggerRegistry; import carpet.script.CarpetScriptServer; import carpet.api.settings.SettingsManager; import carpet.logging.HUDController; -import carpet.utils.FabricAPIHooks; +import carpet.script.external.Carpet; +import carpet.script.utils.ParticleParser; import carpet.utils.MobAI; import carpet.utils.SpawnReporter; import com.mojang.brigadier.CommandDispatcher; @@ -90,6 +90,7 @@ public static void onServerLoaded(MinecraftServer server) e.onServerLoaded(server); }); scriptServer = new CarpetScriptServer(server); + Carpet.MinecraftServer_addScriptServer(server, scriptServer); MobAI.resetTrackers(); LoggerRegistry.initLoggers(); //TickSpeed.reset(); @@ -99,6 +100,14 @@ public static void onServerLoadedWorlds(MinecraftServer minecraftServer) { HopperCounter.resetAll(minecraftServer, true); extensions.forEach(e -> e.onServerLoadedWorlds(minecraftServer)); + // initialize scarpet rules after all extensions are loaded + settingsManager.initializeScarpetRules(); + extensions.forEach(e -> { + if (e.extensionSettingsManager() != null) + { + e.extensionSettingsManager().initializeScarpetRules(); + } + }); scriptServer.initializeForWorld(); } @@ -185,7 +194,7 @@ public static void onServerClosed(MinecraftServer server) LoggerRegistry.stopLoggers(); HUDController.resetScarpetHUDs(); - ParticleDisplay.resetCache(); + ParticleParser.resetCache(); extensions.forEach(e -> e.onServerClosed(server)); minecraft_server = null; } diff --git a/src/main/java/carpet/CarpetSettings.java b/src/main/java/carpet/CarpetSettings.java index 92dc919f67..97b144a06d 100644 --- a/src/main/java/carpet/CarpetSettings.java +++ b/src/main/java/carpet/CarpetSettings.java @@ -4,7 +4,7 @@ import carpet.api.settings.RuleCategory; import carpet.api.settings.Validators; import carpet.api.settings.Validator; -import carpet.script.utils.AppStoreManager; +import carpet.script.external.Carpet; import carpet.settings.Rule; import carpet.utils.Translations; import carpet.utils.CommandHelper; @@ -562,7 +562,7 @@ private static class ModulePermissionLevel extends Validator { }, category = SCARPET, strict = false, - validate= AppStoreManager.ScarpetAppStoreValidator.class + validate= Carpet.ScarpetAppStoreValidator.class ) public static String scriptsAppStore = "gnembon/scarpet/contents/programs"; diff --git a/src/main/java/carpet/api/settings/SettingsManager.java b/src/main/java/carpet/api/settings/SettingsManager.java index 18703606bc..8dec18d6ed 100644 --- a/src/main/java/carpet/api/settings/SettingsManager.java +++ b/src/main/java/carpet/api/settings/SettingsManager.java @@ -25,6 +25,8 @@ import java.util.stream.Collectors; import java.util.stream.Stream; +import carpet.script.CarpetEventServer; +import carpet.script.value.StringValue; import com.google.common.collect.Sets; import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.arguments.StringArgumentType; @@ -54,7 +56,6 @@ import net.minecraft.server.MinecraftServer; import net.minecraft.world.level.storage.LevelResource; -import static carpet.script.CarpetEventServer.Event.CARPET_RULE_CHANGES; import static carpet.utils.Translations.tr; import static java.util.Comparator.comparing; import static net.minecraft.commands.Commands.argument; @@ -258,13 +259,39 @@ public void addCarpetRule(CarpetRule rule) { rules.put(rule.name(), rule); } + public static final CarpetEventServer.Event CARPET_RULE_CHANGES = new CarpetEventServer.Event("carpet_rule_changes", 2, true) + { + @Override + public void handleAny(final Object ... args) + { + final CarpetRule rule = (CarpetRule) args[0]; + final CommandSourceStack source = (CommandSourceStack) args[1]; + final String id = rule.settingsManager().identifier(); + final String namespace; + if (!id.equals("carpet")) + { + namespace = id + ":"; + } + else + { + namespace = ""; + } + handler.call( + () -> Arrays.asList( + new StringValue(namespace + rule.name()), + new StringValue(RuleHelper.toRuleString(rule.value())) + ), () -> source + ); + } + }; + public void notifyRuleChanged(CommandSourceStack source, CarpetRule rule, String userInput) { observers.forEach(observer -> observer.ruleChanged(source, rule, userInput)); staticObservers.forEach(observer -> observer.ruleChanged(source, rule, userInput)); ServerNetworkHandler.updateRuleWithConnectedClients(rule); switchScarpetRuleIfNeeded(source, rule); //TODO move into rule - if (CARPET_RULE_CHANGES.isNeeded()) CARPET_RULE_CHANGES.onCarpetRuleChanges(rule, source); + if (CARPET_RULE_CHANGES.isNeeded()) CARPET_RULE_CHANGES.handleAny(rule, source); } /** diff --git a/src/main/java/carpet/commands/MobAICommand.java b/src/main/java/carpet/commands/MobAICommand.java index f905ebda0c..5345583079 100644 --- a/src/main/java/carpet/commands/MobAICommand.java +++ b/src/main/java/carpet/commands/MobAICommand.java @@ -27,7 +27,7 @@ public static void register(CommandDispatcher dispatcher, fi suggests( (c, b) -> suggest(MobAI.availbleTypes(c.getSource()), b)). then(literal("clear").executes( (c) -> { - MobAI.clearTracking(getSummonableEntityType(c, "entity type").value()); + MobAI.clearTracking(c.getSource().getServer(), getSummonableEntityType(c, "entity type").value()); return 1; } )). diff --git a/src/main/java/carpet/commands/PlayerCommand.java b/src/main/java/carpet/commands/PlayerCommand.java index c93eafeda3..da2c8dd7ae 100644 --- a/src/main/java/carpet/commands/PlayerCommand.java +++ b/src/main/java/carpet/commands/PlayerCommand.java @@ -2,7 +2,7 @@ import carpet.helpers.EntityPlayerActionPack; import carpet.CarpetSettings; -import carpet.fakes.ServerPlayerEntityInterface; +import carpet.fakes.ServerPlayerInterface; import carpet.patches.EntityPlayerMPFake; import carpet.utils.CommandHelper; import carpet.utils.Messenger; @@ -14,7 +14,6 @@ import com.mojang.brigadier.builder.LiteralArgumentBuilder; import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.exceptions.CommandSyntaxException; -import com.mojang.util.UUIDTypeAdapter; import net.minecraft.commands.CommandBuildContext; import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.arguments.DimensionArgument; @@ -336,7 +335,7 @@ private static int stop(CommandContext context) { if (cantManipulate(context)) return 0; ServerPlayer player = getPlayer(context); - ((ServerPlayerEntityInterface) player).getActionPack().stopAll(); + ((ServerPlayerInterface) player).getActionPack().stopAll(); return 1; } @@ -344,7 +343,7 @@ private static int manipulate(CommandContext context, Consum { if (cantManipulate(context)) return 0; ServerPlayer player = getPlayer(context); - action.accept(((ServerPlayerEntityInterface) player).getActionPack()); + action.accept(((ServerPlayerInterface) player).getActionPack()); return 1; } diff --git a/src/main/java/carpet/fakes/ScreenHandlerInterface.java b/src/main/java/carpet/fakes/AbstractContainerMenuInterface.java similarity index 81% rename from src/main/java/carpet/fakes/ScreenHandlerInterface.java rename to src/main/java/carpet/fakes/AbstractContainerMenuInterface.java index fbd0e11d22..501784d4be 100644 --- a/src/main/java/carpet/fakes/ScreenHandlerInterface.java +++ b/src/main/java/carpet/fakes/AbstractContainerMenuInterface.java @@ -5,8 +5,9 @@ import net.minecraft.world.inventory.DataSlot; import net.minecraft.world.item.crafting.Recipe; -public interface ScreenHandlerInterface { - DataSlot getProperty(int index); +public interface AbstractContainerMenuInterface +{ + DataSlot getDataSlot(int index); boolean callButtonClickListener(int button, Player player); boolean callSelectRecipeListener(ServerPlayer player, Recipe recipe, boolean craftAll); } diff --git a/src/main/java/carpet/fakes/ChunkGeneratorInterface.java b/src/main/java/carpet/fakes/ChunkGeneratorInterface.java deleted file mode 100644 index de3d2ffd42..0000000000 --- a/src/main/java/carpet/fakes/ChunkGeneratorInterface.java +++ /dev/null @@ -1,13 +0,0 @@ -package carpet.fakes; - -import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.level.levelgen.structure.Structure; -import net.minecraft.world.level.levelgen.structure.placement.StructurePlacement; - -import java.util.List; - -public interface ChunkGeneratorInterface -{ - void initStrongholds(final ServerLevel level); - List getPlacementsForFeatureCM(final ServerLevel level, final Structure structure); -} diff --git a/src/main/java/carpet/fakes/MinecraftServerInterface.java b/src/main/java/carpet/fakes/MinecraftServerInterface.java index f68a18c9fa..8b0454361c 100644 --- a/src/main/java/carpet/fakes/MinecraftServerInterface.java +++ b/src/main/java/carpet/fakes/MinecraftServerInterface.java @@ -3,6 +3,7 @@ import java.util.Map; import java.util.function.BooleanSupplier; +import carpet.script.CarpetScriptServer; import net.minecraft.core.RegistryAccess; import net.minecraft.resources.ResourceKey; //import net.minecraft.server.ServerResources; @@ -19,4 +20,7 @@ public interface MinecraftServerInterface void reloadAfterReload(RegistryAccess newRegs); MinecraftServer.ReloadableResources getResourceManager(); + + void addScriptServer(CarpetScriptServer scriptServer); + CarpetScriptServer getScriptServer(); } diff --git a/src/main/java/carpet/fakes/ServerPlayerEntityInterface.java b/src/main/java/carpet/fakes/ServerPlayerInterface.java similarity index 83% rename from src/main/java/carpet/fakes/ServerPlayerEntityInterface.java rename to src/main/java/carpet/fakes/ServerPlayerInterface.java index 173081b114..06fea590e6 100644 --- a/src/main/java/carpet/fakes/ServerPlayerEntityInterface.java +++ b/src/main/java/carpet/fakes/ServerPlayerInterface.java @@ -2,7 +2,7 @@ import carpet.helpers.EntityPlayerActionPack; -public interface ServerPlayerEntityInterface +public interface ServerPlayerInterface { EntityPlayerActionPack getActionPack(); void invalidateEntityObjectReference(); diff --git a/src/main/java/carpet/helpers/EntityPlayerActionPack.java b/src/main/java/carpet/helpers/EntityPlayerActionPack.java index 788b58aff4..4e71cf1240 100644 --- a/src/main/java/carpet/helpers/EntityPlayerActionPack.java +++ b/src/main/java/carpet/helpers/EntityPlayerActionPack.java @@ -1,10 +1,12 @@ package carpet.helpers; -import carpet.fakes.ServerPlayerEntityInterface; +import carpet.fakes.ServerPlayerInterface; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; + +import carpet.script.utils.Tracer; import net.minecraft.commands.arguments.EntityAnchorArgument; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -289,7 +291,7 @@ public enum ActionType @Override boolean execute(ServerPlayer player, Action action) { - EntityPlayerActionPack ap = ((ServerPlayerEntityInterface) player).getActionPack(); + EntityPlayerActionPack ap = ((ServerPlayerInterface) player).getActionPack(); if (ap.itemUseCooldown > 0) { ap.itemUseCooldown--; @@ -358,7 +360,7 @@ boolean execute(ServerPlayer player, Action action) @Override void inactiveTick(ServerPlayer player, Action action) { - EntityPlayerActionPack ap = ((ServerPlayerEntityInterface) player).getActionPack(); + EntityPlayerActionPack ap = ((ServerPlayerInterface) player).getActionPack(); ap.itemUseCooldown = 0; player.releaseUsingItem(); } @@ -380,7 +382,7 @@ boolean execute(ServerPlayer player, Action action) { return true; } case BLOCK: { - EntityPlayerActionPack ap = ((ServerPlayerEntityInterface) player).getActionPack(); + EntityPlayerActionPack ap = ((ServerPlayerInterface) player).getActionPack(); if (ap.blockHitDelay > 0) { ap.blockHitDelay--; @@ -451,7 +453,7 @@ else if (ap.currentBlock == null || !ap.currentBlock.equals(pos)) @Override void inactiveTick(ServerPlayer player, Action action) { - EntityPlayerActionPack ap = ((ServerPlayerEntityInterface) player).getActionPack(); + EntityPlayerActionPack ap = ((ServerPlayerInterface) player).getActionPack(); if (ap.currentBlock == null) return; player.level.destroyBlockProgress(-1, ap.currentBlock, -1); player.gameMode.handleBlockBreakAction(ap.currentBlock, ServerboundPlayerActionPacket.Action.ABORT_DESTROY_BLOCK, Direction.DOWN, player.getLevel().getMaxBuildHeight(), -1); diff --git a/src/main/java/carpet/helpers/ParticleDisplay.java b/src/main/java/carpet/helpers/ParticleDisplay.java index 086a8c2381..5335f0b240 100644 --- a/src/main/java/carpet/helpers/ParticleDisplay.java +++ b/src/main/java/carpet/helpers/ParticleDisplay.java @@ -1,10 +1,6 @@ package carpet.helpers; -import com.mojang.brigadier.StringReader; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import java.util.HashMap; -import java.util.Map; -import net.minecraft.commands.arguments.ParticleArgument; +import carpet.script.utils.ParticleParser; import net.minecraft.core.HolderLookup; import net.minecraft.core.particles.ParticleOptions; import net.minecraft.core.particles.ParticleType; @@ -14,34 +10,11 @@ public class ParticleDisplay { - private static final Map particleCache = new HashMap<>(); // we reset this on reloads, but probably need something better - - private static ParticleOptions parseParticle(String name, HolderLookup> lookup) - { - try - { - return ParticleArgument.readParticle(new StringReader(name), lookup); - } - catch (CommandSyntaxException e) - { - throw new IllegalArgumentException("No such particle: " + name); - } - } - public static ParticleOptions getEffect(String name, HolderLookup> lookup) - { - if (name == null) return null; - return particleCache.computeIfAbsent(name, particle -> parseParticle(particle, lookup)); - } - - public static void resetCache() { - particleCache.clear(); - } - public static void drawParticleLine(ServerPlayer player, Vec3 from, Vec3 to, String main, String accent, int count, double spread) { HolderLookup> lookup = player.getLevel().holderLookup(Registries.PARTICLE_TYPE); - ParticleOptions accentParticle = getEffect(accent, lookup); - ParticleOptions mainParticle = getEffect(main, lookup); + ParticleOptions accentParticle = ParticleParser.getEffect(accent, lookup); + ParticleOptions mainParticle = ParticleParser.getEffect(main, lookup); if (accentParticle != null) player.getLevel().sendParticles( player, diff --git a/src/main/java/carpet/mixins/AbstractContainerMenuSubclasses_scarpetMixin.java b/src/main/java/carpet/mixins/AbstractContainerMenuSubclasses_scarpetMixin.java index c164a227c8..1b72742f42 100644 --- a/src/main/java/carpet/mixins/AbstractContainerMenuSubclasses_scarpetMixin.java +++ b/src/main/java/carpet/mixins/AbstractContainerMenuSubclasses_scarpetMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.fakes.ScreenHandlerInterface; +import carpet.fakes.AbstractContainerMenuInterface; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.EnchantmentMenu; @@ -23,7 +23,7 @@ protected AbstractContainerMenuSubclasses_scarpetMixin(MenuType type, int syn @Inject(method = "clickMenuButton", at = @At("HEAD"), cancellable = true) private void buttonClickCallback(Player player, int id, CallbackInfoReturnable cir) { - if(((ScreenHandlerInterface) this).callButtonClickListener(id,player)) + if(((AbstractContainerMenuInterface) this).callButtonClickListener(id,player)) cir.cancel(); } } diff --git a/src/main/java/carpet/mixins/AbstractContainerMenu_scarpetMixin.java b/src/main/java/carpet/mixins/AbstractContainerMenu_scarpetMixin.java index 3cc06d7b2f..3f3fe6ce53 100644 --- a/src/main/java/carpet/mixins/AbstractContainerMenu_scarpetMixin.java +++ b/src/main/java/carpet/mixins/AbstractContainerMenu_scarpetMixin.java @@ -1,7 +1,6 @@ package carpet.mixins; - -import carpet.fakes.ScreenHandlerInterface; +import carpet.fakes.AbstractContainerMenuInterface; import carpet.script.value.ScreenValue; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -20,7 +19,7 @@ import net.minecraft.world.item.crafting.Recipe; @Mixin(AbstractContainerMenu.class) -public abstract class AbstractContainerMenu_scarpetMixin implements ScreenHandlerInterface +public abstract class AbstractContainerMenu_scarpetMixin implements AbstractContainerMenuInterface { @Shadow @Final private List containerListeners; @Shadow public abstract void sendAllDataToRemote(); @@ -73,7 +72,7 @@ public boolean callSelectRecipeListener(ServerPlayer player, Recipe recipe, b } @Override - public DataSlot getProperty(int index) { + public DataSlot getDataSlot(int index) { return this.dataSlots.get(index); } } \ No newline at end of file diff --git a/src/main/java/carpet/mixins/ChunkGenerator_scarpetMixin.java b/src/main/java/carpet/mixins/ChunkGenerator_scarpetMixin.java deleted file mode 100644 index a923c80060..0000000000 --- a/src/main/java/carpet/mixins/ChunkGenerator_scarpetMixin.java +++ /dev/null @@ -1,26 +0,0 @@ -package carpet.mixins; - -import carpet.fakes.ChunkGeneratorInterface; -import net.minecraft.core.Holder; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.level.chunk.ChunkGenerator; -import net.minecraft.world.level.levelgen.structure.Structure; -import net.minecraft.world.level.levelgen.structure.placement.StructurePlacement; -import org.spongepowered.asm.mixin.Mixin; - -import java.util.List; - -@Mixin(ChunkGenerator.class) -public abstract class ChunkGenerator_scarpetMixin implements ChunkGeneratorInterface -{ - @Override - public void initStrongholds(final ServerLevel level) - { - level.getChunkSource().getGeneratorState().ensureStructuresGenerated(); - } - - @Override - public List getPlacementsForFeatureCM(final ServerLevel level, Structure structure) { - return level.getChunkSource().getGeneratorState().getPlacementsForStructure(Holder.direct(structure)); - } -} diff --git a/src/main/java/carpet/mixins/EntityMixin.java b/src/main/java/carpet/mixins/EntityMixin.java index fca20d322c..03cfd2c7df 100644 --- a/src/main/java/carpet/mixins/EntityMixin.java +++ b/src/main/java/carpet/mixins/EntityMixin.java @@ -25,6 +25,7 @@ public abstract class EntityMixin implements EntityInterface @Shadow public Level level; + @Override public float getMainYaw(float partialTicks) { return partialTicks == 1.0F ? this.yRot : Mth.lerp(partialTicks, this.yRotO, this.yRot); diff --git a/src/main/java/carpet/mixins/Ingredient_scarpetMixin.java b/src/main/java/carpet/mixins/Ingredient_scarpetMixin.java index 79a103918f..4d33697e80 100644 --- a/src/main/java/carpet/mixins/Ingredient_scarpetMixin.java +++ b/src/main/java/carpet/mixins/Ingredient_scarpetMixin.java @@ -8,7 +8,6 @@ import java.util.Arrays; import java.util.Collection; import java.util.List; -import java.util.stream.Collectors; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; @@ -20,7 +19,6 @@ public class Ingredient_scarpetMixin implements IngredientInterface @Override public List> getRecipeStacks() { - List> res = Arrays.stream(values).map(Ingredient.Value::getItems).collect(Collectors.toList()); - return res; + return Arrays.stream(values).map(Ingredient.Value::getItems).toList(); } } diff --git a/src/main/java/carpet/mixins/MinecraftServer_scarpetMixin.java b/src/main/java/carpet/mixins/MinecraftServer_scarpetMixin.java index 8848fa9925..27591cbb45 100644 --- a/src/main/java/carpet/mixins/MinecraftServer_scarpetMixin.java +++ b/src/main/java/carpet/mixins/MinecraftServer_scarpetMixin.java @@ -2,6 +2,7 @@ import carpet.fakes.MinecraftServerInterface; import carpet.helpers.TickSpeed; +import carpet.script.CarpetScriptServer; import net.minecraft.Util; import net.minecraft.core.RegistryAccess; import net.minecraft.resources.ResourceKey; @@ -31,6 +32,8 @@ @Mixin(MinecraftServer.class) public abstract class MinecraftServer_scarpetMixin extends ReentrantBlockableEventLoop implements MinecraftServerInterface { + private CarpetScriptServer scriptServer; + public MinecraftServer_scarpetMixin(String string_1) { super(string_1); @@ -74,11 +77,6 @@ public LevelStorageSource.LevelStorageAccess getCMSession() return storageSource; } - //@Override - //public ServerResources getResourceManager() { - // return resources; - //} - @Override public Map, ServerLevel> getCMWorlds() { @@ -93,9 +91,9 @@ public void tickTasks(BooleanSupplier booleanSupplier_1, CallbackInfo ci) { if (!TickSpeed.process_entities) return; - TICK.onTick(); - NETHER_TICK.onTick(); - ENDER_TICK.onTick(); + TICK.onTick((MinecraftServer) (Object) this); + NETHER_TICK.onTick((MinecraftServer) (Object) this); + ENDER_TICK.onTick((MinecraftServer) (Object) this); } @Override @@ -113,4 +111,16 @@ public MinecraftServer.ReloadableResources getResourceManager() { return resources; } + + @Override + public void addScriptServer(final CarpetScriptServer scriptServer) + { + this.scriptServer = scriptServer; + } + + @Override + public CarpetScriptServer getScriptServer() + { + return scriptServer; + } } diff --git a/src/main/java/carpet/mixins/PlayerList_scarpetEventsMixin.java b/src/main/java/carpet/mixins/PlayerList_scarpetEventsMixin.java index cacfb50c7b..5ca7afb479 100644 --- a/src/main/java/carpet/mixins/PlayerList_scarpetEventsMixin.java +++ b/src/main/java/carpet/mixins/PlayerList_scarpetEventsMixin.java @@ -1,7 +1,7 @@ package carpet.mixins; import carpet.CarpetServer; -import carpet.fakes.ServerPlayerEntityInterface; +import carpet.fakes.ServerPlayerInterface; import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.players.PlayerList; import org.spongepowered.asm.mixin.Mixin; @@ -27,7 +27,7 @@ private void onRespawn(ServerPlayer player, boolean olive, CallbackInfoReturnabl )) private void invalidatePreviousInstance(ServerPlayer player, boolean alive, CallbackInfoReturnable cir) { - ((ServerPlayerEntityInterface)player).invalidateEntityObjectReference(); + ((ServerPlayerInterface)player).invalidateEntityObjectReference(); } @Inject(method = "reloadResources", at = @At("HEAD")) diff --git a/src/main/java/carpet/mixins/RecipeBookMenu_scarpetMixin.java b/src/main/java/carpet/mixins/RecipeBookMenu_scarpetMixin.java index d9b291bb38..c13ba04724 100644 --- a/src/main/java/carpet/mixins/RecipeBookMenu_scarpetMixin.java +++ b/src/main/java/carpet/mixins/RecipeBookMenu_scarpetMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.fakes.ScreenHandlerInterface; +import carpet.fakes.AbstractContainerMenuInterface; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.inventory.RecipeBookMenu; import net.minecraft.world.item.crafting.Recipe; @@ -13,7 +13,7 @@ public class RecipeBookMenu_scarpetMixin { @Inject(method = "handlePlacement",at = @At("HEAD"), cancellable = true) private void selectRecipeCallback(boolean craftAll, Recipe recipe, ServerPlayer player, CallbackInfo ci) { - if(((ScreenHandlerInterface) this).callSelectRecipeListener(player,recipe,craftAll)) + if(((AbstractContainerMenuInterface) this).callSelectRecipeListener(player,recipe,craftAll)) ci.cancel(); } } diff --git a/src/main/java/carpet/mixins/ServerLevel_scarpetMixin.java b/src/main/java/carpet/mixins/ServerLevel_scarpetMixin.java index 7bde2865d4..9ace41bbc2 100644 --- a/src/main/java/carpet/mixins/ServerLevel_scarpetMixin.java +++ b/src/main/java/carpet/mixins/ServerLevel_scarpetMixin.java @@ -92,6 +92,7 @@ private void handleChunkUnload(LevelChunk levelChunk, CallbackInfo ci) private ServerLevelData serverLevelData; @Shadow @Final private PersistentEntitySectionManager entityManager; + @Override public ServerLevelData getWorldPropertiesCM(){ return serverLevelData; } diff --git a/src/main/java/carpet/mixins/ServerPlayer_actionPackMixin.java b/src/main/java/carpet/mixins/ServerPlayer_actionPackMixin.java index e49cff0117..6eda0884df 100644 --- a/src/main/java/carpet/mixins/ServerPlayer_actionPackMixin.java +++ b/src/main/java/carpet/mixins/ServerPlayer_actionPackMixin.java @@ -1,9 +1,8 @@ package carpet.mixins; -import carpet.fakes.ServerPlayerEntityInterface; +import carpet.fakes.ServerPlayerInterface; import carpet.helpers.EntityPlayerActionPack; import com.mojang.authlib.GameProfile; -import net.minecraft.network.chat.RemoteChatSession; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; @@ -14,7 +13,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(ServerPlayer.class) -public abstract class ServerPlayer_actionPackMixin implements ServerPlayerEntityInterface +public abstract class ServerPlayer_actionPackMixin implements ServerPlayerInterface { @Unique public EntityPlayerActionPack actionPack; diff --git a/src/main/java/carpet/mixins/ServerPlayer_scarpetEventMixin.java b/src/main/java/carpet/mixins/ServerPlayer_scarpetEventMixin.java index ac66c14e1c..a1a76b0ac1 100644 --- a/src/main/java/carpet/mixins/ServerPlayer_scarpetEventMixin.java +++ b/src/main/java/carpet/mixins/ServerPlayer_scarpetEventMixin.java @@ -1,7 +1,7 @@ package carpet.mixins; import carpet.fakes.EntityInterface; -import carpet.fakes.ServerPlayerEntityInterface; +import carpet.fakes.ServerPlayerInterface; import carpet.script.EntityEventsGroup; import com.mojang.authlib.GameProfile; import net.minecraft.core.BlockPos; @@ -31,7 +31,7 @@ import static carpet.script.CarpetEventServer.Event.STATISTICS; @Mixin(ServerPlayer.class) -public abstract class ServerPlayer_scarpetEventMixin extends Player implements ServerPlayerEntityInterface +public abstract class ServerPlayer_scarpetEventMixin extends Player implements ServerPlayerInterface { // to denote if the player reference is valid diff --git a/src/main/java/carpet/patches/EntityPlayerMPFake.java b/src/main/java/carpet/patches/EntityPlayerMPFake.java index 3872bd889b..2401d14786 100644 --- a/src/main/java/carpet/patches/EntityPlayerMPFake.java +++ b/src/main/java/carpet/patches/EntityPlayerMPFake.java @@ -23,7 +23,7 @@ import net.minecraft.world.level.GameType; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.SkullBlockEntity; -import carpet.fakes.ServerPlayerEntityInterface; +import carpet.fakes.ServerPlayerInterface; import carpet.utils.Messenger; import java.util.concurrent.atomic.AtomicReference; @@ -90,7 +90,7 @@ public static EntityPlayerMPFake createShadow(MinecraftServer server, ServerPlay playerShadow.setHealth(player.getHealth()); playerShadow.connection.teleport(player.getX(), player.getY(), player.getZ(), player.getYRot(), player.getXRot()); playerShadow.gameMode.changeGameModeForPlayer(player.gameMode.getGameModeForPlayer()); - ((ServerPlayerEntityInterface) playerShadow).getActionPack().copyFrom(((ServerPlayerEntityInterface) player).getActionPack()); + ((ServerPlayerInterface) playerShadow).getActionPack().copyFrom(((ServerPlayerInterface) player).getActionPack()); playerShadow.maxUpStep = 0.6F; playerShadow.entityData.set(DATA_PLAYER_MODE_CUSTOMISATION, player.getEntityData().get(DATA_PLAYER_MODE_CUSTOMISATION)); diff --git a/src/main/java/carpet/script/CarpetEventServer.java b/src/main/java/carpet/script/CarpetEventServer.java index 96a198778c..1867dc7628 100644 --- a/src/main/java/carpet/script/CarpetEventServer.java +++ b/src/main/java/carpet/script/CarpetEventServer.java @@ -1,13 +1,10 @@ package carpet.script; -import carpet.CarpetServer; -import carpet.CarpetSettings; -import carpet.api.settings.CarpetRule; -import carpet.api.settings.RuleHelper; -import carpet.helpers.TickSpeed; import carpet.script.exception.IntegrityException; import carpet.script.exception.InternalExpressionException; import carpet.script.exception.InvalidCallbackException; +import carpet.script.external.Carpet; +import carpet.script.external.Vanilla; import carpet.script.utils.GlocalFlag; import carpet.script.value.BlockValue; import carpet.script.value.BooleanValue; @@ -19,8 +16,6 @@ import carpet.script.value.StringValue; import carpet.script.value.Value; import carpet.script.value.ValueConversions; -import carpet.utils.CarpetProfiler; -import carpet.utils.Messenger; import com.mojang.brigadier.exceptions.CommandSyntaxException; import java.util.ArrayList; @@ -51,6 +46,7 @@ import net.minecraft.core.registries.Registries; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.stats.Stat; @@ -93,13 +89,15 @@ public static class Callback public final String optionalTarget; public final FunctionValue function; public final List parametrizedArgs; + public final CarpetScriptServer scriptServer; - public Callback(final String host, final String target, final FunctionValue function, final List parametrizedArgs) + public Callback(final String host, final String target, final FunctionValue function, final List parametrizedArgs, final CarpetScriptServer scriptServer) { this.host = host; this.function = function; this.optionalTarget = target; this.parametrizedArgs = parametrizedArgs == null ? NOARGS : parametrizedArgs; + this.scriptServer = scriptServer; } /** @@ -115,12 +113,12 @@ public CallbackResult execute(final CommandSourceStack sender, List runti runtimeArgs = new ArrayList<>(runtimeArgs); runtimeArgs.addAll(this.parametrizedArgs); } - if (CarpetServer.scriptServer == null) + if (scriptServer.stopAll) { return CallbackResult.FAIL; // already stopped } - return CarpetServer.scriptServer.events.runEventCall( - sender.withPermission(CarpetSettings.runPermissionLevel), + return scriptServer.events.runEventCall( + sender.withPermission(Vanilla.MinecraftServer_getRunPermissionLevel(sender.getServer())), host, optionalTarget, function, runtimeArgs); } @@ -169,7 +167,7 @@ public static class ScheduledCall extends Callback public ScheduledCall(final CarpetContext context, final FunctionValue function, final List args, final long dueTime) { // ignoring target as we will be always calling self - super(context.host.getName(), null, function, args); + super(context.host.getName(), null, function, args, (CarpetScriptServer) context.scriptServer()); this.ctx = context.duplicate(); this.dueTime = dueTime; } @@ -179,7 +177,7 @@ public ScheduledCall(final CarpetContext context, final FunctionValue function, */ public void execute() { - CarpetServer.scriptServer.events.runScheduledCall(ctx.origin(), ctx.source(), host, (CarpetScriptHost) ctx.host, function, parametrizedArgs); + scriptServer.events.runScheduledCall(ctx.origin(), ctx.source(), host, (CarpetScriptHost) ctx.host, function, parametrizedArgs); } } @@ -237,64 +235,69 @@ private void removeCallsIf(final Predicate when) */ public boolean call(final Supplier> argumentSupplier, final Supplier cmdSourceSupplier) { - if (!callList.isEmpty() && CarpetServer.scriptServer != null) + if (callList.isEmpty()) { - final Boolean isCancelled = CarpetServer.scriptServer.events.handleEvents.runIfEnabled(() -> { - final CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet events", CarpetProfiler.TYPE.GENERAL); - final List argv = argumentSupplier.get(); // empty for onTickDone - final CommandSourceStack source; - try - { - source = cmdSourceSupplier.get(); - } - catch (final NullPointerException noReference) // todo figure out what happens when closing. - { - return false; - } - final String nameCheck = perPlayerDistribution ? source.getTextName() : null; - assert argv.size() == reqArgs; - boolean cancelled = false; - try + return false; + } + final CommandSourceStack source; + try + { + source = cmdSourceSupplier.get(); + } + catch (final NullPointerException noReference) // todo figure out what happens when closing. + { + return false; + } + final CarpetScriptServer scriptServer = Vanilla.MinecraftServer_getScriptServer(source.getServer()); + if (scriptServer.stopAll) + { + return false; + } + final Boolean isCancelled = scriptServer.events.handleEvents.runIfEnabled(() -> { + final Runnable profilerToken = Carpet.startProfilerSection("Scarpet events"); + final List argv = argumentSupplier.get(); // empty for onTickDone + final String nameCheck = perPlayerDistribution ? source.getTextName() : null; + assert argv.size() == reqArgs; + boolean cancelled = false; + try + { + // we are ok with list growing in the meantime + // which might happen during inCall or inSignal + inCall = true; + for (int i = 0; i < callList.size(); i++) { - // we are ok with list growing in the meantime - // which might happen during inCall or inSignal - inCall = true; - for (int i = 0; i < callList.size(); i++) + final Callback call = callList.get(i); + // supressing calls where target player hosts simply don't match + // handling global hosts with player targets is left to when the host is resolved (few calls deeper). + if (nameCheck != null && call.optionalTarget != null && !nameCheck.equals(call.optionalTarget)) { - final Callback call = callList.get(i); - // supressing calls where target player hosts simply don't match - // handling global hosts with player targets is left to when the host is resolved (few calls deeper). - if (nameCheck != null && call.optionalTarget != null && !nameCheck.equals(call.optionalTarget)) - { - continue; - } - final CallbackResult result = call.execute(source, argv); - if (result == CallbackResult.CANCEL) - { - cancelled = true; - break; - } - if (result == CallbackResult.FAIL) - { - removedCalls.add(call); - } + continue; + } + final CallbackResult result = call.execute(source, argv); + if (result == CallbackResult.CANCEL) + { + cancelled = true; + break; + } + if (result == CallbackResult.FAIL) + { + removedCalls.add(call); } } - finally - { - inCall = false; - } - for (final Callback call : removedCalls) - { - callList.remove(call); - } - removedCalls.clear(); - CarpetProfiler.end_current_section(currentSection); - return cancelled; - }); - return isCancelled != null && isCancelled; - } - return false; + } + finally + { + inCall = false; + } + for (final Callback call : removedCalls) + { + callList.remove(call); + } + removedCalls.clear(); + profilerToken.run(); + return cancelled; + }); + return isCancelled != null && isCancelled; } public int signal(final CommandSourceStack sender, final ServerPlayer optinoalReceipient, final List callArg) @@ -323,13 +326,13 @@ public int signal(final CommandSourceStack sender, final ServerPlayer optinoalRe return successes; } - public boolean addFromExternal(final CommandSourceStack source, final String hostName, final String funName, final Consumer hostOnEventHandler) + public boolean addFromExternal(final CommandSourceStack source, final String hostName, final String funName, final Consumer hostOnEventHandler, final CarpetScriptServer scriptServer) { - final ScriptHost host = CarpetServer.scriptServer.getAppHostByName(hostName); + final ScriptHost host = scriptServer.getAppHostByName(hostName); if (host == null) { // impossible call to add - Messenger.m(source, "r Unknown app " + hostName); + Carpet.Messenger_message(source, "r Unknown app " + hostName); return false; } hostOnEventHandler.accept(host); @@ -337,7 +340,7 @@ public boolean addFromExternal(final CommandSourceStack source, final String hos if (udf == null || udf.getArguments().size() != reqArgs) { // call won't match arguments - Messenger.m(source, "r Callback doesn't expect required number of arguments: " + reqArgs); + Carpet.Messenger_message(source, "r Callback doesn't expect required number of arguments: " + reqArgs); return false; } String target = null; @@ -349,7 +352,7 @@ public boolean addFromExternal(final CommandSourceStack source, final String hos } catch (final CommandSyntaxException e) { - Messenger.m(source, "r Cannot add event to a player scoped app from a command without a player context"); + Carpet.Messenger_message(source, "r Cannot add event to a player scoped app from a command without a player context"); return false; } } @@ -357,7 +360,7 @@ public boolean addFromExternal(final CommandSourceStack source, final String hos //remove duplicates removeEventCall(hostName, target, udf.getString()); - callList.add(new Callback(hostName, target, udf, null)); + callList.add(new Callback(hostName, target, udf, null, scriptServer)); return true; } @@ -369,7 +372,7 @@ public boolean addEventCallInternal(final ScriptHost host, final FunctionValue f } //removing duplicates removeEventCall(host.getName(), host.user, function.getString()); - callList.add(new Callback(host.getName(), host.user, function, args)); + callList.add(new Callback(host.getName(), host.user, function, args, (CarpetScriptServer) host.scriptServer())); return true; } @@ -392,10 +395,10 @@ public void createChildEvents(final CarpetScriptHost host) final List copyCalls = new ArrayList<>(); callList.forEach((c) -> { - if ((Objects.equals(c.host, host.getName())) + if ((Objects.equals(c.host, host.getName())) // TODO fix me && c.optionalTarget == null) { - copyCalls.add(new Callback(c.host, host.user, c.function, c.parametrizedArgs)); + copyCalls.add(new Callback(c.host, host.user, c.function, c.parametrizedArgs, host.scriptServer())); } }); callList.addAll(copyCalls); @@ -434,11 +437,10 @@ public static List publicEvents(final CarpetScriptServer server) public static final Event START = new Event("server_starts", 0, true) { @Override - public void onTick() + public void onTick(final MinecraftServer server) { handler.call(Collections::emptyList, () -> - CarpetServer.minecraft_server.createCommandSourceStack(). - withLevel(CarpetServer.minecraft_server.getLevel(Level.OVERWORLD)) + server.createCommandSourceStack().withLevel(server.getLevel(Level.OVERWORLD)) ); } }; @@ -446,11 +448,10 @@ public void onTick() public static final Event SHUTDOWN = new Event("server_shuts_down", 0, true) { @Override - public void onTick() + public void onTick(final MinecraftServer server) { handler.call(Collections::emptyList, () -> - CarpetServer.minecraft_server.createCommandSourceStack(). - withLevel(CarpetServer.minecraft_server.getLevel(Level.OVERWORLD)) + server.createCommandSourceStack().withLevel(server.getLevel(Level.OVERWORLD)) ); } }; @@ -458,11 +459,10 @@ public void onTick() public static final Event TICK = new Event("tick", 0, true) { @Override - public void onTick() + public void onTick(final MinecraftServer server) { handler.call(Collections::emptyList, () -> - CarpetServer.minecraft_server.createCommandSourceStack(). - withLevel(CarpetServer.minecraft_server.getLevel(Level.OVERWORLD)) + server.createCommandSourceStack().withLevel(server.getLevel(Level.OVERWORLD)) ); } }; @@ -475,11 +475,11 @@ public boolean deprecated() } @Override - public void onTick() + public void onTick(final MinecraftServer server) { handler.call(Collections::emptyList, () -> - CarpetServer.minecraft_server.createCommandSourceStack(). - withLevel(CarpetServer.minecraft_server.getLevel(Level.NETHER)) + server.createCommandSourceStack(). + withLevel(server.getLevel(Level.NETHER)) ); } }; @@ -492,11 +492,11 @@ public boolean deprecated() } @Override - public void onTick() + public void onTick(final MinecraftServer server) { handler.call(Collections::emptyList, () -> - CarpetServer.minecraft_server.createCommandSourceStack(). - withLevel(CarpetServer.minecraft_server.getLevel(Level.END)) + server.createCommandSourceStack(). + withLevel(server.getLevel(Level.END)) ); } }; @@ -507,7 +507,7 @@ public void onChunkEvent(final ServerLevel world, final ChunkPos chPos, final bo { handler.call( () -> Arrays.asList(new NumericValue(chPos.x << 4), new NumericValue(chPos.z << 4)), - () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel(world) + () -> world.getServer().createCommandSourceStack().withLevel(world) ); } }; @@ -518,7 +518,7 @@ public void onChunkEvent(final ServerLevel world, final ChunkPos chPos, final bo { handler.call( () -> Arrays.asList(new NumericValue(chPos.x << 4), new NumericValue(chPos.z << 4)), - () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel(world) + () -> world.getServer().createCommandSourceStack().withLevel(world) ); } }; @@ -530,7 +530,7 @@ public void onChunkEvent(final ServerLevel world, final ChunkPos chPos, final bo { handler.call( () -> Arrays.asList(new NumericValue(chPos.x << 4), new NumericValue(chPos.z << 4)), - () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel(world) + () -> world.getServer().createCommandSourceStack().withLevel(world) ); } }; @@ -714,7 +714,7 @@ public void onTrade(final ServerPlayer player, final Merchant merchant, final Me final RegistryAccess regs = player.getLevel().registryAccess(); handler.call(() -> Arrays.asList( new EntityValue(player), - merchant instanceof final AbstractVillager villager? new EntityValue(villager) : Value.NULL, + merchant instanceof final AbstractVillager villager ? new EntityValue(villager) : Value.NULL, ValueConversions.of(tradeOffer.getBaseCostA(), regs), ValueConversions.of(tradeOffer.getCostB(), regs), ValueConversions.of(tradeOffer.getResult(), regs) @@ -1015,30 +1015,7 @@ public void onWorldEventFlag(final ServerLevel world, final BlockPos pos, final () -> Arrays.asList( new BlockValue(null, world, pos), flag > 0 ? Value.TRUE : Value.FALSE - ), () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel(world) - ); - } - }; - public static final Event CARPET_RULE_CHANGES = new Event("carpet_rule_changes", 2, true) - { - @Override - public void onCarpetRuleChanges(final CarpetRule rule, final CommandSourceStack source) - { - final String identifier = rule.settingsManager().identifier(); - final String namespace; - if (!identifier.equals("carpet")) - { - namespace = identifier + ":"; - } - else - { - namespace = ""; - } - handler.call( - () -> Arrays.asList( - new StringValue(namespace + rule.name()), - new StringValue(RuleHelper.toRuleString(rule.value())) - ), () -> source + ), () -> world.getServer().createCommandSourceStack().withLevel(world) ); } }; @@ -1086,7 +1063,7 @@ public void onExplosion(final ServerLevel world, final Entity e, final Supplier< b -> new BlockValue(world.getBlockState(b), world, b) )), ListValue.wrap(affectedEntities.stream().map(EntityValue::of)) - ), () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel(world) + ), () -> world.getServer().createCommandSourceStack().withLevel(world) ); } }; @@ -1105,7 +1082,7 @@ public void onExplosion(final ServerLevel world, final Entity e, final Supplier< EntityValue.of(attacker != null ? attacker.get() : Event.getExplosionCausingEntity(e)), StringValue.of(type.name().toLowerCase(Locale.ROOT)), BooleanValue.of(createFire) - ), () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel(world) + ), () -> world.getServer().createCommandSourceStack().withLevel(world) ); } }; @@ -1126,7 +1103,7 @@ public void onEntityAction(final Entity entity, final boolean created) { handler.call( () -> Collections.singletonList(new EntityValue(entity)), - () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel((ServerLevel) entity.level).withPermission(CarpetSettings.runPermissionLevel) + () -> entity.getServer().createCommandSourceStack().withLevel((ServerLevel) entity.level).withPermission(Vanilla.MinecraftServer_getRunPermissionLevel(entity.getServer())) ); } })).collect(Collectors.toUnmodifiableMap(Map.Entry::getKey, Map.Entry::getValue)); @@ -1145,7 +1122,7 @@ public void onEntityAction(final Entity entity, final boolean created) { handler.call( () -> Arrays.asList(new EntityValue(entity), BooleanValue.of(created)), - () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel((ServerLevel) entity.level).withPermission(CarpetSettings.runPermissionLevel) + () -> entity.getServer().createCommandSourceStack().withLevel((ServerLevel) entity.level).withPermission(Vanilla.MinecraftServer_getRunPermissionLevel(entity.getServer())) ); } })) @@ -1241,7 +1218,7 @@ public boolean deprecated() } //stubs for calls just to ease calls in vanilla code so they don't need to deal with scarpet value types - public void onTick() + public void onTick(final MinecraftServer server) { } @@ -1339,7 +1316,7 @@ public void onWorldEventFlag(final ServerLevel world, final BlockPos pos, final { } - public void onCarpetRuleChanges(final CarpetRule rule, final CommandSourceStack source) + public void handleAny(final Object... args) { } @@ -1376,7 +1353,7 @@ public void onCustomWorldEvent(final ServerLevel world, final Object... args) valArgs.add(ValueConversions.guess(world, o)); } return valArgs; - }, () -> CarpetServer.minecraft_server.createCommandSourceStack().withLevel(world) + }, () -> world.getServer().createCommandSourceStack().withLevel(world) ); } } @@ -1390,7 +1367,7 @@ public CarpetEventServer(final CarpetScriptServer scriptServer) public void tick() { - if (!TickSpeed.process_entities) + if (Carpet.isTickProcessingPaused()) { return; } @@ -1455,7 +1432,7 @@ public CallbackResult runEventCall(final CommandSourceStack sender, final String return CallbackResult.FAIL; } } - final CommandSourceStack source = sender.withPermission(CarpetSettings.runPermissionLevel); + final CommandSourceStack source = sender.withPermission(Vanilla.MinecraftServer_getRunPermissionLevel(sender.getServer())); final CarpetScriptHost executingHost = appHost.retrieveForExecution(sender, target); if (executingHost == null) { @@ -1463,7 +1440,7 @@ public CallbackResult runEventCall(final CommandSourceStack sender, final String } try { - final Value returnValue = executingHost.callUDF(source.withPermission(CarpetSettings.runPermissionLevel), udf, argv); + final Value returnValue = executingHost.callUDF(source, udf, argv); return returnValue instanceof StringValue && returnValue.getString().equals("cancel") ? CallbackResult.CANCEL : CallbackResult.SUCCESS; } catch (final NullPointerException | InvalidCallbackException | IntegrityException error) @@ -1475,15 +1452,15 @@ public CallbackResult runEventCall(final CommandSourceStack sender, final String public boolean addEventFromCommand(final CommandSourceStack source, final String event, final String host, final String funName) { - final Event ev = Event.getEvent(event, CarpetServer.scriptServer); + final Event ev = Event.getEvent(event, scriptServer); if (ev == null) { return false; } - final boolean added = ev.handler.addFromExternal(source, host, funName, h -> onEventAddedToHost(ev, h)); + final boolean added = ev.handler.addFromExternal(source, host, funName, h -> onEventAddedToHost(ev, h), scriptServer); if (added) { - Messenger.m(source, "gi Added " + funName + " to " + event); + Carpet.Messenger_message(source, "gi Added " + funName + " to " + event); } return added; } @@ -1524,16 +1501,16 @@ private void onEventAddedToHost(final Event event, final ScriptHost host) public boolean removeEventFromCommand(final CommandSourceStack source, final String event, final String funName) { - final Event ev = Event.getEvent(event, CarpetServer.scriptServer); + final Event ev = Event.getEvent(event, scriptServer); if (ev == null) { - Messenger.m(source, "r Unknown event: " + event); + Carpet.Messenger_message(source, "r Unknown event: " + event); return false; } final Callback.Signature call = Callback.fromString(funName); ev.handler.removeEventCall(call.host, call.target, call.function); // could verified if actually removed - Messenger.m(source, "gi Removed event: " + funName + " from " + event); + Carpet.Messenger_message(source, "gi Removed event: " + funName + " from " + event); return true; } diff --git a/src/main/java/carpet/script/CarpetExpression.java b/src/main/java/carpet/script/CarpetExpression.java index ef78a103d5..e35976880b 100644 --- a/src/main/java/carpet/script/CarpetExpression.java +++ b/src/main/java/carpet/script/CarpetExpression.java @@ -1,6 +1,5 @@ package carpet.script; -import carpet.CarpetServer; import carpet.script.annotation.AnnotationParser; import carpet.script.api.Auxiliary; import carpet.script.api.BlockIterators; @@ -12,6 +11,7 @@ import carpet.script.api.WorldAccess; import carpet.script.exception.CarpetExpressionException; import carpet.script.exception.ExpressionException; +import carpet.script.external.Carpet; import carpet.script.value.BlockValue; import carpet.script.value.EntityValue; import carpet.script.value.NumericValue; @@ -58,12 +58,13 @@ public CarpetExpression(final Module module, final String expression, final Comm Scoreboards.apply(this.expr); Monitoring.apply(this.expr); AnnotationParser.apply(this.expr); - CarpetServer.extensions.forEach(e -> e.scarpetApi(this)); + Carpet.handleExtensionsAPI(this); } public boolean fillAndScanCommand(final ScriptHost host, final int x, final int y, final int z) { - if (CarpetServer.scriptServer.stopAll) + CarpetScriptServer scriptServer = (CarpetScriptServer) host.scriptServer(); + if (scriptServer.stopAll) { return false; } @@ -85,7 +86,7 @@ public boolean fillAndScanCommand(final ScriptHost host, final int x, final int final Value playerValue = new EntityValue(e).bindTo("p"); context.with("p", (cc, tt) -> playerValue); } - return CarpetServer.scriptServer.events.handleEvents.getWhileDisabled(() -> this.expr.eval(context).getBoolean()); + return scriptServer.events.handleEvents.getWhileDisabled(() -> this.expr.eval(context).getBoolean()); } catch (final ExpressionException e) { @@ -103,7 +104,8 @@ public boolean fillAndScanCommand(final ScriptHost host, final int x, final int public Value scriptRunCommand(final ScriptHost host, final BlockPos pos) { - if (CarpetServer.scriptServer.stopAll) + CarpetScriptServer scriptServer = (CarpetScriptServer) host.scriptServer(); + if (scriptServer.stopAll) { throw new CarpetExpressionException("SCRIPTING PAUSED (unpause with /script resume)", null); } @@ -124,7 +126,7 @@ public Value scriptRunCommand(final ScriptHost host, final BlockPos pos) final Value playerValue = new EntityValue(e).bindTo("p"); context.with("p", (cc, tt) -> playerValue); } - return CarpetServer.scriptServer.events.handleEvents.getWhileDisabled(() -> this.expr.eval(context)); + return scriptServer.events.handleEvents.getWhileDisabled(() -> this.expr.eval(context)); } catch (final ExpressionException e) { diff --git a/src/main/java/carpet/script/CarpetScriptHost.java b/src/main/java/carpet/script/CarpetScriptHost.java index 64a46da04b..4edf62db42 100644 --- a/src/main/java/carpet/script/CarpetScriptHost.java +++ b/src/main/java/carpet/script/CarpetScriptHost.java @@ -1,7 +1,5 @@ package carpet.script; -import carpet.CarpetServer; -import carpet.CarpetSettings; import carpet.script.api.Auxiliary; import carpet.script.argument.FileArgument; import carpet.script.argument.FunctionArgument; @@ -13,6 +11,8 @@ import carpet.script.exception.InternalExpressionException; import carpet.script.exception.InvalidCallbackException; import carpet.script.exception.LoadException; +import carpet.script.external.Carpet; +import carpet.script.external.Vanilla; import carpet.script.utils.AppStoreManager; import carpet.script.value.EntityValue; import carpet.script.value.FunctionValue; @@ -21,8 +21,6 @@ import carpet.script.value.NumericValue; import carpet.script.value.StringValue; import carpet.script.value.Value; -import carpet.utils.CarpetProfiler; -import carpet.utils.Messenger; import com.google.gson.JsonElement; import com.mojang.brigadier.arguments.StringArgumentType; @@ -144,8 +142,9 @@ public static CarpetScriptHost create(final CarpetScriptServer scriptServer, fin private static int execute(final CommandContext ctx, final String hostName, final FunctionArgument funcSpec, final List paramNames) throws CommandSyntaxException { - final CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet command", CarpetProfiler.TYPE.GENERAL); - final CarpetScriptHost cHost = CarpetServer.scriptServer.modules.get(hostName).retrieveOwnForExecution(ctx.getSource()); + final Runnable token = Carpet.startProfilerSection("Scarpet command"); + final CarpetScriptServer scriptServer = Vanilla.MinecraftServer_getScriptServer(ctx.getSource().getServer()); + final CarpetScriptHost cHost = scriptServer.modules.get(hostName).retrieveOwnForExecution(ctx.getSource()); final List argNames = funcSpec.function.getArguments(); if ((argNames.size() - funcSpec.args.size()) != paramNames.size()) { @@ -159,7 +158,7 @@ private static int execute(final CommandContext ctx, final S args.addAll(funcSpec.args); final Value response = cHost.handleCommand(ctx.getSource(), funcSpec.function, args); final int intres = (int) response.readInteger(); - CarpetProfiler.end_current_section(currentSection); + token.run(); return intres; } @@ -239,18 +238,18 @@ public Predicate getCommandConfigPermissions() throws Comman return s -> { try { - final CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet command", CarpetProfiler.TYPE.GENERAL); - final CarpetScriptHost cHost = CarpetServer.scriptServer.modules.get(hostName).retrieveOwnForExecution(s); + final Runnable token = Carpet.startProfilerSection("Scarpet command"); + final CarpetScriptHost cHost = scriptServer().modules.get(hostName).retrieveOwnForExecution(s); final Value response = cHost.handleCommand(s, fun, Collections.singletonList( (s.getEntity() instanceof ServerPlayer) ? new EntityValue(s.getEntity()) : Value.NULL) ); final boolean res = response.getBoolean(); - CarpetProfiler.end_current_section(currentSection); + token.run(); return res; } catch (final CommandSyntaxException e) { - Messenger.m(s, "rb Unable to run app command: " + e.getMessage()); + Carpet.Messenger_message(s, "rb Unable to run app command: " + e.getMessage()); return false; } }; @@ -434,14 +433,14 @@ public Boolean addAppCommands(final Consumer notifier) } catch (final CommandSyntaxException e) { - notifier.accept(Messenger.c("r Error when handling of setting up custom argument types: " + e.getMessage())); + notifier.accept(Carpet.Messenger_compose("r Error when handling of setting up custom argument types: " + e.getMessage())); return false; } if (appConfig.get(StringValue.of("commands")) != null) { if (scriptServer().isInvalidCommandRoot(getName())) { - notifier.accept(Messenger.c("g A command with the app's name already exists in vanilla or an installed mod.")); + notifier.accept(Carpet.Messenger_compose("g A command with the app's name already exists in vanilla or an installed mod.")); return null; } try @@ -457,7 +456,7 @@ public Boolean addAppCommands(final Consumer notifier) catch (final CommandSyntaxException cse) { // failed - notifier.accept(Messenger.c("r Failed to build command system: ", cse.getRawMessage())); + notifier.accept(Carpet.Messenger_compose("r Failed to build command system: ", cse.getRawMessage())); return null; } @@ -512,7 +511,7 @@ private Boolean addLegacyCommand(final Consumer notifier) if (scriptServer().isInvalidCommandRoot(getName())) { - notifier.accept(Messenger.c("g A command with the app's name already exists in vanilla or an installed mod.")); + notifier.accept(Carpet.Messenger_compose("g A command with the app's name already exists in vanilla or an installed mod.")); return null; } @@ -523,7 +522,7 @@ private Boolean addLegacyCommand(final Consumer notifier) } catch (final CommandSyntaxException e) { - notifier.accept(Messenger.c("rb " + e.getMessage())); + notifier.accept(Carpet.Messenger_compose("rb " + e.getMessage())); return null; } final String hostName = getName(); @@ -535,7 +534,7 @@ private Boolean addLegacyCommand(final Consumer notifier) final Value response = targetHost.handleCommandLegacy(c.getSource(), "__command", null, ""); if (!response.isNull()) { - Messenger.m(c.getSource(), "gi " + response.getString()); + Carpet.Messenger_message(c.getSource(), "gi " + response.getString()); } return (int) response.readInteger(); }); @@ -570,7 +569,7 @@ private Boolean addLegacyCommand(final Consumer notifier) final Value response = targetHost.handleCommandLegacy(c.getSource(), function, null, ""); if (!response.isNull()) { - Messenger.m(c.getSource(), "gi " + response.getString()); + Carpet.Messenger_message(c.getSource(), "gi " + response.getString()); } return (int) response.readInteger(); }). @@ -580,7 +579,7 @@ private Boolean addLegacyCommand(final Consumer notifier) final Value response = targetHost.handleCommandLegacy(c.getSource(), function, null, StringArgumentType.getString(c, "args...")); if (!response.isNull()) { - Messenger.m(c.getSource(), "gi " + response.getString()); + Carpet.Messenger_message(c.getSource(), "gi " + response.getString()); } return (int) response.readInteger(); }))); @@ -721,9 +720,9 @@ public Value handleCommandLegacy(final CommandSourceStack source, final String c { try { - final CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet command", CarpetProfiler.TYPE.GENERAL); + final Runnable token = Carpet.startProfilerSection("Scarpet command"); final Value res = callLegacy(source, call, coords, arg); - CarpetProfiler.end_current_section(currentSection); + token.run(); return res; } catch (final CarpetExpressionException exc) @@ -764,7 +763,7 @@ public Value handleCommand(final CommandSourceStack source, final FunctionValue public Value callLegacy(final CommandSourceStack source, final String call, final List coords, final String arg) { - if (CarpetServer.scriptServer.stopAll) + if (scriptServer().stopAll) { throw new CarpetExpressionException("SCARPET PAUSED (unpause with /script resume)", null); } @@ -871,7 +870,7 @@ public Value callLegacy(final CommandSourceStack source, final String call, fina public Value call(final CommandSourceStack source, final FunctionValue function, final List argv) { - if (CarpetServer.scriptServer.stopAll) + if (scriptServer().stopAll) { throw new CarpetExpressionException("SCARPET PAUSED (unpause with /script resume)", null); } @@ -909,7 +908,7 @@ public Value callUDF(final CommandSourceStack source, final FunctionValue fun, f public Value callUDF(final BlockPos origin, final CommandSourceStack source, final FunctionValue fun, final List argv) throws InvalidCallbackException, IntegrityException { - if (CarpetServer.scriptServer.stopAll) + if (scriptServer().stopAll) { return Value.NULL; } @@ -987,12 +986,12 @@ public void onClose() private void dumpState() { - Module.saveData(main, globalState); + Module.saveData(main, globalState, this.scriptServer()); } private Tag loadState() { - return Module.getData(main); + return Module.getData(main, this.scriptServer()); } public Tag readFileTag(final FileArgument fdesc) @@ -1061,7 +1060,7 @@ public Stream listFolder(final FileArgument fdesc) public boolean applyActionForResource(final String path, final boolean shared, final Consumer action) { - final FileArgument fdesc = FileArgument.resourceFromPath(path, FileArgument.Reason.CREATE, shared); + final FileArgument fdesc = FileArgument.resourceFromPath(this, path, FileArgument.Reason.CREATE, shared); return fdesc.findPathAndApply(main, action); } @@ -1104,21 +1103,21 @@ public void setChatErrorSnooper(final CommandSourceStack source) { shebang += " at pos " + (token.pos + 1); } - Messenger.m(source, "r " + shebang); + Carpet.Messenger_message(source, "r " + shebang); if (lines.length > 1 && token.lineno > 0) { - Messenger.m(source, withLocals("l", lines[token.lineno - 1], ctx)); + Carpet.Messenger_message(source, withLocals("l", lines[token.lineno - 1], ctx)); } - Messenger.m(source, withLocals("l", lines[token.lineno].substring(0, token.linepos), ctx), "r HERE>> ", + Carpet.Messenger_message(source, withLocals("l", lines[token.lineno].substring(0, token.linepos), ctx), "r HERE>> ", withLocals("l", lines[token.lineno].substring(token.linepos), ctx)); if (lines.length > 1 && token.lineno < lines.length - 1) { - Messenger.m(source, withLocals("l", lines[token.lineno + 1], ctx)); + Carpet.Messenger_message(source, withLocals("l", lines[token.lineno + 1], ctx)); } } else { - Messenger.m(source, "r " + shebang); + Carpet.Messenger_message(source, "r " + shebang); } return new ArrayList<>(); }; @@ -1182,7 +1181,7 @@ private static Component withLocals(String format, final String line, final Cont { stringsToFormat.add(format + line.substring(lastPos)); } - return Messenger.c(stringsToFormat.toArray()); + return Carpet.Messenger_compose(stringsToFormat.toArray()); } @Override @@ -1201,11 +1200,11 @@ public void handleErrorWithStack(final String intro, final Throwable exception) cee.printStack(responsibleSource); } final String message = exception.getMessage(); - Messenger.m(responsibleSource, "r " + intro + ((message == null || message.isEmpty()) ? "" : ": " + message)); + Carpet.Messenger_message(responsibleSource, "r " + intro + ((message == null || message.isEmpty()) ? "" : ": " + message)); } else { - CarpetSettings.LOG.error(intro + ": " + exception.getMessage()); + CarpetScriptServer.LOG.error(intro + ": " + exception.getMessage()); } } @@ -1235,7 +1234,7 @@ public boolean issueDeprecation(final String feature) { if (super.issueDeprecation(feature)) { - Messenger.m(responsibleSource, "rb '" + feature + "' is deprecated and soon will be removed. Please consult the docs for their replacement"); + Carpet.Messenger_message(responsibleSource, "rb '" + feature + "' is deprecated and soon will be removed. Please consult the docs for their replacement"); return true; } return false; diff --git a/src/main/java/carpet/script/CarpetScriptServer.java b/src/main/java/carpet/script/CarpetScriptServer.java index 9ae29a2cb6..ba17d0f266 100644 --- a/src/main/java/carpet/script/CarpetScriptServer.java +++ b/src/main/java/carpet/script/CarpetScriptServer.java @@ -1,7 +1,5 @@ package carpet.script; -import carpet.CarpetSettings; -import carpet.fakes.CommandDispatcherInterface; import carpet.script.annotation.AnnotationParser; import carpet.script.api.Auxiliary; import carpet.script.api.BlockIterators; @@ -9,9 +7,10 @@ import carpet.script.api.Inventories; import carpet.script.api.Scoreboards; import carpet.script.api.WorldAccess; -import carpet.CarpetServer; import carpet.script.exception.ExpressionException; import carpet.script.exception.LoadException; +import carpet.script.external.Carpet; +import carpet.script.external.Vanilla; import carpet.script.language.Arithmetic; import carpet.script.language.ControlFlow; import carpet.script.language.DataStructures; @@ -21,9 +20,6 @@ import carpet.script.language.Threading; import carpet.script.utils.AppStoreManager; import carpet.script.value.FunctionValue; -import carpet.utils.CarpetProfiler; -import carpet.utils.CommandHelper; -import carpet.utils.Messenger; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.tree.CommandNode; @@ -127,21 +123,14 @@ private void init() public void initializeForWorld() { - CarpetServer.settingsManager.initializeScarpetRules(); - CarpetServer.extensions.forEach(e -> { - if (e.extensionSettingsManager() != null) - { - e.extensionSettingsManager().initializeScarpetRules(); - } - }); - if (CarpetSettings.scriptsAutoload) + if (Vanilla.MinecraftServer_doScriptsAutoload(server)) { for (final String moduleName : listAvailableModules(false)) { addScriptHost(server.createCommandSourceStack(), moduleName, null, true, true, false, null); } } - CarpetEventServer.Event.START.onTick(); + CarpetEventServer.Event.START.onTick(server); } public Module getModule(final String name, final boolean allowLibraries) @@ -188,7 +177,7 @@ public Module getModule(final String name, final boolean allowLibraries) } catch (final IOException e) { - CarpetSettings.LOG.error("Exception while loading the app: ", e); + LOG.error("Exception while loading the app: ", e); } for (final Module moduleData : bundledModuleData) { @@ -256,7 +245,7 @@ public List listAvailableModules(final boolean includeBuiltIns) } catch (final IOException e) { - CarpetSettings.LOG.error("Exception while searching for apps: ", e); + LOG.error("Exception while searching for apps: ", e); } return moduleNames; } @@ -269,7 +258,7 @@ public CarpetScriptHost getAppHostByName(final String name) public boolean addScriptHost(final CommandSourceStack source, String name, Predicate commandValidator, final boolean perPlayer, final boolean autoload, final boolean isRuleApp, final AppStoreManager.StoreNode installer) { - final CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet load", CarpetProfiler.TYPE.GENERAL); + final Runnable token = Carpet.startProfilerSection("Scarpet load"); if (commandValidator == null) { commandValidator = p -> true; @@ -289,7 +278,7 @@ public boolean addScriptHost(final CommandSourceStack source, String name, Predi final Module module = isRuleApp ? getRuleModule(name) : getModule(name, false); if (module == null) { - Messenger.m(source, "r Failed to add " + name + " app: App not found"); + Carpet.Messenger_message(source, "r Failed to add " + name + " app: App not found"); return false; } final CarpetScriptHost newHost; @@ -299,7 +288,7 @@ public boolean addScriptHost(final CommandSourceStack source, String name, Predi } catch (final LoadException e) { - Messenger.m(source, "r Failed to add " + name + " app" + (e.getMessage() == null ? "" : ": " + e.getMessage())); + Carpet.Messenger_message(source, "r Failed to add " + name + " app" + (e.getMessage() == null ? "" : ": " + e.getMessage())); return false; } @@ -320,7 +309,7 @@ public boolean addScriptHost(final CommandSourceStack source, String name, Predi final Boolean isCommandAdded = newHost.addAppCommands(s -> { if (!isRuleApp) { - Messenger.m(source, Messenger.c("r Failed to add app '" + finalName + "': ", s)); + Carpet.Messenger_message(source, "r Failed to add app '" + finalName + "': ", s); } }); if (isCommandAdded == null) // error should be dispatched @@ -330,17 +319,17 @@ public boolean addScriptHost(final CommandSourceStack source, String name, Predi } else if (isCommandAdded) { - CommandHelper.notifyPlayersCommandsChanged(server); + Vanilla.MinecraftServer_notifyPlayersCommandsChanged(server); if (!isRuleApp) { - Messenger.m(source, "gi " + name + " app " + action + " with /" + name + " command"); + Carpet.Messenger_message(source, "gi " + name + " app " + action + " with /" + name + " command"); } } else { if (!isRuleApp) { - Messenger.m(source, "gi " + name + " app " + action); + Carpet.Messenger_message(source, "gi " + name + " app " + action); } } @@ -361,9 +350,9 @@ else if (isCommandAdded) newHost.callNow(onStart, Collections.emptyList()); } } - CarpetProfiler.end_current_section(currentSection); + token.run(); final long end = System.nanoTime(); - CarpetSettings.LOG.info("App " + name + " loaded in " + (end - start) / 1000000 + " ms"); + LOG.info("App " + name + " loaded in " + (end - start) / 1000000 + " ms"); return true; } @@ -380,7 +369,7 @@ public boolean removeScriptHost(final CommandSourceStack source, String name, fi { if (notifySource) { - Messenger.m(source, "r No such app found: ", "wb " + name); + Carpet.Messenger_message(source, "r No such app found: ", "wb " + name); } return false; } @@ -390,16 +379,16 @@ public boolean removeScriptHost(final CommandSourceStack source, String name, fi host.onClose(); if (host.hasCommand) { - ((CommandDispatcherInterface) server.getCommands().getDispatcher()).carpet$unregister(name); + Vanilla.CommandDispatcher_unregisterCommand(server.getCommands().getDispatcher(), name); } if (!isRuleApp) { unloadableModules.remove(name); } - CommandHelper.notifyPlayersCommandsChanged(server); + Vanilla.MinecraftServer_notifyPlayersCommandsChanged(server); if (notifySource) { - Messenger.m(source, "gi Removed " + name + " app"); + Carpet.Messenger_message(source, "gi Removed " + name + " app"); } return true; } @@ -416,46 +405,47 @@ public boolean uninstallApp(final CommandSourceStack source, String name) } if (!Files.exists(folder.getParent().resolve(name + ".sc"))) { - Messenger.m(source, "App doesn't exist in the world scripts folder, so can only be unloaded"); + Carpet.Messenger_message(source, "App doesn't exist in the world scripts folder, so can only be unloaded"); return false; } removeScriptHost(source, name, false, false); Files.move(folder.getParent().resolve(name + ".sc"), folder.resolve(name + ".sc"), StandardCopyOption.REPLACE_EXISTING); - Messenger.m(source, "gi Removed " + name + " app"); + Carpet.Messenger_message(source, "gi Removed " + name + " app"); return true; } catch (final IOException exc) { - Messenger.m(source, "rb Failed to uninstall the app"); + Carpet.Messenger_message(source, "rb Failed to uninstall the app"); } return false; } public void tick() { - CarpetProfiler.ProfilerToken token; - token = CarpetProfiler.start_section(null, "Scarpet schedule", CarpetProfiler.TYPE.GENERAL); + Runnable token; + token = Carpet.startProfilerSection("Scarpet schedule"); events.handleEvents.getWhileDisabled(() -> { events.tick(); return null; }); - CarpetProfiler.end_current_section(token); - token = CarpetProfiler.start_section(null, "Scarpet app data", CarpetProfiler.TYPE.GENERAL); + token.run(); + token = Carpet.startProfilerSection("Scarpet app data"); for (final CarpetScriptHost host : modules.values()) { host.tick(); } - CarpetProfiler.end_current_section(token); + token.run(); } public void onClose() { - CarpetEventServer.Event.SHUTDOWN.onTick(); + CarpetEventServer.Event.SHUTDOWN.onTick(server); for (final CarpetScriptHost host : modules.values()) { host.onClose(); events.removeAllHostEvents(host); } + stopAll = true; } public void onPlayerJoin(final ServerPlayer player) @@ -475,6 +465,12 @@ public void onPlayerJoin(final ServerPlayer player) }); } + @Override + public Path resolveResource(final String suffix) + { + return server.getWorldPath(LevelResource.ROOT).resolve("scripts/" + suffix); + } + private record TransferData(boolean perUser, Predicate commandValidator, boolean isRuleApp) { diff --git a/src/main/java/carpet/script/Context.java b/src/main/java/carpet/script/Context.java index 430159caf6..8450667f2d 100644 --- a/src/main/java/carpet/script/Context.java +++ b/src/main/java/carpet/script/Context.java @@ -91,6 +91,11 @@ public ScriptHost.ErrorSnooper getErrorSnooper() return host.errorSnooper; } + public ScriptServer scriptServer() + { + return host.scriptServer(); + } + /** * immutable context only for reason on reporting access violations in evaluating expressions in optimizization * mode detecting any potential violations that may happen on the way diff --git a/src/main/java/carpet/script/EntityEventsGroup.java b/src/main/java/carpet/script/EntityEventsGroup.java index 41b1dc3e8b..f3b9bb4272 100644 --- a/src/main/java/carpet/script/EntityEventsGroup.java +++ b/src/main/java/carpet/script/EntityEventsGroup.java @@ -1,7 +1,7 @@ package carpet.script; -import carpet.CarpetServer; import carpet.script.exception.InternalExpressionException; +import carpet.script.external.Vanilla; import carpet.script.value.EntityValue; import carpet.script.value.FunctionValue; import carpet.script.value.NumericValue; @@ -46,7 +46,8 @@ public void onEvent(final Event type, final Object... args) { return; } - if (CarpetServer.scriptServer == null) + final CarpetScriptServer scriptServer = Vanilla.MinecraftServer_getScriptServer(entity.getServer()); + if (scriptServer.stopAll) { return; // executed after world is closin down } @@ -54,7 +55,7 @@ public void onEvent(final Event type, final Object... args) { final Map.Entry action = iterator.next(); final EventKey key = action.getKey(); - final ScriptHost host = CarpetServer.scriptServer.getAppHostByName(key.host()); + final ScriptHost host = scriptServer.getAppHostByName(key.host()); if (host == null) { iterator.remove(); @@ -81,7 +82,7 @@ public void addEvent(final Event type, final ScriptHost host, final FunctionValu final EventKey key = new EventKey(host.getName(), host.user); if (fun != null) { - final CarpetEventServer.Callback call = type.create(key, fun, extraargs); + final CarpetEventServer.Callback call = type.create(key, fun, extraargs, (CarpetScriptServer) host.scriptServer()); if (call == null) { throw new InternalExpressionException("wrong number of arguments for callback, required " + type.argcount); @@ -154,13 +155,13 @@ public Event(final String identifier, final int args) byName.put(identifier, this); } - public CarpetEventServer.Callback create(final EventKey key, final FunctionValue function, final List extraArgs) + public CarpetEventServer.Callback create(final EventKey key, final FunctionValue function, final List extraArgs, final CarpetScriptServer scriptServer) { if ((function.getArguments().size() - (extraArgs == null ? 0 : extraArgs.size())) != argcount) { return null; } - return new CarpetEventServer.Callback(key.host(), key.user(), function, extraArgs); + return new CarpetEventServer.Callback(key.host(), key.user(), function, extraArgs, scriptServer); } public CarpetEventServer.CallbackResult call(final CarpetEventServer.Callback tickCall, final Entity entity, final Object... args) diff --git a/src/main/java/carpet/script/Expression.java b/src/main/java/carpet/script/Expression.java index c9aca6af0d..290f4fc5a8 100644 --- a/src/main/java/carpet/script/Expression.java +++ b/src/main/java/carpet/script/Expression.java @@ -1,6 +1,5 @@ package carpet.script; -import carpet.CarpetSettings; import carpet.script.Fluff.AbstractFunction; import carpet.script.Fluff.AbstractLazyFunction; import carpet.script.Fluff.AbstractLazyOperator; @@ -20,6 +19,7 @@ import carpet.script.exception.InternalExpressionException; import carpet.script.exception.ResolvedException; import carpet.script.exception.ReturnStatement; +import carpet.script.external.Vanilla; import carpet.script.language.Arithmetic; import carpet.script.language.ControlFlow; import carpet.script.language.DataStructures; @@ -44,12 +44,14 @@ import java.util.List; import java.util.Map; import java.util.Set; -import java.util.function.*; +import java.util.function.BiFunction; +import java.util.function.BinaryOperator; +import java.util.function.DoubleToLongFunction; +import java.util.function.DoubleUnaryOperator; +import java.util.function.Function; +import java.util.function.Supplier; import java.util.stream.Collectors; -import static java.lang.Math.max; -import static java.lang.Math.min; - public class Expression { /** @@ -164,8 +166,8 @@ private static List getExpressionSnippetContext(final Tokenizer.Token to } else { - output.add(expr.substring(max(0, token.pos - 40), token.pos)); - output.add(expr.substring(token.pos, min(token.pos + 1 + 40, expr.length()))); + output.add(expr.substring(Math.max(0, token.pos - 40), token.pos)); + output.add(expr.substring(token.pos, Math.min(token.pos + 1 + 40, expr.length()))); } return output; } @@ -424,7 +426,7 @@ public static RuntimeException handleCodeException(final Context c, final Runtim return exc; } // unexpected really - should be caught earlier and converted to InternalExpressionException - CarpetSettings.LOG.error("Unexpected exception while running Scarpet code", exc); + CarpetScriptServer.LOG.error("Unexpected exception while running Scarpet code", exc); return new ExpressionException(c, e, token, "Internal error (please report this issue to Carpet) while evaluating: " + exc); } @@ -1188,13 +1190,14 @@ private LazyValue getAST(final Context context) final List rpn = shuntingYard(context); validate(context, rpn); final ExpressionNode root = RPNToParseTree(rpn, context); - if (!CarpetSettings.scriptsOptimization) + if (!Vanilla.ScriptServer_scriptOptimizations(((CarpetScriptServer)context.scriptServer()).server)) { return root.op; } final Context optimizeOnlyContext = new Context.ContextForErrorReporting(context); - if (CarpetSettings.scriptsDebugging) + final boolean scriptsDebugging = Vanilla.ScriptServer_scriptDebugging(((CarpetScriptServer)context.scriptServer()).server); + if (scriptsDebugging) { CarpetScriptServer.LOG.info("Input code size for " + getModuleName() + ": " + treeSize(root) + " nodes, " + treeDepth(root) + " deep"); } @@ -1209,36 +1212,36 @@ private LazyValue getAST(final Context context) changed = false; while (true) { - if (CarpetSettings.scriptsDebugging) + if (scriptsDebugging) { prevTreeSize = treeSize(root); prevTreeDepth = treeDepth(root); } - final boolean optimized = compactTree(root, Context.Type.NONE, 0); + final boolean optimized = compactTree(root, Context.Type.NONE, 0, scriptsDebugging); if (!optimized) { break; } changed = true; - if (CarpetSettings.scriptsDebugging) + if (scriptsDebugging) { CarpetScriptServer.LOG.info("Compacted from " + prevTreeSize + " nodes, " + prevTreeDepth + " code depth to " + treeSize(root) + " nodes, " + treeDepth(root) + " code depth"); } } while (true) { - if (CarpetSettings.scriptsDebugging) + if (scriptsDebugging) { prevTreeSize = treeSize(root); prevTreeDepth = treeDepth(root); } - final boolean optimized = optimizeTree(optimizeOnlyContext, root, Context.Type.NONE, 0); + final boolean optimized = optimizeTree(optimizeOnlyContext, root, Context.Type.NONE, 0, scriptsDebugging); if (!optimized) { break; } changed = true; - if (CarpetSettings.scriptsDebugging) + if (scriptsDebugging) { CarpetScriptServer.LOG.info("Optimized from " + prevTreeSize + " nodes, " + prevTreeDepth + " code depth to " + treeSize(root) + " nodes, " + treeDepth(root) + " code depth"); } @@ -1258,7 +1261,7 @@ private int treeDepth(final ExpressionNode node) } - private boolean compactTree(final ExpressionNode node, final Context.Type expectedType, final int indent) + private boolean compactTree(final ExpressionNode node, final Context.Type expectedType, final int indent, final boolean scriptsDebugging) { // ctx is just to report errors, not values evaluation boolean optimized = false; @@ -1278,7 +1281,7 @@ private boolean compactTree(final ExpressionNode node, final Context.Type expect final Context.Type requestedType = operation.staticType(expectedType); for (final ExpressionNode arg : node.args) { - if (compactTree(arg, requestedType, indent + 1)) + if (compactTree(arg, requestedType, indent + 1, scriptsDebugging)) { optimized = true; } @@ -1308,7 +1311,7 @@ else if (rop.equals("return")) returnNode.token = returnNode.args.get(0).token; returnNode.range = returnNode.args.get(0).range; returnNode.args = returnNode.args.get(0).args; - if (CarpetSettings.scriptsDebugging) + if (scriptsDebugging) { CarpetScriptServer.LOG.info(" - Removed unnecessary tail return of " + returnNode.token.surface + " from function body at line " + (returnNode.token.lineno + 1) + ", node depth " + indent); } @@ -1318,7 +1321,7 @@ else if (rop.equals("return")) returnNode.op = LazyValue.ofConstant(Value.NULL); returnNode.token.morph(Tokenizer.Token.TokenType.CONSTANT, ""); returnNode.args = Collections.emptyList(); - if (CarpetSettings.scriptsDebugging) + if (scriptsDebugging) { CarpetScriptServer.LOG.info(" - Removed unnecessary tail return from function body at line " + (returnNode.token.lineno + 1) + ", node depth " + indent); } @@ -1356,7 +1359,7 @@ else if (rop.equals("return")) newargs.addAll(optimizedChild.args); } - if (CarpetSettings.scriptsDebugging) + if (scriptsDebugging) { CarpetScriptServer.LOG.info(" - " + symbol + "(" + node.args.size() + ") => " + function + "(" + newargs.size() + ") at line " + (node.token.lineno + 1) + ", node depth " + indent); } @@ -1368,7 +1371,7 @@ else if (rop.equals("return")) return optimized; } - private boolean optimizeTree(final Context ctx, final ExpressionNode node, Context.Type expectedType, final int indent) + private boolean optimizeTree(final Context ctx, final ExpressionNode node, Context.Type expectedType, final int indent, final boolean scriptsDebugging) { // ctx is just to report errors, not values evaluation boolean optimized = false; @@ -1390,7 +1393,7 @@ private boolean optimizeTree(final Context ctx, final ExpressionNode node, Conte final Context.Type requestedType = operation.staticType(expectedType); for (final ExpressionNode arg : node.args) { - if (optimizeTree(ctx, arg, requestedType, indent + 1)) + if (optimizeTree(ctx, arg, requestedType, indent + 1, scriptsDebugging)) { optimized = true; } @@ -1457,7 +1460,7 @@ else if (args.size() == 1) result = ((ILazyOperator) operation).lazyEval(ctx, expectedType, this, node.token, args.get(0), args.get(1)).evalValue(null, expectedType); } node.op = LazyValue.ofConstant(result); - if (CarpetSettings.scriptsDebugging) + if (scriptsDebugging) { CarpetScriptServer.LOG.info(" - " + symbol + "(" + args.stream().map(a -> a.evalValue(null, requestedType).getString()).collect(Collectors.joining(", ")) + ") => " + result.getString() + " at line " + (node.token.lineno + 1) + ", node depth " + indent); } diff --git a/src/main/java/carpet/script/Fluff.java b/src/main/java/carpet/script/Fluff.java index ca91195e2e..b0fc240ec3 100644 --- a/src/main/java/carpet/script/Fluff.java +++ b/src/main/java/carpet/script/Fluff.java @@ -1,6 +1,5 @@ package carpet.script; -import carpet.CarpetSettings; import carpet.script.exception.ExpressionException; import carpet.script.exception.InternalExpressionException; import carpet.script.value.FunctionUnpackedArgumentsValue; @@ -218,7 +217,7 @@ private List getParams(final Context c) } else { - CarpetSettings.LOG.error("How did we get here 1"); + CarpetScriptServer.LOG.error("How did we get here 1"); } return params; } diff --git a/src/main/java/carpet/script/Module.java b/src/main/java/carpet/script/Module.java index b687c07349..9eff564775 100644 --- a/src/main/java/carpet/script/Module.java +++ b/src/main/java/carpet/script/Module.java @@ -9,10 +9,8 @@ import org.apache.commons.io.IOUtils; -import carpet.CarpetServer; import carpet.script.argument.FileArgument; import net.minecraft.nbt.Tag; -import net.minecraft.world.level.storage.LevelResource; public record Module(String name, String code, boolean library) { @@ -89,9 +87,9 @@ public static Module fromJarPathWithCustomName(final String fullPath, final Stri } } - public static Tag getData(final Module module) + public static Tag getData(final Module module, final ScriptServer scriptServer) { - final Path dataFile = resolveResource(module); + final Path dataFile = resolveResource(module, scriptServer); if (dataFile == null || !Files.exists(dataFile) || !(Files.isRegularFile(dataFile))) { return null; @@ -102,9 +100,9 @@ public static Tag getData(final Module module) } } - public static void saveData(final Module module, final Tag globalState) + public static void saveData(final Module module, final Tag globalState, final ScriptServer scriptServer) { - final Path dataFile = resolveResource(module); + final Path dataFile = resolveResource(module, scriptServer); if (dataFile == null) { return; @@ -126,9 +124,8 @@ public static void saveData(final Module module, final Tag globalState) } } - private static Path resolveResource(final Module module) + private static Path resolveResource(final Module module, final ScriptServer scriptServer) { - return module == null ? null : CarpetServer.minecraft_server.getWorldPath(LevelResource.ROOT).resolve("scripts/" + module.name() + ".data.nbt"); // commandline app + return module == null ? null : scriptServer.resolveResource(module.name() + ".data.nbt"); } - } diff --git a/src/main/java/carpet/commands/ScriptCommand.java b/src/main/java/carpet/script/ScriptCommand.java similarity index 56% rename from src/main/java/carpet/commands/ScriptCommand.java rename to src/main/java/carpet/script/ScriptCommand.java index 8251f051f3..6f9d2256d6 100644 --- a/src/main/java/carpet/commands/ScriptCommand.java +++ b/src/main/java/carpet/script/ScriptCommand.java @@ -1,21 +1,11 @@ -package carpet.commands; +package carpet.script; -import carpet.CarpetServer; -import carpet.CarpetSettings; +import carpet.script.external.Carpet; +import carpet.script.external.Vanilla; import carpet.script.utils.AppStoreManager; -import carpet.script.CarpetEventServer; -import carpet.script.CarpetExpression; -import carpet.script.CarpetScriptHost; -import carpet.script.Expression; -import carpet.script.LazyValue; -import carpet.script.ScriptHost; -import carpet.script.Tokenizer; import carpet.script.exception.CarpetExpressionException; import carpet.script.value.FunctionValue; import carpet.script.value.Value; -import carpet.utils.CarpetProfiler; -import carpet.utils.CommandHelper; -import carpet.utils.Messenger; import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.arguments.StringArgumentType; import com.mojang.brigadier.builder.LiteralArgumentBuilder; @@ -24,7 +14,6 @@ import com.mojang.brigadier.suggestion.Suggestions; import com.mojang.brigadier.suggestion.SuggestionsBuilder; import net.minecraft.commands.CommandBuildContext; -import net.minecraft.world.level.GameRules; import org.apache.commons.lang3.StringUtils; import java.io.IOException; @@ -39,6 +28,7 @@ import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Collectors; + import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.arguments.blocks.BlockInput; import net.minecraft.commands.arguments.blocks.BlockPredicateArgument; @@ -60,52 +50,67 @@ public class ScriptCommand { private static final TreeSet scarpetFunctions; private static final TreeSet APIFunctions; + static { - Set allFunctions = (new CarpetExpression(null, "null", null, null)).getExpr().getFunctionNames(); + final Set allFunctions = (new CarpetExpression(null, "null", null, null)).getExpr().getFunctionNames(); scarpetFunctions = new TreeSet<>(Expression.none.getFunctionNames()); APIFunctions = allFunctions.stream().filter(s -> !scarpetFunctions.contains(s)).collect(Collectors.toCollection(TreeSet::new)); } - public static List suggestFunctions(ScriptHost host, String previous, String prefix) + public static List suggestFunctions(final ScriptHost host, String previous, final String prefix) { previous = previous.replace("\\'", ""); - int quoteCount = StringUtils.countMatches(previous,'\''); + final int quoteCount = StringUtils.countMatches(previous, '\''); if (quoteCount % 2 == 1) + { return Collections.emptyList(); - int maxLen = prefix.length()<3 ? (prefix.length()*2+1) : 1234; - String eventPrefix = prefix.startsWith("__on_")?prefix.substring(5):null; - List scarpetMatches = scarpetFunctions.stream(). - filter(s -> s.startsWith(prefix) && s.length() <= maxLen).map(s -> s+"(").collect(Collectors.toList()); + } + final int maxLen = prefix.length() < 3 ? (prefix.length() * 2 + 1) : 1234; + final String eventPrefix = prefix.startsWith("__on_") ? prefix.substring(5) : null; + final List scarpetMatches = scarpetFunctions.stream(). + filter(s -> s.startsWith(prefix) && s.length() <= maxLen).map(s -> s + "(").collect(Collectors.toList()); scarpetMatches.addAll(APIFunctions.stream(). - filter(s -> s.startsWith(prefix) && s.length() <= maxLen).map(s -> s+"(").collect(Collectors.toList())); + filter(s -> s.startsWith(prefix) && s.length() <= maxLen).map(s -> s + "(").toList()); // not that useful in commandline, more so in external scripts, so skipping here - if (eventPrefix != null) scarpetMatches.addAll(CarpetEventServer.Event.publicEvents(null).stream(). - filter(e -> e.name.startsWith(eventPrefix)).map(s -> "__on_"+s.name+"(").collect(Collectors.toList())); - scarpetMatches.addAll(host.globalFunctionNames(host.main, s -> s.startsWith(prefix)).map(s -> s+"(").collect(Collectors.toList())); - scarpetMatches.addAll(host.globalVariableNames(host.main, s -> s.startsWith(prefix)).collect(Collectors.toList())); + if (eventPrefix != null) + { + scarpetMatches.addAll(CarpetEventServer.Event.publicEvents(null).stream(). + filter(e -> e.name.startsWith(eventPrefix)).map(s -> "__on_" + s.name + "(").toList()); + } + scarpetMatches.addAll(host.globalFunctionNames(host.main, s -> s.startsWith(prefix)).map(s -> s + "(").toList()); + scarpetMatches.addAll(host.globalVariableNames(host.main, s -> s.startsWith(prefix)).toList()); return scarpetMatches; } private static CompletableFuture suggestCode( - CommandContext context, - SuggestionsBuilder suggestionsBuilder + final CommandContext context, + final SuggestionsBuilder suggestionsBuilder ) throws CommandSyntaxException { - CarpetScriptHost currentHost = getHost(context); - String previous = suggestionsBuilder.getRemaining(); - int strlen = previous.length(); - StringBuilder lastToken = new StringBuilder(); - for (int idx = strlen-1; idx >=0; idx--) + final CarpetScriptHost currentHost = getHost(context); + final String previous = suggestionsBuilder.getRemaining(); + final int strlen = previous.length(); + final StringBuilder lastToken = new StringBuilder(); + for (int idx = strlen - 1; idx >= 0; idx--) { - char ch = previous.charAt(idx); - if (Character.isLetterOrDigit(ch) || ch == '_') lastToken.append(ch); else break; + final char ch = previous.charAt(idx); + if (Character.isLetterOrDigit(ch) || ch == '_') + { + lastToken.append(ch); + } + else + { + break; + } } if (lastToken.length() == 0) + { return suggestionsBuilder.buildFuture(); - String prefix = lastToken.reverse().toString(); - String previousString = previous.substring(0,previous.length()-prefix.length()) ; - suggestFunctions(currentHost, previousString, prefix).forEach(text -> suggestionsBuilder.suggest(previousString+text)); + } + final String prefix = lastToken.reverse().toString(); + final String previousString = previous.substring(0, previous.length() - prefix.length()); + suggestFunctions(currentHost, previousString, prefix).forEach(text -> suggestionsBuilder.suggest(previousString + text)); return suggestionsBuilder.buildFuture(); } @@ -114,59 +119,72 @@ private static CompletableFuture suggestCode( * variable. */ private static CompletableFuture suggestDownloadableApps( - CommandContext context, - SuggestionsBuilder suggestionsBuilder - ) throws CommandSyntaxException { - - return CompletableFuture.supplyAsync(()->{ - String previous = suggestionsBuilder.getRemaining(); - try { + final CommandContext context, + final SuggestionsBuilder suggestionsBuilder + ) throws CommandSyntaxException + { + + return CompletableFuture.supplyAsync(() -> { + final String previous = suggestionsBuilder.getRemaining(); + try + { AppStoreManager.suggestionsFromPath(previous).forEach(suggestionsBuilder::suggest); } - catch (IOException e) + catch (final IOException e) { - CarpetSettings.LOG.warn("Exception when fetching app store structure", e); + CarpetScriptServer.LOG.warn("Exception when fetching app store structure", e); } return suggestionsBuilder.build(); }); } - public static void register(CommandDispatcher dispatcher, final CommandBuildContext commandBuildContext) + private static CarpetScriptServer ss(final CommandContext context) { - LiteralArgumentBuilder b = literal("globals"). + return Vanilla.MinecraftServer_getScriptServer(context.getSource().getServer()); + } + + public static void register(final CommandDispatcher dispatcher, final CommandBuildContext commandBuildContext) + { + final LiteralArgumentBuilder b = literal("globals"). executes(context -> listGlobals(context, false)). then(literal("all").executes(context -> listGlobals(context, true))); - LiteralArgumentBuilder o = literal("stop"). - executes( (cc) -> { CarpetServer.scriptServer.stopAll = true; return 1;}); - LiteralArgumentBuilder u = literal("resume"). - executes( (cc) -> { CarpetServer.scriptServer.stopAll = false; return 1;}); - LiteralArgumentBuilder l = literal("run"). - requires((player) -> CommandHelper.canUseCommand(player, CarpetSettings.commandScriptACE)). + final LiteralArgumentBuilder o = literal("stop"). + executes((cc) -> { + ss(cc).stopAll = true; + return 1; + }); + final LiteralArgumentBuilder u = literal("resume"). + executes((cc) -> { + ss(cc).stopAll = false; + return 1; + }); + final LiteralArgumentBuilder l = literal("run"). + requires(Vanilla::ServerPlayer_canScriptACE). then(argument("expr", StringArgumentType.greedyString()).suggests(ScriptCommand::suggestCode). executes((cc) -> compute( cc, StringArgumentType.getString(cc, "expr")))); - LiteralArgumentBuilder s = literal("invoke"). - then(argument("call", StringArgumentType.word()).suggests( (cc, bb)->suggest(suggestFunctionCalls(cc),bb)). - executes( (cc) -> invoke( + final LiteralArgumentBuilder s = literal("invoke"). + then(argument("call", StringArgumentType.word()).suggests((cc, bb) -> suggest(suggestFunctionCalls(cc), bb)). + executes((cc) -> invoke( cc, StringArgumentType.getString(cc, "call"), null, null, "" - )) . + )). then(argument("arguments", StringArgumentType.greedyString()). - executes( (cc) -> invoke( + executes((cc) -> invoke( cc, StringArgumentType.getString(cc, "call"), null, null, StringArgumentType.getString(cc, "arguments") )))); - LiteralArgumentBuilder c = literal("invokepoint"). - then(argument("call", StringArgumentType.word()).suggests( (cc, bb)->suggest(suggestFunctionCalls(cc),bb)). + final LiteralArgumentBuilder c = literal("invokepoint"). + then(argument("call", StringArgumentType.word()).suggests((cc, bb) -> suggest(suggestFunctionCalls(cc), bb)). then(argument("origin", BlockPosArgument.blockPos()). - executes( (cc) -> invoke( + executes((cc) -> invoke( cc, StringArgumentType.getString(cc, "call"), BlockPosArgument.getSpawnablePos(cc, "origin"), @@ -174,18 +192,18 @@ public static void register(CommandDispatcher dispatcher, fi "" )). then(argument("arguments", StringArgumentType.greedyString()). - executes( (cc) -> invoke( + executes((cc) -> invoke( cc, StringArgumentType.getString(cc, "call"), BlockPosArgument.getSpawnablePos(cc, "origin"), null, StringArgumentType.getString(cc, "arguments") ))))); - LiteralArgumentBuilder h = literal("invokearea"). - then(argument("call", StringArgumentType.word()).suggests( (cc, bb)->suggest(suggestFunctionCalls(cc),bb)). + final LiteralArgumentBuilder h = literal("invokearea"). + then(argument("call", StringArgumentType.word()).suggests((cc, bb) -> suggest(suggestFunctionCalls(cc), bb)). then(argument("from", BlockPosArgument.blockPos()). then(argument("to", BlockPosArgument.blockPos()). - executes( (cc) -> invoke( + executes((cc) -> invoke( cc, StringArgumentType.getString(cc, "call"), BlockPosArgument.getSpawnablePos(cc, "from"), @@ -193,27 +211,27 @@ public static void register(CommandDispatcher dispatcher, fi "" )). then(argument("arguments", StringArgumentType.greedyString()). - executes( (cc) -> invoke( + executes((cc) -> invoke( cc, StringArgumentType.getString(cc, "call"), BlockPosArgument.getSpawnablePos(cc, "from"), BlockPosArgument.getSpawnablePos(cc, "to"), StringArgumentType.getString(cc, "arguments") )))))); - LiteralArgumentBuilder i = literal("scan").requires((player) -> player.hasPermission(2)). + final LiteralArgumentBuilder i = literal("scan").requires((player) -> player.hasPermission(2)). then(argument("origin", BlockPosArgument.blockPos()). then(argument("from", BlockPosArgument.blockPos()). then(argument("to", BlockPosArgument.blockPos()). then(argument("expr", StringArgumentType.greedyString()). suggests(ScriptCommand::suggestCode). - executes( (cc) -> scriptScan( + executes((cc) -> scriptScan( cc, BlockPosArgument.getSpawnablePos(cc, "origin"), BlockPosArgument.getSpawnablePos(cc, "from"), BlockPosArgument.getSpawnablePos(cc, "to"), StringArgumentType.getString(cc, "expr") )))))); - LiteralArgumentBuilder e = literal("fill").requires((player) -> player.hasPermission(2)). + final LiteralArgumentBuilder e = literal("fill").requires((player) -> player.hasPermission(2)). then(argument("origin", BlockPosArgument.blockPos()). then(argument("from", BlockPosArgument.blockPos()). then(argument("to", BlockPosArgument.blockPos()). @@ -240,7 +258,7 @@ public static void register(CommandDispatcher dispatcher, fi BlockPredicateArgument.getBlockPredicate(cc, "filter"), "solid" ))))))))); - LiteralArgumentBuilder t = literal("outline").requires((player) -> player.hasPermission(2)). + final LiteralArgumentBuilder t = literal("outline").requires((player) -> player.hasPermission(2)). then(argument("origin", BlockPosArgument.blockPos()). then(argument("from", BlockPosArgument.blockPos()). then(argument("to", BlockPosArgument.blockPos()). @@ -267,179 +285,187 @@ public static void register(CommandDispatcher dispatcher, fi BlockPredicateArgument.getBlockPredicate(cc, "filter"), "outline" ))))))))); - LiteralArgumentBuilder a = literal("load").requires( (player) -> CommandHelper.canUseCommand(player, CarpetSettings.commandScriptACE) ). + final LiteralArgumentBuilder a = literal("load").requires(Vanilla::ServerPlayer_canScriptACE). then(argument("app", StringArgumentType.word()). - suggests( (cc, bb) -> suggest(CarpetServer.scriptServer.listAvailableModules(true),bb)). + suggests((cc, bb) -> suggest(ss(cc).listAvailableModules(true), bb)). executes((cc) -> { - boolean success = CarpetServer.scriptServer.addScriptHost(cc.getSource(), StringArgumentType.getString(cc, "app"), null, true, false, false, null); - return success?1:0; + final boolean success = ss(cc).addScriptHost(cc.getSource(), StringArgumentType.getString(cc, "app"), null, true, false, false, null); + return success ? 1 : 0; }). then(literal("global"). executes((cc) -> - { - boolean success = CarpetServer.scriptServer.addScriptHost(cc.getSource(), StringArgumentType.getString(cc, "app"), null, false, false, false, null); - return success?1:0; - } + { + final boolean success = ss(cc).addScriptHost(cc.getSource(), StringArgumentType.getString(cc, "app"), null, false, false, false, null); + return success ? 1 : 0; + } ) ) ); - LiteralArgumentBuilder f = literal("unload").requires( (player) -> CommandHelper.canUseCommand(player, CarpetSettings.commandScriptACE) ). + final LiteralArgumentBuilder f = literal("unload").requires(Vanilla::ServerPlayer_canScriptACE). then(argument("app", StringArgumentType.word()). - suggests( (cc, bb) -> suggest(CarpetServer.scriptServer.unloadableModules,bb)). + suggests((cc, bb) -> suggest(ss(cc).unloadableModules, bb)). executes((cc) -> { - boolean success =CarpetServer.scriptServer.removeScriptHost(cc.getSource(), StringArgumentType.getString(cc, "app"), true, false); - return success?1:0; + final boolean success = ss(cc).removeScriptHost(cc.getSource(), StringArgumentType.getString(cc, "app"), true, false); + return success ? 1 : 0; })); - LiteralArgumentBuilder q = literal("event").requires( (player) -> CommandHelper.canUseCommand(player, CarpetSettings.commandScriptACE) ). - executes( (cc) -> listEvents(cc.getSource())). + final LiteralArgumentBuilder q = literal("event").requires(Vanilla::ServerPlayer_canScriptACE). + executes(ScriptCommand::listEvents). then(literal("add_to"). then(argument("event", StringArgumentType.word()). - suggests( (cc, bb) -> suggest(CarpetEventServer.Event.publicEvents(CarpetServer.scriptServer).stream().map(ev -> ev.name).collect(Collectors.toList()),bb)). + suggests((cc, bb) -> suggest(CarpetEventServer.Event.publicEvents(ss(cc)).stream().map(ev -> ev.name).collect(Collectors.toList()), bb)). then(argument("call", StringArgumentType.word()). - suggests( (cc, bb) -> suggest(suggestFunctionCalls(cc), bb)). - executes( (cc) -> CarpetServer.scriptServer.events.addEventFromCommand( + suggests((cc, bb) -> suggest(suggestFunctionCalls(cc), bb)). + executes((cc) -> ss(cc).events.addEventFromCommand( cc.getSource(), StringArgumentType.getString(cc, "event"), null, StringArgumentType.getString(cc, "call") - )?1:0)). + ) ? 1 : 0)). then(literal("from"). then(argument("app", StringArgumentType.word()). - suggests( (cc, bb) -> suggest(CarpetServer.scriptServer.modules.keySet(), bb)). + suggests((cc, bb) -> suggest(ss(cc).modules.keySet(), bb)). then(argument("call", StringArgumentType.word()). - suggests( (cc, bb) -> suggest(suggestFunctionCalls(cc), bb)). - executes( (cc) -> CarpetServer.scriptServer.events.addEventFromCommand( + suggests((cc, bb) -> suggest(suggestFunctionCalls(cc), bb)). + executes((cc) -> ss(cc).events.addEventFromCommand( cc.getSource(), StringArgumentType.getString(cc, "event"), StringArgumentType.getString(cc, "app"), StringArgumentType.getString(cc, "call") - )?1:0)))))). + ) ? 1 : 0)))))). then(literal("remove_from"). then(argument("event", StringArgumentType.word()). - suggests( (cc, bb) -> suggest(CarpetEventServer.Event.publicEvents(CarpetServer.scriptServer).stream().filter(CarpetEventServer.Event::isNeeded).map(ev -> ev.name).collect(Collectors.toList()) ,bb)). + suggests((cc, bb) -> suggest(CarpetEventServer.Event.publicEvents(ss(cc)).stream().filter(CarpetEventServer.Event::isNeeded).map(ev -> ev.name).collect(Collectors.toList()), bb)). then(argument("call", StringArgumentType.greedyString()). - suggests( (cc, bb) -> suggest(CarpetEventServer.Event.getEvent(StringArgumentType.getString(cc, "event"), CarpetServer.scriptServer).handler.inspectCurrentCalls().stream().map(CarpetEventServer.Callback::toString), bb)). - executes( (cc) -> CarpetServer.scriptServer.events.removeEventFromCommand( + suggests((cc, bb) -> suggest(CarpetEventServer.Event.getEvent(StringArgumentType.getString(cc, "event"), ss(cc)).handler.inspectCurrentCalls().stream().map(CarpetEventServer.Callback::toString), bb)). + executes((cc) -> ss(cc).events.removeEventFromCommand( cc.getSource(), StringArgumentType.getString(cc, "event"), StringArgumentType.getString(cc, "call") - )?1:0)))); + ) ? 1 : 0)))); - LiteralArgumentBuilder d = literal("download").requires((player) -> CommandHelper.canUseCommand(player, CarpetSettings.commandScriptACE)). + final LiteralArgumentBuilder d = literal("download").requires(Vanilla::ServerPlayer_canScriptACE). then(argument("path", StringArgumentType.greedyString()). suggests(ScriptCommand::suggestDownloadableApps). - executes(cc-> AppStoreManager.downloadScript(cc.getSource(), StringArgumentType.getString(cc,"path")))); - LiteralArgumentBuilder r = literal("remove").requires( (player) -> CommandHelper.canUseCommand(player, CarpetSettings.commandScriptACE) ). + executes(cc -> AppStoreManager.downloadScript(cc.getSource(), StringArgumentType.getString(cc, "path")))); + final LiteralArgumentBuilder r = literal("remove").requires(Vanilla::ServerPlayer_canScriptACE). then(argument("app", StringArgumentType.word()). - suggests( (cc, bb) -> suggest(CarpetServer.scriptServer.unloadableModules,bb)). + suggests((cc, bb) -> suggest(ss(cc).unloadableModules, bb)). executes((cc) -> { - boolean success =CarpetServer.scriptServer.uninstallApp(cc.getSource(), StringArgumentType.getString(cc, "app")); - return success?1:0; + final boolean success = ss(cc).uninstallApp(cc.getSource(), StringArgumentType.getString(cc, "app")); + return success ? 1 : 0; })); dispatcher.register(literal("script"). - requires((player) -> CommandHelper.canUseCommand(player, CarpetSettings.commandScript)). + requires(Vanilla::ServerPlayer_canScriptGeneral). then(b).then(u).then(o).then(l).then(s).then(c).then(h).then(i).then(e).then(t).then(a).then(f).then(q).then(d).then(r)); dispatcher.register(literal("script"). - requires((player) -> CommandHelper.canUseCommand(player, CarpetSettings.commandScript)). + requires(Vanilla::ServerPlayer_canScriptGeneral). then(literal("in"). then(argument("app", StringArgumentType.word()). - suggests( (cc, bb) -> suggest(CarpetServer.scriptServer.modules.keySet(), bb)). + suggests((cc, bb) -> suggest(ss(cc).modules.keySet(), bb)). then(b).then(u).then(o).then(l).then(s).then(c).then(h).then(i).then(e).then(t)))); } - private static CarpetScriptHost getHost(CommandContext context) throws CommandSyntaxException + + private static CarpetScriptHost getHost(final CommandContext context) throws CommandSyntaxException { CarpetScriptHost host; + final CarpetScriptServer scriptServer = ss(context); try { - String name = StringArgumentType.getString(context, "app").toLowerCase(Locale.ROOT); - CarpetScriptHost parentHost = CarpetServer.scriptServer.modules.getOrDefault(name, CarpetServer.scriptServer.globalHost); - host = parentHost.retrieveOwnForExecution(context.getSource()); + final String name = StringArgumentType.getString(context, "app").toLowerCase(Locale.ROOT); + final CarpetScriptHost parentHost = scriptServer.modules.getOrDefault(name, scriptServer.globalHost); + host = parentHost.retrieveOwnForExecution(context.getSource()); } - catch (IllegalArgumentException ignored) + catch (final IllegalArgumentException ignored) { - host = CarpetServer.scriptServer.globalHost; + host = scriptServer.globalHost; } host.setChatErrorSnooper(context.getSource()); return host; } - private static Collection suggestFunctionCalls(CommandContext c) throws CommandSyntaxException + + private static Collection suggestFunctionCalls(final CommandContext c) throws CommandSyntaxException { - CarpetScriptHost host = getHost(c); - return host.globalFunctionNames(host.main, s -> !s.startsWith("_")).sorted().collect(Collectors.toList()); + final CarpetScriptHost host = getHost(c); + return host.globalFunctionNames(host.main, s -> !s.startsWith("_")).sorted().collect(Collectors.toList()); } - private static int listEvents(CommandSourceStack source) + + private static int listEvents(final CommandContext context) { - Messenger.m(source, "w Lists ALL event handlers:"); - for (CarpetEventServer.Event event: CarpetEventServer.Event.getAllEvents(CarpetServer.scriptServer, null)) + CarpetScriptServer scriptServer = ss(context); + CommandSourceStack source = context.getSource(); + Carpet.Messenger_message(source, "w Lists ALL event handlers:"); + for (final CarpetEventServer.Event event : CarpetEventServer.Event.getAllEvents(scriptServer, null)) { boolean shownEvent = false; - for (CarpetEventServer.Callback c: event.handler.inspectCurrentCalls()) + for (final CarpetEventServer.Callback c : event.handler.inspectCurrentCalls()) { if (!shownEvent) { - Messenger.m(source, "w Handlers for "+event.name+": "); + Carpet.Messenger_message(source, "w Handlers for " + event.name + ": "); shownEvent = true; } - Messenger.m(source, "w - "+c.function.getString() +(c.host==null?"":" (from "+c.host+")")); + Carpet.Messenger_message(source, "w - " + c.function.getString() + (c.host == null ? "" : " (from " + c.host + ")")); } } return 1; } - private static int listGlobals(CommandContext context, boolean all) throws CommandSyntaxException + + private static int listGlobals(final CommandContext context, final boolean all) throws CommandSyntaxException { - CarpetScriptHost host = getHost(context); - CommandSourceStack source = context.getSource(); + final CarpetScriptHost host = getHost(context); + final CommandSourceStack source = context.getSource(); + final CarpetScriptServer scriptServer = ss(context); - Messenger.m(source, "lb Stored functions"+((host == CarpetServer.scriptServer.globalHost)?":":" in "+host.getName()+":")); - host.globalFunctionNames(host.main, (str) -> all || !str.startsWith("__")).sorted().forEach( (s) -> { - FunctionValue fun = host.getFunction(s); + Carpet.Messenger_message(source, "lb Stored functions" + ((host == scriptServer.globalHost) ? ":" : " in " + host.getName() + ":")); + host.globalFunctionNames(host.main, (str) -> all || !str.startsWith("__")).sorted().forEach((s) -> { + final FunctionValue fun = host.getFunction(s); if (fun == null) { - Messenger.m(source, "gb "+s, "g - unused import"); - Messenger.m(source, "gi ----------------"); + Carpet.Messenger_message(source, "gb " + s, "g - unused import"); + Carpet.Messenger_message(source, "gi ----------------"); return; } - Expression expr = fun.getExpression(); - Tokenizer.Token tok = fun.getToken(); - List snippet = expr.getExpressionSnippet(tok); - Messenger.m(source, "wb "+fun.fullName(),"t defined at: line "+(tok.lineno+1)+" pos "+(tok.linepos+1)); - for (String snippetLine: snippet) + final Expression expr = fun.getExpression(); + final Tokenizer.Token tok = fun.getToken(); + final List snippet = expr.getExpressionSnippet(tok); + Carpet.Messenger_message(source, "wb " + fun.fullName(), "t defined at: line " + (tok.lineno + 1) + " pos " + (tok.linepos + 1)); + for (final String snippetLine : snippet) { - Messenger.m(source, "w "+snippetLine); + Carpet.Messenger_message(source, "w " + snippetLine); } - Messenger.m(source, "gi ----------------"); + Carpet.Messenger_message(source, "gi ----------------"); }); //Messenger.m(source, "w "+code); - Messenger.m(source, "w "); - Messenger.m(source, "lb Global variables"+((host == CarpetServer.scriptServer.globalHost)?":":" in "+host.getName()+":")); - host.globalVariableNames(host.main, (s) -> s.startsWith("global_")).sorted().forEach( (s) -> { - LazyValue variable = host.getGlobalVariable(s); + Carpet.Messenger_message(source, "w "); + Carpet.Messenger_message(source, "lb Global variables" + ((host == scriptServer.globalHost) ? ":" : " in " + host.getName() + ":")); + host.globalVariableNames(host.main, (s) -> s.startsWith("global_")).sorted().forEach((s) -> { + final LazyValue variable = host.getGlobalVariable(s); if (variable == null) { - Messenger.m(source, "gb "+s, "g - unused import"); + Carpet.Messenger_message(source, "gb " + s, "g - unused import"); } else { - Messenger.m(source, "wb "+s+": ", "w "+ variable.evalValue(null).getPrettyString()); + Carpet.Messenger_message(source, "wb " + s + ": ", "w " + variable.evalValue(null).getPrettyString()); } }); return 1; } - public static int handleCall(CommandSourceStack source, CarpetScriptHost host, Supplier call) + public static int handleCall(final CommandSourceStack source, final CarpetScriptHost host, final Supplier call) { try { - CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet run", CarpetProfiler.TYPE.GENERAL); + final Runnable token = Carpet.startProfilerSection("Scarpet run"); host.setChatErrorSnooper(source); - long start = System.nanoTime(); - Value result = call.get(); - long time = ((System.nanoTime()-start)/1000); + final long start = System.nanoTime(); + final Value result = call.get(); + long time = ((System.nanoTime() - start) / 1000); String metric = "\u00B5s"; if (time > 5000) { @@ -451,20 +477,20 @@ public static int handleCall(CommandSourceStack source, CarpetScriptHost host, S time /= 1000; metric = "s"; } - Messenger.m(source, "wi = ", "wb "+result.getString(), "gi ("+time+metric+")"); - int intres = (int)result.readInteger(); - CarpetProfiler.end_current_section(currentSection); + Carpet.Messenger_message(source, "wi = ", "wb " + result.getString(), "gi (" + time + metric + ")"); + final int intres = (int) result.readInteger(); + token.run(); return intres; } - catch (CarpetExpressionException e) + catch (final CarpetExpressionException e) { host.handleErrorWithStack("Error while evaluating expression", e); } - catch (ArithmeticException ae) + catch (final ArithmeticException ae) { host.handleErrorWithStack("Math doesn't compute", ae); } - catch (StackOverflowError soe) + catch (final StackOverflowError soe) { host.handleErrorWithStack("Your thoughts are too deep", soe); } @@ -472,16 +498,16 @@ public static int handleCall(CommandSourceStack source, CarpetScriptHost host, S //host.resetErrorSnooper(); // lets say no need to reset the snooper in case something happens on the way } - private static int invoke(CommandContext context, String call, BlockPos pos1, BlockPos pos2, String args) throws CommandSyntaxException + private static int invoke(final CommandContext context, final String call, final BlockPos pos1, final BlockPos pos2, final String args) throws CommandSyntaxException { - CommandSourceStack source = context.getSource(); - CarpetScriptHost host = getHost(context); + final CommandSourceStack source = context.getSource(); + final CarpetScriptHost host = getHost(context); if (call.startsWith("__")) { - Messenger.m(source, "r Hidden functions are only callable in scripts"); + Carpet.Messenger_message(source, "r Hidden functions are only callable in scripts"); return 0; } - List positions = new ArrayList<>(); + final List positions = new ArrayList<>(); if (pos1 != null) { positions.add(pos1.getX()); @@ -496,34 +522,34 @@ private static int invoke(CommandContext context, String cal } //if (!(args.trim().isEmpty())) // arguments.addAll(Arrays.asList(args.trim().split("\\s+"))); - return handleCall(source, host, () -> host.callLegacy(source, call, positions, args)); + return handleCall(source, host, () -> host.callLegacy(source, call, positions, args)); } - private static int compute(CommandContext context, String expr) throws CommandSyntaxException + private static int compute(final CommandContext context, final String expr) throws CommandSyntaxException { - CommandSourceStack source = context.getSource(); - CarpetScriptHost host = getHost(context); + final CommandSourceStack source = context.getSource(); + final CarpetScriptHost host = getHost(context); return handleCall(source, host, () -> { - CarpetExpression ex = new CarpetExpression(host.main, expr, source, new BlockPos(0, 0, 0)); + final CarpetExpression ex = new CarpetExpression(host.main, expr, source, new BlockPos(0, 0, 0)); return ex.scriptRunCommand(host, new BlockPos(source.getPosition())); }); } - private static int scriptScan(CommandContext context, BlockPos origin, BlockPos a, BlockPos b, String expr) throws CommandSyntaxException + private static int scriptScan(final CommandContext context, final BlockPos origin, final BlockPos a, final BlockPos b, final String expr) throws CommandSyntaxException { - CommandSourceStack source = context.getSource(); - CarpetScriptHost host = getHost(context); - BoundingBox area = BoundingBox.fromCorners(a, b); - CarpetExpression cexpr = new CarpetExpression(host.main, expr, source, origin); - int int_1 = area.getXSpan() * area.getYSpan() * area.getZSpan(); // X Y Z - if (int_1 > Math.max(source.getServer().getGameRules().getInt(GameRules.RULE_COMMAND_MODIFICATION_BLOCK_LIMIT), CarpetSettings.fillLimit)) + final CommandSourceStack source = context.getSource(); + final CarpetScriptHost host = getHost(context); + final BoundingBox area = BoundingBox.fromCorners(a, b); + final CarpetExpression cexpr = new CarpetExpression(host.main, expr, source, origin); + final int int_1 = area.getXSpan() * area.getYSpan() * area.getZSpan(); // X Y Z + if (int_1 > Vanilla.MinecraftServer_getFillLimit(source.getServer()) ) { - Messenger.m(source, "r too many blocks to evaluate: " + int_1); + Carpet.Messenger_message(source, "r too many blocks to evaluate: " + int_1); return 1; } int successCount = 0; - CarpetSettings.impendingFillSkipUpdates.set(!CarpetSettings.fillUpdates); + Carpet.getImpendingFillSkipUpdates().set(!Carpet.getFillUpdates()); try { for (int x = area.minX(); x <= area.maxX(); x++) @@ -534,48 +560,51 @@ private static int scriptScan(CommandContext context, BlockP { try { - if (cexpr.fillAndScanCommand(host, x, y, z)) successCount++; + if (cexpr.fillAndScanCommand(host, x, y, z)) + { + successCount++; + } } - catch (ArithmeticException ignored) + catch (final ArithmeticException ignored) { } } } } } - catch (CarpetExpressionException exc) + catch (final CarpetExpressionException exc) { host.handleErrorWithStack("Error while processing command", exc); return 0; } finally { - CarpetSettings.impendingFillSkipUpdates.set(false); + Carpet.getImpendingFillSkipUpdates().set(false); } - Messenger.m(source, "w Expression successful in " + successCount + " out of " + int_1 + " blocks"); + Carpet.Messenger_message(source, "w Expression successful in " + successCount + " out of " + int_1 + " blocks"); return successCount; } - private static int scriptFill(CommandContext context, BlockPos origin, BlockPos a, BlockPos b, String expr, - BlockInput block, Predicate replacement, String mode) throws CommandSyntaxException + private static int scriptFill(final CommandContext context, final BlockPos origin, final BlockPos a, final BlockPos b, final String expr, + final BlockInput block, final Predicate replacement, final String mode) throws CommandSyntaxException { - CommandSourceStack source = context.getSource(); - CarpetScriptHost host = getHost(context); - BoundingBox area = BoundingBox.fromCorners(a, b); - CarpetExpression cexpr = new CarpetExpression(host.main, expr, source, origin); - int int_1 = area.getXSpan() * area.getYSpan() * area.getZSpan(); - if (int_1 > Math.max(source.getServer().getGameRules().getInt(GameRules.RULE_COMMAND_MODIFICATION_BLOCK_LIMIT), CarpetSettings.fillLimit)) + final CommandSourceStack source = context.getSource(); + final CarpetScriptHost host = getHost(context); + final BoundingBox area = BoundingBox.fromCorners(a, b); + final CarpetExpression cexpr = new CarpetExpression(host.main, expr, source, origin); + final int int_1 = area.getXSpan() * area.getYSpan() * area.getZSpan(); + if (int_1 > Vanilla.MinecraftServer_getFillLimit(source.getServer())) { - Messenger.m(source, "r too many blocks to evaluate: "+ int_1); + Carpet.Messenger_message(source, "r too many blocks to evaluate: " + int_1); return 1; } boolean[][][] volume = new boolean[area.getXSpan()][area.getYSpan()][area.getZSpan()]; //X then Y then Z got messedup - BlockPos.MutableBlockPos mbpos = origin.mutable(); - ServerLevel world = source.getLevel(); + final BlockPos.MutableBlockPos mbpos = origin.mutable(); + final ServerLevel world = source.getLevel(); for (int x = area.minX(); x <= area.maxX(); x++) { @@ -587,26 +616,26 @@ private static int scriptFill(CommandContext context, BlockP { if (cexpr.fillAndScanCommand(host, x, y, z)) { - volume[x-area.minX()][y-area.minY()][z-area.minZ()]=true; + volume[x - area.minX()][y - area.minY()][z - area.minZ()] = true; } } - catch (CarpetExpressionException e) + catch (final CarpetExpressionException e) { host.handleErrorWithStack("Exception while filling the area", e); return 0; } - catch (ArithmeticException e) + catch (final ArithmeticException e) { } } } } - final int maxx = area.getXSpan()-1; - final int maxy = area.getYSpan()-1; - final int maxz = area.getZSpan()-1; + final int maxx = area.getXSpan() - 1; + final int maxy = area.getYSpan() - 1; + final int maxz = area.getZSpan() - 1; if ("outline".equalsIgnoreCase(mode)) { - boolean[][][] newVolume = new boolean[area.getXSpan()][area.getYSpan()][area.getZSpan()]; + final boolean[][][] newVolume = new boolean[area.getXSpan()][area.getYSpan()][area.getZSpan()]; for (int x = 0; x <= maxx; x++) { for (int y = 0; y <= maxy; y++) @@ -615,12 +644,12 @@ private static int scriptFill(CommandContext context, BlockP { if (volume[x][y][z]) { - if ( ( (x != 0 && !volume[x-1][y ][z ]) || - (x != maxx && !volume[x+1][y ][z ]) || - (y != 0 && !volume[x ][y-1][z ]) || - (y != maxy && !volume[x ][y+1][z ]) || - (z != 0 && !volume[x ][y ][z-1]) || - (z != maxz && !volume[x ][y ][z+1]) + if (((x != 0 && !volume[x - 1][y][z]) || + (x != maxx && !volume[x + 1][y][z]) || + (y != 0 && !volume[x][y - 1][z]) || + (y != maxy && !volume[x][y + 1][z]) || + (z != 0 && !volume[x][y][z - 1]) || + (z != maxz && !volume[x][y][z + 1]) )) { newVolume[x][y][z] = true; @@ -633,7 +662,7 @@ private static int scriptFill(CommandContext context, BlockP } int affected = 0; - CarpetSettings.impendingFillSkipUpdates.set(!CarpetSettings.fillUpdates); + Carpet.getImpendingFillSkipUpdates().set(!Carpet.getFillUpdates()); for (int x = 0; x <= maxx; x++) { for (int y = 0; y <= maxy; y++) @@ -642,14 +671,14 @@ private static int scriptFill(CommandContext context, BlockP { if (volume[x][y][z]) { - mbpos.set(x+area.minX(), y+area.minY(), z+area.minZ()); + mbpos.set(x + area.minX(), y + area.minY(), z + area.minZ()); if (replacement == null || replacement.test( - new BlockInWorld( world, mbpos, true))) + new BlockInWorld(world, mbpos, true))) { - BlockEntity tileentity = world.getBlockEntity(mbpos); + final BlockEntity tileentity = world.getBlockEntity(mbpos); Clearable.tryClear(tileentity); - - if (block.place(world, mbpos,2)) + + if (block.place(world, mbpos, 2)) { ++affected; } @@ -658,9 +687,9 @@ private static int scriptFill(CommandContext context, BlockP } } } - CarpetSettings.impendingFillSkipUpdates.set(false); + Carpet.getImpendingFillSkipUpdates().set(false); - if (CarpetSettings.fillUpdates && block != null) + if (Carpet.getFillUpdates() && block != null) { for (int x = 0; x <= maxx; x++) { @@ -670,15 +699,15 @@ private static int scriptFill(CommandContext context, BlockP { if (volume[x][y][z]) { - mbpos.set(x+area.minX(), y+area.minY(), z+area.minZ()); - Block blokc = world.getBlockState(mbpos).getBlock(); + mbpos.set(x + area.minX(), y + area.minY(), z + area.minZ()); + final Block blokc = world.getBlockState(mbpos).getBlock(); world.blockUpdated(mbpos, blokc); } } } } } - Messenger.m(source, "gi Affected "+affected+" blocks in "+area.getXSpan() * area.getYSpan() * area.getZSpan()+" block volume"); + Carpet.Messenger_message(source, "gi Affected " + affected + " blocks in " + area.getXSpan() * area.getYSpan() * area.getZSpan() + " block volume"); return 1; } } diff --git a/src/main/java/carpet/script/ScriptHost.java b/src/main/java/carpet/script/ScriptHost.java index 6737be00c2..7364eeb4ea 100644 --- a/src/main/java/carpet/script/ScriptHost.java +++ b/src/main/java/carpet/script/ScriptHost.java @@ -10,6 +10,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.nio.file.Path; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -52,6 +53,11 @@ public boolean resetRandom(final long aLong) return randomizers.remove(aLong) != null; } + public Path resolveScriptFile(final String suffix) + { + return scriptServer.resolveResource(suffix); + } + public static class ModuleData { Module parent; diff --git a/src/main/java/carpet/script/ScriptServer.java b/src/main/java/carpet/script/ScriptServer.java index 5d13d02430..c176c9b00a 100644 --- a/src/main/java/carpet/script/ScriptServer.java +++ b/src/main/java/carpet/script/ScriptServer.java @@ -1,12 +1,15 @@ package carpet.script; +import java.nio.file.Path; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import carpet.script.value.Value; // WIP -public class ScriptServer +public abstract class ScriptServer { public final Map systemGlobals = new ConcurrentHashMap<>(); + + public abstract Path resolveResource(final String suffix); } diff --git a/src/main/java/carpet/script/api/Auxiliary.java b/src/main/java/carpet/script/api/Auxiliary.java index 4faa92fb2d..00d273cf8e 100644 --- a/src/main/java/carpet/script/api/Auxiliary.java +++ b/src/main/java/carpet/script/api/Auxiliary.java @@ -1,10 +1,7 @@ package carpet.script.api; -import carpet.CarpetServer; -import carpet.fakes.MinecraftServerInterface; -import carpet.fakes.ThreadedAnvilChunkStorageInterface; -import carpet.helpers.FeatureGenerator; -import carpet.logging.HUDController; +import carpet.script.external.Vanilla; +import carpet.script.utils.FeatureGenerator; import carpet.script.argument.FileArgument; import carpet.script.CarpetContext; import carpet.script.CarpetEventServer; @@ -19,6 +16,7 @@ import carpet.script.exception.InternalExpressionException; import carpet.script.exception.ThrowStatement; import carpet.script.exception.Throwables; +import carpet.script.external.Carpet; import carpet.script.utils.SnoopyCommandSource; import carpet.script.utils.SystemInfo; import carpet.script.utils.InputValidator; @@ -36,7 +34,6 @@ import carpet.script.value.StringValue; import carpet.script.value.Value; import carpet.script.value.ValueConversions; -import carpet.utils.Messenger; import com.google.common.collect.Lists; import net.minecraft.SharedConstants; import net.minecraft.commands.CommandSourceStack; @@ -73,7 +70,6 @@ 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.Level; @@ -613,11 +609,11 @@ else if (!interactable && targetBlock == null) final Map map; if (actionString.equals("player_list_header")) { - map = HUDController.scarpet_headers; + map = Carpet.getScarpetHeaders(); } else { - map = HUDController.scarpet_footers; + map = Carpet.getScarpetFooters(); } final AtomicInteger total = new AtomicInteger(0); @@ -636,7 +632,7 @@ else if (!interactable && targetBlock == null) total.getAndIncrement(); }); } - HUDController.update_hud(((CarpetContext) c).server(), targetList); + Carpet.updateScarpetHUDs(((CarpetContext) c).server(), targetList); return NumericValue.of(total.get()); } final ClientboundSetTitlesAnimationPacket timesPacket; // TimesPacket @@ -678,7 +674,7 @@ else if (!interactable && targetBlock == null) { values = list.getItems(); } - return new FormattedTextValue(Messenger.c(values.stream().map(Value::getString).toArray())); + return new FormattedTextValue(Carpet.Messenger_compose(values.stream().map(Value::getString).toArray())); }); expression.addContextFunction("run", 1, (c, t, lv) -> @@ -750,7 +746,8 @@ else if (!interactable && targetBlock == null) expression.addContextFunction("game_tick", -1, (c, t, lv) -> { final CarpetContext cc = (CarpetContext) c; final MinecraftServer server = cc.server(); - if (CarpetServer.scriptServer == null) + final CarpetScriptServer scriptServer = (CarpetScriptServer) c.host.scriptServer(); + if (scriptServer == null) { return Value.NULL; } @@ -758,18 +755,18 @@ else if (!interactable && targetBlock == null) { throw new InternalExpressionException("Unable to run ticks from threads"); } - if (CarpetServer.scriptServer.tickDepth > 16) + if (scriptServer.tickDepth > 16) { throw new InternalExpressionException("'game_tick' function caused other 'game_tick' functions to run. You should not allow that."); } try { - CarpetServer.scriptServer.tickDepth++; - ((MinecraftServerInterface) server).forceTick(() -> System.nanoTime() - CarpetServer.scriptServer.tickStart < 50000000L); + scriptServer.tickDepth++; + Vanilla.MinecraftServer_forceTick(server, () -> System.nanoTime() - scriptServer.tickStart < 50000000L); if (lv.size() > 0) { final long ms_total = NumericValue.asNumber(lv.get(0)).getLong(); - final long end_expected = CarpetServer.scriptServer.tickStart + ms_total * 1000000L; + final long end_expected = scriptServer.tickStart + ms_total * 1000000L; final long wait = end_expected - System.nanoTime(); if (wait > 0L) { @@ -782,17 +779,17 @@ else if (!interactable && targetBlock == null) } } } - CarpetServer.scriptServer.tickStart = System.nanoTime(); // for the next tick + scriptServer.tickStart = System.nanoTime(); // for the next tick Thread.yield(); } finally { - if (CarpetServer.scriptServer != null) + if (scriptServer != null) { - CarpetServer.scriptServer.tickDepth--; + scriptServer.tickDepth--; } } - if (CarpetServer.scriptServer != null && CarpetServer.scriptServer.stopAll) + if (scriptServer != null && scriptServer.stopAll) { throw new ExitStatement(Value.NULL); } @@ -811,7 +808,7 @@ else if (!interactable && targetBlock == null) final BlockArgument locator = BlockArgument.findIn(cc, lv, 0); final BlockPos pos = locator.block.getPos(); final ServerLevel world = cc.level(); - ((ThreadedAnvilChunkStorageInterface) world.getChunkSource().chunkMap).relightChunk(new ChunkPos(pos)); + Vanilla.ChunkMap_relightChunk(world.getChunkSource().chunkMap, new ChunkPos(pos)); WorldTools.forceChunkUpdate(pos, world); return Value.TRUE; }); @@ -896,7 +893,7 @@ else if (!interactable && targetBlock == null) final long delay = NumericValue.asNumber(lv.get(0)).getLong(); final FunctionArgument functionArgument = FunctionArgument.findIn(c, expression.module, lv, 1, false, false); - CarpetServer.scriptServer.events.scheduleCall( + ((CarpetScriptServer)c.host.scriptServer()).events.scheduleCall( (CarpetContext) c, functionArgument.function, functionArgument.checkedArgs(), @@ -938,14 +935,14 @@ else if (lv.size() == 2) expression.addContextFunction("list_files", 2, (c, t, lv) -> { - final FileArgument fdesc = FileArgument.from(lv, true, FileArgument.Reason.READ); + final FileArgument fdesc = FileArgument.from(c, lv, true, FileArgument.Reason.READ); final Stream files = ((CarpetScriptHost) c.host).listFolder(fdesc); return files == null ? Value.NULL : ListValue.wrap(files.map(StringValue::of)); }); expression.addContextFunction("read_file", 2, (c, t, lv) -> { - final FileArgument fdesc = FileArgument.from(lv, false, FileArgument.Reason.READ); + final FileArgument fdesc = FileArgument.from(c, lv, false, FileArgument.Reason.READ); if (fdesc.type == FileArgument.Type.NBT) { final Tag state = ((CarpetScriptHost) c.host).readFileTag(fdesc); @@ -966,14 +963,14 @@ else if (fdesc.type == FileArgument.Type.JSON) }); expression.addContextFunction("delete_file", 2, (c, t, lv) -> - BooleanValue.of(((CarpetScriptHost) c.host).removeResourceFile(FileArgument.from(lv, false, FileArgument.Reason.DELETE)))); + BooleanValue.of(((CarpetScriptHost) c.host).removeResourceFile(FileArgument.from(c, lv, false, FileArgument.Reason.DELETE)))); expression.addContextFunction("write_file", -1, (c, t, lv) -> { if (lv.size() < 3) { throw new InternalExpressionException("'write_file' requires three or more arguments"); } - final FileArgument fdesc = FileArgument.from(lv, false, FileArgument.Reason.CREATE); + final FileArgument fdesc = FileArgument.from(c, lv, false, FileArgument.Reason.CREATE); final boolean success; if (fdesc.type == FileArgument.Type.NBT) @@ -1021,13 +1018,13 @@ else if (fdesc.type == FileArgument.Type.JSON) expression.addContextFunction("load_app_data", -1, (c, t, lv) -> { - FileArgument fdesc = new FileArgument(null, FileArgument.Type.NBT, null, false, false, FileArgument.Reason.READ); + FileArgument fdesc = new FileArgument(null, FileArgument.Type.NBT, null, false, false, FileArgument.Reason.READ, c.host); if (lv.size() > 0) { c.host.issueDeprecation("load_app_data(...) with arguments"); final String resource = recognizeResource(lv.get(0), false); final boolean shared = lv.size() > 1 && lv.get(1).getBoolean(); - fdesc = new FileArgument(resource, FileArgument.Type.NBT, null, false, shared, FileArgument.Reason.READ); + fdesc = new FileArgument(resource, FileArgument.Type.NBT, null, false, shared, FileArgument.Reason.READ, c.host); } return NBTSerializableValue.of(((CarpetScriptHost) c.host).readFileTag(fdesc)); }); @@ -1039,13 +1036,13 @@ else if (fdesc.type == FileArgument.Type.JSON) throw new InternalExpressionException("'store_app_data' needs NBT tag and an optional file"); } final Value val = lv.get(0); - FileArgument fdesc = new FileArgument(null, FileArgument.Type.NBT, null, false, false, FileArgument.Reason.CREATE); + FileArgument fdesc = new FileArgument(null, FileArgument.Type.NBT, null, false, false, FileArgument.Reason.CREATE, c.host); if (lv.size() > 1) { c.host.issueDeprecation("store_app_data(...) with more than one argument"); final String resource = recognizeResource(lv.get(1), false); final boolean shared = lv.size() > 2 && lv.get(2).getBoolean(); - fdesc = new FileArgument(resource, FileArgument.Type.NBT, null, false, shared, FileArgument.Reason.CREATE); + fdesc = new FileArgument(resource, FileArgument.Type.NBT, null, false, shared, FileArgument.Reason.CREATE, c.host); } final NBTSerializableValue tagValue = (val instanceof final NBTSerializableValue nbtsv) ? nbtsv diff --git a/src/main/java/carpet/script/api/Inventories.java b/src/main/java/carpet/script/api/Inventories.java index 93450aea85..f4aecd84c6 100644 --- a/src/main/java/carpet/script/api/Inventories.java +++ b/src/main/java/carpet/script/api/Inventories.java @@ -1,13 +1,12 @@ package carpet.script.api; -import carpet.fakes.IngredientInterface; -import carpet.fakes.RecipeManagerInterface; import carpet.script.CarpetContext; import carpet.script.Expression; import carpet.script.argument.FunctionArgument; import carpet.script.exception.InternalExpressionException; import carpet.script.exception.ThrowStatement; import carpet.script.exception.Throwables; +import carpet.script.external.Vanilla; import carpet.script.utils.InputValidator; import carpet.script.value.BooleanValue; import carpet.script.value.EntityValue; @@ -111,7 +110,7 @@ public static void apply(final Expression expression) final String recipeType = lv.get(1).getString(); type = cc.registry(Registries.RECIPE_TYPE).get(InputValidator.identifierOf(recipeType)); } - final List> recipes = ((RecipeManagerInterface) cc.server().getRecipeManager()).getAllMatching(type, InputValidator.identifierOf(recipeName), cc.registryAccess()); + final List> recipes = Vanilla.RecipeManager_getAllMatching(cc.server().getRecipeManager(), type, InputValidator.identifierOf(recipeName), cc.registryAccess()); if (recipes.isEmpty()) { return Value.NULL; @@ -126,7 +125,7 @@ public static void apply(final Expression expression) // I am flattening ingredient lists per slot. // consider recipe_data('wooden_sword','crafting') and ('iron_nugget', 'blasting') and notice difference // in depths of lists. - final List> stacks = ((IngredientInterface) (Object) ingredient).getRecipeStacks(); + final List> stacks = Vanilla.Ingredient_getRecipeStacks(ingredient); if (stacks.isEmpty()) { ingredientValue.add(Value.NULL); diff --git a/src/main/java/carpet/script/api/Monitoring.java b/src/main/java/carpet/script/api/Monitoring.java index e32674a23f..8acd1f93cf 100644 --- a/src/main/java/carpet/script/api/Monitoring.java +++ b/src/main/java/carpet/script/api/Monitoring.java @@ -3,13 +3,13 @@ import carpet.script.CarpetContext; import carpet.script.Expression; import carpet.script.exception.InternalExpressionException; +import carpet.script.external.Vanilla; import carpet.script.utils.SystemInfo; import carpet.script.value.ListValue; import carpet.script.value.MapValue; import carpet.script.value.NumericValue; import carpet.script.value.StringValue; import carpet.script.value.Value; -import carpet.utils.SpawnReporter; import it.unimi.dsi.fastutil.objects.Object2IntMap; import java.util.Arrays; @@ -64,7 +64,7 @@ public static void apply(final Expression expression) final Map retDict = new HashMap<>(); for (final MobCategory category : mobcounts.keySet()) { - final int currentCap = category.getMaxInstancesPerChunk() * chunks / SpawnReporter.MAGIC_NUMBER; + final int currentCap = category.getMaxInstancesPerChunk() * chunks / Vanilla.NaturalSpawner_MAGIC_NUMBER(); retDict.put( new StringValue(category.getSerializedName().toLowerCase(Locale.ROOT)), ListValue.of( @@ -82,7 +82,7 @@ public static void apply(final Expression expression) } return ListValue.of( new NumericValue(mobcounts.getInt(cat)), - new NumericValue((int) (cat.getMaxInstancesPerChunk() * chunks / SpawnReporter.MAGIC_NUMBER)) + new NumericValue((int) (cat.getMaxInstancesPerChunk() * chunks / Vanilla.NaturalSpawner_MAGIC_NUMBER())) ); }); } diff --git a/src/main/java/carpet/script/api/Scoreboards.java b/src/main/java/carpet/script/api/Scoreboards.java index f1030d43db..2055c8314d 100644 --- a/src/main/java/carpet/script/api/Scoreboards.java +++ b/src/main/java/carpet/script/api/Scoreboards.java @@ -1,12 +1,11 @@ package carpet.script.api; -import carpet.mixins.Objective_scarpetMixin; -import carpet.mixins.Scoreboard_scarpetMixin; import carpet.script.CarpetContext; import carpet.script.Expression; import carpet.script.exception.InternalExpressionException; import carpet.script.exception.ThrowStatement; import carpet.script.exception.Throwables; +import carpet.script.external.Vanilla; import carpet.script.utils.InputValidator; import carpet.script.value.BooleanValue; import carpet.script.value.EntityValue; @@ -164,9 +163,9 @@ public static void apply(final Expression expression) { return Value.NULL; } - ((Scoreboard_scarpetMixin) scoreboard).getObjectivesByCriterion().get(objective.getCriteria()).remove(objective); - ((Objective_scarpetMixin) objective).setCriterion(criterion); - (((Scoreboard_scarpetMixin) scoreboard).getObjectivesByCriterion().computeIfAbsent(criterion, (criterion1) -> Lists.newArrayList())).add(objective); + Vanilla.Scoreboard_getObjectivesByCriterion(scoreboard).get(objective.getCriteria()).remove(objective); + Vanilla.Objective_setCriterion(objective, criterion); + (Vanilla.Scoreboard_getObjectivesByCriterion(scoreboard).computeIfAbsent(criterion, (criterion1) -> Lists.newArrayList())).add(objective); scoreboard.onObjectiveAdded(objective); return Value.FALSE; } @@ -209,9 +208,9 @@ public static void apply(final Expression expression) { return Value.FALSE; } - ((Scoreboard_scarpetMixin) scoreboard).getObjectivesByCriterion().get(objective.getCriteria()).remove(objective); - ((Objective_scarpetMixin) objective).setCriterion(criterion); - (((Scoreboard_scarpetMixin) scoreboard).getObjectivesByCriterion().computeIfAbsent(criterion, (criterion1) -> Lists.newArrayList())).add(objective); + Vanilla.Scoreboard_getObjectivesByCriterion(scoreboard).get(objective.getCriteria()).remove(objective); + Vanilla.Objective_setCriterion(objective, criterion); + (Vanilla.Scoreboard_getObjectivesByCriterion(scoreboard).computeIfAbsent(criterion, (criterion1) -> Lists.newArrayList())).add(objective); scoreboard.onObjectiveAdded(objective); return Value.TRUE; } diff --git a/src/main/java/carpet/script/api/WorldAccess.java b/src/main/java/carpet/script/api/WorldAccess.java index 5900a3eeb5..4e7112d96d 100644 --- a/src/main/java/carpet/script/api/WorldAccess.java +++ b/src/main/java/carpet/script/api/WorldAccess.java @@ -1,21 +1,14 @@ package carpet.script.api; -import carpet.CarpetSettings; -import carpet.fakes.ChunkGeneratorInterface; -import carpet.fakes.ChunkTicketManagerInterface; -import carpet.fakes.RandomStateVisitorAccessor; -import carpet.fakes.ServerChunkManagerInterface; -import carpet.fakes.ServerWorldInterface; -import carpet.fakes.SpawnHelperInnerInterface; -import carpet.fakes.ThreadedAnvilChunkStorageInterface; -import carpet.helpers.FeatureGenerator; -import carpet.mixins.PoiRecord_scarpetMixin; import carpet.script.CarpetContext; +import carpet.script.CarpetScriptServer; import carpet.script.Context; import carpet.script.Expression; import carpet.script.Fluff; -import carpet.script.annotation.Locator; -import carpet.script.annotation.ScarpetFunction; +import carpet.script.external.Carpet; +import carpet.script.external.Vanilla; +import carpet.script.utils.FeatureGenerator; +import carpet.mixins.PoiRecord_scarpetMixin; import carpet.script.argument.BlockArgument; import carpet.script.argument.Vector3Argument; import carpet.script.exception.InternalExpressionException; @@ -34,7 +27,6 @@ import carpet.script.value.StringValue; import carpet.script.value.Value; import carpet.script.value.ValueConversions; -import carpet.utils.BlockInfo; import com.mojang.brigadier.exceptions.CommandSyntaxException; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; @@ -48,6 +40,11 @@ import net.minecraft.core.Registry; import net.minecraft.core.registries.Registries; import net.minecraft.resources.ResourceKey; +import net.minecraft.server.level.DistanceManager; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.Ticket; +import net.minecraft.server.level.TicketType; import net.minecraft.tags.TagKey; import net.minecraft.world.level.chunk.ChunkGenerator; import net.minecraft.world.level.chunk.PalettedContainer; @@ -59,7 +56,6 @@ import net.minecraft.world.level.levelgen.structure.Structure; import net.minecraft.world.level.levelgen.structure.StructureType; import org.apache.commons.lang3.tuple.Pair; -import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Arrays; @@ -82,10 +78,6 @@ import net.minecraft.nbt.Tag; import net.minecraft.network.protocol.game.ClientboundExplodePacket; import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.server.level.Ticket; -import net.minecraft.server.level.TicketType; import net.minecraft.sounds.SoundSource; import net.minecraft.util.Mth; import net.minecraft.util.SortedArraySet; @@ -135,6 +127,8 @@ import net.minecraft.world.level.storage.ServerLevelData; import net.minecraft.world.phys.Vec3; +import javax.annotation.Nullable; + import static carpet.script.utils.WorldTools.canHasChunk; public class WorldAccess @@ -256,7 +250,7 @@ private static void BooYah(final ServerLevel level) { synchronized (level) { - ((ChunkGeneratorInterface) level.getChunkSource().getGenerator()).initStrongholds(level); + level.getChunkSource().getGeneratorState().ensureStructuresGenerated(); } } @@ -444,7 +438,7 @@ else if (!("any".equals(statusString))) } final Value weather = lv.get(0); - final ServerLevelData worldProperties = ((ServerWorldInterface) world).getWorldPropertiesCM(); + final ServerLevelData worldProperties = Vanilla.ServerLevel_getWorldProperties(world); if (lv.size() == 1) { return new NumericValue(switch (weather.getString().toLowerCase(Locale.ROOT)) @@ -644,10 +638,9 @@ else if (!("any".equals(statusString))) expression.addContextFunction("chunk_tickets", -1, (c, t, lv) -> { final ServerLevel world = ((CarpetContext) c).level(); - final Long2ObjectOpenHashMap>> levelTickets = ( - (ChunkTicketManagerInterface) ((ServerChunkManagerInterface) world.getChunkSource()) - .getCMTicketManager() - ).getTicketsByPosition(); + DistanceManager foo = Vanilla.ServerChunkCache_getCMTicketManager(world.getChunkSource()); + final Long2ObjectOpenHashMap>> levelTickets = Vanilla.ChunkTicketManager_getTicketsByPosition(foo); + final List res = new ArrayList<>(); if (lv.size() == 0) { @@ -723,22 +716,23 @@ else if (!("any".equals(statusString))) // lazy cause its parked execution expression.addLazyFunction("without_updates", 1, (c, t, lv) -> { - final boolean previous = CarpetSettings.impendingFillSkipUpdates.get(); - if (previous) + if (Carpet.getImpendingFillSkipUpdates().get()) { return lv.get(0); } final Value[] result = new Value[]{Value.NULL}; ((CarpetContext) c).server().executeBlocking(() -> { + final ThreadLocal skipUpdates = Carpet.getImpendingFillSkipUpdates(); + final boolean previous = skipUpdates.get(); try { - CarpetSettings.impendingFillSkipUpdates.set(true); + skipUpdates.set(true); result[0] = lv.get(0).evalValue(c, t); } finally { - CarpetSettings.impendingFillSkipUpdates.set(false); + skipUpdates.set(previous); } }); return (cc, tt) -> result[0]; @@ -1080,7 +1074,9 @@ else if (enVal instanceof final EntityValue ev) final Explosion explosion = new Explosion(cc.level(), source, null, null, pos.x, pos.y, pos.z, powah, createFire, mode) { @Override - public @Nullable LivingEntity getIndirectSourceEntity() + @Nullable + public + LivingEntity getIndirectSourceEntity() { return theAttacker; } @@ -1168,15 +1164,15 @@ else if (enVal instanceof final EntityValue ev) expression.addContextFunction("block_sound", -1, (c, t, lv) -> stateStringQuery(c, "block_sound", lv, (s, p) -> - BlockInfo.soundName.get(s.getSoundType()))); + Carpet.getSoundTypeNames().get(s.getSoundType()))); expression.addContextFunction("material", -1, (c, t, lv) -> stateStringQuery(c, "material", lv, (s, p) -> - BlockInfo.materialName.get(s.getMaterial()))); + Carpet.getMaterialNames().get(s.getMaterial()))); expression.addContextFunction("map_colour", -1, (c, t, lv) -> stateStringQuery(c, "map_colour", lv, (s, p) -> - BlockInfo.mapColourName.get(s.getMapColor(((CarpetContext) c).level(), p)))); + Carpet.getMapColorNames().get(s.getMapColor(((CarpetContext) c).level(), p)))); // Deprecated for block_state() @@ -1485,7 +1481,7 @@ else if (enVal instanceof final EntityValue ev) } catch (final NullPointerException npe) { - CarpetSettings.LOG.error("Failed to detect structure: " + reg.getKey(str)); + CarpetScriptServer.LOG.error("Failed to detect structure: " + reg.getKey(str)); start = null; } @@ -1649,7 +1645,7 @@ else if (enVal instanceof final EntityValue ev) final Value[] result = new Value[]{Value.NULL}; ((CarpetContext) c).server().executeBlocking(() -> { - final Map report = ((ThreadedAnvilChunkStorageInterface) world.getChunkSource().chunkMap).regenerateChunkRegion(requestedChunks); + final Map report = Vanilla.ChunkMap_regenerateChunkRegion(world.getChunkSource().chunkMap, requestedChunks); result[0] = MapValue.wrap(report.entrySet().stream().collect(Collectors.toMap( e -> new StringValue(e.getKey()), e -> new NumericValue(e.getValue()) @@ -1677,9 +1673,7 @@ else if (enVal instanceof final EntityValue ev) required_charge = NumericValue.asNumber(lv.get(locator.offset)).getDouble(); } final NaturalSpawner.SpawnState charger = cc.level().getChunkSource().getLastSpawnState(); - return charger == null ? Value.NULL : new NumericValue( - ((SpawnHelperInnerInterface) charger).getPotentialCalculator(). - getPotentialEnergyChange(pos, required_charge) + return charger == null ? Value.NULL : new NumericValue(Vanilla.SpawnState_getPotentialCalculator(charger).getPotentialEnergyChange(pos, required_charge) ); }); @@ -1809,7 +1803,7 @@ public static double sampleNoise(final NoiseRouter router, final ServerLevel lev noiseBasedChunkGenerator.generatorSettings().value(), level.registryAccess().lookupOrThrow(Registries.NOISE), level.getSeed() ); - DensityFunction.Visitor visitor = ((RandomStateVisitorAccessor) (Object) randomState).getVisitor(); + DensityFunction.Visitor visitor = Vanilla.RandomState_getVisitor(randomState); return densityFunction.mapAll(visitor); } diff --git a/src/main/java/carpet/script/argument/FileArgument.java b/src/main/java/carpet/script/argument/FileArgument.java index 835c61ab1d..57e75f88d6 100644 --- a/src/main/java/carpet/script/argument/FileArgument.java +++ b/src/main/java/carpet/script/argument/FileArgument.java @@ -1,8 +1,9 @@ package carpet.script.argument; -import carpet.CarpetServer; import carpet.script.CarpetScriptServer; +import carpet.script.Context; import carpet.script.Module; +import carpet.script.ScriptHost; import carpet.script.exception.InternalExpressionException; import carpet.script.exception.ThrowStatement; import carpet.script.exception.Throwables; @@ -18,7 +19,6 @@ import net.minecraft.nbt.NbtIo; import net.minecraft.nbt.Tag; import net.minecraft.nbt.TagTypes; -import net.minecraft.world.level.storage.LevelResource; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.tuple.Pair; @@ -58,6 +58,7 @@ public class FileArgument public Reason reason; private FileSystem zfs; private Path zipPath; + private ScriptHost host; public static final Object writeIOSync = new Object(); @@ -103,7 +104,7 @@ public enum Reason READ, CREATE, DELETE } - public FileArgument(final String resource, final Type type, final String zipContainer, final boolean isFolder, final boolean isShared, final Reason reason) + public FileArgument(final String resource, final Type type, final String zipContainer, final boolean isFolder, final boolean isShared, final Reason reason, final ScriptHost host) { this.resource = resource; this.type = type; @@ -113,6 +114,7 @@ public FileArgument(final String resource, final Type type, final String zipCont this.reason = reason; this.zfs = null; this.zipPath = null; + this.host = host; } @Override @@ -121,7 +123,7 @@ public String toString() return "path: " + resource + " zip: " + zipContainer + " type: " + type.id + " folder: " + isFolder + " shared: " + isShared + " reason: " + reason.toString(); } - public static FileArgument from(final List lv, final boolean isFolder, final Reason reason) + public static FileArgument from(final Context context, final List lv, final boolean isFolder, final Reason reason) { if (lv.size() < 2) { @@ -140,14 +142,14 @@ public static FileArgument from(final List lv, final boolean isFolder, fi { throw new InternalExpressionException("Folder types are no supported for this IO function"); } - return new FileArgument(resource.getLeft(), type, resource.getRight(), isFolder, shared, reason); + return new FileArgument(resource.getLeft(), type, resource.getRight(), isFolder, shared, reason, context.host); } - public static FileArgument resourceFromPath(final String path, final Reason reason, final boolean shared) + public static FileArgument resourceFromPath(final ScriptHost host, final String path, final Reason reason, final boolean shared) { final Pair resource = recognizeResource(path, false, Type.ANY); - return new FileArgument(resource.getLeft(), Type.ANY, resource.getRight(), false, shared, reason); + return new FileArgument(resource.getLeft(), Type.ANY, resource.getRight(), false, shared, reason, host); } public static Pair recognizeResource(final String origfile, final boolean isFolder, final Type type) @@ -196,11 +198,7 @@ public static Pair recognizeResource(final String origfile, fina private Path resolve(final String suffix) { - if (CarpetServer.minecraft_server == null) - { - throw new InternalExpressionException("Accessing world files without server running"); - } - return CarpetServer.minecraft_server.getWorldPath(LevelResource.ROOT).resolve("scripts/" + suffix); + return host.resolveScriptFile(suffix); } private Path toPath(final Module module) diff --git a/src/main/java/carpet/script/command/CommandArgument.java b/src/main/java/carpet/script/command/CommandArgument.java index f0619c7430..e6d2a30782 100644 --- a/src/main/java/carpet/script/command/CommandArgument.java +++ b/src/main/java/carpet/script/command/CommandArgument.java @@ -1,9 +1,10 @@ package carpet.script.command; -import carpet.CarpetServer; -import carpet.fakes.BlockStateArgumentInterface; import carpet.script.CarpetScriptHost; +import carpet.script.CarpetScriptServer; import carpet.script.argument.FunctionArgument; +import carpet.script.external.Carpet; +import carpet.script.external.Vanilla; import carpet.script.value.BlockValue; import carpet.script.value.BooleanValue; import carpet.script.value.EntityValue; @@ -15,8 +16,6 @@ import carpet.script.value.StringValue; import carpet.script.value.Value; import carpet.script.value.ValueConversions; -import carpet.utils.CarpetProfiler; -import com.mojang.brigadier.exceptions.DynamicCommandExceptionType; import com.mojang.datafixers.util.Either; import it.unimi.dsi.fastutil.ints.IntOpenHashSet; import it.unimi.dsi.fastutil.ints.IntSet; @@ -134,7 +133,7 @@ public static CommandSyntaxException error(final String text) new VanillaUnconfigurableArgument("block", BlockStateArgument::block, (c, p) -> { BlockInput result = BlockStateArgument.getBlock(c, p); - return new BlockValue(result.getState(), c.getSource().getLevel(), null, ((BlockStateArgumentInterface) result).getCMTag()); + return new BlockValue(result.getState(), c.getSource().getLevel(), null, Vanilla.BlockInput_getTag(result)); }, param -> (ctx, builder) -> ctx.getArgument(param, BlockStateArgument.class).listSuggestions(ctx, builder) ), @@ -318,8 +317,9 @@ public static CommandArgument getTypeForArgument(final String argument, final Ca return argument(param, arg.getArgumentType(host)); } final String hostName = host.getName(); + final CarpetScriptServer scriptServer = host.scriptServer(); return argument(param, arg.getArgumentType(host)).suggests((ctx, b) -> { - final CarpetScriptHost cHost = CarpetServer.scriptServer.modules.get(hostName).retrieveOwnForExecution(ctx.getSource()); + final CarpetScriptHost cHost = scriptServer.modules.get(hostName).retrieveOwnForExecution(ctx.getSource()); return arg.suggest(ctx, b, cHost); }); } @@ -426,7 +426,7 @@ protected Collection getOptions(final CommandContext { if (customSuggester != null) { - final CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet command", CarpetProfiler.TYPE.GENERAL); + final Runnable currentSection = Carpet.startProfilerSection("Scarpet command"); final Map params = new HashMap<>(); for (final ParsedCommandNode pnode : context.getNodes()) { @@ -445,7 +445,7 @@ protected Collection getOptions(final CommandContext throw error("Custom suggester should return a list of options" + " for custom type " + suffix); } final Collection res = ((ListValue) response).getItems().stream().map(Value::getString).collect(Collectors.toList()); - CarpetProfiler.end_current_section(currentSection); + currentSection.run(); return res; } return needsMatching ? examples : Collections.singletonList("... " + getTypeSuffix()); diff --git a/src/main/java/carpet/script/exception/CarpetExpressionException.java b/src/main/java/carpet/script/exception/CarpetExpressionException.java index 4ca5d115b6..8e54175471 100644 --- a/src/main/java/carpet/script/exception/CarpetExpressionException.java +++ b/src/main/java/carpet/script/exception/CarpetExpressionException.java @@ -1,7 +1,7 @@ package carpet.script.exception; +import carpet.script.external.Carpet; import carpet.script.value.FunctionValue; -import carpet.utils.Messenger; import java.util.List; @@ -23,7 +23,7 @@ public void printStack(final CommandSourceStack source) { for (final FunctionValue fun : stack) { - Messenger.m(source, "e ... in " + fun.fullName(), "e /" + (fun.getToken().lineno + 1) + ":" + (fun.getToken().linepos + 1)); + Carpet.Messenger_message(source, "e ... in " + fun.fullName(), "e /" + (fun.getToken().lineno + 1) + ":" + (fun.getToken().linepos + 1)); } } } diff --git a/src/main/java/carpet/script/exception/ExpressionException.java b/src/main/java/carpet/script/exception/ExpressionException.java index 7104858976..6a2cb1f4a2 100644 --- a/src/main/java/carpet/script/exception/ExpressionException.java +++ b/src/main/java/carpet/script/exception/ExpressionException.java @@ -3,8 +3,8 @@ import carpet.script.Context; import carpet.script.Expression; import carpet.script.Tokenizer; +import carpet.script.external.Carpet; import carpet.script.value.FunctionValue; -import carpet.utils.Messenger; import java.util.ArrayList; import java.util.Collections; @@ -22,7 +22,7 @@ public class ExpressionException extends StacklessRuntimeException implements Re public static void prepareForDoom() { - Messenger.c("foo bar"); + Carpet.Messenger_compose("foo bar"); } public ExpressionException(final Context c, final Expression e, final String message) diff --git a/src/main/java/carpet/script/exception/StacklessRuntimeException.java b/src/main/java/carpet/script/exception/StacklessRuntimeException.java index 5f0f473e34..1d6b65049b 100644 --- a/src/main/java/carpet/script/exception/StacklessRuntimeException.java +++ b/src/main/java/carpet/script/exception/StacklessRuntimeException.java @@ -3,7 +3,7 @@ /** * A type of {@link RuntimeException} that doesn't spend time producing and filling a stacktrace */ -abstract class StacklessRuntimeException extends RuntimeException +public abstract class StacklessRuntimeException extends RuntimeException { public StacklessRuntimeException() { diff --git a/src/main/java/carpet/script/external/Carpet.java b/src/main/java/carpet/script/external/Carpet.java new file mode 100644 index 0000000000..1afd982aff --- /dev/null +++ b/src/main/java/carpet/script/external/Carpet.java @@ -0,0 +1,181 @@ +package carpet.script.external; + +import carpet.CarpetServer; +import carpet.CarpetSettings; +import carpet.api.settings.CarpetRule; +import carpet.api.settings.RuleHelper; +import carpet.api.settings.SettingsManager; +import carpet.api.settings.Validator; +import carpet.fakes.MinecraftServerInterface; +import carpet.helpers.TickSpeed; +import carpet.logging.HUDController; +import carpet.network.ServerNetworkHandler; +import carpet.patches.EntityPlayerMPFake; +import carpet.script.CarpetExpression; +import carpet.script.CarpetScriptServer; +import carpet.script.utils.AppStoreManager; +import carpet.script.value.MapValue; +import carpet.script.value.StringValue; +import carpet.utils.BlockInfo; +import carpet.utils.CarpetProfiler; +import carpet.utils.Messenger; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.network.chat.Component; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.block.SoundType; +import net.minecraft.world.level.material.Material; +import net.minecraft.world.level.material.MaterialColor; + +import javax.annotation.Nullable; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +public class Carpet +{ + public static Map getScarpetHeaders() + { + return HUDController.scarpet_headers; + } + + public static Map getScarpetFooters() + { + return HUDController.scarpet_footers; + } + + public static void updateScarpetHUDs(final MinecraftServer server, final List players) + { + HUDController.update_hud(server, players); + } + + public static Component Messenger_compose(final Object... messages) + { + return Messenger.c(messages); + } + + public static void Messenger_message(final CommandSourceStack source, final Object... messages) + { + Messenger.m(source, messages); + } + + public static ThreadLocal getImpendingFillSkipUpdates() + { + return CarpetSettings.impendingFillSkipUpdates; + } + + public static Map getSoundTypeNames() + { + return BlockInfo.soundName; + } + + public static Map getMapColorNames() + { + return BlockInfo.mapColourName; + } + + public static Map getMaterialNames() + { + return BlockInfo.materialName; + } + + public static Runnable startProfilerSection(final String name) + { + final CarpetProfiler.ProfilerToken token = CarpetProfiler.start_section(null, name, CarpetProfiler.TYPE.GENERAL); + return () -> CarpetProfiler.end_current_section(token); + } + + public static void MinecraftServer_addScriptServer(final MinecraftServer server, final CarpetScriptServer scriptServer) + { + ((MinecraftServerInterface) server).addScriptServer(scriptServer); + } + + public static boolean isValidCarpetPlayer(final ServerPlayer player) + { + return ServerNetworkHandler.isValidCarpetPlayer(player); + } + + public static String getPlayerStatus(final ServerPlayer player) + { + return ServerNetworkHandler.getPlayerStatus(player); + } + + public static MapValue getAllCarpetRules() + { + final Collection> rules = CarpetServer.settingsManager.getCarpetRules(); + final MapValue carpetRules = new MapValue(Collections.emptyList()); + rules.forEach(rule -> carpetRules.put(new StringValue(rule.name()), new StringValue(RuleHelper.toRuleString(rule.value())))); + CarpetServer.extensions.forEach(e -> { + final SettingsManager manager = e.extensionSettingsManager(); + if (manager == null) + { + return; + } + manager.getCarpetRules().forEach(rule -> carpetRules.put(new StringValue(manager.identifier() + ":" + rule.name()), new StringValue(RuleHelper.toRuleString(rule.value())))); + }); + return carpetRules; + } + + public static String getCarpetVersion() + { + return CarpetSettings.carpetVersion; + } + + @Nullable + public static String isModdedPlayer(final Player p) + { + if (p instanceof final EntityPlayerMPFake fake) + { + return fake.isAShadow ? "shadow" : "fake"; + } + return null; + } + + public static boolean isTickProcessingPaused() + { + return !TickSpeed.process_entities; + } + + public static void handleExtensionsAPI(final CarpetExpression expression) + { + CarpetServer.extensions.forEach(e -> e.scarpetApi(expression)); + } + + public static boolean getFillUpdates() + { + return CarpetSettings.fillUpdates; + } + + public static class ScarpetAppStoreValidator extends Validator + { + @Override + public String validate(final CommandSourceStack source, final CarpetRule currentRule, String newValue, final String stringInput) + { + if (newValue.equals(currentRule.value())) + { + // Don't refresh the local repo if it's the same (world change), helps preventing hitting rate limits from github when + // getting suggestions. Pending is a way to invalidate the cache when it gets old, and investigating api usage further + return newValue; + } + if (newValue.equalsIgnoreCase("none")) + { + AppStoreManager.setScarpetRepoLink(null); + return newValue; + } + if (newValue.endsWith("/")) + { + newValue = newValue.replaceAll("/$", ""); + } + AppStoreManager.setScarpetRepoLink("https://api.github.com/repos/" + newValue + "/"); + return newValue; + } + + @Override + public String description() + { + return "Appstore link should point to a valid github repository"; + } + } +} diff --git a/src/main/java/carpet/script/external/Vanilla.java b/src/main/java/carpet/script/external/Vanilla.java new file mode 100644 index 0000000000..6458520071 --- /dev/null +++ b/src/main/java/carpet/script/external/Vanilla.java @@ -0,0 +1,364 @@ +package carpet.script.external; + +import carpet.CarpetSettings; +import carpet.fakes.BiomeInterface; +import carpet.fakes.BlockPredicateInterface; +import carpet.fakes.BlockStateArgumentInterface; +import carpet.fakes.ChunkTicketManagerInterface; +import carpet.fakes.CommandDispatcherInterface; +import carpet.fakes.EntityInterface; +import carpet.fakes.IngredientInterface; +import carpet.fakes.InventoryBearerInterface; +import carpet.fakes.ItemEntityInterface; +import carpet.fakes.LivingEntityInterface; +import carpet.fakes.MinecraftServerInterface; +import carpet.fakes.MobEntityInterface; +import carpet.fakes.RandomStateVisitorAccessor; +import carpet.fakes.RecipeManagerInterface; +import carpet.fakes.AbstractContainerMenuInterface; +import carpet.fakes.ServerChunkManagerInterface; +import carpet.fakes.ServerPlayerInterface; +import carpet.fakes.ServerPlayerInteractionManagerInterface; +import carpet.fakes.ServerWorldInterface; +import carpet.fakes.SpawnHelperInnerInterface; +import carpet.fakes.ThreadedAnvilChunkStorageInterface; +import carpet.mixins.Objective_scarpetMixin; +import carpet.mixins.Scoreboard_scarpetMixin; +import carpet.network.ServerNetworkHandler; +import carpet.script.CarpetScriptServer; +import carpet.script.EntityEventsGroup; +import carpet.script.value.MapValue; +import carpet.script.value.StringValue; +import carpet.script.value.Value; +import carpet.utils.CommandHelper; +import carpet.utils.SpawnReporter; +import com.mojang.brigadier.CommandDispatcher; +import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; +import net.fabricmc.loader.api.FabricLoader; +import net.fabricmc.loader.api.ModContainer; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.arguments.blocks.BlockInput; +import net.minecraft.core.BlockPos; +import net.minecraft.core.RegistryAccess; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.Tag; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ChunkMap; +import net.minecraft.server.level.DistanceManager; +import net.minecraft.server.level.ServerChunkCache; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ServerPlayerGameMode; +import net.minecraft.server.level.Ticket; +import net.minecraft.tags.TagKey; +import net.minecraft.util.SortedArraySet; +import net.minecraft.world.Container; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.goal.Goal; +import net.minecraft.world.entity.ai.goal.GoalSelector; +import net.minecraft.world.entity.animal.horse.AbstractHorse; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.inventory.DataSlot; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.Ingredient; +import net.minecraft.world.item.crafting.Recipe; +import net.minecraft.world.item.crafting.RecipeManager; +import net.minecraft.world.item.crafting.RecipeType; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.GameRules; +import net.minecraft.world.level.NaturalSpawner; +import net.minecraft.world.level.PotentialCalculator; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.pattern.BlockInWorld; +import net.minecraft.world.level.levelgen.DensityFunction; +import net.minecraft.world.level.levelgen.RandomState; +import net.minecraft.world.level.storage.LevelStorageSource; +import net.minecraft.world.level.storage.ServerLevelData; +import net.minecraft.world.scores.Objective; +import net.minecraft.world.scores.Scoreboard; +import net.minecraft.world.scores.criteria.ObjectiveCriteria; + +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.BooleanSupplier; +import java.util.function.Predicate; + +public class Vanilla +{ + public static void MinecraftServer_forceTick(final MinecraftServer server, final BooleanSupplier sup) + { + ((MinecraftServerInterface) server).forceTick(sup); + } + + public static void ChunkMap_relightChunk(final ChunkMap chunkMap, final ChunkPos pos) + { + ((ThreadedAnvilChunkStorageInterface) chunkMap).relightChunk(pos); + } + + public static Map ChunkMap_regenerateChunkRegion(final ChunkMap chunkMap, final List requestedChunks) + { + return ((ThreadedAnvilChunkStorageInterface) chunkMap).regenerateChunkRegion(requestedChunks); + } + + public static List> Ingredient_getRecipeStacks(final Ingredient ingredient) + { + return ((IngredientInterface) (Object) ingredient).getRecipeStacks(); + } + + public static List> RecipeManager_getAllMatching(final RecipeManager recipeManager, final RecipeType type, final ResourceLocation output, final RegistryAccess registryAccess) + { + return ((RecipeManagerInterface) recipeManager).getAllMatching(type, output, registryAccess); + } + + public static int NaturalSpawner_MAGIC_NUMBER() + { + return SpawnReporter.MAGIC_NUMBER; + } + + public static PotentialCalculator SpawnState_getPotentialCalculator(final NaturalSpawner.SpawnState spawnState) + { + return ((SpawnHelperInnerInterface) spawnState).getPotentialCalculator(); + } + + public static void Objective_setCriterion(final Objective objective, final ObjectiveCriteria criterion) + { + ((Objective_scarpetMixin) objective).setCriterion(criterion); + } + + public static Map> Scoreboard_getObjectivesByCriterion(final Scoreboard scoreboard) + { + return ((Scoreboard_scarpetMixin) scoreboard).getObjectivesByCriterion(); + } + + public static ServerLevelData ServerLevel_getWorldProperties(final ServerLevel world) + { + return ((ServerWorldInterface) world).getWorldPropertiesCM(); + } + + public static DistanceManager ServerChunkCache_getCMTicketManager(final ServerChunkCache chunkCache) + { + return ((ServerChunkManagerInterface) chunkCache).getCMTicketManager(); + } + + public static Long2ObjectOpenHashMap>> ChunkTicketManager_getTicketsByPosition(final DistanceManager ticketManager) + { + return ((ChunkTicketManagerInterface) ticketManager).getTicketsByPosition(); + } + + public static DensityFunction.Visitor RandomState_getVisitor(final RandomState randomState) + { + return ((RandomStateVisitorAccessor) (Object) randomState).getVisitor(); + } + + public static CompoundTag BlockInput_getTag(final BlockInput blockInput) + { + return ((BlockStateArgumentInterface) blockInput).getCMTag(); + } + + public static CarpetScriptServer MinecraftServer_getScriptServer(final MinecraftServer server) + { + return ((MinecraftServerInterface) server).getScriptServer(); + } + + public static Biome.ClimateSettings Biome_getClimateSettings(final Biome biome) + { + return ((BiomeInterface) (Object) biome).getClimateSettings(); + } + + public static ThreadLocal skipGenerationChecks(final ServerLevel level) + { // not sure does vanilla care at all - needs checking + return CarpetSettings.skipGenerationChecks; + } + + public static void sendScarpetShapesDataToPlayer(final ServerPlayer player, final Tag data) + { // dont forget to add the packet to vanilla packed handler and call ShapesRenderer.addShape to handle on client + ServerNetworkHandler.sendCustomCommand(player, "scShapes", data); + } + + public static int MinecraftServer_getRunPermissionLevel(final MinecraftServer server) + { + return CarpetSettings.runPermissionLevel; + } + + public static String MinecraftServer_getReleaseTarget(final MinecraftServer server) + { + return CarpetSettings.releaseTarget; + } + + public static boolean isDevelopmentEnvironment() + { + return FabricLoader.getInstance().isDevelopmentEnvironment(); + } + + public static MapValue getServerMods(final MinecraftServer server) + { + final Map ret = new HashMap<>(); + for (final ModContainer mod : FabricLoader.getInstance().getAllMods()) + { + ret.put(new StringValue(mod.getMetadata().getId()), new StringValue(mod.getMetadata().getVersion().getFriendlyString())); + } + return MapValue.wrap(ret); + } + + public static LevelStorageSource.LevelStorageAccess MinecraftServer_storageSource(final MinecraftServer server) + { + return ((MinecraftServerInterface) server).getCMSession(); + } + + public static BlockPos ServerPlayerGameMode_getCurrentBlockPosition(final ServerPlayerGameMode gameMode) + { + return ((ServerPlayerInteractionManagerInterface) gameMode).getCurrentBreakingBlock(); + } + + public static int ServerPlayerGameMode_getCurrentBlockBreakingProgress(final ServerPlayerGameMode gameMode) + { + return ((ServerPlayerInteractionManagerInterface) gameMode).getCurrentBlockBreakingProgress(); + } + + public static void ServerPlayerGameMode_setBlockBreakingProgress(final ServerPlayerGameMode gameMode, final int progress) + { + ((ServerPlayerInteractionManagerInterface) gameMode).setBlockBreakingProgress(progress); + } + + public static boolean ServerPlayer_isInvalidEntityObject(final ServerPlayer player) + { + return ((ServerPlayerInterface) player).isInvalidEntityObject(); + } + + public static String ServerPlayer_getLanguage(final ServerPlayer player) + { + return ((ServerPlayerInterface) player).getLanguage(); + } + + public static GoalSelector Mob_getAI(final Mob mob, final boolean target) + { + return ((MobEntityInterface) mob).getAI(target); + } + + public static Map Mob_getTemporaryTasks(final Mob mob) + { + return ((MobEntityInterface) mob).getTemporaryTasks(); + } + + public static void Mob_setPersistence(final Mob mob, final boolean what) + { + ((MobEntityInterface) mob).setPersistence(what); + } + + public static EntityEventsGroup Entity_getEventContainer(final Entity entity) + { + return ((EntityInterface) entity).getEventContainer(); + } + + public static boolean Entity_isPermanentVehicle(final Entity entity) + { + return ((EntityInterface) entity).isPermanentVehicle(); + } + + public static void Entity_setPermanentVehicle(final Entity entity, final boolean permanent) + { + ((EntityInterface) entity).setPermanentVehicle(permanent); + } + + public static int Entity_getPortalTimer(final Entity entity) + { + return ((EntityInterface) entity).getPortalTimer(); + } + + public static void Entity_setPortalTimer(final Entity entity, final int amount) + { + ((EntityInterface) entity).setPortalTimer(amount); + } + + public static int Entity_getPublicNetherPortalCooldown(final Entity entity) + { + return ((EntityInterface) entity).getPublicNetherPortalCooldown(); + } + + public static void Entity_setPublicNetherPortalCooldown(final Entity entity, final int what) + { + ((EntityInterface) entity).setPublicNetherPortalCooldown(what); + } + + public static int ItemEntity_getPickupDelay(final ItemEntity entity) + { + return ((ItemEntityInterface) entity).getPickupDelayCM(); + } + + public static boolean LivingEntity_isJumping(final LivingEntity entity) + { + return ((LivingEntityInterface) entity).isJumpingCM(); + } + + public static void LivingEntity_setJumping(final LivingEntity entity) + { + ((LivingEntityInterface) entity).doJumpCM(); + } + + public static Container AbstractHorse_getInventory(final AbstractHorse horse) + { + return ((InventoryBearerInterface) horse).getCMInventory(); + } + + public static DataSlot AbstractContainerMenu_getDataSlot(final AbstractContainerMenu handler, final int index) + { + return ((AbstractContainerMenuInterface) handler).getDataSlot(index); + } + + public static void CommandDispatcher_unregisterCommand(final CommandDispatcher dispatcher, final String name) + { + ((CommandDispatcherInterface) dispatcher).carpet$unregister(name); + } + + public static boolean MinecraftServer_doScriptsAutoload(final MinecraftServer server) + { + return CarpetSettings.scriptsAutoload; + } + + public static void MinecraftServer_notifyPlayersCommandsChanged(final MinecraftServer server) + { + CommandHelper.notifyPlayersCommandsChanged(server); + } + + public static boolean ScriptServer_scriptOptimizations(final MinecraftServer scriptServer) + { + return CarpetSettings.scriptsOptimization; + } + + public static boolean ScriptServer_scriptDebugging(final MinecraftServer server) + { + return CarpetSettings.scriptsDebugging; + } + + public static boolean ServerPlayer_canScriptACE(final CommandSourceStack player) + { + return CommandHelper.canUseCommand(player, CarpetSettings.commandScriptACE); + } + + public static boolean ServerPlayer_canScriptGeneral(final CommandSourceStack player) + { + return CommandHelper.canUseCommand(player, CarpetSettings.commandScript); + } + + public static int MinecraftServer_getFillLimit(final MinecraftServer server) + { + return Math.max(server.getGameRules().getInt(GameRules.RULE_COMMAND_MODIFICATION_BLOCK_LIMIT), CarpetSettings.fillLimit); + } + + public record BlockPredicatePayload(BlockState state, TagKey tagKey, Map properties, CompoundTag tag) { + public static BlockPredicatePayload of(final Predicate blockPredicate) + { + final BlockPredicateInterface predicateData = (BlockPredicateInterface) blockPredicate; + return new BlockPredicatePayload(predicateData.getCMBlockState(), predicateData.getCMBlockTagKey(), predicateData.getCMProperties(), predicateData.getCMDataTag()); + } + } + +} diff --git a/src/main/java/carpet/script/external/VanillaClient.java b/src/main/java/carpet/script/external/VanillaClient.java new file mode 100644 index 0000000000..5c7f1a17d4 --- /dev/null +++ b/src/main/java/carpet/script/external/VanillaClient.java @@ -0,0 +1,13 @@ +package carpet.script.external; + +import carpet.mixins.ShulkerBoxAccessMixin; +import net.minecraft.client.model.ShulkerModel; +import net.minecraft.client.renderer.blockentity.BlockEntityRenderer; +import net.minecraft.world.level.block.entity.ShulkerBoxBlockEntity; + +public class VanillaClient +{ + public static ShulkerModel ShulkerBoxRenderer_model(final BlockEntityRenderer shulkerBoxRenderer) { + return ((ShulkerBoxAccessMixin)shulkerBoxRenderer).getModel(); + } +} diff --git a/src/main/java/carpet/script/external/package-info.java b/src/main/java/carpet/script/external/package-info.java new file mode 100644 index 0000000000..2e80a8175d --- /dev/null +++ b/src/main/java/carpet/script/external/package-info.java @@ -0,0 +1,8 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package carpet.script.external; + +import net.minecraft.FieldsAreNonnullByDefault; +import net.minecraft.MethodsReturnNonnullByDefault; +import javax.annotation.ParametersAreNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/carpet/script/utils/AppStoreManager.java b/src/main/java/carpet/script/utils/AppStoreManager.java index 1f3314760f..ab5b0bf0a7 100644 --- a/src/main/java/carpet/script/utils/AppStoreManager.java +++ b/src/main/java/carpet/script/utils/AppStoreManager.java @@ -1,15 +1,13 @@ package carpet.script.utils; -import carpet.CarpetServer; -import carpet.api.settings.CarpetRule; -import carpet.api.settings.Validator; import carpet.script.CarpetScriptHost; import carpet.script.CarpetScriptServer; import carpet.script.exception.InternalExpressionException; +import carpet.script.external.Carpet; +import carpet.script.external.Vanilla; import carpet.script.value.MapValue; import carpet.script.value.StringValue; import carpet.script.value.Value; -import carpet.utils.Messenger; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; @@ -36,6 +34,8 @@ import org.apache.commons.io.IOUtils; +import javax.annotation.Nullable; + /** * A class used to save scarpet app store scripts to disk */ @@ -52,40 +52,15 @@ public class AppStoreManager */ private static String scarpetRepoLink = "https://api.github.com/repos/gnembon/scarpet/contents/programs/"; - private record AppInfo(String name, String url, StoreNode source) + public static void setScarpetRepoLink(@Nullable final String link) { + APP_STORE_ROOT = AppStoreManager.StoreNode.folder(null, ""); + scarpetRepoLink = link; } - public static class ScarpetAppStoreValidator extends Validator - { - @Override - public String validate(final CommandSourceStack source, final CarpetRule currentRule, String newValue, final String stringInput) - { - if (newValue.equals(currentRule.value())) - { - // Don't refresh the local repo if it's the same (world change), helps preventing hitting rate limits from github when - // getting suggestions. Pending is a way to invalidate the cache when it gets old, and investigating api usage further - return newValue; - } - APP_STORE_ROOT = StoreNode.folder(null, ""); - if (newValue.equalsIgnoreCase("none")) - { - scarpetRepoLink = null; - return newValue; - } - if (newValue.endsWith("/")) - { - newValue = newValue.replaceAll("/$", ""); - } - scarpetRepoLink = "https://api.github.com/repos/" + newValue + "/"; - return newValue; - } - @Override - public String description() - { - return "Appstore link should point to a valid github repository"; - } + private record AppInfo(String name, String url, StoreNode source) + { } public static class StoreNode @@ -291,13 +266,13 @@ private static int downloadScript(final CommandSourceStack source, final String } catch (final IOException e) { - throw new CommandRuntimeException(Messenger.c("rb Failed to obtain app file content: " + e.getMessage())); + throw new CommandRuntimeException(Carpet.Messenger_compose("rb Failed to obtain app file content: " + e.getMessage())); } if (!saveScriptToFile(source, path, nodeInfo.name(), code, false, useTrash)) { return 0; } - final boolean success = CarpetServer.scriptServer.addScriptHost(source, nodeInfo.name().replaceFirst("\\.sc$", ""), null, true, false, false, nodeInfo.source()); + final boolean success = Vanilla.MinecraftServer_getScriptServer(source.getServer()).addScriptHost(source, nodeInfo.name().replaceFirst("\\.sc$", ""), null, true, false, false, nodeInfo.source()); return success ? 1 : 0; } @@ -328,7 +303,7 @@ public static AppInfo getFileNodeFrom(final StoreNode start, final String appPat } catch (final IOException e) { - throw new CommandRuntimeException(Messenger.c("rb '" + appPath + "' is not a valid path to a scarpet app: " + e.getMessage())); + throw new CommandRuntimeException(Carpet.Messenger_compose("rb '" + appPath + "' is not a valid path to a scarpet app: " + e.getMessage())); } } @@ -363,7 +338,7 @@ public static boolean saveScriptToFile(final CommandSourceStack source, final St } Files.move(scriptLocation, trashPath); } - Messenger.m(source, String.format("gi Note: replaced existing app '%s'" + (useTrash ? " (old moved to /trash folder)" : ""), appFileName)); + Carpet.Messenger_message(source, String.format("gi Note: replaced existing app '%s'" + (useTrash ? " (old moved to /trash folder)" : ""), appFileName)); } final BufferedWriter writer = Files.newBufferedWriter(scriptLocation); writer.write(code); @@ -371,7 +346,7 @@ public static boolean saveScriptToFile(final CommandSourceStack source, final St } catch (final IOException e) { - Messenger.m(source, "r Error while downloading app: " + e); + Carpet.Messenger_message(source, "r Error while downloading app: " + e); CarpetScriptServer.LOG.warn("Error while downloading app", e); return false; } diff --git a/src/main/java/carpet/script/utils/BiomeInfo.java b/src/main/java/carpet/script/utils/BiomeInfo.java index 5870848c02..d132239826 100644 --- a/src/main/java/carpet/script/utils/BiomeInfo.java +++ b/src/main/java/carpet/script/utils/BiomeInfo.java @@ -1,6 +1,6 @@ package carpet.script.utils; -import carpet.fakes.BiomeInterface; +import carpet.script.external.Vanilla; import carpet.script.value.ListValue; import carpet.script.value.NumericValue; import carpet.script.value.StringValue; @@ -30,7 +30,7 @@ public class BiomeInfo 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(((BiomeInterface) (Object) b).getClimateSettings().downfall())); + put("humidity", (w, b) -> NumericValue.of(Vanilla.Biome_getClimateSettings(b).downfall())); put("precipitation", (w, b) -> StringValue.of(b.getPrecipitationAt(new BlockPos(0, w.getSeaLevel(), 0)).name().toLowerCase(Locale.ROOT))); put("features", (w, b) -> { final Registry> registry = w.registryAccess().registryOrThrow(Registries.CONFIGURED_FEATURE); diff --git a/src/main/java/carpet/script/utils/EntityTools.java b/src/main/java/carpet/script/utils/EntityTools.java new file mode 100644 index 0000000000..c3a636604e --- /dev/null +++ b/src/main/java/carpet/script/utils/EntityTools.java @@ -0,0 +1,34 @@ +package carpet.script.utils; + +import net.minecraft.core.BlockPos; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.phys.Vec3; + +public class EntityTools +{ + /** + * Not a replacement for living entity jump() - this barely is to allow other entities that can't jump in vanilla to 'jump' + * + * @param e + */ + public static void genericJump(final Entity e) + { + if (!e.isOnGround() && !e.isInWaterOrBubble() && !e.isInLava()) + { + return; + } + final float m = e.level.getBlockState(e.blockPosition()).getBlock().getJumpFactor(); + final float g = e.level.getBlockState(new BlockPos(e.getX(), e.getBoundingBox().minY - 0.5000001D, e.getZ())).getBlock().getJumpFactor(); + final float jumpVelocityMultiplier = m == 1.0D ? g : m; + final float jumpStrength = (0.42F * jumpVelocityMultiplier); + final Vec3 vec3d = e.getDeltaMovement(); + e.setDeltaMovement(vec3d.x, jumpStrength, vec3d.z); + if (e.isSprinting()) + { + final float u = e.getYRot() * 0.017453292F; // yaw + e.setDeltaMovement(e.getDeltaMovement().add((-Mth.sin(g) * 0.2F), 0.0D, (Mth.cos(u) * 0.2F))); + } + e.hasImpulse = true; + } +} diff --git a/src/main/java/carpet/script/utils/Experimental.java b/src/main/java/carpet/script/utils/Experimental.java index b8ab2e7935..79d4283485 100644 --- a/src/main/java/carpet/script/utils/Experimental.java +++ b/src/main/java/carpet/script/utils/Experimental.java @@ -1,7 +1,7 @@ package carpet.script.utils; -import carpet.fakes.MinecraftServerInterface; -import carpet.fakes.ServerWorldInterface; +//import carpet.fakes.MinecraftServerInterface; +//import carpet.fakes.ServerWorldInterface; import carpet.script.CarpetScriptServer; import carpet.script.value.ListValue; import carpet.script.value.Value; diff --git a/src/main/java/carpet/helpers/FeatureGenerator.java b/src/main/java/carpet/script/utils/FeatureGenerator.java similarity index 67% rename from src/main/java/carpet/helpers/FeatureGenerator.java rename to src/main/java/carpet/script/utils/FeatureGenerator.java index 8ba56c4092..8252489ccb 100644 --- a/src/main/java/carpet/helpers/FeatureGenerator.java +++ b/src/main/java/carpet/script/utils/FeatureGenerator.java @@ -1,9 +1,8 @@ -package carpet.helpers; +package carpet.script.utils; -import carpet.CarpetSettings; -import carpet.fakes.ChunkGeneratorInterface; +import carpet.script.CarpetScriptServer; +import carpet.script.external.Vanilla; import com.google.common.collect.ImmutableList; -import com.mojang.datafixers.util.Pair; import java.util.HashMap; import java.util.List; @@ -13,19 +12,19 @@ import java.util.OptionalInt; import java.util.function.Function; +import com.mojang.datafixers.util.Pair; import net.minecraft.core.BlockPos; import net.minecraft.core.Holder; import net.minecraft.core.HolderGetter; import net.minecraft.core.HolderSet; -import net.minecraft.core.QuartPos; import net.minecraft.core.Registry; import net.minecraft.core.RegistryAccess; -import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.Registries; import net.minecraft.data.worldgen.Pools; import net.minecraft.data.worldgen.ProcessorLists; import net.minecraft.data.worldgen.placement.PlacementUtils; import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.level.ServerChunkCache; import net.minecraft.server.level.ServerLevel; import net.minecraft.tags.BiomeTags; import net.minecraft.util.RandomSource; @@ -35,6 +34,7 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.chunk.ChunkGenerator; +import net.minecraft.world.level.chunk.ChunkGeneratorStructureState; import net.minecraft.world.level.levelgen.GenerationStep; import net.minecraft.world.level.levelgen.RandomState; import net.minecraft.world.level.levelgen.VerticalAnchor; @@ -63,75 +63,88 @@ import net.minecraft.world.level.levelgen.structure.structures.JigsawStructure; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureProcessorList; +import javax.annotation.Nullable; + public class FeatureGenerator { - synchronized public static Boolean plop(String featureName, ServerLevel world, BlockPos pos) + @Nullable + public static synchronized Boolean plop(final String featureName, final ServerLevel world, final BlockPos pos) { - Function custom = featureMap.get(featureName); + final Function custom = featureMap.get(featureName); if (custom != null) { return custom.apply(world).plop(world, pos); } - ResourceLocation id = new ResourceLocation(featureName); - Structure structure = world.registryAccess().registryOrThrow(Registries.STRUCTURE).get(id); + final ResourceLocation id = new ResourceLocation(featureName); + final Structure structure = world.registryAccess().registryOrThrow(Registries.STRUCTURE).get(id); if (structure != null) { - return plopAnywhere( structure, world, pos, world.getChunkSource().getGenerator(), false); + return plopAnywhere(structure, world, pos, world.getChunkSource().getGenerator(), false); } - ConfiguredFeature configuredFeature = world.registryAccess().registryOrThrow(Registries.CONFIGURED_FEATURE).get(id); + final ConfiguredFeature configuredFeature = world.registryAccess().registryOrThrow(Registries.CONFIGURED_FEATURE).get(id); if (configuredFeature != null) { - CarpetSettings.skipGenerationChecks.set(true); + final ThreadLocal checks = Vanilla.skipGenerationChecks(world); + checks.set(true); try { return configuredFeature.place(world, world.getChunkSource().getGenerator(), world.random, pos); } finally { - CarpetSettings.skipGenerationChecks.set(false); + checks.set(false); } } - Optional> structureType = world.registryAccess().registryOrThrow(Registries.STRUCTURE_TYPE).getOptional(id); + final Optional> structureType = world.registryAccess().registryOrThrow(Registries.STRUCTURE_TYPE).getOptional(id); if (structureType.isPresent()) { - Structure configuredStandard = getDefaultFeature(structureType.get(), world, pos); + final Structure configuredStandard = getDefaultFeature(structureType.get(), world, pos); if (configuredStandard != null) + { return plopAnywhere(configuredStandard, world, pos, world.getChunkSource().getGenerator(), false); + } } - Feature feature = world.registryAccess().registryOrThrow(Registries.FEATURE).get(id); + final Feature feature = world.registryAccess().registryOrThrow(Registries.FEATURE).get(id); if (feature != null) { - ConfiguredFeature configuredStandard = getDefaultFeature(feature, world, pos, true); + final ConfiguredFeature configuredStandard = getDefaultFeature(feature, world, pos, true); if (configuredStandard != null) { - CarpetSettings.skipGenerationChecks.set(true); + final ThreadLocal checks = Vanilla.skipGenerationChecks(world); + checks.set(true); try { return configuredStandard.place(world, world.getChunkSource().getGenerator(), world.random, pos); } finally { - CarpetSettings.skipGenerationChecks.set(false); + checks.set(false); } } } return null; } - public static Structure resolveConfiguredStructure(String name, ServerLevel world, BlockPos pos) + public static Structure resolveConfiguredStructure(final String name, final ServerLevel world, final BlockPos pos) { - ResourceLocation id = new ResourceLocation(name); - Structure configuredStructureFeature = world.registryAccess().registryOrThrow(Registries.STRUCTURE).get(id); - if (configuredStructureFeature != null) return configuredStructureFeature; - StructureType structureFeature = world.registryAccess().registryOrThrow(Registries.STRUCTURE_TYPE).get(id); - if (structureFeature == null) return null; + final ResourceLocation id = new ResourceLocation(name); + final Structure configuredStructureFeature = world.registryAccess().registryOrThrow(Registries.STRUCTURE).get(id); + if (configuredStructureFeature != null) + { + return configuredStructureFeature; + } + final StructureType structureFeature = world.registryAccess().registryOrThrow(Registries.STRUCTURE_TYPE).get(id); + if (structureFeature == null) + { + return null; + } return getDefaultFeature(structureFeature, world, pos); } - synchronized public static Boolean plopGrid(Structure structureFeature, ServerLevel world, BlockPos pos) + public static synchronized Boolean plopGrid(final Structure structureFeature, final ServerLevel world, final BlockPos pos) { - return plopAnywhere( structureFeature, world, pos, world.getChunkSource().getGenerator(), true); + return plopAnywhere(structureFeature, world, pos, world.getChunkSource().getGenerator(), true); } @FunctionalInterface @@ -139,85 +152,102 @@ private interface Thing { Boolean plop(ServerLevel world, BlockPos pos); } - private static Thing simplePlop(ConfiguredFeature feature) + + private static Thing simplePlop(final ConfiguredFeature feature) { return (w, p) -> { - CarpetSettings.skipGenerationChecks.set(true); + final ThreadLocal checks = Vanilla.skipGenerationChecks(w); + checks.set(true); try { return feature.place(w, w.getChunkSource().getGenerator(), w.random, p); } finally { - CarpetSettings.skipGenerationChecks.set(false); + checks.set(false); } }; } - private static > Thing simplePlop(F feature, FC config) + private static > Thing simplePlop(final F feature, final FC config) { return simplePlop(new ConfiguredFeature<>(feature, config)); } - private static Thing simpleTree(TreeConfiguration config) + private static Thing simpleTree(final TreeConfiguration config) { //config.ignoreFluidCheck(); return simplePlop(new ConfiguredFeature<>(Feature.TREE, config)); } - private static Thing spawnCustomStructure(Structure structure) + private static Thing spawnCustomStructure(final Structure structure) { - return setupCustomStructure(structure,false); + return setupCustomStructure(structure, false); } - private static Thing setupCustomStructure(Structure structure, boolean wireOnly) - { + + private static Thing setupCustomStructure(final Structure structure, final boolean wireOnly) + { return (w, p) -> plopAnywhere(structure, w, p, w.getChunkSource().getGenerator(), wireOnly); } - private static Structure getDefaultFeature(StructureType structure, ServerLevel world, BlockPos pos) + private static Structure getDefaultFeature(final StructureType structure, final ServerLevel world, final BlockPos pos) { // would be nice to have a way to grab structures of this type for position // TODO allow old types, like vaillage, or bastion - Holder existingBiome = world.getBiome(pos); + final Holder existingBiome = world.getBiome(pos); Structure result = null; - for (Structure confstr : world.registryAccess().registryOrThrow(Registries.STRUCTURE).entrySet().stream(). - filter(cS -> cS.getValue().type() == structure).map(Map.Entry::getValue).toList()) + for (final Structure confstr : world.registryAccess().registryOrThrow(Registries.STRUCTURE).entrySet().stream(). + filter(cS -> cS.getValue().type() == structure).map(Map.Entry::getValue).toList()) { result = confstr; - if (confstr.biomes().contains(existingBiome)) return result; + if (confstr.biomes().contains(existingBiome)) + { + return result; + } } return result; } - private static ConfiguredFeature getDefaultFeature(Feature feature, ServerLevel world, BlockPos pos, boolean tryHard) + private static ConfiguredFeature getDefaultFeature(final Feature feature, final ServerLevel world, final BlockPos pos, final boolean tryHard) { - List> configuredStepFeatures = world.getBiome(pos).value().getGenerationSettings().features(); - for (HolderSet step: configuredStepFeatures) - for (Holder provider: step) + final List> configuredStepFeatures = world.getBiome(pos).value().getGenerationSettings().features(); + for (final HolderSet step : configuredStepFeatures) + { + for (final Holder provider : step) { if (provider.value().feature().value().feature() == feature) + { return provider.value().feature().value(); + } } - if (!tryHard) return null; + } + if (!tryHard) + { + return null; + } return world.registryAccess().registryOrThrow(Registries.CONFIGURED_FEATURE).entrySet().stream(). filter(cS -> cS.getValue().feature() == feature). findFirst().map(Map.Entry::getValue).orElse(null); } - public static StructureStart shouldStructureStartAt(ServerLevel world, BlockPos pos, Structure structure, boolean computeBox) + public static StructureStart shouldStructureStartAt(final ServerLevel world, final BlockPos pos, final Structure structure, final boolean computeBox) { - //long seed = world.getSeed(); - RandomState seed = world.getChunkSource().randomState(); - ChunkGenerator generator = world.getChunkSource().getGenerator(); - ChunkGeneratorInterface cgi = (ChunkGeneratorInterface) generator; - List structureConfig = cgi.getPlacementsForFeatureCM(world, structure); - ChunkPos chunkPos = new ChunkPos(pos); - boolean couldPlace = structureConfig.stream().anyMatch(p -> p.isStructureChunk(world.getChunkSource().getGeneratorState(), chunkPos.x, chunkPos.z)); - if (!couldPlace) return null; + final ServerChunkCache chunkSource = world.getChunkSource(); + final RandomState seed = chunkSource.randomState(); + final ChunkGenerator generator = chunkSource.getGenerator(); + final ChunkGeneratorStructureState structureState = chunkSource.getGeneratorState(); + final List structureConfig = structureState.getPlacementsForStructure(Holder.direct(structure)); + final ChunkPos chunkPos = new ChunkPos(pos); + final boolean couldPlace = structureConfig.stream().anyMatch(p -> p.isStructureChunk(structureState, chunkPos.x, chunkPos.z)); + if (!couldPlace) + { + return null; + } final HolderSet structureBiomes = structure.biomes(); - if (!computeBox) { + if (!computeBox) + { //Holder genBiome = generator.getBiomeSource().getNoiseBiome(QuartPos.fromBlock(pos.getX()), QuartPos.fromBlock(pos.getY()), QuartPos.fromBlock(pos.getZ()), seed.sampler()); if (structure.findValidGenerationPoint(new Structure.GenerationContext( world.registryAccess(), generator, generator.getBiomeSource(), @@ -227,26 +257,30 @@ public static StructureStart shouldStructureSta return StructureStart.INVALID_START; } } - else { + else + { final StructureStart filledStructure = structure.generate( world.registryAccess(), generator, generator.getBiomeSource(), seed, world.getStructureManager(), world.getSeed(), chunkPos, 0, world, structureBiomes::contains); - if (filledStructure != null && filledStructure.isValid()) { + if (filledStructure != null && filledStructure.isValid()) + { return filledStructure; } } return null; } - private static TreeConfiguration.TreeConfigurationBuilder createTree(Block block, Block block2, int i, int j, int k, int l) { + private static TreeConfiguration.TreeConfigurationBuilder createTree(final Block block, final Block block2, final int i, final int j, final int k, final int l) + { return new TreeConfiguration.TreeConfigurationBuilder(BlockStateProvider.simple(block), new StraightTrunkPlacer(i, j, k), BlockStateProvider.simple(block2), new BlobFoliagePlacer(ConstantInt.of(l), ConstantInt.of(0), 3), new TwoLayersFeatureSize(1, 0, 1)); } - public static final Map> featureMap = new HashMap<>() {{ + public static final Map> featureMap = new HashMap<>() + {{ - put("oak_bees", l -> simpleTree( createTree(Blocks.OAK_LOG, Blocks.OAK_LEAVES, 4, 2, 0, 2).ignoreVines().decorators(List.of(new BeehiveDecorator(1.00F))).build())); - put("fancy_oak_bees", l -> simpleTree( (new TreeConfiguration.TreeConfigurationBuilder(BlockStateProvider.simple(Blocks.OAK_LOG), new FancyTrunkPlacer(3, 11, 0), BlockStateProvider.simple(Blocks.OAK_LEAVES), new FancyFoliagePlacer(ConstantInt.of(2), ConstantInt.of(4), 4), new TwoLayersFeatureSize(0, 0, 0, OptionalInt.of(4)))).ignoreVines().decorators(List.of(new BeehiveDecorator(1.00F))).build())); - put("birch_bees", l -> simpleTree( createTree(Blocks.BIRCH_LOG, Blocks.BIRCH_LEAVES, 5, 2, 0, 2).ignoreVines().decorators(List.of(new BeehiveDecorator(1.00F))).build())); + put("oak_bees", l -> simpleTree(createTree(Blocks.OAK_LOG, Blocks.OAK_LEAVES, 4, 2, 0, 2).ignoreVines().decorators(List.of(new BeehiveDecorator(1.00F))).build())); + put("fancy_oak_bees", l -> simpleTree((new TreeConfiguration.TreeConfigurationBuilder(BlockStateProvider.simple(Blocks.OAK_LOG), new FancyTrunkPlacer(3, 11, 0), BlockStateProvider.simple(Blocks.OAK_LEAVES), new FancyFoliagePlacer(ConstantInt.of(2), ConstantInt.of(4), 4), new TwoLayersFeatureSize(0, 0, 0, OptionalInt.of(4)))).ignoreVines().decorators(List.of(new BeehiveDecorator(1.00F))).build())); + put("birch_bees", l -> simpleTree(createTree(Blocks.BIRCH_LOG, Blocks.BIRCH_LEAVES, 5, 2, 0, 2).ignoreVines().decorators(List.of(new BeehiveDecorator(1.00F))).build())); put("coral_tree", l -> simplePlop(Feature.CORAL_TREE, FeatureConfiguration.NONE)); @@ -258,7 +292,7 @@ private static TreeConfiguration.TreeConfigurationBuilder createTree(Block block PlacementUtils.inlinePlaced(Feature.CORAL_MUSHROOM, FeatureConfiguration.NONE) )))); put("bastion_remnant_units", l -> { - RegistryAccess regs = l.registryAccess(); + final RegistryAccess regs = l.registryAccess(); final HolderGetter processorLists = regs.lookupOrThrow(Registries.PROCESSOR_LIST); final Holder bastionGenericDegradation = processorLists.getOrThrow(ProcessorLists.BASTION_GENERIC_DEGRADATION); @@ -288,7 +322,7 @@ private static TreeConfiguration.TreeConfigurationBuilder createTree(Block block ); }); put("bastion_remnant_hoglin_stable", l -> { - RegistryAccess regs = l.registryAccess(); + final RegistryAccess regs = l.registryAccess(); final HolderGetter processorLists = regs.lookupOrThrow(Registries.PROCESSOR_LIST); final Holder bastionGenericDegradation = processorLists.getOrThrow(ProcessorLists.BASTION_GENERIC_DEGRADATION); @@ -317,7 +351,7 @@ private static TreeConfiguration.TreeConfigurationBuilder createTree(Block block ); }); put("bastion_remnant_treasure", l -> { - RegistryAccess regs = l.registryAccess(); + final RegistryAccess regs = l.registryAccess(); final HolderGetter processorLists = regs.lookupOrThrow(Registries.PROCESSOR_LIST); final Holder bastionGenericDegradation = processorLists.getOrThrow(ProcessorLists.BASTION_GENERIC_DEGRADATION); @@ -346,7 +380,7 @@ private static TreeConfiguration.TreeConfigurationBuilder createTree(Block block ); }); put("bastion_remnant_bridge", l -> { - RegistryAccess regs = l.registryAccess(); + final RegistryAccess regs = l.registryAccess(); final HolderGetter processorLists = regs.lookupOrThrow(Registries.PROCESSOR_LIST); final Holder bastionGenericDegradation = processorLists.getOrThrow(ProcessorLists.BASTION_GENERIC_DEGRADATION); @@ -377,28 +411,29 @@ private static TreeConfiguration.TreeConfigurationBuilder createTree(Block block }}; - public static boolean plopAnywhere(Structure structure, ServerLevel world, BlockPos pos, ChunkGenerator generator, boolean wireOnly) + public static boolean plopAnywhere(final Structure structure, final ServerLevel world, final BlockPos pos, final ChunkGenerator generator, final boolean wireOnly) { - CarpetSettings.skipGenerationChecks.set(true); + final ThreadLocal checks = Vanilla.skipGenerationChecks(world); + checks.set(true); try { - StructureStart start = structure.generate(world.registryAccess(), generator, generator.getBiomeSource(), world.getChunkSource().randomState(), world.getStructureManager(), world.getSeed(), new ChunkPos(pos), 0, world, b -> true ); + final StructureStart start = structure.generate(world.registryAccess(), generator, generator.getBiomeSource(), world.getChunkSource().randomState(), world.getStructureManager(), world.getSeed(), new ChunkPos(pos), 0, world, b -> true); if (start == StructureStart.INVALID_START) { return false; } - RandomSource rand = RandomSource.create(world.getRandom().nextInt()); - int j = pos.getX() >> 4; - int k = pos.getZ() >> 4; - long chId = ChunkPos.asLong(j, k); + final RandomSource rand = RandomSource.create(world.getRandom().nextInt()); + final int j = pos.getX() >> 4; + final int k = pos.getZ() >> 4; + final long chId = ChunkPos.asLong(j, k); world.getChunk(j, k).setStartForStructure(structure, start); world.getChunk(j, k).addReferenceForStructure(structure, chId); - BoundingBox box = start.getBoundingBox(); + final BoundingBox box = start.getBoundingBox(); if (!wireOnly) { - Registry registry3 = world.registryAccess().registryOrThrow(Registries.STRUCTURE); + final Registry registry3 = world.registryAccess().registryOrThrow(Registries.STRUCTURE); world.setCurrentlyGenerating(() -> { Objects.requireNonNull(structure); return registry3.getResourceKey(structure).map(Object::toString).orElseGet(structure::toString); @@ -406,29 +441,32 @@ public static boolean plopAnywhere(Structure structure, ServerLevel world, Block start.placeInChunk(world, world.structureManager(), generator, rand, box, new ChunkPos(j, k)); } //structurestart.notifyPostProcessAt(new ChunkPos(j, k)); - int i = Math.max(box.getXSpan(),box.getZSpan())/16+1; + final int i = Math.max(box.getXSpan(), box.getZSpan()) / 16 + 1; //int i = getRadius(); for (int k1 = j - i; k1 <= j + i; ++k1) { for (int l1 = k - i; l1 <= k + i; ++l1) { - if (k1 == j && l1 == k) continue; - if (box.intersects(k1<<4, l1<<4, (k1<<4) + 15, (l1<<4) + 15)) + if (k1 == j && l1 == k) + { + continue; + } + if (box.intersects(k1 << 4, l1 << 4, (k1 << 4) + 15, (l1 << 4) + 15)) { world.getChunk(k1, l1).addReferenceForStructure(structure, chId); } } } } - catch (Exception booboo) + catch (final Exception booboo) { - CarpetSettings.LOG.error("Unknown Exception while plopping structure: "+booboo, booboo); + CarpetScriptServer.LOG.error("Unknown Exception while plopping structure: " + booboo, booboo); return false; } finally { - CarpetSettings.skipGenerationChecks.set(false); + checks.set(false); } return true; } diff --git a/src/main/java/carpet/script/utils/ParticleParser.java b/src/main/java/carpet/script/utils/ParticleParser.java new file mode 100644 index 0000000000..6ca6b55837 --- /dev/null +++ b/src/main/java/carpet/script/utils/ParticleParser.java @@ -0,0 +1,42 @@ +package carpet.script.utils; + +import com.mojang.brigadier.StringReader; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import net.minecraft.commands.arguments.ParticleArgument; +import net.minecraft.core.HolderLookup; +import net.minecraft.core.particles.ParticleOptions; +import net.minecraft.core.particles.ParticleType; + +import java.util.HashMap; +import java.util.Map; + +public class ParticleParser +{ + private static final Map particleCache = new HashMap<>(); // we reset this on reloads, but probably need something better + + private static ParticleOptions parseParticle(final String name, final HolderLookup> lookup) + { + try + { + return ParticleArgument.readParticle(new StringReader(name), lookup); + } + catch (final CommandSyntaxException e) + { + throw new IllegalArgumentException("No such particle: " + name); + } + } + + public static ParticleOptions getEffect(final String name, final HolderLookup> lookup) + { + if (name == null) + { + return null; + } + return particleCache.computeIfAbsent(name, particle -> parseParticle(particle, lookup)); + } + + public static void resetCache() + { + particleCache.clear(); + } +} diff --git a/src/main/java/carpet/script/utils/ShapeDispatcher.java b/src/main/java/carpet/script/utils/ShapeDispatcher.java index 7bf3ffa0fd..308b7cb90c 100644 --- a/src/main/java/carpet/script/utils/ShapeDispatcher.java +++ b/src/main/java/carpet/script/utils/ShapeDispatcher.java @@ -1,11 +1,11 @@ package carpet.script.utils; -import carpet.CarpetSettings; -import carpet.helpers.ParticleDisplay; -import carpet.network.ServerNetworkHandler; +import carpet.script.CarpetScriptServer; import carpet.script.exception.InternalExpressionException; import carpet.script.exception.ThrowStatement; import carpet.script.exception.Throwables; +import carpet.script.external.Carpet; +import carpet.script.external.Vanilla; import carpet.script.language.Sys; import carpet.script.utils.shapes.ShapeDirection; import carpet.script.value.AbstractListValue; @@ -149,7 +149,7 @@ public static void sendShape(final Collection players, final List< final List alternativePlayers = new ArrayList<>(); for (final ServerPlayer player : players) { - (ServerNetworkHandler.isValidCarpetPlayer(player) ? clientPlayers : alternativePlayers).add(player); + (Carpet.isValidCarpetPlayer(player) ? clientPlayers : alternativePlayers).add(player); } if (!clientPlayers.isEmpty()) { @@ -162,14 +162,14 @@ public static void sendShape(final Collection players, final List< { tagcount = 0; final Tag finalTag = tag; - clientPlayers.forEach(p -> ServerNetworkHandler.sendCustomCommand(p, "scShapes", finalTag)); + clientPlayers.forEach(p -> Vanilla.sendScarpetShapesDataToPlayer(p, finalTag)); tag = new ListTag(); } } final Tag finalTag = tag; if (!tag.isEmpty()) { - clientPlayers.forEach(p -> ServerNetworkHandler.sendCustomCommand(p, "scShapes", finalTag)); + clientPlayers.forEach(p -> Vanilla.sendScarpetShapesDataToPlayer(p, finalTag)); } } if (!alternativePlayers.isEmpty()) @@ -184,7 +184,7 @@ public static ParticleOptions getParticleData(final String name, final RegistryA { try { - return ParticleDisplay.getEffect(name, regs.lookupOrThrow(Registries.PARTICLE_TYPE)); + return ParticleParser.getEffect(name, regs.lookupOrThrow(Registries.PARTICLE_TYPE)); } catch (final IllegalArgumentException e) { @@ -239,7 +239,7 @@ public static ExpiringShape fromTag(final CompoundTag tag, final Level level) final Param decoder = Param.of.get(key); if (decoder == null) { - CarpetSettings.LOG.info("Unknown parameter for shape: " + key); + CarpetScriptServer.LOG.info("Unknown parameter for shape: " + key); return null; } final Value decodedValue = decoder.decode(tag.get(key), level); @@ -248,13 +248,13 @@ public static ExpiringShape fromTag(final CompoundTag tag, final Level level) final Value shapeValue = options.get("shape"); if (shapeValue == null) { - CarpetSettings.LOG.info("Shape id missing in " + String.join(", ", tag.getAllKeys())); + CarpetScriptServer.LOG.info("Shape id missing in " + String.join(", ", tag.getAllKeys())); return null; } final BiFunction, RegistryAccess, ExpiringShape> factory = ExpiringShape.shapeProviders.get(shapeValue.getString()); if (factory == null) { - CarpetSettings.LOG.info("Unknown shape: " + shapeValue.getString()); + CarpetScriptServer.LOG.info("Unknown shape: " + shapeValue.getString()); return null; } try @@ -263,7 +263,7 @@ public static ExpiringShape fromTag(final CompoundTag tag, final Level level) } catch (final InternalExpressionException exc) { - CarpetSettings.LOG.info(exc.getMessage()); + CarpetScriptServer.LOG.info(exc.getMessage()); } return null; } @@ -2022,7 +2022,7 @@ public static Value validate(final Param p, final Map options, fi new NumericValue(e.getZ()) ); } - CarpetSettings.LOG.error("Value: " + value.getString()); + CarpetScriptServer.LOG.error("Value: " + value.getString()); throw new InternalExpressionException("'" + p.id + "' requires a triple, block or entity to indicate position"); } diff --git a/src/main/java/carpet/script/utils/ShapesRenderer.java b/src/main/java/carpet/script/utils/ShapesRenderer.java index 24a82e3e4a..3505513fc3 100644 --- a/src/main/java/carpet/script/utils/ShapesRenderer.java +++ b/src/main/java/carpet/script/utils/ShapesRenderer.java @@ -1,9 +1,9 @@ package carpet.script.utils; -import carpet.CarpetSettings; -import carpet.mixins.ShulkerBoxAccessMixin; +import carpet.script.CarpetScriptServer; +import carpet.script.external.Carpet; +import carpet.script.external.VanillaClient; import carpet.script.utils.shapes.ShapeDirection; -import carpet.utils.CarpetProfiler; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.BufferBuilder; @@ -82,7 +82,7 @@ public ShapesRenderer(final Minecraft minecraftClient) public void render(final PoseStack matrices, final Camera camera, final float partialTick) { - final CarpetProfiler.ProfilerToken token = CarpetProfiler.start_section(null, "Scarpet client", CarpetProfiler.TYPE.GENERAL); + final Runnable token = Carpet.startProfilerSection("Scarpet client"); //Camera camera = this.client.gameRenderer.getCamera(); final ClientLevel iWorld = this.client.level; final ResourceKey dimensionType = iWorld.dimension(); @@ -163,17 +163,17 @@ public void render(final PoseStack matrices, final Camera camera, final float pa RenderSystem.depthMask(true); RenderSystem.enableBlend(); RenderSystem.defaultBlendFunc(); - CarpetProfiler.end_current_section(token); + token.run(); } public void addShapes(final ListTag tag) { - final CarpetProfiler.ProfilerToken token = CarpetProfiler.start_section(null, "Scarpet client", CarpetProfiler.TYPE.GENERAL); + final Runnable token = Carpet.startProfilerSection("Scarpet client"); for (int i = 0, count = tag.size(); i < count; i++) { addShape(tag.getCompound(i)); } - CarpetProfiler.end_current_section(token); + token.run(); } public void addShape(final CompoundTag tag) @@ -187,7 +187,7 @@ public void addShape(final CompoundTag tag) shapeFactory = renderedShapes.get(tag.getString("shape")); if (shapeFactory == null) { - CarpetSettings.LOG.info("Unrecognized shape: " + tag.getString("shape")); + CarpetScriptServer.LOG.info("Unrecognized shape: " + tag.getString("shape")); } else { @@ -217,11 +217,11 @@ public void reset() public void renewShapes() { - final CarpetProfiler.ProfilerToken token = CarpetProfiler.start_section(null, "Scarpet client", CarpetProfiler.TYPE.GENERAL); + final Runnable token = Carpet.startProfilerSection("Scarpet client"); shapes.values().forEach(el -> el.values().forEach(shape -> shape.expiryTick++)); labels.values().forEach(el -> el.values().forEach(shape -> shape.expiryTick++)); - CarpetProfiler.end_current_section(token); + token.run(); } public abstract static class RenderedShape @@ -468,7 +468,7 @@ public void sbrender(final ShulkerBoxBlockEntity shulkerBoxBlockEntity, final fl poseStack.mulPose(direction.getRotation()); poseStack.scale(1.0F, -1.0F, -1.0F); poseStack.translate(0.0, -1.0, 0.0); - final ShulkerModel model = ((ShulkerBoxAccessMixin) client.getBlockEntityRenderDispatcher().getRenderer(BlockEntity)).getModel(); + final ShulkerModel model = VanillaClient.ShulkerBoxRenderer_model(client.getBlockEntityRenderDispatcher().getRenderer(shulkerBoxBlockEntity)); final ModelPart modelPart = model.getLid(); modelPart.setPos(0.0F, 24.0F - shulkerBoxBlockEntity.getProgress(f) * 0.5F * 16.0F, 0.0F); modelPart.yRot = 270.0F * shulkerBoxBlockEntity.getProgress(f) * (float) (Math.PI / 180.0); @@ -561,7 +561,7 @@ public void promoteWith(final RenderedShape rshape) } catch (final ClassCastException ignored) { - CarpetSettings.LOG.error("shape " + rshape.shape.getClass() + " cannot cast to a Label"); + CarpetScriptServer.LOG.error("shape " + rshape.shape.getClass() + " cannot cast to a Label"); } } } diff --git a/src/main/java/carpet/script/utils/SnoopyCommandSource.java b/src/main/java/carpet/script/utils/SnoopyCommandSource.java index 03f5bec3bf..a462bce5b6 100644 --- a/src/main/java/carpet/script/utils/SnoopyCommandSource.java +++ b/src/main/java/carpet/script/utils/SnoopyCommandSource.java @@ -1,6 +1,6 @@ package carpet.script.utils; -import carpet.CarpetSettings; +import carpet.script.external.Vanilla; import com.mojang.brigadier.ResultConsumer; import net.minecraft.commands.CommandSigningContext; import net.minecraft.commands.CommandSource; @@ -42,14 +42,14 @@ public class SnoopyCommandSource extends CommandSourceStack public SnoopyCommandSource(final CommandSourceStack original, final Component[] error, final List chatOutput) { - super(CommandSource.NULL, original.getPosition(), original.getRotation(), original.getLevel(), CarpetSettings.runPermissionLevel, + super(CommandSource.NULL, original.getPosition(), original.getRotation(), original.getLevel(), Vanilla.MinecraftServer_getRunPermissionLevel(original.getServer()), original.getTextName(), original.getDisplayName(), original.getServer(), original.getEntity(), false, (ctx, succ, res) -> { }, EntityAnchorArgument.Anchor.FEET, CommandSigningContext.ANONYMOUS, TaskChainer.immediate(original.getServer())); this.output = CommandSource.NULL; this.position = original.getPosition(); this.world = original.getLevel(); - this.level = CarpetSettings.runPermissionLevel; + this.level = Vanilla.MinecraftServer_getRunPermissionLevel(original.getServer()); this.simpleName = original.getTextName(); this.name = original.getDisplayName(); this.server = original.getServer(); diff --git a/src/main/java/carpet/script/utils/SystemInfo.java b/src/main/java/carpet/script/utils/SystemInfo.java index dabf724094..fafa59e189 100644 --- a/src/main/java/carpet/script/utils/SystemInfo.java +++ b/src/main/java/carpet/script/utils/SystemInfo.java @@ -1,11 +1,9 @@ package carpet.script.utils; -import carpet.CarpetServer; -import carpet.CarpetSettings; -import carpet.api.settings.CarpetRule; -import carpet.api.settings.RuleHelper; import carpet.script.CarpetContext; import carpet.script.CarpetScriptHost; +import carpet.script.external.Carpet; +import carpet.script.external.Vanilla; import carpet.script.value.BooleanValue; import carpet.script.value.EntityValue; import carpet.script.value.ListValue; @@ -14,10 +12,7 @@ import carpet.script.value.StringValue; import carpet.script.value.Value; import carpet.script.value.ValueConversions; -import carpet.api.settings.SettingsManager; import com.sun.management.OperatingSystemMXBean; -import net.fabricmc.loader.api.FabricLoader; -import net.fabricmc.loader.api.ModContainer; import net.minecraft.SharedConstants; import net.minecraft.server.packs.PackType; import net.minecraft.world.level.GameRules; @@ -29,7 +24,6 @@ import java.lang.management.ManagementFactory; import java.nio.file.Path; import java.util.ArrayList; -import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -93,14 +87,14 @@ public class SystemInfo put("game_view_distance", c -> new NumericValue(c.server().getPlayerList().getViewDistance())); put("game_mod_name", c -> StringValue.of(c.server().getServerModName())); put("game_version", c -> StringValue.of(c.server().getServerVersion())); - put("game_target", c -> StringValue.of(CarpetSettings.releaseTarget)); + put("game_target", c -> StringValue.of(Vanilla.MinecraftServer_getReleaseTarget(c.server()))); put("game_protocol", c -> NumericValue.of(SharedConstants.getProtocolVersion())); put("game_major_target", c -> { - final String[] vers = CarpetSettings.releaseTarget.split("\\."); + final String[] vers = Vanilla.MinecraftServer_getReleaseTarget(c.server()).split("\\."); return NumericValue.of((vers.length > 1) ? Integer.parseInt(vers[1]) : 0); }); put("game_minor_target", c -> { - final String[] vers = CarpetSettings.releaseTarget.split("\\."); + final String[] vers = Vanilla.MinecraftServer_getReleaseTarget(c.server()).split("\\."); return NumericValue.of((vers.length > 2) ? Integer.parseInt(vers[2]) : 0); }); put("game_stable", c -> BooleanValue.of(SharedConstants.getCurrentVersion().isStable())); @@ -133,15 +127,8 @@ public class SystemInfo } return whitelist; }); - put("server_dev_environment", c -> BooleanValue.of(FabricLoader.getInstance().isDevelopmentEnvironment())); - put("server_mods", c -> { - final Map ret = new HashMap<>(); - for (final ModContainer mod : FabricLoader.getInstance().getAllMods()) - { - ret.put(new StringValue(mod.getMetadata().getId()), new StringValue(mod.getMetadata().getVersion().getFriendlyString())); - } - return MapValue.wrap(ret); - }); + put("server_dev_environment", c -> BooleanValue.of(Vanilla.isDevelopmentEnvironment())); + put("server_mods", c -> Vanilla.getServerMods(c.server())); 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. @@ -181,20 +168,7 @@ public class SystemInfo OperatingSystemMXBean.class); return new NumericValue(osBean.getProcessCpuLoad()); }); - put("world_carpet_rules", c -> { - final Collection> rules = CarpetServer.settingsManager.getCarpetRules(); - final MapValue carpetRules = new MapValue(Collections.emptyList()); - rules.forEach(rule -> carpetRules.put(new StringValue(rule.name()), new StringValue(RuleHelper.toRuleString(rule.value())))); - CarpetServer.extensions.forEach(e -> { - final SettingsManager manager = e.extensionSettingsManager(); - if (manager == null) - { - return; - } - manager.getCarpetRules().forEach(rule -> carpetRules.put(new StringValue(manager.identifier() + ":" + rule.name()), new StringValue(RuleHelper.toRuleString(rule.value())))); - }); - return carpetRules; - }); + put("world_carpet_rules", c -> Carpet.getAllCarpetRules()); put("world_gamerules", c -> { final Map rules = new HashMap<>(); final GameRules gameRules = c.level().getGameRules(); @@ -217,9 +191,7 @@ public > void visit(final GameRules.Key key, fin final Vec2 rotation = c.source().getRotation(); return ListValue.of(new NumericValue(rotation.x), new NumericValue(rotation.y)); }); - - put("scarpet_version", c -> StringValue.of(CarpetSettings.carpetVersion)); - + put("scarpet_version", c -> StringValue.of(Carpet.getCarpetVersion())); }}; public static Value get(final String what, final CarpetContext cc) diff --git a/src/main/java/carpet/helpers/Tracer.java b/src/main/java/carpet/script/utils/Tracer.java similarity index 55% rename from src/main/java/carpet/helpers/Tracer.java rename to src/main/java/carpet/script/utils/Tracer.java index 6eed34861a..396e664555 100644 --- a/src/main/java/carpet/helpers/Tracer.java +++ b/src/main/java/carpet/script/utils/Tracer.java @@ -1,7 +1,8 @@ -package carpet.helpers; +package carpet.script.utils; import java.util.Optional; import java.util.function.Predicate; + import net.minecraft.world.entity.Entity; import net.minecraft.world.level.ClipContext; import net.minecraft.world.level.Level; @@ -13,45 +14,45 @@ public class Tracer { - public static HitResult rayTrace(Entity source, float partialTicks, double reach, boolean fluids) + public static HitResult rayTrace(final Entity source, final float partialTicks, final double reach, final boolean fluids) { - BlockHitResult blockHit = rayTraceBlocks(source, partialTicks, reach, fluids); + final BlockHitResult blockHit = rayTraceBlocks(source, partialTicks, reach, fluids); double maxSqDist = reach * reach; if (blockHit != null) { maxSqDist = blockHit.getLocation().distanceToSqr(source.getEyePosition(partialTicks)); } - EntityHitResult entityHit = rayTraceEntities(source, partialTicks, reach, maxSqDist); + final EntityHitResult entityHit = rayTraceEntities(source, partialTicks, reach, maxSqDist); return entityHit == null ? blockHit : entityHit; } - public static BlockHitResult rayTraceBlocks(Entity source, float partialTicks, double reach, boolean fluids) + public static BlockHitResult rayTraceBlocks(final Entity source, final float partialTicks, final double reach, final boolean fluids) { - Vec3 pos = source.getEyePosition(partialTicks); - Vec3 rotation = source.getViewVector(partialTicks); - Vec3 reachEnd = pos.add(rotation.x * reach, rotation.y * reach, rotation.z * reach); + final Vec3 pos = source.getEyePosition(partialTicks); + final Vec3 rotation = source.getViewVector(partialTicks); + final Vec3 reachEnd = pos.add(rotation.x * reach, rotation.y * reach, rotation.z * reach); return source.level.clip(new ClipContext(pos, reachEnd, ClipContext.Block.OUTLINE, fluids ? ClipContext.Fluid.ANY : ClipContext.Fluid.NONE, source)); } - public static EntityHitResult rayTraceEntities(Entity source, float partialTicks, double reach, double maxSqDist) + public static EntityHitResult rayTraceEntities(final Entity source, final float partialTicks, final double reach, final double maxSqDist) { - Vec3 pos = source.getEyePosition(partialTicks); - Vec3 reachVec = source.getViewVector(partialTicks).scale(reach); - AABB box = source.getBoundingBox().expandTowards(reachVec).inflate(1); + final Vec3 pos = source.getEyePosition(partialTicks); + final Vec3 reachVec = source.getViewVector(partialTicks).scale(reach); + final AABB box = source.getBoundingBox().expandTowards(reachVec).inflate(1); return rayTraceEntities(source, pos, pos.add(reachVec), box, e -> !e.isSpectator() && e.isPickable(), maxSqDist); } - public static EntityHitResult rayTraceEntities(Entity source, Vec3 start, Vec3 end, AABB box, Predicate predicate, double maxSqDistance) + public static EntityHitResult rayTraceEntities(final Entity source, final Vec3 start, final Vec3 end, final AABB box, final Predicate predicate, final double maxSqDistance) { - Level world = source.level; + final Level world = source.level; double targetDistance = maxSqDistance; Entity target = null; Vec3 targetHitPos = null; - for (Entity current : world.getEntities(source, box, predicate)) + for (final Entity current : world.getEntities(source, box, predicate)) { - AABB currentBox = current.getBoundingBox().inflate(current.getPickRadius()); - Optional currentHit = currentBox.clip(start, end); + final AABB currentBox = current.getBoundingBox().inflate(current.getPickRadius()); + final Optional currentHit = currentBox.clip(start, end); if (currentBox.contains(start)) { if (targetDistance >= 0) @@ -63,8 +64,8 @@ public static EntityHitResult rayTraceEntities(Entity source, Vec3 start, Vec3 e } else if (currentHit.isPresent()) { - Vec3 currentHitPos = currentHit.get(); - double currentDistance = start.distanceToSqr(currentHitPos); + final Vec3 currentHitPos = currentHit.get(); + final double currentDistance = start.distanceToSqr(currentHitPos); if (currentDistance < targetDistance || targetDistance == 0) { if (current.getRootVehicle() == source.getRootVehicle()) @@ -84,7 +85,6 @@ else if (currentHit.isPresent()) } } } - if (target == null) return null; - return new EntityHitResult(target, targetHitPos); + return target == null ? null : new EntityHitResult(target, targetHitPos); } } diff --git a/src/main/java/carpet/script/utils/WorldTools.java b/src/main/java/carpet/script/utils/WorldTools.java index 4235d43e8e..fc246cb4e5 100644 --- a/src/main/java/carpet/script/utils/WorldTools.java +++ b/src/main/java/carpet/script/utils/WorldTools.java @@ -1,8 +1,9 @@ package carpet.script.utils; -import carpet.fakes.MinecraftServerInterface; -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; +//import carpet.fakes.MinecraftServerInterface; +import carpet.script.external.Vanilla; +//import net.fabricmc.api.EnvType; +//import net.fabricmc.api.Environment; import net.minecraft.Util; import net.minecraft.core.BlockPos; import net.minecraft.core.Holder; @@ -59,7 +60,7 @@ public static boolean canHasChunk(final ServerLevel world, final ChunkPos chpos, } return region.hasChunk(chpos); } - final Path regionsFolder = ((MinecraftServerInterface) world.getServer()).getCMSession().getDimensionPath(world.dimension()).resolve("region"); + final Path regionsFolder = Vanilla.MinecraftServer_storageSource(world.getServer()).getDimensionPath(world.dimension()).resolve("region"); final Path regionPath = regionsFolder.resolve(currentRegionName); if (!regionPath.toFile().exists()) { @@ -169,7 +170,7 @@ public static void forceChunkUpdate(final BlockPos pos, final ServerLevel world) } } - +/* private static class NoopWorldGenerationProgressListener implements ChunkProgressListener { @Override @@ -182,7 +183,7 @@ public void onStatusChange(final ChunkPos pos, final ChunkStatus status) { } - @Environment(EnvType.CLIENT) + //@Environment(EnvType.CLIENT) @Override public void start() { @@ -195,4 +196,6 @@ public void stop() } public static final ChunkProgressListener NOOP_LISTENER = new NoopWorldGenerationProgressListener(); + + */ } diff --git a/src/main/java/carpet/script/value/AbstractListValue.java b/src/main/java/carpet/script/value/AbstractListValue.java index b8e60d0800..cb6a7ab890 100644 --- a/src/main/java/carpet/script/value/AbstractListValue.java +++ b/src/main/java/carpet/script/value/AbstractListValue.java @@ -3,7 +3,6 @@ import carpet.script.exception.InternalExpressionException; import com.google.common.collect.Lists; -import java.util.Iterator; import java.util.List; public abstract class AbstractListValue extends Value implements Iterable diff --git a/src/main/java/carpet/script/value/BlockValue.java b/src/main/java/carpet/script/value/BlockValue.java index c4ec4df3a3..6d7e85637d 100644 --- a/src/main/java/carpet/script/value/BlockValue.java +++ b/src/main/java/carpet/script/value/BlockValue.java @@ -21,7 +21,6 @@ import net.minecraft.core.Direction.Axis; import net.minecraft.core.GlobalPos; import net.minecraft.core.Registry; -import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.StringTag; @@ -38,7 +37,6 @@ import net.minecraft.world.level.chunk.LevelChunk; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.Vec3; -import org.jetbrains.annotations.NotNull; import static carpet.script.value.NBTSerializableValue.nameFromRegistryId; @@ -46,7 +44,6 @@ public class BlockValue extends Value { private BlockState blockState; private final BlockPos pos; - @NotNull private final Level world; private CompoundTag data; @@ -143,7 +140,7 @@ public CompoundTag getData() } - public BlockValue(final BlockState state, @NotNull final Level world, final BlockPos position) + public BlockValue(final BlockState state, final Level world, final BlockPos position) { this.world = world; blockState = state; @@ -151,7 +148,7 @@ public BlockValue(final BlockState state, @NotNull final Level world, final Bloc data = null; } - public BlockValue(final BlockState state, @NotNull final Level world, final BlockPos position, final CompoundTag nbt) + public BlockValue(final BlockState state, final Level world, final BlockPos position, final CompoundTag nbt) { this.world = world; blockState = state; diff --git a/src/main/java/carpet/script/value/EntityValue.java b/src/main/java/carpet/script/value/EntityValue.java index c2a262e1ba..38c44f90b4 100644 --- a/src/main/java/carpet/script/value/EntityValue.java +++ b/src/main/java/carpet/script/value/EntityValue.java @@ -1,19 +1,14 @@ package carpet.script.value; -import carpet.fakes.EntityInterface; -import carpet.fakes.ItemEntityInterface; -import carpet.fakes.LivingEntityInterface; -import carpet.fakes.MobEntityInterface; -import carpet.fakes.ServerPlayerEntityInterface; -import carpet.fakes.ServerPlayerInteractionManagerInterface; -import carpet.helpers.Tracer; -import carpet.network.ServerNetworkHandler; -import carpet.patches.EntityPlayerMPFake; +import carpet.script.external.Vanilla; +import carpet.script.utils.Tracer; import carpet.script.CarpetContext; import carpet.script.CarpetScriptServer; import carpet.script.EntityEventsGroup; import carpet.script.argument.Vector3Argument; import carpet.script.exception.InternalExpressionException; +import carpet.script.external.Carpet; +import carpet.script.utils.EntityTools; import carpet.script.utils.InputValidator; import com.mojang.brigadier.StringReader; import com.mojang.brigadier.exceptions.CommandSyntaxException; @@ -96,7 +91,6 @@ import java.util.stream.Stream; import static carpet.script.value.NBTSerializableValue.nameFromRegistryId; -import static carpet.utils.MobAI.genericJump; // TODO: decide whether copy(entity) should duplicate entity in the world. public class EntityValue extends Value @@ -136,7 +130,7 @@ public static Collection getEntitiesFromSelector(final Command public Entity getEntity() { - if (entity instanceof ServerPlayer && ((ServerPlayerEntityInterface) entity).isInvalidEntityObject()) + if (entity instanceof final ServerPlayer serverPlayer && Vanilla.ServerPlayer_isInvalidEntityObject(serverPlayer)) { final ServerPlayer newPlayer = entity.getServer().getPlayerList().getPlayer(entity.getUUID()); if (newPlayer != null) @@ -449,7 +443,7 @@ public Value get(final String what, final Value arg) put("is_ridden", (e, a) -> BooleanValue.of(e.isVehicle())); put("passengers", (e, a) -> ListValue.wrap(e.getPassengers().stream().map(EntityValue::new))); put("mount", (e, a) -> (e.getVehicle() != null) ? new EntityValue(e.getVehicle()) : Value.NULL); - put("unmountable", (e, a) -> BooleanValue.of(((EntityInterface) e).isPermanentVehicle())); + put("unmountable", (e, a) -> BooleanValue.of(Vanilla.Entity_isPermanentVehicle(e))); // deprecated put("tags", (e, a) -> ListValue.wrap(e.getTags().stream().map(StringValue::new))); @@ -505,9 +499,9 @@ public Value get(final String what, final Value arg) put("offering_flower", (e, a) -> e instanceof final IronGolem ig ? BooleanValue.of(ig.getOfferFlowerTick() > 0) : Value.NULL); put("item", (e, a) -> e instanceof final ItemEntity ie ? ValueConversions.of(ie.getItem(), e.getServer().registryAccess()) : e instanceof final ItemFrame frame ? ValueConversions.of(frame.getItem(), e.getServer().registryAccess()) : Value.NULL); put("count", (e, a) -> (e instanceof final ItemEntity ie) ? new NumericValue(ie.getItem().getCount()) : Value.NULL); - put("pickup_delay", (e, a) -> (e instanceof ItemEntity) ? new NumericValue(((ItemEntityInterface) e).getPickupDelayCM()) : Value.NULL); - put("portal_cooldown", (e, a) -> new NumericValue(((EntityInterface) e).getPublicNetherPortalCooldown())); - put("portal_timer", (e, a) -> new NumericValue(((EntityInterface) e).getPortalTimer())); + put("pickup_delay", (e, a) -> (e instanceof final ItemEntity ie) ? new NumericValue(Vanilla.ItemEntity_getPickupDelay(ie)) : Value.NULL); + put("portal_cooldown", (e, a) -> new NumericValue(Vanilla.Entity_getPublicNetherPortalCooldown(e))); + put("portal_timer", (e, a) -> new NumericValue(Vanilla.Entity_getPortalTimer(e))); // ItemEntity -> despawn timer via ssGetAge put("is_baby", (e, a) -> (e instanceof final LivingEntity le) ? BooleanValue.of(le.isBaby()) : Value.NULL); put("target", (e, a) -> { @@ -544,7 +538,7 @@ public Value get(final String what, final Value arg) put("swimming", (e, a) -> e.isSwimming() ? Value.TRUE : Value.FALSE); put("swinging", (e, a) -> e instanceof final LivingEntity le ? BooleanValue.of(le.swinging) : Value.NULL); put("air", (e, a) -> new NumericValue(e.getAirSupply())); - put("language", (e, a) -> !(e instanceof ServerPlayer) ? NULL : StringValue.of(((ServerPlayerEntityInterface) e).getLanguage())); + put("language", (e, a) -> !(e instanceof final ServerPlayer p) ? NULL : StringValue.of(Vanilla.ServerPlayer_getLanguage(p))); put("persistence", (e, a) -> e instanceof final Mob mob ? BooleanValue.of(mob.isPersistenceRequired()) : Value.NULL); put("hunger", (e, a) -> e instanceof final Player player ? new NumericValue(player.getFoodData().getFoodLevel()) : Value.NULL); put("saturation", (e, a) -> e instanceof final Player player ? new NumericValue(player.getFoodData().getSaturationLevel()) : Value.NULL); @@ -554,7 +548,7 @@ public Value get(final String what, final Value arg) put("xp_level", (e, a) -> e instanceof final Player player ? new NumericValue(player.experienceLevel) : Value.NULL); put("xp_progress", (e, a) -> e instanceof final Player player ? new NumericValue(player.experienceProgress) : Value.NULL); put("score", (e, a) -> e instanceof final Player player ? new NumericValue(player.getScore()) : Value.NULL); - put("jumping", (e, a) -> e instanceof LivingEntity ? ((LivingEntityInterface) e).isJumpingCM() ? Value.TRUE : Value.FALSE : Value.NULL); + put("jumping", (e, a) -> e instanceof final LivingEntity le ? Vanilla.LivingEntity_isJumping(le) ? Value.TRUE : Value.FALSE : Value.NULL); put("gamemode", (e, a) -> e instanceof final ServerPlayer sp ? new StringValue(sp.gameMode.getGameModeForPlayer().getName()) : Value.NULL); put("path", (e, a) -> { if (e instanceof final Mob mob) @@ -610,9 +604,10 @@ public Value get(final String what, final Value arg) put("player_type", (e, a) -> { if (e instanceof final Player p) { - if (e instanceof final EntityPlayerMPFake fake) + final String moddedType = Carpet.isModdedPlayer(p); + if (moddedType != null) { - return new StringValue(fake.isAShadow ? "shadow" : "fake"); + return StringValue.of(moddedType); } final MinecraftServer server = p.getCommandSenderWorld().getServer(); if (server.isDedicatedServer()) @@ -635,7 +630,7 @@ public Value get(final String what, final Value arg) return Value.NULL; }); - put("client_brand", (e, a) -> e instanceof final ServerPlayer sp ? StringValue.of(ServerNetworkHandler.getPlayerStatus(sp)) : Value.NULL); + put("client_brand", (e, a) -> e instanceof final ServerPlayer sp ? StringValue.of(Carpet.getPlayerStatus(sp)) : Value.NULL); put("team", (e, a) -> e.getTeam() == null ? Value.NULL : new StringValue(e.getTeam().getName())); put("ping", (e, a) -> e instanceof final ServerPlayer sp ? new NumericValue(sp.latency) : Value.NULL); @@ -703,8 +698,7 @@ public Value get(final String what, final Value arg) put("active_block", (e, a) -> { if (e instanceof final ServerPlayer sp) { - final ServerPlayerInteractionManagerInterface manager = (ServerPlayerInteractionManagerInterface) (sp.gameMode); - final BlockPos pos = manager.getCurrentBreakingBlock(); + final BlockPos pos = Vanilla.ServerPlayerGameMode_getCurrentBlockPosition(sp.gameMode); if (pos == null) { return Value.NULL; @@ -717,8 +711,7 @@ public Value get(final String what, final Value arg) put("breaking_progress", (e, a) -> { if (e instanceof final ServerPlayer sp) { - final ServerPlayerInteractionManagerInterface manager = (ServerPlayerInteractionManagerInterface) (sp.gameMode); - final int progress = manager.getCurrentBlockBreakingProgress(); + final int progress = Vanilla.ServerPlayerGameMode_getCurrentBlockBreakingProgress (sp.gameMode); return progress < 0 ? Value.NULL : new NumericValue(progress); } return Value.NULL; @@ -1204,7 +1197,7 @@ private static void updateVelocity(final Entity e, final double scale) put("persistence", (e, v) -> { - if (!(e instanceof Mob)) + if (!(e instanceof final Mob mob)) { return; } @@ -1212,7 +1205,7 @@ private static void updateVelocity(final Entity e, final double scale) { v = Value.TRUE; } - ((MobEntityInterface) e).setPersistence(v.getBoolean()); + Vanilla.Mob_setPersistence(mob, v.getBoolean()); }); put("dismount", (e, v) -> e.stopRiding()); @@ -1226,7 +1219,7 @@ private static void updateVelocity(final Entity e, final double scale) sp.connection.send(new ClientboundSetPassengersPacket(e)); } }); - put("unmountable", (e, v) -> ((EntityInterface) e).setPermanentVehicle(v == null || v.getBoolean())); + put("unmountable", (e, v) -> Vanilla.Entity_setPermanentVehicle(e, v == null || v.getBoolean())); put("drop_passengers", (e, v) -> e.ejectPassengers()); put("mount_passengers", (e, v) -> { if (v == null) @@ -1316,8 +1309,8 @@ else if (v instanceof final ListValue lv) if (v.isNull()) { ec.restrictTo(BlockPos.ZERO, -1); - final Map tasks = ((MobEntityInterface) ec).getTemporaryTasks(); - ((MobEntityInterface) ec).getAI(false).removeGoal(tasks.get("home")); + final Map tasks = Vanilla.Mob_getTemporaryTasks(ec); + Vanilla.Mob_getAI(ec, false).removeGoal(tasks.get("home")); tasks.remove("home"); return; } @@ -1349,12 +1342,12 @@ else if (v instanceof final ListValue lv) } ec.restrictTo(pos, distance); - final Map tasks = ((MobEntityInterface) ec).getTemporaryTasks(); + final Map tasks = Vanilla.Mob_getTemporaryTasks(ec); if (!tasks.containsKey("home")) { final Goal task = new MoveTowardsRestrictionGoal(ec, 1.0D); tasks.put("home", task); - ((MobEntityInterface) ec).getAI(false).addGoal(10, task); + Vanilla.Mob_getAI(ec, false).addGoal(10, task); } }); //requires mixing @@ -1430,7 +1423,7 @@ else if (a.isNull()) { throw new InternalExpressionException("'portal_cooldown' requires a value to set"); } - ((EntityInterface) e).setPublicNetherPortalCooldown(NumericValue.asNumber(v).getInt()); + Vanilla.Entity_setPublicNetherPortalCooldown(e, NumericValue.asNumber(v).getInt()); }); put("portal_timer", (e, v) -> @@ -1439,7 +1432,7 @@ else if (a.isNull()) { throw new InternalExpressionException("'portal_timer' requires a value to set"); } - ((EntityInterface) e).setPortalTimer(NumericValue.asNumber(v).getInt()); + Vanilla.Entity_setPortalTimer(e, NumericValue.asNumber(v).getInt()); }); put("ai", (e, v) -> @@ -1555,13 +1548,13 @@ else if (v instanceof final ListValue lv) }); put("jump", (e, v) -> { - if (e instanceof LivingEntity) + if (e instanceof final LivingEntity le) { - ((LivingEntityInterface) e).doJumpCM(); + Vanilla.LivingEntity_setJumping(le); } else { - genericJump(e); + EntityTools.genericJump(e); } }); @@ -1671,8 +1664,7 @@ else if (v instanceof final ListValue lv) if (e instanceof final ServerPlayer sp) { final int progress = (a == null || a.isNull()) ? -1 : NumericValue.asNumber(a).getInt(); - final ServerPlayerInteractionManagerInterface manager = (ServerPlayerInteractionManagerInterface) (sp.gameMode); - manager.setBlockBreakingProgress(progress); + Vanilla.ServerPlayerGameMode_setBlockBreakingProgress(sp.gameMode, progress); } }); @@ -1740,7 +1732,7 @@ public void setEvent(final CarpetContext cc, final String eventName, final Funct { throw new InternalExpressionException("Unknown entity event: " + eventName); } - ((EntityInterface) getEntity()).getEventContainer().addEvent(event, cc.host, fun, args); + Vanilla.Entity_getEventContainer(getEntity()).addEvent(event, cc.host, fun, args); } @Override diff --git a/src/main/java/carpet/script/value/FunctionValue.java b/src/main/java/carpet/script/value/FunctionValue.java index 8ee3780ddf..566471e955 100644 --- a/src/main/java/carpet/script/value/FunctionValue.java +++ b/src/main/java/carpet/script/value/FunctionValue.java @@ -1,6 +1,6 @@ package carpet.script.value; -import carpet.CarpetSettings; +import carpet.script.CarpetScriptServer; import carpet.script.Context; import carpet.script.Expression; import carpet.script.Fluff; @@ -18,7 +18,6 @@ import java.util.List; import java.util.Map; import java.util.function.Consumer; -import java.util.stream.Collectors; import net.minecraft.nbt.StringTag; import net.minecraft.nbt.Tag; @@ -200,7 +199,7 @@ public static List unpackArgs(final List lazyParams, final Con final Value param = lv.evalValue(c, Context.NONE); if (param instanceof FunctionUnpackedArgumentsValue) { - CarpetSettings.LOG.error("How did we get here?"); + CarpetScriptServer.LOG.error("How did we get here?"); params.addAll(((ListValue) param).getItems()); } else diff --git a/src/main/java/carpet/script/value/NBTSerializableValue.java b/src/main/java/carpet/script/value/NBTSerializableValue.java index 32cce9ddda..cfd8eb2ad9 100644 --- a/src/main/java/carpet/script/value/NBTSerializableValue.java +++ b/src/main/java/carpet/script/value/NBTSerializableValue.java @@ -1,10 +1,10 @@ package carpet.script.value; -import carpet.fakes.InventoryBearerInterface; import carpet.script.CarpetContext; import carpet.script.exception.InternalExpressionException; import carpet.script.exception.ThrowStatement; import carpet.script.exception.Throwables; +import carpet.script.external.Vanilla; import carpet.script.utils.EquipmentInventory; import com.mojang.brigadier.StringReader; import com.mojang.brigadier.exceptions.CommandSyntaxException; @@ -44,6 +44,7 @@ import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntitySelector; import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.animal.horse.AbstractHorse; import net.minecraft.world.entity.npc.InventoryCarrier; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; @@ -280,9 +281,9 @@ else if (e instanceof final InventoryCarrier io) { inv = io.getInventory(); } - else if (e instanceof final InventoryBearerInterface ibi) + else if (e instanceof final AbstractHorse ibi) { - inv = ibi.getCMInventory(); // horse only + inv = Vanilla.AbstractHorse_getInventory(ibi); // horse only } else if (e instanceof final LivingEntity le) { diff --git a/src/main/java/carpet/script/value/ScreenValue.java b/src/main/java/carpet/script/value/ScreenValue.java index 0c144c524c..b24d290dd3 100644 --- a/src/main/java/carpet/script/value/ScreenValue.java +++ b/src/main/java/carpet/script/value/ScreenValue.java @@ -1,9 +1,5 @@ package carpet.script.value; -import carpet.CarpetServer; -import carpet.CarpetSettings; -import carpet.fakes.ScreenHandlerInterface; - import carpet.script.CarpetScriptHost; import carpet.script.CarpetScriptServer; import carpet.script.Context; @@ -12,6 +8,7 @@ import carpet.script.exception.InvalidCallbackException; import carpet.script.exception.ThrowStatement; import carpet.script.exception.Throwables; +import carpet.script.external.Vanilla; import java.util.Arrays; import java.util.HashMap; @@ -31,7 +28,32 @@ import net.minecraft.world.SimpleMenuProvider; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; -import net.minecraft.world.inventory.*; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.inventory.AbstractFurnaceMenu; +import net.minecraft.world.inventory.AnvilMenu; +import net.minecraft.world.inventory.BeaconMenu; +import net.minecraft.world.inventory.BlastFurnaceMenu; +import net.minecraft.world.inventory.BrewingStandMenu; +import net.minecraft.world.inventory.CartographyTableMenu; +import net.minecraft.world.inventory.ChestMenu; +import net.minecraft.world.inventory.ClickType; +import net.minecraft.world.inventory.ContainerListener; +import net.minecraft.world.inventory.CraftingMenu; +import net.minecraft.world.inventory.DataSlot; +import net.minecraft.world.inventory.EnchantmentMenu; +import net.minecraft.world.inventory.FurnaceMenu; +import net.minecraft.world.inventory.GrindstoneMenu; +import net.minecraft.world.inventory.HopperMenu; +import net.minecraft.world.inventory.LecternMenu; +import net.minecraft.world.inventory.LegacySmithingMenu; +import net.minecraft.world.inventory.LoomMenu; +import net.minecraft.world.inventory.MerchantMenu; +import net.minecraft.world.inventory.ShulkerBoxMenu; +import net.minecraft.world.inventory.SimpleContainerData; +import net.minecraft.world.inventory.Slot; +import net.minecraft.world.inventory.SmithingMenu; +import net.minecraft.world.inventory.SmokerMenu; +import net.minecraft.world.inventory.StonecutterMenu; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Recipe; @@ -47,6 +69,7 @@ public class ScreenValue extends Value private final FunctionValue callback; private final String hostname; private final ServerPlayer player; + private final CarpetScriptServer scriptServer; public static Map screenHandlerFactories; @@ -96,6 +119,7 @@ public ScreenValue(final ServerPlayer player, final String type, final Component } this.callback = callback; this.hostname = c.host.getName(); + this.scriptServer = (CarpetScriptServer) c.host.scriptServer(); this.player = player; final MenuProvider factory = this.createScreenHandlerFactory(); if (factory == null) @@ -167,18 +191,19 @@ private boolean callListener(final ServerPlayer player, final String action, fin final Value actionValue = StringValue.of(action); final Value dataValue = MapValue.wrap(data); final List args = Arrays.asList(this, playerValue, actionValue, dataValue); - final CarpetScriptHost appHost = CarpetServer.scriptServer.getAppHostByName(this.hostname); + final CarpetScriptHost appHost = scriptServer.getAppHostByName(this.hostname); if (appHost == null) { this.close(); this.screenHandler = null; return false; } - final CommandSourceStack source = player.createCommandSourceStack().withPermission(CarpetSettings.runPermissionLevel); + final int runPermissionLevel = Vanilla.MinecraftServer_getRunPermissionLevel(player.server); + final CommandSourceStack source = player.createCommandSourceStack().withPermission(runPermissionLevel); final CarpetScriptHost executingHost = appHost.retrieveForExecution(source, player); try { - final Value cancelValue = executingHost.callUDF(source.withPermission(CarpetSettings.runPermissionLevel), callback, args); + final Value cancelValue = executingHost.callUDF(source, callback, args); return cancelValue.getString().equals("cancel"); } catch (final NullPointerException | InvalidCallbackException | IntegrityException error) @@ -255,7 +280,7 @@ private DataSlot getPropertyForType(final Class { if (screenHandlerClass.isInstance(this.screenHandler)) { - return ((ScreenHandlerInterface) this.screenHandler).getProperty(propertyIndex); + return Vanilla.AbstractContainerMenu_getDataSlot(this.screenHandler, propertyIndex); } if (!this.isOpen()) { diff --git a/src/main/java/carpet/script/value/Value.java b/src/main/java/carpet/script/value/Value.java index cc0cab1d79..f29b53425e 100644 --- a/src/main/java/carpet/script/value/Value.java +++ b/src/main/java/carpet/script/value/Value.java @@ -1,6 +1,6 @@ package carpet.script.value; -import carpet.CarpetSettings; +import carpet.script.CarpetScriptServer; import carpet.script.exception.InternalExpressionException; import com.google.gson.JsonElement; import com.google.gson.JsonPrimitive; @@ -46,7 +46,7 @@ public Value reboundedTo(final String value) catch (final CloneNotSupportedException e) { // should not happen - CarpetSettings.LOG.error("Failed to clone variable", e); + CarpetScriptServer.LOG.error("Failed to clone variable", e); throw new InternalExpressionException("Variable of type " + getTypeString() + " is not cloneable. Tell gnembon about it, this shoudn't happen"); } copy.boundVariable = value; diff --git a/src/main/java/carpet/script/value/ValueConversions.java b/src/main/java/carpet/script/value/ValueConversions.java index 98ddd780f8..9ffcaff717 100644 --- a/src/main/java/carpet/script/value/ValueConversions.java +++ b/src/main/java/carpet/script/value/ValueConversions.java @@ -1,10 +1,10 @@ package carpet.script.value; -import carpet.fakes.BlockPredicateInterface; import carpet.script.exception.InternalExpressionException; import carpet.script.exception.ThrowStatement; import carpet.script.exception.Throwables; -import carpet.utils.BlockInfo; +import carpet.script.external.Carpet; +import carpet.script.external.Vanilla; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import net.minecraft.advancements.critereon.MinMaxBounds; @@ -83,7 +83,7 @@ public static Value of(final ServerLevel world) public static Value of(final MaterialColor color) { - return ListValue.of(StringValue.of(BlockInfo.mapColourName.get(color)), ofRGB(color.col)); + return ListValue.of(StringValue.of(Carpet.getMapColorNames().get(color)), ofRGB(color.col)); } public static Value of(final MinMaxBounds range) @@ -451,13 +451,13 @@ public static Value ofVanillaSlotResult(final int itemSlot) public static Value ofBlockPredicate(final RegistryAccess registryAccess, final Predicate blockPredicate) { - final BlockPredicateInterface predicateData = (BlockPredicateInterface) blockPredicate; + final Vanilla.BlockPredicatePayload payload = Vanilla.BlockPredicatePayload.of(blockPredicate); final Registry blocks = registryAccess.registryOrThrow(Registries.BLOCK); return ListValue.of( - predicateData.getCMBlockState() == null ? Value.NULL : of(blocks.getKey(predicateData.getCMBlockState().getBlock())), - predicateData.getCMBlockTagKey() == null ? Value.NULL : of(blocks.getTag(predicateData.getCMBlockTagKey()).get().key()), - MapValue.wrap(predicateData.getCMProperties()), - predicateData.getCMDataTag() == null ? Value.NULL : new NBTSerializableValue(predicateData.getCMDataTag()) + payload.state() == null ? Value.NULL : of(blocks.getKey(payload.state().getBlock())), + payload.tagKey() == null ? Value.NULL : of(blocks.getTag(payload.tagKey()).get().key()), + MapValue.wrap(payload.properties()), + payload.tag() == null ? Value.NULL : new NBTSerializableValue(payload.tag()) ); } diff --git a/src/main/java/carpet/utils/MobAI.java b/src/main/java/carpet/utils/MobAI.java index c13fd5946f..80208dd2b2 100644 --- a/src/main/java/carpet/utils/MobAI.java +++ b/src/main/java/carpet/utils/MobAI.java @@ -13,6 +13,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.Registries; +import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerLevel; import net.minecraft.util.Mth; import net.minecraft.world.entity.Entity; @@ -38,10 +39,10 @@ public static boolean isTracking(Entity e, TrackingType type) return currentTrackers.contains(type); } - public static void clearTracking(EntityType etype) + public static void clearTracking(final MinecraftServer server, EntityType etype) { aiTrackers.remove(etype); - for(ServerLevel world : CarpetServer.minecraft_server.getAllLevels() ) + for(ServerLevel world : server.getAllLevels() ) { for (Entity e: world.getEntities(etype, Entity::hasCustomName)) { @@ -86,26 +87,4 @@ public enum TrackingType types = applicableTypes; } } - - /** - * Not a replacement for living entity jump() - this barely is to allow other entities that can't jump in vanilla to 'jump' - * @param e - */ - public static void genericJump(Entity e) - { - if (!e.isOnGround() && !e.isInWaterOrBubble() && !e.isInLava()) return; - float m = e.level.getBlockState(e.blockPosition()).getBlock().getJumpFactor(); - float g = e.level.getBlockState(new BlockPos(e.getX(), e.getBoundingBox().minY - 0.5000001D, e.getZ())).getBlock().getJumpFactor(); - float jumpVelocityMultiplier = (double) m == 1.0D ? g : m; - float jumpStrength = (0.42F * jumpVelocityMultiplier); - Vec3 vec3d = e.getDeltaMovement(); - e.setDeltaMovement(vec3d.x, jumpStrength, vec3d.z); - if (e.isSprinting()) - { - float u = e.getYRot() * 0.017453292F; // yaw - e.setDeltaMovement(e.getDeltaMovement().add((-Mth.sin(g) * 0.2F), 0.0D, (Mth.cos(u) * 0.2F))); - } - e.hasImpulse = true; - } - } diff --git a/src/main/resources/carpet.mixins.json b/src/main/resources/carpet.mixins.json index aae9683cde..dc971d3b1b 100644 --- a/src/main/resources/carpet.mixins.json +++ b/src/main/resources/carpet.mixins.json @@ -88,7 +88,6 @@ "Player_parrotMixin", "SaplingBlock_desertShrubsMixin", "EntityMixin", - "ChunkGenerator_scarpetMixin", "Guardian_renewableSpongesMixin", "Husk_templesMixin", "ChunkGenerator_customMobSpawnsMixin", From aea76d976406073a7e82c3c8747ad3b82d6ede6f Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Sun, 5 Feb 2023 15:27:34 +0100 Subject: [PATCH 046/233] removed static reference to server in annotation parser --- .../script/annotation/AnnotationParser.java | 3 +- .../script/annotation/ListConverter.java | 13 +++---- .../carpet/script/annotation/Locator.java | 2 +- .../script/annotation/MapConverter.java | 22 ++++++------ .../script/annotation/OptionalConverter.java | 4 +-- .../script/annotation/OutputConverter.java | 1 - .../java/carpet/script/annotation/Param.java | 4 +-- .../annotation/SimpleTypeConverter.java | 35 ++++++++++++++----- .../carpet/script/annotation/ValueCaster.java | 3 +- .../script/annotation/ValueConverter.java | 17 ++++++--- 10 files changed, 64 insertions(+), 40 deletions(-) diff --git a/src/main/java/carpet/script/annotation/AnnotationParser.java b/src/main/java/carpet/script/annotation/AnnotationParser.java index 052cb524a4..7251ed75eb 100644 --- a/src/main/java/carpet/script/annotation/AnnotationParser.java +++ b/src/main/java/carpet/script/annotation/AnnotationParser.java @@ -20,7 +20,6 @@ import com.google.common.base.Suppliers; -import carpet.CarpetExtension; import carpet.script.Context; import carpet.script.Expression; import carpet.script.Fluff.AbstractLazyFunction; @@ -85,7 +84,7 @@ public final class AnnotationParser *

Parses a given {@link Class} and registers its annotated methods, the ones with the {@link ScarpetFunction} annotation, * to be used in the Scarpet language.

* - *

Only call this method once per class per lifetime of the JVM! (for example, at {@link CarpetExtension#onGameStarted()} or + *

Only call this method once per class per lifetime of the JVM! (for example, at {@link carpet.CarpetExtension#onGameStarted()} or * {@link ModInitializer#onInitialize()}).

* *

There is a set of requirements for the class and its methods:

diff --git a/src/main/java/carpet/script/annotation/ListConverter.java b/src/main/java/carpet/script/annotation/ListConverter.java index abdfbc5b16..b2648ff83d 100644 --- a/src/main/java/carpet/script/annotation/ListConverter.java +++ b/src/main/java/carpet/script/annotation/ListConverter.java @@ -6,6 +6,7 @@ import java.util.Collections; import java.util.List; +import carpet.script.Context; import carpet.script.value.ListValue; import carpet.script.value.Value; @@ -32,17 +33,17 @@ public String getTypeName() } @Override - public List convert(final Value value) + public List convert(final Value value, final Context context) { - return value instanceof ListValue ? convertListValue((ListValue) value) : allowSingletonCreation ? convertSingleton(value) : null; + return value instanceof ListValue ? convertListValue((ListValue) value, context) : allowSingletonCreation ? convertSingleton(value, context) : null; } - private List convertListValue(final ListValue values) + private List convertListValue(final ListValue values, final Context context) { final List list = new ArrayList<>(values.getItems().size()); for (final Value value : values) { - final T converted = itemConverter.convert(value); + final T converted = itemConverter.convert(value, context); if (converted == null) { return null; @@ -52,9 +53,9 @@ private List convertListValue(final ListValue values) return list; } - private List convertSingleton(final Value val) + private List convertSingleton(final Value val, final Context context) { - final T converted = itemConverter.convert(val); + final T converted = itemConverter.convert(val, context); if (converted == null) { return null; diff --git a/src/main/java/carpet/script/annotation/Locator.java b/src/main/java/carpet/script/annotation/Locator.java index 0c447c3e46..daf403d6d7 100644 --- a/src/main/java/carpet/script/annotation/Locator.java +++ b/src/main/java/carpet/script/annotation/Locator.java @@ -276,7 +276,7 @@ public String getTypeName() private abstract static class AbstractLocator implements ValueConverter, Locator { @Override - public R convert(final Value value) + public R convert(final Value value, final Context context) { throw new UnsupportedOperationException("Cannot call a locator in a parameter that doesn't contain a context!"); } diff --git a/src/main/java/carpet/script/annotation/MapConverter.java b/src/main/java/carpet/script/annotation/MapConverter.java index a39671f5d5..e8ecda802c 100644 --- a/src/main/java/carpet/script/annotation/MapConverter.java +++ b/src/main/java/carpet/script/annotation/MapConverter.java @@ -37,15 +37,15 @@ public String getTypeName() } @Override - public Map convert(final Value value) + public Map convert(final Value value, final Context context) { final Map result = new HashMap<>(); if (value instanceof MapValue) { for (final Entry entry : ((MapValue) value).getMap().entrySet()) { - final K key = keyConverter.convert(entry.getKey()); - final V val = valueConverter.convert(entry.getValue()); + final K key = keyConverter.convert(entry.getKey(), context); + final V val = valueConverter.convert(entry.getValue(), context); if (key == null || val == null) { return null; @@ -105,14 +105,14 @@ public boolean consumesVariableArgs() } @Override - public Map convert(final Value value) { - return value instanceof MapValue ? super.convert(value) - : value instanceof ListValue ? convertList(((ListValue)value).getItems()) + public Map convert(final Value value, final Context context) { + return value instanceof MapValue ? super.convert(value, context) + : value instanceof ListValue ? convertList(((ListValue)value).getItems(), context) : null; // Multiparam mode can only be used in evalAndConvert } - private Map convertList(final List valueList) + private Map convertList(final List valueList, final Context context) { if (valueList.size() % 2 == 1) { @@ -122,8 +122,8 @@ private Map convertList(final List valueList) final Iterator val = valueList.iterator(); while (val.hasNext()) { - final K key = keyConverter.convert(val.next()); - final V value = valueConverter.convert(val.next()); + final K key = keyConverter.convert(val.next(), context); + final V value = valueConverter.convert(val.next(), context); if (key == null || value == null) { return null; @@ -143,11 +143,11 @@ public Map checkAndConvert(final Iterator valueIterator, final Cont final Value val = valueIterator.next(); if (!acceptMultiParam || val instanceof MapValue || (val instanceof ListValue && !(keyConverter instanceof ListConverter))) { - return convert(val); // @KeyValuePairs Map, Boolean> will not support list consumption + return convert(val, context); // @KeyValuePairs Map, Boolean> will not support list consumption } final Map map = new HashMap<>(); - K key = keyConverter.convert(val); //First pair is manual since we got it to check for a different conversion mode + K key = keyConverter.convert(val, context); //First pair is manual since we got it to check for a different conversion mode V value = valueConverter.checkAndConvert(valueIterator, context, theLazyT); if (key == null || value == null) { diff --git a/src/main/java/carpet/script/annotation/OptionalConverter.java b/src/main/java/carpet/script/annotation/OptionalConverter.java index 0851915734..3ef26c3f9e 100644 --- a/src/main/java/carpet/script/annotation/OptionalConverter.java +++ b/src/main/java/carpet/script/annotation/OptionalConverter.java @@ -50,13 +50,13 @@ private OptionalConverter(AnnotatedType type) * {@link #checkAndConvert(Iterator, Context, Context.Type)} and is only used as a fallback in types that don't support it. */ @Override - public Optional convert(final Value value) + public Optional convert(final Value value, final Context context) { if (value.isNull()) { return Optional.empty(); } - final R converted = typeConverter.convert(value); + final R converted = typeConverter.convert(value, context); if (converted == null) { return null; diff --git a/src/main/java/carpet/script/annotation/OutputConverter.java b/src/main/java/carpet/script/annotation/OutputConverter.java index b7947618d4..737cbc7835 100644 --- a/src/main/java/carpet/script/annotation/OutputConverter.java +++ b/src/main/java/carpet/script/annotation/OutputConverter.java @@ -6,7 +6,6 @@ import java.util.function.Function; import net.minecraft.core.BlockPos; import net.minecraft.core.GlobalPos; -import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.nbt.Tag; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; diff --git a/src/main/java/carpet/script/annotation/Param.java b/src/main/java/carpet/script/annotation/Param.java index 7ec081cd6f..177b6faa36 100644 --- a/src/main/java/carpet/script/annotation/Param.java +++ b/src/main/java/carpet/script/annotation/Param.java @@ -148,7 +148,7 @@ final class Params @Override public String getTypeName() { return null; } @Override - public Context convert(final Value value) + public Context convert(final Value value, final Context context) { throw new UnsupportedOperationException("Called convert() with Value in Context Provider converter, where only checkAndConvert is supported"); } @@ -175,7 +175,7 @@ public int valueConsumption() @Override public String getTypeName() { return null; } @Override - public Context.Type convert(final Value value) + public Context.Type convert(final Value value, final Context context) { throw new UnsupportedOperationException("Called convert() with a Value in TheLazyT Provider, where only checkAndConvert is supported"); } diff --git a/src/main/java/carpet/script/annotation/SimpleTypeConverter.java b/src/main/java/carpet/script/annotation/SimpleTypeConverter.java index e6beccbaf8..b5229071ce 100644 --- a/src/main/java/carpet/script/annotation/SimpleTypeConverter.java +++ b/src/main/java/carpet/script/annotation/SimpleTypeConverter.java @@ -2,12 +2,15 @@ import java.util.HashMap; import java.util.Map; +import java.util.function.BiFunction; import java.util.function.Function; + +import carpet.script.CarpetContext; +import carpet.script.Context; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.Entity; import net.minecraft.world.level.Level; -import carpet.CarpetServer; import carpet.script.exception.InternalExpressionException; import carpet.script.value.EntityValue; import carpet.script.value.FormattedTextValue; @@ -31,9 +34,9 @@ public final class SimpleTypeConverter implements ValueConve private static final Map, SimpleTypeConverter> byResult = new HashMap<>(); static { - registerType(Value.class, ServerPlayer.class, val -> EntityValue.getPlayerByValue(CarpetServer.minecraft_server, val), "online player"); + registerType(Value.class, ServerPlayer.class, (v, c) -> EntityValue.getPlayerByValue(((CarpetContext)c).server(), v), "online player"); registerType(EntityValue.class, Entity.class, EntityValue::getEntity, "entity"); - registerType(Value.class, Level.class, val -> ValueConversions.dimFromValue(val, CarpetServer.minecraft_server), "dimension"); + registerType(Value.class, Level.class, (v, c) -> ValueConversions.dimFromValue(v, ((CarpetContext)c).server()), "dimension"); registerType(Value.class, Component.class, FormattedTextValue::getTextByValue, "text"); registerType(Value.class, String.class, Value::getString, "string"); // Check out @Param.Strict for more specific types @@ -44,7 +47,7 @@ public final class SimpleTypeConverter implements ValueConve registerType(Value.class, Boolean.class, Value::getBoolean, "boolean"); // Check out @Param.Strict for more specific types } - private final Function converter; + private final BiFunction converter; private final Class valueClass; private final String typeName; @@ -58,7 +61,7 @@ public final class SimpleTypeConverter implements ValueConve * @param inputType The required type for the input {@link Value} * @param converter The function to convert an instance of inputType into R. */ - public SimpleTypeConverter(final Class inputType, final Function converter, final String typeName) + public SimpleTypeConverter(final Class inputType, final BiFunction converter, final String typeName) { super(); this.converter = converter; @@ -66,6 +69,14 @@ public SimpleTypeConverter(final Class inputType, final Function conver this.typeName = typeName; } + public SimpleTypeConverter(final Class inputType, final Function converter, final String typeName) + { + super(); + this.converter = (v, c) -> converter.apply(v); + this.valueClass = inputType; + this.typeName = typeName; + } + @Override public String getTypeName() { @@ -87,9 +98,9 @@ static SimpleTypeConverter get(final Class outputType) @Override @SuppressWarnings("unchecked") // more than checked. not using class.cast because then "method is too big" for inlining, because javac is useless - public R convert(final Value value) // and adds millions of casts. This one is even removed + public R convert(final Value value, final Context context) // and adds millions of casts. This one is even removed { - return valueClass.isInstance(value) ? converter.apply((T)value) : null; + return valueClass.isInstance(value) ? converter.apply((T)value, context) : null; } /** @@ -99,15 +110,21 @@ public R convert(final Value value) * @param The type of the resulting object * @param requiredInputType The {@link Class} of {@code } * @param outputType The {@link Class} of {@code >} - * @param converter A function that converts from the given {@link Value} subtype to the given type. Should ideally return {@code null} + * @param converter A bi function that converts from the given {@link Value} subtype to the given type. Should ideally return {@code null} * when given {@link Value} cannot be converted to the {@code }, to follow the {@link ValueConverter} contract, but it * can also throw an {@link InternalExpressionException} by itself if really necessary. * @param typeName The name of the type, following the conventions of {@link ValueConverter#getTypeName()} */ public static void registerType(final Class requiredInputType, final Class outputType, - final Function converter, final String typeName) + final BiFunction converter, final String typeName) { final SimpleTypeConverter type = new SimpleTypeConverter<>(requiredInputType, converter, typeName); byResult.put(outputType, type); } + + public static void registerType(final Class requiredInputType, final Class outputType, + final Function converter, final String typeName) + { + registerType(requiredInputType, outputType, (val, ctx) -> converter.apply(val), typeName); + } } diff --git a/src/main/java/carpet/script/annotation/ValueCaster.java b/src/main/java/carpet/script/annotation/ValueCaster.java index cc8c01ce8b..fd422f40fc 100644 --- a/src/main/java/carpet/script/annotation/ValueCaster.java +++ b/src/main/java/carpet/script/annotation/ValueCaster.java @@ -3,6 +3,7 @@ import java.util.HashMap; import java.util.Map; +import carpet.script.Context; import carpet.script.value.AbstractListValue; import carpet.script.value.BlockValue; import carpet.script.value.BooleanValue; @@ -79,7 +80,7 @@ public static ValueCaster get(final Class outputType) @Override @SuppressWarnings("unchecked") // more than checked, see SimpleTypeConverter#converter for reasoning - public R convert(final Value value) + public R convert(final Value value, final Context context) { if (!outputType.isInstance(value)) { diff --git a/src/main/java/carpet/script/annotation/ValueConverter.java b/src/main/java/carpet/script/annotation/ValueConverter.java index ebf3914806..c7de8977b8 100644 --- a/src/main/java/carpet/script/annotation/ValueConverter.java +++ b/src/main/java/carpet/script/annotation/ValueConverter.java @@ -50,6 +50,7 @@ public interface ValueConverter * trying to convert to anything else, where it would be recommended to tell the user the name of the final type instead.

* * @param value The {@link Value} to convert + * @param context * @return The converted value, or {@code null} if the conversion failed in the process * @apiNote

While most implementations of this method should and will return the type from this method, implementations that require * parameters from {@link #checkAndConvert(Iterator, Context, Context.Type)} or that require multiple parameters may decide to throw @@ -59,10 +60,16 @@ public interface ValueConverter *

Implementations can also provide different implementations for this and {@link #checkAndConvert(Iterator, Context, Context.Type)}, in case * they can support it in some situations that can't be used else, such as inside of lists or maps, although they should try to provide * in {@link #checkAndConvert(Iterator, Context, Context.Type)} at least the same conversion as the one from this method.

- *

Even with the above reasons, {@link ValueConverter} users should try to implement {@link #convert(Value)} whenever possible instead of + *

Even with the above reasons, {@link ValueConverter} users should try to implement {@link #convert(Value, Context)} whenever possible instead of * {@link #checkAndConvert(Iterator, Context, Context.Type)}, since it allows its usage in generics of lists and maps.

*/ - @Nullable R convert(Value value); + @Nullable R convert(Value value, final Context context); + + @Deprecated(forRemoval = true) + default R convert(final Value value) + { + return convert(value, null); + } /** *

Returns whether this {@link ValueConverter} consumes a variable number of elements from the {@link Iterator} passed to it via @@ -176,17 +183,17 @@ static ValueConverter fromAnnotatedType(final AnnotatedType annoType) * providers like {@link Context}.

Implementations can also use more than a single parameter when being called with this function, * but in such case they must implement {@link #valueConsumption()} to return how many parameters do they consume at minimum, and, if * they may consume variable arguments, implement {@link #consumesVariableArgs()}

This method holds the same nullability - * constraints as {@link #convert(Value)}

+ * constraints as {@link #convert(Value, Context)}

* @param valueIterator An {@link Iterator} holding the {@link Value} to convert in next position * @param context The {@link Context} this function has been called with. This was used when this passed lazy values instead in order to * evaluate, now it's used to get the context * @param contextType The {@link Context.Type} that the original function was called with * @return The next {@link Value} (s) converted to the type {@code } of this {@link ValueConverter} - * @implNote This method's default implementation runs the {@link #convert(Value)} function in the next {@link Value} ignoring {@link Context} and + * @implNote This method's default implementation runs the {@link #convert(Value, Context)} function in the next {@link Value} ignoring {@link Context} and * {@code theLazyT}. */ default R checkAndConvert(final Iterator valueIterator, final Context context, final Context.Type contextType) { - return !valueIterator.hasNext() ? null : convert(valueIterator.next()); + return !valueIterator.hasNext() ? null : convert(valueIterator.next(), context); } } From 5ab4a9e44208e27e3c6c7c44a28b5d3b5f858ec8 Mon Sep 17 00:00:00 2001 From: altrisi Date: Tue, 7 Feb 2023 19:57:16 +0100 Subject: [PATCH 047/233] Document new and deprecated methods, catch exceptions --- .../annotation/SimpleTypeConverter.java | 52 +++++++++++++------ .../script/annotation/ValueConverter.java | 26 ++++++++-- 2 files changed, 58 insertions(+), 20 deletions(-) diff --git a/src/main/java/carpet/script/annotation/SimpleTypeConverter.java b/src/main/java/carpet/script/annotation/SimpleTypeConverter.java index b5229071ce..aef8f3637c 100644 --- a/src/main/java/carpet/script/annotation/SimpleTypeConverter.java +++ b/src/main/java/carpet/script/annotation/SimpleTypeConverter.java @@ -25,6 +25,7 @@ *

{@link SimpleTypeConverter}s are reused whenever asked for one, since they don't have any complexity.

* * @see #registerType(Class, Class, Function, String) + * @see #registerType(Class, Class, BiFunction, String) * * @param The type of the required input {@link Value} * @param The type that this converter converts to @@ -52,14 +53,29 @@ public final class SimpleTypeConverter implements ValueConve private final String typeName; /** - *

The default constructor for {@link SimpleTypeConverter}.

+ * Same as {@link #SimpleTypeConverter(Class, BiFunction, String)}, but without the converter function taking a {@link Context} + * + * @param inputType The required type for the input {@link Value} + * @param converter The function to convert an instance of inputType into R, with the context of the call. + * @param typeName The name of the type for error messages + * + * @see #SimpleTypeConverter(Class, BiFunction, String) + */ + public SimpleTypeConverter(final Class inputType, final Function converter, final String typeName) + { + this(inputType, (v, c) -> converter.apply(v), typeName); + } + + /** + *

A constructor for {@link SimpleTypeConverter}.

* *

This is public in order to provide an implementation to use when registering {@link ValueConverter}s for the {@link Param.Strict} annotation * registry, and it's not intended way to register new {@link SimpleTypeConverter}

Use {@link #registerType(Class, Class, Function, String)} for * that.

* * @param inputType The required type for the input {@link Value} - * @param converter The function to convert an instance of inputType into R. + * @param converter The function to convert an instance of inputType into R, with the context of the call. + * @param typeName The name of the type for error messages */ public SimpleTypeConverter(final Class inputType, final BiFunction converter, final String typeName) { @@ -69,14 +85,6 @@ public SimpleTypeConverter(final Class inputType, final BiFunction inputType, final Function converter, final String typeName) - { - super(); - this.converter = (v, c) -> converter.apply(v); - this.valueClass = inputType; - this.typeName = typeName; - } - @Override public String getTypeName() { @@ -114,17 +122,31 @@ public R convert(final Value value, final Context context) * when given {@link Value} cannot be converted to the {@code }, to follow the {@link ValueConverter} contract, but it * can also throw an {@link InternalExpressionException} by itself if really necessary. * @param typeName The name of the type, following the conventions of {@link ValueConverter#getTypeName()} + * + * @see #registerType(Class, Class, BiFunction, String) */ public static void registerType(final Class requiredInputType, final Class outputType, - final BiFunction converter, final String typeName) + final Function converter, final String typeName) { - final SimpleTypeConverter type = new SimpleTypeConverter<>(requiredInputType, converter, typeName); - byResult.put(outputType, type); + registerType(requiredInputType, outputType, (val, ctx) -> converter.apply(val), typeName); } + /** + *

Registers a new conversion from a {@link Value} subclass to a Java type, with the context of the call.

+ * + * @param The {@link Value} subtype required for this conversion, for automatic checked casting + * @param The type of the resulting object + * @param requiredInputType The {@link Class} of {@code } + * @param outputType The {@link Class} of {@code >} + * @param converter A function that converts from the given {@link Value} subtype to the given type. Should ideally return {@code null} + * when given {@link Value} cannot be converted to the {@code }, to follow the {@link ValueConverter} contract, but it + * can also throw an {@link InternalExpressionException} by itself if really necessary. + * @param typeName The name of the type, following the conventions of {@link ValueConverter#getTypeName()} + */ public static void registerType(final Class requiredInputType, final Class outputType, - final Function converter, final String typeName) + final BiFunction converter, final String typeName) { - registerType(requiredInputType, outputType, (val, ctx) -> converter.apply(val), typeName); + final SimpleTypeConverter type = new SimpleTypeConverter<>(requiredInputType, converter, typeName); + byResult.put(outputType, type); } } diff --git a/src/main/java/carpet/script/annotation/ValueConverter.java b/src/main/java/carpet/script/annotation/ValueConverter.java index c7de8977b8..ba98f8b765 100644 --- a/src/main/java/carpet/script/annotation/ValueConverter.java +++ b/src/main/java/carpet/script/annotation/ValueConverter.java @@ -49,8 +49,8 @@ public interface ValueConverter *

Functions using the converter can use {@link #getTypeName()} to get the name of the type this was trying to convert to, in case they are not * trying to convert to anything else, where it would be recommended to tell the user the name of the final type instead.

* - * @param value The {@link Value} to convert - * @param context + * @param value The {@link Value} to convert + * @param context The {@link Context} of the call * @return The converted value, or {@code null} if the conversion failed in the process * @apiNote

While most implementations of this method should and will return the type from this method, implementations that require * parameters from {@link #checkAndConvert(Iterator, Context, Context.Type)} or that require multiple parameters may decide to throw @@ -65,10 +65,27 @@ public interface ValueConverter */ @Nullable R convert(Value value, final Context context); + /** + * Old version of {@link #convert(Value)} without taking a {@link Context}.

+ * + * This shouldn't be used given converters now take a context in the convert function to allow for converting + * values in lists or other places without using static state.

+ * + * @param value The value to convert + * @return A converted value + * @deprecated Calling this method instead of {@link #convert(Value, Context)} may not return values for some converters + */ @Deprecated(forRemoval = true) default R convert(final Value value) { - return convert(value, null); + try + { + return convert(value, null); + } + catch (NullPointerException e) + { + return null; + } } /** @@ -185,8 +202,7 @@ static ValueConverter fromAnnotatedType(final AnnotatedType annoType) * they may consume variable arguments, implement {@link #consumesVariableArgs()}

This method holds the same nullability * constraints as {@link #convert(Value, Context)}

* @param valueIterator An {@link Iterator} holding the {@link Value} to convert in next position - * @param context The {@link Context} this function has been called with. This was used when this passed lazy values instead in order to - * evaluate, now it's used to get the context + * @param context The {@link Context} this function has been called with * @param contextType The {@link Context.Type} that the original function was called with * @return The next {@link Value} (s) converted to the type {@code } of this {@link ValueConverter} * @implNote This method's default implementation runs the {@link #convert(Value, Context)} function in the next {@link Value} ignoring {@link Context} and From 277872b33cb5e8569e1fbb48cf86dc03057d8978 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 8 Feb 2023 13:07:30 +0100 Subject: [PATCH 048/233] warning cleanup --- .../java/carpet/script/CarpetContext.java | 8 +- .../java/carpet/script/CarpetEventServer.java | 373 ++++----- .../java/carpet/script/CarpetExpression.java | 34 +- .../java/carpet/script/CarpetScriptHost.java | 350 ++++----- .../carpet/script/CarpetScriptServer.java | 103 +-- src/main/java/carpet/script/Context.java | 26 +- .../java/carpet/script/EntityEventsGroup.java | 40 +- src/main/java/carpet/script/Expression.java | 372 ++++----- src/main/java/carpet/script/Fluff.java | 46 +- src/main/java/carpet/script/LazyValue.java | 12 +- src/main/java/carpet/script/Module.java | 34 +- .../java/carpet/script/ScriptCommand.java | 202 ++--- src/main/java/carpet/script/ScriptHost.java | 120 +-- src/main/java/carpet/script/ScriptServer.java | 2 +- src/main/java/carpet/script/Tokenizer.java | 42 +- .../script/annotation/AnnotationParser.java | 66 +- .../script/annotation/ListConverter.java | 29 +- .../carpet/script/annotation/Locator.java | 33 +- .../script/annotation/MapConverter.java | 41 +- .../script/annotation/OptionalConverter.java | 18 +- .../script/annotation/OutputConverter.java | 14 +- .../java/carpet/script/annotation/Param.java | 48 +- .../annotation/SimpleTypeConverter.java | 21 +- .../carpet/script/annotation/ValueCaster.java | 13 +- .../script/annotation/ValueConverter.java | 14 +- .../java/carpet/script/api/Auxiliary.java | 482 ++++++------ .../carpet/script/api/BlockIterators.java | 228 +++--- src/main/java/carpet/script/api/Entities.java | 125 +-- .../java/carpet/script/api/Inventories.java | 174 +++-- .../java/carpet/script/api/Monitoring.java | 32 +- .../java/carpet/script/api/Scoreboards.java | 184 ++--- .../java/carpet/script/api/Threading.java | 24 +- .../java/carpet/script/api/WorldAccess.java | 733 +++++++++--------- .../java/carpet/script/argument/Argument.java | 2 +- .../carpet/script/argument/BlockArgument.java | 50 +- .../carpet/script/argument/FileArgument.java | 171 ++-- .../script/argument/FunctionArgument.java | 39 +- .../script/argument/Vector3Argument.java | 27 +- .../script/command/CommandArgument.java | 259 ++++--- .../carpet/script/command/CommandToken.java | 38 +- .../script/exception/BreakStatement.java | 4 +- .../exception/CarpetExpressionException.java | 6 +- .../script/exception/ContinueStatement.java | 4 +- .../script/exception/ExitStatement.java | 5 +- .../script/exception/ExpressionException.java | 19 +- .../script/exception/IntegrityException.java | 2 +- .../InternalExpressionException.java | 4 +- .../script/exception/LoadException.java | 2 +- .../exception/ProcessedThrowStatement.java | 2 +- .../script/exception/ReturnStatement.java | 2 +- .../exception/StacklessRuntimeException.java | 2 +- .../script/exception/ThrowStatement.java | 8 +- .../carpet/script/exception/Throwables.java | 14 +- .../java/carpet/script/external/Carpet.java | 28 +- .../java/carpet/script/external/Vanilla.java | 106 +-- .../carpet/script/external/VanillaClient.java | 2 +- .../carpet/script/language/Arithmetic.java | 28 +- .../carpet/script/language/ControlFlow.java | 44 +- .../script/language/DataStructures.java | 100 +-- .../carpet/script/language/Functions.java | 32 +- .../java/carpet/script/language/Loops.java | 232 +++--- .../carpet/script/language/Operators.java | 184 ++--- src/main/java/carpet/script/language/Sys.java | 123 +-- .../carpet/script/language/Threading.java | 37 +- .../carpet/script/utils/AppStoreManager.java | 141 ++-- .../java/carpet/script/utils/BiomeInfo.java | 2 +- .../java/carpet/script/utils/EntityTools.java | 16 +- .../script/utils/EquipmentInventory.java | 34 +- .../carpet/script/utils/FeatureGenerator.java | 144 ++-- .../java/carpet/script/utils/GlocalFlag.java | 12 +- .../carpet/script/utils/InputValidator.java | 8 +- .../carpet/script/utils/ParticleParser.java | 8 +- .../script/utils/PerlinNoiseSampler.java | 144 ++-- .../script/utils/ScarpetJsonDeserializer.java | 14 +- .../carpet/script/utils/ShapeDispatcher.java | 627 +++++++-------- .../carpet/script/utils/ShapesRenderer.java | 438 +++++------ .../script/utils/SimplexNoiseSampler.java | 126 +-- .../script/utils/SnoopyCommandSource.java | 56 +- .../java/carpet/script/utils/SystemInfo.java | 52 +- src/main/java/carpet/script/utils/Tracer.java | 36 +- .../java/carpet/script/utils/WorldTools.java | 25 +- .../script/utils/shapes/ShapeDirection.java | 20 +- .../script/value/AbstractListValue.java | 4 +- .../java/carpet/script/value/BlockValue.java | 97 ++- .../carpet/script/value/BooleanValue.java | 6 +- .../script/value/ContainerValueInterface.java | 2 +- .../java/carpet/script/value/EntityValue.java | 289 +++---- .../script/value/FormattedTextValue.java | 16 +- .../carpet/script/value/FrameworkValue.java | 2 +- .../script/value/FunctionAnnotationValue.java | 4 +- .../script/value/FunctionSignatureValue.java | 10 +- .../value/FunctionUnpackedArgumentsValue.java | 2 +- .../carpet/script/value/FunctionValue.java | 66 +- .../carpet/script/value/LContainerValue.java | 2 +- .../carpet/script/value/LazyListValue.java | 22 +- .../java/carpet/script/value/ListValue.java | 142 ++-- .../java/carpet/script/value/MapValue.java | 58 +- .../script/value/NBTSerializableValue.java | 220 +++--- .../java/carpet/script/value/NullValue.java | 12 +- .../carpet/script/value/NumericValue.java | 48 +- .../java/carpet/script/value/ScreenValue.java | 102 +-- .../java/carpet/script/value/StringValue.java | 8 +- .../java/carpet/script/value/ThreadValue.java | 22 +- .../java/carpet/script/value/UndefValue.java | 20 +- src/main/java/carpet/script/value/Value.java | 62 +- .../carpet/script/value/ValueConversions.java | 116 +-- 106 files changed, 4502 insertions(+), 4352 deletions(-) diff --git a/src/main/java/carpet/script/CarpetContext.java b/src/main/java/carpet/script/CarpetContext.java index 0455c1c5a2..b428c92554 100644 --- a/src/main/java/carpet/script/CarpetContext.java +++ b/src/main/java/carpet/script/CarpetContext.java @@ -18,12 +18,12 @@ public class CarpetContext extends Context public CommandSourceStack s; private final BlockPos origin; - public CarpetContext(final CarpetScriptHost host, final CommandSourceStack source) + public CarpetContext(CarpetScriptHost host, CommandSourceStack source) { this(host, source, BlockPos.ZERO); } - public CarpetContext(final ScriptHost host, final CommandSourceStack source, final BlockPos origin) + public CarpetContext(ScriptHost host, CommandSourceStack source, BlockPos origin) { super(host); s = source; @@ -60,7 +60,7 @@ public RegistryAccess registryAccess() return s.getLevel().registryAccess(); } - public Registry registry(final ResourceKey> resourceKey) + public Registry registry(ResourceKey> resourceKey) { return registryAccess().registryOrThrow(resourceKey); } @@ -75,7 +75,7 @@ public BlockPos origin() return origin; } - public void swapSource(final CommandSourceStack source) + public void swapSource(CommandSourceStack source) { s = source; } diff --git a/src/main/java/carpet/script/CarpetEventServer.java b/src/main/java/carpet/script/CarpetEventServer.java index 1867dc7628..be9b154091 100644 --- a/src/main/java/carpet/script/CarpetEventServer.java +++ b/src/main/java/carpet/script/CarpetEventServer.java @@ -70,6 +70,8 @@ import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.Vec3; +import javax.annotation.Nullable; + public class CarpetEventServer { public final List scheduledCalls = new LinkedList<>(); @@ -86,12 +88,13 @@ public enum CallbackResult public static class Callback { public final String host; + @Nullable public final String optionalTarget; public final FunctionValue function; public final List parametrizedArgs; public final CarpetScriptServer scriptServer; - public Callback(final String host, final String target, final FunctionValue function, final List parametrizedArgs, final CarpetScriptServer scriptServer) + public Callback(String host, @Nullable String target, FunctionValue function, List parametrizedArgs, CarpetScriptServer scriptServer) { this.host = host; this.function = function; @@ -106,7 +109,7 @@ public Callback(final String host, final String target, final FunctionValue func * @param sender - entity command source * @param runtimeArgs = options */ - public CallbackResult execute(final CommandSourceStack sender, List runtimeArgs) + public CallbackResult execute(CommandSourceStack sender, List runtimeArgs) { if (!this.parametrizedArgs.isEmpty()) { @@ -126,13 +129,13 @@ public CallbackResult execute(final CommandSourceStack sender, List runti * Used also in entity events * * @param sender - sender of the signal - * @param optionalRecipient - optional target player argument + * @param recipient - optional target player argument * @param runtimeArgs = options */ - public CallbackResult signal(final CommandSourceStack sender, final ServerPlayer optionalRecipient, final List runtimeArgs) + public CallbackResult signal(CommandSourceStack sender, @Nullable ServerPlayer recipient, List runtimeArgs) { // recipent of the call doesn't match the handlingHost - return optionalRecipient != null && !optionalRecipient.getScoreboardName().equals(optionalTarget) ? CallbackResult.FAIL : execute(sender, runtimeArgs); + return recipient != null && !recipient.getScoreboardName().equals(optionalTarget) ? CallbackResult.FAIL : execute(sender, runtimeArgs); } @@ -146,10 +149,10 @@ public record Signature(String function, String host, String target) { } - public static Signature fromString(final String str) + public static Signature fromString(String str) { - final Pattern find = Pattern.compile("(\\w+)(?:\\(from (\\w+)(?:/(\\w+))?\\))?"); - final Matcher matcher = find.matcher(str); + Pattern find = Pattern.compile("(\\w+)(?:\\(from (\\w+)(?:/(\\w+))?\\))?"); + Matcher matcher = find.matcher(str); if (matcher.matches()) { return new Signature(matcher.group(1), matcher.group(2), matcher.group(3)); @@ -164,7 +167,7 @@ public static class ScheduledCall extends Callback private final CarpetContext ctx; public long dueTime; - public ScheduledCall(final CarpetContext context, final FunctionValue function, final List args, final long dueTime) + public ScheduledCall(CarpetContext context, FunctionValue function, List args, long dueTime) { // ignoring target as we will be always calling self super(context.host.getName(), null, function, args, (CarpetScriptServer) context.scriptServer()); @@ -192,7 +195,7 @@ public static class CallbackList final boolean isSystem; final boolean perPlayerDistribution; - public CallbackList(final int reqArgs, final boolean isSystem, final boolean isGlobalOnly) + public CallbackList(int reqArgs, boolean isSystem, boolean isGlobalOnly) { this.callList = new ArrayList<>(); this.removedCalls = new ArrayList<>(); @@ -208,7 +211,7 @@ public List inspectCurrentCalls() return new ArrayList<>(callList); } - private void removeCallsIf(final Predicate when) + private void removeCallsIf(Predicate when) { if (!inCall && !inSignal) { @@ -218,7 +221,7 @@ private void removeCallsIf(final Predicate when) // we are ok with list growing in the meantime and parallel access, we are only scanning. for (int i = 0; i < callList.size(); i++) { - final Callback call = callList.get(i); + Callback call = callList.get(i); if (when.test(call)) { removedCalls.add(call); @@ -233,30 +236,30 @@ private void removeCallsIf(final Predicate when) * @param cmdSourceSupplier * @return Whether this event call has been cancelled */ - public boolean call(final Supplier> argumentSupplier, final Supplier cmdSourceSupplier) + public boolean call(Supplier> argumentSupplier, Supplier cmdSourceSupplier) { if (callList.isEmpty()) { return false; } - final CommandSourceStack source; + CommandSourceStack source; try { source = cmdSourceSupplier.get(); } - catch (final NullPointerException noReference) // todo figure out what happens when closing. + catch (NullPointerException noReference) // todo figure out what happens when closing. { return false; } - final CarpetScriptServer scriptServer = Vanilla.MinecraftServer_getScriptServer(source.getServer()); + CarpetScriptServer scriptServer = Vanilla.MinecraftServer_getScriptServer(source.getServer()); if (scriptServer.stopAll) { return false; } - final Boolean isCancelled = scriptServer.events.handleEvents.runIfEnabled(() -> { - final Runnable profilerToken = Carpet.startProfilerSection("Scarpet events"); - final List argv = argumentSupplier.get(); // empty for onTickDone - final String nameCheck = perPlayerDistribution ? source.getTextName() : null; + Boolean isCancelled = scriptServer.events.handleEvents.runIfEnabled(() -> { + Runnable profilerToken = Carpet.startProfilerSection("Scarpet events"); + List argv = argumentSupplier.get(); // empty for onTickDone + String nameCheck = perPlayerDistribution ? source.getTextName() : null; assert argv.size() == reqArgs; boolean cancelled = false; try @@ -266,14 +269,14 @@ public boolean call(final Supplier> argumentSupplier, final Supplier inCall = true; for (int i = 0; i < callList.size(); i++) { - final Callback call = callList.get(i); + Callback call = callList.get(i); // supressing calls where target player hosts simply don't match // handling global hosts with player targets is left to when the host is resolved (few calls deeper). if (nameCheck != null && call.optionalTarget != null && !nameCheck.equals(call.optionalTarget)) { continue; } - final CallbackResult result = call.execute(source, argv); + CallbackResult result = call.execute(source, argv); if (result == CallbackResult.CANCEL) { cancelled = true; @@ -289,7 +292,7 @@ public boolean call(final Supplier> argumentSupplier, final Supplier { inCall = false; } - for (final Callback call : removedCalls) + for (Callback call : removedCalls) { callList.remove(call); } @@ -300,7 +303,7 @@ public boolean call(final Supplier> argumentSupplier, final Supplier return isCancelled != null && isCancelled; } - public int signal(final CommandSourceStack sender, final ServerPlayer optinoalReceipient, final List callArg) + public int signal(CommandSourceStack sender, @Nullable ServerPlayer recipient, List callArg) { if (callList.isEmpty()) { @@ -313,7 +316,7 @@ public int signal(final CommandSourceStack sender, final ServerPlayer optinoalRe for (int i = 0; i < callList.size(); i++) { // skipping tracking of fails, its explicit call - if (callList.get(i).signal(sender, optinoalReceipient, callArg) == CallbackResult.SUCCESS) + if (callList.get(i).signal(sender, recipient, callArg) == CallbackResult.SUCCESS) { successes++; } @@ -326,9 +329,9 @@ public int signal(final CommandSourceStack sender, final ServerPlayer optinoalRe return successes; } - public boolean addFromExternal(final CommandSourceStack source, final String hostName, final String funName, final Consumer hostOnEventHandler, final CarpetScriptServer scriptServer) + public boolean addFromExternal(CommandSourceStack source, String hostName, String funName, Consumer hostOnEventHandler, CarpetScriptServer scriptServer) { - final ScriptHost host = scriptServer.getAppHostByName(hostName); + ScriptHost host = scriptServer.getAppHostByName(hostName); if (host == null) { // impossible call to add @@ -336,7 +339,7 @@ public boolean addFromExternal(final CommandSourceStack source, final String hos return false; } hostOnEventHandler.accept(host); - final FunctionValue udf = host.getFunction(funName); + FunctionValue udf = host.getFunction(funName); if (udf == null || udf.getArguments().size() != reqArgs) { // call won't match arguments @@ -350,7 +353,7 @@ public boolean addFromExternal(final CommandSourceStack source, final String hos { target = source.getPlayerOrException().getScoreboardName(); } - catch (final CommandSyntaxException e) + catch (CommandSyntaxException e) { Carpet.Messenger_message(source, "r Cannot add event to a player scoped app from a command without a player context"); return false; @@ -364,7 +367,7 @@ public boolean addFromExternal(final CommandSourceStack source, final String hos return true; } - public boolean addEventCallInternal(final ScriptHost host, final FunctionValue function, final List args) + public boolean addEventCallInternal(ScriptHost host, FunctionValue function, List args) { if (function == null || (function.getArguments().size() - args.size()) != reqArgs) { @@ -376,7 +379,7 @@ public boolean addEventCallInternal(final ScriptHost host, final FunctionValue f return true; } - public void removeEventCall(final String hostName, final String target, final String funName) + public void removeEventCall(String hostName, String target, String funName) { removeCallsIf((c) -> c.function.getString().equals(funName) && (Objects.equals(c.host, hostName)) @@ -384,15 +387,15 @@ public void removeEventCall(final String hostName, final String target, final St ); } - public void removeAllCalls(final CarpetScriptHost host) + public void removeAllCalls(CarpetScriptHost host) { removeCallsIf((c) -> (Objects.equals(c.host, host.getName())) && (Objects.equals(c.optionalTarget, host.user))); } - public void createChildEvents(final CarpetScriptHost host) + public void createChildEvents(CarpetScriptHost host) { - final List copyCalls = new ArrayList<>(); + List copyCalls = new ArrayList<>(); callList.forEach((c) -> { if ((Objects.equals(c.host, host.getName())) // TODO fix me @@ -414,7 +417,7 @@ public void clearEverything() callList.clear(); } - public void sortByPriority(final CarpetScriptServer scriptServer) + public void sortByPriority(CarpetScriptServer scriptServer) { callList.sort(Comparator.comparingDouble(c -> -scriptServer.getAppHostByName(c.host).eventPriority)); } @@ -424,9 +427,9 @@ public static class Event { public static final Map byName = new HashMap<>(); - public static List publicEvents(final CarpetScriptServer server) + public static List publicEvents(CarpetScriptServer server) { - final List events = byName.values().stream().filter(e -> e.isPublic).collect(Collectors.toList()); + List events = byName.values().stream().filter(e -> e.isPublic).collect(Collectors.toList()); if (server != null) { events.addAll(server.events.customEvents.values()); @@ -437,7 +440,7 @@ public static List publicEvents(final CarpetScriptServer server) public static final Event START = new Event("server_starts", 0, true) { @Override - public void onTick(final MinecraftServer server) + public void onTick(MinecraftServer server) { handler.call(Collections::emptyList, () -> server.createCommandSourceStack().withLevel(server.getLevel(Level.OVERWORLD)) @@ -448,7 +451,7 @@ public void onTick(final MinecraftServer server) public static final Event SHUTDOWN = new Event("server_shuts_down", 0, true) { @Override - public void onTick(final MinecraftServer server) + public void onTick(MinecraftServer server) { handler.call(Collections::emptyList, () -> server.createCommandSourceStack().withLevel(server.getLevel(Level.OVERWORLD)) @@ -459,7 +462,7 @@ public void onTick(final MinecraftServer server) public static final Event TICK = new Event("tick", 0, true) { @Override - public void onTick(final MinecraftServer server) + public void onTick(MinecraftServer server) { handler.call(Collections::emptyList, () -> server.createCommandSourceStack().withLevel(server.getLevel(Level.OVERWORLD)) @@ -475,7 +478,7 @@ public boolean deprecated() } @Override - public void onTick(final MinecraftServer server) + public void onTick(MinecraftServer server) { handler.call(Collections::emptyList, () -> server.createCommandSourceStack(). @@ -492,7 +495,7 @@ public boolean deprecated() } @Override - public void onTick(final MinecraftServer server) + public void onTick(MinecraftServer server) { handler.call(Collections::emptyList, () -> server.createCommandSourceStack(). @@ -503,7 +506,7 @@ public void onTick(final MinecraftServer server) public static final Event CHUNK_GENERATED = new Event("chunk_generated", 2, true) { @Override - public void onChunkEvent(final ServerLevel world, final ChunkPos chPos, final boolean generated) + public void onChunkEvent(ServerLevel world, ChunkPos chPos, boolean generated) { handler.call( () -> Arrays.asList(new NumericValue(chPos.x << 4), new NumericValue(chPos.z << 4)), @@ -514,7 +517,7 @@ public void onChunkEvent(final ServerLevel world, final ChunkPos chPos, final bo public static final Event CHUNK_LOADED = new Event("chunk_loaded", 2, true) { @Override - public void onChunkEvent(final ServerLevel world, final ChunkPos chPos, final boolean generated) + public void onChunkEvent(ServerLevel world, ChunkPos chPos, boolean generated) { handler.call( () -> Arrays.asList(new NumericValue(chPos.x << 4), new NumericValue(chPos.z << 4)), @@ -526,7 +529,7 @@ public void onChunkEvent(final ServerLevel world, final ChunkPos chPos, final bo public static final Event CHUNK_UNLOADED = new Event("chunk_unloaded", 2, true) { @Override - public void onChunkEvent(final ServerLevel world, final ChunkPos chPos, final boolean generated) + public void onChunkEvent(ServerLevel world, ChunkPos chPos, boolean generated) { handler.call( () -> Arrays.asList(new NumericValue(chPos.x << 4), new NumericValue(chPos.z << 4)), @@ -538,7 +541,7 @@ public void onChunkEvent(final ServerLevel world, final ChunkPos chPos, final bo public static final Event PLAYER_JUMPS = new Event("player_jumps", 1, false) { @Override - public boolean onPlayerEvent(final ServerPlayer player) + public boolean onPlayerEvent(ServerPlayer player) { handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); return false; @@ -547,7 +550,7 @@ public boolean onPlayerEvent(final ServerPlayer player) public static final Event PLAYER_DEPLOYS_ELYTRA = new Event("player_deploys_elytra", 1, false) { @Override - public boolean onPlayerEvent(final ServerPlayer player) + public boolean onPlayerEvent(ServerPlayer player) { handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); return false; @@ -556,7 +559,7 @@ public boolean onPlayerEvent(final ServerPlayer player) public static final Event PLAYER_WAKES_UP = new Event("player_wakes_up", 1, false) { @Override - public boolean onPlayerEvent(final ServerPlayer player) + public boolean onPlayerEvent(ServerPlayer player) { handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); return false; @@ -565,7 +568,7 @@ public boolean onPlayerEvent(final ServerPlayer player) public static final Event PLAYER_ESCAPES_SLEEP = new Event("player_escapes_sleep", 1, false) { @Override - public boolean onPlayerEvent(final ServerPlayer player) + public boolean onPlayerEvent(ServerPlayer player) { handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); return false; @@ -574,7 +577,7 @@ public boolean onPlayerEvent(final ServerPlayer player) public static final Event PLAYER_RIDES = new Event("player_rides", 5, false) { @Override - public void onMountControls(final ServerPlayer player, final float strafeSpeed, final float forwardSpeed, final boolean jumping, final boolean sneaking) + public void onMountControls(ServerPlayer player, float strafeSpeed, float forwardSpeed, boolean jumping, boolean sneaking) { handler.call(() -> Arrays.asList(new EntityValue(player), new NumericValue(forwardSpeed), new NumericValue(strafeSpeed), BooleanValue.of(jumping), BooleanValue.of(sneaking) @@ -584,7 +587,7 @@ public void onMountControls(final ServerPlayer player, final float strafeSpeed, public static final Event PLAYER_USES_ITEM = new Event("player_uses_item", 3, false) { @Override - public boolean onItemAction(final ServerPlayer player, final InteractionHand enumhand, final ItemStack itemstack) + public boolean onItemAction(ServerPlayer player, InteractionHand enumhand, ItemStack itemstack) { return handler.call(() -> Arrays.asList( @@ -597,7 +600,7 @@ public boolean onItemAction(final ServerPlayer player, final InteractionHand enu public static final Event PLAYER_CLICKS_BLOCK = new Event("player_clicks_block", 3, false) { @Override - public boolean onBlockAction(final ServerPlayer player, final BlockPos blockpos, final Direction facing) + public boolean onBlockAction(ServerPlayer player, BlockPos blockpos, Direction facing) { return handler.call(() -> Arrays.asList( @@ -610,14 +613,14 @@ public boolean onBlockAction(final ServerPlayer player, final BlockPos blockpos, public static final Event PLAYER_RIGHT_CLICKS_BLOCK = new Event("player_right_clicks_block", 6, false) { @Override - public boolean onBlockHit(final ServerPlayer player, final InteractionHand enumhand, final BlockHitResult hitRes) + public boolean onBlockHit(ServerPlayer player, InteractionHand enumhand, BlockHitResult hitRes) { return handler.call(() -> { - final ItemStack itemstack = player.getItemInHand(enumhand); - final BlockPos blockpos = hitRes.getBlockPos(); - final Direction enumfacing = hitRes.getDirection(); - final Vec3 vec3d = hitRes.getLocation().subtract(blockpos.getX(), blockpos.getY(), blockpos.getZ()); + ItemStack itemstack = player.getItemInHand(enumhand); + BlockPos blockpos = hitRes.getBlockPos(); + Direction enumfacing = hitRes.getDirection(); + Vec3 vec3d = hitRes.getLocation().subtract(blockpos.getX(), blockpos.getY(), blockpos.getZ()); return Arrays.asList( new EntityValue(player), ValueConversions.of(itemstack, player.getLevel().registryAccess()), @@ -636,13 +639,13 @@ public boolean onBlockHit(final ServerPlayer player, final InteractionHand enumh public static final Event PLAYER_INTERACTS_WITH_BLOCK = new Event("player_interacts_with_block", 5, false) { @Override - public boolean onBlockHit(final ServerPlayer player, final InteractionHand enumhand, final BlockHitResult hitRes) + public boolean onBlockHit(ServerPlayer player, InteractionHand enumhand, BlockHitResult hitRes) { handler.call(() -> { - final BlockPos blockpos = hitRes.getBlockPos(); - final Direction enumfacing = hitRes.getDirection(); - final Vec3 vec3d = hitRes.getLocation().subtract(blockpos.getX(), blockpos.getY(), blockpos.getZ()); + BlockPos blockpos = hitRes.getBlockPos(); + Direction enumfacing = hitRes.getDirection(); + Vec3 vec3d = hitRes.getLocation().subtract(blockpos.getX(), blockpos.getY(), blockpos.getZ()); return Arrays.asList( new EntityValue(player), StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand"), @@ -661,7 +664,7 @@ public boolean onBlockHit(final ServerPlayer player, final InteractionHand enumh public static final Event PLAYER_PLACING_BLOCK = new Event("player_placing_block", 4, false) { @Override - public boolean onBlockPlaced(final ServerPlayer player, final BlockPos pos, final InteractionHand enumhand, final ItemStack itemstack) + public boolean onBlockPlaced(ServerPlayer player, BlockPos pos, InteractionHand enumhand, ItemStack itemstack) { return handler.call(() -> Arrays.asList( new EntityValue(player), @@ -674,7 +677,7 @@ public boolean onBlockPlaced(final ServerPlayer player, final BlockPos pos, fina public static final Event PLAYER_PLACES_BLOCK = new Event("player_places_block", 4, false) { @Override - public boolean onBlockPlaced(final ServerPlayer player, final BlockPos pos, final InteractionHand enumhand, final ItemStack itemstack) + public boolean onBlockPlaced(ServerPlayer player, BlockPos pos, InteractionHand enumhand, ItemStack itemstack) { handler.call(() -> Arrays.asList( new EntityValue(player), @@ -688,7 +691,7 @@ public boolean onBlockPlaced(final ServerPlayer player, final BlockPos pos, fina public static final Event PLAYER_BREAK_BLOCK = new Event("player_breaks_block", 2, false) { @Override - public boolean onBlockBroken(final ServerPlayer player, final BlockPos pos, final BlockState previousBS) + public boolean onBlockBroken(ServerPlayer player, BlockPos pos, BlockState previousBS) { return handler.call( () -> Arrays.asList(new EntityValue(player), new BlockValue(previousBS, player.getLevel(), pos)), @@ -699,7 +702,7 @@ public boolean onBlockBroken(final ServerPlayer player, final BlockPos pos, fina public static final Event PLAYER_INTERACTS_WITH_ENTITY = new Event("player_interacts_with_entity", 3, false) { @Override - public boolean onEntityHandAction(final ServerPlayer player, final Entity entity, final InteractionHand enumhand) + public boolean onEntityHandAction(ServerPlayer player, Entity entity, InteractionHand enumhand) { return handler.call(() -> Arrays.asList( new EntityValue(player), new EntityValue(entity), StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand") @@ -709,9 +712,9 @@ public boolean onEntityHandAction(final ServerPlayer player, final Entity entity public static final Event PLAYER_TRADES = new Event("player_trades", 5, false) { @Override - public void onTrade(final ServerPlayer player, final Merchant merchant, final MerchantOffer tradeOffer) + public void onTrade(ServerPlayer player, Merchant merchant, MerchantOffer tradeOffer) { - final RegistryAccess regs = player.getLevel().registryAccess(); + RegistryAccess regs = player.getLevel().registryAccess(); handler.call(() -> Arrays.asList( new EntityValue(player), merchant instanceof final AbstractVillager villager ? new EntityValue(villager) : Value.NULL, @@ -724,7 +727,7 @@ public void onTrade(final ServerPlayer player, final Merchant merchant, final Me public static final Event PLAYER_PICKS_UP_ITEM = new Event("player_picks_up_item", 2, false) { @Override - public boolean onItemAction(final ServerPlayer player, final InteractionHand enumhand, final ItemStack itemstack) + public boolean onItemAction(ServerPlayer player, InteractionHand enumhand, ItemStack itemstack) { handler.call(() -> Arrays.asList(new EntityValue(player), ValueConversions.of(itemstack, player.getLevel().registryAccess())), player::createCommandSourceStack); return false; @@ -734,7 +737,7 @@ public boolean onItemAction(final ServerPlayer player, final InteractionHand enu public static final Event PLAYER_ATTACKS_ENTITY = new Event("player_attacks_entity", 2, false) { @Override - public boolean onEntityHandAction(final ServerPlayer player, final Entity entity, final InteractionHand enumhand) + public boolean onEntityHandAction(ServerPlayer player, Entity entity, InteractionHand enumhand) { return handler.call(() -> Arrays.asList(new EntityValue(player), new EntityValue(entity)), player::createCommandSourceStack); } @@ -742,7 +745,7 @@ public boolean onEntityHandAction(final ServerPlayer player, final Entity entity public static final Event PLAYER_STARTS_SNEAKING = new Event("player_starts_sneaking", 1, false) { @Override - public boolean onPlayerEvent(final ServerPlayer player) + public boolean onPlayerEvent(ServerPlayer player) { handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); return false; @@ -751,7 +754,7 @@ public boolean onPlayerEvent(final ServerPlayer player) public static final Event PLAYER_STOPS_SNEAKING = new Event("player_stops_sneaking", 1, false) { @Override - public boolean onPlayerEvent(final ServerPlayer player) + public boolean onPlayerEvent(ServerPlayer player) { handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); return false; @@ -760,7 +763,7 @@ public boolean onPlayerEvent(final ServerPlayer player) public static final Event PLAYER_STARTS_SPRINTING = new Event("player_starts_sprinting", 1, false) { @Override - public boolean onPlayerEvent(final ServerPlayer player) + public boolean onPlayerEvent(ServerPlayer player) { handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); return false; @@ -769,7 +772,7 @@ public boolean onPlayerEvent(final ServerPlayer player) public static final Event PLAYER_STOPS_SPRINTING = new Event("player_stops_sprinting", 1, false) { @Override - public boolean onPlayerEvent(final ServerPlayer player) + public boolean onPlayerEvent(ServerPlayer player) { handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); return false; @@ -779,7 +782,7 @@ public boolean onPlayerEvent(final ServerPlayer player) public static final Event PLAYER_RELEASED_ITEM = new Event("player_releases_item", 3, false) { @Override - public boolean onItemAction(final ServerPlayer player, final InteractionHand enumhand, final ItemStack itemstack) + public boolean onItemAction(ServerPlayer player, InteractionHand enumhand, ItemStack itemstack) { // this.getStackInHand(this.getActiveHand()), this.activeItemStack) handler.call(() -> @@ -794,7 +797,7 @@ public boolean onItemAction(final ServerPlayer player, final InteractionHand enu public static final Event PLAYER_FINISHED_USING_ITEM = new Event("player_finishes_using_item", 3, false) { @Override - public boolean onItemAction(final ServerPlayer player, final InteractionHand enumhand, final ItemStack itemstack) + public boolean onItemAction(ServerPlayer player, InteractionHand enumhand, ItemStack itemstack) { // this.getStackInHand(this.getActiveHand()), this.activeItemStack) return handler.call(() -> @@ -808,7 +811,7 @@ public boolean onItemAction(final ServerPlayer player, final InteractionHand enu public static final Event PLAYER_DROPS_ITEM = new Event("player_drops_item", 1, false) { @Override - public boolean onPlayerEvent(final ServerPlayer player) + public boolean onPlayerEvent(ServerPlayer player) { return handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); } @@ -816,7 +819,7 @@ public boolean onPlayerEvent(final ServerPlayer player) public static final Event PLAYER_DROPS_STACK = new Event("player_drops_stack", 1, false) { @Override - public boolean onPlayerEvent(final ServerPlayer player) + public boolean onPlayerEvent(ServerPlayer player) { return handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); } @@ -824,12 +827,12 @@ public boolean onPlayerEvent(final ServerPlayer player) public static final Event PLAYER_CHOOSES_RECIPE = new Event("player_chooses_recipe", 3, false) { @Override - public boolean onRecipeSelected(final ServerPlayer player, final ResourceLocation recipe, final boolean fullStack) + public boolean onRecipeSelected(ServerPlayer player, ResourceLocation recipe, boolean fullStack) { return handler.call(() -> Arrays.asList( new EntityValue(player), - StringValue.of(NBTSerializableValue.nameFromRegistryId(recipe)), + NBTSerializableValue.nameFromRegistryId(recipe), BooleanValue.of(fullStack) ), player::createCommandSourceStack); } @@ -837,7 +840,7 @@ public boolean onRecipeSelected(final ServerPlayer player, final ResourceLocatio public static final Event PLAYER_SWITCHES_SLOT = new Event("player_switches_slot", 3, false) { @Override - public void onSlotSwitch(final ServerPlayer player, final int from, final int to) + public void onSlotSwitch(ServerPlayer player, int from, int to) { if (from == to) { @@ -854,7 +857,7 @@ public void onSlotSwitch(final ServerPlayer player, final int from, final int to public static final Event PLAYER_SWAPS_HANDS = new Event("player_swaps_hands", 1, false) { @Override - public boolean onPlayerEvent(final ServerPlayer player) + public boolean onPlayerEvent(ServerPlayer player) { return handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); } @@ -862,7 +865,7 @@ public boolean onPlayerEvent(final ServerPlayer player) public static final Event PLAYER_SWINGS_HAND = new Event("player_swings_hand", 2, false) { @Override - public void onHandAction(final ServerPlayer player, final InteractionHand hand) + public void onHandAction(ServerPlayer player, InteractionHand hand) { handler.call(() -> Arrays.asList( new EntityValue(player), @@ -874,7 +877,7 @@ public void onHandAction(final ServerPlayer player, final InteractionHand hand) public static final Event PLAYER_TAKES_DAMAGE = new Event("player_takes_damage", 4, false) { @Override - public boolean onDamage(final Entity target, final float amount, final DamageSource source) + public boolean onDamage(Entity target, float amount, DamageSource source) { return handler.call(() -> Arrays.asList( @@ -888,7 +891,7 @@ public boolean onDamage(final Entity target, final float amount, final DamageSou public static final Event PLAYER_DEALS_DAMAGE = new Event("player_deals_damage", 3, false) { @Override - public boolean onDamage(final Entity target, final float amount, final DamageSource source) + public boolean onDamage(Entity target, float amount, DamageSource source) { return handler.call(() -> Arrays.asList(new EntityValue(source.getEntity()), new NumericValue(amount), new EntityValue(target)), @@ -899,7 +902,7 @@ public boolean onDamage(final Entity target, final float amount, final DamageSou public static final Event PLAYER_COLLIDES_WITH_ENTITY = new Event("player_collides_with_entity", 2, false) { @Override - public boolean onEntityHandAction(final ServerPlayer player, final Entity entity, final InteractionHand enumhand) + public boolean onEntityHandAction(ServerPlayer player, Entity entity, InteractionHand enumhand) { handler.call(() -> Arrays.asList(new EntityValue(player), new EntityValue(entity)), player::createCommandSourceStack); return false; @@ -909,7 +912,7 @@ public boolean onEntityHandAction(final ServerPlayer player, final Entity entity public static final Event PLAYER_DIES = new Event("player_dies", 1, false) { @Override - public boolean onPlayerEvent(final ServerPlayer player) + public boolean onPlayerEvent(ServerPlayer player) { handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); return false; @@ -918,7 +921,7 @@ public boolean onPlayerEvent(final ServerPlayer player) public static final Event PLAYER_RESPAWNS = new Event("player_respawns", 1, false) { @Override - public boolean onPlayerEvent(final ServerPlayer player) + public boolean onPlayerEvent(ServerPlayer player) { handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); return false; @@ -927,13 +930,13 @@ public boolean onPlayerEvent(final ServerPlayer player) public static final Event PLAYER_CHANGES_DIMENSION = new Event("player_changes_dimension", 5, false) { @Override - public void onDimensionChange(final ServerPlayer player, final Vec3 from, final Vec3 to, final ResourceKey fromDim, final ResourceKey dimTo) + public void onDimensionChange(ServerPlayer player, Vec3 from, Vec3 to, ResourceKey fromDim, ResourceKey dimTo) { // eligibility already checked in mixin - final Value fromValue = ListValue.fromTriple(from.x, from.y, from.z); - final Value toValue = (to == null) ? Value.NULL : ListValue.fromTriple(to.x, to.y, to.z); - final Value fromDimStr = new StringValue(NBTSerializableValue.nameFromRegistryId(fromDim.location())); - final Value toDimStr = new StringValue(NBTSerializableValue.nameFromRegistryId(dimTo.location())); + Value fromValue = ListValue.fromTriple(from.x, from.y, from.z); + Value toValue = (to == null) ? Value.NULL : ListValue.fromTriple(to.x, to.y, to.z); + Value fromDimStr = NBTSerializableValue.nameFromRegistryId(fromDim.location()); + Value toDimStr = NBTSerializableValue.nameFromRegistryId(dimTo.location()); handler.call(() -> Arrays.asList(new EntityValue(player), fromValue, fromDimStr, toValue, toDimStr), player::createCommandSourceStack); } @@ -941,7 +944,7 @@ public void onDimensionChange(final ServerPlayer player, final Vec3 from, final public static final Event PLAYER_CONNECTS = new Event("player_connects", 1, false) { @Override - public boolean onPlayerEvent(final ServerPlayer player) + public boolean onPlayerEvent(ServerPlayer player) { handler.call(() -> Collections.singletonList(new EntityValue(player)), player::createCommandSourceStack); return false; @@ -950,7 +953,7 @@ public boolean onPlayerEvent(final ServerPlayer player) public static final Event PLAYER_DISCONNECTS = new Event("player_disconnects", 2, false) { @Override - public boolean onPlayerMessage(final ServerPlayer player, final String message) + public boolean onPlayerMessage(ServerPlayer player, String message) { handler.call(() -> Arrays.asList(new EntityValue(player), new StringValue(message)), player::createCommandSourceStack); return false; @@ -960,7 +963,7 @@ public boolean onPlayerMessage(final ServerPlayer player, final String message) public static final Event PLAYER_MESSAGE = new Event("player_message", 2, false) { @Override - public boolean onPlayerMessage(final ServerPlayer player, final String message) + public boolean onPlayerMessage(ServerPlayer player, String message) { return handler.call(() -> Arrays.asList(new EntityValue(player), new StringValue(message)), player::createCommandSourceStack); } @@ -969,7 +972,7 @@ public boolean onPlayerMessage(final ServerPlayer player, final String message) public static final Event PLAYER_COMMAND = new Event("player_command", 2, false) { @Override - public boolean onPlayerMessage(final ServerPlayer player, final String message) + public boolean onPlayerMessage(ServerPlayer player, String message) { return handler.call(() -> Arrays.asList(new EntityValue(player), new StringValue(message)), player::createCommandSourceStack); } @@ -977,7 +980,7 @@ public boolean onPlayerMessage(final ServerPlayer player, final String message) public static final Event STATISTICS = new Event("statistic", 4, false) { - private ResourceLocation getStatId(final Stat stat) + private ResourceLocation getStatId(Stat stat) { return stat.getType().getRegistry().getKey(stat.getValue()); } @@ -990,18 +993,18 @@ private ResourceLocation getStatId(final Stat stat) ); @Override - public void onPlayerStatistic(final ServerPlayer player, final Stat stat, final int amount) + public void onPlayerStatistic(ServerPlayer player, Stat stat, int amount) { - final ResourceLocation id = getStatId(stat); + ResourceLocation id = getStatId(stat); if (skippedStats.contains(id)) { return; } - final Registry> registry = player.getLevel().registryAccess().registryOrThrow(Registries.STAT_TYPE); + Registry> registry = player.getLevel().registryAccess().registryOrThrow(Registries.STAT_TYPE); handler.call(() -> Arrays.asList( new EntityValue(player), - StringValue.of(NBTSerializableValue.nameFromRegistryId(registry.getKey(stat.getType()))), - StringValue.of(NBTSerializableValue.nameFromRegistryId(id)), + NBTSerializableValue.nameFromRegistryId(registry.getKey(stat.getType())), + NBTSerializableValue.nameFromRegistryId(id), new NumericValue(amount) ), player::createCommandSourceStack); } @@ -1009,7 +1012,7 @@ public void onPlayerStatistic(final ServerPlayer player, final Stat stat, fin public static final Event LIGHTNING = new Event("lightning", 2, true) { @Override - public void onWorldEventFlag(final ServerLevel world, final BlockPos pos, final int flag) + public void onWorldEventFlag(ServerLevel world, BlockPos pos, int flag) { handler.call( () -> Arrays.asList( @@ -1021,7 +1024,7 @@ public void onWorldEventFlag(final ServerLevel world, final BlockPos pos, final }; //copy of Explosion.getCausingEntity() #TRACK# - private static LivingEntity getExplosionCausingEntity(final Entity entity) + private static LivingEntity getExplosionCausingEntity(Entity entity) { if (entity == null) { @@ -1037,7 +1040,7 @@ else if (entity instanceof final LivingEntity le) } else if (entity instanceof final Projectile p) { - final Entity owner = p.getOwner(); + Entity owner = p.getOwner(); if (owner instanceof final LivingEntity le) { return le; @@ -1049,7 +1052,7 @@ else if (entity instanceof final Projectile p) public static final Event EXPLOSION_OUTCOME = new Event("explosion_outcome", 8, true) { @Override - public void onExplosion(final ServerLevel world, final Entity e, final Supplier attacker, final double x, final double y, final double z, final float power, final boolean createFire, final List affectedBlocks, final List affectedEntities, final Explosion.BlockInteraction type) + public void onExplosion(ServerLevel world, Entity e, Supplier attacker, double x, double y, double z, float power, boolean createFire, List affectedBlocks, List affectedEntities, Explosion.BlockInteraction type) { handler.call( () -> Arrays.asList( @@ -1072,7 +1075,7 @@ public void onExplosion(final ServerLevel world, final Entity e, final Supplier< public static final Event EXPLOSION = new Event("explosion", 6, true) { @Override - public void onExplosion(final ServerLevel world, final Entity e, final Supplier attacker, final double x, final double y, final double z, final float power, final boolean createFire, final List affectedBlocks, final List affectedEntities, final Explosion.BlockInteraction type) + public void onExplosion(ServerLevel world, Entity e, Supplier attacker, double x, double y, double z, float power, boolean createFire, List affectedBlocks, List affectedEntities, Explosion.BlockInteraction type) { handler.call( () -> Arrays.asList( @@ -1088,7 +1091,7 @@ public void onExplosion(final ServerLevel world, final Entity e, final Supplier< }; @Deprecated - public static String getEntityLoadEventName(final EntityType et) + public static String getEntityLoadEventName(EntityType et) { return "entity_loaded_" + ValueConversions.of(BuiltInRegistries.ENTITY_TYPE.getKey(et)).getString(); } @@ -1099,7 +1102,7 @@ public static String getEntityLoadEventName(final EntityType e .map(et -> Map.entry(et, new Event(getEntityLoadEventName(et), 1, true, false) { @Override - public void onEntityAction(final Entity entity, final boolean created) + public void onEntityAction(Entity entity, boolean created) { handler.call( () -> Collections.singletonList(new EntityValue(entity)), @@ -1108,7 +1111,7 @@ public void onEntityAction(final Entity entity, final boolean created) } })).collect(Collectors.toUnmodifiableMap(Map.Entry::getKey, Map.Entry::getValue)); - public static String getEntityHandlerEventName(final EntityType et) + public static String getEntityHandlerEventName(EntityType et) { return "entity_handler_" + ValueConversions.of(BuiltInRegistries.ENTITY_TYPE.getKey(et)).getString(); } @@ -1118,7 +1121,7 @@ public static String getEntityHandlerEventName(final EntityType Map.entry(et, new Event(getEntityHandlerEventName(et), 2, true, false) { @Override - public void onEntityAction(final Entity entity, final boolean created) + public void onEntityAction(Entity entity, boolean created) { handler.call( () -> Arrays.asList(new EntityValue(entity), BooleanValue.of(created)), @@ -1135,12 +1138,12 @@ public void onEntityAction(final Entity entity, final boolean created) public final CallbackList handler; public final boolean isPublic; // public events can be targetted with __on_ defs - public Event(final String name, final int reqArgs, final boolean isGlobalOnly) + public Event(String name, int reqArgs, boolean isGlobalOnly) { this(name, reqArgs, isGlobalOnly, true); } - public Event(final String name, final int reqArgs, final boolean isGlobalOnly, final boolean isPublic) + public Event(String name, int reqArgs, boolean isGlobalOnly, boolean isPublic) { this.name = name; this.handler = new CallbackList(reqArgs, true, isGlobalOnly); @@ -1148,9 +1151,9 @@ public Event(final String name, final int reqArgs, final boolean isGlobalOnly, f byName.put(name, this); } - public static List getAllEvents(final CarpetScriptServer server, final Predicate predicate) + public static List getAllEvents(CarpetScriptServer server, Predicate predicate) { - final List eventList = new ArrayList<>(CarpetEventServer.Event.byName.values()); + List eventList = new ArrayList<>(CarpetEventServer.Event.byName.values()); eventList.addAll(server.events.customEvents.values()); if (predicate == null) { @@ -1159,7 +1162,7 @@ public static List getAllEvents(final CarpetScriptServer server, final Pr return eventList.stream().filter(predicate).toList(); } - public static Event getEvent(final String name, final CarpetScriptServer server) + public static Event getEvent(String name, CarpetScriptServer server) { if (byName.containsKey(name)) { @@ -1168,9 +1171,9 @@ public static Event getEvent(final String name, final CarpetScriptServer server) return server.events.customEvents.get(name); } - public static Event getOrCreateCustom(final String name, final CarpetScriptServer server) + public static Event getOrCreateCustom(String name, CarpetScriptServer server) { - final Event event = getEvent(name, server); + Event event = getEvent(name, server); if (event != null) { return event; @@ -1178,13 +1181,13 @@ public static Event getOrCreateCustom(final String name, final CarpetScriptServe return new Event(name, server); } - public static void removeAllHostEvents(final CarpetScriptHost host) + public static void removeAllHostEvents(CarpetScriptHost host) { byName.values().forEach((e) -> e.handler.removeAllCalls(host)); host.scriptServer().events.customEvents.values().forEach((e) -> e.handler.removeAllCalls(host)); } - public static void transferAllHostEventsToChild(final CarpetScriptHost host) + public static void transferAllHostEventsToChild(CarpetScriptHost host) { byName.values().forEach((e) -> e.handler.createChildEvents(host)); host.scriptServer().events.customEvents.values().forEach((e) -> e.handler.createChildEvents(host)); @@ -1196,7 +1199,7 @@ public static void clearAllBuiltinEvents() } // custom event constructor - private Event(final String name, final CarpetScriptServer server) + private Event(String name, CarpetScriptServer server) { this.name = name; this.handler = new CallbackList(1, false, false); @@ -1218,109 +1221,109 @@ public boolean deprecated() } //stubs for calls just to ease calls in vanilla code so they don't need to deal with scarpet value types - public void onTick(final MinecraftServer server) + public void onTick(MinecraftServer server) { } - public void onChunkEvent(final ServerLevel world, final ChunkPos chPos, final boolean generated) + public void onChunkEvent(ServerLevel world, ChunkPos chPos, boolean generated) { } - public boolean onPlayerEvent(final ServerPlayer player) + public boolean onPlayerEvent(ServerPlayer player) { return false; } - public boolean onPlayerMessage(final ServerPlayer player, final String message) + public boolean onPlayerMessage(ServerPlayer player, String message) { return false; } - public void onPlayerStatistic(final ServerPlayer player, final Stat stat, final int amount) + public void onPlayerStatistic(ServerPlayer player, Stat stat, int amount) { } - public void onMountControls(final ServerPlayer player, final float strafeSpeed, final float forwardSpeed, final boolean jumping, final boolean sneaking) + public void onMountControls(ServerPlayer player, float strafeSpeed, float forwardSpeed, boolean jumping, boolean sneaking) { } - public boolean onItemAction(final ServerPlayer player, final InteractionHand enumhand, final ItemStack itemstack) + public boolean onItemAction(ServerPlayer player, InteractionHand enumhand, ItemStack itemstack) { return false; } - public boolean onBlockAction(final ServerPlayer player, final BlockPos blockpos, final Direction facing) + public boolean onBlockAction(ServerPlayer player, BlockPos blockpos, Direction facing) { return false; } - public boolean onBlockHit(final ServerPlayer player, final InteractionHand enumhand, final BlockHitResult hitRes) + public boolean onBlockHit(ServerPlayer player, InteractionHand enumhand, BlockHitResult hitRes) { return false; } - public boolean onBlockBroken(final ServerPlayer player, final BlockPos pos, final BlockState previousBS) + public boolean onBlockBroken(ServerPlayer player, BlockPos pos, BlockState previousBS) { return false; } - public boolean onBlockPlaced(final ServerPlayer player, final BlockPos pos, final InteractionHand enumhand, final ItemStack itemstack) + public boolean onBlockPlaced(ServerPlayer player, BlockPos pos, InteractionHand enumhand, ItemStack itemstack) { return false; } - public boolean onEntityHandAction(final ServerPlayer player, final Entity entity, final InteractionHand enumhand) + public boolean onEntityHandAction(ServerPlayer player, Entity entity, InteractionHand enumhand) { return false; } - public void onHandAction(final ServerPlayer player, final InteractionHand enumhand) + public void onHandAction(ServerPlayer player, InteractionHand enumhand) { } - public void onEntityAction(final Entity entity, final boolean created) + public void onEntityAction(Entity entity, boolean created) { } - public void onDimensionChange(final ServerPlayer player, final Vec3 from, final Vec3 to, final ResourceKey fromDim, final ResourceKey dimTo) + public void onDimensionChange(ServerPlayer player, Vec3 from, Vec3 to, ResourceKey fromDim, ResourceKey dimTo) { } - public boolean onDamage(final Entity target, final float amount, final DamageSource source) + public boolean onDamage(Entity target, float amount, DamageSource source) { return false; } - public boolean onRecipeSelected(final ServerPlayer player, final ResourceLocation recipe, final boolean fullStack) + public boolean onRecipeSelected(ServerPlayer player, ResourceLocation recipe, boolean fullStack) { return false; } - public void onSlotSwitch(final ServerPlayer player, final int from, final int to) + public void onSlotSwitch(ServerPlayer player, int from, int to) { } - public void onTrade(final ServerPlayer player, final Merchant merchant, final MerchantOffer tradeOffer) + public void onTrade(ServerPlayer player, Merchant merchant, MerchantOffer tradeOffer) { } - public void onExplosion(final ServerLevel world, final Entity e, final Supplier attacker, final double x, final double y, final double z, final float power, final boolean createFire, final List affectedBlocks, final List affectedEntities, final Explosion.BlockInteraction type) + public void onExplosion(ServerLevel world, Entity e, Supplier attacker, double x, double y, double z, float power, boolean createFire, List affectedBlocks, List affectedEntities, Explosion.BlockInteraction type) { } - public void onWorldEvent(final ServerLevel world, final BlockPos pos) + public void onWorldEvent(ServerLevel world, BlockPos pos) { } - public void onWorldEventFlag(final ServerLevel world, final BlockPos pos, final int flag) + public void onWorldEventFlag(ServerLevel world, BlockPos pos, int flag) { } - public void handleAny(final Object... args) + public void handleAny(Object... args) { } - public void onCustomPlayerEvent(final ServerPlayer player, final Object... args) + public void onCustomPlayerEvent(ServerPlayer player, Object... args) { if (handler.reqArgs != (args.length + 1)) { @@ -1328,9 +1331,9 @@ public void onCustomPlayerEvent(final ServerPlayer player, final Object... args) } handler.call( () -> { - final List valArgs = new ArrayList<>(); + List valArgs = new ArrayList<>(); valArgs.add(EntityValue.of(player)); - for (final Object o : args) + for (Object o : args) { valArgs.add(ValueConversions.guess(player.getLevel(), o)); } @@ -1339,7 +1342,7 @@ public void onCustomPlayerEvent(final ServerPlayer player, final Object... args) ); } - public void onCustomWorldEvent(final ServerLevel world, final Object... args) + public void onCustomWorldEvent(ServerLevel world, Object... args) { if (handler.reqArgs != args.length) { @@ -1347,8 +1350,8 @@ public void onCustomWorldEvent(final ServerLevel world, final Object... args) } handler.call( () -> { - final List valArgs = new ArrayList<>(); - for (final Object o : args) + List valArgs = new ArrayList<>(); + for (Object o : args) { valArgs.add(ValueConversions.guess(world, o)); } @@ -1359,7 +1362,7 @@ public void onCustomWorldEvent(final ServerLevel world, final Object... args) } - public CarpetEventServer(final CarpetScriptServer scriptServer) + public CarpetEventServer(CarpetScriptServer scriptServer) { this.scriptServer = scriptServer; Event.clearAllBuiltinEvents(); @@ -1371,11 +1374,11 @@ public void tick() { return; } - final Iterator eventIterator = scheduledCalls.iterator(); - final List currentCalls = new ArrayList<>(); + Iterator eventIterator = scheduledCalls.iterator(); + List currentCalls = new ArrayList<>(); while (eventIterator.hasNext()) { - final ScheduledCall call = eventIterator.next(); + ScheduledCall call = eventIterator.next(); call.dueTime--; if (call.dueTime <= 0) { @@ -1383,19 +1386,19 @@ public void tick() eventIterator.remove(); } } - for (final ScheduledCall call : currentCalls) + for (ScheduledCall call : currentCalls) { call.execute(); } } - public void scheduleCall(final CarpetContext context, final FunctionValue function, final List args, final long due) + public void scheduleCall(CarpetContext context, FunctionValue function, List args, long due) { scheduledCalls.add(new ScheduledCall(context, function, args, due)); } - public void runScheduledCall(final BlockPos origin, final CommandSourceStack source, final String hostname, final CarpetScriptHost host, final FunctionValue udf, final List argv) + public void runScheduledCall(BlockPos origin, CommandSourceStack source, String hostname, CarpetScriptHost host, FunctionValue udf, List argv) { if (hostname != null && !scriptServer.modules.containsKey(hostname)) // well - scheduled call app got unloaded { @@ -1405,14 +1408,14 @@ public void runScheduledCall(final BlockPos origin, final CommandSourceStack sou { host.callUDF(origin, source, udf, argv); } - catch (final NullPointerException | InvalidCallbackException | IntegrityException ignored) + catch (NullPointerException | InvalidCallbackException | IntegrityException ignored) { } } - public CallbackResult runEventCall(final CommandSourceStack sender, final String hostname, final String optionalTarget, final FunctionValue udf, final List argv) + public CallbackResult runEventCall(CommandSourceStack sender, String hostname, String optionalTarget, FunctionValue udf, List argv) { - final CarpetScriptHost appHost = scriptServer.getAppHostByName(hostname); + CarpetScriptHost appHost = scriptServer.getAppHostByName(hostname); // no such app if (appHost == null) { @@ -1432,32 +1435,32 @@ public CallbackResult runEventCall(final CommandSourceStack sender, final String return CallbackResult.FAIL; } } - final CommandSourceStack source = sender.withPermission(Vanilla.MinecraftServer_getRunPermissionLevel(sender.getServer())); - final CarpetScriptHost executingHost = appHost.retrieveForExecution(sender, target); + CommandSourceStack source = sender.withPermission(Vanilla.MinecraftServer_getRunPermissionLevel(sender.getServer())); + CarpetScriptHost executingHost = appHost.retrieveForExecution(sender, target); if (executingHost == null) { return CallbackResult.FAIL; } try { - final Value returnValue = executingHost.callUDF(source, udf, argv); + Value returnValue = executingHost.callUDF(source, udf, argv); return returnValue instanceof StringValue && returnValue.getString().equals("cancel") ? CallbackResult.CANCEL : CallbackResult.SUCCESS; } - catch (final NullPointerException | InvalidCallbackException | IntegrityException error) + catch (NullPointerException | InvalidCallbackException | IntegrityException error) { CarpetScriptServer.LOG.error("Got exception when running event call ", error); return CallbackResult.FAIL; } } - public boolean addEventFromCommand(final CommandSourceStack source, final String event, final String host, final String funName) + public boolean addEventFromCommand(CommandSourceStack source, String event, String host, String funName) { - final Event ev = Event.getEvent(event, scriptServer); + Event ev = Event.getEvent(event, scriptServer); if (ev == null) { return false; } - final boolean added = ev.handler.addFromExternal(source, host, funName, h -> onEventAddedToHost(ev, h), scriptServer); + boolean added = ev.handler.addFromExternal(source, host, funName, h -> onEventAddedToHost(ev, h), scriptServer); if (added) { Carpet.Messenger_message(source, "gi Added " + funName + " to " + event); @@ -1465,32 +1468,32 @@ public boolean addEventFromCommand(final CommandSourceStack source, final String return added; } - public void addBuiltInEvent(final String event, final ScriptHost host, final FunctionValue function, final List args) + public void addBuiltInEvent(String event, ScriptHost host, FunctionValue function, List args) { // this is globals only - final Event ev = Event.byName.get(event); + Event ev = Event.byName.get(event); onEventAddedToHost(ev, host); - final boolean success = ev.handler.addEventCallInternal(host, function, args == null ? NOARGS : args); + boolean success = ev.handler.addEventCallInternal(host, function, args == null ? NOARGS : args); if (!success) { throw new InternalExpressionException("Global event " + event + " requires " + ev.handler.reqArgs + ", not " + (function.getNumParams() - ((args == null) ? 0 : args.size()))); } } - public boolean handleCustomEvent(final String event, final CarpetScriptHost host, final FunctionValue function, final List args) + public boolean handleCustomEvent(String event, CarpetScriptHost host, FunctionValue function, List args) { - final Event ev = Event.getOrCreateCustom(event, scriptServer); + Event ev = Event.getOrCreateCustom(event, scriptServer); onEventAddedToHost(ev, host); return ev.handler.addEventCallInternal(host, function, args == null ? NOARGS : args); } - public int signalEvent(final String event, final CarpetContext cc, final ServerPlayer optionalTarget, final List callArgs) + public int signalEvent(String event, CarpetContext cc, @Nullable ServerPlayer target, List callArgs) { - final Event ev = Event.getEvent(event, ((CarpetScriptHost) cc.host).scriptServer()); - return ev == null ? -1 : ev.handler.signal(cc.source(), optionalTarget, callArgs); + Event ev = Event.getEvent(event, ((CarpetScriptHost) cc.host).scriptServer()); + return ev == null ? -1 : ev.handler.signal(cc.source(), target, callArgs); } - private void onEventAddedToHost(final Event event, final ScriptHost host) + private void onEventAddedToHost(Event event, ScriptHost host) { if (event.deprecated()) { @@ -1499,24 +1502,24 @@ private void onEventAddedToHost(final Event event, final ScriptHost host) event.handler.sortByPriority(this.scriptServer); } - public boolean removeEventFromCommand(final CommandSourceStack source, final String event, final String funName) + public boolean removeEventFromCommand(CommandSourceStack source, String event, String funName) { - final Event ev = Event.getEvent(event, scriptServer); + Event ev = Event.getEvent(event, scriptServer); if (ev == null) { Carpet.Messenger_message(source, "r Unknown event: " + event); return false; } - final Callback.Signature call = Callback.fromString(funName); + Callback.Signature call = Callback.fromString(funName); ev.handler.removeEventCall(call.host, call.target, call.function); // could verified if actually removed Carpet.Messenger_message(source, "gi Removed event: " + funName + " from " + event); return true; } - public boolean removeBuiltInEvent(final String event, final CarpetScriptHost host) + public boolean removeBuiltInEvent(String event, CarpetScriptHost host) { - final Event ev = Event.getEvent(event, host.scriptServer()); + Event ev = Event.getEvent(event, host.scriptServer()); if (ev == null) { return false; @@ -1525,22 +1528,22 @@ public boolean removeBuiltInEvent(final String event, final CarpetScriptHost hos return true; } - public void removeBuiltInEvent(final String event, final CarpetScriptHost host, final String funName) + public void removeBuiltInEvent(String event, CarpetScriptHost host, String funName) { - final Event ev = Event.getEvent(event, host.scriptServer()); + Event ev = Event.getEvent(event, host.scriptServer()); if (ev != null) { ev.handler.removeEventCall(host.getName(), host.user, funName); } } - public void removeAllHostEvents(final CarpetScriptHost host) + public void removeAllHostEvents(CarpetScriptHost host) { // remove event handlers Event.removeAllHostEvents(host); if (host.isPerUser()) { - for (final ScriptHost child : host.userHosts.values()) + for (ScriptHost child : host.userHosts.values()) { Event.removeAllHostEvents((CarpetScriptHost) child); } diff --git a/src/main/java/carpet/script/CarpetExpression.java b/src/main/java/carpet/script/CarpetExpression.java index e35976880b..8535812a65 100644 --- a/src/main/java/carpet/script/CarpetExpression.java +++ b/src/main/java/carpet/script/CarpetExpression.java @@ -42,7 +42,7 @@ public BlockPos getOrigin() return origin; } - public CarpetExpression(final Module module, final String expression, final CommandSourceStack source, final BlockPos origin) + public CarpetExpression(Module module, String expression, CommandSourceStack source, BlockPos origin) { this.origin = origin; this.source = source; @@ -61,7 +61,7 @@ public CarpetExpression(final Module module, final String expression, final Comm Carpet.handleExtensionsAPI(this); } - public boolean fillAndScanCommand(final ScriptHost host, final int x, final int y, final int z) + public boolean fillAndScanCommand(ScriptHost host, int x, int y, int z) { CarpetScriptServer scriptServer = (CarpetScriptServer) host.scriptServer(); if (scriptServer.stopAll) @@ -70,39 +70,39 @@ public boolean fillAndScanCommand(final ScriptHost host, final int x, final int } try { - final Context context = new CarpetContext(host, source, origin). + Context context = new CarpetContext(host, source, origin). with("x", (c, t) -> new NumericValue(x - origin.getX()).bindTo("x")). with("y", (c, t) -> new NumericValue(y - origin.getY()).bindTo("y")). with("z", (c, t) -> new NumericValue(z - origin.getZ()).bindTo("z")). with("_", (c, t) -> new BlockValue(null, source.getLevel(), new BlockPos(x, y, z)).bindTo("_")); - final Entity e = source.getEntity(); + Entity e = source.getEntity(); if (e == null) { - final Value nullPlayer = Value.NULL.reboundedTo("p"); + Value nullPlayer = Value.NULL.reboundedTo("p"); context.with("p", (cc, tt) -> nullPlayer); } else { - final Value playerValue = new EntityValue(e).bindTo("p"); + Value playerValue = new EntityValue(e).bindTo("p"); context.with("p", (cc, tt) -> playerValue); } return scriptServer.events.handleEvents.getWhileDisabled(() -> this.expr.eval(context).getBoolean()); } - catch (final ExpressionException e) + catch (ExpressionException e) { throw new CarpetExpressionException(e.getMessage(), e.stack); } - catch (final ArithmeticException ae) + catch (ArithmeticException ae) { throw new CarpetExpressionException("Math doesn't compute... " + ae.getMessage(), null); } - catch (final StackOverflowError soe) + catch (StackOverflowError soe) { throw new CarpetExpressionException("Your thoughts are too deep", null); } } - public Value scriptRunCommand(final ScriptHost host, final BlockPos pos) + public Value scriptRunCommand(ScriptHost host, BlockPos pos) { CarpetScriptServer scriptServer = (CarpetScriptServer) host.scriptServer(); if (scriptServer.stopAll) @@ -111,32 +111,32 @@ public Value scriptRunCommand(final ScriptHost host, final BlockPos pos) } try { - final Context context = new CarpetContext(host, source, origin). + Context context = new CarpetContext(host, source, origin). with("x", (c, t) -> new NumericValue(pos.getX() - origin.getX()).bindTo("x")). with("y", (c, t) -> new NumericValue(pos.getY() - origin.getY()).bindTo("y")). with("z", (c, t) -> new NumericValue(pos.getZ() - origin.getZ()).bindTo("z")); - final Entity e = source.getEntity(); + Entity e = source.getEntity(); if (e == null) { - final Value nullPlayer = Value.NULL.reboundedTo("p"); + Value nullPlayer = Value.NULL.reboundedTo("p"); context.with("p", (cc, tt) -> nullPlayer); } else { - final Value playerValue = new EntityValue(e).bindTo("p"); + Value playerValue = new EntityValue(e).bindTo("p"); context.with("p", (cc, tt) -> playerValue); } return scriptServer.events.handleEvents.getWhileDisabled(() -> this.expr.eval(context)); } - catch (final ExpressionException e) + catch (ExpressionException e) { throw new CarpetExpressionException(e.getMessage(), e.stack); } - catch (final ArithmeticException ae) + catch (ArithmeticException ae) { throw new CarpetExpressionException("Math doesn't compute... " + ae.getMessage(), null); } - catch (final StackOverflowError soe) + catch (StackOverflowError soe) { throw new CarpetExpressionException("Your thoughts are too deep", null); } diff --git a/src/main/java/carpet/script/CarpetScriptHost.java b/src/main/java/carpet/script/CarpetScriptHost.java index 4edf62db42..1353971af9 100644 --- a/src/main/java/carpet/script/CarpetScriptHost.java +++ b/src/main/java/carpet/script/CarpetScriptHost.java @@ -83,7 +83,7 @@ public class CarpetScriptHost extends ScriptHost public AppStoreManager.StoreNode storeSource; boolean hasCommand; - private CarpetScriptHost(final CarpetScriptServer server, final Module code, final boolean perUser, final ScriptHost parent, final Map config, final Map argTypes, final Predicate commandValidator, final boolean isRuleApp) + private CarpetScriptHost(CarpetScriptServer server, Module code, boolean perUser, ScriptHost parent, Map config, Map argTypes, Predicate commandValidator, boolean isRuleApp) { super(code, server, perUser, parent); this.saveTimeout = 0; @@ -104,31 +104,31 @@ else if (parent != null) storeSource = null; } - public static CarpetScriptHost create(final CarpetScriptServer scriptServer, final Module module, final boolean perPlayer, final CommandSourceStack source, final Predicate commandValidator, final boolean isRuleApp, final AppStoreManager.StoreNode storeSource) + public static CarpetScriptHost create(CarpetScriptServer scriptServer, Module module, boolean perPlayer, CommandSourceStack source, Predicate commandValidator, boolean isRuleApp, AppStoreManager.StoreNode storeSource) { - final CarpetScriptHost host = new CarpetScriptHost(scriptServer, module, perPlayer, null, Collections.emptyMap(), new HashMap<>(), commandValidator, isRuleApp); + CarpetScriptHost host = new CarpetScriptHost(scriptServer, module, perPlayer, null, Collections.emptyMap(), new HashMap<>(), commandValidator, isRuleApp); // parse code and convert to expression if (module != null) { try { host.setChatErrorSnooper(source); - final CarpetExpression ex = new CarpetExpression(host.main, module.code(), source, new BlockPos(0, 0, 0)); + CarpetExpression ex = new CarpetExpression(host.main, module.code(), source, new BlockPos(0, 0, 0)); ex.getExpr().asATextSource(); host.storeSource = storeSource; ex.scriptRunCommand(host, new BlockPos(source.getPosition())); } - catch (final CarpetExpressionException e) + catch (CarpetExpressionException e) { host.handleErrorWithStack("Error while evaluating expression", e); throw new LoadException(); } - catch (final ArithmeticException ae) // is this branch ever reached? Seems like arithmetic exceptions are converted to CEEs earlier + catch (ArithmeticException ae) // is this branch ever reached? Seems like arithmetic exceptions are converted to CEEs earlier { host.handleErrorWithStack("Math doesn't compute", ae); throw new LoadException(); } - catch (final StackOverflowError soe) + catch (StackOverflowError soe) { host.handleErrorWithStack("Your thoughts are too deep", soe); } @@ -140,36 +140,36 @@ public static CarpetScriptHost create(final CarpetScriptServer scriptServer, fin return host; } - private static int execute(final CommandContext ctx, final String hostName, final FunctionArgument funcSpec, final List paramNames) throws CommandSyntaxException + private static int execute(CommandContext ctx, String hostName, FunctionArgument funcSpec, List paramNames) throws CommandSyntaxException { - final Runnable token = Carpet.startProfilerSection("Scarpet command"); - final CarpetScriptServer scriptServer = Vanilla.MinecraftServer_getScriptServer(ctx.getSource().getServer()); - final CarpetScriptHost cHost = scriptServer.modules.get(hostName).retrieveOwnForExecution(ctx.getSource()); - final List argNames = funcSpec.function.getArguments(); + Runnable token = Carpet.startProfilerSection("Scarpet command"); + CarpetScriptServer scriptServer = Vanilla.MinecraftServer_getScriptServer(ctx.getSource().getServer()); + CarpetScriptHost cHost = scriptServer.modules.get(hostName).retrieveOwnForExecution(ctx.getSource()); + List argNames = funcSpec.function.getArguments(); if ((argNames.size() - funcSpec.args.size()) != paramNames.size()) { throw new SimpleCommandExceptionType(Component.literal("Target function " + funcSpec.function.getPrettyString() + " as wrong number of arguments, required " + paramNames.size() + ", found " + argNames.size() + " with " + funcSpec.args.size() + " provided")).create(); } - final List args = new ArrayList<>(argNames.size()); - for (final String s : paramNames) + List args = new ArrayList<>(argNames.size()); + for (String s : paramNames) { args.add(CommandArgument.getValue(ctx, s, cHost)); } args.addAll(funcSpec.args); - final Value response = cHost.handleCommand(ctx.getSource(), funcSpec.function, args); - final int intres = (int) response.readInteger(); + Value response = cHost.handleCommand(ctx.getSource(), funcSpec.function, args); + int intres = (int) response.readInteger(); token.run(); return intres; } public LiteralArgumentBuilder addPathToCommand( - final LiteralArgumentBuilder command, - final List path, - final FunctionArgument functionSpec + LiteralArgumentBuilder command, + List path, + FunctionArgument functionSpec ) throws CommandSyntaxException { - final String hostName = main.name(); - final List commandArgs = path.stream().filter(t -> t.isArgument).map(t -> t.surface).collect(Collectors.toList()); + String hostName = main.name(); + List commandArgs = path.stream().filter(t -> t.isArgument).map(t -> t.surface).collect(Collectors.toList()); if (commandArgs.size() != (functionSpec.function.getNumParams() - functionSpec.args.size())) { throw CommandArgument.error("Number of parameters in function " + functionSpec.function.fullName() + " doesn't match parameters for a command"); @@ -178,7 +178,7 @@ public LiteralArgumentBuilder addPathToCommand( { return command.executes((c) -> execute(c, hostName, functionSpec, Collections.emptyList())); } - final List reversedPath = new ArrayList<>(path); + List reversedPath = new ArrayList<>(path); Collections.reverse(reversedPath); ArgumentBuilder argChain = reversedPath.get(0).getCommandNode(this).executes(c -> execute(c, hostName, functionSpec, commandArgs)); for (int i = 1; i < reversedPath.size(); i++) @@ -189,14 +189,14 @@ public LiteralArgumentBuilder addPathToCommand( } public LiteralArgumentBuilder getNewCommandTree( - final List, FunctionArgument>> entries, final Predicate useValidator + List, FunctionArgument>> entries, Predicate useValidator ) throws CommandSyntaxException { - final String hostName = main.name(); - final Predicate configValidator = getCommandConfigPermissions(); + String hostName = main.name(); + Predicate configValidator = getCommandConfigPermissions(); LiteralArgumentBuilder command = literal(hostName). requires((player) -> useValidator.test(player) && configValidator.test(player)); - for (final Pair, FunctionArgument> commandData : entries) + for (Pair, FunctionArgument> commandData : entries) { command = this.addPathToCommand(command, commandData.getKey(), commandData.getValue()); } @@ -205,14 +205,14 @@ public LiteralArgumentBuilder getNewCommandTree( public Predicate getCommandConfigPermissions() throws CommandSyntaxException { - final Value confValue = appConfig.get(StringValue.of("command_permission")); + Value confValue = appConfig.get(StringValue.of("command_permission")); if (confValue == null) { return s -> true; } if (confValue instanceof final NumericValue number) { - final int level = number.getInt(); + int level = number.getInt(); if (level < 1 || level > 4) { throw CommandArgument.error("Numeric permission level for custom commands should be between 1 and 4"); @@ -221,7 +221,7 @@ public Predicate getCommandConfigPermissions() throws Comman } if (!(confValue instanceof final FunctionValue fun)) { - final String perm = confValue.getString().toLowerCase(Locale.ROOT); + String perm = confValue.getString().toLowerCase(Locale.ROOT); return switch (perm) { case "ops" -> s -> s.hasPermission(2); case "server" -> s -> !(s.getEntity() instanceof ServerPlayer); @@ -234,20 +234,20 @@ public Predicate getCommandConfigPermissions() throws Comman { throw CommandArgument.error("Custom command permission function should expect 1 argument"); } - final String hostName = getName(); + String hostName = getName(); return s -> { try { - final Runnable token = Carpet.startProfilerSection("Scarpet command"); - final CarpetScriptHost cHost = scriptServer().modules.get(hostName).retrieveOwnForExecution(s); - final Value response = cHost.handleCommand(s, fun, Collections.singletonList( + Runnable token = Carpet.startProfilerSection("Scarpet command"); + CarpetScriptHost cHost = scriptServer().modules.get(hostName).retrieveOwnForExecution(s); + Value response = cHost.handleCommand(s, fun, Collections.singletonList( (s.getEntity() instanceof ServerPlayer) ? new EntityValue(s.getEntity()) : Value.NULL) ); - final boolean res = response.getBoolean(); + boolean res = response.getBoolean(); token.run(); return res; } - catch (final CommandSyntaxException e) + catch (CommandSyntaxException e) { Carpet.Messenger_message(s, "rb Unable to run app command: " + e.getMessage()); return false; @@ -262,13 +262,13 @@ protected ScriptHost duplicate() } @Override - protected void setupUserHost(final ScriptHost host) + protected void setupUserHost(ScriptHost host) { super.setupUserHost(host); // transfer Events - final CarpetScriptHost child = (CarpetScriptHost) host; + CarpetScriptHost child = (CarpetScriptHost) host; CarpetEventServer.Event.transferAllHostEventsToChild(child); - final FunctionValue onStart = child.getFunction("__on_start"); + FunctionValue onStart = child.getFunction("__on_start"); if (onStart != null) { child.callNow(onStart, Collections.emptyList()); @@ -276,7 +276,7 @@ protected void setupUserHost(final ScriptHost host) } @Override - public void addUserDefinedFunction(final Context ctx, final Module module, final String funName, final FunctionValue function) + public void addUserDefinedFunction(Context ctx, Module module, String funName, FunctionValue function) { super.addUserDefinedFunction(ctx, module, funName, function); if (ctx.host.main != module) @@ -288,7 +288,7 @@ public void addUserDefinedFunction(final Context ctx, final Module module, final if (funName.startsWith("__on_")) // here we can make a determination if we want to only accept events from main module. { // this is nasty, we have the host and function, yet we add it via names, but hey - works for now - final String event = funName.replaceFirst("__on_", ""); + String event = funName.replaceFirst("__on_", ""); if (CarpetEventServer.Event.byName.containsKey(event)) { scriptServer().events.addBuiltInEvent(event, this, function, null); @@ -309,26 +309,26 @@ private boolean readConfig() { try { - final FunctionValue configFunction = getFunction("__config"); + FunctionValue configFunction = getFunction("__config"); if (configFunction == null) { return false; } - final Value ret = callNow(configFunction, Collections.emptyList()); + Value ret = callNow(configFunction, Collections.emptyList()); if (!(ret instanceof final MapValue map)) { return false; } - final Map config = map.getMap(); + Map config = map.getMap(); setPerPlayer(config.getOrDefault(new StringValue("scope"), new StringValue("player")).getString().equalsIgnoreCase("player")); persistenceRequired = config.getOrDefault(new StringValue("stay_loaded"), Value.TRUE).getBoolean(); strict = config.getOrDefault(StringValue.of("strict"), Value.FALSE).getBoolean(); eventPriority = config.getOrDefault(new StringValue("event_priority"), Value.ZERO).readDoubleNumber(); // check requires - final Value loadRequirements = config.get(new StringValue("requires")); + Value loadRequirements = config.get(new StringValue("requires")); if (loadRequirements instanceof final FunctionValue functionValue) { - final Value reqResult = callNow(functionValue, Collections.emptyList()); + Value reqResult = callNow(functionValue, Collections.emptyList()); if (reqResult.getBoolean()) // != false or null { throw new LoadException(reqResult.getString()); @@ -340,26 +340,26 @@ private boolean readConfig() } if (storeSource != null) { - final Value resources = config.get(new StringValue("resources")); + Value resources = config.get(new StringValue("resources")); if (resources != null) { if (!(resources instanceof final ListValue list)) { throw new InternalExpressionException("App resources not defined as a list"); } - for (final Value resource : list.getItems()) + for (Value resource : list.getItems()) { AppStoreManager.addResource(this, storeSource, resource); } } - final Value libraries = config.get(new StringValue("libraries")); + Value libraries = config.get(new StringValue("libraries")); if (libraries != null) { if (!(libraries instanceof final ListValue list)) { throw new InternalExpressionException("App libraries not defined as a list"); } - for (final Value library : list.getItems()) + for (Value library : list.getItems()) { AppStoreManager.addLibrary(this, storeSource, library); } @@ -367,7 +367,7 @@ private boolean readConfig() } appConfig = config; } - catch (final NullPointerException ignored) + catch (NullPointerException ignored) { return false; } @@ -377,13 +377,13 @@ private boolean readConfig() static class ListComparator> implements Comparator, ?>> { @Override - public int compare(final Pair, ?> p1, final Pair, ?> p2) + public int compare(Pair, ?> p1, Pair, ?> p2) { - final List o1 = p1.getKey(); - final List o2 = p2.getKey(); + List o1 = p1.getKey(); + List o2 = p2.getKey(); for (int i = 0; i < Math.min(o1.size(), o2.size()); i++) { - final int c = o1.get(i).compareTo(o2.get(i)); + int c = o1.get(i).compareTo(o2.get(i)); if (c != 0) { return c; @@ -394,7 +394,7 @@ public int compare(final Pair, ?> p1, final Pair, ?> p2) } // Used to ensure app gets marked as holding command from a central place - private void registerCommand(final LiteralArgumentBuilder command) + private void registerCommand(LiteralArgumentBuilder command) { scriptServer().server.getCommands().getDispatcher().register(command); hasCommand = true; @@ -403,7 +403,7 @@ private void registerCommand(final LiteralArgumentBuilder co public void readCustomArgumentTypes() throws CommandSyntaxException { // read custom arguments - final Value arguments = appConfig.get(StringValue.of("arguments")); + Value arguments = appConfig.get(StringValue.of("arguments")); if (arguments != null) { if (!(arguments instanceof final MapValue map)) @@ -411,27 +411,27 @@ public void readCustomArgumentTypes() throws CommandSyntaxException throw CommandArgument.error("'arguments' element in config should be a map"); } appArgTypes.clear(); - for (final Map.Entry typeData : map.getMap().entrySet()) + for (Map.Entry typeData : map.getMap().entrySet()) { - final String argument = typeData.getKey().getString(); - final Value spec = typeData.getValue(); + String argument = typeData.getKey().getString(); + Value spec = typeData.getValue(); if (!(spec instanceof final MapValue specMap)) { throw CommandArgument.error("Spec for '" + argument + "' should be a map"); } - final Map specData = specMap.getMap().entrySet().stream().collect(Collectors.toMap(e -> e.getKey().getString(), Map.Entry::getValue)); + Map specData = specMap.getMap().entrySet().stream().collect(Collectors.toMap(e -> e.getKey().getString(), Map.Entry::getValue)); appArgTypes.put(argument, CommandArgument.buildFromConfig(argument, specData, this)); } } } - public Boolean addAppCommands(final Consumer notifier) + public Boolean addAppCommands(Consumer notifier) { try { readCustomArgumentTypes(); } - catch (final CommandSyntaxException e) + catch (CommandSyntaxException e) { notifier.accept(Carpet.Messenger_compose("r Error when handling of setting up custom argument types: " + e.getMessage())); return false; @@ -445,7 +445,7 @@ public Boolean addAppCommands(final Consumer notifier) } try { - final LiteralArgumentBuilder command = readCommands(commandValidator); + LiteralArgumentBuilder command = readCommands(commandValidator); if (command != null) { registerCommand(command); @@ -453,7 +453,7 @@ public Boolean addAppCommands(final Consumer notifier) } return false; } - catch (final CommandSyntaxException cse) + catch (CommandSyntaxException cse) { // failed notifier.accept(Carpet.Messenger_compose("r Failed to build command system: ", cse.getRawMessage())); @@ -464,7 +464,7 @@ public Boolean addAppCommands(final Consumer notifier) return addLegacyCommand(notifier); } - public void checkModVersionRequirements(final Value reqs) + public void checkModVersionRequirements(Value reqs) { if (reqs == null) { @@ -474,25 +474,25 @@ public void checkModVersionRequirements(final Value reqs) { throw new InternalExpressionException("`requires` field must be a map of mod dependencies or a function to be executed"); } - final Map requirements = map.getMap(); - for (final Entry requirement : requirements.entrySet()) + Map requirements = map.getMap(); + for (Entry requirement : requirements.entrySet()) { - final String requiredModId = requirement.getKey().getString(); - final String stringPredicate = requirement.getValue().getString(); - final VersionPredicate predicate; + String requiredModId = requirement.getKey().getString(); + String stringPredicate = requirement.getValue().getString(); + VersionPredicate predicate; try { predicate = VersionPredicate.parse(stringPredicate); } - catch (final VersionParsingException e) + catch (VersionParsingException e) { throw new InternalExpressionException("Failed to parse version conditions for '" + requiredModId + "' in 'requires': " + e.getMessage()); } - final ModContainer mod = FabricLoader.getInstance().getModContainer(requiredModId).orElse(null); + ModContainer mod = FabricLoader.getInstance().getModContainer(requiredModId).orElse(null); if (mod != null) { - final Version presentVersion = mod.getMetadata().getVersion(); + Version presentVersion = mod.getMetadata().getVersion(); if (predicate.test(presentVersion) || (FabricLoader.getInstance().isDevelopmentEnvironment() && !(presentVersion instanceof SemanticVersion))) { // in a dev env, mod version is usually replaced with ${version}, and that isn't semantic continue; @@ -502,7 +502,7 @@ public void checkModVersionRequirements(final Value reqs) } } - private Boolean addLegacyCommand(final Consumer notifier) + private Boolean addLegacyCommand(Consumer notifier) { if (main == null || getFunction("__command") == null) { @@ -515,23 +515,23 @@ private Boolean addLegacyCommand(final Consumer notifier) return null; } - final Predicate configValidator; + Predicate configValidator; try { configValidator = getCommandConfigPermissions(); } - catch (final CommandSyntaxException e) + catch (CommandSyntaxException e) { notifier.accept(Carpet.Messenger_compose("rb " + e.getMessage())); return null; } - final String hostName = getName(); + String hostName = getName(); LiteralArgumentBuilder command = literal(hostName). requires((player) -> commandValidator.test(player) && configValidator.test(player)). executes((c) -> { - final CarpetScriptHost targetHost = scriptServer().modules.get(hostName).retrieveOwnForExecution(c.getSource()); - final Value response = targetHost.handleCommandLegacy(c.getSource(), "__command", null, ""); + CarpetScriptHost targetHost = scriptServer().modules.get(hostName).retrieveOwnForExecution(c.getSource()); + Value response = targetHost.handleCommandLegacy(c.getSource(), "__command", null, ""); if (!response.isNull()) { Carpet.Messenger_message(c.getSource(), "gi " + response.getString()); @@ -539,22 +539,22 @@ private Boolean addLegacyCommand(final Consumer notifier) return (int) response.readInteger(); }); - final boolean hasTypeSupport = appConfig.getOrDefault(StringValue.of("legacy_command_type_support"), Value.FALSE).getBoolean(); + boolean hasTypeSupport = appConfig.getOrDefault(StringValue.of("legacy_command_type_support"), Value.FALSE).getBoolean(); - for (final String function : globalFunctionNames(main, s -> !s.startsWith("_")).sorted().collect(Collectors.toList())) + for (String function : globalFunctionNames(main, s -> !s.startsWith("_")).sorted().collect(Collectors.toList())) { if (hasTypeSupport) { try { - final FunctionValue functionValue = getFunction(function); + FunctionValue functionValue = getFunction(function); command = addPathToCommand( command, CommandToken.parseSpec(CommandToken.specFromSignature(functionValue), this), FunctionArgument.fromCommandSpec(this, functionValue) ); } - catch (final CommandSyntaxException e) + catch (CommandSyntaxException e) { return false; } @@ -565,8 +565,8 @@ private Boolean addLegacyCommand(final Consumer notifier) then(literal(function). requires((player) -> scriptServer().modules.get(hostName).getFunction(function) != null). executes((c) -> { - final CarpetScriptHost targetHost = scriptServer().modules.get(hostName).retrieveOwnForExecution(c.getSource()); - final Value response = targetHost.handleCommandLegacy(c.getSource(), function, null, ""); + CarpetScriptHost targetHost = scriptServer().modules.get(hostName).retrieveOwnForExecution(c.getSource()); + Value response = targetHost.handleCommandLegacy(c.getSource(), function, null, ""); if (!response.isNull()) { Carpet.Messenger_message(c.getSource(), "gi " + response.getString()); @@ -575,8 +575,8 @@ private Boolean addLegacyCommand(final Consumer notifier) }). then(argument("args...", StringArgumentType.greedyString()). executes((c) -> { - final CarpetScriptHost targetHost = scriptServer().modules.get(hostName).retrieveOwnForExecution(c.getSource()); - final Value response = targetHost.handleCommandLegacy(c.getSource(), function, null, StringArgumentType.getString(c, "args...")); + CarpetScriptHost targetHost = scriptServer().modules.get(hostName).retrieveOwnForExecution(c.getSource()); + Value response = targetHost.handleCommandLegacy(c.getSource(), function, null, StringArgumentType.getString(c, "args...")); if (!response.isNull()) { Carpet.Messenger_message(c.getSource(), "gi " + response.getString()); @@ -589,9 +589,9 @@ private Boolean addLegacyCommand(final Consumer notifier) return true; } - public LiteralArgumentBuilder readCommands(final Predicate useValidator) throws CommandSyntaxException + public LiteralArgumentBuilder readCommands(Predicate useValidator) throws CommandSyntaxException { - final Value commands = appConfig.get(StringValue.of("commands")); + Value commands = appConfig.get(StringValue.of("commands")); if (commands == null) { @@ -601,12 +601,12 @@ public LiteralArgumentBuilder readCommands(final Predicate, FunctionArgument>> commandEntries = new ArrayList<>(); + List, FunctionArgument>> commandEntries = new ArrayList<>(); - for (final Map.Entry commandsData : map.getMap().entrySet().stream().sorted(Entry.comparingByKey()).toList()) + for (Map.Entry commandsData : map.getMap().entrySet().stream().sorted(Entry.comparingByKey()).toList()) { - final List elements = CommandToken.parseSpec(commandsData.getKey().getString(), this); - final FunctionArgument funSpec = FunctionArgument.fromCommandSpec(this, commandsData.getValue()); + List elements = CommandToken.parseSpec(commandsData.getKey().getString(), this); + FunctionArgument funSpec = FunctionArgument.fromCommandSpec(this, commandsData.getValue()); commandEntries.add(Pair.of(elements, funSpec)); } commandEntries.sort(new ListComparator<>()); @@ -614,13 +614,13 @@ public LiteralArgumentBuilder readCommands(final Predicate first = commandEntries.get(i).getKey(); - final List other = commandEntries.get(i + 1).getKey(); - final int checkSize = Math.min(first.size(), other.size()); + List first = commandEntries.get(i).getKey(); + List other = commandEntries.get(i + 1).getKey(); + int checkSize = Math.min(first.size(), other.size()); for (int t = 0; t < checkSize; t++) { - final CommandToken tik = first.get(t); - final CommandToken tok = other.get(t); + CommandToken tik = first.get(t); + CommandToken tok = other.get(t); if (tik.isArgument && tok.isArgument && !tik.surface.equals(tok.surface)) { throw CommandArgument.error("Conflicting commands: \n" + @@ -638,9 +638,9 @@ public LiteralArgumentBuilder readCommands(final Predicate coords, final String arg) + public Value handleCommandLegacy(CommandSourceStack source, String call, List coords, String arg) { try { - final Runnable token = Carpet.startProfilerSection("Scarpet command"); - final Value res = callLegacy(source, call, coords, arg); + Runnable token = Carpet.startProfilerSection("Scarpet command"); + Value res = callLegacy(source, call, coords, arg); token.run(); return res; } - catch (final CarpetExpressionException exc) + catch (CarpetExpressionException exc) { handleErrorWithStack("Error while running custom command", exc); } - catch (final ArithmeticException ae) + catch (ArithmeticException ae) { handleErrorWithStack("Math doesn't compute", ae); } - catch (final StackOverflowError soe) + catch (StackOverflowError soe) { handleErrorWithStack("Your thoughts are too deep", soe); } return Value.NULL; } - public Value handleCommand(final CommandSourceStack source, final FunctionValue function, final List args) + public Value handleCommand(CommandSourceStack source, FunctionValue function, List args) { try { return scriptServer().events.handleEvents.getWhileDisabled(() -> call(source, function, args)); } - catch (final CarpetExpressionException exc) + catch (CarpetExpressionException exc) { handleErrorWithStack("Error while running custom command", exc); } - catch (final ArithmeticException ae) + catch (ArithmeticException ae) { handleErrorWithStack("Math doesn't compute", ae); } - catch (final StackOverflowError soe) + catch (StackOverflowError soe) { handleErrorWithStack("Your thoughts are too deep", soe); } return Value.NULL; } - public Value callLegacy(final CommandSourceStack source, final String call, final List coords, final String arg) + public Value callLegacy(CommandSourceStack source, String call, List coords, String arg) { if (scriptServer().stopAll) { throw new CarpetExpressionException("SCARPET PAUSED (unpause with /script resume)", null); } - final FunctionValue function = getFunction(call); + FunctionValue function = getFunction(call); if (function == null) { throw new CarpetExpressionException("Couldn't find function '" + call + "' in app '" + this.getName() + "'", null); } - final List argv = new ArrayList<>(); + List argv = new ArrayList<>(); if (coords != null) { - for (final Integer i : coords) + for (Integer i : coords) { argv.add((c, t) -> new NumericValue(i)); } } String sign = ""; - for (final Tokenizer.Token tok : Tokenizer.simplepass(arg)) + for (Tokenizer.Token tok : Tokenizer.simplepass(arg)) { switch (tok.type) { case VARIABLE: - final LazyValue variable = getGlobalVariable(tok.surface); + LazyValue variable = getGlobalVariable(tok.surface); if (variable != null) { argv.add(variable); @@ -800,11 +800,11 @@ public Value callLegacy(final CommandSourceStack source, final String call, fina case LITERAL: try { - final String finalSign = sign; + String finalSign = sign; argv.add((c, t) -> new NumericValue(finalSign + tok.surface)); sign = ""; } - catch (final NumberFormatException exception) + catch (NumberFormatException exception) { throw new CarpetExpressionException("Fail: " + sign + tok.surface + " seems like a number but it is" + " not a number. Use quotes to ensure its a string", null); @@ -813,11 +813,11 @@ public Value callLegacy(final CommandSourceStack source, final String call, fina case HEX_LITERAL: try { - final String finalSign = sign; + String finalSign = sign; argv.add((c, t) -> new NumericValue(new BigInteger(finalSign + tok.surface.substring(2), 16).doubleValue())); sign = ""; } - catch (final NumberFormatException exception) + catch (NumberFormatException exception) { throw new CarpetExpressionException("Fail: " + sign + tok.surface + " seems like a number but it is" + " not a number. Use quotes to ensure its a string", null); @@ -841,7 +841,7 @@ public Value callLegacy(final CommandSourceStack source, final String call, fina throw new CarpetExpressionException("Fail: " + tok.surface + " is not allowed in invoke", null); } } - final List args = function.getArguments(); + List args = function.getArguments(); if (argv.size() != args.size()) { String error = "Fail: stored function " + call + " takes " + args.size() + " arguments, not " + argv.size() + ":\n"; @@ -855,27 +855,27 @@ public Value callLegacy(final CommandSourceStack source, final String call, fina { // TODO: this is just for now - invoke would be able to invoke other hosts scripts assertAppIntegrity(function.getModule()); - final Context context = new CarpetContext(this, source); + Context context = new CarpetContext(this, source); return scriptServer().events.handleEvents.getWhileDisabled(() -> function.getExpression().evalValue( () -> function.lazyEval(context, Context.VOID, function.getExpression(), function.getToken(), argv), context, Context.VOID )); } - catch (final ExpressionException e) + catch (ExpressionException e) { throw new CarpetExpressionException(e.getMessage(), e.stack); } } - public Value call(final CommandSourceStack source, final FunctionValue function, final List argv) + public Value call(CommandSourceStack source, FunctionValue function, List argv) { if (scriptServer().stopAll) { throw new CarpetExpressionException("SCARPET PAUSED (unpause with /script resume)", null); } - final List args = function.getArguments(); + List args = function.getArguments(); if (argv.size() != args.size()) { String error = "Fail: stored function " + function.getPrettyString() + " takes " + args.size() + " arguments, not " + argv.size() + ":\n"; @@ -888,25 +888,25 @@ public Value call(final CommandSourceStack source, final FunctionValue function, try { assertAppIntegrity(function.getModule()); - final Context context = new CarpetContext(this, source); + Context context = new CarpetContext(this, source); return function.getExpression().evalValue( () -> function.execute(context, Context.VOID, function.getExpression(), function.getToken(), argv), context, Context.VOID ); } - catch (final ExpressionException e) + catch (ExpressionException e) { throw new CarpetExpressionException(e.getMessage(), e.stack); } } - public Value callUDF(final CommandSourceStack source, final FunctionValue fun, final List argv) throws InvalidCallbackException, IntegrityException + public Value callUDF(CommandSourceStack source, FunctionValue fun, List argv) throws InvalidCallbackException, IntegrityException { return callUDF(BlockPos.ZERO, source, fun, argv); } - public Value callUDF(final BlockPos origin, final CommandSourceStack source, final FunctionValue fun, final List argv) throws InvalidCallbackException, IntegrityException + public Value callUDF(BlockPos origin, CommandSourceStack source, FunctionValue fun, List argv) throws InvalidCallbackException, IntegrityException { if (scriptServer().stopAll) { @@ -918,36 +918,36 @@ public Value callUDF(final BlockPos origin, final CommandSourceStack source, fin throw new InternalExpressionException(""); }); } - catch (final InternalExpressionException ignored) + catch (InternalExpressionException ignored) { throw new InvalidCallbackException(); } try { assertAppIntegrity(fun.getModule()); - final Context context = new CarpetContext(this, source, origin); + Context context = new CarpetContext(this, source, origin); return fun.getExpression().evalValue( () -> fun.execute(context, Context.VOID, fun.getExpression(), fun.getToken(), argv), context, Context.VOID); } - catch (final ExpressionException e) + catch (ExpressionException e) { handleExpressionException("Callback failed", e); } return Value.NULL; } - public Value callNow(final FunctionValue fun, final List arguments) + public Value callNow(FunctionValue fun, List arguments) { - final ServerPlayer player = (user == null) ? null : scriptServer().server.getPlayerList().getPlayerByName(user); - final CommandSourceStack source = (player != null) ? player.createCommandSourceStack() : scriptServer().server.createCommandSourceStack(); + ServerPlayer player = (user == null) ? null : scriptServer().server.getPlayerList().getPlayerByName(user); + CommandSourceStack source = (player != null) ? player.createCommandSourceStack() : scriptServer().server.createCommandSourceStack(); return scriptServer().events.handleEvents.getWhileDisabled(() -> { try { return callUDF(source, fun, arguments); } - catch (final InvalidCallbackException ignored) + catch (InvalidCallbackException ignored) { return Value.NULL; } @@ -959,7 +959,7 @@ public Value callNow(final FunctionValue fun, final List arguments) public void onClose() { super.onClose(); - final FunctionValue closing = getFunction("__on_close"); + FunctionValue closing = getFunction("__on_close"); if (closing != null && (parent != null || !isPerUser())) // either global instance of a global task, or // user host in player scoped app @@ -969,10 +969,10 @@ public void onClose() if (user == null) { - final String markerName = Auxiliary.MARKER_STRING + "_" + ((getName() == null) ? "" : getName()); - for (final ServerLevel world : scriptServer().server.getAllLevels()) + String markerName = Auxiliary.MARKER_STRING + "_" + ((getName() == null) ? "" : getName()); + for (ServerLevel world : scriptServer().server.getAllLevels()) { - for (final Entity e : world.getEntities(EntityType.ARMOR_STAND, (as) -> as.getTags().contains(markerName))) + for (Entity e : world.getEntities(EntityType.ARMOR_STAND, (as) -> as.getTags().contains(markerName))) { e.discard(); } @@ -994,7 +994,7 @@ private Tag loadState() return Module.getData(main, this.scriptServer()); } - public Tag readFileTag(final FileArgument fdesc) + public Tag readFileTag(FileArgument fdesc) { if (getName() == null && !fdesc.isShared) { @@ -1011,7 +1011,7 @@ public Tag readFileTag(final FileArgument fdesc) return ((CarpetScriptHost) parent).globalState; } - public boolean writeTagFile(final Tag tag, final FileArgument fdesc) + public boolean writeTagFile(Tag tag, FileArgument fdesc) { if (getName() == null && !fdesc.isShared) { @@ -1023,7 +1023,7 @@ public boolean writeTagFile(final Tag tag, final FileArgument fdesc) return fdesc.saveNbtData(main, tag); } - final CarpetScriptHost responsibleHost = (parent != null) ? (CarpetScriptHost) parent : this; + CarpetScriptHost responsibleHost = (parent != null) ? (CarpetScriptHost) parent : this; responsibleHost.globalState = tag; if (responsibleHost.saveTimeout == 0) { @@ -1033,34 +1033,34 @@ public boolean writeTagFile(final Tag tag, final FileArgument fdesc) return true; } - public boolean removeResourceFile(final FileArgument fdesc) + public boolean removeResourceFile(FileArgument fdesc) { return (getName() != null || fdesc.isShared) && fdesc.dropExistingFile(main); // } - public boolean appendLogFile(final FileArgument fdesc, final List data) + public boolean appendLogFile(FileArgument fdesc, List data) { return (getName() != null || fdesc.isShared) && fdesc.appendToTextFile(main, data); // if belongs to an app, cannot be default host. } - public List readTextResource(final FileArgument fdesc) + public List readTextResource(FileArgument fdesc) { return getName() == null && !fdesc.isShared ? null : fdesc.listFile(main); } - public JsonElement readJsonFile(final FileArgument fdesc) + public JsonElement readJsonFile(FileArgument fdesc) { return getName() == null && !fdesc.isShared ? null : fdesc.readJsonFile(main); } - public Stream listFolder(final FileArgument fdesc) + public Stream listFolder(FileArgument fdesc) { return getName() == null && !fdesc.isShared ? null : fdesc.listFolder(main); } - public boolean applyActionForResource(final String path, final boolean shared, final Consumer action) + public boolean applyActionForResource(String path, boolean shared, Consumer action) { - final FileArgument fdesc = FileArgument.resourceFromPath(this, path, FileArgument.Reason.CREATE, shared); + FileArgument fdesc = FileArgument.resourceFromPath(this, path, FileArgument.Reason.CREATE, shared); return fdesc.findPathAndApply(main, action); } @@ -1076,7 +1076,7 @@ public void tick() } } - public void setChatErrorSnooper(final CommandSourceStack source) + public void setChatErrorSnooper(CommandSourceStack source) { responsibleSource = source; errorSnooper = (expr, /*Nullable*/ token, ctx, message) -> @@ -1085,7 +1085,7 @@ public void setChatErrorSnooper(final CommandSourceStack source) { source.getPlayerOrException(); } - catch (final CommandSyntaxException e) + catch (CommandSyntaxException e) { return null; } @@ -1093,7 +1093,7 @@ public void setChatErrorSnooper(final CommandSourceStack source) String shebang = message + " in " + expr.getModuleName(); if (token != null) { - final String[] lines = expr.getCodeString().split("\n"); + String[] lines = expr.getCodeString().split("\n"); if (lines.length > 1) { @@ -1135,12 +1135,12 @@ public void setChatErrorSnooper(final CommandSourceStack source) * @implNote The implementation of this method is far from perfect, and won't detect actual references to variables, but try to find the strings * and add the hover effect to anything that equals to any variable name, so short variable names may appear on random positions */ - private static Component withLocals(String format, final String line, final Context context) + private static Component withLocals(String format, String line, Context context) { format += " "; - final List stringsToFormat = new ArrayList<>(); - final TreeMap posToLocal = new TreeMap<>(); //Holds whether a local variable name is found at a specific index - for (final String local : context.variables.keySet()) + List stringsToFormat = new ArrayList<>(); + TreeMap posToLocal = new TreeMap<>(); //Holds whether a local variable name is found at a specific index + for (String local : context.variables.keySet()) { int pos = line.indexOf(local); while (pos != -1) @@ -1154,7 +1154,7 @@ private static Component withLocals(String format, final String line, final Cont } } int lastPos = 0; - for (final Entry foundLocal : posToLocal.entrySet()) + for (Entry foundLocal : posToLocal.entrySet()) { if (foundLocal.getKey() < lastPos) // system isn't perfect: part of another local { @@ -1162,14 +1162,14 @@ private static Component withLocals(String format, final String line, final Cont } stringsToFormat.add(format + line.substring(lastPos, foundLocal.getKey())); stringsToFormat.add(format + foundLocal.getValue()); - final Value val = context.variables.get(foundLocal.getValue()).evalValue(context); - final String type = val.getTypeString(); + Value val = context.variables.get(foundLocal.getValue()).evalValue(context); + String type = val.getTypeString(); String value; try { value = val.getPrettyString(); } - catch (final StackOverflowError e) + catch (StackOverflowError e) { value = "Exception while rendering variable, there seems to be a recursive reference in there"; } @@ -1191,7 +1191,7 @@ public void resetErrorSnooper() super.resetErrorSnooper(); } - public void handleErrorWithStack(final String intro, final Throwable exception) + public void handleErrorWithStack(String intro, Throwable exception) { if (responsibleSource != null) { @@ -1199,7 +1199,7 @@ public void handleErrorWithStack(final String intro, final Throwable exception) { cee.printStack(responsibleSource); } - final String message = exception.getMessage(); + String message = exception.getMessage(); Carpet.Messenger_message(responsibleSource, "r " + intro + ((message == null || message.isEmpty()) ? "" : ": " + message)); } else @@ -1209,7 +1209,7 @@ public void handleErrorWithStack(final String intro, final Throwable exception) } @Override - public synchronized void handleExpressionException(final String message, final ExpressionException exc) + public synchronized void handleExpressionException(String message, ExpressionException exc) { handleErrorWithStack(message, new CarpetExpressionException(exc.getMessage(), exc.stack)); } @@ -1230,7 +1230,7 @@ public CarpetScriptServer scriptServer() } @Override - public boolean issueDeprecation(final String feature) + public boolean issueDeprecation(String feature) { if (super.issueDeprecation(feature)) { diff --git a/src/main/java/carpet/script/CarpetScriptServer.java b/src/main/java/carpet/script/CarpetScriptServer.java index ba17d0f266..aa4f7a7488 100644 --- a/src/main/java/carpet/script/CarpetScriptServer.java +++ b/src/main/java/carpet/script/CarpetScriptServer.java @@ -32,6 +32,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.annotation.Nullable; import java.io.IOException; import java.nio.file.FileVisitOption; import java.nio.file.Files; @@ -73,7 +74,7 @@ public class CarpetScriptServer extends ScriptServer * @param app The {@link Module} of the app * @see Module#fromJarPath(String, String, boolean) */ - public static void registerBuiltInApp(final Module app) + public static void registerBuiltInApp(Module app) { bundledModuleData.add(app); } @@ -85,7 +86,7 @@ public static void registerBuiltInApp(final Module app) * @param app The {@link Module} of the app. * @see Module#fromJarPath(String, String, boolean) */ - public static void registerSettingsApp(final Module app) + public static void registerSettingsApp(Module app) { ruleModuleData.add(app); } @@ -104,7 +105,7 @@ public static void registerSettingsApp(final Module app) registerBuiltInApp(Module.carpetNative("distance_beta", false)); } - public CarpetScriptServer(final MinecraftServer server) + public CarpetScriptServer(MinecraftServer server) { this.server = server; init(); @@ -125,7 +126,7 @@ public void initializeForWorld() { if (Vanilla.MinecraftServer_doScriptsAutoload(server)) { - for (final String moduleName : listAvailableModules(false)) + for (String moduleName : listAvailableModules(false)) { addScriptHost(server.createCommandSourceStack(), moduleName, null, true, true, false, null); } @@ -133,18 +134,18 @@ public void initializeForWorld() CarpetEventServer.Event.START.onTick(server); } - public Module getModule(final String name, final boolean allowLibraries) + public Module getModule(String name, boolean allowLibraries) { try { - final Path folder = server.getWorldPath(LevelResource.ROOT).resolve("scripts"); + Path folder = server.getWorldPath(LevelResource.ROOT).resolve("scripts"); if (!Files.exists(folder)) { Files.createDirectories(folder); } - try (final Stream folderLister = Files.list(folder)) + try (Stream folderLister = Files.list(folder)) { - final Optional scriptPath = folderLister + Optional scriptPath = folderLister .filter(script -> script.getFileName().toString().equalsIgnoreCase(name + ".sc") || (allowLibraries && script.getFileName().toString().equalsIgnoreCase(name + ".scl")) @@ -157,14 +158,14 @@ public Module getModule(final String name, final boolean allowLibraries) if (FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT) { - final Path globalFolder = FabricLoader.getInstance().getConfigDir().resolve("carpet/scripts"); + Path globalFolder = FabricLoader.getInstance().getConfigDir().resolve("carpet/scripts"); if (!Files.exists(globalFolder)) { Files.createDirectories(globalFolder); } - try (final Stream folderWalker = Files.walk(globalFolder)) + try (Stream folderWalker = Files.walk(globalFolder)) { - final Optional scriptPath = folderWalker + Optional scriptPath = folderWalker .filter(script -> script.getFileName().toString().equalsIgnoreCase(name + ".sc") || (allowLibraries && script.getFileName().toString().equalsIgnoreCase(name + ".scl"))) .findFirst(); @@ -175,11 +176,11 @@ public Module getModule(final String name, final boolean allowLibraries) } } } - catch (final IOException e) + catch (IOException e) { LOG.error("Exception while loading the app: ", e); } - for (final Module moduleData : bundledModuleData) + for (Module moduleData : bundledModuleData) { if (moduleData.name().equalsIgnoreCase(name) && (allowLibraries || !moduleData.library())) { @@ -189,9 +190,9 @@ public Module getModule(final String name, final boolean allowLibraries) return null; } - public Module getRuleModule(final String name) + public Module getRuleModule(String name) { - for (final Module moduleData : ruleModuleData) + for (Module moduleData : ruleModuleData) { if (moduleData.name().equalsIgnoreCase(name)) { @@ -201,12 +202,12 @@ public Module getRuleModule(final String name) return null; } - public List listAvailableModules(final boolean includeBuiltIns) + public List listAvailableModules(boolean includeBuiltIns) { - final List moduleNames = new ArrayList<>(); + List moduleNames = new ArrayList<>(); if (includeBuiltIns) { - for (final Module mi : bundledModuleData) + for (Module mi : bundledModuleData) { if (!mi.library() && !mi.name().endsWith("_beta")) { @@ -216,12 +217,12 @@ public List listAvailableModules(final boolean includeBuiltIns) } try { - final Path worldScripts = server.getWorldPath(LevelResource.ROOT).resolve("scripts"); + Path worldScripts = server.getWorldPath(LevelResource.ROOT).resolve("scripts"); if (!Files.exists(worldScripts)) { Files.createDirectories(worldScripts); } - try (final Stream folderLister = Files.list(worldScripts)) + try (Stream folderLister = Files.list(worldScripts)) { folderLister .filter(f -> f.toString().endsWith(".sc")) @@ -230,12 +231,12 @@ public List listAvailableModules(final boolean includeBuiltIns) if (includeBuiltIns && (FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT)) { - final Path globalScripts = FabricLoader.getInstance().getConfigDir().resolve("carpet/scripts"); + Path globalScripts = FabricLoader.getInstance().getConfigDir().resolve("carpet/scripts"); if (!Files.exists(globalScripts)) { Files.createDirectories(globalScripts); } - try (final Stream folderWalker = Files.walk(globalScripts, FileVisitOption.FOLLOW_LINKS)) + try (Stream folderWalker = Files.walk(globalScripts, FileVisitOption.FOLLOW_LINKS)) { folderWalker .filter(f -> f.toString().endsWith(".sc")) @@ -243,27 +244,27 @@ public List listAvailableModules(final boolean includeBuiltIns) } } } - catch (final IOException e) + catch (IOException e) { LOG.error("Exception while searching for apps: ", e); } return moduleNames; } - public CarpetScriptHost getAppHostByName(final String name) + public CarpetScriptHost getAppHostByName(String name) { return name == null ? globalHost : modules.get(name); } - public boolean addScriptHost(final CommandSourceStack source, String name, Predicate commandValidator, - final boolean perPlayer, final boolean autoload, final boolean isRuleApp, final AppStoreManager.StoreNode installer) + public boolean addScriptHost(CommandSourceStack source, String name, @Nullable Predicate commandValidator, + boolean perPlayer, boolean autoload, boolean isRuleApp, AppStoreManager.StoreNode installer) { - final Runnable token = Carpet.startProfilerSection("Scarpet load"); + Runnable token = Carpet.startProfilerSection("Scarpet load"); if (commandValidator == null) { commandValidator = p -> true; } - final long start = System.nanoTime(); + long start = System.nanoTime(); name = name.toLowerCase(Locale.ROOT); boolean reload = false; if (modules.containsKey(name)) @@ -275,18 +276,18 @@ public boolean addScriptHost(final CommandSourceStack source, String name, Predi removeScriptHost(source, name, false, isRuleApp); reload = true; } - final Module module = isRuleApp ? getRuleModule(name) : getModule(name, false); + Module module = isRuleApp ? getRuleModule(name) : getModule(name, false); if (module == null) { Carpet.Messenger_message(source, "r Failed to add " + name + " app: App not found"); return false; } - final CarpetScriptHost newHost; + CarpetScriptHost newHost; try { newHost = CarpetScriptHost.create(this, module, perPlayer, source, commandValidator, isRuleApp, installer); } - catch (final LoadException e) + catch (LoadException e) { Carpet.Messenger_message(source, "r Failed to add " + name + " app" + (e.getMessage() == null ? "" : ": " + e.getMessage())); return false; @@ -303,10 +304,10 @@ public boolean addScriptHost(final CommandSourceStack source, String name, Predi removeScriptHost(source, name, false, false); return false; } - final String action = (installer != null) ? (reload ? "reinstalled" : "installed") : (reload ? "reloaded" : "loaded"); + String action = (installer != null) ? (reload ? "reinstalled" : "installed") : (reload ? "reloaded" : "loaded"); - final String finalName = name; - final Boolean isCommandAdded = newHost.addAppCommands(s -> { + String finalName = name; + Boolean isCommandAdded = newHost.addAppCommands(s -> { if (!isRuleApp) { Carpet.Messenger_message(source, "r Failed to add app '" + finalName + "': ", s); @@ -336,7 +337,7 @@ else if (isCommandAdded) if (newHost.isPerUser()) { // that will provide player hosts right at the startup - for (final ServerPlayer player : source.getServer().getPlayerList().getPlayers()) + for (ServerPlayer player : source.getServer().getPlayerList().getPlayers()) { newHost.retrieveForExecution(player.createCommandSourceStack(), player); } @@ -344,25 +345,25 @@ else if (isCommandAdded) else { // global app - calling start now. - final FunctionValue onStart = newHost.getFunction("__on_start"); + FunctionValue onStart = newHost.getFunction("__on_start"); if (onStart != null) { newHost.callNow(onStart, Collections.emptyList()); } } token.run(); - final long end = System.nanoTime(); + long end = System.nanoTime(); LOG.info("App " + name + " loaded in " + (end - start) / 1000000 + " ms"); return true; } - public boolean isInvalidCommandRoot(final String appName) + public boolean isInvalidCommandRoot(String appName) { return holyMoly.contains(appName); } - public boolean removeScriptHost(final CommandSourceStack source, String name, final boolean notifySource, final boolean isRuleApp) + public boolean removeScriptHost(CommandSourceStack source, String name, boolean notifySource, boolean isRuleApp) { name = name.toLowerCase(Locale.ROOT); if (!modules.containsKey(name) || (!isRuleApp && !unloadableModules.contains(name))) @@ -374,7 +375,7 @@ public boolean removeScriptHost(final CommandSourceStack source, String name, fi return false; } // stop all events associated with name - final CarpetScriptHost host = modules.remove(name); + CarpetScriptHost host = modules.remove(name); events.removeAllHostEvents(host); host.onClose(); if (host.hasCommand) @@ -393,12 +394,12 @@ public boolean removeScriptHost(final CommandSourceStack source, String name, fi return true; } - public boolean uninstallApp(final CommandSourceStack source, String name) + public boolean uninstallApp(CommandSourceStack source, String name) { try { name = name.toLowerCase(Locale.ROOT); - final Path folder = server.getWorldPath(LevelResource.ROOT).resolve("scripts/trash"); + Path folder = server.getWorldPath(LevelResource.ROOT).resolve("scripts/trash"); if (!Files.exists(folder)) { Files.createDirectories(folder); @@ -413,7 +414,7 @@ public boolean uninstallApp(final CommandSourceStack source, String name) Carpet.Messenger_message(source, "gi Removed " + name + " app"); return true; } - catch (final IOException exc) + catch (IOException exc) { Carpet.Messenger_message(source, "rb Failed to uninstall the app"); } @@ -430,7 +431,7 @@ public void tick() }); token.run(); token = Carpet.startProfilerSection("Scarpet app data"); - for (final CarpetScriptHost host : modules.values()) + for (CarpetScriptHost host : modules.values()) { host.tick(); } @@ -440,7 +441,7 @@ public void tick() public void onClose() { CarpetEventServer.Event.SHUTDOWN.onTick(server); - for (final CarpetScriptHost host : modules.values()) + for (CarpetScriptHost host : modules.values()) { host.onClose(); events.removeAllHostEvents(host); @@ -448,7 +449,7 @@ public void onClose() stopAll = true; } - public void onPlayerJoin(final ServerPlayer player) + public void onPlayerJoin(ServerPlayer player) { modules.values().forEach(h -> { @@ -458,7 +459,7 @@ public void onPlayerJoin(final ServerPlayer player) { h.retrieveOwnForExecution(player.createCommandSourceStack()); } - catch (final CommandSyntaxException ignored) + catch (CommandSyntaxException ignored) { } } @@ -466,7 +467,7 @@ public void onPlayerJoin(final ServerPlayer player) } @Override - public Path resolveResource(final String suffix) + public Path resolveResource(String suffix) { return server.getWorldPath(LevelResource.ROOT).resolve("scripts/" + suffix); } @@ -474,15 +475,15 @@ public Path resolveResource(final String suffix) private record TransferData(boolean perUser, Predicate commandValidator, boolean isRuleApp) { - private TransferData(final CarpetScriptHost host) + private TransferData(CarpetScriptHost host) { this(host.perUser, host.commandValidator, host.isRuleApp); } } - public void reload(final MinecraftServer server) + public void reload(MinecraftServer server) { - final Map apps = new HashMap<>(); + Map apps = new HashMap<>(); modules.forEach((s, h) -> apps.put(s, new TransferData(h))); apps.keySet().forEach(s -> removeScriptHost(server.createCommandSourceStack(), s, false, false)); CarpetEventServer.Event.clearAllBuiltinEvents(); diff --git a/src/main/java/carpet/script/Context.java b/src/main/java/carpet/script/Context.java index 8450667f2d..35c46cd0db 100644 --- a/src/main/java/carpet/script/Context.java +++ b/src/main/java/carpet/script/Context.java @@ -30,32 +30,32 @@ public enum Type public final ScriptHost host; - public Context(final ScriptHost host) + public Context(ScriptHost host) { this.host = host; } - public LazyValue getVariable(final String name) + public LazyValue getVariable(String name) { return variables.get(name); } - public void setVariable(final String name, final LazyValue lv) + public void setVariable(String name, LazyValue lv) { variables.put(name, lv); } - public void delVariable(final String variable) + public void delVariable(String variable) { variables.remove(variable); } - public void removeVariablesMatching(final String varname) + public void removeVariablesMatching(String varname) { variables.entrySet().removeIf(e -> e.getKey().startsWith(varname)); } - public Context with(final String variable, final LazyValue lv) + public Context with(String variable, LazyValue lv) { variables.put(variable, lv); return this; @@ -68,7 +68,7 @@ public Set getAllVariableNames() public Context recreate() { - final Context ctx = duplicate(); + Context ctx = duplicate(); ctx.initialize(); return ctx; } @@ -104,7 +104,7 @@ public static class ContextForErrorReporting extends Context { public ScriptHost.ErrorSnooper optmizerEerrorSnooper; - public ContextForErrorReporting(final Context parent) + public ContextForErrorReporting(Context parent) { super(null); optmizerEerrorSnooper = parent.host.errorSnooper; @@ -125,32 +125,32 @@ public void badProgrammer() } @Override - public LazyValue getVariable(final String name) + public LazyValue getVariable(String name) { badProgrammer(); return null; } @Override - public void setVariable(final String name, final LazyValue lv) + public void setVariable(String name, LazyValue lv) { badProgrammer(); } @Override - public void delVariable(final String variable) + public void delVariable(String variable) { badProgrammer(); } @Override - public void removeVariablesMatching(final String varname) + public void removeVariablesMatching(String varname) { badProgrammer(); } @Override - public Context with(final String variable, final LazyValue lv) + public Context with(String variable, LazyValue lv) { badProgrammer(); return this; diff --git a/src/main/java/carpet/script/EntityEventsGroup.java b/src/main/java/carpet/script/EntityEventsGroup.java index f3b9bb4272..7f59f210f9 100644 --- a/src/main/java/carpet/script/EntityEventsGroup.java +++ b/src/main/java/carpet/script/EntityEventsGroup.java @@ -29,33 +29,33 @@ private record EventKey(String host, String user) private final Map> actions; private final Entity entity; - public EntityEventsGroup(final Entity e) + public EntityEventsGroup(Entity e) { actions = new HashMap<>(); entity = e; } - public void onEvent(final Event type, final Object... args) + public void onEvent(Event type, Object... args) { if (actions.isEmpty()) { return; // most of the cases, trying to be nice } - final Map actionSet = actions.get(type); + Map actionSet = actions.get(type); if (actionSet == null) { return; } - final CarpetScriptServer scriptServer = Vanilla.MinecraftServer_getScriptServer(entity.getServer()); + CarpetScriptServer scriptServer = Vanilla.MinecraftServer_getScriptServer(entity.getServer()); if (scriptServer.stopAll) { return; // executed after world is closin down } - for (final Iterator> iterator = actionSet.entrySet().iterator(); iterator.hasNext(); ) + for (Iterator> iterator = actionSet.entrySet().iterator(); iterator.hasNext(); ) { - final Map.Entry action = iterator.next(); - final EventKey key = action.getKey(); - final ScriptHost host = scriptServer.getAppHostByName(key.host()); + Map.Entry action = iterator.next(); + EventKey key = action.getKey(); + ScriptHost host = scriptServer.getAppHostByName(key.host()); if (host == null) { iterator.remove(); @@ -77,12 +77,12 @@ public void onEvent(final Event type, final Object... args) } } - public void addEvent(final Event type, final ScriptHost host, final FunctionValue fun, final List extraargs) + public void addEvent(Event type, ScriptHost host, FunctionValue fun, List extraargs) { - final EventKey key = new EventKey(host.getName(), host.user); + EventKey key = new EventKey(host.getName(), host.user); if (fun != null) { - final CarpetEventServer.Callback call = type.create(key, fun, extraargs, (CarpetScriptServer) host.scriptServer()); + CarpetEventServer.Callback call = type.create(key, fun, extraargs, (CarpetScriptServer) host.scriptServer()); if (call == null) { throw new InternalExpressionException("wrong number of arguments for callback, required " + type.argcount); @@ -106,7 +106,7 @@ public static class Event public static final Event ON_DEATH = new Event("on_death", 1) { @Override - public List makeArgs(final Entity entity, final Object... providedArgs) + public List makeArgs(Entity entity, Object... providedArgs) { return Arrays.asList( new EntityValue(entity), @@ -119,10 +119,10 @@ public List makeArgs(final Entity entity, final Object... providedArgs) public static final Event ON_DAMAGE = new Event("on_damaged", 3) { @Override - public List makeArgs(final Entity entity, final Object... providedArgs) + public List makeArgs(Entity entity, Object... providedArgs) { - final float amount = (Float) providedArgs[0]; - final DamageSource source = (DamageSource) providedArgs[1]; + float amount = (Float) providedArgs[0]; + DamageSource source = (DamageSource) providedArgs[1]; return Arrays.asList( new EntityValue(entity), new NumericValue(amount), @@ -134,7 +134,7 @@ public List makeArgs(final Entity entity, final Object... providedArgs) public static final Event ON_MOVE = new Event("on_move", 3) { @Override - public List makeArgs(final Entity entity, final Object... providedArgs) + public List makeArgs(Entity entity, Object... providedArgs) { return Arrays.asList( new EntityValue(entity), @@ -148,14 +148,14 @@ public List makeArgs(final Entity entity, final Object... providedArgs) public final int argcount; public final String id; - public Event(final String identifier, final int args) + public Event(String identifier, int args) { id = identifier; argcount = args + 1; // entity is not extra byName.put(identifier, this); } - public CarpetEventServer.Callback create(final EventKey key, final FunctionValue function, final List extraArgs, final CarpetScriptServer scriptServer) + public CarpetEventServer.Callback create(EventKey key, FunctionValue function, List extraArgs, CarpetScriptServer scriptServer) { if ((function.getArguments().size() - (extraArgs == null ? 0 : extraArgs.size())) != argcount) { @@ -164,13 +164,13 @@ public CarpetEventServer.Callback create(final EventKey key, final FunctionValue return new CarpetEventServer.Callback(key.host(), key.user(), function, extraArgs, scriptServer); } - public CarpetEventServer.CallbackResult call(final CarpetEventServer.Callback tickCall, final Entity entity, final Object... args) + public CarpetEventServer.CallbackResult call(CarpetEventServer.Callback tickCall, Entity entity, Object... args) { assert args.length == argcount - 1; return tickCall.execute(entity.createCommandSourceStack(), makeArgs(entity, args)); } - protected List makeArgs(final Entity entity, final Object... args) + protected List makeArgs(Entity entity, Object... args) { return Collections.singletonList(new EntityValue(entity)); } diff --git a/src/main/java/carpet/script/Expression.java b/src/main/java/carpet/script/Expression.java index 290f4fc5a8..a03f96cda7 100644 --- a/src/main/java/carpet/script/Expression.java +++ b/src/main/java/carpet/script/Expression.java @@ -80,7 +80,7 @@ public void asATextSource() allowComments = true; } - public void asAModule(final Module mi) + public void asAModule(Module mi) { module = mi; } @@ -95,7 +95,7 @@ public void asAModule(final Module mi) */ private final Map operators = new Object2ObjectOpenHashMap<>(); - public boolean isAnOperator(final String opname) + public boolean isAnOperator(String opname) { return operators.containsKey(opname) || operators.containsKey(opname + "u"); } @@ -109,7 +109,7 @@ public Set getFunctionNames() private final Map functionalEquivalence = new Object2ObjectOpenHashMap<>(); - public void addFunctionalEquivalence(final String operator, final String function) + public void addFunctionalEquivalence(String operator, String function) { assert operators.containsKey(operator); assert functions.containsKey(function); @@ -124,25 +124,25 @@ public void addFunctionalEquivalence(final String operator, final String functio "false", Value.FALSE ); - protected Value getConstantFor(final String surface) + protected Value getConstantFor(String surface) { return constants.get(surface); } - public List getExpressionSnippet(final Tokenizer.Token token) + public List getExpressionSnippet(Tokenizer.Token token) { - final String code = this.getCodeString(); - final List output = new ArrayList<>(getExpressionSnippetLeftContext(token, code, 1)); - final List context = getExpressionSnippetContext(token, code); + String code = this.getCodeString(); + List output = new ArrayList<>(getExpressionSnippetLeftContext(token, code, 1)); + List context = getExpressionSnippetContext(token, code); output.add(context.get(0) + " HERE>> " + context.get(1)); output.addAll(getExpressionSnippetRightContext(token, code, 1)); return output; } - private static List getExpressionSnippetLeftContext(final Tokenizer.Token token, final String expr, final int contextsize) + private static List getExpressionSnippetLeftContext(Tokenizer.Token token, String expr, int contextsize) { - final List output = new ArrayList<>(); - final String[] lines = expr.split("\n"); + List output = new ArrayList<>(); + String[] lines = expr.split("\n"); if (lines.length == 1) { return output; @@ -155,10 +155,10 @@ private static List getExpressionSnippetLeftContext(final Tokenizer.Toke return output; } - private static List getExpressionSnippetContext(final Tokenizer.Token token, final String expr) + private static List getExpressionSnippetContext(Tokenizer.Token token, String expr) { - final List output = new ArrayList<>(); - final String[] lines = expr.split("\n"); + List output = new ArrayList<>(); + String[] lines = expr.split("\n"); if (lines.length > 1) { output.add(lines[token.lineno].substring(0, token.linepos)); @@ -172,10 +172,10 @@ private static List getExpressionSnippetContext(final Tokenizer.Token to return output; } - private static List getExpressionSnippetRightContext(final Tokenizer.Token token, final String expr, final int contextsize) + private static List getExpressionSnippetRightContext(Tokenizer.Token token, String expr, int contextsize) { - final List output = new ArrayList<>(); - final String[] lines = expr.split("\n"); + List output = new ArrayList<>(); + String[] lines = expr.split("\n"); if (lines.length == 1) { return output; @@ -188,8 +188,8 @@ private static List getExpressionSnippetRightContext(final Tokenizer.Tok } - public void addLazyUnaryOperator(final String surface, final int precedence, final boolean leftAssoc, final boolean pure, final Function staticTyper, - final TriFunction lazyfun) + public void addLazyUnaryOperator(String surface, int precedence, boolean leftAssoc, boolean pure, Function staticTyper, + TriFunction lazyfun) { operators.put(surface + "u", new AbstractLazyOperator(precedence, leftAssoc) { @@ -206,19 +206,19 @@ public boolean transitive() } @Override - public Context.Type staticType(final Context.Type outerType) + public Context.Type staticType(Context.Type outerType) { return staticTyper.apply(outerType); } @Override - public LazyValue lazyEval(final Context c, final Context.Type t, final Expression e, final Tokenizer.Token token, final LazyValue v, final LazyValue v2) + public LazyValue lazyEval(Context c, Context.Type t, Expression e, Tokenizer.Token token, LazyValue v, LazyValue v2) { try { return lazyfun.apply(c, t, v); } - catch (final RuntimeException exc) + catch (RuntimeException exc) { throw handleCodeException(c, exc, e, token); } @@ -227,8 +227,8 @@ public LazyValue lazyEval(final Context c, final Context.Type t, final Expressio } - public void addLazyBinaryOperatorWithDelegation(final String surface, final int precedence, final boolean leftAssoc, final boolean pure, - final SexFunction lazyfun) + public void addLazyBinaryOperatorWithDelegation(String surface, int precedence, boolean leftAssoc, boolean pure, + SexFunction lazyfun) { operators.put(surface, new AbstractLazyOperator(precedence, leftAssoc) { @@ -245,13 +245,13 @@ public boolean transitive() } @Override - public LazyValue lazyEval(final Context c, final Context.Type type, final Expression e, final Tokenizer.Token t, final LazyValue v1, final LazyValue v2) + public LazyValue lazyEval(Context c, Context.Type type, Expression e, Tokenizer.Token t, LazyValue v1, LazyValue v2) { try { return lazyfun.apply(c, type, e, t, v1, v2); } - catch (final RuntimeException exc) + catch (RuntimeException exc) { throw handleCodeException(c, exc, e, t); } @@ -259,13 +259,13 @@ public LazyValue lazyEval(final Context c, final Context.Type type, final Expres }); } - public void addCustomFunction(final String name, final ILazyFunction fun) + public void addCustomFunction(String name, ILazyFunction fun) { functions.put(name, fun); } - public void addLazyFunctionWithDelegation(final String name, final int numpar, final boolean pure, final boolean transitive, - final QuinnFunction, LazyValue> lazyfun) + public void addLazyFunctionWithDelegation(String name, int numpar, boolean pure, boolean transitive, + QuinnFunction, LazyValue> lazyfun) { functions.put(name, new AbstractLazyFunction(numpar, name) { @@ -282,14 +282,14 @@ public boolean transitive() } @Override - public LazyValue lazyEval(final Context c, final Context.Type type, final Expression e, final Tokenizer.Token t, final List lv) + public LazyValue lazyEval(Context c, Context.Type type, Expression e, Tokenizer.Token t, List lv) { ILazyFunction.checkInterrupts(); try { return lazyfun.apply(c, type, e, t, lv); } - catch (final RuntimeException exc) + catch (RuntimeException exc) { throw handleCodeException(c, exc, e, t); } @@ -297,8 +297,8 @@ public LazyValue lazyEval(final Context c, final Context.Type type, final Expres }); } - public void addFunctionWithDelegation(final String name, final int numpar, final boolean pure, final boolean transitive, - final QuinnFunction, Value> fun) + public void addFunctionWithDelegation(String name, int numpar, boolean pure, boolean transitive, + QuinnFunction, Value> fun) { functions.put(name, new AbstractLazyFunction(numpar, name) { @@ -315,14 +315,14 @@ public boolean transitive() } @Override - public LazyValue lazyEval(final Context c, final Context.Type type, final Expression e, final Tokenizer.Token t, final List lv) + public LazyValue lazyEval(Context c, Context.Type type, Expression e, Tokenizer.Token t, List lv) { try { - final Value res = fun.apply(c, type, e, t, unpackArgs(lv, c, Context.NONE)); + Value res = fun.apply(c, type, e, t, unpackArgs(lv, c, Context.NONE)); return (cc, tt) -> res; } - catch (final RuntimeException exc) + catch (RuntimeException exc) { throw handleCodeException(c, exc, e, t); } @@ -330,8 +330,8 @@ public LazyValue lazyEval(final Context c, final Context.Type type, final Expres }); } - public void addLazyBinaryOperator(final String surface, final int precedence, final boolean leftAssoc, final boolean pure, final Function typer, - final QuadFunction lazyfun) + public void addLazyBinaryOperator(String surface, int precedence, boolean leftAssoc, boolean pure, Function typer, + QuadFunction lazyfun) { operators.put(surface, new AbstractLazyOperator(precedence, leftAssoc) { @@ -349,20 +349,20 @@ public boolean transitive() } @Override - public Context.Type staticType(final Context.Type outerType) + public Context.Type staticType(Context.Type outerType) { return typer.apply(outerType); } @Override - public LazyValue lazyEval(final Context c, final Context.Type t, final Expression e, final Tokenizer.Token token, final LazyValue v1, final LazyValue v2) + public LazyValue lazyEval(Context c, Context.Type t, Expression e, Tokenizer.Token token, LazyValue v1, LazyValue v2) { ILazyFunction.checkInterrupts(); try { return lazyfun.apply(c, t, v1, v2); } - catch (final RuntimeException exc) + catch (RuntimeException exc) { throw handleCodeException(c, exc, e, token); } @@ -370,8 +370,8 @@ public LazyValue lazyEval(final Context c, final Context.Type t, final Expressio }); } - public void addBinaryContextOperator(final String surface, final int precedence, final boolean leftAssoc, final boolean pure, final boolean transitive, - final QuadFunction fun) + public void addBinaryContextOperator(String surface, int precedence, boolean leftAssoc, boolean pure, boolean transitive, + QuadFunction fun) { operators.put(surface, new AbstractLazyOperator(precedence, leftAssoc) { @@ -388,14 +388,14 @@ public boolean transitive() } @Override - public LazyValue lazyEval(final Context c, final Context.Type t, final Expression e, final Tokenizer.Token token, final LazyValue v1, final LazyValue v2) + public LazyValue lazyEval(Context c, Context.Type t, Expression e, Tokenizer.Token token, LazyValue v1, LazyValue v2) { try { - final Value ret = fun.apply(c, t, v1.evalValue(c, Context.NONE), v2.evalValue(c, Context.NONE)); + Value ret = fun.apply(c, t, v1.evalValue(c, Context.NONE), v2.evalValue(c, Context.NONE)); return (cc, tt) -> ret; } - catch (final RuntimeException exc) + catch (RuntimeException exc) { throw handleCodeException(c, exc, e, token); } @@ -403,7 +403,7 @@ public LazyValue lazyEval(final Context c, final Context.Type t, final Expressio }); } - public static RuntimeException handleCodeException(final Context c, final RuntimeException exc, final Expression e, final Tokenizer.Token token) + public static RuntimeException handleCodeException(Context c, RuntimeException exc, Expression e, Tokenizer.Token token) { if (exc instanceof ExitStatement) { @@ -430,24 +430,24 @@ public static RuntimeException handleCodeException(final Context c, final Runtim return new ExpressionException(c, e, token, "Internal error (please report this issue to Carpet) while evaluating: " + exc); } - public void addUnaryOperator(final String surface, final boolean leftAssoc, final Function fun) + public void addUnaryOperator(String surface, boolean leftAssoc, Function fun) { operators.put(surface + "u", new AbstractUnaryOperator(Operators.precedence.get("unary+-!..."), leftAssoc) { @Override - public Value evalUnary(final Value v1) + public Value evalUnary(Value v1) { return fun.apply(v1); } }); } - public void addBinaryOperator(final String surface, final int precedence, final boolean leftAssoc, final BiFunction fun) + public void addBinaryOperator(String surface, int precedence, boolean leftAssoc, BiFunction fun) { operators.put(surface, new AbstractOperator(precedence, leftAssoc) { @Override - public Value eval(final Value v1, final Value v2) + public Value eval(Value v1, Value v2) { return fun.apply(v1, v2); } @@ -455,19 +455,19 @@ public Value eval(final Value v1, final Value v2) } - public void addUnaryFunction(final String name, final Function fun) + public void addUnaryFunction(String name, Function fun) { functions.put(name, new AbstractFunction(1, name) { @Override - public Value eval(final List parameters) + public Value eval(List parameters) { return fun.apply(parameters.get(0)); } }); } - public void addImpureUnaryFunction(final String name, final Function fun) + public void addImpureUnaryFunction(String name, Function fun) { functions.put(name, new AbstractFunction(1, name) { @@ -478,38 +478,38 @@ public boolean pure() } @Override - public Value eval(final List parameters) + public Value eval(List parameters) { return fun.apply(parameters.get(0)); } }); } - public void addBinaryFunction(final String name, final BiFunction fun) + public void addBinaryFunction(String name, BiFunction fun) { functions.put(name, new AbstractFunction(2, name) { @Override - public Value eval(final List parameters) + public Value eval(List parameters) { return fun.apply(parameters.get(0), parameters.get(1)); } }); } - public void addFunction(final String name, final Function, Value> fun) + public void addFunction(String name, Function, Value> fun) { functions.put(name, new AbstractFunction(-1, name) { @Override - public Value eval(final List parameters) + public Value eval(List parameters) { return fun.apply(parameters); } }); } - public void addImpureFunction(final String name, final Function, Value> fun) + public void addImpureFunction(String name, Function, Value> fun) { functions.put(name, new AbstractFunction(-1, name) { @@ -520,37 +520,37 @@ public boolean pure() } @Override - public Value eval(final List parameters) + public Value eval(List parameters) { return fun.apply(parameters); } }); } - public void addMathematicalUnaryFunction(final String name, final DoubleUnaryOperator fun) + public void addMathematicalUnaryFunction(String name, DoubleUnaryOperator fun) { addUnaryFunction(name, (v) -> new NumericValue(fun.applyAsDouble(NumericValue.asNumber(v).getDouble()))); } - public void addMathematicalUnaryIntFunction(final String name, final DoubleToLongFunction fun) + public void addMathematicalUnaryIntFunction(String name, DoubleToLongFunction fun) { addUnaryFunction(name, (v) -> new NumericValue(fun.applyAsLong(NumericValue.asNumber(v).getDouble()))); } - public void addMathematicalBinaryIntFunction(final String name, final BinaryOperator fun) + public void addMathematicalBinaryIntFunction(String name, BinaryOperator fun) { addBinaryFunction(name, (w, v) -> new NumericValue(fun.apply(NumericValue.asNumber(w).getLong(), NumericValue.asNumber(v).getLong()))); } - public void addMathematicalBinaryFunction(final String name, final BinaryOperator fun) + public void addMathematicalBinaryFunction(String name, BinaryOperator fun) { addBinaryFunction(name, (w, v) -> new NumericValue(fun.apply(NumericValue.asNumber(w).getDouble(), NumericValue.asNumber(v).getDouble()))); } - public void addLazyFunction(final String name, final int numParams, final TriFunction, LazyValue> fun) + public void addLazyFunction(String name, int numParams, TriFunction, LazyValue> fun) { functions.put(name, new AbstractLazyFunction(numParams, name) { @@ -567,12 +567,12 @@ public boolean transitive() } @Override - public LazyValue lazyEval(final Context c, final Context.Type i, final Expression e, final Tokenizer.Token t, final List lazyParams) + public LazyValue lazyEval(Context c, Context.Type i, Expression e, Tokenizer.Token t, List lazyParams) { ILazyFunction.checkInterrupts(); if (numParams >= 0 && lazyParams.size() != numParams) { - final String error = "Function '" + name + "' requires " + numParams + " arguments, got " + lazyParams.size() + ". "; + String error = "Function '" + name + "' requires " + numParams + " arguments, got " + lazyParams.size() + ". "; throw new InternalExpressionException(error + (fun instanceof Fluff.UsageProvider up ? up.getUsage() : "")); } @@ -580,7 +580,7 @@ public LazyValue lazyEval(final Context c, final Context.Type i, final Expressio { return fun.apply(c, i, lazyParams); } - catch (final RuntimeException exc) + catch (RuntimeException exc) { throw handleCodeException(c, exc, e, t); } @@ -588,7 +588,7 @@ public LazyValue lazyEval(final Context c, final Context.Type i, final Expressio }); } - public void addLazyFunction(final String name, final TriFunction, LazyValue> fun) + public void addLazyFunction(String name, TriFunction, LazyValue> fun) { functions.put(name, new AbstractLazyFunction(-1, name) { @@ -605,14 +605,14 @@ public boolean transitive() } @Override - public LazyValue lazyEval(final Context c, final Context.Type i, final Expression e, final Tokenizer.Token t, final List lazyParams) + public LazyValue lazyEval(Context c, Context.Type i, Expression e, Tokenizer.Token t, List lazyParams) { ILazyFunction.checkInterrupts(); try { return fun.apply(c, i, lazyParams); } - catch (final RuntimeException exc) + catch (RuntimeException exc) { throw handleCodeException(c, exc, e, t); } @@ -620,7 +620,7 @@ public LazyValue lazyEval(final Context c, final Context.Type i, final Expressio }); } - public void addPureLazyFunction(final String name, final int num_params, final Function typer, final TriFunction, LazyValue> fun) + public void addPureLazyFunction(String name, int num_params, Function typer, TriFunction, LazyValue> fun) { functions.put(name, new AbstractLazyFunction(num_params, name) { @@ -637,20 +637,20 @@ public boolean transitive() } @Override - public Context.Type staticType(final Context.Type outerType) + public Context.Type staticType(Context.Type outerType) { return typer.apply(outerType); } @Override - public LazyValue lazyEval(final Context c, final Context.Type i, final Expression e, final Tokenizer.Token t, final List lazyParams) + public LazyValue lazyEval(Context c, Context.Type i, Expression e, Tokenizer.Token t, List lazyParams) { ILazyFunction.checkInterrupts(); try { return fun.apply(c, i, lazyParams); } - catch (final RuntimeException exc) + catch (RuntimeException exc) { throw handleCodeException(c, exc, e, t); } @@ -658,7 +658,7 @@ public LazyValue lazyEval(final Context c, final Context.Type i, final Expressio }); } - public void addContextFunction(final String name, final int num_params, final TriFunction, Value> fun) + public void addContextFunction(String name, int num_params, TriFunction, Value> fun) { functions.put(name, new AbstractLazyFunction(num_params, name) { @@ -675,15 +675,15 @@ public boolean transitive() } @Override - public LazyValue lazyEval(final Context c, final Context.Type i, final Expression e, final Tokenizer.Token t, final List lazyParams) + public LazyValue lazyEval(Context c, Context.Type i, Expression e, Tokenizer.Token t, List lazyParams) { ILazyFunction.checkInterrupts(); try { - final Value ret = fun.apply(c, i, unpackArgs(lazyParams, c, Context.NONE)); + Value ret = fun.apply(c, i, unpackArgs(lazyParams, c, Context.NONE)); return (cc, tt) -> ret; } - catch (final RuntimeException exc) + catch (RuntimeException exc) { throw handleCodeException(c, exc, e, t); } @@ -691,7 +691,7 @@ public LazyValue lazyEval(final Context c, final Context.Type i, final Expressio }); } - public void addTypedContextFunction(final String name, final int num_params, final Context.Type reqType, final TriFunction, Value> fun) + public void addTypedContextFunction(String name, int num_params, Context.Type reqType, TriFunction, Value> fun) { functions.put(name, new AbstractLazyFunction(num_params, name) { @@ -708,20 +708,20 @@ public boolean transitive() } @Override - public Context.Type staticType(final Context.Type outerType) + public Context.Type staticType(Context.Type outerType) { return reqType; } @Override - public LazyValue lazyEval(final Context c, final Context.Type i, final Expression e, final Tokenizer.Token t, final List lazyParams) + public LazyValue lazyEval(Context c, Context.Type i, Expression e, Tokenizer.Token t, List lazyParams) { try { - final Value ret = fun.apply(c, i, unpackArgs(lazyParams, c, reqType)); + Value ret = fun.apply(c, i, unpackArgs(lazyParams, c, reqType)); return (cc, tt) -> ret; } - catch (final RuntimeException exc) + catch (RuntimeException exc) { throw handleCodeException(c, exc, e, t); } @@ -729,16 +729,16 @@ public LazyValue lazyEval(final Context c, final Context.Type i, final Expressio }); } - public FunctionValue createUserDefinedFunction(final Context context, final String name, final Expression expr, final Tokenizer.Token token, final List arguments, final String varArgs, final List outers, final LazyValue code) + public FunctionValue createUserDefinedFunction(Context context, String name, Expression expr, Tokenizer.Token token, List arguments, String varArgs, List outers, LazyValue code) { if (functions.containsKey(name)) { throw new ExpressionException(context, expr, token, "Function " + name + " would mask a built-in function"); } Map contextValues = new HashMap<>(); - for (final String outer : outers) + for (String outer : outers) { - final LazyValue lv = context.getVariable(outer); + LazyValue lv = context.getVariable(outer); if (lv == null) { throw new InternalExpressionException("Variable " + outer + " needs to be defined in outer scope to be used as outer parameter, and cannot be global"); @@ -753,7 +753,7 @@ public FunctionValue createUserDefinedFunction(final Context context, final Stri contextValues = null; } - final FunctionValue result = new FunctionValue(expr, token, name, code, arguments, varArgs, contextValues); + FunctionValue result = new FunctionValue(expr, token, name, code, arguments, varArgs, contextValues); // do not store lambda definitions if (!name.equals("_")) { @@ -762,9 +762,9 @@ public FunctionValue createUserDefinedFunction(final Context context, final Stri return result; } - public void alias(final String copy, final String original) + public void alias(String copy, String original) { - final ILazyFunction originalFunction = functions.get(original); + ILazyFunction originalFunction = functions.get(original); functions.put(copy, new ILazyFunction() { @Override @@ -792,13 +792,13 @@ public boolean transitive() } @Override - public Context.Type staticType(final Context.Type outerType) + public Context.Type staticType(Context.Type outerType) { return originalFunction.staticType(outerType); } @Override - public LazyValue lazyEval(final Context c, final Context.Type type, final Expression expr, final Tokenizer.Token token, final List lazyParams) + public LazyValue lazyEval(Context c, Context.Type type, Expression expr, Tokenizer.Token token, List lazyParams) { c.host.issueDeprecation(copy + "(...)"); return originalFunction.lazyEval(c, type, expr, token, lazyParams); @@ -807,7 +807,7 @@ public LazyValue lazyEval(final Context c, final Context.Type type, final Expres } - public void setAnyVariable(final Context c, final String name, final LazyValue lv) + public void setAnyVariable(Context c, String name, LazyValue lv) { if (name.startsWith("global_")) { @@ -819,7 +819,7 @@ public void setAnyVariable(final Context c, final String name, final LazyValue l } } - public LazyValue getOrSetAnyVariable(final Context c, final String name) + public LazyValue getOrSetAnyVariable(Context c, String name) { LazyValue variable; if (!name.startsWith("global_")) @@ -845,7 +845,7 @@ public LazyValue getOrSetAnyVariable(final Context c, final String name) /** * @param expression . */ - public Expression(final String expression) + public Expression(String expression) { this.expression = expression.stripTrailing().replaceAll("\\r\\n?", "\n").replaceAll("\\t", " "); Operators.apply(this); @@ -859,18 +859,18 @@ public Expression(final String expression) } - private List shuntingYard(final Context c) + private List shuntingYard(Context c) { - final List outputQueue = new ArrayList<>(); - final Stack stack = new ObjectArrayList<>(); + List outputQueue = new ArrayList<>(); + Stack stack = new ObjectArrayList<>(); - final Tokenizer tokenizer = new Tokenizer(c, this, expression, allowComments, allowNewlineSubstitutions); + Tokenizer tokenizer = new Tokenizer(c, this, expression, allowComments, allowNewlineSubstitutions); // stripping lousy but acceptable semicolons - final List cleanedTokens = tokenizer.postProcess(); + List cleanedTokens = tokenizer.postProcess(); Tokenizer.Token lastFunction = null; Tokenizer.Token previousToken = null; - for (final Tokenizer.Token token : cleanedTokens) + for (Tokenizer.Token token : cleanedTokens) { switch (token.type) { @@ -922,7 +922,7 @@ private List shuntingYard(final Context c) { throw new ExpressionException(c, this, token, "Missing parameter(s) for operator '" + token + "'"); } - final ILazyOperator o1 = operators.get(token.surface); + ILazyOperator o1 = operators.get(token.surface); if (o1 == null) { throw new ExpressionException(c, this, token, "Unknown operator '" + token + "'"); @@ -939,7 +939,7 @@ private List shuntingYard(final Context c) { throw new ExpressionException(c, this, token, "Invalid position for unary operator " + token); } - final ILazyOperator o1 = operators.get(token.surface); + ILazyOperator o1 = operators.get(token.surface); if (o1 == null) { throw new ExpressionException(c, this, token, "Unknown unary operator '" + token.surface.substring(0, token.surface.length() - 1) + "'"); @@ -979,7 +979,7 @@ private List shuntingYard(final Context c) case MARKER: if ("$".equals(token.surface)) { - final StringBuilder sb = new StringBuilder(expression); + StringBuilder sb = new StringBuilder(expression); sb.setCharAt(token.pos, '\n'); expression = sb.toString(); } @@ -993,7 +993,7 @@ private List shuntingYard(final Context c) while (!stack.isEmpty()) { - final Tokenizer.Token element = stack.pop(); + Tokenizer.Token element = stack.pop(); if (element.type == Tokenizer.Token.TokenType.OPEN_PAREN || element.type == Tokenizer.Token.TokenType.CLOSE_PAREN) { throw new ExpressionException(c, this, element, "Mismatched parentheses"); @@ -1003,7 +1003,7 @@ private List shuntingYard(final Context c) return outputQueue; } - private void shuntOperators(final List outputQueue, final Stack stack, final ILazyOperator o1) + private void shuntOperators(List outputQueue, Stack stack, ILazyOperator o1) { Tokenizer.Token nextToken = stack.isEmpty() ? null : stack.top(); while (nextToken != null @@ -1017,7 +1017,7 @@ private void shuntOperators(final List outputQueue, final Stack } } - public Value eval(final Context c) + public Value eval(Context c) { if (ast == null) { @@ -1026,29 +1026,29 @@ public Value eval(final Context c) return evalValue(() -> ast, c, Context.Type.NONE); } - public Value evalValue(final Supplier exprProvider, final Context c, final Context.Type expectedType) + public Value evalValue(Supplier exprProvider, Context c, Context.Type expectedType) { try { return exprProvider.get().evalValue(c, expectedType); } - catch (final ContinueStatement | BreakStatement | ReturnStatement exc) + catch (ContinueStatement | BreakStatement | ReturnStatement exc) { throw new ExpressionException(c, this, "Control flow functions, like continue, break or return, should only be used in loops, and functions respectively."); } - catch (final ExitStatement exit) + catch (ExitStatement exit) { return exit.retval == null ? Value.NULL : exit.retval; } - catch (final StackOverflowError ignored) + catch (StackOverflowError ignored) { throw new ExpressionException(c, this, "Your thoughts are too deep"); } - catch (final InternalExpressionException exc) + catch (InternalExpressionException exc) { throw new ExpressionException(c, this, "Your expression result is incorrect: " + exc.getMessage()); } - catch (final ArithmeticException exc) + catch (ArithmeticException exc) { throw new ExpressionException(c, this, "The final result is incorrect: " + exc.getMessage()); } @@ -1066,7 +1066,7 @@ public static class ExpressionNode */ public static final ExpressionNode PARAMS_START = new ExpressionNode(null, null, Tokenizer.Token.NONE); - public ExpressionNode(final LazyValue op, final List args, final Tokenizer.Token token) + public ExpressionNode(LazyValue op, List args, Tokenizer.Token token) { this.op = op; this.args = args; @@ -1075,32 +1075,32 @@ public ExpressionNode(final LazyValue op, final List args, final range.add(token); } - public static ExpressionNode ofConstant(final Value val, final Tokenizer.Token token) + public static ExpressionNode ofConstant(Value val, Tokenizer.Token token) { return new ExpressionNode(new LazyValue.Constant(val), Collections.emptyList(), token); } } - private ExpressionNode RPNToParseTree(final List tokens, final Context context) + private ExpressionNode RPNToParseTree(List tokens, Context context) { - final Stack nodeStack = new ObjectArrayList<>(); - for (final Tokenizer.Token token : tokens) + Stack nodeStack = new ObjectArrayList<>(); + for (Tokenizer.Token token : tokens) { switch (token.type) { case UNARY_OPERATOR -> { - final ExpressionNode node = nodeStack.pop(); - final LazyValue result = (c, t) -> operators.get(token.surface).lazyEval(c, t, this, token, node.op, null).evalValue(c, t); + ExpressionNode node = nodeStack.pop(); + LazyValue result = (c, t) -> operators.get(token.surface).lazyEval(c, t, this, token, node.op, null).evalValue(c, t); nodeStack.push(new ExpressionNode(result, Collections.singletonList(node), token)); } case OPERATOR -> { - final ExpressionNode v1 = nodeStack.pop(); - final ExpressionNode v2 = nodeStack.pop(); - final LazyValue result = (c, t) -> operators.get(token.surface).lazyEval(c, t, this, token, v2.op, v1.op).evalValue(c, t); + ExpressionNode v1 = nodeStack.pop(); + ExpressionNode v2 = nodeStack.pop(); + LazyValue result = (c, t) -> operators.get(token.surface).lazyEval(c, t, this, token, v2.op, v1.op).evalValue(c, t); nodeStack.push(new ExpressionNode(result, List.of(v2, v1), token)); } case VARIABLE -> { - final Value constant = getConstantFor(token.surface); + Value constant = getConstantFor(token.surface); if (constant != null) { token.morph(Tokenizer.Token.TokenType.CONSTANT, token.surface); @@ -1112,10 +1112,10 @@ private ExpressionNode RPNToParseTree(final List tokens, final } } case FUNCTION -> { - final String name = token.surface; - final ILazyFunction f; - final ArrayList p; - final boolean isKnown = functions.containsKey(name); // globals will be evaluated lazily, not at compile time via . + String name = token.surface; + ILazyFunction f; + ArrayList p; + boolean isKnown = functions.containsKey(name); // globals will be evaluated lazily, not at compile time via . if (isKnown) { f = functions.get(name); @@ -1142,7 +1142,7 @@ private ExpressionNode RPNToParseTree(final List tokens, final { nodeStack.pop(); } - final List params = p.stream().map(n -> n.op).collect(Collectors.toList()); + List params = p.stream().map(n -> n.op).collect(Collectors.toList()); nodeStack.push(new ExpressionNode( (c, t) -> f.lazyEval(c, t, this, token, params).evalValue(c, t), p, token @@ -1150,12 +1150,12 @@ private ExpressionNode RPNToParseTree(final List tokens, final } case OPEN_PAREN -> nodeStack.push(ExpressionNode.PARAMS_START); case LITERAL -> { - final Value number; + Value number; try { number = new NumericValue(token.surface); } - catch (final NumberFormatException exception) + catch (NumberFormatException exception) { throw new ExpressionException(context, this, token, "Not a number"); } @@ -1167,12 +1167,12 @@ private ExpressionNode RPNToParseTree(final List tokens, final nodeStack.push(ExpressionNode.ofConstant(new StringValue(token.surface), token)); } case HEX_LITERAL -> { - final Value hexNumber; + Value hexNumber; try { hexNumber = new NumericValue(new BigInteger(token.surface.substring(2), 16).longValue()); } - catch (final NumberFormatException exception) + catch (NumberFormatException exception) { throw new ExpressionException(context, this, token, "Not a number"); } @@ -1185,18 +1185,18 @@ private ExpressionNode RPNToParseTree(final List tokens, final return nodeStack.pop(); } - private LazyValue getAST(final Context context) + private LazyValue getAST(Context context) { - final List rpn = shuntingYard(context); + List rpn = shuntingYard(context); validate(context, rpn); - final ExpressionNode root = RPNToParseTree(rpn, context); + ExpressionNode root = RPNToParseTree(rpn, context); if (!Vanilla.ScriptServer_scriptOptimizations(((CarpetScriptServer)context.scriptServer()).server)) { return root.op; } - final Context optimizeOnlyContext = new Context.ContextForErrorReporting(context); - final boolean scriptsDebugging = Vanilla.ScriptServer_scriptDebugging(((CarpetScriptServer)context.scriptServer()).server); + Context optimizeOnlyContext = new Context.ContextForErrorReporting(context); + boolean scriptsDebugging = Vanilla.ScriptServer_scriptDebugging(((CarpetScriptServer)context.scriptServer()).server); if (scriptsDebugging) { CarpetScriptServer.LOG.info("Input code size for " + getModuleName() + ": " + treeSize(root) + " nodes, " + treeDepth(root) + " deep"); @@ -1217,7 +1217,7 @@ private LazyValue getAST(final Context context) prevTreeSize = treeSize(root); prevTreeDepth = treeDepth(root); } - final boolean optimized = compactTree(root, Context.Type.NONE, 0, scriptsDebugging); + boolean optimized = compactTree(root, Context.Type.NONE, 0, scriptsDebugging); if (!optimized) { break; @@ -1235,7 +1235,7 @@ private LazyValue getAST(final Context context) prevTreeSize = treeSize(root); prevTreeDepth = treeDepth(root); } - final boolean optimized = optimizeTree(optimizeOnlyContext, root, Context.Type.NONE, 0, scriptsDebugging); + boolean optimized = optimizeTree(optimizeOnlyContext, root, Context.Type.NONE, 0, scriptsDebugging); if (!optimized) { break; @@ -1250,22 +1250,22 @@ private LazyValue getAST(final Context context) return extractOp(optimizeOnlyContext, root, Context.Type.NONE); } - private int treeSize(final ExpressionNode node) + private int treeSize(ExpressionNode node) { return node.op instanceof LazyValue.ContextFreeLazyValue ? 1 : node.args.stream().mapToInt(this::treeSize).sum() + 1; } - private int treeDepth(final ExpressionNode node) + private int treeDepth(ExpressionNode node) { return node.op instanceof LazyValue.ContextFreeLazyValue ? 1 : node.args.stream().mapToInt(this::treeDepth).max().orElse(0) + 1; } - private boolean compactTree(final ExpressionNode node, final Context.Type expectedType, final int indent, final boolean scriptsDebugging) + private boolean compactTree(ExpressionNode node, Context.Type expectedType, int indent, boolean scriptsDebugging) { // ctx is just to report errors, not values evaluation boolean optimized = false; - final Tokenizer.Token.TokenType token = node.token.type; + Tokenizer.Token.TokenType token = node.token.type; if (!token.isFunctional()) { return false; @@ -1276,10 +1276,10 @@ private boolean compactTree(final ExpressionNode node, final Context.Type expect return false; // optimized already } // function or operator - final String symbol = node.token.surface; - final Fluff.EvalNode operation = ((token == Tokenizer.Token.TokenType.FUNCTION) ? functions : operators).get(symbol); - final Context.Type requestedType = operation.staticType(expectedType); - for (final ExpressionNode arg : node.args) + String symbol = node.token.surface; + Fluff.EvalNode operation = ((token == Tokenizer.Token.TokenType.FUNCTION) ? functions : operators).get(symbol); + Context.Type requestedType = operation.staticType(expectedType); + for (ExpressionNode arg : node.args) { if (compactTree(arg, requestedType, indent + 1, scriptsDebugging)) { @@ -1289,11 +1289,11 @@ private boolean compactTree(final ExpressionNode node, final Context.Type expect if (expectedType != Context.Type.MAPDEF && symbol.equals("->") && node.args.size() == 2) { - final String rop = node.args.get(1).token.surface; + String rop = node.args.get(1).token.surface; ExpressionNode returnNode = null; if ((rop.equals(";") || rop.equals("then"))) { - final List thenArgs = node.args.get(1).args; + List thenArgs = node.args.get(1).args; if (thenArgs.size() > 1 && thenArgs.get(thenArgs.size() - 1).token.surface.equals("return")) { returnNode = thenArgs.get(thenArgs.size() - 1); @@ -1329,19 +1329,19 @@ else if (rop.equals("return")) } } - for (final Map.Entry pair : functionalEquivalence.entrySet()) + for (Map.Entry pair : functionalEquivalence.entrySet()) { - final String operator = pair.getKey(); - final String function = pair.getValue(); + String operator = pair.getKey(); + String function = pair.getValue(); if ((symbol.equals(operator) || symbol.equals(function)) && node.args.size() > 0) { - final boolean leftOptimizable = operators.get(operator).isLeftAssoc(); - final ExpressionNode optimizedChild = node.args.get(leftOptimizable ? 0 : (node.args.size() - 1)); - final String type = optimizedChild.token.surface; + boolean leftOptimizable = operators.get(operator).isLeftAssoc(); + ExpressionNode optimizedChild = node.args.get(leftOptimizable ? 0 : (node.args.size() - 1)); + String type = optimizedChild.token.surface; if ((type.equals(operator) || type.equals(function)) && (!(optimizedChild.op instanceof LazyValue.ContextFreeLazyValue))) { optimized = true; - final List newargs = new ArrayList<>(); + List newargs = new ArrayList<>(); if (leftOptimizable) { newargs.addAll(optimizedChild.args); @@ -1371,16 +1371,16 @@ else if (rop.equals("return")) return optimized; } - private boolean optimizeTree(final Context ctx, final ExpressionNode node, Context.Type expectedType, final int indent, final boolean scriptsDebugging) + private boolean optimizeTree(Context ctx, ExpressionNode node, Context.Type expectedType, int indent, boolean scriptsDebugging) { // ctx is just to report errors, not values evaluation boolean optimized = false; - final Tokenizer.Token.TokenType token = node.token.type; + Tokenizer.Token.TokenType token = node.token.type; if (!token.isFunctional()) { return false; } - final String symbol = node.token.surface; + String symbol = node.token.surface; // input special cases here, like function signature if (node.op instanceof LazyValue.Constant) @@ -1389,9 +1389,9 @@ private boolean optimizeTree(final Context ctx, final ExpressionNode node, Conte } // function or operator - final Fluff.EvalNode operation = ((token == Tokenizer.Token.TokenType.FUNCTION) ? functions : operators).get(symbol); - final Context.Type requestedType = operation.staticType(expectedType); - for (final ExpressionNode arg : node.args) + Fluff.EvalNode operation = ((token == Tokenizer.Token.TokenType.FUNCTION) ? functions : operators).get(symbol); + Context.Type requestedType = operation.staticType(expectedType); + for (ExpressionNode arg : node.args) { if (optimizeTree(ctx, arg, requestedType, indent + 1, scriptsDebugging)) { @@ -1399,7 +1399,7 @@ private boolean optimizeTree(final Context ctx, final ExpressionNode node, Conte } } - for (final ExpressionNode arg : node.args) + for (ExpressionNode arg : node.args) { if (arg.token.type.isConstant()) { @@ -1425,13 +1425,13 @@ private boolean optimizeTree(final Context ctx, final ExpressionNode node, Conte expectedType = Context.Type.NONE; } List args = new ArrayList<>(node.args.size()); - for (final ExpressionNode arg : node.args) + for (ExpressionNode arg : node.args) { try { if (arg.op instanceof LazyValue.Constant) { - final Value val = ((LazyValue.Constant) arg.op).get(); + Value val = ((LazyValue.Constant) arg.op).get(); args.add((c, t) -> val); } else @@ -1439,14 +1439,14 @@ private boolean optimizeTree(final Context ctx, final ExpressionNode node, Conte args.add((c, t) -> arg.op.evalValue(ctx, requestedType)); } } - catch (final NullPointerException npe) + catch (NullPointerException npe) { throw new ExpressionException(ctx, this, node.token, "Attempted to evaluate context free expression"); } } // applying argument unpacking args = AbstractLazyFunction.lazify(AbstractLazyFunction.unpackLazy(args, ctx, requestedType)); - final Value result; + Value result; if (operation instanceof ILazyFunction) { result = ((ILazyFunction) operation).lazyEval(ctx, expectedType, this, node.token, args).evalValue(null, expectedType); @@ -1467,48 +1467,48 @@ else if (args.size() == 1) return true; } - private LazyValue extractOp(final Context ctx, final ExpressionNode node, final Context.Type expectedType) + private LazyValue extractOp(Context ctx, ExpressionNode node, Context.Type expectedType) { if (node.op instanceof LazyValue.Constant) { // constants are immutable if (node.token.type.isConstant()) { - final Value value = ((LazyValue.Constant) node.op).get(); + Value value = ((LazyValue.Constant) node.op).get(); return (c, t) -> value; } return node.op; } if (node.op instanceof LazyValue.ContextFreeLazyValue) { - final Value ret = ((LazyValue.ContextFreeLazyValue) node.op).evalType(expectedType); + Value ret = ((LazyValue.ContextFreeLazyValue) node.op).evalType(expectedType); return (c, t) -> ret; } - final Tokenizer.Token token = node.token; + Tokenizer.Token token = node.token; switch (token.type) { case UNARY_OPERATOR: { - final ILazyOperator op = operators.get(token.surface); - final Context.Type requestedType = op.staticType(expectedType); - final LazyValue arg = extractOp(ctx, node.args.get(0), requestedType); + ILazyOperator op = operators.get(token.surface); + Context.Type requestedType = op.staticType(expectedType); + LazyValue arg = extractOp(ctx, node.args.get(0), requestedType); return (c, t) -> op.lazyEval(c, t, this, token, arg, null).evalValue(c, t); } case OPERATOR: { - final ILazyOperator op = operators.get(token.surface); - final Context.Type requestedType = op.staticType(expectedType); - final LazyValue arg = extractOp(ctx, node.args.get(0), requestedType); - final LazyValue arh = extractOp(ctx, node.args.get(1), requestedType); + ILazyOperator op = operators.get(token.surface); + Context.Type requestedType = op.staticType(expectedType); + LazyValue arg = extractOp(ctx, node.args.get(0), requestedType); + LazyValue arh = extractOp(ctx, node.args.get(1), requestedType); return (c, t) -> op.lazyEval(c, t, this, token, arg, arh).evalValue(c, t); } case VARIABLE: return (c, t) -> getOrSetAnyVariable(c, token.surface).evalValue(c, t); case FUNCTION: { - final ILazyFunction f = functions.get(token.surface); - final Context.Type requestedType = f.staticType(expectedType); - final List params = node.args.stream().map(n -> extractOp(ctx, n, requestedType)).collect(Collectors.toList()); + ILazyFunction f = functions.get(token.surface); + Context.Type requestedType = f.staticType(expectedType); + List params = node.args.stream().map(n -> extractOp(ctx, n, requestedType)).collect(Collectors.toList()); return (c, t) -> f.lazyEval(c, t, this, token, params).evalValue(c, t); } case CONSTANT: @@ -1519,7 +1519,7 @@ private LazyValue extractOp(final Context ctx, final ExpressionNode node, final } } - private void validate(final Context c, final List rpn) + private void validate(Context c, List rpn) { /*- * Thanks to Norman Ramsey: @@ -1529,12 +1529,12 @@ private void validate(final Context c, final List rpn) // each // layer on the stack being the count of the number of parameters in // that scope - final IntArrayList stack = new IntArrayList(); // IntArrayList instead of just IntStack because we need to query the size + IntArrayList stack = new IntArrayList(); // IntArrayList instead of just IntStack because we need to query the size // push the 'global' scope stack.push(0); - for (final Tokenizer.Token token : rpn) + for (Tokenizer.Token token : rpn) { switch (token.type) { diff --git a/src/main/java/carpet/script/Fluff.java b/src/main/java/carpet/script/Fluff.java index b0fc240ec3..0ab2e11deb 100644 --- a/src/main/java/carpet/script/Fluff.java +++ b/src/main/java/carpet/script/Fluff.java @@ -57,7 +57,7 @@ public interface EvalNode /** * @return required argument eval type in case its evaluated statically without context but with a given context type */ - default Context.Type staticType(final Context.Type outerType) + default Context.Type staticType(Context.Type outerType) { return transitive() ? outerType : Context.NONE; } @@ -106,7 +106,7 @@ public abstract static class AbstractLazyFunction implements ILazyFunction protected String name; int numParams; - public AbstractLazyFunction(final int numParams, final String name) + public AbstractLazyFunction(int numParams, String name) { super(); this.numParams = numParams; @@ -131,12 +131,12 @@ public boolean numParamsVaries() return numParams < 0; } - public static List unpackLazy(final List lzargs, final Context c, final Context.Type contextType) + public static List unpackLazy(List lzargs, Context c, Context.Type contextType) { - final List args = new ArrayList<>(); - for (final LazyValue lv : lzargs) + List args = new ArrayList<>(); + for (LazyValue lv : lzargs) { - final Value arg = lv.evalValue(c, contextType); + Value arg = lv.evalValue(c, contextType); if (arg instanceof FunctionUnpackedArgumentsValue) { args.addAll(((ListValue) arg).getItems()); @@ -149,9 +149,9 @@ public static List unpackLazy(final List lzargs, final Context return args; } - public List unpackArgs(final List lzargs, final Context c, final Context.Type contextType) + public List unpackArgs(List lzargs, Context c, Context.Type contextType) { - final List args = unpackLazy(lzargs, c, contextType); + List args = unpackLazy(lzargs, c, contextType); if (!numParamsVaries() && getNumParams() != args.size()) { throw new InternalExpressionException("Function " + getName() + " expected " + getNumParams() + " parameters, got " + args.size()); @@ -159,9 +159,9 @@ public List unpackArgs(final List lzargs, final Context c, fin return args; } - public static List lazify(final List args) + public static List lazify(List args) { - final List lzargs = new ArrayList<>(args.size()); + List lzargs = new ArrayList<>(args.size()); args.forEach(v -> lzargs.add((c, t) -> v)); return lzargs; } @@ -169,7 +169,7 @@ public static List lazify(final List args) public abstract static class AbstractFunction extends AbstractLazyFunction implements IFunction { - AbstractFunction(final int numParams, final String name) + AbstractFunction(int numParams, String name) { super(numParams, name); } @@ -187,7 +187,7 @@ public boolean transitive() } @Override - public LazyValue lazyEval(final Context cc, final Context.Type type, final Expression e, final Tokenizer.Token t, final List lazyParams) + public LazyValue lazyEval(Context cc, Context.Type type, Expression e, Tokenizer.Token t, List lazyParams) { return new LazyValue() @@ -195,20 +195,20 @@ public LazyValue lazyEval(final Context cc, final Context.Type type, final Expre private List params; @Override - public Value evalValue(final Context c, final Context.Type type) + public Value evalValue(Context c, Context.Type type) { ILazyFunction.checkInterrupts(); try { return AbstractFunction.this.eval(getParams(c)); } - catch (final RuntimeException exc) + catch (RuntimeException exc) { throw Expression.handleCodeException(cc, exc, e, t); } } - private List getParams(final Context c) + private List getParams(Context c) { if (params == null) { @@ -231,7 +231,7 @@ public abstract static class AbstractLazyOperator implements ILazyOperator boolean leftAssoc; - AbstractLazyOperator(final int precedence, final boolean leftAssoc) + AbstractLazyOperator(int precedence, boolean leftAssoc) { super(); this.precedence = precedence; @@ -255,7 +255,7 @@ public boolean isLeftAssoc() public abstract static class AbstractOperator extends AbstractLazyOperator implements IOperator { - AbstractOperator(final int precedence, final boolean leftAssoc) + AbstractOperator(int precedence, boolean leftAssoc) { super(precedence, leftAssoc); } @@ -273,14 +273,14 @@ public boolean transitive() } @Override - public LazyValue lazyEval(final Context cc, final Context.Type type, final Expression e, final Tokenizer.Token t, final LazyValue v1, final LazyValue v2) + public LazyValue lazyEval(Context cc, Context.Type type, Expression e, Tokenizer.Token t, LazyValue v1, LazyValue v2) { return (c, typeIgnored) -> { try { return AbstractOperator.this.eval(v1.evalValue(c, Context.Type.NONE), v2.evalValue(c, Context.Type.NONE)); } - catch (final RuntimeException exc) + catch (RuntimeException exc) { throw Expression.handleCodeException(cc, exc, e, t); } @@ -290,7 +290,7 @@ public LazyValue lazyEval(final Context cc, final Context.Type type, final Expre public abstract static class AbstractUnaryOperator extends AbstractOperator { - AbstractUnaryOperator(final int precedence, final boolean leftAssoc) + AbstractUnaryOperator(int precedence, boolean leftAssoc) { super(precedence, leftAssoc); } @@ -308,7 +308,7 @@ public boolean transitive() } @Override - public LazyValue lazyEval(final Context cc, final Context.Type type, final Expression e, final Tokenizer.Token t, final LazyValue v1, final LazyValue v2) + public LazyValue lazyEval(Context cc, Context.Type type, Expression e, Tokenizer.Token t, LazyValue v1, LazyValue v2) { if (v2 != null) { @@ -319,7 +319,7 @@ public LazyValue lazyEval(final Context cc, final Context.Type type, final Expre { return AbstractUnaryOperator.this.evalUnary(v1.evalValue(c, Context.Type.NONE)); } - catch (final RuntimeException exc) + catch (RuntimeException exc) { throw Expression.handleCodeException(cc, exc, e, t); } @@ -327,7 +327,7 @@ public LazyValue lazyEval(final Context cc, final Context.Type type, final Expre } @Override - public Value eval(final Value v1, final Value v2) + public Value eval(Value v1, Value v2) { throw new IllegalStateException("Shouldn't end up here"); } diff --git a/src/main/java/carpet/script/LazyValue.java b/src/main/java/carpet/script/LazyValue.java index 88713d0880..ab616a6975 100644 --- a/src/main/java/carpet/script/LazyValue.java +++ b/src/main/java/carpet/script/LazyValue.java @@ -13,14 +13,14 @@ public interface LazyValue LazyValue NULL = (c, t) -> Value.NULL; LazyValue ZERO = (c, t) -> Value.ZERO; - static LazyValue ofConstant(final Value val) + static LazyValue ofConstant(Value val) { return new Constant(val); } Value evalValue(Context c, Context.Type type); - default Value evalValue(final Context c) + default Value evalValue(Context c) { return evalValue(c, Context.Type.NONE); } @@ -32,7 +32,7 @@ interface ContextFreeLazyValue extends LazyValue Value evalType(Context.Type type); @Override - default Value evalValue(final Context c, final Context.Type type) + default Value evalValue(Context c, Context.Type type) { return evalType(type); } @@ -43,7 +43,7 @@ class Constant implements ContextFreeLazyValue { Value result; - public Constant(final Value value) + public Constant(Value value) { result = value; } @@ -54,14 +54,14 @@ public Value get() } @Override - public Value evalType(final Context.Type type) + public Value evalType(Context.Type type) { return result.fromConstant(); } @Override - public Value evalValue(final Context c, final Context.Type type) + public Value evalValue(Context c, Context.Type type) { return result.fromConstant(); } diff --git a/src/main/java/carpet/script/Module.java b/src/main/java/carpet/script/Module.java index 9eff564775..30264e6b0c 100644 --- a/src/main/java/carpet/script/Module.java +++ b/src/main/java/carpet/script/Module.java @@ -20,16 +20,16 @@ public record Module(String name, String code, boolean library) Objects.requireNonNull(code); } - public static Module fromPath(final Path path) + public static Module fromPath(Path path) { - final boolean library = path.getFileName().toString().endsWith(".scl"); + boolean library = path.getFileName().toString().endsWith(".scl"); try { - final String name = path.getFileName().toString().replaceFirst("\\.scl?", "").toLowerCase(Locale.ROOT); - final String code = new String(Files.readAllBytes(path), StandardCharsets.UTF_8); + String name = path.getFileName().toString().replaceFirst("\\.scl?", "").toLowerCase(Locale.ROOT); + String code = new String(Files.readAllBytes(path), StandardCharsets.UTF_8); return new Module(name, code, library); } - catch (final IOException e) + catch (IOException e) { throw new IllegalArgumentException("Failed to load scarpet module", e); } @@ -42,7 +42,7 @@ public static Module fromPath(final Path path) * @param isLibrary A {@link boolean} indicating whether or not the script is a library * @return The created {@link BundledModule} */ - public static Module carpetNative(final String scriptName, final boolean isLibrary) + public static Module carpetNative(String scriptName, boolean isLibrary) { return fromJarPath("assets/carpet/scripts/", scriptName, isLibrary); } @@ -56,7 +56,7 @@ public static Module carpetNative(final String scriptName, final boolean isLibra * @return The created {@link BundledModule} * @see #fromJarPathWithCustomName(String, String, boolean) */ - public static Module fromJarPath(final String path, final String scriptName, final boolean isLibrary) + public static Module fromJarPath(String path, String scriptName, boolean isLibrary) { return fromJarPathWithCustomName(path + scriptName + (isLibrary ? ".scl" : ".sc"), scriptName, isLibrary); } @@ -70,26 +70,26 @@ public static Module fromJarPath(final String path, final String scriptName, fin * @return The created {@link Module} * @see #fromJarPath(String, String, boolean) */ - public static Module fromJarPathWithCustomName(final String fullPath, final String customName, final boolean isLibrary) + public static Module fromJarPathWithCustomName(String fullPath, String customName, boolean isLibrary) { try { - final String name = customName.toLowerCase(Locale.ROOT); - final String code = IOUtils.toString( + String name = customName.toLowerCase(Locale.ROOT); + String code = IOUtils.toString( Module.class.getClassLoader().getResourceAsStream(fullPath), StandardCharsets.UTF_8 ); return new Module(name, code, isLibrary); } - catch (final IOException e) + catch (IOException e) { throw new IllegalArgumentException("Failed to load bundled module", e); } } - public static Tag getData(final Module module, final ScriptServer scriptServer) + public static Tag getData(Module module, ScriptServer scriptServer) { - final Path dataFile = resolveResource(module, scriptServer); + Path dataFile = resolveResource(module, scriptServer); if (dataFile == null || !Files.exists(dataFile) || !(Files.isRegularFile(dataFile))) { return null; @@ -100,9 +100,9 @@ public static Tag getData(final Module module, final ScriptServer scriptServer) } } - public static void saveData(final Module module, final Tag globalState, final ScriptServer scriptServer) + public static void saveData(Module module, Tag globalState, ScriptServer scriptServer) { - final Path dataFile = resolveResource(module, scriptServer); + Path dataFile = resolveResource(module, scriptServer); if (dataFile == null) { return; @@ -113,7 +113,7 @@ public static void saveData(final Module module, final Tag globalState, final Sc { Files.createDirectories(dataFile.getParent()); } - catch (final IOException e) + catch (IOException e) { throw new IllegalStateException(e); } @@ -124,7 +124,7 @@ public static void saveData(final Module module, final Tag globalState, final Sc } } - private static Path resolveResource(final Module module, final ScriptServer scriptServer) + private static Path resolveResource(Module module, ScriptServer scriptServer) { return module == null ? null : scriptServer.resolveResource(module.name() + ".data.nbt"); } diff --git a/src/main/java/carpet/script/ScriptCommand.java b/src/main/java/carpet/script/ScriptCommand.java index 6f9d2256d6..b9bd17b1f2 100644 --- a/src/main/java/carpet/script/ScriptCommand.java +++ b/src/main/java/carpet/script/ScriptCommand.java @@ -53,22 +53,22 @@ public class ScriptCommand static { - final Set allFunctions = (new CarpetExpression(null, "null", null, null)).getExpr().getFunctionNames(); + Set allFunctions = (new CarpetExpression(null, "null", null, null)).getExpr().getFunctionNames(); scarpetFunctions = new TreeSet<>(Expression.none.getFunctionNames()); APIFunctions = allFunctions.stream().filter(s -> !scarpetFunctions.contains(s)).collect(Collectors.toCollection(TreeSet::new)); } - public static List suggestFunctions(final ScriptHost host, String previous, final String prefix) + public static List suggestFunctions(ScriptHost host, String previous, String prefix) { previous = previous.replace("\\'", ""); - final int quoteCount = StringUtils.countMatches(previous, '\''); + int quoteCount = StringUtils.countMatches(previous, '\''); if (quoteCount % 2 == 1) { return Collections.emptyList(); } - final int maxLen = prefix.length() < 3 ? (prefix.length() * 2 + 1) : 1234; - final String eventPrefix = prefix.startsWith("__on_") ? prefix.substring(5) : null; - final List scarpetMatches = scarpetFunctions.stream(). + int maxLen = prefix.length() < 3 ? (prefix.length() * 2 + 1) : 1234; + String eventPrefix = prefix.startsWith("__on_") ? prefix.substring(5) : null; + List scarpetMatches = scarpetFunctions.stream(). filter(s -> s.startsWith(prefix) && s.length() <= maxLen).map(s -> s + "(").collect(Collectors.toList()); scarpetMatches.addAll(APIFunctions.stream(). filter(s -> s.startsWith(prefix) && s.length() <= maxLen).map(s -> s + "(").toList()); @@ -84,17 +84,17 @@ public static List suggestFunctions(final ScriptHost host, String previo } private static CompletableFuture suggestCode( - final CommandContext context, - final SuggestionsBuilder suggestionsBuilder + CommandContext context, + SuggestionsBuilder suggestionsBuilder ) throws CommandSyntaxException { - final CarpetScriptHost currentHost = getHost(context); - final String previous = suggestionsBuilder.getRemaining(); - final int strlen = previous.length(); - final StringBuilder lastToken = new StringBuilder(); + CarpetScriptHost currentHost = getHost(context); + String previous = suggestionsBuilder.getRemaining(); + int strlen = previous.length(); + StringBuilder lastToken = new StringBuilder(); for (int idx = strlen - 1; idx >= 0; idx--) { - final char ch = previous.charAt(idx); + char ch = previous.charAt(idx); if (Character.isLetterOrDigit(ch) || ch == '_') { lastToken.append(ch); @@ -108,8 +108,8 @@ private static CompletableFuture suggestCode( { return suggestionsBuilder.buildFuture(); } - final String prefix = lastToken.reverse().toString(); - final String previousString = previous.substring(0, previous.length() - prefix.length()); + String prefix = lastToken.reverse().toString(); + String previousString = previous.substring(0, previous.length() - prefix.length()); suggestFunctions(currentHost, previousString, prefix).forEach(text -> suggestionsBuilder.suggest(previousString + text)); return suggestionsBuilder.buildFuture(); } @@ -119,18 +119,18 @@ private static CompletableFuture suggestCode( * variable. */ private static CompletableFuture suggestDownloadableApps( - final CommandContext context, - final SuggestionsBuilder suggestionsBuilder + CommandContext context, + SuggestionsBuilder suggestionsBuilder ) throws CommandSyntaxException { return CompletableFuture.supplyAsync(() -> { - final String previous = suggestionsBuilder.getRemaining(); + String previous = suggestionsBuilder.getRemaining(); try { AppStoreManager.suggestionsFromPath(previous).forEach(suggestionsBuilder::suggest); } - catch (final IOException e) + catch (IOException e) { CarpetScriptServer.LOG.warn("Exception when fetching app store structure", e); } @@ -138,33 +138,33 @@ private static CompletableFuture suggestDownloadableApps( }); } - private static CarpetScriptServer ss(final CommandContext context) + private static CarpetScriptServer ss(CommandContext context) { return Vanilla.MinecraftServer_getScriptServer(context.getSource().getServer()); } - public static void register(final CommandDispatcher dispatcher, final CommandBuildContext commandBuildContext) + public static void register(CommandDispatcher dispatcher, CommandBuildContext commandBuildContext) { - final LiteralArgumentBuilder b = literal("globals"). + LiteralArgumentBuilder b = literal("globals"). executes(context -> listGlobals(context, false)). then(literal("all").executes(context -> listGlobals(context, true))); - final LiteralArgumentBuilder o = literal("stop"). + LiteralArgumentBuilder o = literal("stop"). executes((cc) -> { ss(cc).stopAll = true; return 1; }); - final LiteralArgumentBuilder u = literal("resume"). + LiteralArgumentBuilder u = literal("resume"). executes((cc) -> { ss(cc).stopAll = false; return 1; }); - final LiteralArgumentBuilder l = literal("run"). + LiteralArgumentBuilder l = literal("run"). requires(Vanilla::ServerPlayer_canScriptACE). then(argument("expr", StringArgumentType.greedyString()).suggests(ScriptCommand::suggestCode). executes((cc) -> compute( cc, StringArgumentType.getString(cc, "expr")))); - final LiteralArgumentBuilder s = literal("invoke"). + LiteralArgumentBuilder s = literal("invoke"). then(argument("call", StringArgumentType.word()).suggests((cc, bb) -> suggest(suggestFunctionCalls(cc), bb)). executes((cc) -> invoke( cc, @@ -181,7 +181,7 @@ public static void register(final CommandDispatcher dispatch null, StringArgumentType.getString(cc, "arguments") )))); - final LiteralArgumentBuilder c = literal("invokepoint"). + LiteralArgumentBuilder c = literal("invokepoint"). then(argument("call", StringArgumentType.word()).suggests((cc, bb) -> suggest(suggestFunctionCalls(cc), bb)). then(argument("origin", BlockPosArgument.blockPos()). executes((cc) -> invoke( @@ -199,7 +199,7 @@ public static void register(final CommandDispatcher dispatch null, StringArgumentType.getString(cc, "arguments") ))))); - final LiteralArgumentBuilder h = literal("invokearea"). + LiteralArgumentBuilder h = literal("invokearea"). then(argument("call", StringArgumentType.word()).suggests((cc, bb) -> suggest(suggestFunctionCalls(cc), bb)). then(argument("from", BlockPosArgument.blockPos()). then(argument("to", BlockPosArgument.blockPos()). @@ -218,7 +218,7 @@ public static void register(final CommandDispatcher dispatch BlockPosArgument.getSpawnablePos(cc, "to"), StringArgumentType.getString(cc, "arguments") )))))); - final LiteralArgumentBuilder i = literal("scan").requires((player) -> player.hasPermission(2)). + LiteralArgumentBuilder i = literal("scan").requires((player) -> player.hasPermission(2)). then(argument("origin", BlockPosArgument.blockPos()). then(argument("from", BlockPosArgument.blockPos()). then(argument("to", BlockPosArgument.blockPos()). @@ -231,7 +231,7 @@ public static void register(final CommandDispatcher dispatch BlockPosArgument.getSpawnablePos(cc, "to"), StringArgumentType.getString(cc, "expr") )))))); - final LiteralArgumentBuilder e = literal("fill").requires((player) -> player.hasPermission(2)). + LiteralArgumentBuilder e = literal("fill").requires((player) -> player.hasPermission(2)). then(argument("origin", BlockPosArgument.blockPos()). then(argument("from", BlockPosArgument.blockPos()). then(argument("to", BlockPosArgument.blockPos()). @@ -258,7 +258,7 @@ public static void register(final CommandDispatcher dispatch BlockPredicateArgument.getBlockPredicate(cc, "filter"), "solid" ))))))))); - final LiteralArgumentBuilder t = literal("outline").requires((player) -> player.hasPermission(2)). + LiteralArgumentBuilder t = literal("outline").requires((player) -> player.hasPermission(2)). then(argument("origin", BlockPosArgument.blockPos()). then(argument("from", BlockPosArgument.blockPos()). then(argument("to", BlockPosArgument.blockPos()). @@ -285,33 +285,33 @@ public static void register(final CommandDispatcher dispatch BlockPredicateArgument.getBlockPredicate(cc, "filter"), "outline" ))))))))); - final LiteralArgumentBuilder a = literal("load").requires(Vanilla::ServerPlayer_canScriptACE). + LiteralArgumentBuilder a = literal("load").requires(Vanilla::ServerPlayer_canScriptACE). then(argument("app", StringArgumentType.word()). suggests((cc, bb) -> suggest(ss(cc).listAvailableModules(true), bb)). executes((cc) -> { - final boolean success = ss(cc).addScriptHost(cc.getSource(), StringArgumentType.getString(cc, "app"), null, true, false, false, null); + boolean success = ss(cc).addScriptHost(cc.getSource(), StringArgumentType.getString(cc, "app"), null, true, false, false, null); return success ? 1 : 0; }). then(literal("global"). executes((cc) -> { - final boolean success = ss(cc).addScriptHost(cc.getSource(), StringArgumentType.getString(cc, "app"), null, false, false, false, null); + boolean success = ss(cc).addScriptHost(cc.getSource(), StringArgumentType.getString(cc, "app"), null, false, false, false, null); return success ? 1 : 0; } ) ) ); - final LiteralArgumentBuilder f = literal("unload").requires(Vanilla::ServerPlayer_canScriptACE). + LiteralArgumentBuilder f = literal("unload").requires(Vanilla::ServerPlayer_canScriptACE). then(argument("app", StringArgumentType.word()). suggests((cc, bb) -> suggest(ss(cc).unloadableModules, bb)). executes((cc) -> { - final boolean success = ss(cc).removeScriptHost(cc.getSource(), StringArgumentType.getString(cc, "app"), true, false); + boolean success = ss(cc).removeScriptHost(cc.getSource(), StringArgumentType.getString(cc, "app"), true, false); return success ? 1 : 0; })); - final LiteralArgumentBuilder q = literal("event").requires(Vanilla::ServerPlayer_canScriptACE). + LiteralArgumentBuilder q = literal("event").requires(Vanilla::ServerPlayer_canScriptACE). executes(ScriptCommand::listEvents). then(literal("add_to"). then(argument("event", StringArgumentType.word()). @@ -346,16 +346,16 @@ public static void register(final CommandDispatcher dispatch StringArgumentType.getString(cc, "call") ) ? 1 : 0)))); - final LiteralArgumentBuilder d = literal("download").requires(Vanilla::ServerPlayer_canScriptACE). + LiteralArgumentBuilder d = literal("download").requires(Vanilla::ServerPlayer_canScriptACE). then(argument("path", StringArgumentType.greedyString()). suggests(ScriptCommand::suggestDownloadableApps). executes(cc -> AppStoreManager.downloadScript(cc.getSource(), StringArgumentType.getString(cc, "path")))); - final LiteralArgumentBuilder r = literal("remove").requires(Vanilla::ServerPlayer_canScriptACE). + LiteralArgumentBuilder r = literal("remove").requires(Vanilla::ServerPlayer_canScriptACE). then(argument("app", StringArgumentType.word()). suggests((cc, bb) -> suggest(ss(cc).unloadableModules, bb)). executes((cc) -> { - final boolean success = ss(cc).uninstallApp(cc.getSource(), StringArgumentType.getString(cc, "app")); + boolean success = ss(cc).uninstallApp(cc.getSource(), StringArgumentType.getString(cc, "app")); return success ? 1 : 0; })); @@ -370,17 +370,17 @@ public static void register(final CommandDispatcher dispatch then(b).then(u).then(o).then(l).then(s).then(c).then(h).then(i).then(e).then(t)))); } - private static CarpetScriptHost getHost(final CommandContext context) throws CommandSyntaxException + private static CarpetScriptHost getHost(CommandContext context) throws CommandSyntaxException { CarpetScriptHost host; - final CarpetScriptServer scriptServer = ss(context); + CarpetScriptServer scriptServer = ss(context); try { - final String name = StringArgumentType.getString(context, "app").toLowerCase(Locale.ROOT); - final CarpetScriptHost parentHost = scriptServer.modules.getOrDefault(name, scriptServer.globalHost); + String name = StringArgumentType.getString(context, "app").toLowerCase(Locale.ROOT); + CarpetScriptHost parentHost = scriptServer.modules.getOrDefault(name, scriptServer.globalHost); host = parentHost.retrieveOwnForExecution(context.getSource()); } - catch (final IllegalArgumentException ignored) + catch (IllegalArgumentException ignored) { host = scriptServer.globalHost; } @@ -388,21 +388,21 @@ private static CarpetScriptHost getHost(final CommandContext return host; } - private static Collection suggestFunctionCalls(final CommandContext c) throws CommandSyntaxException + private static Collection suggestFunctionCalls(CommandContext c) throws CommandSyntaxException { - final CarpetScriptHost host = getHost(c); + CarpetScriptHost host = getHost(c); return host.globalFunctionNames(host.main, s -> !s.startsWith("_")).sorted().collect(Collectors.toList()); } - private static int listEvents(final CommandContext context) + private static int listEvents(CommandContext context) { CarpetScriptServer scriptServer = ss(context); CommandSourceStack source = context.getSource(); Carpet.Messenger_message(source, "w Lists ALL event handlers:"); - for (final CarpetEventServer.Event event : CarpetEventServer.Event.getAllEvents(scriptServer, null)) + for (CarpetEventServer.Event event : CarpetEventServer.Event.getAllEvents(scriptServer, null)) { boolean shownEvent = false; - for (final CarpetEventServer.Callback c : event.handler.inspectCurrentCalls()) + for (CarpetEventServer.Callback c : event.handler.inspectCurrentCalls()) { if (!shownEvent) { @@ -415,26 +415,26 @@ private static int listEvents(final CommandContext context) return 1; } - private static int listGlobals(final CommandContext context, final boolean all) throws CommandSyntaxException + private static int listGlobals(CommandContext context, boolean all) throws CommandSyntaxException { - final CarpetScriptHost host = getHost(context); - final CommandSourceStack source = context.getSource(); - final CarpetScriptServer scriptServer = ss(context); + CarpetScriptHost host = getHost(context); + CommandSourceStack source = context.getSource(); + CarpetScriptServer scriptServer = ss(context); Carpet.Messenger_message(source, "lb Stored functions" + ((host == scriptServer.globalHost) ? ":" : " in " + host.getName() + ":")); host.globalFunctionNames(host.main, (str) -> all || !str.startsWith("__")).sorted().forEach((s) -> { - final FunctionValue fun = host.getFunction(s); + FunctionValue fun = host.getFunction(s); if (fun == null) { Carpet.Messenger_message(source, "gb " + s, "g - unused import"); Carpet.Messenger_message(source, "gi ----------------"); return; } - final Expression expr = fun.getExpression(); - final Tokenizer.Token tok = fun.getToken(); - final List snippet = expr.getExpressionSnippet(tok); + Expression expr = fun.getExpression(); + Tokenizer.Token tok = fun.getToken(); + List snippet = expr.getExpressionSnippet(tok); Carpet.Messenger_message(source, "wb " + fun.fullName(), "t defined at: line " + (tok.lineno + 1) + " pos " + (tok.linepos + 1)); - for (final String snippetLine : snippet) + for (String snippetLine : snippet) { Carpet.Messenger_message(source, "w " + snippetLine); } @@ -444,7 +444,7 @@ private static int listGlobals(final CommandContext context, Carpet.Messenger_message(source, "w "); Carpet.Messenger_message(source, "lb Global variables" + ((host == scriptServer.globalHost) ? ":" : " in " + host.getName() + ":")); host.globalVariableNames(host.main, (s) -> s.startsWith("global_")).sorted().forEach((s) -> { - final LazyValue variable = host.getGlobalVariable(s); + LazyValue variable = host.getGlobalVariable(s); if (variable == null) { Carpet.Messenger_message(source, "gb " + s, "g - unused import"); @@ -457,14 +457,14 @@ private static int listGlobals(final CommandContext context, return 1; } - public static int handleCall(final CommandSourceStack source, final CarpetScriptHost host, final Supplier call) + public static int handleCall(CommandSourceStack source, CarpetScriptHost host, Supplier call) { try { - final Runnable token = Carpet.startProfilerSection("Scarpet run"); + Runnable token = Carpet.startProfilerSection("Scarpet run"); host.setChatErrorSnooper(source); - final long start = System.nanoTime(); - final Value result = call.get(); + long start = System.nanoTime(); + Value result = call.get(); long time = ((System.nanoTime() - start) / 1000); String metric = "\u00B5s"; if (time > 5000) @@ -478,19 +478,19 @@ public static int handleCall(final CommandSourceStack source, final CarpetScript metric = "s"; } Carpet.Messenger_message(source, "wi = ", "wb " + result.getString(), "gi (" + time + metric + ")"); - final int intres = (int) result.readInteger(); + int intres = (int) result.readInteger(); token.run(); return intres; } - catch (final CarpetExpressionException e) + catch (CarpetExpressionException e) { host.handleErrorWithStack("Error while evaluating expression", e); } - catch (final ArithmeticException ae) + catch (ArithmeticException ae) { host.handleErrorWithStack("Math doesn't compute", ae); } - catch (final StackOverflowError soe) + catch (StackOverflowError soe) { host.handleErrorWithStack("Your thoughts are too deep", soe); } @@ -498,16 +498,16 @@ public static int handleCall(final CommandSourceStack source, final CarpetScript //host.resetErrorSnooper(); // lets say no need to reset the snooper in case something happens on the way } - private static int invoke(final CommandContext context, final String call, final BlockPos pos1, final BlockPos pos2, final String args) throws CommandSyntaxException + private static int invoke(CommandContext context, String call, BlockPos pos1, BlockPos pos2, String args) throws CommandSyntaxException { - final CommandSourceStack source = context.getSource(); - final CarpetScriptHost host = getHost(context); + CommandSourceStack source = context.getSource(); + CarpetScriptHost host = getHost(context); if (call.startsWith("__")) { Carpet.Messenger_message(source, "r Hidden functions are only callable in scripts"); return 0; } - final List positions = new ArrayList<>(); + List positions = new ArrayList<>(); if (pos1 != null) { positions.add(pos1.getX()); @@ -526,23 +526,23 @@ private static int invoke(final CommandContext context, fina } - private static int compute(final CommandContext context, final String expr) throws CommandSyntaxException + private static int compute(CommandContext context, String expr) throws CommandSyntaxException { - final CommandSourceStack source = context.getSource(); - final CarpetScriptHost host = getHost(context); + CommandSourceStack source = context.getSource(); + CarpetScriptHost host = getHost(context); return handleCall(source, host, () -> { - final CarpetExpression ex = new CarpetExpression(host.main, expr, source, new BlockPos(0, 0, 0)); + CarpetExpression ex = new CarpetExpression(host.main, expr, source, new BlockPos(0, 0, 0)); return ex.scriptRunCommand(host, new BlockPos(source.getPosition())); }); } - private static int scriptScan(final CommandContext context, final BlockPos origin, final BlockPos a, final BlockPos b, final String expr) throws CommandSyntaxException + private static int scriptScan(CommandContext context, BlockPos origin, BlockPos a, BlockPos b, String expr) throws CommandSyntaxException { - final CommandSourceStack source = context.getSource(); - final CarpetScriptHost host = getHost(context); - final BoundingBox area = BoundingBox.fromCorners(a, b); - final CarpetExpression cexpr = new CarpetExpression(host.main, expr, source, origin); - final int int_1 = area.getXSpan() * area.getYSpan() * area.getZSpan(); // X Y Z + CommandSourceStack source = context.getSource(); + CarpetScriptHost host = getHost(context); + BoundingBox area = BoundingBox.fromCorners(a, b); + CarpetExpression cexpr = new CarpetExpression(host.main, expr, source, origin); + int int_1 = area.getXSpan() * area.getYSpan() * area.getZSpan(); // X Y Z if (int_1 > Vanilla.MinecraftServer_getFillLimit(source.getServer()) ) { Carpet.Messenger_message(source, "r too many blocks to evaluate: " + int_1); @@ -565,14 +565,14 @@ private static int scriptScan(final CommandContext context, successCount++; } } - catch (final ArithmeticException ignored) + catch (ArithmeticException ignored) { } } } } } - catch (final CarpetExpressionException exc) + catch (CarpetExpressionException exc) { host.handleErrorWithStack("Error while processing command", exc); return 0; @@ -587,14 +587,14 @@ private static int scriptScan(final CommandContext context, } - private static int scriptFill(final CommandContext context, final BlockPos origin, final BlockPos a, final BlockPos b, final String expr, - final BlockInput block, final Predicate replacement, final String mode) throws CommandSyntaxException + private static int scriptFill(CommandContext context, BlockPos origin, BlockPos a, BlockPos b, String expr, + BlockInput block, Predicate replacement, String mode) throws CommandSyntaxException { - final CommandSourceStack source = context.getSource(); - final CarpetScriptHost host = getHost(context); - final BoundingBox area = BoundingBox.fromCorners(a, b); - final CarpetExpression cexpr = new CarpetExpression(host.main, expr, source, origin); - final int int_1 = area.getXSpan() * area.getYSpan() * area.getZSpan(); + CommandSourceStack source = context.getSource(); + CarpetScriptHost host = getHost(context); + BoundingBox area = BoundingBox.fromCorners(a, b); + CarpetExpression cexpr = new CarpetExpression(host.main, expr, source, origin); + int int_1 = area.getXSpan() * area.getYSpan() * area.getZSpan(); if (int_1 > Vanilla.MinecraftServer_getFillLimit(source.getServer())) { Carpet.Messenger_message(source, "r too many blocks to evaluate: " + int_1); @@ -603,8 +603,8 @@ private static int scriptFill(final CommandContext context, boolean[][][] volume = new boolean[area.getXSpan()][area.getYSpan()][area.getZSpan()]; //X then Y then Z got messedup - final BlockPos.MutableBlockPos mbpos = origin.mutable(); - final ServerLevel world = source.getLevel(); + BlockPos.MutableBlockPos mbpos = origin.mutable(); + ServerLevel world = source.getLevel(); for (int x = area.minX(); x <= area.maxX(); x++) { @@ -619,23 +619,23 @@ private static int scriptFill(final CommandContext context, volume[x - area.minX()][y - area.minY()][z - area.minZ()] = true; } } - catch (final CarpetExpressionException e) + catch (CarpetExpressionException e) { host.handleErrorWithStack("Exception while filling the area", e); return 0; } - catch (final ArithmeticException e) + catch (ArithmeticException e) { } } } } - final int maxx = area.getXSpan() - 1; - final int maxy = area.getYSpan() - 1; - final int maxz = area.getZSpan() - 1; + int maxx = area.getXSpan() - 1; + int maxy = area.getYSpan() - 1; + int maxz = area.getZSpan() - 1; if ("outline".equalsIgnoreCase(mode)) { - final boolean[][][] newVolume = new boolean[area.getXSpan()][area.getYSpan()][area.getZSpan()]; + boolean[][][] newVolume = new boolean[area.getXSpan()][area.getYSpan()][area.getZSpan()]; for (int x = 0; x <= maxx; x++) { for (int y = 0; y <= maxy; y++) @@ -675,7 +675,7 @@ private static int scriptFill(final CommandContext context, if (replacement == null || replacement.test( new BlockInWorld(world, mbpos, true))) { - final BlockEntity tileentity = world.getBlockEntity(mbpos); + BlockEntity tileentity = world.getBlockEntity(mbpos); Clearable.tryClear(tileentity); if (block.place(world, mbpos, 2)) @@ -700,7 +700,7 @@ private static int scriptFill(final CommandContext context, if (volume[x][y][z]) { mbpos.set(x + area.minX(), y + area.minY(), z + area.minZ()); - final Block blokc = world.getBlockState(mbpos).getBlock(); + Block blokc = world.getBlockState(mbpos).getBlock(); world.blockUpdated(mbpos, blokc); } } diff --git a/src/main/java/carpet/script/ScriptHost.java b/src/main/java/carpet/script/ScriptHost.java index 7364eeb4ea..3fbf31216a 100644 --- a/src/main/java/carpet/script/ScriptHost.java +++ b/src/main/java/carpet/script/ScriptHost.java @@ -39,7 +39,7 @@ public abstract class ScriptHost private final Set deprecations = new HashSet<>(); - public Random getRandom(final long aLong) + public Random getRandom(long aLong) { if (randomizers.size() > 65536) { @@ -48,12 +48,12 @@ public Random getRandom(final long aLong) return randomizers.computeIfAbsent(aLong, Random::new); } - public boolean resetRandom(final long aLong) + public boolean resetRandom(long aLong) { return randomizers.remove(aLong) != null; } - public Path resolveScriptFile(final String suffix) + public Path resolveScriptFile(String suffix) { return scriptServer.resolveResource(suffix); } @@ -67,7 +67,7 @@ public static class ModuleData public final Map globalsImports = new Object2ObjectOpenHashMap<>(); // imported global variables string to module public final Map futureImports = new Object2ObjectOpenHashMap<>(); // imports not known before used - public ModuleData(final Module parent, final ModuleData other) + public ModuleData(Module parent, ModuleData other) { super(); // imports are just pointers, but they still point to the wrong modules (point to the parent) @@ -75,14 +75,14 @@ public ModuleData(final Module parent, final ModuleData other) globalFunctions.putAll(other.globalFunctions); other.globalVariables.forEach((key, value) -> { - final Value var = value.evalValue(null); - final Value copy = var.deepcopy(); + Value var = value.evalValue(null); + Value copy = var.deepcopy(); copy.boundVariable = var.boundVariable; globalVariables.put(key, (c, t) -> copy); }); } - public void setImportsBasedOn(final ScriptHost host, final ModuleData other) + public void setImportsBasedOn(ScriptHost host, ModuleData other) { // fixing imports other.functionImports.forEach((name, targetData) -> { @@ -97,7 +97,7 @@ public void setImportsBasedOn(final ScriptHost host, final ModuleData other) } - public ModuleData(final Module parent) + public ModuleData(Module parent) { this.parent = parent; } @@ -126,7 +126,7 @@ public interface ErrorSnooper public ErrorSnooper errorSnooper = null; - protected ScriptHost(final Module code, final ScriptServer scriptServer, final boolean perUser, final ScriptHost parent) + protected ScriptHost(Module code, ScriptServer scriptServer, boolean perUser, ScriptHost parent) { this.parent = parent; this.main = code; @@ -134,30 +134,30 @@ protected ScriptHost(final Module code, final ScriptServer scriptServer, final b this.user = null; this.strict = false; this.scriptServer = scriptServer; - final ModuleData moduleData = new ModuleData(code); + ModuleData moduleData = new ModuleData(code); initializeModuleGlobals(moduleData); this.moduleData.put(code, moduleData); this.modules.put(code == null ? null : code.name(), code); mainThread = Thread.currentThread(); } - void initializeModuleGlobals(final ModuleData md) + void initializeModuleGlobals(ModuleData md) { } - public void importModule(final Context c, final String moduleName) + public void importModule(Context c, String moduleName) { if (modules.containsKey(moduleName.toLowerCase(Locale.ROOT))) { return; // aready imported } - final Module module = getModuleOrLibraryByName(moduleName); + Module module = getModuleOrLibraryByName(moduleName); if (modules.containsKey(module.name())) { return; // aready imported, once again, in case some discrepancies in names? } modules.put(module.name(), module); - final ModuleData data = new ModuleData(module); + ModuleData data = new ModuleData(module); initializeModuleGlobals(data); moduleData.put(module, data); runModuleCode(c, module); @@ -166,20 +166,20 @@ public void importModule(final Context c, final String moduleName) //throw new InternalExpressionException("Failed to import a module "+moduleName); } - public void importNames(final Context c, final Module targetModule, final String sourceModuleName, final List identifiers) + public void importNames(Context c, Module targetModule, String sourceModuleName, List identifiers) { if (!moduleData.containsKey(targetModule)) { throw new InternalExpressionException("Cannot import to module that doesn't exist"); } - final Module source = modules.get(sourceModuleName); - final ModuleData sourceData = moduleData.get(source); - final ModuleData targetData = moduleData.get(targetModule); + Module source = modules.get(sourceModuleName); + ModuleData sourceData = moduleData.get(source); + ModuleData targetData = moduleData.get(targetModule); if (sourceData == null || targetData == null) { throw new InternalExpressionException("Cannot import from module that is not imported"); } - for (final String identifier : identifiers) + for (String identifier : identifiers) { if (sourceData.globalFunctions.containsKey(identifier)) { @@ -196,10 +196,10 @@ else if (sourceData.globalVariables.containsKey(identifier)) } } - public Stream availableImports(final String moduleName) + public Stream availableImports(String moduleName) { - final Module source = modules.get(moduleName); - final ModuleData sourceData = moduleData.get(source); + Module source = modules.get(moduleName); + ModuleData sourceData = moduleData.get(source); if (sourceData == null) { throw new InternalExpressionException("Cannot import from module that is not imported"); @@ -214,14 +214,14 @@ public Stream availableImports(final String moduleName) protected abstract void runModuleCode(Context c, Module module); // this should be shell out in the executor - public FunctionValue getFunction(final String name) + public FunctionValue getFunction(String name) { return getFunction(main, name); } - public FunctionValue getAssertFunction(final Module module, final String name) + public FunctionValue getAssertFunction(Module module, String name) { - final FunctionValue ret = getFunction(module, name); + FunctionValue ret = getFunction(module, name); if (ret == null) { if (module == main) @@ -236,9 +236,9 @@ public FunctionValue getAssertFunction(final Module module, final String name) return ret; } - private FunctionValue getFunction(final Module module, final String name) + private FunctionValue getFunction(Module module, String name) { - final ModuleData local = getModuleData(module); + ModuleData local = getModuleData(module); FunctionValue ret = local.globalFunctions.get(name); // most uses would be from local scope anyways if (ret != null) { @@ -269,7 +269,7 @@ private FunctionValue getFunction(final Module module, final String name) return target.globalFunctions.get(name); } - private ModuleData findModuleDataFromFunctionImports(final String name, final ModuleData source, final int ttl) + private ModuleData findModuleDataFromFunctionImports(String name, ModuleData source, int ttl) { if (ttl > 64) { @@ -290,14 +290,14 @@ private ModuleData findModuleDataFromFunctionImports(final String name, final Mo return null; } - public LazyValue getGlobalVariable(final String name) + public LazyValue getGlobalVariable(String name) { return getGlobalVariable(main, name); } - public LazyValue getGlobalVariable(final Module module, final String name) + public LazyValue getGlobalVariable(Module module, String name) { - final ModuleData local = getModuleData(module); + ModuleData local = getModuleData(module); LazyValue ret = local.globalVariables.get(name); // most uses would be from local scope anyways if (ret != null) { @@ -328,7 +328,7 @@ public LazyValue getGlobalVariable(final Module module, final String name) return target.globalVariables.get(name); } - private ModuleData findModuleDataFromGlobalImports(final String name, final ModuleData source, final int ttl) + private ModuleData findModuleDataFromGlobalImports(String name, ModuleData source, int ttl) { if (ttl > 64) { @@ -349,37 +349,37 @@ private ModuleData findModuleDataFromGlobalImports(final String name, final Modu return null; } - public void delFunctionWithPrefix(final Module module, final String prefix) + public void delFunctionWithPrefix(Module module, String prefix) { - final ModuleData data = getModuleData(module); + ModuleData data = getModuleData(module); data.globalFunctions.entrySet().removeIf(e -> e.getKey().startsWith(prefix)); data.functionImports.entrySet().removeIf(e -> e.getKey().startsWith(prefix)); } - public void delFunction(final Module module, final String funName) + public void delFunction(Module module, String funName) { - final ModuleData data = getModuleData(module); + ModuleData data = getModuleData(module); data.globalFunctions.remove(funName); data.functionImports.remove(funName); } - public void delGlobalVariableWithPrefix(final Module module, final String prefix) + public void delGlobalVariableWithPrefix(Module module, String prefix) { - final ModuleData data = getModuleData(module); + ModuleData data = getModuleData(module); data.globalVariables.entrySet().removeIf(e -> e.getKey().startsWith(prefix)); data.globalsImports.entrySet().removeIf(e -> e.getKey().startsWith(prefix)); } - public void delGlobalVariable(final Module module, final String varName) + public void delGlobalVariable(Module module, String varName) { - final ModuleData data = getModuleData(module); + ModuleData data = getModuleData(module); data.globalFunctions.remove(varName); data.functionImports.remove(varName); } - private ModuleData getModuleData(final Module module) + private ModuleData getModuleData(Module module) { - final ModuleData data = moduleData.get(module); + ModuleData data = moduleData.get(module); if (data == null) { throw new IntegrityException("Module structure changed for the app. Did you reload the app with tasks running?"); @@ -387,22 +387,22 @@ private ModuleData getModuleData(final Module module) return data; } - protected void assertAppIntegrity(final Module module) + protected void assertAppIntegrity(Module module) { getModuleData(module); } - public void addUserDefinedFunction(final Context ctx, final Module module, final String name, final FunctionValue fun) + public void addUserDefinedFunction(Context ctx, Module module, String name, FunctionValue fun) { getModuleData(module).globalFunctions.put(name, fun); } - public void setGlobalVariable(final Module module, final String name, final LazyValue lv) + public void setGlobalVariable(Module module, String name, LazyValue lv) { getModuleData(module).globalVariables.put(name, lv); } - public Stream globalVariableNames(final Module module, final Predicate predicate) + public Stream globalVariableNames(Module module, Predicate predicate) { return Stream.concat(Stream.concat( getModuleData(module).globalVariables.keySet().stream(), @@ -410,7 +410,7 @@ public Stream globalVariableNames(final Module module, final Predicate s.startsWith("global_"))).filter(predicate); } - public Stream globalFunctionNames(final Module module, final Predicate predicate) + public Stream globalFunctionNames(Module module, Predicate predicate) { return Stream.concat(Stream.concat( getModuleData(module).globalFunctions.keySet().stream(), @@ -418,25 +418,25 @@ public Stream globalFunctionNames(final Module module, final Predicate !s.startsWith("global_"))).filter(predicate); } - public ScriptHost retrieveForExecution(final String /*Nullable*/ user) + public ScriptHost retrieveForExecution(String /*Nullable*/ user) { if (!perUser) { return this; } - final ScriptHost oldUserHost = userHosts.get(user); + ScriptHost oldUserHost = userHosts.get(user); if (oldUserHost != null) { return oldUserHost; } - final ScriptHost userHost = this.duplicate(); + ScriptHost userHost = this.duplicate(); userHost.user = user; this.setupUserHost(userHost); userHosts.put(user, userHost); return userHost; } - protected void setupUserHost(final ScriptHost host) + protected void setupUserHost(ScriptHost host) { // adding imports host.modules.putAll(this.modules); @@ -445,19 +445,19 @@ protected void setupUserHost(final ScriptHost host) host.moduleData.forEach((module, data) -> data.setImportsBasedOn(host, this.moduleData.get(data.parent))); } - public synchronized void handleExpressionException(final String msg, final ExpressionException exc) + public synchronized void handleExpressionException(String msg, ExpressionException exc) { System.out.println(msg + ": " + exc); } protected abstract ScriptHost duplicate(); - public Object getLock(final Value name) + public Object getLock(Value name) { return locks.computeIfAbsent(name, n -> new Object()); } - public ThreadPoolExecutor getExecutor(final Value pool) + public ThreadPoolExecutor getExecutor(Value pool) { if (inTermination) { @@ -471,7 +471,7 @@ public int taskCount() return executorServices.values().stream().map(ThreadPoolExecutor::getActiveCount).reduce(0, Integer::sum); } - public int taskCount(final Value pool) + public int taskCount(Value pool) { return executorServices.containsKey(pool) ? executorServices.get(pool).getActiveCount() : 0; } @@ -480,14 +480,14 @@ public void onClose() { inTermination = true; executorServices.values().forEach(ThreadPoolExecutor::shutdown); - for (final ScriptHost uh : userHosts.values()) + for (ScriptHost uh : userHosts.values()) { uh.onClose(); } if (taskCount() > 0) { executorServices.values().forEach(e -> { - final ExecutorService stopper = Executors.newSingleThreadExecutor(); + ExecutorService stopper = Executors.newSingleThreadExecutor(); stopper.submit(() -> { try { @@ -502,7 +502,7 @@ public void onClose() } } } - catch (final InterruptedException ie) + catch (InterruptedException ie) { // (Re-)Cancel if current thread also interrupted e.shutdownNow(); @@ -516,7 +516,7 @@ public void onClose() } } - public void setPerPlayer(final boolean isPerUser) + public void setPerPlayer(boolean isPerUser) { perUser = isPerUser; } @@ -539,7 +539,7 @@ public void resetErrorSnooper() public static final Logger DEPRECATION_LOG = LoggerFactory.getLogger("Scarpet Deprecation Warnings"); - public boolean issueDeprecation(final String feature) + public boolean issueDeprecation(String feature) { if (deprecations.contains(feature)) { diff --git a/src/main/java/carpet/script/ScriptServer.java b/src/main/java/carpet/script/ScriptServer.java index c176c9b00a..a00a7f5b95 100644 --- a/src/main/java/carpet/script/ScriptServer.java +++ b/src/main/java/carpet/script/ScriptServer.java @@ -11,5 +11,5 @@ public abstract class ScriptServer { public final Map systemGlobals = new ConcurrentHashMap<>(); - public abstract Path resolveResource(final String suffix); + public abstract Path resolveResource(String suffix); } diff --git a/src/main/java/carpet/script/Tokenizer.java b/src/main/java/carpet/script/Tokenizer.java index e62d4394ee..90994f0069 100644 --- a/src/main/java/carpet/script/Tokenizer.java +++ b/src/main/java/carpet/script/Tokenizer.java @@ -44,7 +44,7 @@ public class Tokenizer implements Iterator private final Expression expression; private final Context context; - Tokenizer(final Context c, final Expression expr, final String input, final boolean allowComments, final boolean allowNewLineMakers) + Tokenizer(Context c, Expression expr, String input, boolean allowComments, boolean allowNewLineMakers) { this.input = input; this.expression = expr; @@ -55,13 +55,13 @@ public class Tokenizer implements Iterator public List postProcess() { - final Iterable iterable = () -> this; - final List originalTokens = StreamSupport.stream(iterable.spliterator(), false).collect(Collectors.toList()); - final List cleanedTokens = new ArrayList<>(); + Iterable iterable = () -> this; + List originalTokens = StreamSupport.stream(iterable.spliterator(), false).collect(Collectors.toList()); + List cleanedTokens = new ArrayList<>(); Token last = null; while (!originalTokens.isEmpty()) { - final Token current = originalTokens.remove(originalTokens.size() - 1); + Token current = originalTokens.remove(originalTokens.size() - 1); if (current.type == Token.TokenType.MARKER && current.surface.startsWith("//")) { continue; @@ -120,22 +120,22 @@ private char peekNextChar() return (pos < (input.length() - 1)) ? input.charAt(pos + 1) : 0; } - private boolean isHexDigit(final char ch) + private boolean isHexDigit(char ch) { return ch == 'x' || ch == 'X' || (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F'); } - private static boolean isSemicolon(final Token tok) + private static boolean isSemicolon(Token tok) { return (tok.type == Token.TokenType.OPERATOR && tok.surface.equals(";")) || (tok.type == Token.TokenType.UNARY_OPERATOR && tok.surface.equals(";u")); } - public static List simplepass(final String input) + public static List simplepass(String input) { - final Tokenizer tok = new Tokenizer(null, null, input, false, false); - final List res = new ArrayList<>(); + Tokenizer tok = new Tokenizer(null, null, input, false, false); + List res = new ArrayList<>(); while (tok.hasNext()) { res.add(tok.next()); @@ -146,7 +146,7 @@ public static List simplepass(final String input) @Override public Token next() { - final Token token = new Token(); + Token token = new Token(); if (pos >= input.length()) { @@ -208,7 +208,7 @@ else if (ch == '\'') { if (ch == '\\') { - final char nextChar = peekNextChar(); + char nextChar = peekNextChar(); if (nextChar == 'n') { token.append('\n'); @@ -324,8 +324,8 @@ else if (ch == ',') else { String greedyMatch = ""; - final int initialPos = pos; - final int initialLinePos = linepos; + int initialPos = pos; + int initialLinePos = linepos; ch = input.charAt(pos); int validOperatorSeenUntil = -1; while (!Character.isLetter(ch) && !Character.isDigit(ch) && "_".indexOf(ch) < 0 @@ -433,7 +433,7 @@ enum TokenType final boolean functional; final boolean constant; - TokenType(final boolean functional, final boolean constant) + TokenType(boolean functional, boolean constant) { this.functional = functional; this.constant = constant; @@ -457,9 +457,9 @@ public boolean isConstant() public int lineno; public static final Token NONE = new Token(); - public Token morphedInto(final TokenType newType, final String newSurface) + public Token morphedInto(TokenType newType, String newSurface) { - final Token created = new Token(); + Token created = new Token(); created.surface = newSurface; created.type = newType; created.pos = pos; @@ -468,23 +468,23 @@ public Token morphedInto(final TokenType newType, final String newSurface) return created; } - public void morph(final TokenType type, final String s) + public void morph(TokenType type, String s) { this.type = type; this.surface = s; } - public void append(final char c) + public void append(char c) { surface += c; } - public void append(final String s) + public void append(String s) { surface += s; } - public char charAt(final int pos) + public char charAt(int pos) { return surface.charAt(pos); } diff --git a/src/main/java/carpet/script/annotation/AnnotationParser.java b/src/main/java/carpet/script/annotation/AnnotationParser.java index 7251ed75eb..1e98ed67c2 100644 --- a/src/main/java/carpet/script/annotation/AnnotationParser.java +++ b/src/main/java/carpet/script/annotation/AnnotationParser.java @@ -104,10 +104,10 @@ public final class AnnotationParser * @see ScarpetFunction * @param clazz The class to parse */ - public static void parseFunctionClass(final Class clazz) + public static void parseFunctionClass(Class clazz) { // Only try to instantiate or require concrete classes if there are non-static annotated methods - final Supplier instanceSupplier = Suppliers.memoize(() -> { + Supplier instanceSupplier = Suppliers.memoize(() -> { if (Modifier.isAbstract(clazz.getModifiers())) { throw new IllegalArgumentException("Function class must be concrete to support non-static methods! Class: " + clazz.getSimpleName()); @@ -116,14 +116,14 @@ public static void parseFunctionClass(final Class clazz) { return clazz.getConstructor().newInstance(); } - catch (final ReflectiveOperationException e) + catch (ReflectiveOperationException e) { throw new IllegalArgumentException( "Couldn't create instance of given " + clazz + ". This is needed for non-static methods. Make sure default constructor is available", e); } }); - final Method[] methodz = clazz.getDeclaredMethods(); - for (final Method method : methodz) + Method[] methodz = clazz.getDeclaredMethods(); + for (Method method : methodz) { if (!method.isAnnotationPresent(ScarpetFunction.class)) { @@ -135,7 +135,7 @@ public static void parseFunctionClass(final Class clazz) throw new IllegalArgumentException("Annotated method '" + method.getName() +"', provided in '"+clazz+"' must not declare checked exceptions"); } - final ParsedFunction function = new ParsedFunction(method, clazz, instanceSupplier); + ParsedFunction function = new ParsedFunction(method, clazz, instanceSupplier); functionList.add(function); } } @@ -146,9 +146,9 @@ public static void parseFunctionClass(final Class clazz) * * @param expr The expression to add every function to */ - public static void apply(final Expression expr) + public static void apply(Expression expr) { - for (final ParsedFunction function : functionList) + for (ParsedFunction function : functionList) { expr.addLazyFunction(function.name, function.scarpetParamCount, function); } @@ -171,52 +171,52 @@ private static class ParsedFunction implements TriFunction originClass, final Supplier instance) + private ParsedFunction(Method method, Class originClass, Supplier instance) { this.name = method.getName(); this.isMethodVarArgs = method.isVarArgs(); this.methodParamCount = method.getParameterCount(); - final Parameter[] methodParameters = method.getParameters(); + Parameter[] methodParameters = method.getParameters(); this.valueConverters = new ValueConverter[isMethodVarArgs ? methodParamCount - 1 : methodParamCount]; for (int i = 0; i < this.methodParamCount; i++) { - final Parameter param = methodParameters[i]; + Parameter param = methodParameters[i]; if (!isMethodVarArgs || i != this.methodParamCount - 1) // Varargs converter is separate { this.valueConverters[i] = ValueConverter.fromAnnotatedType(param.getAnnotatedType()); } } - final Class originalVarArgsType = isMethodVarArgs ? methodParameters[methodParamCount - 1].getType().getComponentType() : null; + Class originalVarArgsType = isMethodVarArgs ? methodParameters[methodParamCount - 1].getType().getComponentType() : null; this.varArgsType = ClassUtils.primitiveToWrapper(originalVarArgsType); // Primitive array cannot be cast to Obj[] this.primitiveVarArgs = originalVarArgsType != null && originalVarArgsType.isPrimitive(); this.varArgsConverter = isMethodVarArgs ? ValueConverter.fromAnnotatedType(methodParameters[methodParamCount - 1].getAnnotatedType()) : null; - @SuppressWarnings("unchecked") final // Yes. Making a T is not worth + @SuppressWarnings("unchecked") // Yes. Making a T is not worth OutputConverter converter = OutputConverter.get((Class) method.getReturnType()); this.outputConverter = converter; this.isEffectivelyVarArgs = isMethodVarArgs || Arrays.stream(valueConverters).anyMatch(ValueConverter::consumesVariableArgs); this.minParams = Arrays.stream(valueConverters).mapToInt(ValueConverter::valueConsumption).sum(); // Note: In !varargs, this is params - int maxParams = this.minParams; // Unlimited == Integer.MAX_VALUE + int setMaxParams = this.minParams; // Unlimited == Integer.MAX_VALUE if (this.isEffectivelyVarArgs) { - maxParams = method.getAnnotation(ScarpetFunction.class).maxParams(); - if (maxParams == UNDEFINED_PARAMS) + setMaxParams = method.getAnnotation(ScarpetFunction.class).maxParams(); + if (setMaxParams == UNDEFINED_PARAMS) { throw new IllegalArgumentException("No maximum number of params specified for " + name + ", use ScarpetFunction.UNLIMITED_PARAMS for unlimited. " + "Provided in " + originClass); } - if (maxParams == ScarpetFunction.UNLIMITED_PARAMS) + if (setMaxParams == ScarpetFunction.UNLIMITED_PARAMS) { - maxParams = Integer.MAX_VALUE; + setMaxParams = Integer.MAX_VALUE; } - if (maxParams < this.minParams) + if (setMaxParams < this.minParams) { throw new IllegalArgumentException("Provided maximum number of params for " + name + " is smaller than method's param count." + "Provided in " + originClass); } } - this.maxParams = maxParams; + this.maxParams = setMaxParams; // Why MethodHandles? // MethodHandles are blazing fast (in some situations they can even compile to a single invokeVirtual), but slightly complex to work with. @@ -242,9 +242,9 @@ private ParsedFunction(final Method method, final Class originClass, final Su } @Override - public LazyValue apply(final Context context, final Context.Type t, final List lazyValues) + public LazyValue apply(Context context, Context.Type t, List lazyValues) { - final List lv = AbstractLazyFunction.unpackLazy(lazyValues, context, contextType); + List lv = AbstractLazyFunction.unpackLazy(lazyValues, context, contextType); if (isEffectivelyVarArgs) { if (lv.size() < minParams) @@ -258,12 +258,12 @@ public LazyValue apply(final Context context, final Context.Type t, final List lv, final Context context, final Context.Type theLazyT) + private Object[] getMethodParams(List lv, Context context, Context.Type theLazyT) { - final Object[] params = new Object[methodParamCount]; - final ListIterator lvIterator = lv.listIterator(); + Object[] params = new Object[methodParamCount]; + ListIterator lvIterator = lv.listIterator(); - final int regularArgs = isMethodVarArgs ? methodParamCount - 1 : methodParamCount; + int regularArgs = isMethodVarArgs ? methodParamCount - 1 : methodParamCount; for (int i = 0; i < regularArgs; i++) { params[i] = valueConverters[i].checkAndConvert(lvIterator, context, theLazyT); @@ -290,14 +290,14 @@ private Object[] getMethodParams(final List lv, final Context context, fi } if (isMethodVarArgs) { - final int remaining = lv.size() - lvIterator.nextIndex(); - final Object[] varArgs; + int remaining = lv.size() - lvIterator.nextIndex(); + Object[] varArgs; if (varArgsConverter.consumesVariableArgs()) { - final List varArgsList = new ArrayList<>(); // fastutil's is extremely slow in toArray, and we use that + List varArgsList = new ArrayList<>(); // fastutil's is extremely slow in toArray, and we use that while (lvIterator.hasNext()) { - final Object obj = varArgsConverter.checkAndConvert(lvIterator, context, theLazyT); + Object obj = varArgsConverter.checkAndConvert(lvIterator, context, theLazyT); if (obj == null) { throw new InternalExpressionException("Incorrect argument passsed to '" + name + "' function.\n" + getUsage()); @@ -326,7 +326,7 @@ private Object[] getMethodParams(final List lv, final Context context, fi public String getUsage() { // Possibility: More descriptive messages using param.getName()? Would need changing gradle setup to keep those - final StringBuilder builder = new StringBuilder("Usage: '"); + StringBuilder builder = new StringBuilder("Usage: '"); builder.append(name); builder.append('('); builder.append(Arrays.stream(valueConverters).map(ValueConverter::getTypeName).filter(Objects::nonNull).collect(Collectors.joining(", "))); diff --git a/src/main/java/carpet/script/annotation/ListConverter.java b/src/main/java/carpet/script/annotation/ListConverter.java index b2648ff83d..b02d501ffc 100644 --- a/src/main/java/carpet/script/annotation/ListConverter.java +++ b/src/main/java/carpet/script/annotation/ListConverter.java @@ -10,6 +10,8 @@ import carpet.script.value.ListValue; import carpet.script.value.Value; +import javax.annotation.Nullable; + /** *

Converts a given {@link ListValue} into a {@link List} of values converted to {@code }.

* @@ -32,18 +34,20 @@ public String getTypeName() return (allowSingletonCreation ? itemConverter.getTypeName() + " or " : "") + "list of " + itemConverter.getTypeName() + "s"; } + @Nullable @Override - public List convert(final Value value, final Context context) + public List convert(Value value, @Nullable Context context) { return value instanceof ListValue ? convertListValue((ListValue) value, context) : allowSingletonCreation ? convertSingleton(value, context) : null; } - private List convertListValue(final ListValue values, final Context context) + @Nullable + private List convertListValue(ListValue values, @Nullable Context context) { - final List list = new ArrayList<>(values.getItems().size()); - for (final Value value : values) + List list = new ArrayList<>(values.getItems().size()); + for (Value value : values) { - final T converted = itemConverter.convert(value, context); + T converted = itemConverter.convert(value, context); if (converted == null) { return null; @@ -53,9 +57,10 @@ private List convertListValue(final ListValue values, final Context context) return list; } - private List convertSingleton(final Value val, final Context context) + @Nullable + private List convertSingleton(Value val, @Nullable Context context) { - final T converted = itemConverter.convert(val, context); + T converted = itemConverter.convert(val, context); if (converted == null) { return null; @@ -64,7 +69,7 @@ private List convertSingleton(final Value val, final Context context) } - private ListConverter(final AnnotatedType itemType, final boolean allowSingletonCreation) + private ListConverter(AnnotatedType itemType, boolean allowSingletonCreation) { itemConverter = ValueConverter.fromAnnotatedType(itemType); this.allowSingletonCreation = allowSingletonCreation; @@ -84,11 +89,11 @@ private ListConverter(final AnnotatedType itemType, final boolean allowSingleton * @param annotatedType The type to get generics information from * @return A new {@link ListConverter} for the data specified in the {@link AnnotatedType} */ - static ListConverter fromAnnotatedType(final AnnotatedType annotatedType) + static ListConverter fromAnnotatedType(AnnotatedType annotatedType) { - final AnnotatedParameterizedType paramType = (AnnotatedParameterizedType) annotatedType; - final AnnotatedType itemType = paramType.getAnnotatedActualTypeArguments()[0]; - final boolean allowSingletonCreation = annotatedType.isAnnotationPresent(Param.AllowSingleton.class); + AnnotatedParameterizedType paramType = (AnnotatedParameterizedType) annotatedType; + AnnotatedType itemType = paramType.getAnnotatedActualTypeArguments()[0]; + boolean allowSingletonCreation = annotatedType.isAnnotationPresent(Param.AllowSingleton.class); return new ListConverter<>(itemType, allowSingletonCreation); } diff --git a/src/main/java/carpet/script/annotation/Locator.java b/src/main/java/carpet/script/annotation/Locator.java index daf403d6d7..af59274371 100644 --- a/src/main/java/carpet/script/annotation/Locator.java +++ b/src/main/java/carpet/script/annotation/Locator.java @@ -20,6 +20,8 @@ import carpet.script.value.FunctionValue; import carpet.script.value.Value; +import javax.annotation.Nullable; + import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE_USE; import static java.lang.annotation.RetentionPolicy.RUNTIME; @@ -122,7 +124,7 @@ private Locators() super(); } - static ValueConverter fromAnnotatedType(final AnnotatedType annoType, final Class type) + static ValueConverter fromAnnotatedType(AnnotatedType annoType, Class type) { if (annoType.isAnnotationPresent(Block.class)) { @@ -146,7 +148,7 @@ private static class BlockLocator extends AbstractLocator private final boolean anyString; private final boolean optional; - public BlockLocator(final Block annotation, final Class type) + public BlockLocator(Block annotation, Class type) { super(); this.acceptString = annotation.acceptString(); @@ -163,8 +165,9 @@ public BlockLocator(final Block annotation, final Class type) } } + @Nullable @SuppressWarnings("unchecked") - private static java.util.function.Function getReturnFunction(final Class type) + private static java.util.function.Function getReturnFunction(Class type) { if (type == BlockArgument.class) { @@ -192,9 +195,9 @@ public String getTypeName() } @Override - public R checkAndConvert(final Iterator valueIterator, final Context context, final Context.Type theLazyT) + public R checkAndConvert(Iterator valueIterator, Context context, Context.Type theLazyT) { - final BlockArgument locator = BlockArgument.findIn((CarpetContext) context, valueIterator, 0, acceptString, optional, anyString); + BlockArgument locator = BlockArgument.findIn((CarpetContext) context, valueIterator, 0, acceptString, optional, anyString); return returnFunction.apply(locator); } } @@ -205,7 +208,7 @@ private static class Vec3dLocator extends AbstractLocator private final boolean optionalEntity; private final boolean returnVec3d; - public Vec3dLocator(final Vec3d annotation, final Class type) + public Vec3dLocator(Vec3d annotation, Class type) { this.optionalDirection = annotation.optionalDirection(); this.optionalEntity = annotation.optionalEntity(); @@ -227,10 +230,10 @@ public String getTypeName() } @Override - public R checkAndConvert(final Iterator valueIterator, final Context context, final Context.Type theLazyT) + public R checkAndConvert(Iterator valueIterator, Context context, Context.Type theLazyT) { - final Vector3Argument locator = Vector3Argument.findIn(valueIterator, 0, optionalDirection, optionalEntity); - @SuppressWarnings("unchecked") final R ret = (R) (returnVec3d ? locator.vec : locator); + Vector3Argument locator = Vector3Argument.findIn(valueIterator, 0, optionalDirection, optionalEntity); + @SuppressWarnings("unchecked") R ret = (R) (returnVec3d ? locator.vec : locator); return ret; } } @@ -241,7 +244,7 @@ private static class FunctionLocator extends AbstractLocator private final boolean allowNone; private final boolean checkArgs; - FunctionLocator(final Function annotation, final Class type) + FunctionLocator(Function annotation, Class type) { super(); this.returnFunctionValue = type == FunctionValue.class; @@ -258,11 +261,11 @@ private static class FunctionLocator extends AbstractLocator } @Override - public R checkAndConvert(final Iterator valueIterator, final Context context, final Context.Type theLazyT) + public R checkAndConvert(Iterator valueIterator, Context context, Context.Type theLazyT) { - final Module module = context.host.main; - final FunctionArgument locator = FunctionArgument.findIn(context, module, Lists.newArrayList(valueIterator), 0, allowNone, checkArgs); - @SuppressWarnings("unchecked") final R ret = (R) (returnFunctionValue ? locator.function : locator); + Module module = context.host.main; + FunctionArgument locator = FunctionArgument.findIn(context, module, Lists.newArrayList(valueIterator), 0, allowNone, checkArgs); + @SuppressWarnings("unchecked") R ret = (R) (returnFunctionValue ? locator.function : locator); return ret; } @@ -276,7 +279,7 @@ public String getTypeName() private abstract static class AbstractLocator implements ValueConverter, Locator { @Override - public R convert(final Value value, final Context context) + public R convert(Value value, @Nullable Context context) { throw new UnsupportedOperationException("Cannot call a locator in a parameter that doesn't contain a context!"); } diff --git a/src/main/java/carpet/script/annotation/MapConverter.java b/src/main/java/carpet/script/annotation/MapConverter.java index e8ecda802c..dc818a243c 100644 --- a/src/main/java/carpet/script/annotation/MapConverter.java +++ b/src/main/java/carpet/script/annotation/MapConverter.java @@ -13,6 +13,8 @@ import carpet.script.value.MapValue; import carpet.script.value.Value; +import javax.annotation.Nullable; + /** *

Converts a {@link MapValue} to a {@link Map}, converting all of its contents to their respective types.

* @@ -37,15 +39,15 @@ public String getTypeName() } @Override - public Map convert(final Value value, final Context context) + public Map convert(Value value, @Nullable Context context) { - final Map result = new HashMap<>(); + Map result = new HashMap<>(); if (value instanceof MapValue) { - for (final Entry entry : ((MapValue) value).getMap().entrySet()) + for (Entry entry : ((MapValue) value).getMap().entrySet()) { - final K key = keyConverter.convert(entry.getKey(), context); - final V val = valueConverter.convert(entry.getValue(), context); + K key = keyConverter.convert(entry.getKey(), context); + V val = valueConverter.convert(entry.getValue(), context); if (key == null || val == null) { return null; @@ -57,7 +59,7 @@ public Map convert(final Value value, final Context context) return null; } - private MapConverter(final AnnotatedType keyType, final AnnotatedType valueType) + private MapConverter(AnnotatedType keyType, AnnotatedType valueType) { super(); keyConverter = ValueConverter.fromAnnotatedType(keyType); @@ -80,9 +82,9 @@ private MapConverter(final AnnotatedType keyType, final AnnotatedType valueType) * @param annotatedType The type to get generics information from * @return A new {@link MapConverter} for the data specified in the {@link AnnotatedType} */ - static MapConverter fromAnnotatedType(final AnnotatedType annotatedType) + static MapConverter fromAnnotatedType(AnnotatedType annotatedType) { - final AnnotatedType[] annotatedGenerics = ((AnnotatedParameterizedType) annotatedType).getAnnotatedActualTypeArguments(); + AnnotatedType[] annotatedGenerics = ((AnnotatedParameterizedType) annotatedType).getAnnotatedActualTypeArguments(); return annotatedType.isAnnotationPresent(Param.KeyValuePairs.class) ? new PairConverter<>(annotatedGenerics[0], annotatedGenerics[1], annotatedType.getAnnotation(Param.KeyValuePairs.class)) : new MapConverter<>(annotatedGenerics[0], annotatedGenerics[1]); @@ -92,7 +94,7 @@ private static final class PairConverter extends MapConverter { private final boolean acceptMultiParam; - private PairConverter(final AnnotatedType keyType, final AnnotatedType valueType, final Param.KeyValuePairs config) + private PairConverter(AnnotatedType keyType, AnnotatedType valueType, Param.KeyValuePairs config) { super(keyType, valueType); acceptMultiParam = config.allowMultiparam(); @@ -104,26 +106,28 @@ public boolean consumesVariableArgs() return acceptMultiParam; } + @Nullable @Override - public Map convert(final Value value, final Context context) { + public Map convert(Value value, @Nullable Context context) { return value instanceof MapValue ? super.convert(value, context) : value instanceof ListValue ? convertList(((ListValue)value).getItems(), context) : null; // Multiparam mode can only be used in evalAndConvert } - private Map convertList(final List valueList, final Context context) + @Nullable + private Map convertList(List valueList, @Nullable Context context) { if (valueList.size() % 2 == 1) { return null; } - final Map map = new HashMap<>(); - final Iterator val = valueList.iterator(); + Map map = new HashMap<>(); + Iterator val = valueList.iterator(); while (val.hasNext()) { - final K key = keyConverter.convert(val.next(), context); - final V value = valueConverter.convert(val.next(), context); + K key = keyConverter.convert(val.next(), context); + V value = valueConverter.convert(val.next(), context); if (key == null || value == null) { return null; @@ -133,20 +137,21 @@ private Map convertList(final List valueList, final Context context return map; } + @Nullable @Override - public Map checkAndConvert(final Iterator valueIterator, final Context context, final Context.Type theLazyT) + public Map checkAndConvert(Iterator valueIterator, Context context, Context.Type theLazyT) { if (!valueIterator.hasNext()) { return null; } - final Value val = valueIterator.next(); + Value val = valueIterator.next(); if (!acceptMultiParam || val instanceof MapValue || (val instanceof ListValue && !(keyConverter instanceof ListConverter))) { return convert(val, context); // @KeyValuePairs Map, Boolean> will not support list consumption } - final Map map = new HashMap<>(); + Map map = new HashMap<>(); K key = keyConverter.convert(val, context); //First pair is manual since we got it to check for a different conversion mode V value = valueConverter.checkAndConvert(valueIterator, context, theLazyT); if (key == null || value == null) diff --git a/src/main/java/carpet/script/annotation/OptionalConverter.java b/src/main/java/carpet/script/annotation/OptionalConverter.java index 3ef26c3f9e..462bf83ed4 100644 --- a/src/main/java/carpet/script/annotation/OptionalConverter.java +++ b/src/main/java/carpet/script/annotation/OptionalConverter.java @@ -9,6 +9,8 @@ import carpet.script.Context; import carpet.script.value.Value; +import javax.annotation.Nullable; + /** *

{@link ValueConverter} that accepts a parameter to not be present on function call.

* @@ -49,14 +51,15 @@ private OptionalConverter(AnnotatedType type) * @implNote Unlike most other converters, {@link OptionalConverter} will not call this method from * {@link #checkAndConvert(Iterator, Context, Context.Type)} and is only used as a fallback in types that don't support it. */ + @Nullable @Override - public Optional convert(final Value value, final Context context) + public Optional convert(Value value, @Nullable Context context) { if (value.isNull()) { return Optional.empty(); } - final R converted = typeConverter.convert(value, context); + R converted = typeConverter.convert(value, context); if (converted == null) { return null; @@ -64,15 +67,16 @@ public Optional convert(final Value value, final Context context) return Optional.of(converted); } + @Nullable @Override - public Optional checkAndConvert(final Iterator valueIterator, final Context context, final Context.Type theLazyT) + public Optional checkAndConvert(Iterator valueIterator, Context context, Context.Type theLazyT) { if (!valueIterator.hasNext() || valueIterator.next().isNull()) { return Optional.empty(); } ((ListIterator) valueIterator).previous(); - final R converted = typeConverter.checkAndConvert(valueIterator, context, theLazyT); + R converted = typeConverter.checkAndConvert(valueIterator, context, theLazyT); if (converted == null) { return null; @@ -106,10 +110,10 @@ public int valueConsumption() * @param annotatedType The type to get generics information from * @return A new {@link OptionalConverter} for the data specified in the {@link AnnotatedType} */ - static OptionalConverter fromAnnotatedType(final AnnotatedType annotatedType) + static OptionalConverter fromAnnotatedType(AnnotatedType annotatedType) { - final AnnotatedParameterizedType paramType = (AnnotatedParameterizedType) annotatedType; - final AnnotatedType wrappedType = paramType.getAnnotatedActualTypeArguments()[0]; + AnnotatedParameterizedType paramType = (AnnotatedParameterizedType) annotatedType; + AnnotatedType wrappedType = paramType.getAnnotatedActualTypeArguments()[0]; return new OptionalConverter<>(wrappedType); } } diff --git a/src/main/java/carpet/script/annotation/OutputConverter.java b/src/main/java/carpet/script/annotation/OutputConverter.java index 737cbc7835..2c95b87e47 100644 --- a/src/main/java/carpet/script/annotation/OutputConverter.java +++ b/src/main/java/carpet/script/annotation/OutputConverter.java @@ -23,6 +23,8 @@ import carpet.script.value.Value; import carpet.script.value.ValueConversions; +import javax.annotation.Nullable; + /** *

A converter from a given {@link Object} of type T into a {@link LazyValue}, used in order to convert the outputs of methods into usable Scarpet * values.

@@ -57,7 +59,7 @@ public final class OutputConverter private final Function converter; - private OutputConverter(final Function converter) + private OutputConverter(Function converter) { this.converter = converter; } @@ -90,7 +92,7 @@ public static OutputConverter get(Class returnType) * @param input The value to convert * @return The converted value */ - public LazyValue convert(final T input) + public LazyValue convert(@Nullable T input) { return input == null ? LazyValue.NULL : converter.apply(input); } @@ -103,9 +105,9 @@ public LazyValue convert(final T input) * @param inputType The class of T * @param converter The function that converts the an instance of T to a {@link LazyValue} */ - public static void register(final Class inputType, final Function converter) + public static void register(Class inputType, Function converter) { - final OutputConverter instance = new OutputConverter<>(converter); + OutputConverter instance = new OutputConverter<>(converter); if (byResult.containsKey(inputType)) { throw new IllegalArgumentException(inputType + " already has a registered OutputConverter"); @@ -122,9 +124,9 @@ public static void register(final Class inputType, final Function void registerToValue(final Class inputType, final Function converter) + public static void registerToValue(Class inputType, Function converter) { - final OutputConverter instance = new OutputConverter<>(converter.andThen(v -> (c, t) -> v)); + OutputConverter instance = new OutputConverter<>(converter.andThen(v -> (c, t) -> v)); if (byResult.containsKey(inputType)) { throw new IllegalArgumentException(inputType + " already has a registered OutputConverter"); diff --git a/src/main/java/carpet/script/annotation/Param.java b/src/main/java/carpet/script/annotation/Param.java index 177b6faa36..28185963f1 100644 --- a/src/main/java/carpet/script/annotation/Param.java +++ b/src/main/java/carpet/script/annotation/Param.java @@ -24,6 +24,8 @@ import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerPlayer; +import javax.annotation.Nullable; + import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE_USE; import static java.lang.annotation.RetentionPolicy.RUNTIME; @@ -143,18 +145,23 @@ final class Params *

A {@link ValueConverter} that outputs the {@link Context} in which the function has been called, and throws {@link UnsupportedOperationException} when trying to convert a {@link Value} * directly.

*/ - static final ValueConverter CONTEXT_PROVIDER = new ValueConverter() + static final ValueConverter CONTEXT_PROVIDER = new ValueConverter<>() { - @Override public String getTypeName() { return null; } + @Nullable + @Override + public String getTypeName() + { + return null; + } @Override - public Context convert(final Value value, final Context context) + public Context convert(Value value, @Nullable Context context) { throw new UnsupportedOperationException("Called convert() with Value in Context Provider converter, where only checkAndConvert is supported"); } @Override - public Context checkAndConvert(final Iterator valueIterator, final Context context, final Context.Type theLazyT) + public Context checkAndConvert(Iterator valueIterator, Context context, Context.Type theLazyT) { return context; } @@ -170,18 +177,23 @@ public int valueConsumption() *

A {@link ValueConverter} that outputs the {@link Context.Type} which the function has been called, or throws {@link UnsupportedOperationException} when trying to convert a {@link Value} * directly.

*/ - static final ValueConverter CONTEXT_TYPE_PROVIDER = new ValueConverter() + static final ValueConverter CONTEXT_TYPE_PROVIDER = new ValueConverter<>() { - @Override public String getTypeName() { return null; } + @Nullable + @Override + public String getTypeName() + { + return null; + } @Override - public Context.Type convert(final Value value, final Context context) + public Context.Type convert(Value value, @Nullable Context context) { throw new UnsupportedOperationException("Called convert() with a Value in TheLazyT Provider, where only checkAndConvert is supported"); } @Override - public Context.Type checkAndConvert(final Iterator valueIterator, final Context context, final Context.Type theLazyT) + public Context.Type checkAndConvert(Iterator valueIterator, Context context, Context.Type theLazyT) { return theLazyT; } @@ -214,12 +226,12 @@ record StrictConverterInfo(Class type, boolean shallow) {} * @throws IllegalArgumentException If the type doesn't accept the {@link Strict} annotation or if it has been used incorrectly (shallow in * unsupported places) */ - static ValueConverter getStrictConverter(final AnnotatedType type) + static ValueConverter getStrictConverter(AnnotatedType type) { - final boolean shallow = type.getAnnotation(Strict.class).shallow(); - final Class clazz = (Class) type.getType(); - final StrictConverterInfo key = new StrictConverterInfo(clazz, shallow); - final ValueConverter converter = strictParamsByClassAndShallowness.get(key); + boolean shallow = type.getAnnotation(Strict.class).shallow(); + Class clazz = (Class) type.getType(); + StrictConverterInfo key = new StrictConverterInfo(clazz, shallow); + ValueConverter converter = strictParamsByClassAndShallowness.get(key); if (converter != null) { return converter; @@ -239,9 +251,9 @@ static ValueConverter getStrictConverter(final AnnotatedType type) * @param shallow {@code true} if you are registering a shallow-strict parameter, {@code false} if a "fully" strict one * @param converter The {@link ValueConverter} for the given type and shallowness. */ - public static void registerStrictConverter(final Class type, final boolean shallow, final ValueConverter converter) + public static void registerStrictConverter(Class type, boolean shallow, ValueConverter converter) { - final StrictConverterInfo key = new StrictConverterInfo(type, shallow); + StrictConverterInfo key = new StrictConverterInfo(type, shallow); if (strictParamsByClassAndShallowness.containsKey(key)) { throw new IllegalArgumentException(type + " already has a registered " + (shallow ? "" : "non-") + "shallow StrictConverter"); @@ -271,16 +283,16 @@ public static void registerStrictConverter(final Class type, final boolea * avoid possible collisions with other extensions. */ @SuppressWarnings("unchecked") // this makes no sense... But I guess its preferable to enforce typesafety in callers - public static void registerCustomConverterFactory(final BiFunction, ValueConverter> factory) + public static void registerCustomConverterFactory(BiFunction, ValueConverter> factory) { customFactories.add((BiFunction, ValueConverter>) (Object) factory); } @SuppressWarnings("unchecked") // Stored correctly - static ValueConverter getCustomConverter(final AnnotatedType annoType, final Class type) + static ValueConverter getCustomConverter(AnnotatedType annoType, Class type) { ValueConverter result; - for (final BiFunction, ValueConverter> factory : customFactories) + for (BiFunction, ValueConverter> factory : customFactories) { if ((result = (ValueConverter) factory.apply(annoType, type)) != null) { diff --git a/src/main/java/carpet/script/annotation/SimpleTypeConverter.java b/src/main/java/carpet/script/annotation/SimpleTypeConverter.java index aef8f3637c..87c4f25e5c 100644 --- a/src/main/java/carpet/script/annotation/SimpleTypeConverter.java +++ b/src/main/java/carpet/script/annotation/SimpleTypeConverter.java @@ -18,6 +18,8 @@ import carpet.script.value.Value; import carpet.script.value.ValueConversions; +import javax.annotation.Nullable; + /** *

A simple {@link ValueConverter} implementation that converts from a specified subclass of {@link Value} into {@code } by using a given * function.

@@ -61,7 +63,7 @@ public final class SimpleTypeConverter implements ValueConve * * @see #SimpleTypeConverter(Class, BiFunction, String) */ - public SimpleTypeConverter(final Class inputType, final Function converter, final String typeName) + public SimpleTypeConverter(Class inputType, Function converter, String typeName) { this(inputType, (v, c) -> converter.apply(v), typeName); } @@ -77,7 +79,7 @@ public SimpleTypeConverter(final Class inputType, final Function conver * @param converter The function to convert an instance of inputType into R, with the context of the call. * @param typeName The name of the type for error messages */ - public SimpleTypeConverter(final Class inputType, final BiFunction converter, final String typeName) + public SimpleTypeConverter(Class inputType, BiFunction converter, String typeName) { super(); this.converter = converter; @@ -99,14 +101,15 @@ public String getTypeName() * @return The {@link SimpleTypeConverter} for the specified outputType */ @SuppressWarnings("unchecked") // T always extends Value, R is always the same as map's key, since map is private. - static SimpleTypeConverter get(final Class outputType) + static SimpleTypeConverter get(Class outputType) { return (SimpleTypeConverter) byResult.get(outputType); } + @Nullable @Override @SuppressWarnings("unchecked") // more than checked. not using class.cast because then "method is too big" for inlining, because javac is useless - public R convert(final Value value, final Context context) // and adds millions of casts. This one is even removed + public R convert(Value value, @Nullable Context context) // and adds millions of casts. This one is even removed { return valueClass.isInstance(value) ? converter.apply((T)value, context) : null; } @@ -125,8 +128,8 @@ public R convert(final Value value, final Context context) * * @see #registerType(Class, Class, BiFunction, String) */ - public static void registerType(final Class requiredInputType, final Class outputType, - final Function converter, final String typeName) + public static void registerType(Class requiredInputType, Class outputType, + Function converter, String typeName) { registerType(requiredInputType, outputType, (val, ctx) -> converter.apply(val), typeName); } @@ -143,10 +146,10 @@ public static void registerType(final Class requiredInpu * can also throw an {@link InternalExpressionException} by itself if really necessary. * @param typeName The name of the type, following the conventions of {@link ValueConverter#getTypeName()} */ - public static void registerType(final Class requiredInputType, final Class outputType, - final BiFunction converter, final String typeName) + public static void registerType(Class requiredInputType, Class outputType, + BiFunction converter, String typeName) { - final SimpleTypeConverter type = new SimpleTypeConverter<>(requiredInputType, converter, typeName); + SimpleTypeConverter type = new SimpleTypeConverter<>(requiredInputType, converter, typeName); byResult.put(outputType, type); } } diff --git a/src/main/java/carpet/script/annotation/ValueCaster.java b/src/main/java/carpet/script/annotation/ValueCaster.java index fd422f40fc..6cd2624e86 100644 --- a/src/main/java/carpet/script/annotation/ValueCaster.java +++ b/src/main/java/carpet/script/annotation/ValueCaster.java @@ -18,6 +18,8 @@ import carpet.script.value.ThreadValue; import carpet.script.value.Value; +import javax.annotation.Nullable; + /** *

Simple {@link ValueConverter} implementation that casts a {@link Value} into one of its subclasses, either for use directly in parameters or * converters, or as an already working middle step.

@@ -51,7 +53,7 @@ public final class ValueCaster implements ValueConverter // R always exten private final Class outputType; private final String typeName; - private ValueCaster(final Class outputType, final String typeName) + private ValueCaster(Class outputType, String typeName) { super(); this.outputType = outputType; @@ -73,14 +75,15 @@ public String getTypeName() */ @SuppressWarnings("unchecked") // Casters are stored with their exact class, for sure since the map is private (&& class has same generic as // caster) - public static ValueCaster get(final Class outputType) + public static ValueCaster get(Class outputType) { return (ValueCaster) byResult.get(outputType); } + @Nullable @Override @SuppressWarnings("unchecked") // more than checked, see SimpleTypeConverter#converter for reasoning - public R convert(final Value value, final Context context) + public R convert(Value value, @Nullable Context context) { if (!outputType.isInstance(value)) { @@ -98,9 +101,9 @@ public R convert(final Value value, final Context context) * required */ - public static void register(final Class valueClass, final String typeName) + public static void register(Class valueClass, String typeName) { - final ValueCaster caster = new ValueCaster<>(valueClass, typeName); + ValueCaster caster = new ValueCaster<>(valueClass, typeName); byResult.putIfAbsent(valueClass, caster); } } diff --git a/src/main/java/carpet/script/annotation/ValueConverter.java b/src/main/java/carpet/script/annotation/ValueConverter.java index ba98f8b765..8c916ef4ae 100644 --- a/src/main/java/carpet/script/annotation/ValueConverter.java +++ b/src/main/java/carpet/script/annotation/ValueConverter.java @@ -9,12 +9,13 @@ import java.util.Optional; import org.apache.commons.lang3.ClassUtils; -import org.jetbrains.annotations.Nullable; import carpet.script.Context; import carpet.script.annotation.Param.Params; import carpet.script.value.Value; +import javax.annotation.Nullable; + /** *

Classes implementing this interface are able to convert {@link Value} instances into {@code }, in order to easily use them in parameters for * Scarpet functions created using the {@link ScarpetFunction} annotation.

@@ -37,6 +38,7 @@ public interface ValueConverter * @apiNote This method is intended to only be called when an error has occurred and therefore there is a need to print a stacktrace with some * helpful usage instructions. */ + @Nullable String getTypeName(); /** @@ -63,7 +65,7 @@ public interface ValueConverter *

Even with the above reasons, {@link ValueConverter} users should try to implement {@link #convert(Value, Context)} whenever possible instead of * {@link #checkAndConvert(Iterator, Context, Context.Type)}, since it allows its usage in generics of lists and maps.

*/ - @Nullable R convert(Value value, final Context context); + @Nullable R convert(Value value, @Nullable Context context); /** * Old version of {@link #convert(Value)} without taking a {@link Context}.

@@ -75,8 +77,9 @@ public interface ValueConverter * @return A converted value * @deprecated Calling this method instead of {@link #convert(Value, Context)} may not return values for some converters */ + @Nullable @Deprecated(forRemoval = true) - default R convert(final Value value) + default R convert(Value value) { try { @@ -130,7 +133,7 @@ default int valueConsumption() * @return A usable {@link ValueConverter} to convert from a {@link Value} to {@code } */ @SuppressWarnings("unchecked") - static ValueConverter fromAnnotatedType(final AnnotatedType annoType) + static ValueConverter fromAnnotatedType(AnnotatedType annoType) { Class type = annoType.getType() instanceof ParameterizedType ? // We are defining R here. (Class) ((ParameterizedType) annoType.getType()).getRawType() : @@ -208,7 +211,8 @@ static ValueConverter fromAnnotatedType(final AnnotatedType annoType) * @implNote This method's default implementation runs the {@link #convert(Value, Context)} function in the next {@link Value} ignoring {@link Context} and * {@code theLazyT}. */ - default R checkAndConvert(final Iterator valueIterator, final Context context, final Context.Type contextType) + @Nullable + default R checkAndConvert(Iterator valueIterator, Context context, Context.Type contextType) { return !valueIterator.hasNext() ? null : convert(valueIterator.next(), context); } diff --git a/src/main/java/carpet/script/api/Auxiliary.java b/src/main/java/carpet/script/api/Auxiliary.java index 00d273cf8e..f08e5b0ee8 100644 --- a/src/main/java/carpet/script/api/Auxiliary.java +++ b/src/main/java/carpet/script/api/Auxiliary.java @@ -83,6 +83,7 @@ import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; +import javax.annotation.Nullable; import java.io.BufferedWriter; import java.io.IOException; import java.net.URI; @@ -104,7 +105,6 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -import static carpet.script.value.NBTSerializableValue.nameFromRegistryId; import static java.lang.Math.max; import static java.lang.Math.min; @@ -115,9 +115,9 @@ public class Auxiliary public static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().registerTypeAdapter(Value.class, new ScarpetJsonDeserializer()).create(); @Deprecated - public static String recognizeResource(final Value value, final boolean isFloder) + public static String recognizeResource(Value value, boolean isFloder) { - final String origfile = value.getString(); + String origfile = value.getString(); String file = origfile.toLowerCase(Locale.ROOT).replaceAll("[^A-Za-z0-9\\-+_/]", ""); file = Arrays.stream(file.split("/+")).filter(s -> !s.isEmpty()).collect(Collectors.joining("/")); if (file.isEmpty() && !isFloder) @@ -127,34 +127,34 @@ public static String recognizeResource(final Value value, final boolean isFloder return file; } - public static void apply(final Expression expression) + public static void apply(Expression expression) { expression.addContextFunction("sound", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - if (lv.size() == 0) + CarpetContext cc = (CarpetContext) c; + if (lv.isEmpty()) { return ListValue.wrap(cc.registry(Registries.SOUND_EVENT).keySet().stream().map(ValueConversions::of)); } - final String rawString = lv.get(0).getString(); - final ResourceLocation soundName = InputValidator.identifierOf(rawString); - final Vector3Argument locator = Vector3Argument.findIn(lv, 1); + String rawString = lv.get(0).getString(); + ResourceLocation soundName = InputValidator.identifierOf(rawString); + Vector3Argument locator = Vector3Argument.findIn(lv, 1); if (cc.registry(Registries.SOUND_EVENT).get(soundName) == null) { throw new ThrowStatement(rawString, Throwables.UNKNOWN_SOUND); } - final Holder soundHolder = Holder.direct(SoundEvent.createVariableRangeEvent(soundName)); + Holder soundHolder = Holder.direct(SoundEvent.createVariableRangeEvent(soundName)); float volume = 1.0F; float pitch = 1.0F; SoundSource mixer = SoundSource.MASTER; - if (lv.size() > 0 + locator.offset) + if (lv.size() > locator.offset) { - volume = (float) NumericValue.asNumber(lv.get(0 + locator.offset)).getDouble(); + volume = (float) NumericValue.asNumber(lv.get(locator.offset)).getDouble(); if (lv.size() > 1 + locator.offset) { pitch = (float) NumericValue.asNumber(lv.get(1 + locator.offset)).getDouble(); if (lv.size() > 2 + locator.offset) { - final String mixerName = lv.get(2 + locator.offset).getString(); + String mixerName = lv.get(2 + locator.offset).getString(); mixer = mixerMap.get(mixerName.toLowerCase(Locale.ROOT)); if (mixer == null) { @@ -163,12 +163,12 @@ public static void apply(final Expression expression) } } } - final Vec3 vec = locator.vec; - final double d0 = Math.pow(volume > 1.0F ? (double) (volume * 16.0F) : 16.0D, 2.0D); + Vec3 vec = locator.vec; + double d0 = Math.pow(volume > 1.0F ? (double) (volume * 16.0F) : 16.0D, 2.0D); int count = 0; - final ServerLevel level = cc.level(); - final long seed = level.getRandom().nextLong(); - for (final ServerPlayer player : level.getPlayers((p) -> p.distanceToSqr(vec) < d0)) + ServerLevel level = cc.level(); + long seed = level.getRandom().nextLong(); + for (ServerPlayer player : level.getPlayers(p -> p.distanceToSqr(vec) < d0)) { count++; player.connection.send(new ClientboundSoundPacket(soundHolder, mixer, vec.x, vec.y, vec.z, volume, pitch, seed)); @@ -178,15 +178,15 @@ public static void apply(final Expression expression) expression.addContextFunction("particle", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - if (lv.size() == 0) + CarpetContext cc = (CarpetContext) c; + if (lv.isEmpty()) { return ListValue.wrap(cc.registry(Registries.PARTICLE_TYPE).keySet().stream().map(ValueConversions::of)); } - final MinecraftServer ms = cc.server(); - final ServerLevel world = cc.level(); - final Vector3Argument locator = Vector3Argument.findIn(lv, 1); - final String particleName = lv.get(0).getString(); + MinecraftServer ms = cc.server(); + ServerLevel world = cc.level(); + Vector3Argument locator = Vector3Argument.findIn(lv, 1); + String particleName = lv.get(0).getString(); int count = 10; double speed = 0; float spread = 0.5f; @@ -207,11 +207,11 @@ public static void apply(final Expression expression) } } } - final ParticleOptions particle = ShapeDispatcher.getParticleData(particleName, world.registryAccess()); - final Vec3 vec = locator.vec; + ParticleOptions particle = ShapeDispatcher.getParticleData(particleName, world.registryAccess()); + Vec3 vec = locator.vec; if (player == null) { - for (final ServerPlayer p : (world.players())) + for (ServerPlayer p : (world.players())) { world.sendParticles(p, particle, true, vec.x, vec.y, vec.z, count, spread, spread, spread, speed); @@ -229,27 +229,27 @@ public static void apply(final Expression expression) expression.addContextFunction("particle_line", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final ServerLevel world = cc.level(); - final String particleName = lv.get(0).getString(); - final ParticleOptions particle = ShapeDispatcher.getParticleData(particleName, world.registryAccess()); - final Vector3Argument pos1 = Vector3Argument.findIn(lv, 1); - final Vector3Argument pos2 = Vector3Argument.findIn(lv, pos1.offset); + CarpetContext cc = (CarpetContext) c; + ServerLevel world = cc.level(); + String particleName = lv.get(0).getString(); + ParticleOptions particle = ShapeDispatcher.getParticleData(particleName, world.registryAccess()); + Vector3Argument pos1 = Vector3Argument.findIn(lv, 1); + Vector3Argument pos2 = Vector3Argument.findIn(lv, pos1.offset); double density = 1.0; ServerPlayer player = null; - if (lv.size() > pos2.offset + 0) + if (lv.size() > pos2.offset) { - density = NumericValue.asNumber(lv.get(pos2.offset + 0)).getDouble(); + density = NumericValue.asNumber(lv.get(pos2.offset)).getDouble(); if (density <= 0) { throw new InternalExpressionException("Particle density should be positive"); } if (lv.size() > pos2.offset + 1) { - final Value playerValue = lv.get(pos2.offset + 1); + Value playerValue = lv.get(pos2.offset + 1); if (playerValue instanceof EntityValue entityValue) { - final Entity e = entityValue.getEntity(); + Entity e = entityValue.getEntity(); if (!(e instanceof final ServerPlayer sp)) { throw new InternalExpressionException("'particle_line' player argument has to be a player"); @@ -273,28 +273,28 @@ public static void apply(final Expression expression) expression.addContextFunction("particle_box", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final ServerLevel world = cc.level(); - final String particleName = lv.get(0).getString(); - final ParticleOptions particle = ShapeDispatcher.getParticleData(particleName, world.registryAccess()); - final Vector3Argument pos1 = Vector3Argument.findIn(lv, 1); - final Vector3Argument pos2 = Vector3Argument.findIn(lv, pos1.offset); + CarpetContext cc = (CarpetContext) c; + ServerLevel world = cc.level(); + String particleName = lv.get(0).getString(); + ParticleOptions particle = ShapeDispatcher.getParticleData(particleName, world.registryAccess()); + Vector3Argument pos1 = Vector3Argument.findIn(lv, 1); + Vector3Argument pos2 = Vector3Argument.findIn(lv, pos1.offset); double density = 1.0; ServerPlayer player = null; - if (lv.size() > pos2.offset + 0) + if (lv.size() > pos2.offset) { - density = NumericValue.asNumber(lv.get(pos2.offset + 0)).getDouble(); + density = NumericValue.asNumber(lv.get(pos2.offset)).getDouble(); if (density <= 0) { throw new InternalExpressionException("Particle density should be positive"); } if (lv.size() > pos2.offset + 1) { - final Value playerValue = lv.get(pos2.offset + 1); + Value playerValue = lv.get(pos2.offset + 1); if (playerValue instanceof EntityValue entityValue) { - final Entity e = entityValue.getEntity(); + Entity e = entityValue.getEntity(); if (!(e instanceof final ServerPlayer sp)) { throw new InternalExpressionException("'particle_box' player argument has to be a player"); @@ -307,11 +307,11 @@ public static void apply(final Expression expression) } } } - final Vec3 a = pos1.vec; - final Vec3 b = pos2.vec; - final Vec3 from = new Vec3(min(a.x, b.x), min(a.y, b.y), min(a.z, b.z)); - final Vec3 to = new Vec3(max(a.x, b.x), max(a.y, b.y), max(a.z, b.z)); - final int particleCount = ShapeDispatcher.Box.particleMesh( + 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.players() : Collections.singletonList(player), particle, density, from, to ); @@ -323,19 +323,19 @@ public static void apply(final Expression expression) expression.addContextFunction("draw_shape", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final ServerLevel world = cc.level(); - final MinecraftServer server = world.getServer(); - final Set playerTargets = new HashSet<>(); - final List shapes = new ArrayList<>(); + CarpetContext cc = (CarpetContext) c; + ServerLevel world = cc.level(); + MinecraftServer server = world.getServer(); + Set playerTargets = new HashSet<>(); + List shapes = new ArrayList<>(); if (lv.size() == 1) // bulk { - final Value specLoad = lv.get(0); + Value specLoad = lv.get(0); if (!(specLoad instanceof final ListValue spec)) { throw new InternalExpressionException("In bulk mode - shapes need to be provided as a list of shape specs"); } - for (final Value list : spec.getItems()) + for (Value list : spec.getItems()) { if (!(list instanceof final ListValue inner)) { @@ -357,20 +357,20 @@ public static void apply(final Expression expression) }); expression.addContextFunction("create_marker", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; + CarpetContext cc = (CarpetContext) c; BlockState targetBlock = null; - final Vector3Argument pointLocator; + Vector3Argument pointLocator; boolean interactable = true; - final Component name; + Component name; try { - final Value nameValue = lv.get(0); + Value nameValue = lv.get(0); name = nameValue.isNull() ? null : FormattedTextValue.getTextByValue(nameValue); pointLocator = Vector3Argument.findIn(lv, 1, true, false); if (lv.size() > pointLocator.offset) { - final BlockArgument blockLocator = BlockArgument.findIn(cc, lv, pointLocator.offset, true, true, false); - if (blockLocator.block != null) + BlockArgument blockLocator = BlockArgument.findIn(cc, lv, pointLocator.offset, true, true, false); + if (!(blockLocator instanceof BlockArgument.MissingBlockArgument)) { targetBlock = blockLocator.block.getBlockState(); } @@ -384,9 +384,9 @@ public static void apply(final Expression expression) { throw new InternalExpressionException("'create_marker' requires a name and three coordinates, with optional direction, and optional block on its head"); } - final Level level = cc.level(); - final ArmorStand armorstand = new ArmorStand(EntityType.ARMOR_STAND, level); - final double yoffset; + Level level = cc.level(); + ArmorStand armorstand = new ArmorStand(EntityType.ARMOR_STAND, level); + double yoffset; if (targetBlock == null && name == null) { yoffset = 0.0; @@ -435,13 +435,13 @@ else if (!interactable && targetBlock == null) }); expression.addContextFunction("remove_all_markers", 0, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; + CarpetContext cc = (CarpetContext) c; int total = 0; - final String markerName = MARKER_STRING + "_" + ((cc.host.getName() == null) ? "" : cc.host.getName()); - for (final Entity e : cc.level().getEntities(EntityType.ARMOR_STAND, (as) -> as.getTags().contains(markerName))) + String markerName = MARKER_STRING + "_" + ((cc.host.getName() == null) ? "" : cc.host.getName()); + for (Entity e : cc.level().getEntities(EntityType.ARMOR_STAND, as -> as.getTags().contains(markerName))) { total++; - e.discard(); // discard // remove(); + e.discard(); } return new NumericValue(total); }); @@ -455,12 +455,12 @@ else if (!interactable && targetBlock == null) { return nbtsv.toValue(); } - final NBTSerializableValue ret = NBTSerializableValue.parseString(v.getString(), false); + NBTSerializableValue ret = NBTSerializableValue.parseString(v.getString()); return ret == null ? Value.NULL : ret.toValue(); }); - expression.addFunction("tag_matches", (lv) -> { - final int numParam = lv.size(); + expression.addFunction("tag_matches", lv -> { + int numParam = lv.size(); if (numParam != 2 && numParam != 3) { throw new InternalExpressionException("'tag_matches' requires 2 or 3 arguments"); @@ -473,25 +473,25 @@ else if (!interactable && targetBlock == null) { return Value.FALSE; } - final Tag source = ((NBTSerializableValue) (NBTSerializableValue.fromValue(lv.get(0)))).getTag(); - final Tag match = ((NBTSerializableValue) (NBTSerializableValue.fromValue(lv.get(1)))).getTag(); + 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 -> { - final int argSize = lv.size(); + int argSize = lv.size(); if (argSize == 0 || argSize > 2) { throw new InternalExpressionException("'encode_nbt' requires 1 or 2 parameters"); } - final Value v = lv.get(0); - final boolean force = (argSize > 1) && lv.get(1).getBoolean(); - final Tag tag; + Value v = lv.get(0); + boolean force = (argSize > 1) && lv.get(1).getBoolean(); + Tag tag; try { tag = v.toTag(force); } - catch (final NBTSerializableValue.IncompatibleTypeException exception) + catch (NBTSerializableValue.IncompatibleTypeException exception) { throw new InternalExpressionException("cannot reliably encode to a tag the value of '" + exception.val.getPrettyString() + "'"); } @@ -501,20 +501,20 @@ else if (!interactable && targetBlock == null) //"overridden" native call that prints to stderr expression.addContextFunction("print", -1, (c, t, lv) -> { - if (lv.size() == 0 || lv.size() > 2) + if (lv.isEmpty() || lv.size() > 2) { throw new InternalExpressionException("'print' takes one or two arguments"); } - final CommandSourceStack s = ((CarpetContext) c).source(); - final MinecraftServer server = s.getServer(); + CommandSourceStack s = ((CarpetContext) c).source(); + MinecraftServer server = s.getServer(); Value res = lv.get(0); List targets = null; if (lv.size() == 2) { - final List playerValues = (res instanceof ListValue list) ? list.getItems() : Collections.singletonList(res); - final List playerTargets = new ArrayList<>(); + List playerValues = (res instanceof ListValue list) ? list.getItems() : Collections.singletonList(res); + List playerTargets = new ArrayList<>(); playerValues.forEach(pv -> { - final ServerPlayer player = EntityValue.getPlayerByValue(server, pv); + ServerPlayer player = EntityValue.getPlayerByValue(server, pv); if (player == null) { throw new InternalExpressionException("Cannot target player " + pv.getString() + " in print"); @@ -524,7 +524,7 @@ else if (!interactable && targetBlock == null) targets = playerTargets; res = lv.get(1); } - final Component message = FormattedTextValue.getTextByValue(res); + Component message = FormattedTextValue.getTextByValue(res); if (targets == null) { s.sendSuccess(message, false); @@ -546,10 +546,10 @@ else if (!interactable && targetBlock == null) { pVal = ListValue.of(pVal); } - final MinecraftServer server = ((CarpetContext) c).server(); - final Stream targets = ((ListValue) pVal).getItems().stream().map(v -> + MinecraftServer server = ((CarpetContext) c).server(); + Stream targets = ((ListValue) pVal).getItems().stream().map(v -> { - final ServerPlayer 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."); @@ -557,7 +557,7 @@ else if (!interactable && targetBlock == null) return player; }); Function> packetGetter = null; - final String actionString = lv.get(1).getString().toLowerCase(Locale.ROOT); + String actionString = lv.get(1).getString().toLowerCase(Locale.ROOT); switch (actionString) { case "title": @@ -592,7 +592,7 @@ else if (!interactable && targetBlock == null) default: throw new InternalExpressionException("'display_title' requires 'title', 'subtitle', 'actionbar', 'player_list_header', 'player_list_footer' or 'clear' as second argument"); } - final Component title; + Component title; boolean soundsTrue = false; if (lv.size() > 2) { @@ -606,7 +606,7 @@ else if (!interactable && targetBlock == null) } if (packetGetter == null) { - final Map map; + Map map; if (actionString.equals("player_list_header")) { map = Carpet.getScarpetHeaders(); @@ -616,8 +616,8 @@ else if (!interactable && targetBlock == null) map = Carpet.getScarpetFooters(); } - final AtomicInteger total = new AtomicInteger(0); - final List targetList = targets.collect(Collectors.toList()); + AtomicInteger total = new AtomicInteger(0); + List targetList = targets.collect(Collectors.toList()); if (!soundsTrue) // null or empty string { targetList.forEach(target -> { @@ -635,16 +635,16 @@ else if (!interactable && targetBlock == null) Carpet.updateScarpetHUDs(((CarpetContext) c).server(), targetList); return NumericValue.of(total.get()); } - final ClientboundSetTitlesAnimationPacket 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"); } - final int in = NumericValue.asNumber(lv.get(3), "fade in for display_title").getInt(); - final int stay = NumericValue.asNumber(lv.get(4), "stay for display_title").getInt(); - final int out = NumericValue.asNumber(lv.get(5), "fade out for display_title").getInt(); + 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 ClientboundSetTitlesAnimationPacket(in, stay, out); } else @@ -652,8 +652,8 @@ else if (!interactable && targetBlock == null) timesPacket = null; } - final Packet packet = packetGetter.apply(title); - final AtomicInteger total = new AtomicInteger(0); + Packet packet = packetGetter.apply(title); + AtomicInteger total = new AtomicInteger(0); targets.forEach(p -> { if (timesPacket != null) { @@ -666,7 +666,7 @@ else if (!interactable && targetBlock == null) }); expression.addFunction("format", values -> { - if (values.size() == 0) + if (values.isEmpty()) { throw new InternalExpressionException("'format' requires at least one component"); } @@ -679,12 +679,12 @@ else if (!interactable && targetBlock == null) expression.addContextFunction("run", 1, (c, t, lv) -> { - final CommandSourceStack s = ((CarpetContext) c).source(); + CommandSourceStack s = ((CarpetContext) c).source(); try { - final Component[] error = {null}; - final List output = new ArrayList<>(); - final Value retval = new NumericValue(s.getServer().getCommands().performPrefixedCommand( + Component[] error = {null}; + List output = new ArrayList<>(); + Value retval = new NumericValue(s.getServer().getCommands().performPrefixedCommand( new SnoopyCommandSource(s, error, output), lv.get(0).getString()) ); @@ -694,7 +694,7 @@ else if (!interactable && targetBlock == null) FormattedTextValue.of(error[0]) ); } - catch (final Exception exc) + catch (Exception exc) { return ListValue.of(Value.NULL, ListValue.of(), new FormattedTextValue(Component.literal(exc.getMessage()))); } @@ -702,10 +702,10 @@ else if (!interactable && targetBlock == null) expression.addContextFunction("save", 0, (c, t, lv) -> { - final CommandSourceStack s = ((CarpetContext) c).source(); + CommandSourceStack s = ((CarpetContext) c).source(); s.getServer().getPlayerList().saveAll(); s.getServer().saveAllChunks(true, true, true); - for (final ServerLevel world : s.getServer().getAllLevels()) + for (ServerLevel world : s.getServer().getAllLevels()) { world.getChunkSource().tick(() -> true, false); } @@ -723,8 +723,8 @@ else if (!interactable && targetBlock == null) expression.addContextFunction("day_time", -1, (c, t, lv) -> { - final Value time = new NumericValue(((CarpetContext) c).level().getDayTime()); - if (lv.size() > 0) + Value time = new NumericValue(((CarpetContext) c).level().getDayTime()); + if (!lv.isEmpty()) { long newTime = NumericValue.asNumber(lv.get(0)).getLong(); if (newTime < 0) @@ -744,9 +744,9 @@ else if (!interactable && targetBlock == null) expression.addContextFunction("game_tick", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final MinecraftServer server = cc.server(); - final CarpetScriptServer scriptServer = (CarpetScriptServer) c.host.scriptServer(); + CarpetContext cc = (CarpetContext) c; + MinecraftServer server = cc.server(); + CarpetScriptServer scriptServer = (CarpetScriptServer) c.host.scriptServer(); if (scriptServer == null) { return Value.NULL; @@ -763,18 +763,18 @@ else if (!interactable && targetBlock == null) { scriptServer.tickDepth++; Vanilla.MinecraftServer_forceTick(server, () -> System.nanoTime() - scriptServer.tickStart < 50000000L); - if (lv.size() > 0) + if (!lv.isEmpty()) { - final long ms_total = NumericValue.asNumber(lv.get(0)).getLong(); - final long end_expected = scriptServer.tickStart + ms_total * 1000000L; - final long wait = end_expected - System.nanoTime(); + long msTotal = NumericValue.asNumber(lv.get(0)).getLong(); + long endExpected = scriptServer.tickStart + msTotal * 1000000L; + long wait = endExpected - System.nanoTime(); if (wait > 0L) { try { Thread.sleep(wait / 1000000L); } - catch (final InterruptedException ignored) + catch (InterruptedException ignored) { } } @@ -784,12 +784,12 @@ else if (!interactable && targetBlock == null) } finally { - if (scriptServer != null) + if (!scriptServer.stopAll) { scriptServer.tickDepth--; } } - if (scriptServer != null && scriptServer.stopAll) + if (scriptServer.stopAll) { throw new ExitStatement(Value.NULL); } @@ -797,17 +797,17 @@ else if (!interactable && targetBlock == null) }); expression.addContextFunction("seed", -1, (c, t, lv) -> { - final CommandSourceStack s = ((CarpetContext) c).source(); + CommandSourceStack s = ((CarpetContext) c).source(); c.host.issueDeprecation("seed()"); return new NumericValue(s.getLevel().getSeed()); }); expression.addContextFunction("relight", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final BlockArgument locator = BlockArgument.findIn(cc, lv, 0); - final BlockPos pos = locator.block.getPos(); - final ServerLevel world = cc.level(); + CarpetContext cc = (CarpetContext) c; + BlockArgument locator = BlockArgument.findIn(cc, lv, 0); + BlockPos pos = locator.block.getPos(); + ServerLevel world = cc.level(); Vanilla.ChunkMap_relightChunk(world.getChunkSource().chunkMap, new ChunkPos(pos)); WorldTools.forceChunkUpdate(pos, world); return Value.TRUE; @@ -824,26 +824,26 @@ else if (!interactable && targetBlock == null) // lazy due to passthrough and context changing ability expression.addLazyFunction("in_dimension", 2, (c, t, lv) -> { - final CommandSourceStack outerSource = ((CarpetContext) c).source(); - final Value dimensionValue = lv.get(0).evalValue(c); - final Level world = ValueConversions.dimFromValue(dimensionValue, outerSource.getServer()); + CommandSourceStack outerSource = ((CarpetContext) c).source(); + Value dimensionValue = lv.get(0).evalValue(c); + Level world = ValueConversions.dimFromValue(dimensionValue, outerSource.getServer()); if (world == outerSource.getLevel()) { return lv.get(1); } - final CommandSourceStack innerSource = outerSource.withLevel((ServerLevel) world); - final Context newCtx = c.recreate(); + CommandSourceStack innerSource = outerSource.withLevel((ServerLevel) world); + Context newCtx = c.recreate(); ((CarpetContext) newCtx).swapSource(innerSource); newCtx.variables = c.variables; - final Value retval = lv.get(1).evalValue(newCtx); + Value retval = lv.get(1).evalValue(newCtx); return (cc, tt) -> retval; }); expression.addContextFunction("plop", -1, (c, t, lv) -> { - if (lv.size() == 0) + if (lv.isEmpty()) { - final Map plopData = new HashMap<>(); - final CarpetContext cc = (CarpetContext) c; + Map plopData = new HashMap<>(); + CarpetContext cc = (CarpetContext) c; plopData.put(StringValue.of("scarpet_custom"), ListValue.wrap(FeatureGenerator.featureMap.keySet().stream().sorted().map(StringValue::of)) ); @@ -861,16 +861,16 @@ else if (!interactable && targetBlock == null) ); return MapValue.wrap(plopData); } - final BlockArgument locator = BlockArgument.findIn((CarpetContext) c, lv, 0); + BlockArgument locator = BlockArgument.findIn((CarpetContext) c, lv, 0); if (lv.size() <= locator.offset) { throw new InternalExpressionException("'plop' needs extra argument indicating what to plop"); } - final String what = lv.get(locator.offset).getString(); - final Value[] result = new Value[]{Value.NULL}; + String what = lv.get(locator.offset).getString(); + Value[] result = new Value[]{Value.NULL}; ((CarpetContext) c).server().executeBlocking(() -> { - final Boolean res = FeatureGenerator.plop(what, ((CarpetContext) c).level(), locator.block.getPos()); + Boolean res = FeatureGenerator.plop(what, ((CarpetContext) c).level(), locator.block.getPos()); if (res == null) { @@ -890,9 +890,9 @@ else if (!interactable && targetBlock == null) { throw new InternalExpressionException("'schedule' should have at least 2 arguments, delay and call name"); } - final long delay = NumericValue.asNumber(lv.get(0)).getLong(); + long delay = NumericValue.asNumber(lv.get(0)).getLong(); - final FunctionArgument functionArgument = FunctionArgument.findIn(c, expression.module, lv, 1, false, false); + FunctionArgument functionArgument = FunctionArgument.findIn(c, expression.module, lv, 1, false, false); ((CarpetScriptServer)c.host.scriptServer()).events.scheduleCall( (CarpetContext) c, functionArgument.function, @@ -904,7 +904,7 @@ else if (!interactable && targetBlock == null) expression.addImpureFunction("logger", lv -> { - final Value res; + Value res; if (lv.size() == 1) { @@ -913,7 +913,7 @@ else if (!interactable && targetBlock == null) } else if (lv.size() == 2) { - final String level = lv.get(0).getString().toLowerCase(Locale.ROOT); + String level = lv.get(0).getString().toLowerCase(Locale.ROOT); res = lv.get(1); switch (level) { @@ -935,29 +935,29 @@ else if (lv.size() == 2) expression.addContextFunction("list_files", 2, (c, t, lv) -> { - final FileArgument fdesc = FileArgument.from(c, lv, true, FileArgument.Reason.READ); - final Stream files = ((CarpetScriptHost) c.host).listFolder(fdesc); + FileArgument fdesc = FileArgument.from(c, lv, true, FileArgument.Reason.READ); + Stream files = ((CarpetScriptHost) c.host).listFolder(fdesc); return files == null ? Value.NULL : ListValue.wrap(files.map(StringValue::of)); }); expression.addContextFunction("read_file", 2, (c, t, lv) -> { - final FileArgument fdesc = FileArgument.from(c, lv, false, FileArgument.Reason.READ); + FileArgument fdesc = FileArgument.from(c, lv, false, FileArgument.Reason.READ); if (fdesc.type == FileArgument.Type.NBT) { - final Tag state = ((CarpetScriptHost) c.host).readFileTag(fdesc); + Tag state = ((CarpetScriptHost) c.host).readFileTag(fdesc); return state == null ? Value.NULL : new NBTSerializableValue(state); } else if (fdesc.type == FileArgument.Type.JSON) { - final JsonElement json; + JsonElement json; json = ((CarpetScriptHost) c.host).readJsonFile(fdesc); - final Value parsedJson = GSON.fromJson(json, Value.class); + Value parsedJson = GSON.fromJson(json, Value.class); return parsedJson == null ? Value.NULL : parsedJson; } else { - final List content = ((CarpetScriptHost) c.host).readTextResource(fdesc); + List content = ((CarpetScriptHost) c.host).readTextResource(fdesc); return content == null ? Value.NULL : ListValue.wrap(content.stream().map(StringValue::new)); } }); @@ -970,33 +970,33 @@ else if (fdesc.type == FileArgument.Type.JSON) { throw new InternalExpressionException("'write_file' requires three or more arguments"); } - final FileArgument fdesc = FileArgument.from(c, lv, false, FileArgument.Reason.CREATE); + FileArgument fdesc = FileArgument.from(c, lv, false, FileArgument.Reason.CREATE); - final boolean success; + boolean success; if (fdesc.type == FileArgument.Type.NBT) { - final Value val = lv.get(2); - final NBTSerializableValue tagValue = (val instanceof final NBTSerializableValue nbtsv) + Value val = lv.get(2); + NBTSerializableValue tagValue = (val instanceof final NBTSerializableValue nbtsv) ? nbtsv : new NBTSerializableValue(val.getString()); - final Tag tag = tagValue.getTag(); + Tag tag = tagValue.getTag(); success = ((CarpetScriptHost) c.host).writeTagFile(tag, fdesc); } else if (fdesc.type == FileArgument.Type.JSON) { - final List data = Collections.singletonList(GSON.toJson(lv.get(2).toJson())); + List data = Collections.singletonList(GSON.toJson(lv.get(2).toJson())); ((CarpetScriptHost) c.host).removeResourceFile(fdesc); success = ((CarpetScriptHost) c.host).appendLogFile(fdesc, data); } else { - final List data = new ArrayList<>(); + List data = new ArrayList<>(); if (lv.size() == 3) { - final Value val = lv.get(2); + Value val = lv.get(2); if (val instanceof final ListValue list) { - final List lval = list.getItems(); + List lval = list.getItems(); lval.forEach(v -> data.add(v.getString())); } else @@ -1019,11 +1019,11 @@ else if (fdesc.type == FileArgument.Type.JSON) expression.addContextFunction("load_app_data", -1, (c, t, lv) -> { FileArgument fdesc = new FileArgument(null, FileArgument.Type.NBT, null, false, false, FileArgument.Reason.READ, c.host); - if (lv.size() > 0) + if (!lv.isEmpty()) { c.host.issueDeprecation("load_app_data(...) with arguments"); - final String resource = recognizeResource(lv.get(0), false); - final boolean shared = lv.size() > 1 && lv.get(1).getBoolean(); + String resource = recognizeResource(lv.get(0), false); + boolean shared = lv.size() > 1 && lv.get(1).getBoolean(); fdesc = new FileArgument(resource, FileArgument.Type.NBT, null, false, shared, FileArgument.Reason.READ, c.host); } return NBTSerializableValue.of(((CarpetScriptHost) c.host).readFileTag(fdesc)); @@ -1031,20 +1031,20 @@ else if (fdesc.type == FileArgument.Type.JSON) expression.addContextFunction("store_app_data", -1, (c, t, lv) -> { - if (lv.size() == 0) + if (lv.isEmpty()) { throw new InternalExpressionException("'store_app_data' needs NBT tag and an optional file"); } - final Value val = lv.get(0); + Value val = lv.get(0); FileArgument fdesc = new FileArgument(null, FileArgument.Type.NBT, null, false, false, FileArgument.Reason.CREATE, c.host); if (lv.size() > 1) { c.host.issueDeprecation("store_app_data(...) with more than one argument"); - final String resource = recognizeResource(lv.get(1), false); - final boolean shared = lv.size() > 2 && lv.get(2).getBoolean(); + String resource = recognizeResource(lv.get(1), false); + boolean shared = lv.size() > 2 && lv.get(2).getBoolean(); fdesc = new FileArgument(resource, FileArgument.Type.NBT, null, false, shared, FileArgument.Reason.CREATE, c.host); } - final NBTSerializableValue tagValue = (val instanceof final NBTSerializableValue nbtsv) + NBTSerializableValue tagValue = (val instanceof final NBTSerializableValue nbtsv) ? nbtsv : new NBTSerializableValue(val.getString()); return BooleanValue.of(((CarpetScriptHost) c.host).writeTagFile(tagValue.getTag(), fdesc)); @@ -1052,22 +1052,22 @@ else if (fdesc.type == FileArgument.Type.JSON) expression.addContextFunction("statistic", 3, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final ServerPlayer player = EntityValue.getPlayerByValue(cc.server(), lv.get(0)); + CarpetContext cc = (CarpetContext) c; + ServerPlayer player = EntityValue.getPlayerByValue(cc.server(), lv.get(0)); if (player == null) { return Value.NULL; } - final ResourceLocation category; - final ResourceLocation statName; + ResourceLocation category; + ResourceLocation statName; category = InputValidator.identifierOf(lv.get(1).getString()); statName = InputValidator.identifierOf(lv.get(2).getString()); - final StatType type = cc.registry(Registries.STAT_TYPE).get(category); + StatType type = cc.registry(Registries.STAT_TYPE).get(category); if (type == null) { return Value.NULL; } - final Stat stat = getStat(type, statName); + Stat stat = getStat(type, statName); if (stat == null) { return Value.NULL; @@ -1082,9 +1082,9 @@ else if (fdesc.type == FileArgument.Type.JSON) { throw new InternalExpressionException("'handle_event' requires at least two arguments, event name, and a callback"); } - final String event = lv.get(0).getString(); - final FunctionArgument callback = FunctionArgument.findIn(c, expression.module, lv, 1, true, false); - final CarpetScriptHost host = ((CarpetScriptHost) c.host); + String event = lv.get(0).getString(); + FunctionArgument callback = FunctionArgument.findIn(c, expression.module, lv, 1, true, false); + CarpetScriptHost host = ((CarpetScriptHost) c.host); if (callback.function == null) { return BooleanValue.of(host.scriptServer().events.removeBuiltInEvent(event, host)); @@ -1095,13 +1095,13 @@ else if (fdesc.type == FileArgument.Type.JSON) //signal_event('event', player or null, args.... ) -> number of apps notified expression.addContextFunction("signal_event", -1, (c, t, lv) -> { - if (lv.size() == 0) + if (lv.isEmpty()) { throw new InternalExpressionException("'signal' requires at least one argument"); } - final CarpetContext cc = (CarpetContext) c; - final CarpetScriptServer server = ((CarpetScriptHost) c.host).scriptServer(); - final String eventName = lv.get(0).getString(); + CarpetContext cc = (CarpetContext) c; + CarpetScriptServer server = ((CarpetScriptHost) c.host).scriptServer(); + String eventName = lv.get(0).getString(); // no such event yet if (CarpetEventServer.Event.getEvent(eventName, server) == null) { @@ -1117,7 +1117,7 @@ else if (fdesc.type == FileArgument.Type.JSON) args = lv.subList(2, lv.size()); } } - final int counts = ((CarpetScriptHost) c.host).scriptServer().events.signalEvent(eventName, cc, player, args); + int counts = ((CarpetScriptHost) c.host).scriptServer().events.signalEvent(eventName, cc, player, args); if (counts < 0) { return Value.NULL; @@ -1133,32 +1133,32 @@ else if (fdesc.type == FileArgument.Type.JSON) { throw new InternalExpressionException("'nbt_storage' requires 0, 1 or 2 arguments."); } - final CarpetContext cc = (CarpetContext) c; - final CommandStorage storage = cc.server().getCommandStorage(); - if (lv.size() == 0) + CarpetContext cc = (CarpetContext) c; + CommandStorage storage = cc.server().getCommandStorage(); + if (lv.isEmpty()) { - return ListValue.wrap(storage.keys().map(i -> new StringValue(nameFromRegistryId(i)))); + return ListValue.wrap(storage.keys().map(NBTSerializableValue::nameFromRegistryId)); } - final String key = lv.get(0).getString(); - final CompoundTag old_nbt = storage.get(InputValidator.identifierOf(key)); + String key = lv.get(0).getString(); + CompoundTag oldNbt = storage.get(InputValidator.identifierOf(key)); if (lv.size() == 2) { - final Value nbt = lv.get(1); - final NBTSerializableValue new_nbt = (nbt instanceof final NBTSerializableValue nbtsv) + Value nbt = lv.get(1); + NBTSerializableValue newNbt = (nbt instanceof final NBTSerializableValue nbtsv) ? nbtsv - : NBTSerializableValue.parseString(nbt.getString(), true); - storage.set(InputValidator.identifierOf(key), new_nbt.getCompoundTag()); + : NBTSerializableValue.parseStringOrFail(nbt.getString()); + storage.set(InputValidator.identifierOf(key), newNbt.getCompoundTag()); } - return NBTSerializableValue.of(old_nbt); + return NBTSerializableValue.of(oldNbt); }); // script run create_datapack('foo', {'foo' -> {'bar.json' -> {'c' -> true,'d' -> false,'e' -> {'foo' -> [1,2,3]},'a' -> 'foobar','b' -> 5}}}) expression.addContextFunction("create_datapack", 2, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final String origName = lv.get(0).getString(); - final String name = InputValidator.validateSimpleString(origName, true); - final MinecraftServer server = cc.server(); - for (final String dpName : server.getPackRepository().getAvailableIds()) + CarpetContext cc = (CarpetContext) c; + String origName = lv.get(0).getString(); + String name = InputValidator.validateSimpleString(origName, true); + MinecraftServer server = cc.server(); + for (String dpName : server.getPackRepository().getAvailableIds()) { if (dpName.equalsIgnoreCase("file/" + name + ".zip") || dpName.equalsIgnoreCase("file/" + name)) @@ -1167,26 +1167,26 @@ else if (fdesc.type == FileArgument.Type.JSON) } } - final Value dpdata = lv.get(1); + Value dpdata = lv.get(1); if (!(dpdata instanceof final MapValue dpMap)) { throw new InternalExpressionException("datapack data needs to be a valid map type"); } - final PackRepository packManager = server.getPackRepository(); - final Path dbFloder = server.getWorldPath(LevelResource.DATAPACK_DIR); - final Path packFloder = dbFloder.resolve(name + ".zip"); + 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; } - final Boolean[] successful = new Boolean[]{true}; + Boolean[] successful = new Boolean[]{true}; server.executeBlocking(() -> { try { - try (final FileSystem zipfs = FileSystems.newFileSystem(URI.create("jar:" + packFloder.toUri().toString()), Map.of("create", "true"))) + try (FileSystem zipfs = FileSystems.newFileSystem(URI.create("jar:" + packFloder.toUri()), Map.of("create", "true"))) { - final Path zipRoot = zipfs.getPath("/"); + 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.getCurrentVersion().getPackVersion(PackType.SERVER_DATA)), @@ -1197,12 +1197,12 @@ else if (fdesc.type == FileArgument.Type.JSON) walkTheDPMap(dpMap, zipRoot); } packManager.reload(); - final Pack resourcePackProfile = packManager.getPack("file/" + name + ".zip"); + Pack resourcePackProfile = packManager.getPack("file/" + name + ".zip"); if (resourcePackProfile == null || packManager.getSelectedPacks().contains(resourcePackProfile)) { throw new IOException(); } - final List list = Lists.newArrayList(packManager.getSelectedPacks()); + List list = Lists.newArrayList(packManager.getSelectedPacks()); resourcePackProfile.getDefaultPosition().insert(list, resourcePackProfile, p -> p, false); @@ -1216,14 +1216,14 @@ else if (fdesc.type == FileArgument.Type.JSON) throw new IOException(); } } - catch (final IOException e) + catch (IOException e) { successful[0] = false; try { PathUtils.delete(packFloder); } - catch (final IOException ignored) + catch (IOException ignored) { throw new InternalExpressionException("Failed to install a datapack and failed to clean up after it"); } @@ -1234,28 +1234,28 @@ else if (fdesc.type == FileArgument.Type.JSON) }); expression.addContextFunction("enable_hidden_dimensions", 0, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; + CarpetContext cc = (CarpetContext) c; cc.host.issueDeprecation("enable_hidden_dimensions in 1.18.2 and 1.19+"); return Value.NULL; }); } - private static void zipValueToJson(final Path path, final Value output) throws IOException + private static void zipValueToJson(Path path, Value output) throws IOException { - final JsonElement element = output.toJson(); + JsonElement element = output.toJson(); if (element == null) { throw new InternalExpressionException("Cannot interpret " + output.getPrettyString() + " as a json object"); } - final String string = GSON.toJson(element); + String string = GSON.toJson(element); Files.createDirectories(path.getParent()); - final BufferedWriter bufferedWriter = Files.newBufferedWriter(path); + BufferedWriter bufferedWriter = Files.newBufferedWriter(path); Throwable incident = null; try { bufferedWriter.write(string); } - catch (final Throwable shitHappened) + catch (Throwable shitHappened) { incident = shitHappened; throw shitHappened; @@ -1268,7 +1268,7 @@ private static void zipValueToJson(final Path path, final Value output) throws I { bufferedWriter.close(); } - catch (final Throwable otherShitHappened) + catch (Throwable otherShitHappened) { incident.addSuppressed(otherShitHappened); } @@ -1280,11 +1280,11 @@ private static void zipValueToJson(final Path path, final Value output) throws I } } - private static void zipValueToText(final Path path, final Value output) throws IOException + private static void zipValueToText(Path path, Value output) throws IOException { - final List toJoin; - final String string; - final String delimiter = System.lineSeparator(); + List toJoin; + String string; + String delimiter = System.lineSeparator(); // i dont know it shoule be \n or System.lineSeparator if (output instanceof LazyListValue lazyListValue) { @@ -1303,13 +1303,13 @@ else if (output instanceof ListValue listValue) Files.createDirectories(path.getParent()); - final BufferedWriter bufferedWriter = Files.newBufferedWriter(path); + BufferedWriter bufferedWriter = Files.newBufferedWriter(path); Throwable incident = null; try { bufferedWriter.write(string); } - catch (final Throwable shitHappened) + catch (Throwable shitHappened) { incident = shitHappened; throw shitHappened; @@ -1322,7 +1322,7 @@ else if (output instanceof ListValue listValue) { bufferedWriter.close(); } - catch (final Throwable otherShitHappened) + catch (Throwable otherShitHappened) { incident.addSuppressed(otherShitHappened); } @@ -1334,34 +1334,27 @@ else if (output instanceof ListValue listValue) } } - private static void zipValueToNBT(final Path path, final Value output) throws IOException + private static void zipValueToNBT(Path path, Value output) throws IOException { - final NBTSerializableValue tagValue = (output instanceof NBTSerializableValue nbtSerializableValue) + NBTSerializableValue tagValue = (output instanceof NBTSerializableValue nbtSerializableValue) ? nbtSerializableValue : new NBTSerializableValue(output.getString()); - final Tag tag = tagValue.getTag(); + Tag tag = tagValue.getTag(); Files.createDirectories(path.getParent()); - try + if (tag instanceof final CompoundTag cTag) { - if (tag instanceof final CompoundTag cTag) - { - NbtIo.writeCompressed(cTag, Files.newOutputStream(path)); - } - } - catch (final Throwable shitHappened) - { - throw shitHappened; + NbtIo.writeCompressed(cTag, Files.newOutputStream(path)); } } - private static void walkTheDPMap(final MapValue node, final Path path) throws IOException + private static void walkTheDPMap(MapValue node, Path path) throws IOException { - final Map items = node.getMap(); - for (final Map.Entry entry : items.entrySet()) + Map items = node.getMap(); + for (Map.Entry entry : items.entrySet()) { - final Value val = entry.getValue(); - final String strkey = entry.getKey().getString(); - final Path child = path.resolve(strkey); + Value val = entry.getValue(); + String strkey = entry.getKey().getString(); + Path child = path.resolve(strkey); if (strkey.endsWith(".json")) { zipValueToJson(child, val); @@ -1386,9 +1379,10 @@ else if (strkey.endsWith(".nbt")) } } - private static Stat getStat(final StatType type, final ResourceLocation id) + @Nullable + private static Stat getStat(StatType type, ResourceLocation id) { - final T key = type.getRegistry().get(id); + T key = type.getRegistry().get(id); if (key == null || !type.contains(key)) { return null; diff --git a/src/main/java/carpet/script/api/BlockIterators.java b/src/main/java/carpet/script/api/BlockIterators.java index e171632973..e6061e02dc 100644 --- a/src/main/java/carpet/script/api/BlockIterators.java +++ b/src/main/java/carpet/script/api/BlockIterators.java @@ -31,7 +31,7 @@ public class BlockIterators { - public static void apply(final Expression expression) + public static void apply(Expression expression) { // lazy cause of lazy expression expression.addLazyFunction("scan", (c, t, llv) -> @@ -40,12 +40,12 @@ public static void apply(final Expression expression) { throw new InternalExpressionException("'scan' needs many more arguments"); } - final List lv = Fluff.AbstractFunction.unpackLazy(llv.subList(0, llv.size() - 1), c, Context.NONE); - final CarpetContext cc = (CarpetContext) c; - final BlockArgument centerLocator = BlockArgument.findIn(cc, lv, 0); + List lv = Fluff.AbstractFunction.unpackLazy(llv.subList(0, llv.size() - 1), c, Context.NONE); + CarpetContext cc = (CarpetContext) c; + BlockArgument centerLocator = BlockArgument.findIn(cc, lv, 0); Vector3Argument rangeLocator = Vector3Argument.findIn(lv, centerLocator.offset); - final BlockPos center = centerLocator.block.getPos(); - final Vec3i range; + BlockPos center = centerLocator.block.getPos(); + Vec3i range; if (rangeLocator.fromBlock) { @@ -80,50 +80,50 @@ public static void apply(final Expression expression) { throw new InternalExpressionException("'scan' takes two, or three block positions, and an expression: " + lv.size() + " " + rangeLocator.offset); } - final LazyValue expr = llv.get(rangeLocator.offset); - - final int cx = center.getX(); - final int cy = center.getY(); - final int cz = center.getZ(); - final int xrange = range.getX(); - final int yrange = range.getY(); - final int zrange = range.getZ(); - final int xprange = upperRange.getX(); - final int yprange = upperRange.getY(); - final int zprange = upperRange.getZ(); + LazyValue expr = llv.get(rangeLocator.offset); + + int cx = center.getX(); + int cy = center.getY(); + int cz = center.getZ(); + int xrange = range.getX(); + int yrange = range.getY(); + int zrange = range.getZ(); + int xprange = upperRange.getX(); + int yprange = upperRange.getY(); + int zprange = upperRange.getZ(); //saving outer scope - final LazyValue _x = c.getVariable("_x"); - final LazyValue _y = c.getVariable("_y"); - final LazyValue _z = c.getVariable("_z"); - final LazyValue __ = c.getVariable("_"); + LazyValue xVal = c.getVariable("_x"); + LazyValue yVal = c.getVariable("_y"); + LazyValue zVal = c.getVariable("_z"); + LazyValue defaultVal = c.getVariable("_"); int sCount = 0; outer: for (int y = cy - yrange; y <= cy + yprange; y++) { - final int yFinal = y; - c.setVariable("_y", (c_, t_) -> new NumericValue(yFinal).bindTo("_y")); + int yFinal = y; + c.setVariable("_y", (ct, tt) -> new NumericValue(yFinal).bindTo("_y")); for (int x = cx - xrange; x <= cx + xprange; x++) { - final int xFinal = x; - c.setVariable("_x", (c_, t_) -> new NumericValue(xFinal).bindTo("_x")); + int xFinal = x; + c.setVariable("_x", (ct, tt) -> new NumericValue(xFinal).bindTo("_x")); for (int z = cz - zrange; z <= cz + zprange; z++) { - final int zFinal = z; + int zFinal = z; - c.setVariable("_z", (c_, t_) -> new NumericValue(zFinal).bindTo("_z")); - final Value blockValue = BlockValue.fromCoords(((CarpetContext) c), xFinal, yFinal, zFinal).bindTo("_"); - c.setVariable("_", (cc_, t_c) -> blockValue); + c.setVariable("_z", (ct, tt) -> new NumericValue(zFinal).bindTo("_z")); + Value blockValue = BlockValue.fromCoords(((CarpetContext) c), xFinal, yFinal, zFinal).bindTo("_"); + c.setVariable("_", (ct, tt) -> blockValue); Value result; try { result = expr.evalValue(c, t); } - catch (final ContinueStatement notIgnored) + catch (ContinueStatement notIgnored) { result = notIgnored.retval; } - catch (final BreakStatement notIgnored) + catch (BreakStatement notIgnored) { break outer; } @@ -135,74 +135,74 @@ public static void apply(final Expression expression) } } //restoring outer scope - c.setVariable("_x", _x); - c.setVariable("_y", _y); - c.setVariable("_z", _z); - c.setVariable("_", __); - final int finalSCount = sCount; - return (c_, t_) -> new NumericValue(finalSCount); + c.setVariable("_x", xVal); + c.setVariable("_y", yVal); + c.setVariable("_z", zVal); + c.setVariable("_", defaultVal); + int finalSCount = sCount; + return (ct, tt) -> new NumericValue(finalSCount); }); // must be lazy expression.addLazyFunction("volume", (c, t, llv) -> { - final CarpetContext cc = (CarpetContext) c; + CarpetContext cc = (CarpetContext) c; if (llv.size() < 3) { throw new InternalExpressionException("'volume' needs many more arguments"); } - final List lv = Fluff.AbstractFunction.unpackLazy(llv.subList(0, llv.size() - 1), c, Context.NONE); - - final BlockArgument pos1Locator = BlockArgument.findIn(cc, lv, 0); - final BlockArgument pos2Locator = BlockArgument.findIn(cc, lv, pos1Locator.offset); - final BlockPos pos1 = pos1Locator.block.getPos(); - final BlockPos pos2 = pos2Locator.block.getPos(); - - final int x1 = pos1.getX(); - final int y1 = pos1.getY(); - final int z1 = pos1.getZ(); - final int x2 = pos2.getX(); - final int y2 = pos2.getY(); - final int z2 = pos2.getZ(); - final int minx = min(x1, x2); - final int miny = min(y1, y2); - final int minz = min(z1, z2); - final int maxx = max(x1, x2); - final int maxy = max(y1, y2); - final int maxz = max(z1, z2); - final LazyValue expr = llv.get(pos2Locator.offset); + List lv = Fluff.AbstractFunction.unpackLazy(llv.subList(0, llv.size() - 1), c, Context.NONE); + + BlockArgument pos1Locator = BlockArgument.findIn(cc, lv, 0); + BlockArgument pos2Locator = BlockArgument.findIn(cc, lv, pos1Locator.offset); + BlockPos pos1 = pos1Locator.block.getPos(); + BlockPos pos2 = pos2Locator.block.getPos(); + + int x1 = pos1.getX(); + int y1 = pos1.getY(); + int z1 = pos1.getZ(); + int x2 = pos2.getX(); + int y2 = pos2.getY(); + int z2 = pos2.getZ(); + int minx = min(x1, x2); + int miny = min(y1, y2); + int minz = min(z1, z2); + int maxx = max(x1, x2); + int maxy = max(y1, y2); + int maxz = max(z1, z2); + LazyValue expr = llv.get(pos2Locator.offset); //saving outer scope - final LazyValue _x = c.getVariable("_x"); - final LazyValue _y = c.getVariable("_y"); - final LazyValue _z = c.getVariable("_z"); - final LazyValue __ = c.getVariable("_"); + LazyValue xVal = c.getVariable("_x"); + LazyValue yVal = c.getVariable("_y"); + LazyValue zVal = c.getVariable("_z"); + LazyValue defaultVal = c.getVariable("_"); int sCount = 0; outer: for (int y = miny; y <= maxy; y++) { - final int yFinal = y; - c.setVariable("_y", (c_, t_) -> new NumericValue(yFinal).bindTo("_y")); + int yFinal = y; + c.setVariable("_y", (ct, tt) -> new NumericValue(yFinal).bindTo("_y")); for (int x = minx; x <= maxx; x++) { - final int xFinal = x; - c.setVariable("_x", (c_, t_) -> new NumericValue(xFinal).bindTo("_x")); + int xFinal = x; + c.setVariable("_x", (ct, tt) -> new NumericValue(xFinal).bindTo("_x")); for (int z = minz; z <= maxz; z++) { - final int zFinal = z; - c.setVariable("_z", (c_, t_) -> new NumericValue(zFinal).bindTo("_z")); - final Value blockValue = BlockValue.fromCoords(((CarpetContext) c), xFinal, yFinal, zFinal).bindTo("_"); - c.setVariable("_", (cc_, t_c) -> blockValue); + int zFinal = z; + c.setVariable("_z", (ct, tt) -> new NumericValue(zFinal).bindTo("_z")); + Value blockValue = BlockValue.fromCoords(((CarpetContext) c), xFinal, yFinal, zFinal).bindTo("_"); + c.setVariable("_", (ct, tt) -> blockValue); Value result; try { result = expr.evalValue(c, t); } - catch (final ContinueStatement notIgnored) + catch (ContinueStatement notIgnored) { result = notIgnored.retval; } - catch (final BreakStatement notIgnored) + catch (BreakStatement notIgnored) { break outer; } @@ -214,49 +214,49 @@ public static void apply(final Expression expression) } } //restoring outer scope - c.setVariable("_x", _x); - c.setVariable("_y", _y); - c.setVariable("_z", _z); - c.setVariable("_", __); - final int finalSCount = sCount; - return (c_, t_) -> new NumericValue(finalSCount); + c.setVariable("_x", xVal); + c.setVariable("_y", yVal); + c.setVariable("_z", zVal); + c.setVariable("_", defaultVal); + int finalSCount = sCount; + return (ct, tt) -> new NumericValue(finalSCount); }); expression.addContextFunction("neighbours", -1, (c, t, lv) -> { - final BlockPos center = BlockArgument.findIn((CarpetContext) c, lv, 0).block.getPos(); - final ServerLevel world = ((CarpetContext) c).level(); - - final List neighbours = new ArrayList<>(); - 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())); - neighbours.add(new BlockValue(null, world, center.west())); + BlockPos center = BlockArgument.findIn((CarpetContext) c, lv, 0).block.getPos(); + ServerLevel world = ((CarpetContext) c).level(); + + List neighbours = new ArrayList<>(); + neighbours.add(new BlockValue(world, center.above())); + neighbours.add(new BlockValue(world, center.below())); + neighbours.add(new BlockValue(world, center.north())); + neighbours.add(new BlockValue(world, center.south())); + neighbours.add(new BlockValue(world, center.east())); + neighbours.add(new BlockValue(world, center.west())); return ListValue.wrap(neighbours); }); expression.addContextFunction("rect", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final int cx; - final int cy; - final int cz; - final int sminx; - final int sminy; - final int sminz; - final int smaxx; - final int smaxy; - final int smaxz; - final BlockArgument cposLocator = BlockArgument.findIn(cc, lv, 0); - final BlockPos cpos = cposLocator.block.getPos(); + CarpetContext cc = (CarpetContext) c; + int cx; + int cy; + int cz; + int sminx; + int sminy; + int sminz; + int smaxx; + int smaxy; + int smaxz; + BlockArgument cposLocator = BlockArgument.findIn(cc, lv, 0); + BlockPos cpos = cposLocator.block.getPos(); cx = cpos.getX(); cy = cpos.getY(); cz = cpos.getZ(); if (lv.size() > cposLocator.offset) { - final Vector3Argument diffLocator = Vector3Argument.findIn(lv, cposLocator.offset); + Vector3Argument diffLocator = Vector3Argument.findIn(lv, cposLocator.offset); if (diffLocator.fromBlock) { sminx = Mth.floor(abs(diffLocator.vec.x - cx)); @@ -271,7 +271,7 @@ public static void apply(final Expression expression) } if (lv.size() > diffLocator.offset) { - final Vector3Argument posDiff = Vector3Argument.findIn(lv, diffLocator.offset); + Vector3Argument posDiff = Vector3Argument.findIn(lv, diffLocator.offset); if (posDiff.fromBlock) { smaxx = Mth.floor(abs(posDiff.vec.x - cx)); @@ -328,7 +328,7 @@ public boolean hasNext() @Override public Value next() { - final Value r = BlockValue.fromCoords(cc, x, y, z); + Value r = BlockValue.fromCoords(cc, x, y, z); //possibly reroll context x++; if (x > maxx) @@ -371,16 +371,16 @@ public String getString() expression.addContextFunction("diamond", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; + CarpetContext cc = (CarpetContext) c; - final BlockArgument cposLocator = BlockArgument.findIn((CarpetContext) c, lv, 0); - final BlockPos cpos = cposLocator.block.getPos(); + BlockArgument cposLocator = BlockArgument.findIn((CarpetContext) c, lv, 0); + BlockPos cpos = cposLocator.block.getPos(); - final int cx; - final int cy; - final int cz; - final int width; - final int height; + int cx; + int cy; + int cz; + int width; + int height; try { cx = cpos.getX(); @@ -414,7 +414,7 @@ else if (lv.size() == 2 + cposLocator.offset) throw new InternalExpressionException("Incorrect number of arguments for 'diamond'"); } } - catch (final ClassCastException ignored) + catch (ClassCastException ignored) { throw new InternalExpressionException("Attempted to pass a non-number to 'diamond'"); } @@ -445,7 +445,7 @@ public Value next() } // x = 3-|i-6| // z = |( (i-3)%12-6|-3 - final Value block = BlockValue.fromCoords(cc, cx + (curradius - abs(curpos - 2 * curradius)), cy, cz - curradius + abs(abs(curpos - curradius) % (4 * curradius) - 2 * curradius)); + Value block = BlockValue.fromCoords(cc, cx + (curradius - abs(curpos - 2 * curradius)), cy, cz - curradius + abs(abs(curpos - curradius) % (4 * curradius) - 2 * curradius)); curpos++; if (curpos >= curradius * 4) { @@ -503,7 +503,7 @@ public Value next() // x = 3-|i-6| // z = |( (i-3)%12-6|-3 - final Value block = BlockValue.fromCoords(cc, cx + (curradius - abs(curpos - 2 * curradius)), cy + curheight, cz - curradius + abs(abs(curpos - curradius) % (4 * curradius) - 2 * curradius)); + Value block = BlockValue.fromCoords(cc, cx + (curradius - abs(curpos - 2 * curradius)), cy + curheight, cz - curradius + abs(abs(curpos - curradius) % (4 * curradius) - 2 * curradius)); curpos++; if (curpos >= curradius * 4) { diff --git a/src/main/java/carpet/script/api/Entities.java b/src/main/java/carpet/script/api/Entities.java index ed917f2ef0..c4919f6f4b 100644 --- a/src/main/java/carpet/script/api/Entities.java +++ b/src/main/java/carpet/script/api/Entities.java @@ -42,10 +42,10 @@ public class Entities { - private static ListValue getPlayersFromWorldMatching(final Context c, final Predicate condition) + private static ListValue getPlayersFromWorldMatching(Context c, Predicate condition) { - final List ret = new ArrayList<>(); - for (final ServerPlayer player : ((CarpetContext) c).level().players()) + List ret = new ArrayList<>(); + for (ServerPlayer player : ((CarpetContext) c).level().players()) { if (condition.test(player)) { @@ -55,45 +55,45 @@ private static ListValue getPlayersFromWorldMatching(final Context c, final Pred return ListValue.wrap(ret); } - public static void apply(final Expression expression) + public static void apply(Expression expression) { expression.addContextFunction("player", -1, (c, t, lv) -> { - if (lv.size() == 0) + if (lv.isEmpty()) { - final CarpetContext cc = (CarpetContext) c; + CarpetContext cc = (CarpetContext) c; if (cc.host.user != null) { - final ServerPlayer player = cc.server().getPlayerList().getPlayerByName(cc.host.user); + ServerPlayer player = cc.server().getPlayerList().getPlayerByName(cc.host.user); return EntityValue.of(player); } - final Entity callingEntity = cc.source().getEntity(); + Entity callingEntity = cc.source().getEntity(); if (callingEntity instanceof Player) { return EntityValue.of(callingEntity); } - final Vec3 pos = ((CarpetContext) c).source().getPosition(); - final Player closestPlayer = ((CarpetContext) c).level().getNearestPlayer(pos.x, pos.y, pos.z, -1.0, EntitySelector.ENTITY_STILL_ALIVE); + Vec3 pos = ((CarpetContext) c).source().getPosition(); + Player closestPlayer = ((CarpetContext) c).level().getNearestPlayer(pos.x, pos.y, pos.z, -1.0, EntitySelector.ENTITY_STILL_ALIVE); return EntityValue.of(closestPlayer); } - final String playerName = lv.get(0).getString(); + String playerName = lv.get(0).getString(); return switch (playerName) { case "all" -> { - final List ret = new ArrayList<>(); - for (final ServerPlayer player : ((CarpetContext) c).server().getPlayerList().getPlayers()) + List ret = new ArrayList<>(); + for (ServerPlayer player : ((CarpetContext) c).server().getPlayerList().getPlayers()) { ret.add(new EntityValue(player)); } yield ListValue.wrap(ret); } case "*" -> getPlayersFromWorldMatching(c, p -> true); - case "survival" -> getPlayersFromWorldMatching(c, p -> p.gameMode.isSurvival()); // todo assert correct + case "survival" -> getPlayersFromWorldMatching(c, p -> p.gameMode.isSurvival()); // includes adventure case "creative" -> getPlayersFromWorldMatching(c, ServerPlayer::isCreative); case "spectating" -> getPlayersFromWorldMatching(c, ServerPlayer::isSpectator); case "!spectating" -> getPlayersFromWorldMatching(c, p -> !p.isSpectator()); default -> { - final ServerPlayer player = ((CarpetContext) c).server().getPlayerList().getPlayerByName(playerName); + ServerPlayer player = ((CarpetContext) c).server().getPlayerList().getPlayerByName(playerName); yield player != null ? new EntityValue(player) : Value.NULL; } }; @@ -101,28 +101,28 @@ public static void apply(final Expression expression) expression.addContextFunction("spawn", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; + CarpetContext cc = (CarpetContext) c; if (lv.size() < 2) { throw new InternalExpressionException("'spawn' function takes mob name, and position to spawn"); } - final String entityString = lv.get(0).getString(); - final ResourceLocation entityId; + String entityString = lv.get(0).getString(); + ResourceLocation entityId; try { entityId = ResourceLocation.read(new StringReader(entityString)); - final EntityType type = cc.registry(Registries.ENTITY_TYPE).getOptional(entityId).orElse(null); + EntityType type = cc.registry(Registries.ENTITY_TYPE).getOptional(entityId).orElse(null); if (type == null || !type.canSummon()) { return Value.NULL; } } - catch (final CommandSyntaxException ignored) + catch (CommandSyntaxException ignored) { return Value.NULL; } - final Vector3Argument position = Vector3Argument.findIn(lv, 1); + Vector3Argument position = Vector3Argument.findIn(lv, 1); if (position.fromBlock) { position.vec = position.vec.subtract(0, 0.5, 0); @@ -131,20 +131,20 @@ public static void apply(final Expression expression) boolean hasTag = false; if (lv.size() > position.offset) { - final Value nbt = lv.get(position.offset); - final NBTSerializableValue v = (nbt instanceof final NBTSerializableValue nbtsv) + Value nbt = lv.get(position.offset); + NBTSerializableValue v = (nbt instanceof final NBTSerializableValue nbtsv) ? nbtsv - : NBTSerializableValue.parseString(nbt.getString(), true); + : NBTSerializableValue.parseStringOrFail(nbt.getString()); hasTag = true; tag = v.getCompoundTag(); } tag.putString("id", entityId.toString()); - final Vec3 vec3d = position.vec; + Vec3 vec3d = position.vec; - final ServerLevel serverWorld = cc.level(); - final Entity entity = EntityType.loadEntityRecursive(tag, serverWorld, e -> { + ServerLevel serverWorld = cc.level(); + Entity entity = EntityType.loadEntityRecursive(tag, serverWorld, e -> { e.moveTo(vec3d.x, vec3d.y, vec3d.z, e.getYRot(), e.getXRot()); - return !serverWorld.addWithUUID(e) ? null : e; + return e; }); if (entity == null) { @@ -154,12 +154,17 @@ public static void apply(final Expression expression) { mob.finalizeSpawn(serverWorld, serverWorld.getCurrentDifficultyAt(entity.blockPosition()), MobSpawnType.COMMAND, null, null); } + if (!serverWorld.tryAddFreshEntityWithPassengers(entity)) + { + entity.discard(); + return Value.NULL; + } return new EntityValue(entity); }); expression.addContextFunction("entity_id", 1, (c, t, lv) -> { - final Value who = lv.get(0); + Value who = lv.get(0); if (who instanceof final NumericValue numericValue) { return EntityValue.of(((CarpetContext) c).level().getEntity((int) numericValue.getLong())); @@ -169,10 +174,10 @@ public static void apply(final Expression expression) expression.addContextFunction("entity_list", 1, (c, t, lv) -> { - final String who = lv.get(0).getString(); - final CommandSourceStack source = ((CarpetContext) c).source(); - final EntityValue.EntityClassDescriptor eDesc = EntityValue.getEntityDescriptor(who, source.getServer()); - final List entityList = source.getLevel().getEntities(eDesc.directType, eDesc.filteringPredicate); + String who = lv.get(0).getString(); + CommandSourceStack source = ((CarpetContext) c).source(); + EntityValue.EntityClassDescriptor eDesc = EntityValue.getEntityDescriptor(who, source.getServer()); + List entityList = source.getLevel().getEntities(eDesc.directType, eDesc.filteringPredicate); return ListValue.wrap(entityList.stream().map(EntityValue::new)); }); @@ -182,41 +187,41 @@ public static void apply(final Expression expression) { throw new InternalExpressionException("'entity_area' requires entity type, center and range arguments"); } - final String who = lv.get(0).getString(); - final CarpetContext cc = (CarpetContext) c; - final Vector3Argument centerLocator = Vector3Argument.findIn(lv, 1, false, true); + String who = lv.get(0).getString(); + CarpetContext cc = (CarpetContext) c; + Vector3Argument centerLocator = Vector3Argument.findIn(lv, 1, false, true); - final AABB centerBox; + AABB centerBox; if (centerLocator.entity != null) { centerBox = centerLocator.entity.getBoundingBox(); } else { - final Vec3 center = centerLocator.vec; + Vec3 center = centerLocator.vec; if (centerLocator.fromBlock) { center.add(0.5, 0.5, 0.5); } centerBox = new AABB(center, center); } - final Vector3Argument rangeLocator = Vector3Argument.findIn(lv, centerLocator.offset); + Vector3Argument rangeLocator = Vector3Argument.findIn(lv, centerLocator.offset); if (rangeLocator.fromBlock) { throw new InternalExpressionException("Range of 'entity_area' cannot come from a block argument"); } - final Vec3 range = rangeLocator.vec; - final AABB area = centerBox.inflate(range.x, range.y, range.z); - final EntityValue.EntityClassDescriptor eDesc = EntityValue.getEntityDescriptor(who, cc.server()); - final List entityList = cc.level().getEntities(eDesc.directType, area, eDesc.filteringPredicate); + Vec3 range = rangeLocator.vec; + AABB area = centerBox.inflate(range.x, range.y, range.z); + EntityValue.EntityClassDescriptor eDesc = EntityValue.getEntityDescriptor(who, cc.server()); + List entityList = cc.level().getEntities(eDesc.directType, area, eDesc.filteringPredicate); return ListValue.wrap(entityList.stream().map(EntityValue::new)); }); expression.addContextFunction("entity_selector", -1, (c, t, lv) -> { - final String selector = lv.get(0).getString(); - final List retlist = new ArrayList<>(); - for (final Entity e : EntityValue.getEntitiesFromSelector(((CarpetContext) c).source(), selector)) + String selector = lv.get(0).getString(); + List retlist = new ArrayList<>(); + for (Entity e : EntityValue.getEntitiesFromSelector(((CarpetContext) c).source(), selector)) { retlist.add(new EntityValue(e)); } @@ -229,12 +234,12 @@ public static void apply(final Expression expression) { throw new InternalExpressionException("'query' takes entity as a first argument, and queried feature as a second"); } - final Value v = lv.get(0); + Value v = lv.get(0); if (!(v instanceof final EntityValue ev)) { throw new InternalExpressionException("First argument to query should be an entity"); } - final String what = lv.get(1).getString().toLowerCase(Locale.ROOT); + String what = lv.get(1).getString().toLowerCase(Locale.ROOT); if (what.equals("tags")) { c.host.issueDeprecation("'tags' for entity querying"); @@ -254,12 +259,12 @@ public static void apply(final Expression expression) { throw new InternalExpressionException("'modify' takes entity as a first argument, and queried feature as a second"); } - final Value v = lv.get(0); + Value v = lv.get(0); if (!(v instanceof final EntityValue ev)) { throw new InternalExpressionException("First argument to modify should be an entity"); } - final String what = lv.get(1).getString(); + String what = lv.get(1).getString(); switch (lv.size()) { case 2 -> ev.set(what, null); @@ -275,7 +280,7 @@ public static void apply(final Expression expression) { throw new InternalExpressionException("'entity_types' requires one or no arguments"); } - final String desc = (lv.size() == 1) ? lv.get(0).getString() : "*"; + String desc = (lv.size() == 1) ? lv.get(0).getString() : "*"; return EntityValue.getEntityDescriptor(desc, ((CarpetContext) c).server()).listValue(((CarpetContext) c).registryAccess()); }); @@ -285,14 +290,14 @@ public static void apply(final Expression expression) { throw new InternalExpressionException("'entity_load_handler' required the entity type, and a function to call"); } - final Value entityValue = lv.get(0); - final List descriptors = (entityValue instanceof final ListValue list) + Value entityValue = lv.get(0); + List descriptors = (entityValue instanceof final ListValue list) ? list.getItems().stream().map(Value::getString).toList() : Collections.singletonList(entityValue.getString()); - final Set> types = new HashSet<>(); + Set> types = new HashSet<>(); descriptors.forEach(s -> types.addAll(EntityValue.getEntityDescriptor(s, ((CarpetContext) c).server()).types)); - final FunctionArgument funArg = FunctionArgument.findIn(c, expression.module, lv, 1, true, false); - final CarpetEventServer events = ((CarpetScriptHost) c.host).scriptServer().events; + FunctionArgument funArg = FunctionArgument.findIn(c, expression.module, lv, 1, true, false); + CarpetEventServer events = ((CarpetScriptHost) c.host).scriptServer().events; if (funArg.function == null) { types.forEach(et -> events.removeBuiltInEvent(CarpetEventServer.Event.getEntityLoadEventName(et), (CarpetScriptHost) c.host)); @@ -301,7 +306,7 @@ public static void apply(final Expression expression) else { ///compat - final int numberOfArguments = funArg.function.getArguments().size() - funArg.args.size(); + int numberOfArguments = funArg.function.getArguments().size() - funArg.args.size(); if (numberOfArguments == 1) { c.host.issueDeprecation("entity_load_handler() with single argument callback"); @@ -322,14 +327,14 @@ public static void apply(final Expression expression) { throw new InternalExpressionException("'entity_event' requires at least 3 arguments, entity, event to be handled, and function name, with optional arguments"); } - final Value v = lv.get(0); + Value v = lv.get(0); if (!(v instanceof final EntityValue ev)) { throw new InternalExpressionException("First argument to entity_event should be an entity"); } - final String what = lv.get(1).getString(); + String what = lv.get(1).getString(); - final FunctionArgument funArg = FunctionArgument.findIn(c, expression.module, lv, 2, true, false); + FunctionArgument funArg = FunctionArgument.findIn(c, expression.module, lv, 2, true, false); ev.setEvent((CarpetContext) c, what, funArg.function, funArg.args); diff --git a/src/main/java/carpet/script/api/Inventories.java b/src/main/java/carpet/script/api/Inventories.java index f4aecd84c6..2347f7ca8e 100644 --- a/src/main/java/carpet/script/api/Inventories.java +++ b/src/main/java/carpet/script/api/Inventories.java @@ -24,6 +24,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; +import java.util.Objects; import java.util.Optional; import java.util.Set; @@ -54,7 +55,7 @@ public class Inventories { - public static void apply(final Expression expression) + public static void apply(Expression expression) { expression.addContextFunction("stack_limit", 1, (c, t, lv) -> new NumericValue(NBTSerializableValue.parseItem(lv.get(0).getString(), ((CarpetContext) c).registryAccess()).getItem().getMaxStackSize())); @@ -66,78 +67,82 @@ public static void apply(final Expression expression) expression.addContextFunction("item_list", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final Registry items = cc.registry(Registries.ITEM); - if (lv.size() == 0) + CarpetContext cc = (CarpetContext) c; + Registry items = cc.registry(Registries.ITEM); + if (lv.isEmpty()) { return ListValue.wrap(items.keySet().stream().map(ValueConversions::of)); } - final String tag = lv.get(0).getString(); - final Optional> itemTag = items.getTag(TagKey.create(Registries.ITEM, InputValidator.identifierOf(tag))); - return itemTag.isEmpty() ? Value.NULL : ListValue.wrap(itemTag.get().stream().map(b -> ValueConversions.of(items.getKey(b.value())))); + String tag = lv.get(0).getString(); + Optional> itemTag = items.getTag(TagKey.create(Registries.ITEM, InputValidator.identifierOf(tag))); + return itemTag.isEmpty() ? Value.NULL : ListValue.wrap(itemTag.get().stream().map(b -> items.getKey(b.value())).filter(Objects::nonNull).map(ValueConversions::of)); }); expression.addContextFunction("item_tags", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; + CarpetContext cc = (CarpetContext) c; - final Registry blocks = cc.registry(Registries.ITEM); - if (lv.size() == 0) + Registry blocks = cc.registry(Registries.ITEM); + if (lv.isEmpty()) { return ListValue.wrap(blocks.getTagNames().map(ValueConversions::of)); } - final Item item = NBTSerializableValue.parseItem(lv.get(0).getString(), cc.registryAccess()).getItem(); + Item item = NBTSerializableValue.parseItem(lv.get(0).getString(), cc.registryAccess()).getItem(); if (lv.size() == 1) { return ListValue.wrap(blocks.getTags().filter(e -> e.getSecond().stream().anyMatch(h -> (h.value() == item))).map(e -> ValueConversions.of(e.getFirst()))); } - final String tag = lv.get(1).getString(); - final Optional> tagSet = blocks.getTag(TagKey.create(Registries.ITEM, InputValidator.identifierOf(tag))); + String tag = lv.get(1).getString(); + Optional> tagSet = blocks.getTag(TagKey.create(Registries.ITEM, InputValidator.identifierOf(tag))); return tagSet.isEmpty() ? Value.NULL : BooleanValue.of(tagSet.get().stream().anyMatch(h -> h.value() == item)); }); expression.addContextFunction("recipe_data", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; + CarpetContext cc = (CarpetContext) c; if (lv.size() < 1) { throw new InternalExpressionException("'recipe_data' requires at least one argument"); } - final String recipeName = lv.get(0).getString(); + String recipeName = lv.get(0).getString(); RecipeType type = RecipeType.CRAFTING; if (lv.size() > 1) { - final String recipeType = lv.get(1).getString(); + String recipeType = lv.get(1).getString(); type = cc.registry(Registries.RECIPE_TYPE).get(InputValidator.identifierOf(recipeType)); + if (type == null) + { + throw new InternalExpressionException("Unknown recipe type: "+recipeType); + } } - final List> recipes = Vanilla.RecipeManager_getAllMatching(cc.server().getRecipeManager(), type, InputValidator.identifierOf(recipeName), cc.registryAccess()); + List> recipes = Vanilla.RecipeManager_getAllMatching(cc.server().getRecipeManager(), type, InputValidator.identifierOf(recipeName), cc.registryAccess()); if (recipes.isEmpty()) { return Value.NULL; } - final List recipesOutput = new ArrayList<>(); - final RegistryAccess regs = cc.registryAccess(); - for (final Recipe recipe : recipes) + List recipesOutput = new ArrayList<>(); + RegistryAccess regs = cc.registryAccess(); + for (Recipe recipe : recipes) { - final ItemStack result = recipe.getResultItem(regs); - final List ingredientValue = new ArrayList<>(); + ItemStack result = recipe.getResultItem(regs); + List ingredientValue = new ArrayList<>(); recipe.getIngredients().forEach( ingredient -> { // I am flattening ingredient lists per slot. // consider recipe_data('wooden_sword','crafting') and ('iron_nugget', 'blasting') and notice difference // in depths of lists. - final List> stacks = Vanilla.Ingredient_getRecipeStacks(ingredient); + List> stacks = Vanilla.Ingredient_getRecipeStacks(ingredient); if (stacks.isEmpty()) { ingredientValue.add(Value.NULL); } else { - final List alternatives = new ArrayList<>(); + List alternatives = new ArrayList<>(); stacks.forEach(col -> col.stream().map(is -> ValueConversions.of(is, regs)).forEach(alternatives::add)); ingredientValue.add(ListValue.wrap(alternatives)); } }); - final Value recipeSpec; + Value recipeSpec; if (recipe instanceof final ShapedRecipe shapedRecipe) { recipeSpec = ListValue.of( @@ -178,42 +183,41 @@ else if (recipe instanceof CustomRecipe) expression.addContextFunction("crafting_remaining_item", 1, (c, t, v) -> { - final String itemStr = v.get(0).getString(); - final ResourceLocation id = InputValidator.identifierOf(itemStr); - final Registry registry = ((CarpetContext) c).registry(Registries.ITEM); - final Item item = registry.getOptional(id).orElseThrow(() -> new ThrowStatement(itemStr, Throwables.UNKNOWN_ITEM)); - return !item.hasCraftingRemainingItem() - ? Value.NULL - : new StringValue(NBTSerializableValue.nameFromRegistryId(registry.getKey(item.getCraftingRemainingItem()))); + String itemStr = v.get(0).getString(); + ResourceLocation id = InputValidator.identifierOf(itemStr); + Registry registry = ((CarpetContext) c).registry(Registries.ITEM); + Item item = registry.getOptional(id).orElseThrow(() -> new ThrowStatement(itemStr, Throwables.UNKNOWN_ITEM)); + Item reminder = item.getCraftingRemainingItem(); + return reminder == null ? Value.NULL : NBTSerializableValue.nameFromRegistryId(registry.getKey(reminder)); }); expression.addContextFunction("inventory_size", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); + CarpetContext cc = (CarpetContext) c; + NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); return inventoryLocator == null ? Value.NULL : new NumericValue(inventoryLocator.inventory().getContainerSize()); }); expression.addContextFunction("inventory_has_items", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); + CarpetContext cc = (CarpetContext) c; + NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); return inventoryLocator == null ? Value.NULL : BooleanValue.of(!inventoryLocator.inventory().isEmpty()); }); //inventory_get(, ) -> item_triple expression.addContextFunction("inventory_get", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); + CarpetContext cc = (CarpetContext) c; + NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); if (inventoryLocator == null) { return Value.NULL; } - final RegistryAccess regs = cc.registryAccess(); + RegistryAccess regs = cc.registryAccess(); if (lv.size() == inventoryLocator.offset()) { - final List fullInventory = new ArrayList<>(); + List fullInventory = new ArrayList<>(); for (int i = 0, maxi = inventoryLocator.inventory().getContainerSize(); i < maxi; i++) { fullInventory.add(ValueConversions.of(inventoryLocator.inventory().getItem(i), regs)); @@ -230,8 +234,8 @@ else if (recipe instanceof CustomRecipe) //inventory_set(, , , , ) expression.addContextFunction("inventory_set", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); + CarpetContext cc = (CarpetContext) c; + NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); if (inventoryLocator == null) { return Value.NULL; @@ -240,25 +244,25 @@ else if (recipe instanceof CustomRecipe) { 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(); + int slot = (int) NumericValue.asNumber(lv.get(inventoryLocator.offset())).getLong(); slot = NBTSerializableValue.validateSlot(slot, inventoryLocator.inventory()); if (slot == inventoryLocator.inventory().getContainerSize()) { return Value.NULL; } - final int count = (int) NumericValue.asNumber(lv.get(inventoryLocator.offset() + 1)).getLong(); - final RegistryAccess regs = cc.registryAccess(); + int count = (int) NumericValue.asNumber(lv.get(inventoryLocator.offset() + 1)).getLong(); + RegistryAccess regs = cc.registryAccess(); if (count == 0) { // clear slot - final ItemStack removedStack = inventoryLocator.inventory().removeItemNoUpdate(slot); + ItemStack removedStack = inventoryLocator.inventory().removeItemNoUpdate(slot); syncPlayerInventory(inventoryLocator, slot); return ValueConversions.of(removedStack, regs); } if (lv.size() < inventoryLocator.offset() + 3) { - final ItemStack previousStack = inventoryLocator.inventory().getItem(slot); - final ItemStack newStack = previousStack.copy(); + ItemStack previousStack = inventoryLocator.inventory().getItem(slot); + ItemStack newStack = previousStack.copy(); newStack.setCount(count); inventoryLocator.inventory().setItem(slot, newStack); syncPlayerInventory(inventoryLocator, slot); @@ -267,28 +271,24 @@ else if (recipe instanceof CustomRecipe) CompoundTag nbt = null; // skipping one argument if (lv.size() > inventoryLocator.offset() + 3) { - final Value nbtValue = lv.get(inventoryLocator.offset() + 3); + Value nbtValue = lv.get(inventoryLocator.offset() + 3); if (nbtValue instanceof final NBTSerializableValue nbtsv) { nbt = nbtsv.getCompoundTag(); } - else if (nbtValue.isNull()) - { - nbt = null; - } - else + else if (!nbtValue.isNull()) { nbt = new NBTSerializableValue(nbtValue.getString()).getCompoundTag(); } } - final ItemInput newitem = NBTSerializableValue.parseItem(lv.get(inventoryLocator.offset() + 2).getString(), nbt, cc.registryAccess()); - final ItemStack previousStack = inventoryLocator.inventory().getItem(slot); + ItemInput newitem = NBTSerializableValue.parseItem(lv.get(inventoryLocator.offset() + 2).getString(), nbt, cc.registryAccess()); + ItemStack previousStack = inventoryLocator.inventory().getItem(slot); try { inventoryLocator.inventory().setItem(slot, newitem.createItemStack(count, false)); syncPlayerInventory(inventoryLocator, slot); } - catch (final CommandSyntaxException e) + catch (CommandSyntaxException e) { throw new InternalExpressionException(e.getMessage()); } @@ -298,8 +298,8 @@ else if (nbtValue.isNull()) //inventory_find(, or null (first empty slot), ) -> or null expression.addContextFunction("inventory_find", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); + CarpetContext cc = (CarpetContext) c; + NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); if (inventoryLocator == null) { return Value.NULL; @@ -307,7 +307,7 @@ else if (nbtValue.isNull()) ItemInput itemArg = null; if (lv.size() > inventoryLocator.offset()) { - final Value secondArg = lv.get(inventoryLocator.offset() + 0); + Value secondArg = lv.get(inventoryLocator.offset()); if (!secondArg.isNull()) { itemArg = NBTSerializableValue.parseItem(secondArg.getString(), cc.registryAccess()); @@ -321,7 +321,7 @@ else if (nbtValue.isNull()) startIndex = NBTSerializableValue.validateSlot(startIndex, inventoryLocator.inventory()); for (int i = startIndex, maxi = inventoryLocator.inventory().getContainerSize(); i < maxi; i++) { - final ItemStack stack = inventoryLocator.inventory().getItem(i); + ItemStack stack = inventoryLocator.inventory().getItem(i); if ((itemArg == null && stack.isEmpty()) || (itemArg != null && itemArg.getItem().equals(stack.getItem()))) { return new NumericValue(i); @@ -333,8 +333,8 @@ else if (nbtValue.isNull()) //inventory_remove(, , ) -> bool expression.addContextFunction("inventory_remove", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); + CarpetContext cc = (CarpetContext) c; + NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); if (inventoryLocator == null) { return Value.NULL; @@ -343,7 +343,7 @@ else if (nbtValue.isNull()) { throw new InternalExpressionException("'inventory_remove' requires at least an item to be removed"); } - final ItemInput searchItem = NBTSerializableValue.parseItem(lv.get(inventoryLocator.offset()).getString(), cc.registryAccess()); + ItemInput searchItem = NBTSerializableValue.parseItem(lv.get(inventoryLocator.offset()).getString(), cc.registryAccess()); int amount = 1; if (lv.size() > inventoryLocator.offset() + 1) { @@ -357,12 +357,12 @@ else if (nbtValue.isNull()) } for (int i = 0, maxi = inventoryLocator.inventory().getContainerSize(); i < maxi; i++) { - final ItemStack stack = inventoryLocator.inventory().getItem(i); + ItemStack stack = inventoryLocator.inventory().getItem(i); if (stack.isEmpty() || !stack.getItem().equals(searchItem.getItem())) { continue; } - final int left = stack.getCount() - amount; + int left = stack.getCount() - amount; if (left > 0) { stack.setCount(left); @@ -384,8 +384,8 @@ else if (nbtValue.isNull()) //inventory_drop(, , ) -> entity_item (and sets slot) or null if cannot expression.addContextFunction("drop_item", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); + CarpetContext cc = (CarpetContext) c; + NBTSerializableValue.InventoryLocator inventoryLocator = NBTSerializableValue.locateInventory(cc, lv, 0); if (inventoryLocator == null) { return Value.NULL; @@ -409,7 +409,7 @@ else if (nbtValue.isNull()) { throw new InternalExpressionException("Cannot throw negative number of items"); } - final ItemStack stack = inventoryLocator.inventory().getItem(slot); + ItemStack stack = inventoryLocator.inventory().getItem(slot); if (stack == null || stack.isEmpty()) { return Value.ZERO; @@ -418,30 +418,34 @@ else if (nbtValue.isNull()) { amount = stack.getCount(); } - final ItemStack droppedStack = inventoryLocator.inventory().removeItem(slot, amount); + ItemStack droppedStack = inventoryLocator.inventory().removeItem(slot, amount); if (droppedStack.isEmpty()) { return Value.ZERO; } - final Object owner = inventoryLocator.owner(); - final ItemEntity item; + Object owner = inventoryLocator.owner(); + ItemEntity item; if (owner instanceof final Player player) { item = player.drop(droppedStack, false, true); + if (item == null) + { + return Value.ZERO; + } } else if (owner instanceof LivingEntity livingEntity) { // stolen from LookTargetUtil.give((VillagerEntity)owner, droppedStack, (LivingEntity) owner); - double double_1 = livingEntity.getY() - 0.30000001192092896D + livingEntity.getEyeHeight(); - item = new ItemEntity(livingEntity.level, livingEntity.getX(), double_1, livingEntity.getZ(), droppedStack); - final Vec3 vec3d = livingEntity.getViewVector(1.0F).normalize().scale(0.3);// new Vec3d(0, 0.3, 0); + double dropY = livingEntity.getY() - 0.30000001192092896D + livingEntity.getEyeHeight(); + item = new ItemEntity(livingEntity.level, livingEntity.getX(), dropY, livingEntity.getZ(), droppedStack); + Vec3 vec3d = livingEntity.getViewVector(1.0F).normalize().scale(0.3);// new Vec3d(0, 0.3, 0); item.setDeltaMovement(vec3d); item.setDefaultPickUpDelay(); cc.level().addFreshEntity(item); } else { - final Vec3 point = Vec3.atCenterOf(inventoryLocator.position()); //pos+0.5v + Vec3 point = Vec3.atCenterOf(inventoryLocator.position()); //pos+0.5v item = new ItemEntity(cc.level(), point.x, point.y, point.z, droppedStack); item.setDefaultPickUpDelay(); cc.level().addFreshEntity(item); @@ -455,14 +459,14 @@ else if (owner instanceof LivingEntity livingEntity) { throw new InternalExpressionException("'create_screen' requires at least three arguments"); } - final Value playerValue = lv.get(0); - final ServerPlayer player = EntityValue.getPlayerByValue(((CarpetContext) c).server(), playerValue); + Value playerValue = lv.get(0); + ServerPlayer player = EntityValue.getPlayerByValue(((CarpetContext) c).server(), playerValue); if (player == null) { throw new InternalExpressionException("'create_screen' requires a valid online player as the first argument."); } - final String type = lv.get(1).getString(); - final Component name = FormattedTextValue.getTextByValue(lv.get(2)); + String type = lv.get(1).getString(); + Component name = FormattedTextValue.getTextByValue(lv.get(2)); FunctionValue function = null; if (lv.size() > 3) { @@ -474,7 +478,7 @@ else if (owner instanceof LivingEntity livingEntity) expression.addContextFunction("close_screen", 1, (c, t, lv) -> { - final Value value = lv.get(0); + Value value = lv.get(0); if (!(value instanceof final ScreenValue screenValue)) { throw new InternalExpressionException("'close_screen' requires a screen value as the first argument."); @@ -497,21 +501,21 @@ else if (owner instanceof LivingEntity livingEntity) { throw new InternalExpressionException("'screen_property' requires a screen value as the first argument"); } - final String propertyName = lv.get(1).getString(); + String propertyName = lv.get(1).getString(); return lv.size() >= 3 ? screenValue.modifyProperty(propertyName, lv.subList(2, lv.size())) : screenValue.queryProperty(propertyName); }); } - private static void syncPlayerInventory(final NBTSerializableValue.InventoryLocator inventory, final int int_1) + private static void syncPlayerInventory(NBTSerializableValue.InventoryLocator inventory, int slot) { if (inventory.owner() instanceof final ServerPlayer player && !inventory.isEnder() && !(inventory.inventory() instanceof ScreenValue.ScreenHandlerInventory)) { player.connection.send(new ClientboundContainerSetSlotPacket( -2, 0, // resolve mystery argument - int_1, - inventory.inventory().getItem(int_1) + slot, + inventory.inventory().getItem(slot) )); } } diff --git a/src/main/java/carpet/script/api/Monitoring.java b/src/main/java/carpet/script/api/Monitoring.java index 8acd1f93cf..5f232af020 100644 --- a/src/main/java/carpet/script/api/Monitoring.java +++ b/src/main/java/carpet/script/api/Monitoring.java @@ -27,18 +27,18 @@ public class Monitoring { private static final Map MOB_CATEGORY_MAP = Arrays.stream(MobCategory.values()).collect(Collectors.toMap(MobCategory::getName, Function.identity())); - public static void apply(final Expression expression) + public static void apply(Expression expression) { expression.addContextFunction("system_info", -1, (c, t, lv) -> { - if (lv.size() == 0) + if (lv.isEmpty()) { return SystemInfo.getAll(); } if (lv.size() == 1) { - final String what = lv.get(0).getString(); - final Value res = SystemInfo.get(what, (CarpetContext) c); + String what = lv.get(0).getString(); + Value res = SystemInfo.get(what, (CarpetContext) c); if (res == null) { throw new InternalExpressionException("Unknown option for 'system_info': " + what); @@ -50,21 +50,21 @@ public static void apply(final Expression expression) // game processed snooper functions expression.addContextFunction("get_mob_counts", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final ServerLevel world = cc.level(); - final NaturalSpawner.SpawnState info = world.getChunkSource().getLastSpawnState(); + CarpetContext cc = (CarpetContext) c; + ServerLevel world = cc.level(); + NaturalSpawner.SpawnState info = world.getChunkSource().getLastSpawnState(); if (info == null) { return Value.NULL; } - final Object2IntMap mobcounts = info.getMobCategoryCounts(); - final int chunks = info.getSpawnableChunkCount(); - if (lv.size() == 0) + Object2IntMap mobcounts = info.getMobCategoryCounts(); + int chunks = info.getSpawnableChunkCount(); + if (lv.isEmpty()) { - final Map retDict = new HashMap<>(); - for (final MobCategory category : mobcounts.keySet()) + Map retDict = new HashMap<>(); + for (MobCategory category : mobcounts.keySet()) { - final int currentCap = category.getMaxInstancesPerChunk() * chunks / Vanilla.NaturalSpawner_MAGIC_NUMBER(); + int currentCap = category.getMaxInstancesPerChunk() * chunks / Vanilla.NaturalSpawner_MAGIC_NUMBER(); retDict.put( new StringValue(category.getSerializedName().toLowerCase(Locale.ROOT)), ListValue.of( @@ -74,15 +74,15 @@ public static void apply(final Expression expression) } return MapValue.wrap(retDict); } - final String catString = lv.get(0).getString(); - final MobCategory cat = MOB_CATEGORY_MAP.get(catString.toLowerCase(Locale.ROOT)); + String catString = lv.get(0).getString(); + MobCategory cat = MOB_CATEGORY_MAP.get(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.getMaxInstancesPerChunk() * chunks / Vanilla.NaturalSpawner_MAGIC_NUMBER())) + new NumericValue((long) cat.getMaxInstancesPerChunk() * chunks / Vanilla.NaturalSpawner_MAGIC_NUMBER()) ); }); } diff --git a/src/main/java/carpet/script/api/Scoreboards.java b/src/main/java/carpet/script/api/Scoreboards.java index 2055c8314d..dd275e72b5 100644 --- a/src/main/java/carpet/script/api/Scoreboards.java +++ b/src/main/java/carpet/script/api/Scoreboards.java @@ -38,30 +38,30 @@ public class Scoreboards { - private static String getScoreboardKeyFromValue(final Value keyValue) + private static String getScoreboardKeyFromValue(Value keyValue) { if (keyValue instanceof final EntityValue ev) { - final Entity e = ev.getEntity(); + Entity e = ev.getEntity(); return e instanceof Player ? e.getName().getString() : e.getStringUUID(); } return keyValue.getString(); } - public static void apply(final Expression expression) + public static void apply(Expression expression) { // scoreboard(player,'objective') // scoreboard(player, objective, newValue) expression.addContextFunction("scoreboard", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final Scoreboard scoreboard = cc.server().getScoreboard(); - if (lv.size() == 0) + CarpetContext cc = (CarpetContext) c; + Scoreboard scoreboard = cc.server().getScoreboard(); + if (lv.isEmpty()) { return ListValue.wrap(scoreboard.getObjectiveNames().stream().map(StringValue::new)); } - final String objectiveName = lv.get(0).getString(); - final Objective objective = scoreboard.getOrCreateObjective(objectiveName); + String objectiveName = lv.get(0).getString(); + Objective objective = scoreboard.getOrCreateObjective(objectiveName); if (objective == null) { return Value.NULL; @@ -70,7 +70,7 @@ public static void apply(final Expression expression) { return ListValue.wrap(scoreboard.getPlayerScores(objective).stream().map(s -> new StringValue(s.getOwner()))); } - final String key = getScoreboardKeyFromValue(lv.get(1)); + String key = getScoreboardKeyFromValue(lv.get(1)); if (lv.size() == 2) { return !scoreboard.hasPlayerScore(key, objective) @@ -78,16 +78,16 @@ public static void apply(final Expression expression) : NumericValue.of(scoreboard.getOrCreatePlayerScore(key, objective).getScore()); } - final Value value = lv.get(2); + Value value = lv.get(2); if (value.isNull()) { - final Score score = scoreboard.getOrCreatePlayerScore(key, objective); + Score score = scoreboard.getOrCreatePlayerScore(key, objective); scoreboard.resetPlayerScore(key, objective); return NumericValue.of(score.getScore()); } if (value instanceof NumericValue) { - final Score score = scoreboard.getOrCreatePlayerScore(key, objective); + Score score = scoreboard.getOrCreatePlayerScore(key, objective); score.setScore(NumericValue.asNumber(value).getInt()); return NumericValue.of(score.getScore()); } @@ -96,14 +96,14 @@ public static void apply(final Expression expression) expression.addContextFunction("scoreboard_remove", -1, (c, t, lv) -> { - if (lv.size() == 0) + if (lv.isEmpty()) { throw new InternalExpressionException("'scoreboard_remove' requires at least one parameter"); } - final CarpetContext cc = (CarpetContext) c; - final Scoreboard scoreboard = cc.server().getScoreboard(); - final String objectiveName = lv.get(0).getString(); - final Objective objective = scoreboard.getOrCreateObjective(objectiveName); + CarpetContext cc = (CarpetContext) c; + Scoreboard scoreboard = cc.server().getScoreboard(); + String objectiveName = lv.get(0).getString(); + Objective objective = scoreboard.getOrCreateObjective(objectiveName); if (objective == null) { return Value.FALSE; @@ -113,13 +113,13 @@ public static void apply(final Expression expression) scoreboard.removeObjective(objective); return Value.TRUE; } - final String key = getScoreboardKeyFromValue(lv.get(1)); + String key = getScoreboardKeyFromValue(lv.get(1)); if (!scoreboard.hasPlayerScore(key, objective)) { return Value.NULL; } - final Score scoreboardPlayerScore = scoreboard.getOrCreatePlayerScore(key, objective); - final Value previous = new NumericValue(scoreboardPlayerScore.getScore()); + Score scoreboardPlayerScore = scoreboard.getOrCreatePlayerScore(key, objective); + Value previous = new NumericValue(scoreboardPlayerScore.getScore()); scoreboard.resetPlayerScore(key, objective); return previous; }); @@ -129,21 +129,21 @@ public static void apply(final Expression expression) expression.addContextFunction("scoreboard_add", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final Scoreboard scoreboard = cc.server().getScoreboard(); - if (lv.size() == 0 || lv.size() > 2) + CarpetContext cc = (CarpetContext) c; + Scoreboard scoreboard = cc.server().getScoreboard(); + if (lv.isEmpty() || lv.size() > 2) { throw new InternalExpressionException("'scoreboard_add' should have one or two parameters"); } - final String objectiveName = lv.get(0).getString(); - final ObjectiveCriteria criterion; + String objectiveName = lv.get(0).getString(); + ObjectiveCriteria criterion; if (lv.size() == 1) { criterion = ObjectiveCriteria.DUMMY; } else { - final String critetionName = lv.get(1).getString(); + String critetionName = lv.get(1).getString(); criterion = ObjectiveCriteria.byName(critetionName).orElse(null); if (criterion == null) { @@ -151,7 +151,7 @@ public static void apply(final Expression expression) } } - final Objective objective = scoreboard.getOrCreateObjective(objectiveName); + Objective objective = scoreboard.getOrCreateObjective(objectiveName); if (objective != null) { c.host.issueDeprecation("reading or modifying an objective's criterion with scoreboard_add"); @@ -165,7 +165,7 @@ public static void apply(final Expression expression) } Vanilla.Scoreboard_getObjectivesByCriterion(scoreboard).get(objective.getCriteria()).remove(objective); Vanilla.Objective_setCriterion(objective, criterion); - (Vanilla.Scoreboard_getObjectivesByCriterion(scoreboard).computeIfAbsent(criterion, (criterion1) -> Lists.newArrayList())).add(objective); + (Vanilla.Scoreboard_getObjectivesByCriterion(scoreboard).computeIfAbsent(criterion, cr -> Lists.newArrayList())).add(objective); scoreboard.onObjectiveAdded(objective); return Value.FALSE; } @@ -179,27 +179,27 @@ public static void apply(final Expression expression) { throw new InternalExpressionException("'scoreboard_property' requires at least two parameters"); } - final CarpetContext cc = (CarpetContext) c; - final Scoreboard scoreboard = cc.server().getScoreboard(); - final Objective objective = scoreboard.getOrCreateObjective(lv.get(0).getString()); + CarpetContext cc = (CarpetContext) c; + Scoreboard scoreboard = cc.server().getScoreboard(); + Objective objective = scoreboard.getOrCreateObjective(lv.get(0).getString()); if (objective == null) { return Value.NULL; } - final boolean modify = lv.size() > 2; + boolean modify = lv.size() > 2; Value setValue = null; if (modify) { setValue = lv.get(2); } - final String property = lv.get(1).getString(); + String property = lv.get(1).getString(); switch (property) { case "criterion" -> { if (modify) { - final ObjectiveCriteria criterion = ObjectiveCriteria.byName(setValue.getString()).orElse(null); + ObjectiveCriteria criterion = ObjectiveCriteria.byName(setValue.getString()).orElse(null); if (criterion == null) { throw new InternalExpressionException("Unknown scoreboard criterion: " + setValue.getString()); @@ -210,7 +210,7 @@ public static void apply(final Expression expression) } Vanilla.Scoreboard_getObjectivesByCriterion(scoreboard).get(objective.getCriteria()).remove(objective); Vanilla.Objective_setCriterion(objective, criterion); - (Vanilla.Scoreboard_getObjectivesByCriterion(scoreboard).computeIfAbsent(criterion, (criterion1) -> Lists.newArrayList())).add(objective); + (Vanilla.Scoreboard_getObjectivesByCriterion(scoreboard).computeIfAbsent(criterion, cr -> Lists.newArrayList())).add(objective); scoreboard.onObjectiveAdded(objective); return Value.TRUE; } @@ -219,7 +219,7 @@ public static void apply(final Expression expression) case "display_name" -> { if (modify) { - final Component text = FormattedTextValue.getTextByValue(setValue); + Component text = FormattedTextValue.getTextByValue(setValue); objective.setDisplayName(text); return Value.TRUE; } @@ -228,7 +228,7 @@ public static void apply(final Expression expression) case "display_slot" -> { if (modify) { - final int slotId = Scoreboard.getDisplaySlotByName(setValue.getString()); + int slotId = Scoreboard.getDisplaySlotByName(setValue.getString()); if (slotId == -1) { throw new InternalExpressionException("Unknown scoreboard display slot: " + setValue.getString()); @@ -240,12 +240,12 @@ public static void apply(final Expression expression) scoreboard.setDisplayObjective(slotId, objective); return Value.TRUE; } - final List slots = new ArrayList<>(); + List slots = new ArrayList<>(); for (int i = 0; i < 19; i++) { if (scoreboard.getDisplayObjective(i) == objective) { - final String slotName = Scoreboard.getDisplaySlotName(i); + String slotName = Scoreboard.getDisplaySlotName(i); slots.add(StringValue.of(slotName)); } } @@ -254,7 +254,7 @@ public static void apply(final Expression expression) case "render_type" -> { if (modify) { - final ObjectiveCriteria.RenderType renderType = ObjectiveCriteria.RenderType.byId(setValue.getString().toLowerCase()); + ObjectiveCriteria.RenderType renderType = ObjectiveCriteria.RenderType.byId(setValue.getString().toLowerCase()); if (objective.getRenderType().equals(renderType)) { return Value.FALSE; @@ -270,22 +270,22 @@ public static void apply(final Expression expression) expression.addContextFunction("scoreboard_display", 2, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final Scoreboard scoreboard = cc.server().getScoreboard(); - final String location = lv.get(0).getString(); - final int slot = Scoreboard.getDisplaySlotByName(location); + CarpetContext cc = (CarpetContext) c; + Scoreboard scoreboard = cc.server().getScoreboard(); + String location = lv.get(0).getString(); + int slot = Scoreboard.getDisplaySlotByName(location); if (slot < 0) { throw new InternalExpressionException("Invalid objective slot: " + location); } - final Value target = lv.get(1); + Value target = lv.get(1); if (target.isNull()) { scoreboard.setDisplayObjective(slot, null); return new NumericValue(slot); } - final String objectiveString = target.getString(); - final Objective objective = scoreboard.getOrCreateObjective(objectiveString); + String objectiveString = target.getString(); + Objective objective = scoreboard.getOrCreateObjective(objectiveString); if (objective == null) { return Value.NULL; @@ -300,9 +300,9 @@ public static void apply(final Expression expression) { throw new InternalExpressionException("'team_list' requires zero or one parameters"); } - final CarpetContext cc = (CarpetContext) c; - final ServerScoreboard scoreboard = cc.server().getScoreboard(); - if (lv.size() == 0) + CarpetContext cc = (CarpetContext) c; + ServerScoreboard scoreboard = cc.server().getScoreboard(); + if (lv.isEmpty()) { return ListValue.wrap(scoreboard.getTeamNames().stream().map(StringValue::of)); } @@ -310,21 +310,21 @@ public static void apply(final Expression expression) { return Value.NULL; } - final PlayerTeam team = scoreboard.getPlayerTeam(lv.get(0).getString()); + PlayerTeam team = scoreboard.getPlayerTeam(lv.get(0).getString()); return team == null ? Value.NULL : ListValue.wrap(team.getPlayers().stream().map(StringValue::of)); }); expression.addContextFunction("team_add", -1, (c, t, lv) -> { - if (!(lv.size() < 3 && lv.size() > 0)) + if (!(lv.size() < 3 && !lv.isEmpty())) { throw new InternalExpressionException("'team_add' requires one or two parameters"); } - final CarpetContext cc = (CarpetContext) c; - final ServerScoreboard scoreboard = cc.server().getScoreboard(); - final String teamName = lv.get(0).getString(); + CarpetContext cc = (CarpetContext) c; + ServerScoreboard scoreboard = cc.server().getScoreboard(); + String teamName = lv.get(0).getString(); if (lv.size() == 1) { @@ -339,13 +339,13 @@ public static void apply(final Expression expression) { return Value.NULL; } - final Value playerVal = lv.get(1); - final String player = EntityValue.getPlayerNameByValue(playerVal); + Value playerVal = lv.get(1); + String player = EntityValue.getPlayerNameByValue(playerVal); if (player == null) { return Value.NULL; } - final PlayerTeam team = scoreboard.getPlayerTeam(teamName); + PlayerTeam team = scoreboard.getPlayerTeam(teamName); if (team == null) { return Value.NULL; @@ -354,44 +354,44 @@ public static void apply(final Expression expression) { return Value.FALSE; } - scoreboard.addPlayerToTeam(player, scoreboard.getPlayerTeam(teamName)); + scoreboard.addPlayerToTeam(player, team); return Value.TRUE; }); expression.addContextFunction("team_remove", 1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final ServerScoreboard scoreboard = cc.server().getScoreboard(); - final Value teamVal = lv.get(0); - final String team = teamVal.getString(); - if (scoreboard.getPlayerTeam(team) == null) + CarpetContext cc = (CarpetContext) c; + ServerScoreboard scoreboard = cc.server().getScoreboard(); + Value teamVal = lv.get(0); + PlayerTeam team = scoreboard.getPlayerTeam(teamVal.getString()); + if (team == null) { return Value.NULL; } - scoreboard.removePlayerTeam(scoreboard.getPlayerTeam(team)); + scoreboard.removePlayerTeam(team); return Value.TRUE; }); expression.addContextFunction("team_leave", 1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final ServerScoreboard scoreboard = cc.server().getScoreboard(); - final Value playerVal = lv.get(0); - final String player = EntityValue.getPlayerNameByValue(playerVal); + CarpetContext cc = (CarpetContext) c; + ServerScoreboard scoreboard = cc.server().getScoreboard(); + Value playerVal = lv.get(0); + String player = EntityValue.getPlayerNameByValue(playerVal); return player == null ? Value.NULL : BooleanValue.of(scoreboard.removePlayerFromTeam(player)); }); expression.addContextFunction("team_property", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final ServerScoreboard scoreboard = cc.server().getScoreboard(); + CarpetContext cc = (CarpetContext) c; + ServerScoreboard scoreboard = cc.server().getScoreboard(); if (lv.size() < 2 || lv.size() > 3) { throw new InternalExpressionException("'team_property' requires two or three arguments"); } - final Value teamVal = lv.get(0); - final Value propertyVal = lv.get(1); + Value teamVal = lv.get(0); + Value propertyVal = lv.get(1); Value settingVal = null; boolean modifying = false; @@ -401,7 +401,7 @@ public static void apply(final Expression expression) settingVal = lv.get(2); } - final PlayerTeam team = scoreboard.getPlayerTeam(teamVal.getString()); + PlayerTeam team = scoreboard.getPlayerTeam(teamVal.getString()); if (team == null) { return Value.NULL; @@ -423,7 +423,7 @@ public static void apply(final Expression expression) { throw new InternalExpressionException("'team_property' requires a string as the third argument for the property " + propertyVal.getString()); } - final Team.CollisionRule collisionRule = Team.CollisionRule.byName(settingVal.getString()); + Team.CollisionRule collisionRule = Team.CollisionRule.byName(settingVal.getString()); if (collisionRule == null) { throw new InternalExpressionException("Unknown value for property " + propertyVal.getString() + ": " + settingVal.getString()); @@ -439,7 +439,7 @@ public static void apply(final Expression expression) { throw new InternalExpressionException("'team_property' requires a string as the third argument for the property " + propertyVal.getString()); } - final ChatFormatting color = ChatFormatting.getByName(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()); @@ -455,7 +455,7 @@ public static void apply(final Expression expression) { throw new InternalExpressionException("'team_property' requires a string as the third argument for the property " + propertyVal.getString()); } - final Team.Visibility deathMessageVisibility = Team.Visibility.byName(settingVal.getString()); + Team.Visibility deathMessageVisibility = Team.Visibility.byName(settingVal.getString()); if (deathMessageVisibility == null) { throw new InternalExpressionException("Unknown value for property " + propertyVal.getString() + ": " + settingVal.getString()); @@ -493,7 +493,7 @@ public static void apply(final Expression expression) { throw new InternalExpressionException("'team_property' requires a string as the third argument for the property " + propertyVal.getString()); } - final Team.Visibility nametagVisibility = Team.Visibility.byName(settingVal.getString()); + Team.Visibility nametagVisibility = Team.Visibility.byName(settingVal.getString()); if (nametagVisibility == null) { throw new InternalExpressionException("Unknown value for property " + propertyVal.getString() + ": " + settingVal.getString()); @@ -540,19 +540,19 @@ public static void apply(final Expression expression) expression.addContextFunction("bossbar", -1, (c, t, lv) -> { - final CustomBossEvents bossBarManager = ((CarpetContext) c).server().getCustomBossEvents(); + CustomBossEvents bossBarManager = ((CarpetContext) c).server().getCustomBossEvents(); if (lv.size() > 3) { throw new InternalExpressionException("'bossbar' accepts max three arguments"); } - if (lv.size() == 0) + if (lv.isEmpty()) { return ListValue.wrap(bossBarManager.getEvents().stream().map(CustomBossEvent::getTextId).map(ResourceLocation::toString).map(StringValue::of)); } - final String id = lv.get(0).getString(); - final ResourceLocation identifier = InputValidator.identifierOf(id); + String id = lv.get(0).getString(); + ResourceLocation identifier = InputValidator.identifierOf(id); if (lv.size() == 1) { @@ -563,25 +563,25 @@ public static void apply(final Expression expression) return StringValue.of(bossBarManager.create(identifier, Component.literal(id)).getTextId().toString()); } - final String property = lv.get(1).getString(); + String property = lv.get(1).getString(); - final CustomBossEvent bossBar = bossBarManager.get(identifier); + CustomBossEvent bossBar = bossBarManager.get(identifier); if (bossBar == null) { return Value.NULL; } - final Value propertyValue = (lv.size() == 3) ? lv.get(2) : null; + Value propertyValue = (lv.size() == 3) ? lv.get(2) : null; switch (property) { case "color" -> { if (propertyValue == null) { - final BossEvent.BossBarColor color = (bossBar).getColor(); + BossEvent.BossBarColor color = (bossBar).getColor(); return color == null ? Value.NULL : StringValue.of(color.getName()); } - final BossEvent.BossBarColor color = BossEvent.BossBarColor.byName(propertyValue.getString()); + BossEvent.BossBarColor color = BossEvent.BossBarColor.byName(propertyValue.getString()); if (color == null) { return Value.NULL; @@ -616,8 +616,8 @@ public static void apply(final Expression expression) } if (propertyValue instanceof final ListValue list) { - list.getItems().forEach((v) -> { - final ServerPlayer player = EntityValue.getPlayerByValue(((CarpetContext) c).server(), propertyValue); + list.getItems().forEach(v -> { + ServerPlayer player = EntityValue.getPlayerByValue(((CarpetContext) c).server(), propertyValue); if (player != null) { bossBar.addPlayer(player); @@ -625,7 +625,7 @@ public static void apply(final Expression expression) }); return Value.TRUE; } - final ServerPlayer player = EntityValue.getPlayerByValue(((CarpetContext) c).server(), propertyValue); + ServerPlayer player = EntityValue.getPlayerByValue(((CarpetContext) c).server(), propertyValue); if (player != null) { bossBar.addPlayer(player); @@ -650,7 +650,7 @@ public static void apply(final Expression expression) }); return Value.TRUE; } - final ServerPlayer p = EntityValue.getPlayerByValue(((CarpetContext) c).server(), propertyValue); + ServerPlayer p = EntityValue.getPlayerByValue(((CarpetContext) c).server(), propertyValue); bossBar.removeAllPlayers(); if (p != null) { @@ -664,7 +664,7 @@ public static void apply(final Expression expression) { return StringValue.of(bossBar.getOverlay().getName()); } - final BossEvent.BossBarOverlay style = BossEvent.BossBarOverlay.byName(propertyValue.getString()); + BossEvent.BossBarOverlay style = BossEvent.BossBarOverlay.byName(propertyValue.getString()); if (style == null) { throw new InternalExpressionException("'" + propertyValue.getString() + "' is not a valid value for property " + property); diff --git a/src/main/java/carpet/script/api/Threading.java b/src/main/java/carpet/script/api/Threading.java index eef2531757..504838c6e3 100644 --- a/src/main/java/carpet/script/api/Threading.java +++ b/src/main/java/carpet/script/api/Threading.java @@ -14,13 +14,13 @@ public class Threading { public static void apply(Expression expression) { - //"overidden" native call to cancel if on main thread + //"overridden" native call to cancel if on main thread expression.addContextFunction("task_join", 1, (c, t, lv) -> { if (((CarpetContext) c).server().isSameThread()) { throw new InternalExpressionException("'task_join' cannot be called from main thread to avoid deadlocks"); } - final Value v = lv.get(0); + Value v = lv.get(0); if (!(v instanceof final ThreadValue tv)) { throw new InternalExpressionException("'task_join' could only be used with a task value"); @@ -30,14 +30,14 @@ public static void apply(Expression expression) // has to be lazy due to deferred execution of the expression expression.addLazyFunctionWithDelegation("task_dock", 1, false, true, (c, t, expr, tok, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final MinecraftServer server = cc.server(); + CarpetContext cc = (CarpetContext) c; + MinecraftServer server = cc.server(); if (server.isSameThread()) { return lv.get(0); // pass through for on thread tasks } - final Value[] result = new Value[]{Value.NULL}; - final RuntimeException[] internal = new RuntimeException[]{null}; + Value[] result = new Value[]{Value.NULL}; + RuntimeException[] internal = new RuntimeException[]{null}; try { ((CarpetContext) c).server().executeBlocking(() -> @@ -46,22 +46,22 @@ public static void apply(Expression expression) { result[0] = lv.get(0).evalValue(c, t); } - catch (final ExpressionException exc) + catch (ExpressionException exc) { internal[0] = exc; } - catch (final InternalExpressionException exc) + catch (InternalExpressionException exc) { internal[0] = new ExpressionException(c, expr, tok, exc.getMessage(), exc.stack); } - catch (final ArithmeticException exc) + catch (ArithmeticException exc) { internal[0] = new ExpressionException(c, expr, tok, "Your math is wrong, " + exc.getMessage()); } }); } - catch (final CompletionException exc) + catch (CompletionException exc) { throw new InternalExpressionException("Error while executing docked task section, internal stack trace is gone"); } @@ -69,8 +69,8 @@ public static void apply(Expression expression) { throw internal[0]; } - final Value ret = result[0]; // preventing from lazy evaluating of the result in case a future completes later - return (_c, _t) -> ret; + Value ret = result[0]; // preventing from lazy evaluating of the result in case a future completes later + return (ct, tt) -> ret; // pass through placeholder // implmenetation should dock the task on the main thread. }); diff --git a/src/main/java/carpet/script/api/WorldAccess.java b/src/main/java/carpet/script/api/WorldAccess.java index 4e7112d96d..cc9f43ca19 100644 --- a/src/main/java/carpet/script/api/WorldAccess.java +++ b/src/main/java/carpet/script/api/WorldAccess.java @@ -133,7 +133,7 @@ public class WorldAccess { - private static final Map DIRECTION_MAP = Arrays.stream(Direction.values()).collect(Collectors.toMap(Direction::getName, (direction) -> direction)); + private static final Map DIRECTION_MAP = Arrays.stream(Direction.values()).collect(Collectors.toMap(Direction::getName, Function.identity())); static { @@ -151,14 +151,14 @@ public class WorldAccess private static FallingBlockEntity DUMMY_ENTITY = null; private static Value booleanStateTest( - final Context c, - final String name, - final List params, - final BiPredicate test + Context c, + String name, + List params, + BiPredicate test ) { - final CarpetContext cc = (CarpetContext) c; - if (params.size() == 0) + CarpetContext cc = (CarpetContext) c; + if (params.isEmpty()) { throw new InternalExpressionException("'" + name + "' requires at least one parameter"); } @@ -166,19 +166,19 @@ private static Value booleanStateTest( { return BooleanValue.of(test.test(bv.getBlockState(), bv.getPos())); } - final BlockValue block = BlockArgument.findIn(cc, params, 0).block; + BlockValue block = BlockArgument.findIn(cc, params, 0).block; return BooleanValue.of(test.test(block.getBlockState(), block.getPos())); } private static Value stateStringQuery( - final Context c, - final String name, - final List params, - final BiFunction test + Context c, + String name, + List params, + BiFunction test ) { - final CarpetContext cc = (CarpetContext) c; - if (params.size() == 0) + CarpetContext cc = (CarpetContext) c; + if (params.isEmpty()) { throw new InternalExpressionException("'" + name + "' requires at least one parameter"); } @@ -186,19 +186,19 @@ private static Value stateStringQuery( { return StringValue.of(test.apply(bv.getBlockState(), bv.getPos())); } - final BlockValue block = BlockArgument.findIn(cc, params, 0).block; + BlockValue block = BlockArgument.findIn(cc, params, 0).block; return StringValue.of(test.apply(block.getBlockState(), block.getPos())); } private static Value genericStateTest( - final Context c, - final String name, - final List params, - final Fluff.TriFunction test + Context c, + String name, + List params, + Fluff.TriFunction test ) { - final CarpetContext cc = (CarpetContext) c; - if (params.size() == 0) + CarpetContext cc = (CarpetContext) c; + if (params.isEmpty()) { throw new InternalExpressionException("'" + name + "' requires at least one parameter"); } @@ -208,19 +208,19 @@ private static Value genericStateTest( { return test.apply(bv.getBlockState(), bv.getPos(), cc.level()); } - catch (final NullPointerException ignored) + catch (NullPointerException ignored) { throw new InternalExpressionException("'" + name + "' function requires a block that is positioned in the world"); } } - final BlockValue block = BlockArgument.findIn(cc, params, 0).block; + BlockValue block = BlockArgument.findIn(cc, params, 0).block; return test.apply(block.getBlockState(), block.getPos(), cc.level()); } - private static > BlockState setProperty(final Property property, final String name, final String value, - final BlockState bs) + private static > BlockState setProperty(Property property, String name, String value, + BlockState bs) { - final Optional optional = property.getValue(value); + Optional optional = property.getValue(value); if (optional.isEmpty()) { throw new InternalExpressionException(value + " is not a valid value for property " + name); @@ -228,7 +228,7 @@ private static > BlockState setProperty(final Property { - final CarpetContext cc = (CarpetContext) c; - if (lv.size() == 0) + CarpetContext cc = (CarpetContext) c; + if (lv.isEmpty()) { throw new InternalExpressionException("Block requires at least one parameter"); } - final BlockValue retval = BlockArgument.findIn(cc, lv, 0, true).block; + BlockValue retval = BlockArgument.findIn(cc, lv, 0, true).block; // fixing block state and data retval.getBlockState(); retval.getData(); @@ -272,7 +272,7 @@ public static void apply(final Expression expression) expression.addContextFunction("block_data", -1, (c, t, lv) -> { - if (lv.size() == 0) + if (lv.isEmpty()) { throw new InternalExpressionException("Block requires at least one parameter"); } @@ -282,28 +282,28 @@ public static void apply(final Expression expression) // poi_get(pos, radius?, type?, occupation?, column_mode?) expression.addContextFunction("poi", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - if (lv.size() == 0) + CarpetContext cc = (CarpetContext) c; + if (lv.isEmpty()) { throw new InternalExpressionException("'poi' requires at least one parameter"); } - final BlockArgument locator = BlockArgument.findIn(cc, lv, 0, false); - final BlockPos pos = locator.block.getPos(); - final PoiManager store = cc.level().getPoiManager(); - final Registry poiReg = cc.registry(Registries.POINT_OF_INTEREST_TYPE); + BlockArgument locator = BlockArgument.findIn(cc, lv, 0, false); + BlockPos pos = locator.block.getPos(); + PoiManager store = cc.level().getPoiManager(); + Registry poiReg = cc.registry(Registries.POINT_OF_INTEREST_TYPE); if (lv.size() == locator.offset) { - final Optional> foo = store.getType(pos); + Optional> foo = store.getType(pos); if (foo.isEmpty()) { return Value.NULL; } - final PoiType poiType = foo.get().value(); + PoiType poiType = foo.get().value(); // this feels wrong, but I don't want to mix-in more than I really need to. // also distance adds 0.5 to each point which screws up accurate distance calculations // you shoudn't be using POI with that in mind anyways, so I am not worried about it. - final PoiRecord poi = store.getInRange( + PoiRecord poi = store.getInRange( type -> type.value() == poiType, pos, 1, @@ -314,7 +314,7 @@ public static void apply(final Expression expression) new NumericValue(poiType.maxTickets() - ((PoiRecord_scarpetMixin) poi).getFreeTickets()) ); } - final int radius = NumericValue.asNumber(lv.get(locator.offset + 0)).getInt(); + int radius = NumericValue.asNumber(lv.get(locator.offset)).getInt(); if (radius < 0) { return ListValue.of(); @@ -324,16 +324,16 @@ public static void apply(final Expression expression) boolean inColumn = false; if (locator.offset + 1 < lv.size()) { - final String poiType = lv.get(locator.offset + 1).getString().toLowerCase(Locale.ROOT); + String poiType = lv.get(locator.offset + 1).getString().toLowerCase(Locale.ROOT); if (!"any".equals(poiType)) { - final PoiType type = poiReg.getOptional(InputValidator.identifierOf(poiType)) + PoiType type = poiReg.getOptional(InputValidator.identifierOf(poiType)) .orElseThrow(() -> new ThrowStatement(poiType, Throwables.UNKNOWN_POI)); - condition = (tt) -> tt.value() == type; + condition = tt -> tt.value() == type; } if (locator.offset + 2 < lv.size()) { - final String statusString = lv.get(locator.offset + 2).getString().toLowerCase(Locale.ROOT); + String statusString = lv.get(locator.offset + 2).getString().toLowerCase(Locale.ROOT); if ("occupied".equals(statusString)) { status = PoiManager.Occupancy.IS_OCCUPIED; @@ -354,7 +354,7 @@ else if (!("any".equals(statusString))) } } } - final Stream pois = inColumn ? + Stream pois = inColumn ? store.getInSquare(condition, pos, radius, status) : store.getInRange(condition, pos, radius, status); return ListValue.wrap(pois.sorted(Comparator.comparingDouble(p -> p.getPos().distSqr(pos))).map(p -> @@ -369,19 +369,19 @@ else if (!("any".equals(statusString))) //poi_set(pos, null) poi_set(pos, type, occupied?, expression.addContextFunction("set_poi", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - if (lv.size() == 0) + CarpetContext cc = (CarpetContext) c; + if (lv.isEmpty()) { throw new InternalExpressionException("'set_poi' requires at least one parameter"); } - final BlockArgument locator = BlockArgument.findIn(cc, lv, 0, false); - final BlockPos pos = locator.block.getPos(); + BlockArgument locator = BlockArgument.findIn(cc, lv, 0, false); + BlockPos pos = locator.block.getPos(); if (lv.size() < locator.offset) { throw new InternalExpressionException("'set_poi' requires the new poi type or null, after position argument"); } - final Value poi = lv.get(locator.offset + 0); - final PoiManager store = cc.level().getPoiManager(); + Value poi = lv.get(locator.offset); + PoiManager store = cc.level().getPoiManager(); if (poi.isNull()) { // clear poi information if (store.getType(pos).isEmpty()) @@ -391,12 +391,12 @@ else if (!("any".equals(statusString))) store.remove(pos); return Value.TRUE; } - final String poiTypeString = poi.getString().toLowerCase(Locale.ROOT); - final ResourceLocation resource = InputValidator.identifierOf(poiTypeString); - final Registry poiReg = cc.registry(Registries.POINT_OF_INTEREST_TYPE); - final PoiType type = poiReg.getOptional(resource) + String poiTypeString = poi.getString().toLowerCase(Locale.ROOT); + ResourceLocation resource = InputValidator.identifierOf(poiTypeString); + Registry poiReg = cc.registry(Registries.POINT_OF_INTEREST_TYPE); + PoiType type = poiReg.getOptional(resource) .orElseThrow(() -> new ThrowStatement(poiTypeString, Throwables.UNKNOWN_POI)); - final Holder holder = poiReg.getHolderOrThrow(ResourceKey.create(Registries.POINT_OF_INTEREST_TYPE, resource)); + Holder holder = poiReg.getHolderOrThrow(ResourceKey.create(Registries.POINT_OF_INTEREST_TYPE, resource)); int occupancy = 0; if (locator.offset + 1 < lv.size()) @@ -416,8 +416,8 @@ else if (!("any".equals(statusString))) // again - don't want to mix in unnecessarily - peeps not gonna use it that often so not worries about it. if (occupancy > 0) { - final int finalO = occupancy; - store.getInSquare((tt) -> tt.value() == type, pos, 1, PoiManager.Occupancy.ANY + int finalO = occupancy; + store.getInSquare(tt -> tt.value() == type, pos, 1, PoiManager.Occupancy.ANY ).filter(p -> p.getPos().equals(pos)).findFirst().ifPresent(p -> { for (int i = 0; i < finalO; i++) { @@ -430,15 +430,15 @@ else if (!("any".equals(statusString))) expression.addContextFunction("weather", -1, (c, t, lv) -> { - final ServerLevel world = ((CarpetContext) c).level(); + ServerLevel world = ((CarpetContext) c).level(); - if (lv.size() == 0)//cos it can thunder when raining or when clear. + if (lv.isEmpty())//cos it can thunder when raining or when clear. { return new StringValue(world.isThundering() ? "thunder" : (world.isRaining() ? "rain" : "clear")); } - final Value weather = lv.get(0); - final ServerLevelData worldProperties = Vanilla.ServerLevel_getWorldProperties(world); + Value weather = lv.get(0); + ServerLevelData worldProperties = Vanilla.ServerLevel_getWorldProperties(world); if (lv.size() == 1) { return new NumericValue(switch (weather.getString().toLowerCase(Locale.ROOT)) @@ -451,7 +451,7 @@ else if (!("any".equals(statusString))) } if (lv.size() == 2) { - final int ticks = NumericValue.asNumber(lv.get(1), "tick_time in 'weather'").getInt(); + int ticks = NumericValue.asNumber(lv.get(1), "tick_time in 'weather'").getInt(); switch (weather.getString().toLowerCase(Locale.ROOT)) { case "clear" -> world.setWeatherParameters(ticks, 0, false, false); @@ -473,7 +473,7 @@ else if (!("any".equals(statusString))) { if (v instanceof final BlockValue bv) { - final BlockPos pos = bv.getPos(); + BlockPos pos = bv.getPos(); if (pos == null) { throw new InternalExpressionException("Cannot fetch position of an unrealized block"); @@ -482,7 +482,7 @@ else if (!("any".equals(statusString))) } if (v instanceof final EntityValue ev) { - final Entity e = ev.getEntity(); + Entity e = ev.getEntity(); if (e == null) { throw new InternalExpressionException("Null entity"); @@ -494,14 +494,14 @@ else if (!("any".equals(statusString))) expression.addContextFunction("pos_offset", -1, (c, t, lv) -> { - final BlockArgument locator = BlockArgument.findIn((CarpetContext) c, lv, 0); - final BlockPos pos = locator.block.getPos(); + BlockArgument locator = BlockArgument.findIn((CarpetContext) c, lv, 0); + BlockPos pos = locator.block.getPos(); if (lv.size() <= locator.offset) { throw new InternalExpressionException("'pos_offset' needs at least position, and direction"); } - final String directionString = lv.get(locator.offset).getString(); - final Direction dir = DIRECTION_MAP.get(directionString); + String directionString = lv.get(locator.offset).getString(); + Direction dir = DIRECTION_MAP.get(directionString); if (dir == null) { throw new InternalExpressionException("Unknown direction: " + directionString); @@ -564,8 +564,8 @@ else if (!("any".equals(statusString))) expression.addContextFunction("in_slime_chunk", -1, (c, t, lv) -> { - final BlockPos pos = BlockArgument.findIn((CarpetContext) c, lv, 0).block.getPos(); - final ChunkPos chunkPos = new ChunkPos(pos); + BlockPos pos = BlockArgument.findIn((CarpetContext) c, lv, 0).block.getPos(); + ChunkPos chunkPos = new ChunkPos(pos); return BooleanValue.of(WorldgenRandom.seedSlimeChunk( chunkPos.x, chunkPos.z, ((CarpetContext) c).level().getSeed(), @@ -575,8 +575,8 @@ else if (!("any".equals(statusString))) expression.addContextFunction("top", -1, (c, t, lv) -> { - final String type = lv.get(0).getString().toLowerCase(Locale.ROOT); - final Heightmap.Types htype = switch (type) + String type = lv.get(0).getString().toLowerCase(Locale.ROOT); + Heightmap.Types htype = switch (type) { //case "light": htype = Heightmap.Type.LIGHT_BLOCKING; break; //investigate case "motion" -> Heightmap.Types.MOTION_BLOCKING; @@ -585,10 +585,10 @@ else if (!("any".equals(statusString))) case "surface" -> Heightmap.Types.WORLD_SURFACE; default -> throw new InternalExpressionException("Unknown heightmap type: " + type); }; - final BlockArgument locator = BlockArgument.findIn((CarpetContext) c, lv, 1); - final BlockPos pos = locator.block.getPos(); - final int x = pos.getX(); - final int z = pos.getZ(); + BlockArgument locator = BlockArgument.findIn((CarpetContext) c, lv, 1); + BlockPos pos = locator.block.getPos(); + int x = pos.getX(); + int z = pos.getZ(); return new NumericValue(((CarpetContext) c).level().getChunk(x >> 4, z >> 4).getHeight(htype, x & 15, z & 15) + 1); }); @@ -599,21 +599,21 @@ else if (!("any".equals(statusString))) expression.addContextFunction("loaded_ep", -1, (c, t, lv) -> { c.host.issueDeprecation("loaded_ep(...)"); - final BlockPos pos = BlockArgument.findIn((CarpetContext) c, lv, 0).block.getPos(); + BlockPos pos = BlockArgument.findIn((CarpetContext) c, lv, 0).block.getPos(); return BooleanValue.of(((CarpetContext) c).level().isPositionEntityTicking(pos)); }); expression.addContextFunction("loaded_status", -1, (c, t, lv) -> { - final BlockPos pos = BlockArgument.findIn((CarpetContext) c, lv, 0).block.getPos(); - final LevelChunk chunk = ((CarpetContext) c).level().getChunkSource().getChunk(pos.getX() >> 4, pos.getZ() >> 4, false); + BlockPos pos = BlockArgument.findIn((CarpetContext) c, lv, 0).block.getPos(); + LevelChunk chunk = ((CarpetContext) c).level().getChunkSource().getChunk(pos.getX() >> 4, pos.getZ() >> 4, false); return chunk == null ? Value.ZERO : new NumericValue(chunk.getFullStatus().ordinal()); }); expression.addContextFunction("is_chunk_generated", -1, (c, t, lv) -> { - final BlockArgument locator = BlockArgument.findIn((CarpetContext) c, lv, 0); - final BlockPos pos = locator.block.getPos(); + BlockArgument locator = BlockArgument.findIn((CarpetContext) c, lv, 0); + BlockPos pos = locator.block.getPos(); boolean force = false; if (lv.size() > locator.offset) { @@ -624,30 +624,30 @@ else if (!("any".equals(statusString))) expression.addContextFunction("generation_status", -1, (c, t, lv) -> { - final BlockArgument blockArgument = BlockArgument.findIn((CarpetContext) c, lv, 0); - final BlockPos pos = blockArgument.block.getPos(); + BlockArgument blockArgument = BlockArgument.findIn((CarpetContext) c, lv, 0); + BlockPos pos = blockArgument.block.getPos(); boolean forceLoad = false; if (lv.size() > blockArgument.offset) { forceLoad = lv.get(blockArgument.offset).getBoolean(); } - final ChunkAccess chunk = ((CarpetContext) c).level().getChunk(pos.getX() >> 4, pos.getZ() >> 4, ChunkStatus.EMPTY, forceLoad); + ChunkAccess chunk = ((CarpetContext) c).level().getChunk(pos.getX() >> 4, pos.getZ() >> 4, ChunkStatus.EMPTY, forceLoad); return chunk == null ? Value.NULL : new StringValue(chunk.getStatus().getName()); }); expression.addContextFunction("chunk_tickets", -1, (c, t, lv) -> { - final ServerLevel world = ((CarpetContext) c).level(); + ServerLevel world = ((CarpetContext) c).level(); DistanceManager foo = Vanilla.ServerChunkCache_getCMTicketManager(world.getChunkSource()); - final Long2ObjectOpenHashMap>> levelTickets = Vanilla.ChunkTicketManager_getTicketsByPosition(foo); + Long2ObjectOpenHashMap>> levelTickets = Vanilla.ChunkTicketManager_getTicketsByPosition(foo); - final List res = new ArrayList<>(); - if (lv.size() == 0) + List res = new ArrayList<>(); + if (lv.isEmpty()) { - for (final long key : levelTickets.keySet()) + for (long key : levelTickets.keySet()) { - final ChunkPos chpos = new ChunkPos(key); - for (final Ticket ticket : levelTickets.get(key)) + ChunkPos chpos = new ChunkPos(key); + for (Ticket ticket : levelTickets.get(key)) { res.add(ListValue.of( new StringValue(ticket.getType().toString()), @@ -660,12 +660,12 @@ else if (!("any".equals(statusString))) } else { - final BlockArgument blockArgument = BlockArgument.findIn((CarpetContext) c, lv, 0); - final BlockPos pos = blockArgument.block.getPos(); - final SortedArraySet> tickets = levelTickets.get(new ChunkPos(pos).toLong()); + BlockArgument blockArgument = BlockArgument.findIn((CarpetContext) c, lv, 0); + BlockPos pos = blockArgument.block.getPos(); + SortedArraySet> tickets = levelTickets.get(new ChunkPos(pos).toLong()); if (tickets != null) { - for (final Ticket ticket : tickets) + for (Ticket ticket : tickets) { res.add(ListValue.of( new StringValue(ticket.getType().toString()), @@ -697,7 +697,7 @@ else if (!("any".equals(statusString))) expression.addContextFunction("block_tick", -1, (c, t, lv) -> booleanStateTest(c, "block_tick", lv, (s, p) -> { - final ServerLevel w = ((CarpetContext) c).level(); + ServerLevel w = ((CarpetContext) c).level(); s.randomTick(w, p, w.random); return true; })); @@ -705,7 +705,7 @@ else if (!("any".equals(statusString))) expression.addContextFunction("random_tick", -1, (c, t, lv) -> booleanStateTest(c, "random_tick", lv, (s, p) -> { - final ServerLevel w = ((CarpetContext) c).level(); + ServerLevel w = ((CarpetContext) c).level(); if (s.isRandomlyTicking() || s.getFluidState().isRandomlyTicking()) { s.randomTick(w, p, w.random); @@ -720,11 +720,11 @@ else if (!("any".equals(statusString))) { return lv.get(0); } - final Value[] result = new Value[]{Value.NULL}; + Value[] result = new Value[]{Value.NULL}; ((CarpetContext) c).server().executeBlocking(() -> { - final ThreadLocal skipUpdates = Carpet.getImpendingFillSkipUpdates(); - final boolean previous = skipUpdates.get(); + ThreadLocal skipUpdates = Carpet.getImpendingFillSkipUpdates(); + boolean previous = skipUpdates.get(); try { skipUpdates.set(true); @@ -740,12 +740,12 @@ else if (!("any".equals(statusString))) expression.addContextFunction("set", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final ServerLevel world = cc.level(); - final BlockArgument targetLocator = BlockArgument.findIn(cc, lv, 0); - final BlockArgument sourceLocator = BlockArgument.findIn(cc, lv, targetLocator.offset, true); + CarpetContext cc = (CarpetContext) c; + ServerLevel world = cc.level(); + BlockArgument targetLocator = BlockArgument.findIn(cc, lv, 0); + BlockArgument sourceLocator = BlockArgument.findIn(cc, lv, targetLocator.offset, true); BlockState sourceBlockState = sourceLocator.block.getBlockState(); - final BlockState targetBlockState = world.getBlockState(targetLocator.block.getPos()); + BlockState targetBlockState = world.getBlockState(targetLocator.block.getPos()); CompoundTag data = null; if (lv.size() > sourceLocator.offset) { @@ -768,8 +768,8 @@ else if (args.get(0) instanceof final MapValue map) { data = nbtsv.getCompoundTag(); } - final Map state = map.getMap(); - final List mapargs = new ArrayList<>(); + Map state = map.getMap(); + List mapargs = new ArrayList<>(); state.forEach((k, v) -> { mapargs.add(k); mapargs.add(v); @@ -783,16 +783,16 @@ else if (args.get(0) instanceof final MapValue map) data = nbtsv.getCompoundTag(); } } - final StateDefinition states = sourceBlockState.getBlock().getStateDefinition(); + StateDefinition states = sourceBlockState.getBlock().getStateDefinition(); for (int i = 0; i < args.size() - 1; i += 2) { - final String paramString = args.get(i).getString(); - final Property property = states.getProperty(paramString); + String paramString = args.get(i).getString(); + Property property = states.getProperty(paramString); if (property == null) { throw new InternalExpressionException("Property " + paramString + " doesn't apply to " + sourceLocator.block.getString()); } - final String paramValue = args.get(i + 1).getString(); + String paramValue = args.get(i + 1).getString(); sourceBlockState = setProperty(property, paramString, paramValue, sourceBlockState); } } @@ -801,25 +801,25 @@ else if (args.get(0) instanceof final MapValue map) { data = sourceLocator.block.getData(); } - final CompoundTag finalData = data; + CompoundTag finalData = data; if (sourceBlockState == targetBlockState && data == null) { return Value.FALSE; } - final BlockState finalSourceBlockState = sourceBlockState; - final BlockPos targetPos = targetLocator.block.getPos(); - final Boolean[] result = new Boolean[]{true}; + BlockState finalSourceBlockState = sourceBlockState; + BlockPos targetPos = targetLocator.block.getPos(); + Boolean[] result = new Boolean[]{true}; cc.server().executeBlocking(() -> { Clearable.tryClear(world.getBlockEntity(targetPos)); boolean success = world.setBlock(targetPos, finalSourceBlockState, 2); if (finalData != null) { - final BlockEntity be = world.getBlockEntity(targetPos); + BlockEntity be = world.getBlockEntity(targetPos); if (be != null) { - final CompoundTag destTag = finalData.copy(); + CompoundTag destTag = finalData.copy(); destTag.putInt("x", targetPos.getX()); destTag.putInt("y", targetPos.getY()); destTag.putInt("z", targetPos.getZ()); @@ -835,22 +835,22 @@ else if (args.get(0) instanceof final MapValue map) expression.addContextFunction("destroy", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final ServerLevel world = cc.level(); - final BlockArgument locator = BlockArgument.findIn(cc, lv, 0); - final BlockState state = locator.block.getBlockState(); + CarpetContext cc = (CarpetContext) c; + ServerLevel world = cc.level(); + BlockArgument locator = BlockArgument.findIn(cc, lv, 0); + BlockState state = locator.block.getBlockState(); if (state.isAir()) { return Value.FALSE; } - final BlockPos where = locator.block.getPos(); - final BlockEntity be = world.getBlockEntity(where); + BlockPos where = locator.block.getPos(); + BlockEntity be = world.getBlockEntity(where); long how = 0; Item item = Items.DIAMOND_PICKAXE; boolean playerBreak = false; if (lv.size() > locator.offset) { - final Value val = lv.get(locator.offset); + Value val = lv.get(locator.offset); if (val instanceof final NumericValue number) { how = number.getLong(); @@ -858,7 +858,7 @@ else if (args.get(0) instanceof final MapValue map) else { playerBreak = true; - final String itemString = val.getString(); + String itemString = val.getString(); item = cc.registry(Registries.ITEM).getOptional(InputValidator.identifierOf(itemString)) .orElseThrow(() -> new ThrowStatement(itemString, Throwables.UNKNOWN_ITEM)); } @@ -870,22 +870,16 @@ else if (args.get(0) instanceof final MapValue map) { throw new InternalExpressionException("tag is not necessary with 'destroy' with no item"); } - final Value tagValue = lv.get(locator.offset + 1); - if (tagValue.isNull()) - { - tag = null; - } - else if (tagValue instanceof final NBTSerializableValue nbtsv) - { - tag = nbtsv.getCompoundTag(); - } - else + Value tagValue = lv.get(locator.offset + 1); + if (!tagValue.isNull()) { - tag = NBTSerializableValue.parseString(tagValue.getString(), true).getCompoundTag(); + tag = tagValue instanceof final NBTSerializableValue nbtsv + ? nbtsv.getCompoundTag() + : NBTSerializableValue.parseStringOrFail(tagValue.getString()).getCompoundTag(); } } - final ItemStack tool = new ItemStack(item, 1); + ItemStack tool = new ItemStack(item, 1); if (tag != null) { tool.setTag(tag); @@ -894,7 +888,7 @@ else if (tagValue instanceof final NBTSerializableValue nbtsv) { return Value.FALSE; } - final boolean removed = world.removeBlock(where, false); + boolean removed = world.removeBlock(where, false); if (!removed) { return Value.FALSE; @@ -905,9 +899,9 @@ else if (tagValue instanceof final NBTSerializableValue nbtsv) boolean dropLoot = true; if (playerBreak) { - final boolean isUsingEffectiveTool = !state.requiresCorrectToolForDrops() || tool.isCorrectToolForDrops(state); + boolean isUsingEffectiveTool = !state.requiresCorrectToolForDrops() || tool.isCorrectToolForDrops(state); //postMine() durability from item classes - final float hardness = state.getDestroySpeed(world, where); + float hardness = state.getDestroySpeed(world, where); int damageAmount = 0; if ((item instanceof DiggerItem && hardness > 0.0) || item instanceof ShearsItem) { @@ -938,7 +932,7 @@ else if (item instanceof TridentItem || item instanceof SwordItem) } if (DUMMY_ENTITY == null) { - DUMMY_ENTITY = new FallingBlockEntity(EntityType.FALLING_BLOCK, null); + DUMMY_ENTITY = new FallingBlockEntity(EntityType.FALLING_BLOCK, cc.server().overworld()); } Block.dropResources(state, world, where, be, DUMMY_ENTITY, tool); } @@ -951,7 +945,7 @@ else if (item instanceof TridentItem || item instanceof SwordItem) { return Value.NULL; } - final Tag outtag = tool.getTag(); + Tag outtag = tool.getTag(); return outtag == null ? Value.TRUE : new NBTSerializableValue(() -> outtag); }); @@ -962,22 +956,22 @@ else if (item instanceof TridentItem || item instanceof SwordItem) { throw new InternalExpressionException("'harvest' takes at least 2 parameters: entity and block, or position, to harvest"); } - final CarpetContext cc = (CarpetContext) c; - final Level world = cc.level(); - final Value entityValue = lv.get(0); + CarpetContext cc = (CarpetContext) c; + Level world = cc.level(); + Value entityValue = lv.get(0); if (!(entityValue instanceof final EntityValue ev)) { return Value.FALSE; } - final Entity e = ev.getEntity(); + Entity e = ev.getEntity(); if (!(e instanceof final ServerPlayer player)) { return Value.FALSE; } - final BlockArgument locator = BlockArgument.findIn(cc, lv, 1); - final BlockPos where = locator.block.getPos(); - final BlockState state = locator.block.getBlockState(); - final Block block = state.getBlock(); + BlockArgument locator = BlockArgument.findIn(cc, lv, 1); + BlockPos where = locator.block.getPos(); + BlockState state = locator.block.getBlockState(); + Block block = state.getBlock(); boolean success = false; if (!((block == Blocks.BEDROCK || block == Blocks.BARRIER) && player.gameMode.isSurvival())) { @@ -996,14 +990,14 @@ else if (item instanceof TridentItem || item instanceof SwordItem) { throw new InternalExpressionException("'create_explosion' requires at least a position to explode"); } - final CarpetContext cc = (CarpetContext) c; + CarpetContext cc = (CarpetContext) c; float powah = 4.0f; Explosion.BlockInteraction mode = Explosion.BlockInteraction.DESTROY; // should probably read the gamerule for default behaviour boolean createFire = false; Entity source = null; LivingEntity attacker = null; - final Vector3Argument location = Vector3Argument.findIn(lv, 0, false, true); - final Vec3 pos = location.vec; + Vector3Argument location = Vector3Argument.findIn(lv, 0, false, true); + Vec3 pos = location.vec; if (lv.size() > location.offset) { powah = NumericValue.asNumber(lv.get(location.offset), "explosion power").getFloat(); @@ -1013,12 +1007,12 @@ else if (item instanceof TridentItem || item instanceof SwordItem) } if (lv.size() > location.offset + 1) { - final String strval = lv.get(location.offset + 1).getString(); + String strval = lv.get(location.offset + 1).getString(); try { mode = Explosion.BlockInteraction.valueOf(strval.toUpperCase(Locale.ROOT)); } - catch (final IllegalArgumentException ile) + catch (IllegalArgumentException ile) { throw new InternalExpressionException("Illegal explosions block behaviour: " + strval); } @@ -1028,50 +1022,50 @@ else if (item instanceof TridentItem || item instanceof SwordItem) if (lv.size() > location.offset + 3) { Value enVal = lv.get(location.offset + 3); - if (enVal.isNull()) - { - } // is null already - else if (enVal instanceof final EntityValue ev) - { - source = ev.getEntity(); - } - else + if (!enVal.isNull()) { - throw new InternalExpressionException("Fourth parameter of the explosion has to be an entity, not " + enVal.getTypeString()); + if (enVal instanceof final EntityValue ev) + { + source = ev.getEntity(); + } + else + { + throw new InternalExpressionException("Fourth parameter of the explosion has to be an entity, not " + enVal.getTypeString()); + } } if (lv.size() > location.offset + 4) { enVal = lv.get(location.offset + 4); - if (enVal.isNull()) + if (!enVal.isNull()) { - } // is null already - else if (enVal instanceof final EntityValue ev) - { - final Entity attackingEntity = ev.getEntity(); - if (attackingEntity instanceof final LivingEntity le) + if (enVal instanceof final EntityValue ev) { - attacker = le; + Entity attackingEntity = ev.getEntity(); + if (attackingEntity instanceof final LivingEntity le) + { + attacker = le; + } + else + { + throw new InternalExpressionException("Attacking entity needs to be a living thing, " + + ValueConversions.of(cc.registry(Registries.ENTITY_TYPE).getKey(attackingEntity.getType())).getString() + " ain't it."); + } } else { - throw new InternalExpressionException("Attacking entity needs to be a living thing, " + - ValueConversions.of(cc.registry(Registries.ENTITY_TYPE).getKey(attackingEntity.getType())).getString() + " ain't it."); + throw new InternalExpressionException("Fifth parameter of the explosion has to be a living entity, not " + enVal.getTypeString()); } } - else - { - throw new InternalExpressionException("Fifth parameter of the explosion has to be a living entity, not " + enVal.getTypeString()); - } } } } } } - final LivingEntity theAttacker = attacker; - final float thePowah = powah; + LivingEntity theAttacker = attacker; + float thePowah = powah; // copy of ServerWorld.createExplosion #TRACK# - final Explosion explosion = new Explosion(cc.level(), source, null, null, pos.x, pos.y, pos.z, powah, createFire, mode) + Explosion explosion = new Explosion(cc.level(), source, null, null, pos.x, pos.y, pos.z, powah, createFire, mode) { @Override @Nullable @@ -1103,13 +1097,13 @@ LivingEntity getIndirectSourceEntity() { throw new InternalExpressionException("'place_item' takes at least 2 parameters: item and block, or position, to place onto"); } - final CarpetContext cc = (CarpetContext) c; - final String itemString = lv.get(0).getString(); - final Vector3Argument locator = Vector3Argument.findIn(lv, 1); - final ItemInput stackArg = NBTSerializableValue.parseItem(itemString, cc.registryAccess()); - final BlockPos where = new BlockPos(locator.vec); + CarpetContext cc = (CarpetContext) c; + String itemString = lv.get(0).getString(); + Vector3Argument locator = Vector3Argument.findIn(lv, 1); + ItemInput stackArg = NBTSerializableValue.parseItem(itemString, cc.registryAccess()); + BlockPos where = new BlockPos(locator.vec); // Paintings throw an exception if their direction is vertical, therefore we change the default here - final String facing = lv.size() > locator.offset + String facing = lv.size() > locator.offset ? lv.get(locator.offset).getString() : stackArg.getItem() != Items.PAINTING ? "up" : "north"; boolean sneakPlace = false; @@ -1118,19 +1112,19 @@ LivingEntity getIndirectSourceEntity() sneakPlace = lv.get(locator.offset + 1).getBoolean(); } - final BlockValue.PlacementContext ctx; + BlockValue.PlacementContext ctx; try { ctx = BlockValue.PlacementContext.from(cc.level(), where, facing, sneakPlace, stackArg.createItemStack(1, false)); } - catch (final CommandSyntaxException e) + catch (CommandSyntaxException e) { throw new InternalExpressionException(e.getMessage()); } if (!(stackArg.getItem() instanceof final BlockItem blockItem)) { - final InteractionResult useResult = ctx.getItemInHand().useOn(ctx); + InteractionResult useResult = ctx.getItemInHand().useOn(ctx); if (useResult == InteractionResult.CONSUME || useResult == InteractionResult.SUCCESS) { return Value.TRUE; @@ -1142,14 +1136,14 @@ LivingEntity getIndirectSourceEntity() { return Value.FALSE; } - final BlockState placementState = blockItem.getBlock().getStateForPlacement(ctx); + BlockState placementState = blockItem.getBlock().getStateForPlacement(ctx); if (placementState != null) { - final Level level = ctx.getLevel(); + Level level = ctx.getLevel(); if (placementState.canSurvive(level, where)) { level.setBlock(where, placementState, 2); - final SoundType blockSoundGroup = placementState.getSoundType(); + SoundType blockSoundGroup = placementState.getSoundType(); level.playSound(null, where, blockSoundGroup.getPlaceSound(), SoundSource.BLOCKS, (blockSoundGroup.getVolume() + 1.0F) / 2.0F, blockSoundGroup.getPitch() * 0.8F); return Value.TRUE; } @@ -1179,15 +1173,15 @@ LivingEntity getIndirectSourceEntity() expression.addContextFunction("property", -1, (c, t, lv) -> { c.host.issueDeprecation("property(...)"); - final BlockArgument locator = BlockArgument.findIn((CarpetContext) c, lv, 0); - final BlockState state = locator.block.getBlockState(); + BlockArgument locator = BlockArgument.findIn((CarpetContext) c, lv, 0); + BlockState state = locator.block.getBlockState(); if (lv.size() <= locator.offset) { throw new InternalExpressionException("'property' requires to specify a property to query"); } - final String tag = lv.get(locator.offset).getString(); - final StateDefinition states = state.getBlock().getStateDefinition(); - final Property property = states.getProperty(tag); + String tag = lv.get(locator.offset).getString(); + StateDefinition states = state.getBlock().getStateDefinition(); + Property property = states.getProperty(tag); return property == null ? Value.NULL : new StringValue(state.getValue(property).toString().toLowerCase(Locale.ROOT)); }); @@ -1195,9 +1189,9 @@ LivingEntity getIndirectSourceEntity() expression.addContextFunction("block_properties", -1, (c, t, lv) -> { c.host.issueDeprecation("block_properties(...)"); - final BlockArgument locator = BlockArgument.findIn((CarpetContext) c, lv, 0); - final BlockState state = locator.block.getBlockState(); - final StateDefinition states = state.getBlock().getStateDefinition(); + BlockArgument locator = BlockArgument.findIn((CarpetContext) c, lv, 0); + BlockState state = locator.block.getBlockState(); + StateDefinition states = state.getBlock().getStateDefinition(); return ListValue.wrap(states.getProperties().stream().map( p -> new StringValue(p.getName())) ); @@ -1207,89 +1201,89 @@ LivingEntity getIndirectSourceEntity() // block_state(block, property) expression.addContextFunction("block_state", -1, (c, t, lv) -> { - final BlockArgument locator = BlockArgument.findIn((CarpetContext) c, lv, 0, true); - final BlockState state = locator.block.getBlockState(); - final StateDefinition states = state.getBlock().getStateDefinition(); + BlockArgument locator = BlockArgument.findIn((CarpetContext) c, lv, 0, true); + BlockState state = locator.block.getBlockState(); + StateDefinition states = state.getBlock().getStateDefinition(); if (locator.offset == lv.size()) { - final Map properties = new HashMap<>(); - for (final Property p : states.getProperties()) + Map properties = new HashMap<>(); + for (Property p : states.getProperties()) { properties.put(StringValue.of(p.getName()), ValueConversions.fromProperty(state, p)); } return MapValue.wrap(properties); } - final String tag = lv.get(locator.offset).getString(); - final Property property = states.getProperty(tag); + String tag = lv.get(locator.offset).getString(); + Property property = states.getProperty(tag); return property == null ? Value.NULL : ValueConversions.fromProperty(state, property); }); expression.addContextFunction("block_list", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final Registry blocks = cc.registry(Registries.BLOCK); - if (lv.size() == 0) + CarpetContext cc = (CarpetContext) c; + Registry blocks = cc.registry(Registries.BLOCK); + if (lv.isEmpty()) { return ListValue.wrap(blocks.keySet().stream().map(ValueConversions::of)); } - final ResourceLocation tag = InputValidator.identifierOf(lv.get(0).getString()); - final Optional> tagset = blocks.getTag(TagKey.create(Registries.BLOCK, tag)); + ResourceLocation tag = InputValidator.identifierOf(lv.get(0).getString()); + Optional> tagset = blocks.getTag(TagKey.create(Registries.BLOCK, tag)); return tagset.isEmpty() ? Value.NULL : ListValue.wrap(tagset.get().stream().map(b -> ValueConversions.of(blocks.getKey(b.value())))); }); expression.addContextFunction("block_tags", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final Registry blocks = cc.registry(Registries.BLOCK); - if (lv.size() == 0) + CarpetContext cc = (CarpetContext) c; + Registry blocks = cc.registry(Registries.BLOCK); + if (lv.isEmpty()) { return ListValue.wrap(blocks.getTagNames().map(ValueConversions::of)); } - final BlockArgument blockLocator = BlockArgument.findIn(cc, lv, 0, true); + BlockArgument blockLocator = BlockArgument.findIn(cc, lv, 0, true); if (blockLocator.offset == lv.size()) { - final Block target = blockLocator.block.getBlockState().getBlock(); + Block target = blockLocator.block.getBlockState().getBlock(); return ListValue.wrap(blocks.getTags().filter(e -> e.getSecond().stream().anyMatch(h -> (h.value() == target))).map(e -> ValueConversions.of(e.getFirst()))); } - final String tag = lv.get(blockLocator.offset).getString(); - final Optional> tagSet = blocks.getTag(TagKey.create(Registries.BLOCK, InputValidator.identifierOf(tag))); + String tag = lv.get(blockLocator.offset).getString(); + Optional> tagSet = blocks.getTag(TagKey.create(Registries.BLOCK, InputValidator.identifierOf(tag))); return tagSet.isEmpty() ? Value.NULL : BooleanValue.of(blockLocator.block.getBlockState().is(tagSet.get())); }); expression.addContextFunction("biome", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final ServerLevel world = cc.level(); - if (lv.size() == 0) + CarpetContext cc = (CarpetContext) c; + ServerLevel world = cc.level(); + if (lv.isEmpty()) { return ListValue.wrap(world.registryAccess().registryOrThrow(Registries.BIOME).keySet().stream().map(ValueConversions::of)); } - final Biome biome; - final BiomeSource biomeSource = world.getChunkSource().getGenerator().getBiomeSource(); + Biome biome; + BiomeSource biomeSource = world.getChunkSource().getGenerator().getBiomeSource(); if (lv.size() == 1 && lv.get(0) instanceof final MapValue map && biomeSource instanceof final MultiNoiseBiomeSource mnbs ) { - final Value temperature = map.get(new StringValue("temperature")); + Value temperature = map.get(new StringValue("temperature")); nullCheck(temperature, "temperature"); - final Value humidity = map.get(new StringValue("humidity")); + Value humidity = map.get(new StringValue("humidity")); nullCheck(humidity, "humidity"); - final Value continentalness = map.get(new StringValue("continentalness")); + Value continentalness = map.get(new StringValue("continentalness")); nullCheck(continentalness, "continentalness"); - final Value erosion = map.get(new StringValue("erosion")); + Value erosion = map.get(new StringValue("erosion")); nullCheck(erosion, "erosion"); - final Value depth = map.get(new StringValue("depth")); + Value depth = map.get(new StringValue("depth")); nullCheck(depth, "depth"); - final Value weirdness = map.get(new StringValue("weirdness")); + Value weirdness = map.get(new StringValue("weirdness")); nullCheck(weirdness, "weirdness"); - final Climate.TargetPoint point = new Climate.TargetPoint( + Climate.TargetPoint point = new Climate.TargetPoint( Climate.quantizeCoord(numberGetOrThrow(temperature)), Climate.quantizeCoord(numberGetOrThrow(humidity)), Climate.quantizeCoord(numberGetOrThrow(continentalness)), @@ -1298,11 +1292,11 @@ LivingEntity getIndirectSourceEntity() Climate.quantizeCoord(numberGetOrThrow(weirdness)) ); biome = mnbs.getNoiseBiome(point).value(); - final ResourceLocation biomeId = cc.registry(Registries.BIOME).getKey(biome); - return new StringValue(NBTSerializableValue.nameFromRegistryId(biomeId)); + ResourceLocation biomeId = cc.registry(Registries.BIOME).getKey(biome); + return NBTSerializableValue.nameFromRegistryId(biomeId); } - final BlockArgument locator = BlockArgument.findIn(cc, lv, 0, false, false, true); + BlockArgument locator = BlockArgument.findIn(cc, lv, 0, false, false, true); if (locator.replacement != null) { @@ -1319,11 +1313,11 @@ LivingEntity getIndirectSourceEntity() // in locatebiome if (locator.offset == lv.size()) { - final ResourceLocation biomeId = cc.registry(Registries.BIOME).getKey(biome); - return new StringValue(NBTSerializableValue.nameFromRegistryId(biomeId)); + ResourceLocation biomeId = cc.registry(Registries.BIOME).getKey(biome); + return NBTSerializableValue.nameFromRegistryId(biomeId); } - final String biomeFeature = lv.get(locator.offset).getString(); - final BiFunction featureProvider = BiomeInfo.biomeFeatures.get(biomeFeature); + String biomeFeature = lv.get(locator.offset).getString(); + BiFunction featureProvider = BiomeInfo.biomeFeatures.get(biomeFeature); if (featureProvider == null) { throw new InternalExpressionException("Unknown biome feature: " + biomeFeature); @@ -1333,37 +1327,37 @@ LivingEntity getIndirectSourceEntity() expression.addContextFunction("set_biome", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final BlockArgument locator = BlockArgument.findIn(cc, lv, 0); + CarpetContext cc = (CarpetContext) c; + BlockArgument locator = BlockArgument.findIn(cc, lv, 0); if (lv.size() == locator.offset) { throw new InternalExpressionException("'set_biome' needs a biome name as an argument"); } - final String biomeName = lv.get(locator.offset + 0).getString(); + String biomeName = lv.get(locator.offset).getString(); // from locatebiome command code - final Holder biome = cc.registry(Registries.BIOME).getHolder(ResourceKey.create(Registries.BIOME, InputValidator.identifierOf(biomeName))) + Holder biome = cc.registry(Registries.BIOME).getHolder(ResourceKey.create(Registries.BIOME, InputValidator.identifierOf(biomeName))) .orElseThrow(() -> new ThrowStatement(biomeName, Throwables.UNKNOWN_BIOME)); boolean doImmediateUpdate = true; if (lv.size() > locator.offset + 1) { doImmediateUpdate = lv.get(locator.offset + 1).getBoolean(); } - final ServerLevel world = cc.level(); - final BlockPos pos = locator.block.getPos(); - final ChunkAccess chunk = world.getChunk(pos); // getting level chunk instead of protochunk with biomes - final int biomeX = QuartPos.fromBlock(pos.getX()); - final int biomeY = QuartPos.fromBlock(pos.getY()); - final int biomeZ = QuartPos.fromBlock(pos.getZ()); + ServerLevel world = cc.level(); + BlockPos pos = locator.block.getPos(); + ChunkAccess chunk = world.getChunk(pos); // getting level chunk instead of protochunk with biomes + int biomeX = QuartPos.fromBlock(pos.getX()); + int biomeY = QuartPos.fromBlock(pos.getY()); + int biomeZ = QuartPos.fromBlock(pos.getZ()); try { - final int i = QuartPos.fromBlock(chunk.getMinBuildHeight()); - final int j = i + QuartPos.fromBlock(chunk.getHeight()) - 1; - final int k = Mth.clamp(biomeY, i, j); - final int l = chunk.getSectionIndex(QuartPos.toBlock(k)); + int i = QuartPos.fromBlock(chunk.getMinBuildHeight()); + int j = i + QuartPos.fromBlock(chunk.getHeight()) - 1; + int k = Mth.clamp(biomeY, i, j); + int l = chunk.getSectionIndex(QuartPos.toBlock(k)); // accessing outside of the interface - might be dangerous in the future. ((PalettedContainer>) chunk.getSection(l).getBiomes()).set(biomeX & 3, k & 3, biomeZ & 3, biome); } - catch (final Throwable var8) + catch (Throwable var8) { return Value.FALSE; } @@ -1376,67 +1370,67 @@ LivingEntity getIndirectSourceEntity() }); expression.addContextFunction("reload_chunk", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final BlockPos pos = BlockArgument.findIn(cc, lv, 0).block.getPos(); - final ServerLevel world = cc.level(); + CarpetContext cc = (CarpetContext) c; + BlockPos pos = BlockArgument.findIn(cc, lv, 0).block.getPos(); + ServerLevel world = cc.level(); cc.server().executeBlocking(() -> WorldTools.forceChunkUpdate(pos, world)); return Value.TRUE; }); expression.addContextFunction("structure_references", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final BlockArgument locator = BlockArgument.findIn(cc, lv, 0); - final ServerLevel world = cc.level(); - final BlockPos pos = locator.block.getPos(); - final Map references = world.getChunk(pos.getX() >> 4, pos.getZ() >> 4, ChunkStatus.STRUCTURE_REFERENCES).getAllReferences(); - final Registry reg = cc.registry(Registries.STRUCTURE); + CarpetContext cc = (CarpetContext) c; + BlockArgument locator = BlockArgument.findIn(cc, lv, 0); + ServerLevel world = cc.level(); + BlockPos pos = locator.block.getPos(); + Map references = world.getChunk(pos.getX() >> 4, pos.getZ() >> 4, ChunkStatus.STRUCTURE_REFERENCES).getAllReferences(); + Registry reg = cc.registry(Registries.STRUCTURE); if (lv.size() == locator.offset) { return ListValue.wrap(references.entrySet().stream(). filter(e -> e.getValue() != null && !e.getValue().isEmpty()). - map(e -> new StringValue(NBTSerializableValue.nameFromRegistryId(reg.getKey(e.getKey())))) + map(e -> NBTSerializableValue.nameFromRegistryId(reg.getKey(e.getKey()))) ); } - final String simpleStructureName = lv.get(locator.offset).getString().toLowerCase(Locale.ROOT); - final Structure structureName = reg.get(InputValidator.identifierOf(simpleStructureName)); + String simpleStructureName = lv.get(locator.offset).getString().toLowerCase(Locale.ROOT); + Structure structureName = reg.get(InputValidator.identifierOf(simpleStructureName)); if (structureName == null) { return Value.NULL; } - final LongSet structureReferences = references.get(structureName); + LongSet structureReferences = references.get(structureName); if (structureReferences == null || structureReferences.isEmpty()) { return ListValue.of(); } return ListValue.wrap(structureReferences.longStream().mapToObj(l -> ListValue.of( - new NumericValue(16 * ChunkPos.getX(l)), + new NumericValue(16L * ChunkPos.getX(l)), Value.ZERO, - new NumericValue(16 * ChunkPos.getZ(l))))); + new NumericValue(16L * ChunkPos.getZ(l))))); }); expression.addContextFunction("structure_eligibility", -1, (c, t, lv) -> {// TODO rename structureName to class - final CarpetContext cc = (CarpetContext) c; - final BlockArgument locator = BlockArgument.findIn(cc, lv, 0); + CarpetContext cc = (CarpetContext) c; + BlockArgument locator = BlockArgument.findIn(cc, lv, 0); - final ServerLevel world = cc.level(); + ServerLevel world = cc.level(); // well, because - BooYah(world); + theBooYah(world); - final BlockPos pos = locator.block.getPos(); - final List structure = new ArrayList<>(); + BlockPos pos = locator.block.getPos(); + List structure = new ArrayList<>(); boolean needSize = false; boolean singleOutput = false; - final Registry reg = cc.registry(Registries.STRUCTURE); + Registry reg = cc.registry(Registries.STRUCTURE); if (lv.size() > locator.offset) { - final Value requested = lv.get(locator.offset + 0); + Value requested = lv.get(locator.offset); if (!requested.isNull()) { - final String reqString = requested.getString(); - final ResourceLocation id = InputValidator.identifierOf(reqString); - final Structure requestedStructure = reg.get(id); + String reqString = requested.getString(); + ResourceLocation id = InputValidator.identifierOf(reqString); + Structure requestedStructure = reg.get(id); if (requestedStructure != null) { singleOutput = true; @@ -1444,7 +1438,7 @@ LivingEntity getIndirectSourceEntity() } else { - final StructureType sss = cc.registry(Registries.STRUCTURE_TYPE).get(id); + StructureType sss = cc.registry(Registries.STRUCTURE_TYPE).get(id); reg.entrySet().stream().filter(e -> e.getValue().type() == sss).forEach(e -> structure.add(e.getValue())); } if (structure.isEmpty()) @@ -1468,18 +1462,18 @@ LivingEntity getIndirectSourceEntity() } if (singleOutput) { - final StructureStart start = FeatureGenerator.shouldStructureStartAt(world, pos, structure.get(0), needSize); + StructureStart start = FeatureGenerator.shouldStructureStartAt(world, pos, structure.get(0), needSize); return start == null ? Value.NULL : !needSize ? Value.TRUE : ValueConversions.of(start, cc.registryAccess()); } - final Map ret = new HashMap<>(); - for (final Structure str : structure) + Map ret = new HashMap<>(); + for (Structure str : structure) { StructureStart start; try { start = FeatureGenerator.shouldStructureStartAt(world, pos, str, needSize); } - catch (final NullPointerException npe) + catch (NullPointerException npe) { CarpetScriptServer.LOG.error("Failed to detect structure: " + reg.getKey(str)); start = null; @@ -1490,102 +1484,97 @@ LivingEntity getIndirectSourceEntity() continue; } - final Value key = new StringValue(NBTSerializableValue.nameFromRegistryId(reg.getKey(str))); + Value key = NBTSerializableValue.nameFromRegistryId(reg.getKey(str)); ret.put(key, (!needSize) ? Value.NULL : ValueConversions.of(start, cc.registryAccess())); } return MapValue.wrap(ret); }); expression.addContextFunction("structures", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final BlockArgument locator = BlockArgument.findIn(cc, lv, 0); + CarpetContext cc = (CarpetContext) c; + BlockArgument locator = BlockArgument.findIn(cc, lv, 0); - final ServerLevel world = cc.level(); - final BlockPos pos = locator.block.getPos(); - final Map structures = world.getChunk(pos.getX() >> 4, pos.getZ() >> 4, ChunkStatus.STRUCTURE_STARTS).getAllStarts(); - final Registry reg = cc.registry(Registries.STRUCTURE); + ServerLevel world = cc.level(); + BlockPos pos = locator.block.getPos(); + Map structures = world.getChunk(pos.getX() >> 4, pos.getZ() >> 4, ChunkStatus.STRUCTURE_STARTS).getAllStarts(); + Registry reg = cc.registry(Registries.STRUCTURE); if (lv.size() == locator.offset) { - final Map structureList = new HashMap<>(); - for (final Map.Entry entry : structures.entrySet()) + Map structureList = new HashMap<>(); + for (Map.Entry entry : structures.entrySet()) { - final StructureStart start = entry.getValue(); + StructureStart start = entry.getValue(); if (start == StructureStart.INVALID_START) { continue; } - final BoundingBox box = start.getBoundingBox(); + BoundingBox box = start.getBoundingBox(); structureList.put( - new StringValue(NBTSerializableValue.nameFromRegistryId(reg.getKey(entry.getKey()))), + NBTSerializableValue.nameFromRegistryId(reg.getKey(entry.getKey())), ValueConversions.of(box) ); } return MapValue.wrap(structureList); } - final String structureName = lv.get(locator.offset).getString().toLowerCase(Locale.ROOT); + String structureName = lv.get(locator.offset).getString().toLowerCase(Locale.ROOT); return ValueConversions.of(structures.get(reg.get(InputValidator.identifierOf(structureName))), cc.registryAccess()); }); expression.addContextFunction("set_structure", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final BlockArgument locator = BlockArgument.findIn(cc, lv, 0); + CarpetContext cc = (CarpetContext) c; + BlockArgument locator = BlockArgument.findIn(cc, lv, 0); - final ServerLevel world = cc.level(); - final BlockPos pos = locator.block.getPos(); + ServerLevel world = cc.level(); + BlockPos pos = locator.block.getPos(); if (lv.size() == locator.offset) { throw new InternalExpressionException("'set_structure requires at least position and a structure name"); } - final String structureName = lv.get(locator.offset).getString().toLowerCase(Locale.ROOT); - final Structure configuredStructure = FeatureGenerator.resolveConfiguredStructure(structureName, world, pos); + String structureName = lv.get(locator.offset).getString().toLowerCase(Locale.ROOT); + Structure configuredStructure = FeatureGenerator.resolveConfiguredStructure(structureName, world, pos); if (configuredStructure == null) { throw new ThrowStatement(structureName, Throwables.UNKNOWN_STRUCTURE); } // good 'ol pointer - final Value[] result = new Value[]{Value.NULL}; + Value[] result = new Value[]{Value.NULL}; // technically a world modification. Even if we could let it slide, we will still park it ((CarpetContext) c).server().executeBlocking(() -> { - final Map structures = world.getChunk(pos).getAllStarts(); + Map structures = world.getChunk(pos).getAllStarts(); if (lv.size() == locator.offset + 1) { - final Boolean res = FeatureGenerator.plopGrid(configuredStructure, ((CarpetContext) c).level(), locator.block.getPos()); - if (res == null) - { - return; - } + boolean res = FeatureGenerator.plopGrid(configuredStructure, ((CarpetContext) c).level(), locator.block.getPos()); result[0] = res ? Value.TRUE : Value.FALSE; return; } - final Value newValue = lv.get(locator.offset + 1); + Value newValue = lv.get(locator.offset + 1); if (newValue.isNull()) // remove structure { - final Structure structure = configuredStructure; - if (!structures.containsKey(structure)) + if (!structures.containsKey(configuredStructure)) { return; } - final StructureStart start = structures.get(structure); - final ChunkPos structureChunkPos = start.getChunkPos(); - final BoundingBox box = start.getBoundingBox(); + StructureStart start = structures.get(configuredStructure); + ChunkPos structureChunkPos = start.getChunkPos(); + BoundingBox box = start.getBoundingBox(); for (int chx = box.minX() / 16; chx <= box.maxX() / 16; chx++) // minx maxx { for (int chz = box.minZ() / 16; chz <= box.maxZ() / 16; chz++) //minZ maxZ { - final ChunkPos chpos = new ChunkPos(chx, chz); + ChunkPos chpos = new ChunkPos(chx, chz); // getting a chunk will convert it to full, allowing to modify references - final Map references = + Map references = world.getChunk(chpos.getWorldPosition()).getAllReferences(); - if (references.containsKey(structure) && references.get(structure) != null) + if (references.containsKey(configuredStructure) && references.get(configuredStructure) != null) { - references.get(structure).remove(structureChunkPos.toLong()); + references.get(configuredStructure).remove(structureChunkPos.toLong()); } } } - structures.remove(structure); + structures.remove(configuredStructure); result[0] = Value.TRUE; } }); @@ -1595,15 +1584,15 @@ LivingEntity getIndirectSourceEntity() // todo maybe enable chunk blending? expression.addContextFunction("reset_chunk", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final List requestedChunks = new ArrayList<>(); + CarpetContext cc = (CarpetContext) c; + List requestedChunks = new ArrayList<>(); if (lv.size() == 1) { //either one block or list of chunks - final Value first = lv.get(0); + Value first = lv.get(0); if (first instanceof final ListValue list) { - final List listVal = list.getItems(); + List listVal = list.getItems(); BlockArgument locator = BlockArgument.findIn(cc, listVal, 0); requestedChunks.add(new ChunkPos(locator.block.getPos())); while (listVal.size() > locator.offset) @@ -1614,20 +1603,20 @@ LivingEntity getIndirectSourceEntity() } else { - final BlockArgument locator = BlockArgument.findIn(cc, Collections.singletonList(first), 0); + BlockArgument locator = BlockArgument.findIn(cc, Collections.singletonList(first), 0); requestedChunks.add(new ChunkPos(locator.block.getPos())); } } else { BlockArgument locator = BlockArgument.findIn(cc, lv, 0); - final ChunkPos from = new ChunkPos(locator.block.getPos()); + ChunkPos from = new ChunkPos(locator.block.getPos()); if (lv.size() > locator.offset) { locator = BlockArgument.findIn(cc, lv, locator.offset); - final ChunkPos to = new ChunkPos(locator.block.getPos()); - final int xmax = Math.max(from.x, to.x); - final int zmax = Math.max(from.z, to.z); + ChunkPos to = new ChunkPos(locator.block.getPos()); + int xmax = Math.max(from.x, to.x); + int zmax = Math.max(from.z, to.z); for (int x = Math.min(from.x, to.x); x <= xmax; x++) { for (int z = Math.min(from.z, to.z); z <= zmax; z++) @@ -1641,11 +1630,11 @@ LivingEntity getIndirectSourceEntity() requestedChunks.add(from); } } - final ServerLevel world = cc.level(); - final Value[] result = new Value[]{Value.NULL}; + ServerLevel world = cc.level(); + Value[] result = new Value[]{Value.NULL}; ((CarpetContext) c).server().executeBlocking(() -> { - final Map report = Vanilla.ChunkMap_regenerateChunkRegion(world.getChunkSource().chunkMap, requestedChunks); + Map report = Vanilla.ChunkMap_regenerateChunkRegion(world.getChunkSource().chunkMap, requestedChunks); result[0] = MapValue.wrap(report.entrySet().stream().collect(Collectors.toMap( e -> new StringValue(e.getKey()), e -> new NumericValue(e.getValue()) @@ -1656,49 +1645,49 @@ LivingEntity getIndirectSourceEntity() expression.addContextFunction("inhabited_time", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final BlockArgument locator = BlockArgument.findIn(cc, lv, 0); - final BlockPos pos = locator.block.getPos(); + CarpetContext cc = (CarpetContext) c; + BlockArgument locator = BlockArgument.findIn(cc, lv, 0); + BlockPos pos = locator.block.getPos(); return new NumericValue(cc.level().getChunk(pos).getInhabitedTime()); }); expression.addContextFunction("spawn_potential", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final BlockArgument locator = BlockArgument.findIn(cc, lv, 0); - final BlockPos pos = locator.block.getPos(); - double required_charge = 1; + CarpetContext cc = (CarpetContext) c; + BlockArgument locator = BlockArgument.findIn(cc, lv, 0); + BlockPos pos = locator.block.getPos(); + double requiredCharge = 1; if (lv.size() > locator.offset) { - required_charge = NumericValue.asNumber(lv.get(locator.offset)).getDouble(); + requiredCharge = NumericValue.asNumber(lv.get(locator.offset)).getDouble(); } - final NaturalSpawner.SpawnState charger = cc.level().getChunkSource().getLastSpawnState(); - return charger == null ? Value.NULL : new NumericValue(Vanilla.SpawnState_getPotentialCalculator(charger).getPotentialEnergyChange(pos, required_charge) + NaturalSpawner.SpawnState charger = cc.level().getChunkSource().getLastSpawnState(); + return charger == null ? Value.NULL : new NumericValue(Vanilla.SpawnState_getPotentialCalculator(charger).getPotentialEnergyChange(pos, requiredCharge) ); }); expression.addContextFunction("add_chunk_ticket", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - final BlockArgument locator = BlockArgument.findIn(cc, lv, 0); - final BlockPos pos = locator.block.getPos(); + CarpetContext cc = (CarpetContext) c; + BlockArgument locator = BlockArgument.findIn(cc, lv, 0); + BlockPos pos = locator.block.getPos(); if (lv.size() != locator.offset + 2) { throw new InternalExpressionException("'add_chunk_ticket' requires block position, ticket type and radius"); } - final String type = lv.get(locator.offset).getString(); - final TicketType ticket = ticketTypes.get(type.toLowerCase(Locale.ROOT)); + String type = lv.get(locator.offset).getString(); + TicketType ticket = ticketTypes.get(type.toLowerCase(Locale.ROOT)); if (ticket == null) { throw new InternalExpressionException("Unknown ticket type: " + type); } - final int radius = NumericValue.asNumber(lv.get(locator.offset + 1)).getInt(); + int radius = NumericValue.asNumber(lv.get(locator.offset + 1)).getInt(); if (radius < 1 || radius > 32) { throw new InternalExpressionException("Ticket radius should be between 1 and 32 chunks"); } // due to types we will wing it: - final ChunkPos target = new ChunkPos(pos); + ChunkPos target = new ChunkPos(pos); if (ticket == TicketType.PORTAL) // portal { cc.level().getChunkSource().addRegionTicket(TicketType.PORTAL, target, radius, pos); @@ -1716,29 +1705,29 @@ else if (ticket == TicketType.POST_TELEPORT) // post teleport expression.addContextFunction("sample_noise", -1, (c, t, lv) -> { - final CarpetContext cc = (CarpetContext) c; - if (lv.size() == 0) + CarpetContext cc = (CarpetContext) c; + if (lv.isEmpty()) { return ListValue.wrap(cc.registry(Registries.DENSITY_FUNCTION).keySet().stream().map(ValueConversions::of)); } - final ServerLevel level = cc.level(); - final BlockArgument locator = BlockArgument.findIn(cc, lv, 0); - final BlockPos pos = locator.block.getPos(); - final String[] densityFunctionQueries = lv.stream().skip(locator.offset).map(Value::getString).toArray(String[]::new); + ServerLevel level = cc.level(); + BlockArgument locator = BlockArgument.findIn(cc, lv, 0); + BlockPos pos = locator.block.getPos(); + String[] densityFunctionQueries = lv.stream().skip(locator.offset).map(Value::getString).toArray(String[]::new); if (densityFunctionQueries.length == 0) { return ListValue.wrap(cc.registry(Registries.DENSITY_FUNCTION).keySet().stream().map(ValueConversions::of)); } - final NoiseRouter router = level.getChunkSource().randomState().router(); + NoiseRouter router = level.getChunkSource().randomState().router(); return densityFunctionQueries.length == 1 ? NumericValue.of(sampleNoise(router, level, densityFunctionQueries[0], pos)) : ListValue.wrap(Arrays.stream(densityFunctionQueries).map(s -> NumericValue.of(sampleNoise(router, level, s, pos)))); }); } - public static double sampleNoise(final NoiseRouter router, final ServerLevel level, final String what, final BlockPos pos) + public static double sampleNoise(NoiseRouter router, ServerLevel level, String what, BlockPos pos) { - final DensityFunction densityFunction = switch (what) + DensityFunction densityFunction = switch (what) { case "barrier_noise" -> router.barrierNoise(); case "fluid_level_floodedness_noise" -> router.fluidLevelFloodednessNoise(); @@ -1761,7 +1750,7 @@ public static double sampleNoise(final NoiseRouter router, final ServerLevel lev } // to be used with future seedable noise - public static Function, DensityFunction> stupidWorldgenNoiseCacheGetter = Util.memoize(pair -> { + public static final Function, DensityFunction> stupidWorldgenNoiseCacheGetter = Util.memoize(pair -> { ServerLevel level = pair.getKey(); String densityFunctionQuery = pair.getValue(); ChunkGenerator generator = level.getChunkSource().getGenerator(); @@ -1769,7 +1758,7 @@ public static double sampleNoise(final NoiseRouter router, final ServerLevel lev if (generator instanceof final NoiseBasedChunkGenerator noiseBasedChunkGenerator) { Registry densityFunctionRegistry = level.registryAccess().registryOrThrow(Registries.DENSITY_FUNCTION); - final NoiseRouter router = noiseBasedChunkGenerator.generatorSettings().value().noiseRouter(); + NoiseRouter router = noiseBasedChunkGenerator.generatorSettings().value().noiseRouter(); DensityFunction densityFunction = switch (densityFunctionQuery) { case "barrier_noise" -> router.barrierNoise(); @@ -1788,14 +1777,12 @@ public static double sampleNoise(final NoiseRouter router, final ServerLevel lev case "vein_ridged" -> router.veinRidged(); case "vein_gap" -> router.veinGap(); default -> { - ResourceLocation densityFunctionKey = InputValidator.identifierOf(densityFunctionQuery); - - if (densityFunctionRegistry.containsKey(densityFunctionKey)) + DensityFunction result = densityFunctionRegistry.get(InputValidator.identifierOf(densityFunctionQuery)); + if (result == null) { - yield densityFunctionRegistry.get(densityFunctionKey); + throw new InternalExpressionException("Density function '" + densityFunctionQuery + "' is not defined in the registies."); } - - throw new InternalExpressionException("Density function '" + densityFunctionQuery + "' is not defined in the registies."); + yield result; } }; diff --git a/src/main/java/carpet/script/argument/Argument.java b/src/main/java/carpet/script/argument/Argument.java index 4fac0a370f..e6702991d6 100644 --- a/src/main/java/carpet/script/argument/Argument.java +++ b/src/main/java/carpet/script/argument/Argument.java @@ -2,7 +2,7 @@ public abstract class Argument { - public int offset; + public final int offset; protected Argument(int offset) { diff --git a/src/main/java/carpet/script/argument/BlockArgument.java b/src/main/java/carpet/script/argument/BlockArgument.java index 4641b48de5..b9f1040d14 100644 --- a/src/main/java/carpet/script/argument/BlockArgument.java +++ b/src/main/java/carpet/script/argument/BlockArgument.java @@ -14,53 +14,55 @@ import net.minecraft.core.BlockPos; +import javax.annotation.Nullable; + public class BlockArgument extends Argument { public final BlockValue block; - public final String replacement; + @Nullable public final String replacement; - private BlockArgument(final BlockValue b, final int o) + private BlockArgument(BlockValue b, int o) { super(o); block = b; replacement = null; } - private BlockArgument(final BlockValue b, final int o, final String replacement) + private BlockArgument(BlockValue b, int o, @Nullable String replacement) { super(o); block = b; this.replacement = replacement; } - public static BlockArgument findIn(final CarpetContext c, final List params, final int offset) + public static BlockArgument findIn(CarpetContext c, List params, int offset) { return findIn(c, params, offset, false, false, false); } - public static BlockArgument findIn(final CarpetContext c, final List params, final int offset, final boolean acceptString) + public static BlockArgument findIn(CarpetContext c, List params, int offset, boolean acceptString) { return findIn(c, params, offset, acceptString, false, false); } - public static BlockArgument findIn(final CarpetContext c, final List params, final int offset, final boolean acceptString, final boolean optional, final boolean anyString) + public static BlockArgument findIn(CarpetContext c, List params, int offset, boolean acceptString, boolean optional, boolean anyString) { return findIn(c, params.listIterator(offset), offset, acceptString, optional, anyString); } - public static BlockArgument findIn(final CarpetContext c, final Iterator params, final int offset, final boolean acceptString, final boolean optional, final boolean anyString) + public static BlockArgument findIn(CarpetContext c, Iterator params, int offset, boolean acceptString, boolean optional, boolean anyString) { try { - final Value v1 = params.next(); + Value v1 = params.next(); //add conditional from string name if (optional && v1.isNull()) { - return new BlockArgument(null, 1 + offset); + return new MissingBlockArgument(1 + offset, null); } if (anyString && v1 instanceof StringValue) { - return new BlockArgument(null, 1 + offset, v1.getString()); + return new MissingBlockArgument(1 + offset, v1.getString()); } if (acceptString && v1 instanceof StringValue) { @@ -70,28 +72,26 @@ public static BlockArgument findIn(final CarpetContext c, final Iterator { return new BlockArgument(((BlockValue) v1), 1 + offset); } - final BlockPos pos = c.origin(); + BlockPos pos = c.origin(); if (v1 instanceof ListValue) { - final List args = ((ListValue) v1).getItems(); - final int xpos = (int) NumericValue.asNumber(args.get(0)).getLong(); - final int ypos = (int) NumericValue.asNumber(args.get(1)).getLong(); - final int zpos = (int) NumericValue.asNumber(args.get(2)).getLong(); + List args = ((ListValue) v1).getItems(); + int xpos = (int) NumericValue.asNumber(args.get(0)).getLong(); + int ypos = (int) NumericValue.asNumber(args.get(1)).getLong(); + int zpos = (int) NumericValue.asNumber(args.get(2)).getLong(); return new BlockArgument( new BlockValue( - null, c.level(), new BlockPos(pos.getX() + xpos, pos.getY() + ypos, pos.getZ() + zpos) ), 1 + offset); } - final int xpos = (int) NumericValue.asNumber(v1).getLong(); - final int ypos = (int) NumericValue.asNumber(params.next()).getLong(); - final int zpos = (int) NumericValue.asNumber(params.next()).getLong(); + int xpos = (int) NumericValue.asNumber(v1).getLong(); + int ypos = (int) NumericValue.asNumber(params.next()).getLong(); + int zpos = (int) NumericValue.asNumber(params.next()).getLong(); return new BlockArgument( new BlockValue( - null, c.level(), new BlockPos(pos.getX() + xpos, pos.getY() + ypos, pos.getZ() + zpos) ), @@ -104,7 +104,15 @@ public static BlockArgument findIn(final CarpetContext c, final Iterator } } - private static InternalExpressionException handleError(final boolean optional, final boolean acceptString) + public static class MissingBlockArgument extends BlockArgument + { + public MissingBlockArgument(int o, @Nullable String replacement) + { + super(BlockValue.NONE, o, replacement); + } + } + + private static InternalExpressionException handleError(boolean optional, boolean acceptString) { String message = "Block-type argument should be defined either by three coordinates (a triple or by three arguments), or a block value"; if (acceptString) diff --git a/src/main/java/carpet/script/argument/FileArgument.java b/src/main/java/carpet/script/argument/FileArgument.java index 57e75f88d6..c5e3cb5336 100644 --- a/src/main/java/carpet/script/argument/FileArgument.java +++ b/src/main/java/carpet/script/argument/FileArgument.java @@ -22,6 +22,7 @@ import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.tuple.Pair; +import javax.annotation.Nullable; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; @@ -50,15 +51,15 @@ public class FileArgument { - public String resource; - public Type type; - public String zipContainer; - public boolean isFolder; - public boolean isShared; - public Reason reason; + public final String resource; + public final Type type; + public final String zipContainer; + public final boolean isFolder; + public final boolean isShared; + public final Reason reason; private FileSystem zfs; private Path zipPath; - private ScriptHost host; + private final ScriptHost host; public static final Object writeIOSync = new Object(); @@ -70,7 +71,7 @@ public void close() { zfs.close(); } - catch (final IOException e) + catch (IOException e) { throw new InternalExpressionException("Unable to close zip container: " + zipContainer); } @@ -90,9 +91,9 @@ public enum Type private final String id; private final String extension; - public static Map of = Arrays.stream(values()).collect(Collectors.toMap(t -> t.id, t -> t)); + private static final Map of = Arrays.stream(values()).collect(Collectors.toMap(t -> t.id, t -> t)); - Type(final String id, final String extension) + Type(String id, String extension) { this.id = id; this.extension = extension; @@ -104,7 +105,7 @@ public enum Reason READ, CREATE, DELETE } - public FileArgument(final String resource, final Type type, final String zipContainer, final boolean isFolder, final boolean isShared, final Reason reason, final ScriptHost host) + public FileArgument(@Nullable String resource, Type type, @Nullable String zipContainer, boolean isFolder, boolean isShared, Reason reason, ScriptHost host) { this.resource = resource; this.type = type; @@ -120,24 +121,24 @@ public FileArgument(final String resource, final Type type, final String zipCont @Override public String toString() { - return "path: " + resource + " zip: " + zipContainer + " type: " + type.id + " folder: " + isFolder + " shared: " + isShared + " reason: " + reason.toString(); + return "path: " + resource + " zip: " + zipContainer + " type: " + type.id + " folder: " + isFolder + " shared: " + isShared + " reason: " + reason; } - public static FileArgument from(final Context context, final List lv, final boolean isFolder, final Reason reason) + public static FileArgument from(Context context, List lv, boolean isFolder, Reason reason) { if (lv.size() < 2) { throw new InternalExpressionException("File functions require path and type as first two arguments"); } - final String origtype = lv.get(1).getString().toLowerCase(Locale.ROOT); - final boolean shared = origtype.startsWith("shared_"); - final String typeString = shared ? origtype.substring(7) : origtype; //len(shared_) - final Type type = Type.of.get(typeString); - final Pair resource = recognizeResource(lv.get(0).getString(), isFolder, type); + String origtype = lv.get(1).getString().toLowerCase(Locale.ROOT); + boolean shared = origtype.startsWith("shared_"); + String typeString = shared ? origtype.substring(7) : origtype; //len(shared_) + Type type = Type.of.get(typeString); if (type == null) { throw new InternalExpressionException("Unsupported file type: " + origtype); } + Pair resource = recognizeResource(lv.get(0).getString(), isFolder, type); if (type == Type.FOLDER && !isFolder) { throw new InternalExpressionException("Folder types are no supported for this IO function"); @@ -146,21 +147,21 @@ public static FileArgument from(final Context context, final List lv, fin } - public static FileArgument resourceFromPath(final ScriptHost host, final String path, final Reason reason, final boolean shared) + public static FileArgument resourceFromPath(ScriptHost host, String path, Reason reason, boolean shared) { - final Pair resource = recognizeResource(path, false, Type.ANY); + Pair resource = recognizeResource(path, false, Type.ANY); return new FileArgument(resource.getLeft(), Type.ANY, resource.getRight(), false, shared, reason, host); } - public static Pair recognizeResource(final String origfile, final boolean isFolder, final Type type) + public static Pair recognizeResource(String origfile, boolean isFolder, Type type) { - final String[] pathElements = origfile.split("[/\\\\]+"); - final List path = new ArrayList<>(); + String[] pathElements = origfile.split("[/\\\\]+"); + List path = new ArrayList<>(); String zipPath = null; for (int i = 0; i < pathElements.length; i++) { String token = pathElements[i]; - final boolean isZip = token.endsWith(".zip") && (isFolder || (i < pathElements.length - 1)); + boolean isZip = token.endsWith(".zip") && (isFolder || (i < pathElements.length - 1)); if (zipPath != null && isZip) { throw new InternalExpressionException(token + " indicates zip access in an already zipped location " + zipPath); @@ -196,12 +197,13 @@ public static Pair recognizeResource(final String origfile, fina return Pair.of(String.join("/", path), zipPath); } - private Path resolve(final String suffix) + private Path resolve(String suffix) { return host.resolveScriptFile(suffix); } - private Path toPath(final Module module) + @Nullable + private Path toPath(@Nullable Module module) { if (!isShared && module == null) { @@ -215,7 +217,7 @@ private Path toPath(final Module module) { if (zfs == null) { - final Map env = new HashMap<>(); + Map env = new HashMap<>(); if (reason == Reason.CREATE) { env.put("create", "true"); @@ -233,7 +235,7 @@ private Path toPath(final Module module) } zfs = FileSystems.newFileSystem(URI.create("jar:" + zipPath.toUri()), env); } - catch (final FileSystemNotFoundException | IOException e) + catch (FileSystemNotFoundException | IOException e) { CarpetScriptServer.LOG.warn("Exception when opening zip file", e); throw new ThrowStatement("Unable to open zip file: " + zipContainer, Throwables.IO_EXCEPTION); @@ -243,7 +245,8 @@ private Path toPath(final Module module) } } - private Path moduleRootPath(final Module module) + @Nullable + private Path moduleRootPath(@Nullable Module module) { return !isShared && module == null ? null @@ -255,7 +258,7 @@ public String getDisplayPath() return (isShared ? "shared/" : "") + (zipContainer != null ? zipContainer + "/" : "") + resource + type.extension; } - private String getDescriptor(final Module module, final String res) + private String getDescriptor(@Nullable Module module, @Nullable String res) { if (isShared) { @@ -269,13 +272,13 @@ private String getDescriptor(final Module module, final String res) } - public boolean findPathAndApply(final Module module, final Consumer action) + public boolean findPathAndApply(Module module, Consumer action) { try { synchronized (writeIOSync) { - final Path dataFile = toPath(module);//, resourceName, supportedTypes.get(type), isShared); + Path dataFile = toPath(module);//, resourceName, supportedTypes.get(type), isShared); if (dataFile == null) { return false; @@ -291,14 +294,15 @@ public boolean findPathAndApply(final Module module, final Consumer action return true; } - public Stream listFiles(final Module module) + @Nullable + public Stream listFiles(Module module) { - final Path dir = toPath(module); + Path dir = toPath(module); if (dir == null || !Files.exists(dir)) { return null; } - final String ext = type.extension; + String ext = type.extension; try { return Files.list(dir).filter(path -> (type == Type.FOLDER) @@ -306,16 +310,17 @@ public Stream listFiles(final Module module) : (Files.isRegularFile(path) && path.toString().endsWith(ext)) ); } - catch (final IOException ignored) + catch (IOException ignored) { return null; } } - public Stream listFolder(final Module module) + @Nullable + public Stream listFolder(Module module) { Stream strings; - try (final Stream result = listFiles(module)) + try (Stream result = listFiles(module)) { synchronized (writeIOSync) { @@ -323,12 +328,12 @@ public Stream listFolder(final Module module) { return null; } - final Path rootPath = moduleRootPath(module); + Path rootPath = moduleRootPath(module); if (rootPath == null) { return null; } - final String zipComponent = (zipContainer != null) ? rootPath.relativize(zipPath).toString() : null; + String zipComponent = (zipContainer != null) ? rootPath.relativize(zipPath).toString() : null; // need to evaluate the stream before exiting try-with-resources else there'll be no data to stream strings = (zipContainer == null) ? result.map(p -> rootPath.relativize(p).toString().replaceAll("[\\\\/]+", "/")).toList().stream() @@ -345,7 +350,7 @@ public Stream listFolder(final Module module) : strings.map(FilenameUtils::removeExtension); } - private void createPaths(final Path file) + private void createPaths(Path file) { try { @@ -357,29 +362,29 @@ private void createPaths(final Path file) throw new IOException(); } } - catch (final IOException e) + catch (IOException e) { CarpetScriptServer.LOG.warn("IOException when creating paths", e); throw new ThrowStatement("Unable to create paths for " + file, Throwables.IO_EXCEPTION); } } - public boolean appendToTextFile(final Module module, final List message) + public boolean appendToTextFile(Module module, List message) { try { synchronized (writeIOSync) { - final Path dataFile = toPath(module); + Path dataFile = toPath(module); if (dataFile == null) { return false; } createPaths(dataFile); - final OutputStream out = Files.newOutputStream(dataFile, StandardOpenOption.APPEND, StandardOpenOption.CREATE); - try (final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8))) + OutputStream out = Files.newOutputStream(dataFile, StandardOpenOption.APPEND, StandardOpenOption.CREATE); + try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8))) { - for (final String line : message) + for (String line : message) { writer.append(line); if (type == Type.TEXT) @@ -390,7 +395,7 @@ public boolean appendToTextFile(final Module module, final List message) } } } - catch (final IOException e) + catch (IOException e) { CarpetScriptServer.LOG.warn("IOException when appending to text file", e); throw new ThrowStatement("Error when writing to the file: " + e, Throwables.IO_EXCEPTION); @@ -402,13 +407,14 @@ public boolean appendToTextFile(final Module module, final List message) return true; } - public Tag getNbtData(final Module module) // aka getData + @Nullable + public Tag getNbtData(Module module) // aka getData { try { synchronized (writeIOSync) { - final Path dataFile = toPath(module); + Path dataFile = toPath(module); if (dataFile == null || !Files.exists(dataFile)) { return null; @@ -424,29 +430,30 @@ public Tag getNbtData(final Module module) // aka getData //copied private method from net.minecraft.nbt.NbtIo.read() // to read non-compound tags - these won't be compressed - public static Tag readTag(final Path path) + @Nullable + public static Tag readTag(Path path) { try { return NbtIo.readCompressed(Files.newInputStream(path)); } - catch (final IOException e) + catch (IOException e) { // Copy of NbtIo.read(File) because that's now client-side only if (!Files.exists(path)) { return null; } - try (final DataInputStream in = new DataInputStream(new BufferedInputStream(Files.newInputStream(path)))) + try (DataInputStream in = new DataInputStream(new BufferedInputStream(Files.newInputStream(path)))) { return NbtIo.read(in); } - catch (final IOException ioException) + catch (IOException ioException) { // not compressed compound tag neither uncompressed compound tag - trying any type of a tag - try (final DataInputStream dataInputStream = new DataInputStream(new BufferedInputStream(Files.newInputStream(path)))) + try (DataInputStream dataInputStream = new DataInputStream(new BufferedInputStream(Files.newInputStream(path)))) { - final byte b = dataInputStream.readByte(); + byte b = dataInputStream.readByte(); if (b == 0) { return null; @@ -457,7 +464,7 @@ public static Tag readTag(final Path path) return TagTypes.getType(b).load(dataInputStream, 0, NbtAccounter.UNLIMITED); } } - catch (final IOException secondIO) + catch (IOException secondIO) { CarpetScriptServer.LOG.warn("IOException when trying to read nbt file, something may have gone wrong with the fs", e); CarpetScriptServer.LOG.warn("", ioException); @@ -466,19 +473,19 @@ public static Tag readTag(final Path path) } } } - catch (final ReportedException e) + catch (ReportedException e) { - throw new ThrowStatement("Error when reading NBT file " + path.toString(), Throwables.NBT_ERROR); + throw new ThrowStatement("Error when reading NBT file " + path, Throwables.NBT_ERROR); } } - public boolean saveNbtData(final Module module, final Tag tag) // aka saveData + public boolean saveNbtData(Module module, Tag tag) // aka saveData { try { synchronized (writeIOSync) { - final Path dataFile = toPath(module); + Path dataFile = toPath(module); if (dataFile == null) { return false; @@ -494,9 +501,9 @@ public boolean saveNbtData(final Module module, final Tag tag) // aka saveData } //copied private method from net.minecraft.nbt.NbtIo.write() and client method safe_write - public static boolean writeTagDisk(final Tag tag, Path path, final boolean zipped) + public static boolean writeTagDisk(Tag tag, Path path, boolean zipped) { - final Path original = path; + Path original = path; try { if (!zipped) @@ -511,7 +518,7 @@ public static boolean writeTagDisk(final Tag tag, Path path, final boolean zippe } else { - try (final DataOutputStream dataOutputStream = new DataOutputStream(Files.newOutputStream(path))) + try (DataOutputStream dataOutputStream = new DataOutputStream(Files.newOutputStream(path))) { dataOutputStream.writeByte(tag.getId()); if (tag.getId() != 0) @@ -528,20 +535,20 @@ public static boolean writeTagDisk(final Tag tag, Path path, final boolean zippe } return true; } - catch (final IOException e) + catch (IOException e) { CarpetScriptServer.LOG.warn("IO Exception when writing nbt file", e); throw new ThrowStatement("Unable to write tag to " + original, Throwables.IO_EXCEPTION); } } - public boolean dropExistingFile(final Module module) + public boolean dropExistingFile(Module module) { try { synchronized (writeIOSync) { - final Path dataFile = toPath(module); + Path dataFile = toPath(module); if (dataFile == null) { return false; @@ -549,7 +556,7 @@ public boolean dropExistingFile(final Module module) return Files.deleteIfExists(dataFile); } } - catch (final IOException e) + catch (IOException e) { CarpetScriptServer.LOG.warn("IOException when removing file", e); throw new ThrowStatement("Error while removing file: " + getDisplayPath(), Throwables.IO_EXCEPTION); @@ -560,13 +567,14 @@ public boolean dropExistingFile(final Module module) } } - public List listFile(final Module module) + @Nullable + public List listFile(Module module) { try { synchronized (writeIOSync) { - final Path dataFile = toPath(module); + Path dataFile = toPath(module); if (dataFile == null) { return null; @@ -584,14 +592,14 @@ public List listFile(final Module module) } } - public static List listFileContent(final Path filePath) + public static List listFileContent(Path filePath) { - try (final BufferedReader reader = Files.newBufferedReader(filePath, StandardCharsets.UTF_8)) + try (BufferedReader reader = Files.newBufferedReader(filePath, StandardCharsets.UTF_8)) { - final List result = new ArrayList<>(); + List result = new ArrayList<>(); for (; ; ) { - final String line = reader.readLine(); + String line = reader.readLine(); if (line == null) { break; @@ -600,20 +608,21 @@ public static List listFileContent(final Path filePath) } return result; } - catch (final IOException e) + catch (IOException e) { CarpetScriptServer.LOG.warn("IOException when reading text file", e); throw new ThrowStatement("Failed to read text file " + filePath, Throwables.IO_EXCEPTION); } } - public JsonElement readJsonFile(final Module module) + @Nullable + public JsonElement readJsonFile(Module module) { try { synchronized (writeIOSync) { - final Path dataFile = toPath(module); + Path dataFile = toPath(module); if (dataFile == null || !Files.exists(dataFile)) { return null; @@ -627,13 +636,13 @@ public JsonElement readJsonFile(final Module module) } } - public static JsonElement readJsonContent(final Path filePath) + public static JsonElement readJsonContent(Path filePath) { - try (final BufferedReader reader = Files.newBufferedReader(filePath, StandardCharsets.UTF_8)) + try (BufferedReader reader = Files.newBufferedReader(filePath, StandardCharsets.UTF_8)) { return JsonParser.parseReader(reader); } - catch (final JsonParseException e) + catch (JsonParseException e) { Throwable exc = e; if (e.getCause() != null) @@ -645,7 +654,7 @@ public static JsonElement readJsonContent(final Path filePath) StringValue.of("path"), StringValue.of(filePath.toString()) )), Throwables.JSON_ERROR); } - catch (final IOException e) + catch (IOException e) { CarpetScriptServer.LOG.warn("IOException when reading JSON file", e); throw new ThrowStatement("Failed to read json file content " + filePath, Throwables.IO_EXCEPTION); diff --git a/src/main/java/carpet/script/argument/FunctionArgument.java b/src/main/java/carpet/script/argument/FunctionArgument.java index eb19526fb0..b30f2f5606 100644 --- a/src/main/java/carpet/script/argument/FunctionArgument.java +++ b/src/main/java/carpet/script/argument/FunctionArgument.java @@ -10,16 +10,17 @@ import carpet.script.value.Value; import com.mojang.brigadier.exceptions.CommandSyntaxException; +import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class FunctionArgument extends Argument { - public FunctionValue function; - public List args; + public final FunctionValue function; + public final List args; - private FunctionArgument(final FunctionValue function, final int offset, final List args) + private FunctionArgument(@Nullable FunctionValue function, int offset, List args) { super(offset); this.function = function; @@ -38,12 +39,12 @@ private FunctionArgument(final FunctionValue function, final int offset, final L * @return argument data */ public static FunctionArgument findIn( - final Context c, - final Module module, - final List params, - final int offset, - final boolean allowNone, - final boolean checkArgs) + Context c, + Module module, + List params, + int offset, + boolean allowNone, + boolean checkArgs) { Value functionValue = params.get(offset); if (functionValue.isNull()) @@ -56,14 +57,14 @@ public static FunctionArgument findIn( } if (!(functionValue instanceof FunctionValue)) { - final String name = functionValue.getString(); + String name = functionValue.getString(); functionValue = c.host.getAssertFunction(module, name); } - final FunctionValue fun = (FunctionValue) functionValue; - final int argsize = fun.getArguments().size(); + FunctionValue fun = (FunctionValue) functionValue; + int argsize = fun.getArguments().size(); if (checkArgs) { - final int extraargs = params.size() - argsize - offset - 1; + int extraargs = params.size() - argsize - offset - 1; if (extraargs < 0) { throw new InternalExpressionException("Function " + fun.getPrettyString() + " requires at least " + fun.getArguments().size() + " arguments"); @@ -73,7 +74,7 @@ public static FunctionArgument findIn( throw new InternalExpressionException("Function " + fun.getPrettyString() + " requires " + fun.getArguments().size() + " arguments"); } } - final List lvargs = new ArrayList<>(); + List lvargs = new ArrayList<>(); for (int i = offset + 1, mx = params.size(); i < mx; i++) { lvargs.add(params.get(i)); @@ -81,27 +82,27 @@ public static FunctionArgument findIn( return new FunctionArgument(fun, offset + 1 + argsize, lvargs); } - public static FunctionArgument fromCommandSpec(final ScriptHost host, Value funSpec) throws CommandSyntaxException + public static FunctionArgument fromCommandSpec(ScriptHost host, Value funSpec) throws CommandSyntaxException { - final FunctionValue function; + FunctionValue function; List args = Collections.emptyList(); if (!(funSpec instanceof ListValue)) { funSpec = ListValue.of(funSpec); } - final List params = ((ListValue) funSpec).getItems(); + List params = ((ListValue) funSpec).getItems(); if (params.isEmpty()) { throw CommandArgument.error("Function has empty spec"); } - final Value first = params.get(0); + Value first = params.get(0); if (first instanceof FunctionValue) { function = (FunctionValue) first; } else { - final String name = first.getString(); + String name = first.getString(); function = host.getFunction(name); if (function == null) { diff --git a/src/main/java/carpet/script/argument/Vector3Argument.java b/src/main/java/carpet/script/argument/Vector3Argument.java index f46068e8fe..6f475f44a1 100644 --- a/src/main/java/carpet/script/argument/Vector3Argument.java +++ b/src/main/java/carpet/script/argument/Vector3Argument.java @@ -14,15 +14,18 @@ import net.minecraft.world.entity.Entity; import net.minecraft.world.phys.Vec3; +import javax.annotation.Nullable; + public class Vector3Argument extends Argument { public Vec3 vec; public final double yaw; public final double pitch; public boolean fromBlock = false; + @Nullable public Entity entity = null; - private Vector3Argument(final Vec3 v, final int o) + private Vector3Argument(Vec3 v, int o) { super(o); this.vec = v; @@ -30,7 +33,7 @@ private Vector3Argument(final Vec3 v, final int o) this.pitch = 0.0D; } - private Vector3Argument(final Vec3 v, final int o, final double y, final double p) + private Vector3Argument(Vec3 v, int o, double y, double p) { super(o); this.vec = v; @@ -44,40 +47,40 @@ private Vector3Argument fromBlock() return this; } - private Vector3Argument withEntity(final Entity e) + private Vector3Argument withEntity(Entity e) { entity = e; return this; } - public static Vector3Argument findIn(final List params, final int offset) + public static Vector3Argument findIn(List params, int offset) { return findIn(params, offset, false, false); } - public static Vector3Argument findIn(final List params, final int offset, final boolean optionalDirection, final boolean optionalEntity) + public static Vector3Argument findIn(List params, int offset, boolean optionalDirection, boolean optionalEntity) { return findIn(params.listIterator(offset), offset, optionalDirection, optionalEntity); } - public static Vector3Argument findIn(final Iterator params, final int offset, final boolean optionalDirection, final boolean optionalEntity) + public static Vector3Argument findIn(Iterator params, int offset, boolean optionalDirection, boolean optionalEntity) { try { - final Value v1 = params.next(); + Value v1 = params.next(); if (v1 instanceof BlockValue) { return (new Vector3Argument(Vec3.atCenterOf(((BlockValue) v1).getPos()), 1 + offset)).fromBlock(); } if (optionalEntity && v1 instanceof EntityValue) { - final Entity e = ((EntityValue) v1).getEntity(); + Entity e = ((EntityValue) v1).getEntity(); return new Vector3Argument(e.position(), 1 + offset).withEntity(e); } if (v1 instanceof ListValue) { - final List args = ((ListValue) v1).getItems(); - final Vec3 pos = new Vec3( + List args = ((ListValue) v1).getItems(); + Vec3 pos = new Vec3( NumericValue.asNumber(args.get(0)).getDouble(), NumericValue.asNumber(args.get(1)).getDouble(), NumericValue.asNumber(args.get(2)).getDouble()); @@ -90,7 +93,7 @@ public static Vector3Argument findIn(final Iterator params, final int off } return new Vector3Argument(pos, offset + 1, yaw, pitch); } - final Vec3 pos = new Vec3( + Vec3 pos = new Vec3( NumericValue.asNumber(v1).getDouble(), NumericValue.asNumber(params.next()).getDouble(), NumericValue.asNumber(params.next()).getDouble()); @@ -106,7 +109,7 @@ public static Vector3Argument findIn(final Iterator params, final int off return new Vector3Argument(pos, offset + eatenLength, yaw, pitch); } - catch (final IndexOutOfBoundsException | NoSuchElementException e) + catch (IndexOutOfBoundsException | NoSuchElementException e) { throw new InternalExpressionException("Position argument should be defined either by three coordinates (a triple or by three arguments), or a positioned block value"); } diff --git a/src/main/java/carpet/script/command/CommandArgument.java b/src/main/java/carpet/script/command/CommandArgument.java index e6d2a30782..a0e43b500c 100644 --- a/src/main/java/carpet/script/command/CommandArgument.java +++ b/src/main/java/carpet/script/command/CommandArgument.java @@ -107,11 +107,13 @@ import net.minecraft.world.phys.Vec2; import net.minecraft.world.scores.Scoreboard; +import javax.annotation.Nullable; + import static net.minecraft.commands.Commands.argument; public abstract class CommandArgument { - public static CommandSyntaxException error(final String text) + public static CommandSyntaxException error(String text) { return new SimpleCommandExceptionType(Component.literal(text)).create(); } @@ -133,7 +135,7 @@ public static CommandSyntaxException error(final String text) new VanillaUnconfigurableArgument("block", BlockStateArgument::block, (c, p) -> { BlockInput result = BlockStateArgument.getBlock(c, p); - return new BlockValue(result.getState(), c.getSource().getLevel(), null, Vanilla.BlockInput_getTag(result)); + return new BlockValue(result.getState(), c.getSource().getLevel(), Vanilla.BlockInput_getTag(result)); }, param -> (ctx, builder) -> ctx.getArgument(param, BlockStateArgument.class).listSuggestions(ctx, builder) ), @@ -219,7 +221,7 @@ public static CommandSyntaxException error(final String text) (c, p) -> ValueConversions.of(ResourceLocationArgument.getId(c, p)), BossBarCommands.SUGGEST_BOSS_BAR ), - new VanillaUnconfigurableArgument("biome", (c) -> ResourceOrTagArgument.resourceOrTag(c, Registries.BIOME), + new VanillaUnconfigurableArgument("biome", c -> ResourceOrTagArgument.resourceOrTag(c, Registries.BIOME), (c, p) -> { ResourceOrTagArgument.Result result = ResourceOrTagArgument.getResourceOrTag(c, "biome", Registries.BIOME); Either, HolderSet.Named> res = result.unwrap(); @@ -270,7 +272,7 @@ public static CommandSyntaxException error(final String text) new VanillaUnconfigurableArgument("uuid", UuidArgument::uuid, (c, p) -> StringValue.of(UuidArgument.getUuid(c, p).toString()), false ), - new VanillaUnconfigurableArgument("surfacelocation", () -> Vec2Argument.vec2(), // vec2 + new VanillaUnconfigurableArgument("surfacelocation", Vec2Argument::vec2, (c, p) -> { Vec2 res = Vec2Argument.getVec2(c, p); return ListValue.of(NumericValue.of(res.x), NumericValue.of(res.y)); @@ -284,13 +286,13 @@ public static CommandSyntaxException error(final String text) public static final CommandArgument DEFAULT = baseTypes.get(0); - public static CommandArgument getTypeForArgument(final String argument, final CarpetScriptHost host) + public static CommandArgument getTypeForArgument(String argument, CarpetScriptHost host) { - final String[] components = argument.split("_"); + String[] components = argument.split("_"); CommandArgument arg; for (int i = 0; i < components.length; i++) { - final String candidate = String.join("_", Arrays.asList(components).subList(i, components.length)); + String candidate = String.join("_", Arrays.asList(components).subList(i, components.length)); arg = host.appArgTypes.get(candidate); if (arg != null) { @@ -305,9 +307,9 @@ public static CommandArgument getTypeForArgument(final String argument, final Ca return DEFAULT; } - public static RequiredArgumentBuilder argumentNode(final String param, final CarpetScriptHost host) throws CommandSyntaxException + public static RequiredArgumentBuilder argumentNode(String param, CarpetScriptHost host) throws CommandSyntaxException { - final CommandArgument arg = getTypeForArgument(param, host); + CommandArgument arg = getTypeForArgument(param, host); if (arg.suggestionProvider != null) { return argument(param, arg.getArgumentType(host)).suggests(arg.suggestionProvider.apply(param)); @@ -316,15 +318,16 @@ public static CommandArgument getTypeForArgument(final String argument, final Ca { return argument(param, arg.getArgumentType(host)); } - final String hostName = host.getName(); - final CarpetScriptServer scriptServer = host.scriptServer(); + String hostName = host.getName(); + CarpetScriptServer scriptServer = host.scriptServer(); return argument(param, arg.getArgumentType(host)).suggests((ctx, b) -> { - final CarpetScriptHost cHost = scriptServer.modules.get(hostName).retrieveOwnForExecution(ctx.getSource()); + CarpetScriptHost cHost = scriptServer.modules.get(hostName).retrieveOwnForExecution(ctx.getSource()); return arg.suggest(ctx, b, cHost); }); } protected String suffix; + @Nullable protected Collection examples; protected boolean needsMatching; protected boolean caseSensitive = true; @@ -333,9 +336,9 @@ public static CommandArgument getTypeForArgument(final String argument, final Ca protected CommandArgument( - final String suffix, - final Collection examples, - final boolean suggestFromExamples) + String suffix, + @Nullable Collection examples, + boolean suggestFromExamples) { this.suffix = suffix; this.examples = examples; @@ -345,7 +348,7 @@ protected CommandArgument( protected abstract ArgumentType getArgumentType(CarpetScriptHost host) throws CommandSyntaxException; - public static Value getValue(final CommandContext context, final String param, final CarpetScriptHost host) throws CommandSyntaxException + public static Value getValue(CommandContext context, String param, CarpetScriptHost host) throws CommandSyntaxException { return getTypeForArgument(param, host).getValueFromContext(context, param); } @@ -357,24 +360,24 @@ public String getTypeSuffix() return suffix; } - public static CommandArgument buildFromConfig(final String suffix, final Map config, final CarpetScriptHost host) throws CommandSyntaxException + public static CommandArgument buildFromConfig(String suffix, Map config, CarpetScriptHost host) throws CommandSyntaxException { if (!config.containsKey("type")) { throw CommandArgument.error("Custom type " + suffix + " should at least specify the type"); } - final String baseType = config.get("type").getString(); + String baseType = config.get("type").getString(); if (!builtIns.containsKey(baseType)) { throw CommandArgument.error("Unknown base type " + baseType + " for custom type " + suffix); } - final CommandArgument variant = builtIns.get(baseType).factory(host.scriptServer().server).get(); + CommandArgument variant = builtIns.get(baseType).factory(host.scriptServer().server).get(); variant.suffix = suffix; variant.configure(config, host); return variant; } - protected void configure(final Map config, final CarpetScriptHost host) throws CommandSyntaxException + protected void configure(Map config, CarpetScriptHost host) throws CommandSyntaxException { caseSensitive = config.getOrDefault("case_sensitive", Value.TRUE).getBoolean(); if (config.containsKey("suggester")) @@ -387,7 +390,7 @@ protected void configure(final Map config, final CarpetScriptHost { throw error("Attempted to provide 'suggest' list while 'suggester' is present" + " for custom type " + suffix); } - final Value suggestionValue = config.get("suggest"); + Value suggestionValue = config.get("suggest"); if (!(suggestionValue instanceof ListValue)) { throw error("Argument suggestions needs to be a list" + " for custom type " + suffix); @@ -403,9 +406,9 @@ protected void configure(final Map config, final CarpetScriptHost } public CompletableFuture suggest( - final CommandContext context, - final SuggestionsBuilder suggestionsBuilder, - final CarpetScriptHost host + CommandContext context, + SuggestionsBuilder suggestionsBuilder, + CarpetScriptHost host ) throws CommandSyntaxException { String prefix = suggestionsBuilder.getRemaining(); @@ -417,41 +420,41 @@ public CompletableFuture suggest( return suggestionsBuilder.buildFuture(); } - protected List suggestFor(final CommandContext context, final String prefix, final CarpetScriptHost host) throws CommandSyntaxException + protected List suggestFor(CommandContext context, String prefix, CarpetScriptHost host) throws CommandSyntaxException { return getOptions(context, host).stream().filter(s -> optionMatchesPrefix(prefix, s)).collect(Collectors.toList()); } - protected Collection getOptions(final CommandContext context, final CarpetScriptHost host) throws CommandSyntaxException + protected Collection getOptions(CommandContext context, CarpetScriptHost host) throws CommandSyntaxException { if (customSuggester != null) { - final Runnable currentSection = Carpet.startProfilerSection("Scarpet command"); - final Map params = new HashMap<>(); - for (final ParsedCommandNode pnode : context.getNodes()) + Runnable currentSection = Carpet.startProfilerSection("Scarpet command"); + Map params = new HashMap<>(); + for (ParsedCommandNode pnode : context.getNodes()) { - final CommandNode node = pnode.getNode(); + CommandNode node = pnode.getNode(); if (node instanceof ArgumentCommandNode) { params.put(StringValue.of(node.getName()), CommandArgument.getValue(context, node.getName(), host)); } } - final List args = new ArrayList<>(customSuggester.args.size() + 1); + List args = new ArrayList<>(customSuggester.args.size() + 1); args.add(MapValue.wrap(params)); args.addAll(customSuggester.args); - final Value response = host.handleCommand(context.getSource(), customSuggester.function, args); + Value response = host.handleCommand(context.getSource(), customSuggester.function, args); if (!(response instanceof ListValue)) { throw error("Custom suggester should return a list of options" + " for custom type " + suffix); } - final Collection res = ((ListValue) response).getItems().stream().map(Value::getString).collect(Collectors.toList()); + Collection res = ((ListValue) response).getItems().stream().map(Value::getString).collect(Collectors.toList()); currentSection.run(); return res; } return needsMatching ? examples : Collections.singletonList("... " + getTypeSuffix()); } - protected boolean optionMatchesPrefix(final String prefix, String option) + protected boolean optionMatchesPrefix(String prefix, String option) { if (!caseSensitive) { @@ -480,13 +483,13 @@ private StringArgument() } @Override - public ArgumentType getArgumentType(final CarpetScriptHost host) + public ArgumentType getArgumentType(CarpetScriptHost host) { return StringArgumentType.string(); } @Override - public Value getValueFromContext(final CommandContext context, final String param) throws CommandSyntaxException + public Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException { String choseValue = StringArgumentType.getString(context, param); if (!caseSensitive) @@ -501,12 +504,12 @@ public Value getValueFromContext(final CommandContext contex } @Override - protected void configure(final Map config, final CarpetScriptHost host) throws CommandSyntaxException + protected void configure(Map config, CarpetScriptHost host) throws CommandSyntaxException { super.configure(config, host); if (config.containsKey("options")) { - final Value optionsValue = config.get("options"); + Value optionsValue = config.get("options"); if (!(optionsValue instanceof ListValue)) { throw error("Custom string type requires options passed as a list" + " for custom type " + suffix); @@ -518,13 +521,13 @@ protected void configure(final Map config, final CarpetScriptHost } @Override - protected Collection getOptions(final CommandContext context, final CarpetScriptHost host) throws CommandSyntaxException + protected Collection getOptions(CommandContext context, CarpetScriptHost host) throws CommandSyntaxException { return validOptions.isEmpty() ? super.getOptions(context, host) : validOptions; } @Override - protected Supplier factory(final MinecraftServer server) + protected Supplier factory(MinecraftServer server) { return StringArgument::new; } @@ -540,13 +543,13 @@ private WordArgument() } @Override - public ArgumentType getArgumentType(final CarpetScriptHost host) + public ArgumentType getArgumentType(CarpetScriptHost host) { return StringArgumentType.word(); } @Override - protected Supplier factory(final MinecraftServer server) + protected Supplier factory(MinecraftServer server) { return WordArgument::new; } @@ -562,13 +565,13 @@ private GreedyStringArgument() } @Override - public ArgumentType getArgumentType(final CarpetScriptHost host) + public ArgumentType getArgumentType(CarpetScriptHost host) { return StringArgumentType.greedyString(); } @Override - protected Supplier factory(final MinecraftServer server) + protected Supplier factory(MinecraftServer server) { return GreedyStringArgument::new; } @@ -584,29 +587,29 @@ private BlockPosArgument() } @Override - public ArgumentType getArgumentType(final CarpetScriptHost host) + public ArgumentType getArgumentType(CarpetScriptHost host) { return net.minecraft.commands.arguments.coordinates.BlockPosArgument.blockPos(); } @Override - public Value getValueFromContext(final CommandContext context, final String param) throws CommandSyntaxException + public Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException { - final BlockPos pos = mustBeLoaded + BlockPos pos = mustBeLoaded ? net.minecraft.commands.arguments.coordinates.BlockPosArgument.getLoadedBlockPos(context, param) : net.minecraft.commands.arguments.coordinates.BlockPosArgument.getSpawnablePos(context, param); return ValueConversions.of(pos); } @Override - protected void configure(final Map config, final CarpetScriptHost host) throws CommandSyntaxException + protected void configure(Map config, CarpetScriptHost host) throws CommandSyntaxException { super.configure(config, host); mustBeLoaded = config.getOrDefault("loaded", Value.FALSE).getBoolean(); } @Override - protected Supplier factory(final MinecraftServer server) + protected Supplier factory(MinecraftServer server) { return BlockPosArgument::new; } @@ -623,26 +626,26 @@ private LocationArgument() } @Override - protected ArgumentType getArgumentType(final CarpetScriptHost host) + protected ArgumentType getArgumentType(CarpetScriptHost host) { return Vec3Argument.vec3(blockCentered); } @Override - protected Value getValueFromContext(final CommandContext context, final String param) throws CommandSyntaxException + protected Value getValueFromContext(CommandContext context, String param) { return ValueConversions.of(Vec3Argument.getVec3(context, param)); } @Override - protected void configure(final Map config, final CarpetScriptHost host) throws CommandSyntaxException + protected void configure(Map config, CarpetScriptHost host) throws CommandSyntaxException { super.configure(config, host); blockCentered = config.getOrDefault("block_centered", Value.TRUE).getBoolean(); } @Override - protected Supplier factory(final MinecraftServer server) + protected Supplier factory(MinecraftServer server) { return LocationArgument::new; } @@ -661,7 +664,7 @@ private EntityArgument() } @Override - protected ArgumentType getArgumentType(final CarpetScriptHost host) + protected ArgumentType getArgumentType(CarpetScriptHost host) { if (onlyFans) { @@ -671,14 +674,14 @@ protected ArgumentType getArgumentType(final CarpetScriptHost host) } @Override - protected Value getValueFromContext(final CommandContext context, final String param) throws CommandSyntaxException + protected Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException { - final Collection founds = net.minecraft.commands.arguments.EntityArgument.getOptionalEntities(context, param); + Collection founds = net.minecraft.commands.arguments.EntityArgument.getOptionalEntities(context, param); if (!single) { return ListValue.wrap(founds.stream().map(EntityValue::new)); } - if (founds.size() == 0) + if (founds.isEmpty()) { return Value.NULL; } @@ -690,7 +693,7 @@ protected Value getValueFromContext(final CommandContext con } @Override - protected void configure(final Map config, final CarpetScriptHost host) throws CommandSyntaxException + protected void configure(Map config, CarpetScriptHost host) throws CommandSyntaxException { super.configure(config, host); onlyFans = config.getOrDefault("players", Value.FALSE).getBoolean(); @@ -698,7 +701,7 @@ protected void configure(final Map config, final CarpetScriptHost } @Override - protected Supplier factory(final MinecraftServer server) + protected Supplier factory(MinecraftServer server) { return EntityArgument::new; } @@ -715,20 +718,20 @@ private PlayerProfileArgument() } @Override - protected ArgumentType getArgumentType(final CarpetScriptHost host) + protected ArgumentType getArgumentType(CarpetScriptHost host) { return GameProfileArgument.gameProfile(); } @Override - protected Value getValueFromContext(final CommandContext context, final String param) throws CommandSyntaxException + protected Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException { - final Collection profiles = GameProfileArgument.getGameProfiles(context, param); + Collection profiles = GameProfileArgument.getGameProfiles(context, param); if (!single) { return ListValue.wrap(profiles.stream().map(p -> StringValue.of(p.getName()))); } - final int size = profiles.size(); + int size = profiles.size(); if (size == 0) { return Value.NULL; @@ -741,14 +744,14 @@ protected Value getValueFromContext(final CommandContext con } @Override - protected void configure(final Map config, final CarpetScriptHost host) throws CommandSyntaxException + protected void configure(Map config, CarpetScriptHost host) throws CommandSyntaxException { super.configure(config, host); single = config.getOrDefault("single", Value.FALSE).getBoolean(); } @Override - protected Supplier factory(final MinecraftServer server) + protected Supplier factory(MinecraftServer server) { return PlayerProfileArgument::new; } @@ -766,20 +769,20 @@ private ScoreholderArgument() } @Override - protected ArgumentType getArgumentType(final CarpetScriptHost host) + protected ArgumentType getArgumentType(CarpetScriptHost host) { return single ? ScoreHolderArgument.scoreHolder() : ScoreHolderArgument.scoreHolders(); } @Override - protected Value getValueFromContext(final CommandContext context, final String param) throws CommandSyntaxException + protected Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException { - final Collection holders = ScoreHolderArgument.getNames(context, param); + Collection holders = ScoreHolderArgument.getNames(context, param); if (!single) { return ListValue.wrap(holders.stream().map(StringValue::of)); } - final int size = holders.size(); + int size = holders.size(); if (size == 0) { return Value.NULL; @@ -792,14 +795,14 @@ protected Value getValueFromContext(final CommandContext con } @Override - protected void configure(final Map config, final CarpetScriptHost host) throws CommandSyntaxException + protected void configure(Map config, CarpetScriptHost host) throws CommandSyntaxException { super.configure(config, host); single = config.getOrDefault("single", Value.FALSE).getBoolean(); } @Override - protected Supplier factory(final MinecraftServer server) + protected Supplier factory(MinecraftServer server) { return PlayerProfileArgument::new; } @@ -816,13 +819,13 @@ private TagArgument() } @Override - protected ArgumentType getArgumentType(final CarpetScriptHost host) + protected ArgumentType getArgumentType(CarpetScriptHost host) { return mapRequired ? CompoundTagArgument.compoundTag() : NbtTagArgument.nbtTag(); } @Override - protected Value getValueFromContext(final CommandContext context, final String param) throws CommandSyntaxException + protected Value getValueFromContext(CommandContext context, String param) { return mapRequired ? new NBTSerializableValue(CompoundTagArgument.getCompoundTag(context, param)) @@ -830,14 +833,14 @@ protected Value getValueFromContext(final CommandContext con } @Override - protected void configure(final Map config, final CarpetScriptHost host) throws CommandSyntaxException + protected void configure(Map config, CarpetScriptHost host) throws CommandSyntaxException { super.configure(config, host); mapRequired = !config.getOrDefault("allow_element", Value.FALSE).getBoolean(); } @Override - protected Supplier factory(final MinecraftServer server) + protected Supplier factory(MinecraftServer server) { return TagArgument::new; } @@ -853,15 +856,15 @@ protected CustomIdentifierArgument() } @Override - protected ArgumentType getArgumentType(final CarpetScriptHost host) + protected ArgumentType getArgumentType(CarpetScriptHost host) { return ResourceLocationArgument.id(); } @Override - protected Value getValueFromContext(final CommandContext context, final String param) throws CommandSyntaxException + protected Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException { - final ResourceLocation choseValue = ResourceLocationArgument.getId(context, param); + ResourceLocation choseValue = ResourceLocationArgument.getId(context, param); if (!validOptions.isEmpty() && !validOptions.contains(choseValue)) { throw new SimpleCommandExceptionType(Component.literal("Incorrect value for " + param + ": " + choseValue + " for custom type " + suffix)).create(); @@ -870,18 +873,18 @@ protected Value getValueFromContext(final CommandContext con } @Override - protected Supplier factory(final MinecraftServer server) + protected Supplier factory(MinecraftServer server) { return CustomIdentifierArgument::new; } @Override - protected void configure(final Map config, final CarpetScriptHost host) throws CommandSyntaxException + protected void configure(Map config, CarpetScriptHost host) throws CommandSyntaxException { super.configure(config, host); if (config.containsKey("options")) { - final Value optionsValue = config.get("options"); + Value optionsValue = config.get("options"); if (!(optionsValue instanceof ListValue)) { throw error("Custom sting type requires options passed as a list" + " for custom type " + suffix); @@ -902,7 +905,7 @@ private FloatArgument() } @Override - public ArgumentType getArgumentType(final CarpetScriptHost host) + public ArgumentType getArgumentType(CarpetScriptHost host) { if (min != null) { @@ -916,13 +919,13 @@ public ArgumentType getArgumentType(final CarpetScriptHost host) } @Override - public Value getValueFromContext(final CommandContext context, final String param) throws CommandSyntaxException + public Value getValueFromContext(CommandContext context, String param) { return new NumericValue(DoubleArgumentType.getDouble(context, param)); } @Override - protected void configure(final Map config, final CarpetScriptHost host) throws CommandSyntaxException + protected void configure(Map config, CarpetScriptHost host) throws CommandSyntaxException { super.configure(config, host); if (config.containsKey("min")) @@ -940,7 +943,7 @@ protected void configure(final Map config, final CarpetScriptHost } @Override - protected Supplier factory(final MinecraftServer server) + protected Supplier factory(MinecraftServer server) { return FloatArgument::new; } @@ -957,7 +960,7 @@ private IntArgument() } @Override - public ArgumentType getArgumentType(final CarpetScriptHost host) + public ArgumentType getArgumentType(CarpetScriptHost host) { if (min != null) { @@ -971,13 +974,13 @@ public ArgumentType getArgumentType(final CarpetScriptHost host) } @Override - public Value getValueFromContext(final CommandContext context, final String param) throws CommandSyntaxException + public Value getValueFromContext(CommandContext context, String param) { return new NumericValue(LongArgumentType.getLong(context, param)); } @Override - protected void configure(final Map config, final CarpetScriptHost host) throws CommandSyntaxException + protected void configure(Map config, CarpetScriptHost host) throws CommandSyntaxException { super.configure(config, host); if (config.containsKey("min")) @@ -995,7 +998,7 @@ protected void configure(final Map config, final CarpetScriptHost } @Override - protected Supplier factory(final MinecraftServer server) + protected Supplier factory(MinecraftServer server) { return IntArgument::new; } @@ -1011,7 +1014,7 @@ private record ContainerIds(IntSet numericalIds, Set commandIds) private static final Map RESTRICTED_CONTAINERS = new HashMap<>() {{ int i; - for (final String source : Arrays.asList("player", "enderchest", "equipment", "armor", "weapon", "container", "villager", "horse")) + for (String source : Arrays.asList("player", "enderchest", "equipment", "armor", "weapon", "container", "villager", "horse")) { put(source, new ContainerIds(new IntOpenHashSet(), new HashSet<>())); } @@ -1031,13 +1034,13 @@ private record ContainerIds(IntSet numericalIds, Set commandIds) { get("player").commandIds().add("inventory." + i); } - for (final String place : Arrays.asList("weapon", "weapon.mainhand", "weapon.offhand")) + for (String place : Arrays.asList("weapon", "weapon.mainhand", "weapon.offhand")) { get("player").commandIds().add(place); get("equipment").commandIds().add(place); get("weapon").commandIds().add(place); } - for (final String place : Arrays.asList("armor.feet", "armor.legs", "armor.chest", "armor.head")) + for (String place : Arrays.asList("armor.feet", "armor.legs", "armor.chest", "armor.head")) { get("player").commandIds().add(place); get("equipment").commandIds().add(place); @@ -1106,15 +1109,15 @@ protected SlotArgument() } @Override - protected ArgumentType getArgumentType(final CarpetScriptHost host) throws CommandSyntaxException + protected ArgumentType getArgumentType(CarpetScriptHost host) { return net.minecraft.commands.arguments.SlotArgument.slot(); } @Override - protected Value getValueFromContext(final CommandContext context, final String param) throws CommandSyntaxException + protected Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException { - final int slot = net.minecraft.commands.arguments.SlotArgument.getSlot(context, param); + int slot = net.minecraft.commands.arguments.SlotArgument.getSlot(context, param); if (restrict != null && !RESTRICTED_CONTAINERS.get(restrict).numericalIds().contains(slot)) { throw new SimpleCommandExceptionType(Component.literal("Incorrect slot restricted to " + restrict + " for custom type " + suffix)).create(); @@ -1123,7 +1126,7 @@ protected Value getValueFromContext(final CommandContext con } @Override - protected void configure(final Map config, final CarpetScriptHost host) throws CommandSyntaxException + protected void configure(Map config, CarpetScriptHost host) throws CommandSyntaxException { super.configure(config, host); if (config.containsKey("restrict")) @@ -1138,13 +1141,13 @@ protected void configure(final Map config, final CarpetScriptHost } @Override - protected Collection getOptions(final CommandContext context, final CarpetScriptHost host) throws CommandSyntaxException + protected Collection getOptions(CommandContext context, CarpetScriptHost host) throws CommandSyntaxException { return restrict == null ? super.getOptions(context, host) : RESTRICTED_CONTAINERS.get(restrict).commandIds(); } @Override - protected Supplier factory(final MinecraftServer server) + protected Supplier factory(MinecraftServer server) { return SlotArgument::new; } @@ -1176,10 +1179,10 @@ public static class VanillaUnconfigurableArgument extends CommandArgument private final boolean providesExamples; public VanillaUnconfigurableArgument( - final String suffix, - final ArgumentProvider argumentTypeSupplier, - final ValueExtractor valueExtractor, - final boolean suggestFromExamples + String suffix, + ArgumentProvider argumentTypeSupplier, + ValueExtractor valueExtractor, + boolean suggestFromExamples ) { super(suffix, null, suggestFromExamples); @@ -1187,7 +1190,7 @@ public VanillaUnconfigurableArgument( { this.examples = argumentTypeSupplier.get().getExamples(); } - catch (final CommandSyntaxException e) + catch (CommandSyntaxException e) { this.examples = Collections.emptyList(); } @@ -1198,10 +1201,10 @@ public VanillaUnconfigurableArgument( } public VanillaUnconfigurableArgument( - final String suffix, - final ArgumentProvider argumentTypeSupplier, - final ValueExtractor valueExtractor, - final SuggestionProvider suggester + String suffix, + ArgumentProvider argumentTypeSupplier, + ValueExtractor valueExtractor, + SuggestionProvider suggester ) { super(suffix, Collections.emptyList(), false); @@ -1213,19 +1216,19 @@ public VanillaUnconfigurableArgument( } public VanillaUnconfigurableArgument( - final String suffix, - final ArgumentProviderEx argumentTypeSupplier, - final ValueExtractor valueExtractor, - final boolean suggestFromExamples, - final MinecraftServer server) + String suffix, + ArgumentProviderEx argumentTypeSupplier, + ValueExtractor valueExtractor, + boolean suggestFromExamples, + MinecraftServer server) { super(suffix, null, suggestFromExamples); try { - final CommandBuildContext context = CommandBuildContext.simple(server.registryAccess(), server.getWorldData().enabledFeatures()); + CommandBuildContext context = CommandBuildContext.simple(server.registryAccess(), server.getWorldData().enabledFeatures()); this.examples = argumentTypeSupplier.get(context).getExamples(); } - catch (final CommandSyntaxException e) + catch (CommandSyntaxException e) { this.examples = Collections.emptyList(); } @@ -1236,10 +1239,10 @@ public VanillaUnconfigurableArgument( } public VanillaUnconfigurableArgument( - final String suffix, - final ArgumentProviderEx argumentTypeSupplier, - final ValueExtractor valueExtractor, - final SuggestionProvider suggester + String suffix, + ArgumentProviderEx argumentTypeSupplier, + ValueExtractor valueExtractor, + SuggestionProvider suggester ) { super(suffix, Collections.emptyList(), false); @@ -1251,10 +1254,10 @@ public VanillaUnconfigurableArgument( } public VanillaUnconfigurableArgument( - final String suffix, - final ArgumentProviderEx argumentTypeSupplier, - final ValueExtractor valueExtractor, - final Function> suggesterGen + String suffix, + ArgumentProviderEx argumentTypeSupplier, + ValueExtractor valueExtractor, + Function> suggesterGen ) { super(suffix, Collections.emptyList(), false); @@ -1266,20 +1269,20 @@ public VanillaUnconfigurableArgument( } public VanillaUnconfigurableArgument( - final String suffix, - final ResourceKey> registry + String suffix, + ResourceKey> registry ) { this( suffix, - (c) -> ResourceArgument.resource(c, registry), + c -> ResourceArgument.resource(c, registry), (c, p) -> ValueConversions.of(ResourceArgument.getResource(c, p, registry).key()), (c, b) -> SharedSuggestionProvider.suggestResource(c.getSource().getServer().registryAccess().registryOrThrow(registry).keySet(), b) ); } @Override - protected ArgumentType getArgumentType(final CarpetScriptHost host) throws CommandSyntaxException + protected ArgumentType getArgumentType(CarpetScriptHost host) throws CommandSyntaxException { return argumentTypeSupplier != null ? argumentTypeSupplier.get() @@ -1287,13 +1290,13 @@ protected ArgumentType getArgumentType(final CarpetScriptHost host) throws Co } @Override - protected Value getValueFromContext(final CommandContext context, final String param) throws CommandSyntaxException + protected Value getValueFromContext(CommandContext context, String param) throws CommandSyntaxException { return valueExtractor.apply(context, param); } @Override - protected Supplier factory(final MinecraftServer server) + protected Supplier factory(MinecraftServer server) { return argumentTypeSupplier != null ? (() -> new VanillaUnconfigurableArgument(getTypeSuffix(), argumentTypeSupplier, valueExtractor, providesExamples)) diff --git a/src/main/java/carpet/script/command/CommandToken.java b/src/main/java/carpet/script/command/CommandToken.java index 7f028ee99e..22c06f4f84 100644 --- a/src/main/java/carpet/script/command/CommandToken.java +++ b/src/main/java/carpet/script/command/CommandToken.java @@ -14,22 +14,26 @@ import net.minecraft.commands.CommandSourceStack; +import javax.annotation.Nullable; + import static net.minecraft.commands.Commands.literal; public class CommandToken implements Comparable { - public String surface; - public boolean isArgument; - public CommandArgument type; + public final String surface; + public final boolean isArgument; + @Nullable + public final CommandArgument type; - private CommandToken(final String surface, final CommandArgument type) + private CommandToken(String surface, @Nullable CommandArgument type) { this.surface = surface; this.type = type; isArgument = type != null; } - public static CommandToken getToken(String source, final CarpetScriptHost host) + @Nullable + public static CommandToken getToken(String source, CarpetScriptHost host) { // todo add more type checking and return null if (!source.startsWith("<")) @@ -40,18 +44,18 @@ public static CommandToken getToken(String source, final CarpetScriptHost host) return source.matches("[_a-zA-Z]+") ? new CommandToken(source, CommandArgument.getTypeForArgument(source, host)) : null; } - public static List parseSpec(String spec, final CarpetScriptHost host) throws CommandSyntaxException + public static List parseSpec(String spec, CarpetScriptHost host) throws CommandSyntaxException { spec = spec.trim(); if (spec.isEmpty()) { return Collections.emptyList(); } - final List elements = new ArrayList<>(); - final HashSet seenArgs = new HashSet<>(); - for (final String el : spec.split("\\s+")) + List elements = new ArrayList<>(); + HashSet seenArgs = new HashSet<>(); + for (String el : spec.split("\\s+")) { - final CommandToken tok = CommandToken.getToken(el, host); + CommandToken tok = CommandToken.getToken(el, host); if (tok == null) { throw CommandArgument.error("Unrecognized command token: " + el); @@ -69,23 +73,23 @@ public static List parseSpec(String spec, final CarpetScriptHost h return elements; } - public static String specFromSignature(final FunctionValue function) + public static String specFromSignature(FunctionValue function) { - final List tokens = Lists.newArrayList(function.getString()); - for (final String arg : function.getArguments()) + List tokens = Lists.newArrayList(function.getString()); + for (String arg : function.getArguments()) { tokens.add("<" + arg + ">"); } return String.join(" ", tokens); } - public ArgumentBuilder getCommandNode(final CarpetScriptHost host) throws CommandSyntaxException + public ArgumentBuilder getCommandNode(CarpetScriptHost host) throws CommandSyntaxException { return isArgument ? CommandArgument.argumentNode(surface, host) : literal(surface); } @Override - public boolean equals(final Object o) + public boolean equals(Object o) { if (this == o) { @@ -95,7 +99,7 @@ public boolean equals(final Object o) { return false; } - final CommandToken that = (CommandToken) o; + CommandToken that = (CommandToken) o; return surface.equals(that.surface) && Objects.equals(type, that.type); } @@ -107,7 +111,7 @@ public int hashCode() } @Override - public int compareTo(final CommandToken o) + public int compareTo(CommandToken o) { if (isArgument && !o.isArgument) { diff --git a/src/main/java/carpet/script/exception/BreakStatement.java b/src/main/java/carpet/script/exception/BreakStatement.java index 76c69a7a8c..40b76a194c 100644 --- a/src/main/java/carpet/script/exception/BreakStatement.java +++ b/src/main/java/carpet/script/exception/BreakStatement.java @@ -2,9 +2,11 @@ import carpet.script.value.Value; +import javax.annotation.Nullable; + public class BreakStatement extends ExitStatement { - public BreakStatement(final Value value) + public BreakStatement(@Nullable Value value) { super(value); } diff --git a/src/main/java/carpet/script/exception/CarpetExpressionException.java b/src/main/java/carpet/script/exception/CarpetExpressionException.java index 8e54175471..a583c88c5f 100644 --- a/src/main/java/carpet/script/exception/CarpetExpressionException.java +++ b/src/main/java/carpet/script/exception/CarpetExpressionException.java @@ -11,17 +11,17 @@ public class CarpetExpressionException extends StacklessRuntimeException impleme { public final List stack; - public CarpetExpressionException(final String message, final List stack) + public CarpetExpressionException(String message, List stack) { super(message); this.stack = stack; } - public void printStack(final CommandSourceStack source) + public void printStack(CommandSourceStack source) { if (stack != null && !stack.isEmpty()) { - for (final FunctionValue fun : stack) + for (FunctionValue fun : stack) { Carpet.Messenger_message(source, "e ... in " + fun.fullName(), "e /" + (fun.getToken().lineno + 1) + ":" + (fun.getToken().linepos + 1)); } diff --git a/src/main/java/carpet/script/exception/ContinueStatement.java b/src/main/java/carpet/script/exception/ContinueStatement.java index a471d4f4e2..449b15efb7 100644 --- a/src/main/java/carpet/script/exception/ContinueStatement.java +++ b/src/main/java/carpet/script/exception/ContinueStatement.java @@ -2,9 +2,11 @@ import carpet.script.value.Value; +import javax.annotation.Nullable; + public class ContinueStatement extends ExitStatement { - public ContinueStatement(final Value value) + public ContinueStatement(@Nullable Value value) { super(value); } diff --git a/src/main/java/carpet/script/exception/ExitStatement.java b/src/main/java/carpet/script/exception/ExitStatement.java index 744ec9f630..b1982332a2 100644 --- a/src/main/java/carpet/script/exception/ExitStatement.java +++ b/src/main/java/carpet/script/exception/ExitStatement.java @@ -2,12 +2,15 @@ import carpet.script.value.Value; +import javax.annotation.Nullable; + /* Exception thrown to terminate execution mid expression (aka return statement) */ public class ExitStatement extends StacklessRuntimeException { + @Nullable public final Value retval; - public ExitStatement(final Value value) + public ExitStatement(@Nullable Value value) { retval = value; } diff --git a/src/main/java/carpet/script/exception/ExpressionException.java b/src/main/java/carpet/script/exception/ExpressionException.java index 6a2cb1f4a2..d0ab16503d 100644 --- a/src/main/java/carpet/script/exception/ExpressionException.java +++ b/src/main/java/carpet/script/exception/ExpressionException.java @@ -6,6 +6,7 @@ import carpet.script.external.Carpet; import carpet.script.value.FunctionValue; +import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -25,17 +26,17 @@ public static void prepareForDoom() Carpet.Messenger_compose("foo bar"); } - public ExpressionException(final Context c, final Expression e, final String message) + public ExpressionException(Context c, Expression e, String message) { this(c, e, Tokenizer.Token.NONE, message); } - public ExpressionException(final Context c, final Expression e, final Tokenizer.Token t, final String message) + public ExpressionException(Context c, Expression e, Tokenizer.Token t, String message) { this(c, e, t, message, Collections.emptyList()); } - public ExpressionException(final Context c, final Expression e, final Tokenizer.Token t, final String message, final List stack) + public ExpressionException(Context c, Expression e, Tokenizer.Token t, String message, List stack) { super("Error"); this.stack.addAll(stack); @@ -44,7 +45,7 @@ public ExpressionException(final Context c, final Expression e, final Tokenizer. context = c; } - public ExpressionException(final Context c, final Expression e, final Tokenizer.Token t, final Supplier messageSupplier, final List stack) + public ExpressionException(Context c, Expression e, Tokenizer.Token t, Supplier messageSupplier, List stack) { super("Error"); this.stack.addAll(stack); @@ -53,13 +54,13 @@ public ExpressionException(final Context c, final Expression e, final Tokenizer. context = c; } - private static List makeError(final Expression expr, /*Nullable*/final Tokenizer.Token token, String errmessage) + private static List makeError(Expression expr, @Nullable Tokenizer.Token token, String errmessage) { - final List errMsg = new ArrayList<>(); + List errMsg = new ArrayList<>(); errmessage += expr.getModuleName() == null ? "" : (" in " + expr.getModuleName()); if (token != null) { - final List snippet = expr.getExpressionSnippet(token); + List snippet = expr.getExpressionSnippet(token); errMsg.addAll(snippet); if (snippet.size() != 1) @@ -75,11 +76,11 @@ private static List makeError(final Expression expr, /*Nullable*/final T return errMsg; } - static synchronized String makeMessage(final Context c, final Expression e, final Tokenizer.Token t, final String message) throws ExpressionException + static synchronized String makeMessage(Context c, Expression e, Tokenizer.Token t, String message) throws ExpressionException { if (c.getErrorSnooper() != null) { - final List alternative = c.getErrorSnooper().apply(e, t, c, message); + List alternative = c.getErrorSnooper().apply(e, t, c, message); if (alternative != null) { return String.join("\n", alternative); diff --git a/src/main/java/carpet/script/exception/IntegrityException.java b/src/main/java/carpet/script/exception/IntegrityException.java index 7aee600b9c..262c57f9e7 100644 --- a/src/main/java/carpet/script/exception/IntegrityException.java +++ b/src/main/java/carpet/script/exception/IntegrityException.java @@ -2,7 +2,7 @@ public class IntegrityException extends RuntimeException { - public IntegrityException(final String message) + public IntegrityException(String message) { super(message); } diff --git a/src/main/java/carpet/script/exception/InternalExpressionException.java b/src/main/java/carpet/script/exception/InternalExpressionException.java index dec1b9c5c8..ef850ed142 100644 --- a/src/main/java/carpet/script/exception/InternalExpressionException.java +++ b/src/main/java/carpet/script/exception/InternalExpressionException.java @@ -13,7 +13,7 @@ public class InternalExpressionException extends StacklessRuntimeException { public List stack = new ArrayList<>(); - public InternalExpressionException(final String message) + public InternalExpressionException(String message) { super(message); } @@ -30,7 +30,7 @@ public InternalExpressionException(final String message) * @return The new {@link ExpressionException} (or {@link ProcessedThrowStatement}), * depending on the implementation. */ - public ExpressionException promote(final Context c, final Expression e, final Tokenizer.Token token) + public ExpressionException promote(Context c, Expression e, Tokenizer.Token token) { return new ExpressionException(c, e, token, getMessage(), stack); } diff --git a/src/main/java/carpet/script/exception/LoadException.java b/src/main/java/carpet/script/exception/LoadException.java index bdbd41491e..54245a8390 100644 --- a/src/main/java/carpet/script/exception/LoadException.java +++ b/src/main/java/carpet/script/exception/LoadException.java @@ -12,7 +12,7 @@ public LoadException() { super(); } - public LoadException(final String message) + public LoadException(String message) { super(message); } diff --git a/src/main/java/carpet/script/exception/ProcessedThrowStatement.java b/src/main/java/carpet/script/exception/ProcessedThrowStatement.java index 45c990be52..3768550b72 100644 --- a/src/main/java/carpet/script/exception/ProcessedThrowStatement.java +++ b/src/main/java/carpet/script/exception/ProcessedThrowStatement.java @@ -13,7 +13,7 @@ public class ProcessedThrowStatement extends ExpressionException public final Throwables thrownExceptionType; public final Value data; - public ProcessedThrowStatement(final Context c, final Expression e, final Token token, final List stack, final Throwables thrownExceptionType, final Value data) + public ProcessedThrowStatement(Context c, Expression e, Token token, List stack, Throwables thrownExceptionType, Value data) { super(c, e, token, () -> "Unhandled " + thrownExceptionType.getId() + " exception: " + data.getString(), stack); this.thrownExceptionType = thrownExceptionType; diff --git a/src/main/java/carpet/script/exception/ReturnStatement.java b/src/main/java/carpet/script/exception/ReturnStatement.java index e275efb915..a1ed7a6155 100644 --- a/src/main/java/carpet/script/exception/ReturnStatement.java +++ b/src/main/java/carpet/script/exception/ReturnStatement.java @@ -4,7 +4,7 @@ public class ReturnStatement extends ExitStatement { - public ReturnStatement(final Value value) + public ReturnStatement(Value value) { super(value); } diff --git a/src/main/java/carpet/script/exception/StacklessRuntimeException.java b/src/main/java/carpet/script/exception/StacklessRuntimeException.java index 1d6b65049b..476e6aefa1 100644 --- a/src/main/java/carpet/script/exception/StacklessRuntimeException.java +++ b/src/main/java/carpet/script/exception/StacklessRuntimeException.java @@ -10,7 +10,7 @@ public StacklessRuntimeException() super(); } - public StacklessRuntimeException(final String message) + public StacklessRuntimeException(String message) { super(message); } diff --git a/src/main/java/carpet/script/exception/ThrowStatement.java b/src/main/java/carpet/script/exception/ThrowStatement.java index f413246dd2..40cf10b952 100644 --- a/src/main/java/carpet/script/exception/ThrowStatement.java +++ b/src/main/java/carpet/script/exception/ThrowStatement.java @@ -18,14 +18,14 @@ public class ThrowStatement extends InternalExpressionException * @param data The value to pass * @param type Exception type */ - public ThrowStatement(final Value data, final Throwables type) + public ThrowStatement(Value data, Throwables type) { super(type.getId()); this.data = data; this.type = type; } - public ThrowStatement(final Value data, final Throwables parent, final String subtype) + public ThrowStatement(Value data, Throwables parent, String subtype) { super(subtype); this.data = data; @@ -42,7 +42,7 @@ public ThrowStatement(final Value data, final Throwables parent, final String su * for this exception. When throwing from Java, * those exceptions should be pre-registered. */ - public ThrowStatement(final String message, final Throwables type) + public ThrowStatement(String message, Throwables type) { super(type.getId()); this.data = StringValue.of(message); @@ -50,7 +50,7 @@ public ThrowStatement(final String message, final Throwables type) } @Override - public ExpressionException promote(final Context c, final Expression e, final Token token) + public ExpressionException promote(Context c, Expression e, Token token) { return new ProcessedThrowStatement(c, e, token, stack, type, data); } diff --git a/src/main/java/carpet/script/exception/Throwables.java b/src/main/java/carpet/script/exception/Throwables.java index 48e3d278a8..7d399dfa93 100644 --- a/src/main/java/carpet/script/exception/Throwables.java +++ b/src/main/java/carpet/script/exception/Throwables.java @@ -1,5 +1,6 @@ package carpet.script.exception; +import javax.annotation.Nullable; import java.util.HashMap; import java.util.Map; @@ -10,6 +11,7 @@ public class Throwables { private final String id; + @Nullable private final Throwables parent; private static final Map byId = new HashMap<>(); @@ -41,9 +43,9 @@ public class Throwables * @param parent The parent of the exception being created, or null if top-level * @return The created exception */ - public static Throwables register(final String id, final Throwables parent) + public static Throwables register(String id, @Nullable Throwables parent) { - final Throwables exc = new Throwables(id, parent); + Throwables exc = new Throwables(id, parent); byId.put(id, exc); return exc; } @@ -55,15 +57,15 @@ public static Throwables register(final String id, final Throwables parent) * * @param id The exception's value as a {@link String} */ - public Throwables(final String id, final Throwables parent) + public Throwables(String id, @Nullable Throwables parent) { this.id = id; this.parent = parent; } - public static Throwables getTypeForException(final String type) + public static Throwables getTypeForException(String type) { - final Throwables properType = byId.get(type); + Throwables properType = byId.get(type); if (properType == null) { throw new InternalExpressionException("Unknown exception type: " + type); @@ -78,7 +80,7 @@ public static Throwables getTypeForException(final String type) * @param filter The type to check against * @return Whether or not the given value matches this exception's hierarchy */ - public boolean isRelevantFor(final String filter) + public boolean isRelevantFor(String filter) { return (id.equals(filter) || (parent != null && parent.isRelevantFor(filter))); } diff --git a/src/main/java/carpet/script/external/Carpet.java b/src/main/java/carpet/script/external/Carpet.java index 1afd982aff..eafd1cd036 100644 --- a/src/main/java/carpet/script/external/Carpet.java +++ b/src/main/java/carpet/script/external/Carpet.java @@ -46,17 +46,17 @@ public static Map getScarpetFooters() return HUDController.scarpet_footers; } - public static void updateScarpetHUDs(final MinecraftServer server, final List players) + public static void updateScarpetHUDs(MinecraftServer server, List players) { HUDController.update_hud(server, players); } - public static Component Messenger_compose(final Object... messages) + public static Component Messenger_compose(Object... messages) { return Messenger.c(messages); } - public static void Messenger_message(final CommandSourceStack source, final Object... messages) + public static void Messenger_message(CommandSourceStack source, Object... messages) { Messenger.m(source, messages); } @@ -81,34 +81,34 @@ public static Map getMaterialNames() return BlockInfo.materialName; } - public static Runnable startProfilerSection(final String name) + public static Runnable startProfilerSection(String name) { - final CarpetProfiler.ProfilerToken token = CarpetProfiler.start_section(null, name, CarpetProfiler.TYPE.GENERAL); + CarpetProfiler.ProfilerToken token = CarpetProfiler.start_section(null, name, CarpetProfiler.TYPE.GENERAL); return () -> CarpetProfiler.end_current_section(token); } - public static void MinecraftServer_addScriptServer(final MinecraftServer server, final CarpetScriptServer scriptServer) + public static void MinecraftServer_addScriptServer(MinecraftServer server, CarpetScriptServer scriptServer) { ((MinecraftServerInterface) server).addScriptServer(scriptServer); } - public static boolean isValidCarpetPlayer(final ServerPlayer player) + public static boolean isValidCarpetPlayer(ServerPlayer player) { return ServerNetworkHandler.isValidCarpetPlayer(player); } - public static String getPlayerStatus(final ServerPlayer player) + public static String getPlayerStatus(ServerPlayer player) { return ServerNetworkHandler.getPlayerStatus(player); } public static MapValue getAllCarpetRules() { - final Collection> rules = CarpetServer.settingsManager.getCarpetRules(); - final MapValue carpetRules = new MapValue(Collections.emptyList()); + Collection> rules = CarpetServer.settingsManager.getCarpetRules(); + MapValue carpetRules = new MapValue(Collections.emptyList()); rules.forEach(rule -> carpetRules.put(new StringValue(rule.name()), new StringValue(RuleHelper.toRuleString(rule.value())))); CarpetServer.extensions.forEach(e -> { - final SettingsManager manager = e.extensionSettingsManager(); + SettingsManager manager = e.extensionSettingsManager(); if (manager == null) { return; @@ -124,7 +124,7 @@ public static String getCarpetVersion() } @Nullable - public static String isModdedPlayer(final Player p) + public static String isModdedPlayer(Player p) { if (p instanceof final EntityPlayerMPFake fake) { @@ -138,7 +138,7 @@ public static boolean isTickProcessingPaused() return !TickSpeed.process_entities; } - public static void handleExtensionsAPI(final CarpetExpression expression) + public static void handleExtensionsAPI(CarpetExpression expression) { CarpetServer.extensions.forEach(e -> e.scarpetApi(expression)); } @@ -151,7 +151,7 @@ public static boolean getFillUpdates() public static class ScarpetAppStoreValidator extends Validator { @Override - public String validate(final CommandSourceStack source, final CarpetRule currentRule, String newValue, final String stringInput) + public String validate(@Nullable CommandSourceStack source, CarpetRule currentRule, String newValue, String stringInput) { if (newValue.equals(currentRule.value())) { diff --git a/src/main/java/carpet/script/external/Vanilla.java b/src/main/java/carpet/script/external/Vanilla.java index 6458520071..79f2e00995 100644 --- a/src/main/java/carpet/script/external/Vanilla.java +++ b/src/main/java/carpet/script/external/Vanilla.java @@ -93,27 +93,27 @@ public class Vanilla { - public static void MinecraftServer_forceTick(final MinecraftServer server, final BooleanSupplier sup) + public static void MinecraftServer_forceTick(MinecraftServer server, BooleanSupplier sup) { ((MinecraftServerInterface) server).forceTick(sup); } - public static void ChunkMap_relightChunk(final ChunkMap chunkMap, final ChunkPos pos) + public static void ChunkMap_relightChunk(ChunkMap chunkMap, ChunkPos pos) { ((ThreadedAnvilChunkStorageInterface) chunkMap).relightChunk(pos); } - public static Map ChunkMap_regenerateChunkRegion(final ChunkMap chunkMap, final List requestedChunks) + public static Map ChunkMap_regenerateChunkRegion(ChunkMap chunkMap, List requestedChunks) { return ((ThreadedAnvilChunkStorageInterface) chunkMap).regenerateChunkRegion(requestedChunks); } - public static List> Ingredient_getRecipeStacks(final Ingredient ingredient) + public static List> Ingredient_getRecipeStacks(Ingredient ingredient) { return ((IngredientInterface) (Object) ingredient).getRecipeStacks(); } - public static List> RecipeManager_getAllMatching(final RecipeManager recipeManager, final RecipeType type, final ResourceLocation output, final RegistryAccess registryAccess) + public static List> RecipeManager_getAllMatching(RecipeManager recipeManager, RecipeType type, ResourceLocation output, RegistryAccess registryAccess) { return ((RecipeManagerInterface) recipeManager).getAllMatching(type, output, registryAccess); } @@ -123,72 +123,72 @@ public static int NaturalSpawner_MAGIC_NUMBER() return SpawnReporter.MAGIC_NUMBER; } - public static PotentialCalculator SpawnState_getPotentialCalculator(final NaturalSpawner.SpawnState spawnState) + public static PotentialCalculator SpawnState_getPotentialCalculator(NaturalSpawner.SpawnState spawnState) { return ((SpawnHelperInnerInterface) spawnState).getPotentialCalculator(); } - public static void Objective_setCriterion(final Objective objective, final ObjectiveCriteria criterion) + public static void Objective_setCriterion(Objective objective, ObjectiveCriteria criterion) { ((Objective_scarpetMixin) objective).setCriterion(criterion); } - public static Map> Scoreboard_getObjectivesByCriterion(final Scoreboard scoreboard) + public static Map> Scoreboard_getObjectivesByCriterion(Scoreboard scoreboard) { return ((Scoreboard_scarpetMixin) scoreboard).getObjectivesByCriterion(); } - public static ServerLevelData ServerLevel_getWorldProperties(final ServerLevel world) + public static ServerLevelData ServerLevel_getWorldProperties(ServerLevel world) { return ((ServerWorldInterface) world).getWorldPropertiesCM(); } - public static DistanceManager ServerChunkCache_getCMTicketManager(final ServerChunkCache chunkCache) + public static DistanceManager ServerChunkCache_getCMTicketManager(ServerChunkCache chunkCache) { return ((ServerChunkManagerInterface) chunkCache).getCMTicketManager(); } - public static Long2ObjectOpenHashMap>> ChunkTicketManager_getTicketsByPosition(final DistanceManager ticketManager) + public static Long2ObjectOpenHashMap>> ChunkTicketManager_getTicketsByPosition(DistanceManager ticketManager) { return ((ChunkTicketManagerInterface) ticketManager).getTicketsByPosition(); } - public static DensityFunction.Visitor RandomState_getVisitor(final RandomState randomState) + public static DensityFunction.Visitor RandomState_getVisitor(RandomState randomState) { return ((RandomStateVisitorAccessor) (Object) randomState).getVisitor(); } - public static CompoundTag BlockInput_getTag(final BlockInput blockInput) + public static CompoundTag BlockInput_getTag(BlockInput blockInput) { return ((BlockStateArgumentInterface) blockInput).getCMTag(); } - public static CarpetScriptServer MinecraftServer_getScriptServer(final MinecraftServer server) + public static CarpetScriptServer MinecraftServer_getScriptServer(MinecraftServer server) { return ((MinecraftServerInterface) server).getScriptServer(); } - public static Biome.ClimateSettings Biome_getClimateSettings(final Biome biome) + public static Biome.ClimateSettings Biome_getClimateSettings(Biome biome) { return ((BiomeInterface) (Object) biome).getClimateSettings(); } - public static ThreadLocal skipGenerationChecks(final ServerLevel level) + public static ThreadLocal skipGenerationChecks(ServerLevel level) { // not sure does vanilla care at all - needs checking return CarpetSettings.skipGenerationChecks; } - public static void sendScarpetShapesDataToPlayer(final ServerPlayer player, final Tag data) + public static void sendScarpetShapesDataToPlayer(ServerPlayer player, Tag data) { // dont forget to add the packet to vanilla packed handler and call ShapesRenderer.addShape to handle on client ServerNetworkHandler.sendCustomCommand(player, "scShapes", data); } - public static int MinecraftServer_getRunPermissionLevel(final MinecraftServer server) + public static int MinecraftServer_getRunPermissionLevel(MinecraftServer server) { return CarpetSettings.runPermissionLevel; } - public static String MinecraftServer_getReleaseTarget(final MinecraftServer server) + public static String MinecraftServer_getReleaseTarget(MinecraftServer server) { return CarpetSettings.releaseTarget; } @@ -198,165 +198,165 @@ public static boolean isDevelopmentEnvironment() return FabricLoader.getInstance().isDevelopmentEnvironment(); } - public static MapValue getServerMods(final MinecraftServer server) + public static MapValue getServerMods(MinecraftServer server) { - final Map ret = new HashMap<>(); - for (final ModContainer mod : FabricLoader.getInstance().getAllMods()) + Map ret = new HashMap<>(); + for (ModContainer mod : FabricLoader.getInstance().getAllMods()) { ret.put(new StringValue(mod.getMetadata().getId()), new StringValue(mod.getMetadata().getVersion().getFriendlyString())); } return MapValue.wrap(ret); } - public static LevelStorageSource.LevelStorageAccess MinecraftServer_storageSource(final MinecraftServer server) + public static LevelStorageSource.LevelStorageAccess MinecraftServer_storageSource(MinecraftServer server) { return ((MinecraftServerInterface) server).getCMSession(); } - public static BlockPos ServerPlayerGameMode_getCurrentBlockPosition(final ServerPlayerGameMode gameMode) + public static BlockPos ServerPlayerGameMode_getCurrentBlockPosition(ServerPlayerGameMode gameMode) { return ((ServerPlayerInteractionManagerInterface) gameMode).getCurrentBreakingBlock(); } - public static int ServerPlayerGameMode_getCurrentBlockBreakingProgress(final ServerPlayerGameMode gameMode) + public static int ServerPlayerGameMode_getCurrentBlockBreakingProgress(ServerPlayerGameMode gameMode) { return ((ServerPlayerInteractionManagerInterface) gameMode).getCurrentBlockBreakingProgress(); } - public static void ServerPlayerGameMode_setBlockBreakingProgress(final ServerPlayerGameMode gameMode, final int progress) + public static void ServerPlayerGameMode_setBlockBreakingProgress(ServerPlayerGameMode gameMode, int progress) { ((ServerPlayerInteractionManagerInterface) gameMode).setBlockBreakingProgress(progress); } - public static boolean ServerPlayer_isInvalidEntityObject(final ServerPlayer player) + public static boolean ServerPlayer_isInvalidEntityObject(ServerPlayer player) { return ((ServerPlayerInterface) player).isInvalidEntityObject(); } - public static String ServerPlayer_getLanguage(final ServerPlayer player) + public static String ServerPlayer_getLanguage(ServerPlayer player) { return ((ServerPlayerInterface) player).getLanguage(); } - public static GoalSelector Mob_getAI(final Mob mob, final boolean target) + public static GoalSelector Mob_getAI(Mob mob, boolean target) { return ((MobEntityInterface) mob).getAI(target); } - public static Map Mob_getTemporaryTasks(final Mob mob) + public static Map Mob_getTemporaryTasks(Mob mob) { return ((MobEntityInterface) mob).getTemporaryTasks(); } - public static void Mob_setPersistence(final Mob mob, final boolean what) + public static void Mob_setPersistence(Mob mob, boolean what) { ((MobEntityInterface) mob).setPersistence(what); } - public static EntityEventsGroup Entity_getEventContainer(final Entity entity) + public static EntityEventsGroup Entity_getEventContainer(Entity entity) { return ((EntityInterface) entity).getEventContainer(); } - public static boolean Entity_isPermanentVehicle(final Entity entity) + public static boolean Entity_isPermanentVehicle(Entity entity) { return ((EntityInterface) entity).isPermanentVehicle(); } - public static void Entity_setPermanentVehicle(final Entity entity, final boolean permanent) + public static void Entity_setPermanentVehicle(Entity entity, boolean permanent) { ((EntityInterface) entity).setPermanentVehicle(permanent); } - public static int Entity_getPortalTimer(final Entity entity) + public static int Entity_getPortalTimer(Entity entity) { return ((EntityInterface) entity).getPortalTimer(); } - public static void Entity_setPortalTimer(final Entity entity, final int amount) + public static void Entity_setPortalTimer(Entity entity, int amount) { ((EntityInterface) entity).setPortalTimer(amount); } - public static int Entity_getPublicNetherPortalCooldown(final Entity entity) + public static int Entity_getPublicNetherPortalCooldown(Entity entity) { return ((EntityInterface) entity).getPublicNetherPortalCooldown(); } - public static void Entity_setPublicNetherPortalCooldown(final Entity entity, final int what) + public static void Entity_setPublicNetherPortalCooldown(Entity entity, int what) { ((EntityInterface) entity).setPublicNetherPortalCooldown(what); } - public static int ItemEntity_getPickupDelay(final ItemEntity entity) + public static int ItemEntity_getPickupDelay(ItemEntity entity) { return ((ItemEntityInterface) entity).getPickupDelayCM(); } - public static boolean LivingEntity_isJumping(final LivingEntity entity) + public static boolean LivingEntity_isJumping(LivingEntity entity) { return ((LivingEntityInterface) entity).isJumpingCM(); } - public static void LivingEntity_setJumping(final LivingEntity entity) + public static void LivingEntity_setJumping(LivingEntity entity) { ((LivingEntityInterface) entity).doJumpCM(); } - public static Container AbstractHorse_getInventory(final AbstractHorse horse) + public static Container AbstractHorse_getInventory(AbstractHorse horse) { return ((InventoryBearerInterface) horse).getCMInventory(); } - public static DataSlot AbstractContainerMenu_getDataSlot(final AbstractContainerMenu handler, final int index) + public static DataSlot AbstractContainerMenu_getDataSlot(AbstractContainerMenu handler, int index) { return ((AbstractContainerMenuInterface) handler).getDataSlot(index); } - public static void CommandDispatcher_unregisterCommand(final CommandDispatcher dispatcher, final String name) + public static void CommandDispatcher_unregisterCommand(CommandDispatcher dispatcher, String name) { ((CommandDispatcherInterface) dispatcher).carpet$unregister(name); } - public static boolean MinecraftServer_doScriptsAutoload(final MinecraftServer server) + public static boolean MinecraftServer_doScriptsAutoload(MinecraftServer server) { return CarpetSettings.scriptsAutoload; } - public static void MinecraftServer_notifyPlayersCommandsChanged(final MinecraftServer server) + public static void MinecraftServer_notifyPlayersCommandsChanged(MinecraftServer server) { CommandHelper.notifyPlayersCommandsChanged(server); } - public static boolean ScriptServer_scriptOptimizations(final MinecraftServer scriptServer) + public static boolean ScriptServer_scriptOptimizations(MinecraftServer scriptServer) { return CarpetSettings.scriptsOptimization; } - public static boolean ScriptServer_scriptDebugging(final MinecraftServer server) + public static boolean ScriptServer_scriptDebugging(MinecraftServer server) { return CarpetSettings.scriptsDebugging; } - public static boolean ServerPlayer_canScriptACE(final CommandSourceStack player) + public static boolean ServerPlayer_canScriptACE(CommandSourceStack player) { return CommandHelper.canUseCommand(player, CarpetSettings.commandScriptACE); } - public static boolean ServerPlayer_canScriptGeneral(final CommandSourceStack player) + public static boolean ServerPlayer_canScriptGeneral(CommandSourceStack player) { return CommandHelper.canUseCommand(player, CarpetSettings.commandScript); } - public static int MinecraftServer_getFillLimit(final MinecraftServer server) + public static int MinecraftServer_getFillLimit(MinecraftServer server) { return Math.max(server.getGameRules().getInt(GameRules.RULE_COMMAND_MODIFICATION_BLOCK_LIMIT), CarpetSettings.fillLimit); } public record BlockPredicatePayload(BlockState state, TagKey tagKey, Map properties, CompoundTag tag) { - public static BlockPredicatePayload of(final Predicate blockPredicate) + public static BlockPredicatePayload of(Predicate blockPredicate) { - final BlockPredicateInterface predicateData = (BlockPredicateInterface) blockPredicate; + BlockPredicateInterface predicateData = (BlockPredicateInterface) blockPredicate; return new BlockPredicatePayload(predicateData.getCMBlockState(), predicateData.getCMBlockTagKey(), predicateData.getCMProperties(), predicateData.getCMDataTag()); } } diff --git a/src/main/java/carpet/script/external/VanillaClient.java b/src/main/java/carpet/script/external/VanillaClient.java index 5c7f1a17d4..874d15fc8a 100644 --- a/src/main/java/carpet/script/external/VanillaClient.java +++ b/src/main/java/carpet/script/external/VanillaClient.java @@ -7,7 +7,7 @@ public class VanillaClient { - public static ShulkerModel ShulkerBoxRenderer_model(final BlockEntityRenderer shulkerBoxRenderer) { + public static ShulkerModel ShulkerBoxRenderer_model(BlockEntityRenderer shulkerBoxRenderer) { return ((ShulkerBoxAccessMixin)shulkerBoxRenderer).getModel(); } } diff --git a/src/main/java/carpet/script/language/Arithmetic.java b/src/main/java/carpet/script/language/Arithmetic.java index 4b9c3df530..ca649abe98 100644 --- a/src/main/java/carpet/script/language/Arithmetic.java +++ b/src/main/java/carpet/script/language/Arithmetic.java @@ -13,12 +13,12 @@ public class Arithmetic public static final Value PI = new NumericValue(Math.PI); public static final Value euler = new NumericValue(Math.E); - public static void apply(final Expression expression) + public static void apply(Expression expression) { expression.addTypedContextFunction("not", 1, Context.Type.BOOLEAN, (c, t, lv) -> BooleanValue.of(lv.get(0).getBoolean())); - expression.addUnaryFunction("fact", (v) -> + expression.addUnaryFunction("fact", v -> { - final long number = NumericValue.asNumber(v).getLong(); + long number = NumericValue.asNumber(v).getLong(); if (number < 21) { long factorial = 1; @@ -82,26 +82,26 @@ else if (number > 170) expression.addMathematicalUnaryIntFunction("ceil", n -> (long) Math.ceil(n)); expression.addContextFunction("mandelbrot", 3, (c, t, lv) -> { - final double a0 = NumericValue.asNumber(lv.get(0)).getDouble(); - final double b0 = NumericValue.asNumber(lv.get(1)).getDouble(); - final long maxiter = NumericValue.asNumber(lv.get(2)).getLong(); + double a0 = NumericValue.asNumber(lv.get(0)).getDouble(); + double b0 = NumericValue.asNumber(lv.get(1)).getDouble(); + long maxiter = NumericValue.asNumber(lv.get(2)).getLong(); double a = 0.0D; double b = 0.0D; long iter = 0; while (a * a + b * b < 4 && iter < maxiter) { - final double temp = a * a - b * b + a0; + double temp = a * a - b * b + a0; b = 2 * a * b + b0; a = temp; iter++; } - final long iFinal = iter; + long iFinal = iter; return new NumericValue(iFinal); }); - expression.addFunction("max", (lv) -> + expression.addFunction("max", lv -> { - if (lv.size() == 0) + if (lv.isEmpty()) { throw new InternalExpressionException("'max' requires at least one parameter"); } @@ -110,7 +110,7 @@ else if (number > 170) { lv = ((ListValue) lv.get(0)).getItems(); } - for (final Value parameter : lv) + for (Value parameter : lv) { if (max == null || parameter.compareTo(max) > 0) { @@ -120,9 +120,9 @@ else if (number > 170) return max; }); - expression.addFunction("min", (lv) -> + expression.addFunction("min", lv -> { - if (lv.size() == 0) + if (lv.isEmpty()) { throw new InternalExpressionException("'min' requires at least one parameter"); } @@ -131,7 +131,7 @@ else if (number > 170) { lv = ((ListValue) lv.get(0)).getItems(); } - for (final Value parameter : lv) + for (Value parameter : lv) { if (min == null || parameter.compareTo(min) < 0) { diff --git a/src/main/java/carpet/script/language/ControlFlow.java b/src/main/java/carpet/script/language/ControlFlow.java index eb0aa5db85..d96d1209ea 100644 --- a/src/main/java/carpet/script/language/ControlFlow.java +++ b/src/main/java/carpet/script/language/ControlFlow.java @@ -19,23 +19,23 @@ public class ControlFlow { - public static void apply(final Expression expression) // public just to get the javadoc right + public static void apply(Expression expression) // public just to get the javadoc right { // needs to be lazy cause of custom contextualization expression.addLazyBinaryOperator(";", Operators.precedence.get("nextop;"), true, true, t -> Context.Type.VOID, (c, t, lv1, lv2) -> { lv1.evalValue(c, Context.VOID); - final Value v2 = lv2.evalValue(c, t); + Value v2 = lv2.evalValue(c, t); return (cc, tt) -> v2; }); expression.addPureLazyFunction("then", -1, t -> Context.Type.VOID, (c, t, lv) -> { - final int imax = lv.size() - 1; + int imax = lv.size() - 1; for (int i = 0; i < imax; i++) { lv.get(i).evalValue(c, Context.VOID); } - final Value v = lv.get(imax).evalValue(c, t); + Value v = lv.get(imax).evalValue(c, t); return (cc, tt) -> v; }); expression.addFunctionalEquivalence(";", "then"); @@ -52,20 +52,20 @@ public static void apply(final Expression expression) // public just to get the { if (lv.get(i).evalValue(c, Context.BOOLEAN).getBoolean()) { - final Value ret = lv.get(i + 1).evalValue(c, t); + Value ret = lv.get(i + 1).evalValue(c, t); return (cc, tt) -> ret; } } if (lv.size() % 2 == 1) { - final Value ret = lv.get(lv.size() - 1).evalValue(c, t); + Value ret = lv.get(lv.size() - 1).evalValue(c, t); return (cc, tt) -> ret; } return (cc, tt) -> Value.NULL; }); - expression.addImpureFunction("exit", (lv) -> { - throw new ExitStatement(lv.size() == 0 ? Value.NULL : lv.get(0)); + expression.addImpureFunction("exit", lv -> { + throw new ExitStatement(lv.isEmpty() ? Value.NULL : lv.get(0)); }); expression.addImpureFunction("throw", lv -> @@ -83,16 +83,16 @@ public static void apply(final Expression expression) // public just to get the // needs to be lazy since execution of parameters but first one are conditional expression.addLazyFunction("try", (c, t, lv) -> { - if (lv.size() == 0) + if (lv.isEmpty()) { throw new InternalExpressionException("'try' needs at least an expression block, and either a catch_epr, or a number of pairs of filters and catch_expr"); } try { - final Value retval = lv.get(0).evalValue(c, t); - return (c_, t_) -> retval; + Value retval = lv.get(0).evalValue(c, t); + return (ct, tt) -> retval; } - catch (final ProcessedThrowStatement ret) + catch (ProcessedThrowStatement ret) { if (lv.size() == 1) { @@ -100,7 +100,7 @@ public static void apply(final Expression expression) // public just to get the { throw ret; } - return (c_, t_) -> Value.NULL; + return (ct, tt) -> Value.NULL; } if (lv.size() > 3 && lv.size() % 2 == 0) { @@ -109,10 +109,10 @@ public static void apply(final Expression expression) // public just to get the Value val = null; // This is always assigned at some point, just the compiler doesn't know - final LazyValue __ = c.getVariable("_"); - c.setVariable("_", (__c, __t) -> ret.data.reboundedTo("_")); - final LazyValue _trace = c.getVariable("_trace"); - c.setVariable("_trace", (__c, __t) -> MapValue.wrap(Map.of( + LazyValue defaultVal = c.getVariable("_"); + c.setVariable("_", (ct, tt) -> ret.data.reboundedTo("_")); + LazyValue trace = c.getVariable("_trace"); + c.setVariable("_trace", (ct, tt) -> MapValue.wrap(Map.of( StringValue.of("stack"), ListValue.wrap(ret.stack.stream().map(f -> ListValue.of( StringValue.of(f.getModule().name()), StringValue.of(f.getString()), @@ -151,10 +151,10 @@ public static void apply(final Expression expression) // public just to get the pointer += 2; } } - c.setVariable("_", __); - if (_trace != null) + c.setVariable("_", defaultVal); + if (trace != null) { - c.setVariable("_trace", _trace); + c.setVariable("_trace", trace); } else { @@ -164,8 +164,8 @@ public static void apply(final Expression expression) // public just to get the { throw ret; } - final Value retval = val; - return (c_, t_) -> retval; + Value retval = val; + return (ct, tt) -> retval; } }); } diff --git a/src/main/java/carpet/script/language/DataStructures.java b/src/main/java/carpet/script/language/DataStructures.java index b70dd079fa..24adb64284 100644 --- a/src/main/java/carpet/script/language/DataStructures.java +++ b/src/main/java/carpet/script/language/DataStructures.java @@ -27,21 +27,21 @@ public class DataStructures { - public static void apply(final Expression expression) + public static void apply(Expression expression) { expression.addFunction("l", lv -> lv.size() == 1 && lv.get(0) instanceof final LazyListValue llv ? ListValue.wrap(llv.unroll()) : new ListValue.ListConstructorValue(lv)); - expression.addFunction("join", (lv) -> + expression.addFunction("join", lv -> { if (lv.size() < 2) { throw new InternalExpressionException("'join' takes at least 2 arguments"); } - final String delimiter = lv.get(0).getString(); - final List toJoin; + String delimiter = lv.get(0).getString(); + List toJoin; if (lv.size() == 2 && lv.get(1) instanceof final LazyListValue llv) { toJoin = llv.unroll(); @@ -57,10 +57,10 @@ else if (lv.size() == 2 && lv.get(1) instanceof final ListValue llv) return new StringValue(toJoin.stream().map(Value::getString).collect(Collectors.joining(delimiter))); }); - expression.addFunction("split", (lv) -> + expression.addFunction("split", lv -> { - final Value delimiter; - final Value hwat; + Value delimiter; + Value hwat; if (lv.size() == 1) { hwat = lv.get(0); @@ -78,14 +78,14 @@ else if (lv.size() == 2) return hwat.split(delimiter); }); - expression.addFunction("slice", (lv) -> + expression.addFunction("slice", lv -> { if (lv.size() != 2 && lv.size() != 3) { throw new InternalExpressionException("'slice' takes 2 or 3 arguments"); } - final Value hwat = lv.get(0); - final long from = NumericValue.asNumber(lv.get(1)).getLong(); + Value hwat = lv.get(0); + long from = NumericValue.asNumber(lv.get(1)).getLong(); Long to = null; if (lv.size() == 3) { @@ -94,7 +94,7 @@ else if (lv.size() == 2) return hwat.slice(from, to); }); - expression.addFunction("sort", (lv) -> + expression.addFunction("sort", lv -> { List toSort = lv; if (lv.size() == 1 && lv.get(0) instanceof final ListValue llv) @@ -108,44 +108,44 @@ else if (lv.size() == 2) // needs lazy cause sort function is reused expression.addLazyFunction("sort_key", (c, t, lv) -> //get working with iterators { - if (lv.size() == 0) + if (lv.isEmpty()) { throw new InternalExpressionException("First argument for 'sort_key' should be a List"); } - final Value v = lv.get(0).evalValue(c); + Value v = lv.get(0).evalValue(c); if (!(v instanceof final ListValue list)) { throw new InternalExpressionException("First argument for 'sort_key' should be a List"); } - final List toSort = new ArrayList<>(list.getItems()); + List toSort = new ArrayList<>(list.getItems()); if (lv.size() == 1) { Collections.shuffle(toSort); - final Value ret = ListValue.wrap(toSort); - return (_c, _t) -> ret; + Value ret = ListValue.wrap(toSort); + return (ct, tt) -> ret; } - final LazyValue sortKey = lv.get(1); + LazyValue sortKey = lv.get(1); //scoping - final LazyValue __ = c.getVariable("_"); + LazyValue defaultVal = c.getVariable("_"); toSort.sort((v1, v2) -> { c.setVariable("_", (cc, tt) -> v1); - final Value ev1 = sortKey.evalValue(c); + Value ev1 = sortKey.evalValue(c); c.setVariable("_", (cc, tt) -> v2); - final Value ev2 = sortKey.evalValue(c); + Value ev2 = sortKey.evalValue(c); return ev1.compareTo(ev2); }); //revering scope - c.setVariable("_", __); - final Value ret = ListValue.wrap(toSort); + c.setVariable("_", defaultVal); + Value ret = ListValue.wrap(toSort); return (cc, tt) -> ret; }); - expression.addFunction("range", (lv) -> + expression.addFunction("range", lv -> { NumericValue from = Value.ZERO; NumericValue to; NumericValue step = Value.ONE; - final int argsize = lv.size(); + int argsize = lv.size(); if (argsize == 0 || argsize > 3) { throw new InternalExpressionException("'range' accepts from 1 to 3 arguments, not " + argsize); @@ -192,7 +192,7 @@ else if (lv.size() == 2) { if (container instanceof final LContainerValue lcv) { - final ContainerValueInterface outerContainer = lcv.container(); + ContainerValueInterface outerContainer = lcv.container(); if (outerContainer == null) { return LContainerValue.NULL_CONTAINER; @@ -211,23 +211,23 @@ else if (lv.size() == 2) // lazy cause conditional typing - questionable expression.addLazyFunction("get", (c, t, lv) -> { - if (lv.size() == 0) + if (lv.isEmpty()) { throw new InternalExpressionException("'get' requires parameters"); } if (lv.size() == 1) { - final Value v = lv.get(0).evalValue(c, Context.LVALUE); + Value v = lv.get(0).evalValue(c, Context.LVALUE); if (!(v instanceof final LContainerValue lcv)) { return LazyValue.NULL; } - final ContainerValueInterface container = lcv.container(); + ContainerValueInterface container = lcv.container(); if (container == null) { return LazyValue.NULL; } - final Value ret = container.get(lcv.address()); + Value ret = container.get(lcv.address()); return (cc, tt) -> ret; } Value container = lv.get(0).evalValue(c); @@ -243,30 +243,30 @@ else if (lv.size() == 2) { return (cc, tt) -> Value.NULL; } - final Value finalContainer = container; + Value finalContainer = container; return (cc, tt) -> finalContainer; }); // same as `get` expression.addLazyFunction("has", (c, t, lv) -> { - if (lv.size() == 0) + if (lv.isEmpty()) { throw new InternalExpressionException("'has' requires parameters"); } if (lv.size() == 1) { - final Value v = lv.get(0).evalValue(c, Context.LVALUE); + Value v = lv.get(0).evalValue(c, Context.LVALUE); if (!(v instanceof final LContainerValue lcv)) { return LazyValue.NULL; } - final ContainerValueInterface container = lcv.container(); + ContainerValueInterface container = lcv.container(); if (container == null) { return LazyValue.NULL; } - final Value ret = BooleanValue.of(container.has(lcv.address())); + Value ret = BooleanValue.of(container.has(lcv.address())); return (cc, tt) -> ret; } Value container = lv.get(0).evalValue(c); @@ -282,7 +282,7 @@ else if (lv.size() == 2) { return LazyValue.NULL; } - final Value ret = BooleanValue.of(cvi.has(lv.get(lv.size() - 1).evalValue(c))); + Value ret = BooleanValue.of(cvi.has(lv.get(lv.size() - 1).evalValue(c))); return (cc, tt) -> ret; }); @@ -293,17 +293,17 @@ else if (lv.size() == 2) { throw new InternalExpressionException("'put' takes at least three arguments, a container, address, and values to insert at that index"); } - final Value container = lv.get(0).evalValue(c, Context.LVALUE); + Value container = lv.get(0).evalValue(c, Context.LVALUE); if (container instanceof final LContainerValue lcv) { - final ContainerValueInterface internalContainer = lcv.container(); + ContainerValueInterface internalContainer = lcv.container(); if (internalContainer == null) { return LazyValue.NULL; } - final Value address = lcv.address(); - final Value what = lv.get(1).evalValue(c); - final Value retVal = BooleanValue.of((lv.size() > 2) + Value address = lcv.address(); + Value what = lv.get(1).evalValue(c); + Value retVal = BooleanValue.of((lv.size() > 2) ? internalContainer.put(address, what, lv.get(2).evalValue(c)) : internalContainer.put(address, what)); return (cc, tt) -> retVal; @@ -317,9 +317,9 @@ else if (lv.size() == 2) { return LazyValue.NULL; } - final Value where = lv.get(1).evalValue(c); - final Value what = lv.get(2).evalValue(c); - final Value retVal = BooleanValue.of((lv.size() > 3) + Value where = lv.get(1).evalValue(c); + Value what = lv.get(2).evalValue(c); + Value retVal = BooleanValue.of((lv.size() > 3) ? cvi.put(where, what, lv.get(3).evalValue(c)) : cvi.put(where, what)); return (cc, tt) -> retVal; @@ -328,23 +328,23 @@ else if (lv.size() == 2) // same as `get` expression.addLazyFunction("delete", (c, t, lv) -> { - if (lv.size() == 0) + if (lv.isEmpty()) { throw new InternalExpressionException("'delete' requires parameters"); } if (lv.size() == 1) { - final Value v = lv.get(0).evalValue(c, Context.LVALUE); + Value v = lv.get(0).evalValue(c, Context.LVALUE); if (!(v instanceof final LContainerValue lcv)) { return LazyValue.NULL; } - final ContainerValueInterface container = lcv.container(); + ContainerValueInterface container = lcv.container(); if (container == null) { return LazyValue.NULL; } - final Value ret = BooleanValue.of(container.delete(lcv.address())); + Value ret = BooleanValue.of(container.delete(lcv.address())); return (cc, tt) -> ret; } Value container = lv.get(0).evalValue(c); @@ -360,7 +360,7 @@ else if (lv.size() == 2) { return LazyValue.NULL; } - final Value ret = BooleanValue.of(cvi.delete(lv.get(lv.size() - 1).evalValue(c))); + Value ret = BooleanValue.of(cvi.delete(lv.get(lv.size() - 1).evalValue(c))); return (cc, tt) -> ret; }); @@ -370,7 +370,7 @@ else if (lv.size() == 2) { return StringValue.of(new String(Base64.getDecoder().decode(v.getString()), StandardCharsets.UTF_8)); } - catch (final IllegalArgumentException iae) + catch (IllegalArgumentException iae) { throw new ThrowStatement("Invalid b64 string: " + v.getString(), Throwables.B64_ERROR); } @@ -382,7 +382,7 @@ else if (lv.size() == 2) { return Auxiliary.GSON.fromJson(v.getString(), Value.class); } - catch (final JsonParseException jpe) + catch (JsonParseException jpe) { throw new ThrowStatement("Invalid json string: " + v.getString(), Throwables.JSON_ERROR); } diff --git a/src/main/java/carpet/script/language/Functions.java b/src/main/java/carpet/script/language/Functions.java index 93e1196eae..8bc29712df 100644 --- a/src/main/java/carpet/script/language/Functions.java +++ b/src/main/java/carpet/script/language/Functions.java @@ -21,7 +21,7 @@ public class Functions { - public static void apply(final Expression expression) // public just to get the javadoc right + public static void apply(Expression expression) // public just to get the javadoc right { // artificial construct to handle user defined functions and function definitions expression.addContextFunction("import", -1, (c, t, lv) -> @@ -45,28 +45,28 @@ public static void apply(final Expression expression) // public just to get the expression.addCustomFunction("call", new Fluff.AbstractLazyFunction(-1, "call") { @Override - public LazyValue lazyEval(final Context c, final Context.Type t, final Expression expr, final Tokenizer.Token tok, final List lv) + public LazyValue lazyEval(Context c, Context.Type t, Expression expr, Tokenizer.Token tok, List lv) { - if (lv.size() == 0) + if (lv.isEmpty()) { throw new InternalExpressionException("'call' expects at least function name to call"); } //lv.remove(lv.size()-1); // aint gonna cut it // maybe it will because of the eager eval changes if (t != Context.SIGNATURE) // just call the function { - final List args = Fluff.AbstractFunction.unpackLazy(lv, c, Context.NONE); - final FunctionArgument functionArgument = FunctionArgument.findIn(c, expression.module, args, 0, false, true); - final FunctionValue fun = functionArgument.function; + List args = Fluff.AbstractFunction.unpackLazy(lv, c, Context.NONE); + FunctionArgument functionArgument = FunctionArgument.findIn(c, expression.module, args, 0, false, true); + FunctionValue fun = functionArgument.function; return fun.callInContext(c, t, functionArgument.args); } // gimme signature - final String name = lv.get(0).evalValue(c, Context.NONE).getString(); - final List args = new ArrayList<>(); - final List globals = new ArrayList<>(); + String name = lv.get(0).evalValue(c, Context.NONE).getString(); + List args = new ArrayList<>(); + List globals = new ArrayList<>(); String varArgs = null; for (int i = 1; i < lv.size(); i++) { - final Value v = lv.get(i).evalValue(c, Context.LOCALIZATION); + Value v = lv.get(i).evalValue(c, Context.LOCALIZATION); if (!v.isBound()) { throw new InternalExpressionException("Only variables can be used in function signature, not " + v.getString()); @@ -91,7 +91,7 @@ public LazyValue lazyEval(final Context c, final Context.Type t, final Expressio args.add(v.boundVariable); } } - final Value retval = new FunctionSignatureValue(name, args, varArgs, globals); + Value retval = new FunctionSignatureValue(name, args, varArgs, globals); return (cc, tt) -> retval; } @@ -108,7 +108,7 @@ public boolean transitive() } @Override - public Context.Type staticType(final Context.Type outerType) + public Context.Type staticType(Context.Type outerType) { return outerType == Context.SIGNATURE ? Context.LOCALIZATION : Context.NONE; } @@ -130,19 +130,19 @@ public Context.Type staticType(final Context.Type outerType) { if (type == Context.MAPDEF) { - final Value result = ListValue.of(lv1.evalValue(c), lv2.evalValue(c)); + Value result = ListValue.of(lv1.evalValue(c), lv2.evalValue(c)); return (cc, tt) -> result; } - final Value v1 = lv1.evalValue(c, Context.SIGNATURE); + Value v1 = lv1.evalValue(c, Context.SIGNATURE); if (!(v1 instanceof final FunctionSignatureValue sign)) { throw new InternalExpressionException("'->' operator requires a function signature on the LHS"); } - final Value result = expression.createUserDefinedFunction(c, sign.identifier(), e, t, sign.arguments(), sign.varArgs(), sign.globals(), lv2); + Value result = expression.createUserDefinedFunction(c, sign.identifier(), e, t, sign.arguments(), sign.varArgs(), sign.globals(), lv2); return (cc, tt) -> result; }); - expression.addImpureFunction("return", (lv) -> { + expression.addImpureFunction("return", lv -> { throw new ReturnStatement(lv.size() == 0 ? Value.NULL : lv.get(0)); }); } diff --git a/src/main/java/carpet/script/language/Loops.java b/src/main/java/carpet/script/language/Loops.java index 36e4b626c3..ac42642b25 100644 --- a/src/main/java/carpet/script/language/Loops.java +++ b/src/main/java/carpet/script/language/Loops.java @@ -17,14 +17,14 @@ public class Loops { - public static void apply(final Expression expression) + public static void apply(Expression expression) { // condition and expression will get a bound '_i' // returns last successful expression or false // while(cond, limit, expr) => ?? expression.addImpureFunction("break", lv -> { - if (lv.size() == 0) + if (lv.isEmpty()) { throw new BreakStatement(null); } @@ -37,7 +37,7 @@ public static void apply(final Expression expression) expression.addImpureFunction("continue", lv -> { - if (lv.size() == 0) + if (lv.isEmpty()) { throw new ContinueStatement(null); } @@ -51,13 +51,13 @@ public static void apply(final Expression expression) // lazy expression.addLazyFunction("while", 3, (c, t, lv) -> { - final long limit = NumericValue.asNumber(lv.get(1).evalValue(c)).getLong(); - final LazyValue condition = lv.get(0); - final LazyValue expr = lv.get(2); + long limit = NumericValue.asNumber(lv.get(1).evalValue(c)).getLong(); + LazyValue condition = lv.get(0); + LazyValue expr = lv.get(2); long i = 0; Value lastOne = Value.NULL; //scoping - final LazyValue _val = c.getVariable("_"); + LazyValue defaultVal = c.getVariable("_"); c.setVariable("_", (cc, tt) -> new NumericValue(0).bindTo("_")); while (i < limit && condition.evalValue(c, Context.BOOLEAN).getBoolean()) { @@ -65,7 +65,7 @@ public static void apply(final Expression expression) { lastOne = expr.evalValue(c, t); } - catch (final BreakStatement | ContinueStatement stmt) + catch (BreakStatement | ContinueStatement stmt) { if (stmt.retval != null) { @@ -77,33 +77,33 @@ public static void apply(final Expression expression) } } i++; - final long seriously = i; + long seriously = i; c.setVariable("_", (cc, tt) -> new NumericValue(seriously).bindTo("_")); } //revering scope - c.setVariable("_", _val); - final Value lastValueNoKidding = lastOne; + c.setVariable("_", defaultVal); + Value lastValueNoKidding = lastOne; return (cc, tt) -> lastValueNoKidding; }); - // loop(Num, expr) => last_value + // loop(Num, expr) => lastdefaultValue // expr receives bounded variable '_' indicating iteration expression.addLazyFunction("loop", 2, (c, t, lv) -> { - final long limit = NumericValue.asNumber(lv.get(0).evalValue(c, Context.NONE)).getLong(); + long limit = NumericValue.asNumber(lv.get(0).evalValue(c, Context.NONE)).getLong(); Value lastOne = Value.NULL; - final LazyValue expr = lv.get(1); + LazyValue expr = lv.get(1); //scoping - final LazyValue _val = c.getVariable("_"); + LazyValue defaultVal = c.getVariable("_"); for (long i = 0; i < limit; i++) { - final long whyYouAsk = i; + long whyYouAsk = i; c.setVariable("_", (cc, tt) -> new NumericValue(whyYouAsk).bindTo("_")); try { lastOne = expr.evalValue(c, t); } - catch (final BreakStatement | ContinueStatement stmt) + catch (BreakStatement | ContinueStatement stmt) { if (stmt.retval != null) { @@ -116,8 +116,8 @@ public static void apply(final Expression expression) } } //revering scope - c.setVariable("_", _val); - final Value trulyLastOne = lastOne; + c.setVariable("_", defaultVal); + Value trulyLastOne = lastOne; return (cc, tt) -> trulyLastOne; }); @@ -125,7 +125,7 @@ public static void apply(final Expression expression) // receives bounded variable '_' with the expression expression.addLazyFunction("map", 2, (c, t, lv) -> { - final Value rval = lv.get(0).evalValue(c, Context.NONE); + Value rval = lv.get(0).evalValue(c, Context.NONE); if (rval.isNull()) { return ListValue.lazyEmpty(); @@ -134,25 +134,25 @@ public static void apply(final Expression expression) { throw new InternalExpressionException("First argument of 'map' function should be a list or iterator"); } - final Iterator iterator = alv.iterator(); - final LazyValue expr = lv.get(1); + Iterator iterator = alv.iterator(); + LazyValue expr = lv.get(1); //scoping - final LazyValue _val = c.getVariable("_"); - final LazyValue _iter = c.getVariable("_i"); - final List result = new ArrayList<>(); + LazyValue defaultVal = c.getVariable("_"); + LazyValue iterVal = c.getVariable("_i"); + List result = new ArrayList<>(); for (int i = 0; iterator.hasNext(); i++) { - final Value next = iterator.next(); - final String var = next.boundVariable; + Value next = iterator.next(); + String variable = next.boundVariable; next.bindTo("_"); - final int doYouReally = i; + int doYouReally = i; c.setVariable("_", (cc, tt) -> next); c.setVariable("_i", (cc, tt) -> new NumericValue(doYouReally).bindTo("_i")); try { result.add(expr.evalValue(c, t)); } - catch (final BreakStatement | ContinueStatement stmt) + catch (BreakStatement | ContinueStatement stmt) { if (stmt.retval != null) { @@ -160,17 +160,17 @@ public static void apply(final Expression expression) } if (stmt instanceof BreakStatement) { - next.boundVariable = var; + next.boundVariable = variable; break; } } - next.boundVariable = var; + next.boundVariable = variable; } ((AbstractListValue) rval).fatality(); - final Value ret = ListValue.wrap(result); + Value ret = ListValue.wrap(result); //revering scope - c.setVariable("_", _val); - c.setVariable("_i", _iter); + c.setVariable("_", defaultVal); + c.setVariable("_i", iterVal); return (cc, tt) -> ret; }); @@ -179,7 +179,7 @@ public static void apply(final Expression expression) // produces list of values for which the expression is true expression.addLazyFunction("filter", 2, (c, t, lv) -> { - final Value rval = lv.get(0).evalValue(c, Context.NONE); + Value rval = lv.get(0).evalValue(c, Context.NONE); if (rval.isNull()) { return ListValue.lazyEmpty(); @@ -188,18 +188,18 @@ public static void apply(final Expression expression) { throw new InternalExpressionException("First argument of 'filter' function should be a list or iterator"); } - final Iterator iterator = alv.iterator(); - final LazyValue expr = lv.get(1); + Iterator iterator = alv.iterator(); + LazyValue expr = lv.get(1); //scoping - final LazyValue _val = c.getVariable("_"); - final LazyValue _iter = c.getVariable("_i"); - final List result = new ArrayList<>(); + LazyValue defaultVal = c.getVariable("_"); + LazyValue iterVal = c.getVariable("_i"); + List result = new ArrayList<>(); for (int i = 0; iterator.hasNext(); i++) { - final Value next = iterator.next(); - final String var = next.boundVariable; + Value next = iterator.next(); + String veriable = next.boundVariable; next.bindTo("_"); - final int seriously = i; + int seriously = i; c.setVariable("_", (cc, tt) -> next); c.setVariable("_i", (cc, tt) -> new NumericValue(seriously).bindTo("_i")); try @@ -209,7 +209,7 @@ public static void apply(final Expression expression) result.add(next); } } - catch (final BreakStatement | ContinueStatement stmt) + catch (BreakStatement | ContinueStatement stmt) { if (stmt.retval != null && stmt.retval.getBoolean()) { @@ -217,17 +217,17 @@ public static void apply(final Expression expression) } if (stmt instanceof BreakStatement) { - next.boundVariable = var; + next.boundVariable = veriable; break; } } - next.boundVariable = var; + next.boundVariable = veriable; } ((AbstractListValue) rval).fatality(); - final Value ret = ListValue.wrap(result); + Value ret = ListValue.wrap(result); //revering scope - c.setVariable("_", _val); - c.setVariable("_i", _iter); + c.setVariable("_", defaultVal); + c.setVariable("_i", iterVal); return (cc, tt) -> ret; }); @@ -236,7 +236,7 @@ public static void apply(final Expression expression) // returns first element on the list for which the expr is true expression.addLazyFunction("first", 2, (c, t, lv) -> { - final Value rval = lv.get(0).evalValue(c, Context.NONE); + Value rval = lv.get(0).evalValue(c, Context.NONE); if (rval.isNull()) { return LazyValue.NULL; @@ -245,18 +245,18 @@ public static void apply(final Expression expression) { throw new InternalExpressionException("First argument of 'first' function should be a list or iterator"); } - final Iterator iterator = alv.iterator(); - final LazyValue expr = lv.get(1); + Iterator iterator = alv.iterator(); + LazyValue expr = lv.get(1); //scoping - final LazyValue _val = c.getVariable("_"); - final LazyValue _iter = c.getVariable("_i"); + LazyValue defaultVal = c.getVariable("_"); + LazyValue iterVal = c.getVariable("_i"); Value result = Value.NULL; for (int i = 0; iterator.hasNext(); i++) { - final Value next = iterator.next(); - final String var = next.boundVariable; + Value next = iterator.next(); + String variable = next.boundVariable; next.bindTo("_"); - final int seriously = i; + int seriously = i; c.setVariable("_", (cc, tt) -> next); c.setVariable("_i", (cc, tt) -> new NumericValue(seriously).bindTo("_i")); try @@ -264,27 +264,27 @@ public static void apply(final Expression expression) if (expr.evalValue(c, Context.BOOLEAN).getBoolean()) { result = next; - next.boundVariable = var; + next.boundVariable = variable; break; } } - catch (final BreakStatement stmt) + catch (BreakStatement stmt) { result = stmt.retval == null ? next : stmt.retval; - next.boundVariable = var; + next.boundVariable = variable; break; } - catch (final ContinueStatement ignored) + catch (ContinueStatement ignored) { throw new InternalExpressionException("'continue' inside 'first' function has no sense"); } - next.boundVariable = var; + next.boundVariable = variable; } //revering scope ((AbstractListValue) rval).fatality(); - final Value whyWontYouTrustMeJava = result; - c.setVariable("_", _val); - c.setVariable("_i", _iter); + Value whyWontYouTrustMeJava = result; + c.setVariable("_", defaultVal); + c.setVariable("_i", iterVal); return (cc, tt) -> whyWontYouTrustMeJava; }); @@ -293,7 +293,7 @@ public static void apply(final Expression expression) // returns true if expr is true for all items expression.addLazyFunction("all", 2, (c, t, lv) -> { - final Value rval = lv.get(0).evalValue(c, Context.NONE); + Value rval = lv.get(0).evalValue(c, Context.NONE); if (rval.isNull()) { return LazyValue.TRUE; @@ -302,42 +302,42 @@ public static void apply(final Expression expression) { throw new InternalExpressionException("First argument of 'all' function should be a list or iterator"); } - final Iterator iterator = alv.iterator(); - final LazyValue expr = lv.get(1); + Iterator iterator = alv.iterator(); + LazyValue expr = lv.get(1); //scoping - final LazyValue _val = c.getVariable("_"); - final LazyValue _iter = c.getVariable("_i"); + LazyValue defaultVal = c.getVariable("_"); + LazyValue iterVal = c.getVariable("_i"); LazyValue result = LazyValue.TRUE; for (int i = 0; iterator.hasNext(); i++) { - final Value next = iterator.next(); - final String var = next.boundVariable; + Value next = iterator.next(); + String variable = next.boundVariable; next.bindTo("_"); - final int seriously = i; + int seriously = i; c.setVariable("_", (cc, tt) -> next); c.setVariable("_i", (cc, tt) -> new NumericValue(seriously).bindTo("_i")); if (!expr.evalValue(c, Context.BOOLEAN).getBoolean()) { result = LazyValue.FALSE; - next.boundVariable = var; + next.boundVariable = variable; break; } - next.boundVariable = var; + next.boundVariable = variable; } //revering scope ((AbstractListValue) rval).fatality(); - c.setVariable("_", _val); - c.setVariable("_i", _iter); + c.setVariable("_", defaultVal); + c.setVariable("_i", iterVal); return result; }); // runs traditional for(init, condition, increment, body) tri-argument for loop with body in between expression.addLazyFunction("c_for", 4, (c, t, lv) -> { - final LazyValue initial = lv.get(0); - final LazyValue condition = lv.get(1); - final LazyValue increment = lv.get(2); - final LazyValue body = lv.get(3); + LazyValue initial = lv.get(0); + LazyValue condition = lv.get(1); + LazyValue increment = lv.get(2); + LazyValue body = lv.get(3); int iterations = 0; for (initial.evalValue(c, Context.VOID); condition.evalValue(c, Context.BOOLEAN).getBoolean(); increment.evalValue(c, Context.VOID)) { @@ -345,16 +345,16 @@ public static void apply(final Expression expression) { body.evalValue(c, Context.VOID); } - catch (final BreakStatement stmt) + catch (BreakStatement stmt) { break; } - catch (final ContinueStatement ignored) + catch (ContinueStatement ignored) { } iterations++; } - final int finalIterations = iterations; + int finalIterations = iterations; return (cc, tt) -> new NumericValue(finalIterations); }); @@ -363,7 +363,7 @@ public static void apply(final Expression expression) // can be substituted for first and all, but first is more efficient and all doesn't require knowing list size expression.addLazyFunction("for", 2, (c, t, lv) -> { - final Value rval = lv.get(0).evalValue(c, Context.NONE); + Value rval = lv.get(0).evalValue(c, Context.NONE); if (rval.isNull()) { return LazyValue.ZERO; @@ -372,18 +372,18 @@ public static void apply(final Expression expression) { throw new InternalExpressionException("First argument of 'for' function should be a list or iterator"); } - final Iterator iterator = alv.iterator(); - final LazyValue expr = lv.get(1); + Iterator iterator = alv.iterator(); + LazyValue expr = lv.get(1); //scoping - final LazyValue _val = c.getVariable("_"); - final LazyValue _ite = c.getVariable("_i"); + LazyValue defaultVal = c.getVariable("_"); + LazyValue iterVal = c.getVariable("_i"); int successCount = 0; for (int i = 0; iterator.hasNext(); i++) { - final Value next = iterator.next(); - final String var = next.boundVariable; + Value next = iterator.next(); + String variable = next.boundVariable; next.bindTo("_"); - final int seriously = i; + int seriously = i; c.setVariable("_", (cc, tt) -> next); c.setVariable("_i", (cc, tt) -> new NumericValue(seriously).bindTo("_i")); Value result = Value.FALSE; @@ -391,7 +391,7 @@ public static void apply(final Expression expression) { result = expr.evalValue(c, t); } - catch (final BreakStatement | ContinueStatement stmt) + catch (BreakStatement | ContinueStatement stmt) { if (stmt.retval != null) { @@ -399,7 +399,7 @@ public static void apply(final Expression expression) } if (stmt instanceof BreakStatement) { - next.boundVariable = var; + next.boundVariable = variable; break; } } @@ -407,13 +407,13 @@ public static void apply(final Expression expression) { successCount++; } - next.boundVariable = var; + next.boundVariable = variable; } //revering scope ((AbstractListValue) rval).fatality(); - c.setVariable("_", _val); - c.setVariable("_i", _ite); - final long promiseWontChange = successCount; + c.setVariable("_", defaultVal); + c.setVariable("_i", iterVal); + long promiseWontChange = successCount; return (cc, tt) -> new NumericValue(promiseWontChange); }); @@ -425,7 +425,7 @@ public static void apply(final Expression expression) expression.addLazyFunction("reduce", 3, (c, t, lv) -> { - final Value rval = lv.get(0).evalValue(c, Context.NONE); + Value rval = lv.get(0).evalValue(c, Context.NONE); if (rval.isNull()) { return ListValue.lazyEmpty(); @@ -434,28 +434,28 @@ public static void apply(final Expression expression) { throw new InternalExpressionException("First argument of 'reduce' should be a list or iterator"); } - final LazyValue expr = lv.get(1); + LazyValue expr = lv.get(1); Value acc = lv.get(2).evalValue(c, Context.NONE); - final Iterator iterator = alv.iterator(); + Iterator iterator = alv.iterator(); if (!iterator.hasNext()) { - final Value seriouslyWontChange = acc; + Value seriouslyWontChange = acc; return (cc, tt) -> seriouslyWontChange; } //scoping - final LazyValue _val = c.getVariable("_"); - final LazyValue _acc = c.getVariable("_a"); - final LazyValue _ite = c.getVariable("_i"); + LazyValue defaultVal = c.getVariable("_"); + LazyValue accumulatorVal = c.getVariable("_a"); + LazyValue iterVal = c.getVariable("_i"); for (int i = 0; iterator.hasNext(); i++) { - final Value next = iterator.next(); - final String var = next.boundVariable; + Value next = iterator.next(); + String variable = next.boundVariable; next.bindTo("_"); - final Value promiseWontChangeYou = acc; - final int seriously = i; + Value promiseWontChangeYou = acc; + int seriously = i; c.setVariable("_a", (cc, tt) -> promiseWontChangeYou.bindTo("_a")); c.setVariable("_", (cc, tt) -> next); c.setVariable("_i", (cc, tt) -> new NumericValue(seriously).bindTo("_i")); @@ -463,7 +463,7 @@ public static void apply(final Expression expression) { acc = expr.evalValue(c, t); } - catch (final BreakStatement | ContinueStatement stmt) + catch (BreakStatement | ContinueStatement stmt) { if (stmt.retval != null) { @@ -471,19 +471,19 @@ public static void apply(final Expression expression) } if (stmt instanceof BreakStatement) { - next.boundVariable = var; + next.boundVariable = variable; break; } } - next.boundVariable = var; + next.boundVariable = variable; } //reverting scope ((AbstractListValue) rval).fatality(); - c.setVariable("_a", _acc); - c.setVariable("_", _val); - c.setVariable("_i", _ite); + c.setVariable("_a", accumulatorVal); + c.setVariable("_", defaultVal); + c.setVariable("_i", iterVal); - final Value hopeItsEnoughPromise = acc; + Value hopeItsEnoughPromise = acc; return (cc, tt) -> hopeItsEnoughPromise; }); } diff --git a/src/main/java/carpet/script/language/Operators.java b/src/main/java/carpet/script/language/Operators.java index 539ed3fc6e..24a3ce2006 100644 --- a/src/main/java/carpet/script/language/Operators.java +++ b/src/main/java/carpet/script/language/Operators.java @@ -39,17 +39,17 @@ public class Operators put("nextop;", 1); }}; - public static void apply(final Expression expression) + public static void apply(Expression expression) { expression.addBinaryOperator("+", precedence.get("addition+-"), true, Value::add); expression.addFunction("sum", lv -> { - final int size = lv.size(); + int size = lv.size(); if (size == 0) { return Value.NULL; } Value accumulator = lv.get(0); - for (final Value v : lv.subList(1, size)) + for (Value v : lv.subList(1, size)) { accumulator = accumulator.add(v); } @@ -59,13 +59,13 @@ public static void apply(final Expression expression) expression.addBinaryOperator("-", precedence.get("addition+-"), true, Value::subtract); expression.addFunction("difference", lv -> { - final int size = lv.size(); + int size = lv.size(); if (size == 0) { return Value.NULL; } Value accumulator = lv.get(0); - for (final Value v : lv.subList(1, size)) + for (Value v : lv.subList(1, size)) { accumulator = accumulator.subtract(v); } @@ -75,13 +75,13 @@ public static void apply(final Expression expression) expression.addBinaryOperator("*", precedence.get("multiplication*/%"), true, Value::multiply); expression.addFunction("product", lv -> { - final int size = lv.size(); + int size = lv.size(); if (size == 0) { return Value.NULL; } Value accumulator = lv.get(0); - for (final Value v : lv.subList(1, size)) + for (Value v : lv.subList(1, size)) { accumulator = accumulator.multiply(v); } @@ -91,13 +91,13 @@ public static void apply(final Expression expression) expression.addBinaryOperator("/", precedence.get("multiplication*/%"), true, Value::divide); expression.addFunction("quotient", lv -> { - final int size = lv.size(); + int size = lv.size(); if (size == 0) { return Value.NULL; } Value accumulator = lv.get(0); - for (final Value v : lv.subList(1, size)) + for (Value v : lv.subList(1, size)) { accumulator = accumulator.divide(v); } @@ -111,13 +111,13 @@ public static void apply(final Expression expression) new NumericValue(java.lang.Math.pow(NumericValue.asNumber(v1).getDouble(), NumericValue.asNumber(v2).getDouble()))); expression.addFunction("bitwise_and", lv -> { - final int size = lv.size(); + int size = lv.size(); if (size == 0) { return Value.NULL; } long accumulator = NumericValue.asNumber(lv.get(0)).getLong(); - for (final Value v : lv.subList(1, size)) + for (Value v : lv.subList(1, size)) { accumulator = accumulator & NumericValue.asNumber(v).getLong(); } @@ -125,13 +125,13 @@ public static void apply(final Expression expression) }); expression.addFunction("bitwise_xor", lv -> { - final int size = lv.size(); + int size = lv.size(); if (size == 0) { return Value.NULL; } long accumulator = NumericValue.asNumber(lv.get(0)).getLong(); - for (final Value v : lv.subList(1, size)) + for (Value v : lv.subList(1, size)) { accumulator = accumulator ^ NumericValue.asNumber(v).getLong(); } @@ -139,13 +139,13 @@ public static void apply(final Expression expression) }); expression.addFunction("bitwise_or", lv -> { - final int size = lv.size(); + int size = lv.size(); if (size == 0) { return Value.NULL; } long accumulator = NumericValue.asNumber(lv.get(0)).getLong(); - for (final Value v : lv.subList(1, size)) + for (Value v : lv.subList(1, size)) { accumulator = accumulator | NumericValue.asNumber(v).getLong(); } @@ -155,22 +155,22 @@ public static void apply(final Expression expression) // lazy cause RHS is only conditional expression.addLazyBinaryOperator("&&", precedence.get("and&&"), false, true, t -> Context.Type.BOOLEAN, (c, t, lv1, lv2) -> { // todo check how is optimizations going - final Value v1 = lv1.evalValue(c, Context.BOOLEAN); + Value v1 = lv1.evalValue(c, Context.BOOLEAN); return v1.getBoolean() ? lv2 : ((cc, tt) -> v1); }); expression.addPureLazyFunction("and", -1, t -> Context.Type.BOOLEAN, (c, t, lv) -> { - final int last = lv.size() - 1; + int last = lv.size() - 1; if (last == -1) { return LazyValue.TRUE; } - for (final LazyValue l : lv.subList(0, last)) + for (LazyValue l : lv.subList(0, last)) { - final Value val = l.evalValue(c, Context.Type.BOOLEAN); + Value val = l.evalValue(c, Context.Type.BOOLEAN); if (val instanceof final FunctionUnpackedArgumentsValue fuav) { - for (final Value it : fuav) + for (Value it : fuav) { if (!it.getBoolean()) { @@ -193,22 +193,22 @@ public static void apply(final Expression expression) // lazy cause RHS is only conditional expression.addLazyBinaryOperator("||", precedence.get("or||"), false, true, t -> Context.Type.BOOLEAN, (c, t, lv1, lv2) -> { - final Value v1 = lv1.evalValue(c, Context.BOOLEAN); + Value v1 = lv1.evalValue(c, Context.BOOLEAN); return v1.getBoolean() ? ((cc, tt) -> v1) : lv2; }); expression.addPureLazyFunction("or", -1, t -> Context.Type.BOOLEAN, (c, t, lv) -> { - final int last = lv.size() - 1; + int last = lv.size() - 1; if (last == -1) { return LazyValue.FALSE; } - for (final LazyValue l : lv.subList(0, last)) + for (LazyValue l : lv.subList(0, last)) { - final Value val = l.evalValue(c, Context.Type.BOOLEAN); + Value val = l.evalValue(c, Context.Type.BOOLEAN); if (val instanceof final FunctionUnpackedArgumentsValue fuav) { - for (final Value it : fuav) + for (Value it : fuav) { if (it.getBoolean()) { @@ -233,13 +233,13 @@ public static void apply(final Expression expression) expression.addBinaryOperator(">", precedence.get("compare>=><=<"), false, (v1, v2) -> BooleanValue.of(v1.compareTo(v2) > 0)); expression.addFunction("decreasing", lv -> { - final int size = lv.size(); + int size = lv.size(); if (size < 2) { return Value.TRUE; } Value prev = lv.get(0); - for (final Value next : lv.subList(1, size)) + for (Value next : lv.subList(1, size)) { if (prev.compareTo(next) <= 0) { @@ -254,13 +254,13 @@ public static void apply(final Expression expression) expression.addBinaryOperator(">=", precedence.get("compare>=><=<"), false, (v1, v2) -> BooleanValue.of(v1.compareTo(v2) >= 0)); expression.addFunction("nonincreasing", lv -> { - final int size = lv.size(); + int size = lv.size(); if (size < 2) { return Value.TRUE; } Value prev = lv.get(0); - for (final Value next : lv.subList(1, size)) + for (Value next : lv.subList(1, size)) { if (prev.compareTo(next) < 0) { @@ -275,13 +275,13 @@ public static void apply(final Expression expression) expression.addBinaryOperator("<", precedence.get("compare>=><=<"), false, (v1, v2) -> BooleanValue.of(v1.compareTo(v2) < 0)); expression.addFunction("increasing", lv -> { - final int size = lv.size(); + int size = lv.size(); if (size < 2) { return Value.TRUE; } Value prev = lv.get(0); - for (final Value next : lv.subList(1, size)) + for (Value next : lv.subList(1, size)) { if (prev.compareTo(next) >= 0) { @@ -296,13 +296,13 @@ public static void apply(final Expression expression) expression.addBinaryOperator("<=", precedence.get("compare>=><=<"), false, (v1, v2) -> BooleanValue.of(v1.compareTo(v2) <= 0)); expression.addFunction("nondecreasing", lv -> { - final int size = lv.size(); + int size = lv.size(); if (size < 2) { return Value.TRUE; } Value prev = lv.get(0); - for (final Value next : lv.subList(1, size)) + for (Value next : lv.subList(1, size)) { if (prev.compareTo(next) > 0) { @@ -316,21 +316,21 @@ public static void apply(final Expression expression) expression.addMathematicalBinaryIntFunction("bitwise_shift_left", (num, amount) -> num << amount); expression.addMathematicalBinaryIntFunction("bitwise_shift_right", (num, amount) -> num >> amount); expression.addMathematicalBinaryIntFunction("bitwise_roll_left", (num, num2) -> { - final long amount = num2 % 64; - final long amountToRoll = 64 - amount; - final long rolledBits = ((-1L) >> amountToRoll) << amountToRoll; - final long rolledAmount = (num & rolledBits) >> amountToRoll; + long amount = num2 % 64; + long amountToRoll = 64 - amount; + long rolledBits = ((-1L) >> amountToRoll) << amountToRoll; + long rolledAmount = (num & rolledBits) >> amountToRoll; return num << amount | rolledAmount; }); expression.addMathematicalBinaryIntFunction("bitwise_roll_right", (num, num2) -> { - final long amount = num2 % 64; - final long amountToRoll = 64 - amount; - final long rolledBits = ((-1L) << amountToRoll) >> amountToRoll; - final long rolledAmount = (num & rolledBits) << amountToRoll; + long amount = num2 % 64; + long amountToRoll = 64 - amount; + long rolledBits = ((-1L) << amountToRoll) >> amountToRoll; + long rolledAmount = (num & rolledBits) << amountToRoll; return num >> amount | rolledAmount; }); expression.addMathematicalUnaryIntFunction("bitwise_not", d -> { - final long num = (long) d; + long num = (long) d; return ~num; }); expression.addMathematicalUnaryIntFunction("bitwise_popcount", d -> (long) Long.bitCount((long)d)); @@ -340,13 +340,13 @@ public static void apply(final Expression expression) expression.addBinaryOperator("==", precedence.get("equal==!="), false, (v1, v2) -> v1.equals(v2) ? Value.TRUE : Value.FALSE); expression.addFunction("equal", lv -> { - final int size = lv.size(); + int size = lv.size(); if (size < 2) { return Value.TRUE; } Value prev = lv.get(0); - for (final Value next : lv.subList(1, size)) + for (Value next : lv.subList(1, size)) { if (!prev.equals(next)) { @@ -360,7 +360,7 @@ public static void apply(final Expression expression) expression.addBinaryOperator("!=", precedence.get("equal==!="), false, (v1, v2) -> v1.equals(v2) ? Value.FALSE : Value.TRUE); expression.addFunction("unique", lv -> { - final int size = lv.size(); + int size = lv.size(); if (size < 2) { return Value.TRUE; @@ -368,7 +368,7 @@ public static void apply(final Expression expression) // need to order them so same obejects will be next to each other. lv.sort(Comparator.comparingInt(Value::hashCode)); Value prev = lv.get(0); - for (final Value next : lv.subList(1, size)) + for (Value next : lv.subList(1, size)) { if (prev.equals(next)) { @@ -383,12 +383,12 @@ public static void apply(final Expression expression) // lazy cause of assignment which is non-trivial expression.addLazyBinaryOperator("=", precedence.get("assign=<>"), false, false, t -> Context.Type.LVALUE, (c, t, lv1, lv2) -> { - final Value v1 = lv1.evalValue(c, Context.LVALUE); - final Value v2 = lv2.evalValue(c); + Value v1 = lv1.evalValue(c, Context.LVALUE); + Value v2 = lv2.evalValue(c); if (v1 instanceof final ListValue.ListConstructorValue lcv && v2 instanceof final ListValue list) { - final List ll = lcv.getItems(); - final List rl = list.getItems(); + List ll = lcv.getItems(); + List rl = list.getItems(); if (ll.size() < rl.size()) { throw new InternalExpressionException("Too many values to unpack"); @@ -397,28 +397,28 @@ public static void apply(final Expression expression) { throw new InternalExpressionException("Too few values to unpack"); } - for (final Value v : ll) + for (Value v : ll) { v.assertAssignable(); } - final Iterator li = ll.iterator(); - final Iterator ri = rl.iterator(); + Iterator li = ll.iterator(); + Iterator ri = rl.iterator(); while (li.hasNext()) { - final String lname = li.next().getVariable(); - final Value vval = ri.next().reboundedTo(lname); + String lname = li.next().getVariable(); + Value vval = ri.next().reboundedTo(lname); expression.setAnyVariable(c, lname, (cc, tt) -> vval); } return (cc, tt) -> Value.TRUE; } if (v1 instanceof final LContainerValue lcv) { - final ContainerValueInterface container = lcv.container(); + ContainerValueInterface container = lcv.container(); if (container == null) { return (cc, tt) -> Value.NULL; } - final Value address = lcv.address(); + Value address = lcv.address(); if (!(container.put(address, v2))) { return (cc, tt) -> Value.NULL; @@ -426,9 +426,9 @@ public static void apply(final Expression expression) return (cc, tt) -> v2; } v1.assertAssignable(); - final String varname = v1.getVariable(); - final Value copy = v2.reboundedTo(varname); - final LazyValue boundedLHS = (cc, tt) -> copy; + String varname = v1.getVariable(); + Value copy = v2.reboundedTo(varname); + LazyValue boundedLHS = (cc, tt) -> copy; expression.setAnyVariable(c, varname, boundedLHS); return boundedLHS; }); @@ -436,12 +436,12 @@ public static void apply(final Expression expression) // lazy due to assignment expression.addLazyBinaryOperator("+=", precedence.get("assign=<>"), false, false, t -> Context.Type.LVALUE, (c, t, lv1, lv2) -> { - final Value v1 = lv1.evalValue(c, Context.LVALUE); - final Value v2 = lv2.evalValue(c); + Value v1 = lv1.evalValue(c, Context.LVALUE); + Value v2 = lv2.evalValue(c); if (v1 instanceof final ListValue.ListConstructorValue lcv && v2 instanceof final ListValue list) { - final List ll = lcv.getItems(); - final List rl = list.getItems(); + List ll = lcv.getItems(); + List rl = list.getItems(); if (ll.size() < rl.size()) { throw new InternalExpressionException("Too many values to unpack"); @@ -450,30 +450,30 @@ public static void apply(final Expression expression) { throw new InternalExpressionException("Too few values to unpack"); } - for (final Value v : ll) + for (Value v : ll) { v.assertAssignable(); } - final Iterator li = ll.iterator(); - final Iterator ri = rl.iterator(); + Iterator li = ll.iterator(); + Iterator ri = rl.iterator(); while (li.hasNext()) { - final Value lval = li.next(); - final String lname = lval.getVariable(); - final Value result = lval.add(ri.next()).bindTo(lname); + Value lval = li.next(); + String lname = lval.getVariable(); + Value result = lval.add(ri.next()).bindTo(lname); expression.setAnyVariable(c, lname, (cc, tt) -> result); } return (cc, tt) -> Value.TRUE; } if (v1 instanceof final LContainerValue lcv) { - final ContainerValueInterface cvi = lcv.container(); + ContainerValueInterface cvi = lcv.container(); if (cvi == null) { throw new InternalExpressionException("Failed to resolve left hand side of the += operation"); } - final Value key = lcv.address(); - final Value value = cvi.get(key); + Value key = lcv.address(); + Value value = cvi.get(key); if (value instanceof ListValue || value instanceof MapValue) { ((AbstractListValue) value).append(v2); @@ -481,14 +481,14 @@ public static void apply(final Expression expression) } else { - final Value res = value.add(v2); + Value res = value.add(v2); cvi.put(key, res); return (cc, tt) -> res; } } v1.assertAssignable(); - final String varname = v1.getVariable(); - final LazyValue boundedLHS; + String varname = v1.getVariable(); + LazyValue boundedLHS; if (v1 instanceof ListValue || v1 instanceof MapValue) { ((AbstractListValue) v1).append(v2); @@ -496,7 +496,7 @@ public static void apply(final Expression expression) } else { - final Value result = v1.add(v2).bindTo(varname); + Value result = v1.add(v2).bindTo(varname); boundedLHS = (cc, tt) -> result; } expression.setAnyVariable(c, varname, boundedLHS); @@ -507,8 +507,8 @@ public static void apply(final Expression expression) { if (v1 instanceof final ListValue.ListConstructorValue lcv1 && v2 instanceof final ListValue.ListConstructorValue lcv2) { - final List ll = lcv1.getItems(); - final List rl = lcv2.getItems(); + List ll = lcv1.getItems(); + List rl = lcv2.getItems(); if (ll.size() < rl.size()) { throw new InternalExpressionException("Too many values to unpack"); @@ -517,22 +517,22 @@ public static void apply(final Expression expression) { throw new InternalExpressionException("Too few values to unpack"); } - for (final Value v : ll) + for (Value v : ll) { v.assertAssignable(); } - for (final Value v : rl) + for (Value v : rl) { v.assertAssignable(); } - final Iterator li = ll.iterator(); - final Iterator ri = rl.iterator(); + Iterator li = ll.iterator(); + Iterator ri = rl.iterator(); while (li.hasNext()) { - final Value lval = li.next(); - final Value rval = ri.next(); - final String lname = lval.getVariable(); - final String rname = rval.getVariable(); + Value lval = li.next(); + Value rval = ri.next(); + String lname = lval.getVariable(); + String rname = rval.getVariable(); lval.reboundedTo(rname); rval.reboundedTo(lname); expression.setAnyVariable(c, lname, (cc, tt) -> rval); @@ -542,10 +542,10 @@ public static void apply(final Expression expression) } v1.assertAssignable(); v2.assertAssignable(); - final String lvalvar = v1.getVariable(); - final String rvalvar = v2.getVariable(); - final Value lval = v2.reboundedTo(lvalvar); - final Value rval = v1.reboundedTo(rvalvar); + String lvalvar = v1.getVariable(); + String rvalvar = v2.getVariable(); + Value lval = v2.reboundedTo(lvalvar); + Value rval = v1.reboundedTo(rvalvar); expression.setAnyVariable(c, lvalvar, (cc, tt) -> lval); expression.setAnyVariable(c, rvalvar, (cc, tt) -> rval); return lval; @@ -571,7 +571,7 @@ public static void apply(final Expression expression) { throw new InternalExpressionException("Unable to unpack a non-list"); } - final FunctionUnpackedArgumentsValue fuaval = new FunctionUnpackedArgumentsValue(alv.unpack()); + FunctionUnpackedArgumentsValue fuaval = new FunctionUnpackedArgumentsValue(alv.unpack()); return (cc, tt) -> fuaval; }); diff --git a/src/main/java/carpet/script/language/Sys.java b/src/main/java/carpet/script/language/Sys.java index 475aac724b..01f455288d 100644 --- a/src/main/java/carpet/script/language/Sys.java +++ b/src/main/java/carpet/script/language/Sys.java @@ -13,7 +13,6 @@ import carpet.script.value.NumericValue; import carpet.script.value.StringValue; import carpet.script.value.Value; -import org.apache.commons.lang3.text.WordUtils; import java.util.ArrayList; import java.util.Calendar; @@ -32,7 +31,7 @@ public class Sys // %[argument_index$][flags][width][.precision][t]conversion private static final Pattern formatPattern = Pattern.compile("%(\\d+\\$)?([-#+ 0,(<]*)?(\\d+)?(\\.\\d+)?([tT])?([a-zA-Z%])"); - public static void apply(final Expression expression) + public static void apply(Expression expression) { expression.addUnaryFunction("hash_code", v -> new NumericValue(v.hashCode())); @@ -40,10 +39,10 @@ public static void apply(final Expression expression) expression.addTypedContextFunction("bool", 1, Context.BOOLEAN, (c, t, lv) -> { - final Value v = lv.get(0); + Value v = lv.get(0); if (v instanceof StringValue) { - final String str = v.getString().toLowerCase(Locale.ROOT); + String str = v.getString().toLowerCase(Locale.ROOT); if ("false".equals(str) || "null".equals(str)) { return Value.FALSE; @@ -66,7 +65,7 @@ public static void apply(final Expression expression) { return new NumericValue(v.getString()); } - catch (final NumberFormatException format) + catch (NumberFormatException format) { return Value.NULL; } @@ -74,11 +73,11 @@ public static void apply(final Expression expression) expression.addFunction("str", lv -> { - if (lv.size() == 0) + if (lv.isEmpty()) { throw new InternalExpressionException("'str' requires at least one argument"); } - final String format = lv.get(0).getString(); + String format = lv.get(0).getString(); if (lv.size() == 1) { return new StringValue(format); @@ -89,8 +88,8 @@ public static void apply(final Expression expression) lv = list.getItems(); argIndex = 0; } - final List args = new ArrayList<>(); - final Matcher m = formatPattern.matcher(format); + List args = new ArrayList<>(); + Matcher m = formatPattern.matcher(format); for (int i = 0, len = format.length(); i < len; ) { @@ -100,7 +99,7 @@ public static void apply(final Expression expression) // of the format specifier is either fixed text or contains // an invalid format string. // [[scarpet]] but we skip it and let the String.format fail - final char fmt = m.group(6).toLowerCase().charAt(0); + char fmt = m.group(6).toLowerCase().charAt(0); if (fmt == 's') { if (argIndex >= lv.size()) @@ -137,11 +136,7 @@ else if (fmt == 'b') args.add(lv.get(argIndex).getBoolean()); argIndex++; } - else if (fmt == '%') - { - //skip /%% - } - else + else if (fmt != '%') { throw new InternalExpressionException("Format not supported: " + m.group(6)); } @@ -160,7 +155,7 @@ else if (fmt == '%') { return new StringValue(String.format(Locale.ROOT, format, args.toArray())); } - catch (final IllegalFormatException ife) + catch (IllegalFormatException ife) { throw new InternalExpressionException("Illegal string format: " + ife.getMessage()); } @@ -170,16 +165,16 @@ else if (fmt == '%') expression.addUnaryFunction("upper", v -> new StringValue(v.getString().toUpperCase(Locale.ROOT))); - expression.addUnaryFunction("title", v -> new StringValue(WordUtils.capitalizeFully(v.getString()))); + expression.addUnaryFunction("title", v -> new StringValue(titleCase(v.getString()))); - expression.addFunction("replace", (lv) -> + expression.addFunction("replace", lv -> { if (lv.size() != 3 && lv.size() != 2) { throw new InternalExpressionException("'replace' expects string to read, pattern regex, and optional replacement string"); } - final String data = lv.get(0).getString(); - final String regex = lv.get(1).getString(); + String data = lv.get(0).getString(); + String regex = lv.get(1).getString(); String replacement = ""; if (lv.size() == 3) { @@ -189,20 +184,20 @@ else if (fmt == '%') { return new StringValue(data.replaceAll(regex, replacement)); } - catch (final PatternSyntaxException pse) + catch (PatternSyntaxException pse) { throw new InternalExpressionException("Incorrect pattern for 'replace': " + pse.getMessage()); } }); - expression.addFunction("replace_first", (lv) -> + expression.addFunction("replace_first", lv -> { if (lv.size() != 3 && lv.size() != 2) { throw new InternalExpressionException("'replace_first' expects string to read, pattern regex, and optional replacement string"); } - final String data = lv.get(0).getString(); - final String regex = lv.get(1).getString(); + String data = lv.get(0).getString(); + String regex = lv.get(1).getString(); String replacement = ""; if (lv.size() == 3) { @@ -215,7 +210,7 @@ else if (fmt == '%') expression.addUnaryFunction("length", v -> new NumericValue(v.length())); expression.addContextFunction("rand", -1, (c, t, lv) -> { - final int argsize = lv.size(); + int argsize = lv.size(); Random randomizer = Sys.randomizer; if (argsize != 1 && argsize != 2) { @@ -225,24 +220,24 @@ else if (fmt == '%') { randomizer = c.host.getRandom(NumericValue.asNumber(lv.get(1)).getLong()); } - final Value argument = lv.get(0); + Value argument = lv.get(0); if (argument instanceof final ListValue listValue) { - final List list = listValue.getItems(); + List list = listValue.getItems(); return list.get(randomizer.nextInt(list.size())); } - final double value = NumericValue.asNumber(argument).getDouble() * randomizer.nextDouble(); + double value = NumericValue.asNumber(argument).getDouble() * randomizer.nextDouble(); return t == Context.BOOLEAN ? BooleanValue.of(value >= 1.0D) : new NumericValue(value); }); expression.addContextFunction("reset_seed", 1, (c, t, lv) -> { - final boolean gotIt = c.host.resetRandom(NumericValue.asNumber(lv.get(0)).getLong()); + boolean gotIt = c.host.resetRandom(NumericValue.asNumber(lv.get(0)).getLong()); return BooleanValue.of(gotIt); }); expression.addFunction("perlin", lv -> { - final PerlinNoiseSampler sampler; - final Value x; + PerlinNoiseSampler sampler; + Value x; Value y; Value z; @@ -258,7 +253,7 @@ else if (fmt == '%') sampler = PerlinNoiseSampler.instance; y = Value.NULL; z = Value.NULL; - if (lv.size() == 0) + if (lv.isEmpty()) { throw new InternalExpressionException("'perlin' requires at least one dimension to sample from"); } @@ -273,7 +268,7 @@ else if (fmt == '%') } } - final double result; + double result; if (z.isNull()) { @@ -293,9 +288,9 @@ else if (fmt == '%') expression.addFunction("simplex", lv -> { - final SimplexNoiseSampler sampler; - final Value x; - final Value y; + SimplexNoiseSampler sampler; + Value x; + Value y; Value z; if (lv.size() >= 4) @@ -320,7 +315,7 @@ else if (fmt == '%') z = NumericValue.asNumber(lv.get(2)); } } - final double result; + double result; if (z.isNull()) { @@ -336,7 +331,7 @@ else if (fmt == '%') return new NumericValue(result); }); - expression.addUnaryFunction("print", (v) -> + expression.addUnaryFunction("print", v -> { System.out.println(v.getString()); return v; // pass through for variables @@ -351,14 +346,14 @@ else if (fmt == '%') expression.addFunction("convert_date", lv -> { int argsize = lv.size(); - if (lv.size() == 0) + if (lv.isEmpty()) { throw new InternalExpressionException("'convert_date' requires at least one parameter"); } - final Value value = lv.get(0); + Value value = lv.get(0); if (argsize == 1 && !(value instanceof ListValue)) { - final Calendar cal = new GregorianCalendar(Locale.ROOT); + Calendar cal = new GregorianCalendar(Locale.ROOT); cal.setTimeInMillis(NumericValue.asNumber(value, "timestamp").getLong()); int weekday = cal.get(Calendar.DAY_OF_WEEK) - 1; if (weekday == 0) @@ -382,7 +377,7 @@ else if (value instanceof final ListValue list) lv = list.getItems(); argsize = lv.size(); } - final Calendar cal = new GregorianCalendar(0, 0, 0, 0, 0, 0); + Calendar cal = new GregorianCalendar(0, Calendar.JANUARY, 1, 0, 0, 0); if (argsize == 3) { @@ -413,15 +408,15 @@ else if (argsize == 6) // lazy cause evaluates expression multiple times expression.addLazyFunction("profile_expr", 1, (c, t, lv) -> { - final LazyValue lazy = lv.get(0); - final long end = System.nanoTime() + 50000000L; + LazyValue lazy = lv.get(0); + long end = System.nanoTime() + 50000000L; long it = 0; while (System.nanoTime() < end) { lazy.evalValue(c); it++; } - final Value res = new NumericValue(it); + Value res = new NumericValue(it); return (cc, tt) -> res; }); @@ -430,14 +425,14 @@ else if (argsize == 6) expression.addContextFunction("undef", 1, (c, t, lv) -> { - final Value remove = lv.get(0); + Value remove = lv.get(0); if (remove instanceof FunctionValue) { c.host.delFunction(expression.module, remove.getString()); return Value.NULL; } String varname = remove.getString(); - final boolean isPrefix = varname.endsWith("*"); + boolean isPrefix = varname.endsWith("*"); if (isPrefix) { varname = varname.replaceAll("\\*+$", ""); @@ -472,11 +467,11 @@ else if (!varname.startsWith("_")) //deprecate expression.addContextFunction("vars", 1, (c, t, lv) -> { - final String prefix = lv.get(0).getString(); - final List values = new ArrayList<>(); + String prefix = lv.get(0).getString(); + List values = new ArrayList<>(); if (prefix.startsWith("global")) { - c.host.globalVariableNames(expression.module, (s) -> s.startsWith(prefix)).forEach(s -> values.add(new StringValue(s))); + c.host.globalVariableNames(expression.module, s -> s.startsWith(prefix)).forEach(s -> values.add(new StringValue(s))); } else { @@ -488,23 +483,43 @@ else if (!varname.startsWith("_")) // lazy cause default expression may not be executed if not needed expression.addLazyFunction("system_variable_get", (c, t, lv) -> { - if (lv.size() == 0) + if (lv.isEmpty()) { throw new InternalExpressionException("'system_variable_get' expects at least a key to be fetched"); } - final Value key = lv.get(0).evalValue(c); + Value key = lv.get(0).evalValue(c); if (lv.size() > 1) { c.host.scriptServer().systemGlobals.computeIfAbsent(key, k -> lv.get(1).evalValue(c)); } - final Value res = c.host.scriptServer().systemGlobals.get(key); + Value res = c.host.scriptServer().systemGlobals.get(key); return res == null ? LazyValue.NULL : ((cc, tt) -> res); }); expression.addContextFunction("system_variable_set", 2, (c, t, lv) -> { - final Value res = c.host.scriptServer().systemGlobals.put(lv.get(0), lv.get(1)); + Value res = c.host.scriptServer().systemGlobals.put(lv.get(0), lv.get(1)); return res == null ? Value.NULL : res; }); } + + public static String titleCase(String str) { + if (str.isEmpty()) { + return str; + } + str = str.toLowerCase(); + char[] buffer = str.toCharArray(); + boolean capitalizeNext = true; + for (int i = 0; i < buffer.length; i++) { + char ch = buffer[i]; + if (Character.isWhitespace(ch)) { + capitalizeNext = true; + } else if (capitalizeNext) { + buffer[i] = Character.toTitleCase(ch); + capitalizeNext = false; + } + } + return new String(buffer); + } + } diff --git a/src/main/java/carpet/script/language/Threading.java b/src/main/java/carpet/script/language/Threading.java index b61448d67b..a6f4a0a73d 100644 --- a/src/main/java/carpet/script/language/Threading.java +++ b/src/main/java/carpet/script/language/Threading.java @@ -11,16 +11,16 @@ public class Threading { - public static void apply(final Expression expression) + public static void apply(Expression expression) { expression.addFunctionWithDelegation("task", -1, false, false, (c, t, expr, tok, lv) -> { - if (lv.size() == 0) + if (lv.isEmpty()) { throw new InternalExpressionException("'task' requires at least function to call as a parameter"); } - final FunctionArgument functionArgument = FunctionArgument.findIn(c, expression.module, lv, 0, false, true); - final ThreadValue thread = new ThreadValue(Value.NULL, functionArgument.function, expr, tok, c, functionArgument.checkedArgs()); + FunctionArgument functionArgument = FunctionArgument.findIn(c, expression.module, lv, 0, false, true); + ThreadValue thread = new ThreadValue(Value.NULL, functionArgument.function, expr, tok, c, functionArgument.checkedArgs()); Thread.yield(); return thread; }); @@ -31,18 +31,18 @@ public static void apply(final Expression expression) { throw new InternalExpressionException("'task' requires at least function to call as a parameter"); } - final Value queue = lv.get(0); - final FunctionArgument functionArgument = FunctionArgument.findIn(c, expression.module, lv, 1, false, true); - final ThreadValue thread = new ThreadValue(queue, functionArgument.function, expr, tok, c, functionArgument.checkedArgs()); + Value queue = lv.get(0); + FunctionArgument functionArgument = FunctionArgument.findIn(c, expression.module, lv, 1, false, true); + ThreadValue thread = new ThreadValue(queue, functionArgument.function, expr, tok, c, functionArgument.checkedArgs()); Thread.yield(); return thread; }); expression.addContextFunction("task_count", -1, (c, t, lv) -> - (lv.size() > 0) ? new NumericValue(c.host.taskCount(lv.get(0))) : new NumericValue(c.host.taskCount())); + (!lv.isEmpty()) ? new NumericValue(c.host.taskCount(lv.get(0))) : new NumericValue(c.host.taskCount())); - expression.addUnaryFunction("task_value", (v) -> + expression.addUnaryFunction("task_value", v -> { if (!(v instanceof final ThreadValue tv)) { @@ -51,7 +51,7 @@ public static void apply(final Expression expression) return tv.getValue(); }); - expression.addUnaryFunction("task_join", (v) -> + expression.addUnaryFunction("task_join", v -> { if (!(v instanceof final ThreadValue tv)) { @@ -61,13 +61,12 @@ public static void apply(final Expression expression) }); expression.addLazyFunction("task_dock", 1, (c, t, lv) -> - { // pass through placeholder // implmenetation should dock the task on the main thread. - return lv.get(0); - }); + lv.get(0) + ); - expression.addUnaryFunction("task_completed", (v) -> + expression.addUnaryFunction("task_completed", v -> { if (!(v instanceof final ThreadValue tv)) { @@ -79,7 +78,7 @@ public static void apply(final Expression expression) // lazy cause expr is evaluated in the same type expression.addLazyFunction("synchronize", (c, t, lv) -> { - if (lv.size() == 0) + if (lv.isEmpty()) { throw new InternalExpressionException("'synchronize' require at least an expression to synchronize"); } @@ -92,15 +91,15 @@ public static void apply(final Expression expression) } synchronized (c.host.getLock(lockValue)) { - final Value ret = lv.get(ind).evalValue(c, t); - return (_c, _t) -> ret; + Value ret = lv.get(ind).evalValue(c, t); + return (ct, tt) -> ret; } }); // lazy since exception expression is very conditional expression.addLazyFunction("sleep", (c, t, lv) -> { - final long time = lv.isEmpty() ? 0L : NumericValue.asNumber(lv.get(0).evalValue(c)).getLong(); + long time = lv.isEmpty() ? 0L : NumericValue.asNumber(lv.get(0).evalValue(c)).getLong(); boolean interrupted = false; try { @@ -114,7 +113,7 @@ public static void apply(final Expression expression) } Thread.yield(); } - catch (final InterruptedException ignored) + catch (InterruptedException ignored) { interrupted = true; } diff --git a/src/main/java/carpet/script/utils/AppStoreManager.java b/src/main/java/carpet/script/utils/AppStoreManager.java index ab5b0bf0a7..9a5f387884 100644 --- a/src/main/java/carpet/script/utils/AppStoreManager.java +++ b/src/main/java/carpet/script/utils/AppStoreManager.java @@ -52,7 +52,7 @@ public class AppStoreManager */ private static String scarpetRepoLink = "https://api.github.com/repos/gnembon/scarpet/contents/programs/"; - public static void setScarpetRepoLink(@Nullable final String link) + public static void setScarpetRepoLink(@Nullable String link) { APP_STORE_ROOT = AppStoreManager.StoreNode.folder(null, ""); scarpetRepoLink = link; @@ -66,23 +66,24 @@ private record AppInfo(String name, String url, StoreNode source) public static class StoreNode { public String name; + @Nullable public StoreNode parent; public Map children; public boolean sealed; public String value; - public static StoreNode folder(final StoreNode parent, final String name) + public static StoreNode folder(@Nullable StoreNode parent, String name) { - final StoreNode node = new StoreNode(parent, name); + StoreNode node = new StoreNode(parent, name); node.children = new HashMap<>(); node.value = null; node.sealed = false; return node; } - public static StoreNode scriptFile(final StoreNode parent, final String name, final String value) + public static StoreNode scriptFile(StoreNode parent, String name, String value) { - final StoreNode node = new StoreNode(parent, name); + StoreNode node = new StoreNode(parent, name); node.children = null; node.value = value; node.sealed = true; @@ -109,7 +110,7 @@ private StringBuilder createPrePath() return this == APP_STORE_ROOT ? new StringBuilder() : parent.createPrePath().append(pathElement()); } - private StoreNode(final StoreNode parent, final String name) + private StoreNode(@Nullable StoreNode parent, String name) { this.parent = parent; this.name = name; @@ -127,43 +128,40 @@ public synchronized void fillChildren() throws IOException throw new IOException("Accessing scarpet app repo is disabled"); } - final String queryPath = scarpetRepoLink + getPath(); - final String response; + String queryPath = scarpetRepoLink + getPath(); + String response; try { response = IOUtils.toString(new URL(queryPath), StandardCharsets.UTF_8); } - catch (final IOException e) + catch (IOException e) { // Not sealing to allow retrying throw new IOException("Problems fetching " + queryPath, e); } - final JsonArray files = JsonParser.parseString(response).getAsJsonArray(); - for (final JsonElement je : files) + JsonArray files = JsonParser.parseString(response).getAsJsonArray(); + for (JsonElement je : files) { - final JsonObject jo = je.getAsJsonObject(); - final String name = jo.get("name").getAsString(); + JsonObject jo = je.getAsJsonObject(); + String elementName = jo.get("name").getAsString(); if (jo.get("type").getAsString().equals("dir")) { - children.put(name, folder(this, name)); + children.put(elementName, folder(this, elementName)); } else// if (name.matches("(\\w+\\.scl?)")) { - final String value = jo.get("download_url").getAsString(); - children.put(name, scriptFile(this, name, value)); + String url = jo.get("download_url").getAsString(); + children.put(elementName, scriptFile(this, elementName, url)); } } sealed = true; } /** - * Returns true if doing down the directory structire cannot continue since the matching element is either a leaf or + * Returns true if doing down the directory structure cannot continue since the matching element is either a leaf or * a string not matching of any node. - * - * @param pathElement - * @return */ - public boolean cannotContinueFor(final String pathElement) throws IOException + public boolean cannotContinueFor(String pathElement) throws IOException { if (isLeaf()) { @@ -180,14 +178,13 @@ public List createPathSuggestions() throws IOException return name.endsWith(".sc") ? Collections.singletonList(getPath()) : Collections.emptyList(); } fillChildren(); - final String prefix = getPath(); + String prefix = getPath(); return children.values().stream(). filter(n -> (!n.isLeaf() || n.name.endsWith(".sc"))). - map(s -> prefix + s.pathElement().replaceAll("/$", "")). - collect(Collectors.toList()); + map(s -> prefix + s.pathElement().replaceAll("/$", "")).toList(); } - public StoreNode drillDown(final String pathElement) throws IOException + public StoreNode drillDown(String pathElement) throws IOException { if (isLeaf()) { @@ -201,9 +198,9 @@ public StoreNode drillDown(final String pathElement) throws IOException return children.get(pathElement); } - public String getValue(final String file) throws IOException + public String getValue(String file) throws IOException { - final StoreNode leaf = drillDown(file); + StoreNode leaf = drillDown(file); if (!leaf.isLeaf()) { throw new IOException(file + " is not a file"); @@ -220,11 +217,11 @@ public String getValue(final String file) throws IOException * @param currentPath The path down which we want to search for files * @return A pair of the current valid path, as well as the set of all the file/directory names at the end of that path */ - public static List suggestionsFromPath(final String currentPath) throws IOException + public static List suggestionsFromPath(String currentPath) throws IOException { - final String[] path = currentPath.split("/"); + String[] path = currentPath.split("/"); StoreNode appKiosk = APP_STORE_ROOT; - for (final String pathElement : path) + for (String pathElement : path) { if (appKiosk.cannotContinueFor(pathElement)) { @@ -232,13 +229,10 @@ public static List suggestionsFromPath(final String currentPath) throws } appKiosk = appKiosk.children.get(pathElement); } - final List filteredSuggestions = appKiosk.createPathSuggestions().stream().filter(s -> s.startsWith(currentPath)).collect(Collectors.toList()); - if (filteredSuggestions.size() == 1) + List filteredSuggestions = appKiosk.createPathSuggestions().stream().filter(s -> s.startsWith(currentPath)).toList(); + if (filteredSuggestions.size() == 1 && !appKiosk.isLeaf()) { - if (!appKiosk.isLeaf()) - { - return suggestionsFromPath(filteredSuggestions.get(0)); // Start suggesting directory contents - } + return suggestionsFromPath(filteredSuggestions.get(0)); // Start suggesting directory contents } return filteredSuggestions; } @@ -251,20 +245,20 @@ public static List suggestionsFromPath(final String currentPath) throws * @return {@code 1} if we succesfully saved the script, {@code 0} otherwise */ - public static int downloadScript(final CommandSourceStack source, final String path) + public static int downloadScript(CommandSourceStack source, String path) { - final AppInfo nodeInfo = getFileNode(path); + AppInfo nodeInfo = getFileNode(path); return downloadScript(source, path, nodeInfo, false); } - private static int downloadScript(final CommandSourceStack source, final String path, final AppInfo nodeInfo, final boolean useTrash) + private static int downloadScript(CommandSourceStack source, String path, AppInfo nodeInfo, boolean useTrash) { - final String code; + String code; try { code = IOUtils.toString(new URL(nodeInfo.url()), StandardCharsets.UTF_8); } - catch (final IOException e) + catch (IOException e) { throw new CommandRuntimeException(Carpet.Messenger_compose("rb Failed to obtain app file content: " + e.getMessage())); } @@ -272,7 +266,7 @@ private static int downloadScript(final CommandSourceStack source, final String { return 0; } - final boolean success = Vanilla.MinecraftServer_getScriptServer(source.getServer()).addScriptHost(source, nodeInfo.name().replaceFirst("\\.sc$", ""), null, true, false, false, nodeInfo.source()); + boolean success = Vanilla.MinecraftServer_getScriptServer(source.getServer()).addScriptHost(source, nodeInfo.name().replaceFirst("\\.sc$", ""), null, true, false, false, nodeInfo.source()); return success ? 1 : 0; } @@ -282,35 +276,35 @@ private static int downloadScript(final CommandSourceStack source, final String * @param appPath The user inputted path to the scarpet script * @return Pair of app file name and content */ - public static AppInfo getFileNode(final String appPath) + public static AppInfo getFileNode(String appPath) { return getFileNodeFrom(APP_STORE_ROOT, appPath); } - public static AppInfo getFileNodeFrom(final StoreNode start, final String appPath) + public static AppInfo getFileNodeFrom(StoreNode start, String appPath) { - final String[] path = appPath.split("/"); + String[] path = appPath.split("/"); StoreNode appKiosk = start; try { - for (final String pathElement : Arrays.copyOfRange(path, 0, path.length - 1)) + for (String pathElement : Arrays.copyOfRange(path, 0, path.length - 1)) { appKiosk = appKiosk.drillDown(pathElement); } - final String appName = path[path.length - 1]; + String appName = path[path.length - 1]; appKiosk.getValue(appName); return new AppInfo(appName, appKiosk.getValue(appName), appKiosk); } - catch (final IOException e) + catch (IOException e) { throw new CommandRuntimeException(Carpet.Messenger_compose("rb '" + appPath + "' is not a valid path to a scarpet app: " + e.getMessage())); } } - public static boolean saveScriptToFile(final CommandSourceStack source, final String path, final String appFileName, final String code, final boolean globalSavePath, final boolean useTrash) + public static boolean saveScriptToFile(CommandSourceStack source, String path, String appFileName, String code, boolean globalSavePath, boolean useTrash) { - final Path scriptLocation; + Path scriptLocation; 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); @@ -331,8 +325,8 @@ public static boolean saveScriptToFile(final CommandSourceStack source, final St int i = 0; while (Files.exists(trashPath)) { - final String[] nameAndExtension = appFileName.split("\\."); - final String newFileName = String.format(nameAndExtension[0] + "%02d." + nameAndExtension[1], i); + String[] nameAndExtension = appFileName.split("\\."); + String newFileName = String.format(nameAndExtension[0] + "%02d." + nameAndExtension[1], i); trashPath = trashPath.getParent().resolve(newFileName); i++; } @@ -340,11 +334,11 @@ public static boolean saveScriptToFile(final CommandSourceStack source, final St } Carpet.Messenger_message(source, String.format("gi Note: replaced existing app '%s'" + (useTrash ? " (old moved to /trash folder)" : ""), appFileName)); } - final BufferedWriter writer = Files.newBufferedWriter(scriptLocation); + BufferedWriter writer = Files.newBufferedWriter(scriptLocation); writer.write(code); writer.close(); } - catch (final IOException e) + catch (IOException e) { Carpet.Messenger_message(source, "r Error while downloading app: " + e); CarpetScriptServer.LOG.warn("Error while downloading app", e); @@ -353,15 +347,15 @@ public static boolean saveScriptToFile(final CommandSourceStack source, final St return true; } - public static void writeUrlToFile(final String url, final Path destination) throws IOException + public static void writeUrlToFile(String url, Path destination) throws IOException { - try (final InputStream in = new URL(url).openStream()) + try (InputStream in = new URL(url).openStream()) { Files.copy(in, destination, StandardCopyOption.REPLACE_EXISTING); } } - private static String getFullContentUrl(final String original, final StoreNode storeSource) + private static String getFullContentUrl(String original, StoreNode storeSource) { if (original.matches("^https?://.*$")) // We've got a full url here: Just use it { @@ -374,28 +368,28 @@ private static String getFullContentUrl(final String original, final StoreNode s return getFileNodeFrom(storeSource, original).url(); // Relative path: Use download location } - public static void addResource(final CarpetScriptHost carpetScriptHost, final StoreNode storeSource, final Value resource) + public static void addResource(CarpetScriptHost carpetScriptHost, StoreNode storeSource, Value resource) { if (!(resource instanceof final MapValue map)) { throw new InternalExpressionException("This is not a valid resource map: " + resource.getString()); } - final Map resourceMap = map.getMap().entrySet().stream().collect(Collectors.toMap(e -> e.getKey().getString(), Map.Entry::getValue)); + Map resourceMap = map.getMap().entrySet().stream().collect(Collectors.toMap(e -> e.getKey().getString(), Map.Entry::getValue)); if (!resourceMap.containsKey("source")) { throw new InternalExpressionException("Missing 'source' field in resource descriptor: " + resource.getString()); } - final String source = resourceMap.get("source").getString(); - final String contentUrl = getFullContentUrl(source, storeSource); - final String target = resourceMap.computeIfAbsent("target", k -> new StringValue(contentUrl.substring(contentUrl.lastIndexOf('/') + 1))).getString(); - final boolean shared = resourceMap.getOrDefault("shared", Value.FALSE).getBoolean(); + String source = resourceMap.get("source").getString(); + String contentUrl = getFullContentUrl(source, storeSource); + String target = resourceMap.computeIfAbsent("target", k -> new StringValue(contentUrl.substring(contentUrl.lastIndexOf('/') + 1))).getString(); + boolean shared = resourceMap.getOrDefault("shared", Value.FALSE).getBoolean(); if (!carpetScriptHost.applyActionForResource(target, shared, p -> { try { writeUrlToFile(contentUrl, p); } - catch (final IOException e) + catch (IOException e) { throw new InternalExpressionException("Unable to write resource " + target + ": " + e); } @@ -414,7 +408,8 @@ public static void addResource(final CarpetScriptHost carpetScriptHost, final St * @param contentUrl The full content URL, from {@link #getFullContentUrl(String, StoreNode)} * @return A {@link StoreNode} that can be used in an app that came from the provided source */ - private static StoreNode getNewStoreNode(final StoreNode originalSource, String sourceString, final String contentUrl) + @Nullable + private static StoreNode getNewStoreNode(StoreNode originalSource, String sourceString, String contentUrl) { StoreNode next = originalSource; if (sourceString == contentUrl) // External URL (check getFullUrlContent) @@ -426,7 +421,7 @@ private static StoreNode getNewStoreNode(final StoreNode originalSource, String next = APP_STORE_ROOT; sourceString = sourceString.substring(1); } - final String[] dirs = sourceString.split("/"); + String[] dirs = sourceString.split("/"); try { for (int i = 0; i < dirs.length - 1; i++) @@ -434,23 +429,23 @@ private static StoreNode getNewStoreNode(final StoreNode originalSource, String next = next.drillDown(dirs[i]); } } - catch (final IOException e) + catch (IOException e) { return null; // Should never happen, but let's not give a potentially incorrect node just in case } return next; } - public static void addLibrary(final CarpetScriptHost carpetScriptHost, final StoreNode storeSource, final Value library) + public static void addLibrary(CarpetScriptHost carpetScriptHost, StoreNode storeSource, Value library) { if (!(library instanceof final MapValue map)) { throw new InternalExpressionException("This is not a valid library map: " + library.getString()); } - final Map libraryMap = map.getMap().entrySet().stream().collect(Collectors.toMap(e -> e.getKey().getString(), e -> e.getValue().getString())); - final String source = libraryMap.get("source"); - final String contentUrl = getFullContentUrl(source, storeSource); - final String target = libraryMap.computeIfAbsent("target", k -> contentUrl.substring(contentUrl.lastIndexOf('/') + 1)); + Map libraryMap = map.getMap().entrySet().stream().collect(Collectors.toMap(e -> e.getKey().getString(), e -> e.getValue().getString())); + String source = libraryMap.get("source"); + String contentUrl = getFullContentUrl(source, storeSource); + String target = libraryMap.computeIfAbsent("target", k -> contentUrl.substring(contentUrl.lastIndexOf('/') + 1)); if (!(contentUrl.endsWith(".sc") || contentUrl.endsWith(".scl"))) { throw new InternalExpressionException("App resource type must download a scarpet app or library."); @@ -463,7 +458,7 @@ public static void addLibrary(final CarpetScriptHost carpetScriptHost, final Sto { downloadScript(carpetScriptHost.responsibleSource, target, new AppInfo(target, contentUrl, getNewStoreNode(storeSource, source, contentUrl)), true); } - catch (final CommandRuntimeException e) + catch (CommandRuntimeException e) { throw new InternalExpressionException("Error when installing app dependencies: " + e); } diff --git a/src/main/java/carpet/script/utils/BiomeInfo.java b/src/main/java/carpet/script/utils/BiomeInfo.java index d132239826..4cd077603f 100644 --- a/src/main/java/carpet/script/utils/BiomeInfo.java +++ b/src/main/java/carpet/script/utils/BiomeInfo.java @@ -33,7 +33,7 @@ public class BiomeInfo put("humidity", (w, b) -> NumericValue.of(Vanilla.Biome_getClimateSettings(b).downfall())); put("precipitation", (w, b) -> StringValue.of(b.getPrecipitationAt(new BlockPos(0, w.getSeaLevel(), 0)).name().toLowerCase(Locale.ROOT))); put("features", (w, b) -> { - final Registry> registry = w.registryAccess().registryOrThrow(Registries.CONFIGURED_FEATURE); + Registry> registry = w.registryAccess().registryOrThrow(Registries.CONFIGURED_FEATURE); return ListValue.wrap( b.getGenerationSettings().features().stream().map(step -> ListValue.wrap(step.stream().map(cfp -> diff --git a/src/main/java/carpet/script/utils/EntityTools.java b/src/main/java/carpet/script/utils/EntityTools.java index c3a636604e..232d2b2b52 100644 --- a/src/main/java/carpet/script/utils/EntityTools.java +++ b/src/main/java/carpet/script/utils/EntityTools.java @@ -9,24 +9,22 @@ public class EntityTools { /** * Not a replacement for living entity jump() - this barely is to allow other entities that can't jump in vanilla to 'jump' - * - * @param e */ - public static void genericJump(final Entity e) + public static void genericJump(Entity e) { if (!e.isOnGround() && !e.isInWaterOrBubble() && !e.isInLava()) { return; } - final float m = e.level.getBlockState(e.blockPosition()).getBlock().getJumpFactor(); - final float g = e.level.getBlockState(new BlockPos(e.getX(), e.getBoundingBox().minY - 0.5000001D, e.getZ())).getBlock().getJumpFactor(); - final float jumpVelocityMultiplier = m == 1.0D ? g : m; - final float jumpStrength = (0.42F * jumpVelocityMultiplier); - final Vec3 vec3d = e.getDeltaMovement(); + float m = e.level.getBlockState(e.blockPosition()).getBlock().getJumpFactor(); + float g = e.level.getBlockState(new BlockPos(e.getX(), e.getBoundingBox().minY - 0.5000001D, e.getZ())).getBlock().getJumpFactor(); + float jumpVelocityMultiplier = m == 1.0D ? g : m; + float jumpStrength = (0.42F * jumpVelocityMultiplier); + Vec3 vec3d = e.getDeltaMovement(); e.setDeltaMovement(vec3d.x, jumpStrength, vec3d.z); if (e.isSprinting()) { - final float u = e.getYRot() * 0.017453292F; // yaw + float u = e.getYRot() * 0.017453292F; // yaw e.setDeltaMovement(e.getDeltaMovement().add((-Mth.sin(g) * 0.2F), 0.0D, (Mth.cos(u) * 0.2F))); } e.hasImpulse = true; diff --git a/src/main/java/carpet/script/utils/EquipmentInventory.java b/src/main/java/carpet/script/utils/EquipmentInventory.java index a4021a189f..c6d6ca0559 100644 --- a/src/main/java/carpet/script/utils/EquipmentInventory.java +++ b/src/main/java/carpet/script/utils/EquipmentInventory.java @@ -19,7 +19,7 @@ public class EquipmentInventory implements Container LivingEntity mob; - public EquipmentInventory(final LivingEntity mob) + public EquipmentInventory(LivingEntity mob) { this.mob = mob; } @@ -33,7 +33,7 @@ public int getContainerSize() @Override public boolean isEmpty() { - for (final EquipmentSlot slot : slotToSlot) + for (EquipmentSlot slot : slotToSlot) { if (!mob.getItemBySlot(slot).isEmpty()) { @@ -44,14 +44,14 @@ public boolean isEmpty() } @Override - public ItemStack getItem(final int slot) + public ItemStack getItem(int slot) { - final EquipmentSlot slotSlot; + EquipmentSlot slotSlot; try { slotSlot = slotToSlot.get(slot); } - catch (final IndexOutOfBoundsException ignored) + catch (IndexOutOfBoundsException ignored) { //going out of the index should be really exceptional return ItemStack.EMPTY; @@ -60,14 +60,14 @@ public ItemStack getItem(final int slot) } @Override - public ItemStack removeItem(final int slot, final int amount) + public ItemStack removeItem(int slot, int amount) { - final EquipmentSlot slotSlot; + EquipmentSlot slotSlot; try { slotSlot = slotToSlot.get(slot); } - catch (final IndexOutOfBoundsException ignored) + catch (IndexOutOfBoundsException ignored) { //going out of the index should be really exceptional return ItemStack.EMPTY; @@ -76,32 +76,32 @@ public ItemStack removeItem(final int slot, final int amount) } @Override - public ItemStack removeItemNoUpdate(final int slot) + public ItemStack removeItemNoUpdate(int slot) { - final EquipmentSlot slotSlot; + EquipmentSlot slotSlot; try { slotSlot = slotToSlot.get(slot); } - catch (final IndexOutOfBoundsException ignored) + catch (IndexOutOfBoundsException ignored) { //going out of the index should be really exceptional return ItemStack.EMPTY; } - final ItemStack previous = mob.getItemBySlot(slotSlot); + ItemStack previous = mob.getItemBySlot(slotSlot); mob.setItemSlot(slotSlot, ItemStack.EMPTY); return previous; } @Override - public void setItem(final int slot, final ItemStack stack) + public void setItem(int slot, ItemStack stack) { - final EquipmentSlot slotSlot; + EquipmentSlot slotSlot; try { slotSlot = slotToSlot.get(slot); } - catch (final IndexOutOfBoundsException ignored) + catch (IndexOutOfBoundsException ignored) { //going out of the index should be really exceptional return; @@ -116,7 +116,7 @@ public void setChanged() } @Override - public boolean stillValid(final Player player) + public boolean stillValid(Player player) { return false; } @@ -124,7 +124,7 @@ public boolean stillValid(final Player player) @Override public void clearContent() { - for (final EquipmentSlot slot : slotToSlot) + for (EquipmentSlot slot : slotToSlot) { mob.setItemSlot(slot, ItemStack.EMPTY); } diff --git a/src/main/java/carpet/script/utils/FeatureGenerator.java b/src/main/java/carpet/script/utils/FeatureGenerator.java index 8252489ccb..db1f11a6fa 100644 --- a/src/main/java/carpet/script/utils/FeatureGenerator.java +++ b/src/main/java/carpet/script/utils/FeatureGenerator.java @@ -68,24 +68,24 @@ public class FeatureGenerator { @Nullable - public static synchronized Boolean plop(final String featureName, final ServerLevel world, final BlockPos pos) + public static synchronized Boolean plop(String featureName, ServerLevel world, BlockPos pos) { - final Function custom = featureMap.get(featureName); + Function custom = featureMap.get(featureName); if (custom != null) { return custom.apply(world).plop(world, pos); } - final ResourceLocation id = new ResourceLocation(featureName); - final Structure structure = world.registryAccess().registryOrThrow(Registries.STRUCTURE).get(id); + ResourceLocation id = new ResourceLocation(featureName); + Structure structure = world.registryAccess().registryOrThrow(Registries.STRUCTURE).get(id); if (structure != null) { return plopAnywhere(structure, world, pos, world.getChunkSource().getGenerator(), false); } - final ConfiguredFeature configuredFeature = world.registryAccess().registryOrThrow(Registries.CONFIGURED_FEATURE).get(id); + ConfiguredFeature configuredFeature = world.registryAccess().registryOrThrow(Registries.CONFIGURED_FEATURE).get(id); if (configuredFeature != null) { - final ThreadLocal checks = Vanilla.skipGenerationChecks(world); + ThreadLocal checks = Vanilla.skipGenerationChecks(world); checks.set(true); try { @@ -96,22 +96,22 @@ public static synchronized Boolean plop(final String featureName, final ServerLe checks.set(false); } } - final Optional> structureType = world.registryAccess().registryOrThrow(Registries.STRUCTURE_TYPE).getOptional(id); + Optional> structureType = world.registryAccess().registryOrThrow(Registries.STRUCTURE_TYPE).getOptional(id); if (structureType.isPresent()) { - final Structure configuredStandard = getDefaultFeature(structureType.get(), world, pos); + Structure configuredStandard = getDefaultFeature(structureType.get(), world, pos); if (configuredStandard != null) { return plopAnywhere(configuredStandard, world, pos, world.getChunkSource().getGenerator(), false); } } - final Feature feature = world.registryAccess().registryOrThrow(Registries.FEATURE).get(id); + Feature feature = world.registryAccess().registryOrThrow(Registries.FEATURE).get(id); if (feature != null) { - final ConfiguredFeature configuredStandard = getDefaultFeature(feature, world, pos, true); + ConfiguredFeature configuredStandard = getDefaultFeature(feature, world, pos, true); if (configuredStandard != null) { - final ThreadLocal checks = Vanilla.skipGenerationChecks(world); + ThreadLocal checks = Vanilla.skipGenerationChecks(world); checks.set(true); try { @@ -126,15 +126,16 @@ public static synchronized Boolean plop(final String featureName, final ServerLe return null; } - public static Structure resolveConfiguredStructure(final String name, final ServerLevel world, final BlockPos pos) + @Nullable + public static Structure resolveConfiguredStructure(String name, ServerLevel world, BlockPos pos) { - final ResourceLocation id = new ResourceLocation(name); - final Structure configuredStructureFeature = world.registryAccess().registryOrThrow(Registries.STRUCTURE).get(id); + ResourceLocation id = new ResourceLocation(name); + Structure configuredStructureFeature = world.registryAccess().registryOrThrow(Registries.STRUCTURE).get(id); if (configuredStructureFeature != null) { return configuredStructureFeature; } - final StructureType structureFeature = world.registryAccess().registryOrThrow(Registries.STRUCTURE_TYPE).get(id); + StructureType structureFeature = world.registryAccess().registryOrThrow(Registries.STRUCTURE_TYPE).get(id); if (structureFeature == null) { return null; @@ -142,7 +143,7 @@ public static Structure resolveConfiguredStructure(final String name, final Serv return getDefaultFeature(structureFeature, world, pos); } - public static synchronized Boolean plopGrid(final Structure structureFeature, final ServerLevel world, final BlockPos pos) + public static synchronized boolean plopGrid(Structure structureFeature, ServerLevel world, BlockPos pos) { return plopAnywhere(structureFeature, world, pos, world.getChunkSource().getGenerator(), true); } @@ -153,10 +154,10 @@ private interface Thing Boolean plop(ServerLevel world, BlockPos pos); } - private static Thing simplePlop(final ConfiguredFeature feature) + private static Thing simplePlop(ConfiguredFeature feature) { return (w, p) -> { - final ThreadLocal checks = Vanilla.skipGenerationChecks(w); + ThreadLocal checks = Vanilla.skipGenerationChecks(w); checks.set(true); try { @@ -169,34 +170,34 @@ private static Thing simplePlop(final ConfiguredFeature feature) }; } - private static > Thing simplePlop(final F feature, final FC config) + private static > Thing simplePlop(F feature, FC config) { return simplePlop(new ConfiguredFeature<>(feature, config)); } - private static Thing simpleTree(final TreeConfiguration config) + private static Thing simpleTree(TreeConfiguration config) { //config.ignoreFluidCheck(); return simplePlop(new ConfiguredFeature<>(Feature.TREE, config)); } - private static Thing spawnCustomStructure(final Structure structure) + private static Thing spawnCustomStructure(Structure structure) { return setupCustomStructure(structure, false); } - private static Thing setupCustomStructure(final Structure structure, final boolean wireOnly) + private static Thing setupCustomStructure(Structure structure, boolean wireOnly) { return (w, p) -> plopAnywhere(structure, w, p, w.getChunkSource().getGenerator(), wireOnly); } - private static Structure getDefaultFeature(final StructureType structure, final ServerLevel world, final BlockPos pos) + private static Structure getDefaultFeature(StructureType structure, ServerLevel world, BlockPos pos) { // would be nice to have a way to grab structures of this type for position // TODO allow old types, like vaillage, or bastion - final Holder existingBiome = world.getBiome(pos); + Holder existingBiome = world.getBiome(pos); Structure result = null; - for (final Structure confstr : world.registryAccess().registryOrThrow(Registries.STRUCTURE).entrySet().stream(). + for (Structure confstr : world.registryAccess().registryOrThrow(Registries.STRUCTURE).entrySet().stream(). filter(cS -> cS.getValue().type() == structure).map(Map.Entry::getValue).toList()) { result = confstr; @@ -208,12 +209,12 @@ private static Structure getDefaultFeature(final StructureType structure, fin return result; } - private static ConfiguredFeature getDefaultFeature(final Feature feature, final ServerLevel world, final BlockPos pos, final boolean tryHard) + private static ConfiguredFeature getDefaultFeature(Feature feature, ServerLevel world, BlockPos pos, boolean tryHard) { - final List> configuredStepFeatures = world.getBiome(pos).value().getGenerationSettings().features(); - for (final HolderSet step : configuredStepFeatures) + List> configuredStepFeatures = world.getBiome(pos).value().getGenerationSettings().features(); + for (HolderSet step : configuredStepFeatures) { - for (final Holder provider : step) + for (Holder provider : step) { if (provider.value().feature().value().feature() == feature) { @@ -230,21 +231,22 @@ private static Structure getDefaultFeature(final StructureType structure, fin findFirst().map(Map.Entry::getValue).orElse(null); } - public static StructureStart shouldStructureStartAt(final ServerLevel world, final BlockPos pos, final Structure structure, final boolean computeBox) + + public static StructureStart shouldStructureStartAt(ServerLevel world, BlockPos pos, Structure structure, boolean computeBox) { - final ServerChunkCache chunkSource = world.getChunkSource(); - final RandomState seed = chunkSource.randomState(); - final ChunkGenerator generator = chunkSource.getGenerator(); - final ChunkGeneratorStructureState structureState = chunkSource.getGeneratorState(); - final List structureConfig = structureState.getPlacementsForStructure(Holder.direct(structure)); - final ChunkPos chunkPos = new ChunkPos(pos); - final boolean couldPlace = structureConfig.stream().anyMatch(p -> p.isStructureChunk(structureState, chunkPos.x, chunkPos.z)); + ServerChunkCache chunkSource = world.getChunkSource(); + RandomState seed = chunkSource.randomState(); + ChunkGenerator generator = chunkSource.getGenerator(); + ChunkGeneratorStructureState structureState = chunkSource.getGeneratorState(); + List structureConfig = structureState.getPlacementsForStructure(Holder.direct(structure)); + ChunkPos chunkPos = new ChunkPos(pos); + boolean couldPlace = structureConfig.stream().anyMatch(p -> p.isStructureChunk(structureState, chunkPos.x, chunkPos.z)); if (!couldPlace) { return null; } - final HolderSet structureBiomes = structure.biomes(); + HolderSet structureBiomes = structure.biomes(); if (!computeBox) { @@ -259,7 +261,7 @@ public static StructureStart shouldStructureSta } else { - final StructureStart filledStructure = structure.generate( + StructureStart filledStructure = structure.generate( world.registryAccess(), generator, generator.getBiomeSource(), seed, world.getStructureManager(), world.getSeed(), chunkPos, 0, world, structureBiomes::contains); if (filledStructure != null && filledStructure.isValid()) @@ -270,7 +272,7 @@ public static StructureStart shouldStructureSta return null; } - private static TreeConfiguration.TreeConfigurationBuilder createTree(final Block block, final Block block2, final int i, final int j, final int k, final int l) + private static TreeConfiguration.TreeConfigurationBuilder createTree(Block block, Block block2, int i, int j, int k, int l) { return new TreeConfiguration.TreeConfigurationBuilder(BlockStateProvider.simple(block), new StraightTrunkPlacer(i, j, k), BlockStateProvider.simple(block2), new BlobFoliagePlacer(ConstantInt.of(l), ConstantInt.of(0), 3), new TwoLayersFeatureSize(1, 0, 1)); } @@ -292,13 +294,13 @@ private static TreeConfiguration.TreeConfigurationBuilder createTree(final Block PlacementUtils.inlinePlaced(Feature.CORAL_MUSHROOM, FeatureConfiguration.NONE) )))); put("bastion_remnant_units", l -> { - final RegistryAccess regs = l.registryAccess(); + RegistryAccess regs = l.registryAccess(); - final HolderGetter processorLists = regs.lookupOrThrow(Registries.PROCESSOR_LIST); - final Holder bastionGenericDegradation = processorLists.getOrThrow(ProcessorLists.BASTION_GENERIC_DEGRADATION); + HolderGetter processorLists = regs.lookupOrThrow(Registries.PROCESSOR_LIST); + Holder bastionGenericDegradation = processorLists.getOrThrow(ProcessorLists.BASTION_GENERIC_DEGRADATION); - final HolderGetter pools = regs.lookupOrThrow(Registries.TEMPLATE_POOL); - final Holder empty = pools.getOrThrow(Pools.EMPTY); + HolderGetter pools = regs.lookupOrThrow(Registries.TEMPLATE_POOL); + Holder empty = pools.getOrThrow(Pools.EMPTY); return spawnCustomStructure( @@ -322,13 +324,13 @@ private static TreeConfiguration.TreeConfigurationBuilder createTree(final Block ); }); put("bastion_remnant_hoglin_stable", l -> { - final RegistryAccess regs = l.registryAccess(); + RegistryAccess regs = l.registryAccess(); - final HolderGetter processorLists = regs.lookupOrThrow(Registries.PROCESSOR_LIST); - final Holder bastionGenericDegradation = processorLists.getOrThrow(ProcessorLists.BASTION_GENERIC_DEGRADATION); + HolderGetter processorLists = regs.lookupOrThrow(Registries.PROCESSOR_LIST); + Holder bastionGenericDegradation = processorLists.getOrThrow(ProcessorLists.BASTION_GENERIC_DEGRADATION); - final HolderGetter pools = regs.lookupOrThrow(Registries.TEMPLATE_POOL); - final Holder empty = pools.getOrThrow(Pools.EMPTY); + HolderGetter pools = regs.lookupOrThrow(Registries.TEMPLATE_POOL); + Holder empty = pools.getOrThrow(Pools.EMPTY); return spawnCustomStructure( new JigsawStructure(new Structure.StructureSettings( @@ -351,13 +353,13 @@ private static TreeConfiguration.TreeConfigurationBuilder createTree(final Block ); }); put("bastion_remnant_treasure", l -> { - final RegistryAccess regs = l.registryAccess(); + RegistryAccess regs = l.registryAccess(); - final HolderGetter processorLists = regs.lookupOrThrow(Registries.PROCESSOR_LIST); - final Holder bastionGenericDegradation = processorLists.getOrThrow(ProcessorLists.BASTION_GENERIC_DEGRADATION); + HolderGetter processorLists = regs.lookupOrThrow(Registries.PROCESSOR_LIST); + Holder bastionGenericDegradation = processorLists.getOrThrow(ProcessorLists.BASTION_GENERIC_DEGRADATION); - final HolderGetter pools = regs.lookupOrThrow(Registries.TEMPLATE_POOL); - final Holder empty = pools.getOrThrow(Pools.EMPTY); + HolderGetter pools = regs.lookupOrThrow(Registries.TEMPLATE_POOL); + Holder empty = pools.getOrThrow(Pools.EMPTY); return spawnCustomStructure( new JigsawStructure(new Structure.StructureSettings( @@ -380,13 +382,13 @@ private static TreeConfiguration.TreeConfigurationBuilder createTree(final Block ); }); put("bastion_remnant_bridge", l -> { - final RegistryAccess regs = l.registryAccess(); + RegistryAccess regs = l.registryAccess(); - final HolderGetter processorLists = regs.lookupOrThrow(Registries.PROCESSOR_LIST); - final Holder bastionGenericDegradation = processorLists.getOrThrow(ProcessorLists.BASTION_GENERIC_DEGRADATION); + HolderGetter processorLists = regs.lookupOrThrow(Registries.PROCESSOR_LIST); + Holder bastionGenericDegradation = processorLists.getOrThrow(ProcessorLists.BASTION_GENERIC_DEGRADATION); - final HolderGetter pools = regs.lookupOrThrow(Registries.TEMPLATE_POOL); - final Holder empty = pools.getOrThrow(Pools.EMPTY); + HolderGetter pools = regs.lookupOrThrow(Registries.TEMPLATE_POOL); + Holder empty = pools.getOrThrow(Pools.EMPTY); return spawnCustomStructure( new JigsawStructure(new Structure.StructureSettings( @@ -411,29 +413,29 @@ private static TreeConfiguration.TreeConfigurationBuilder createTree(final Block }}; - public static boolean plopAnywhere(final Structure structure, final ServerLevel world, final BlockPos pos, final ChunkGenerator generator, final boolean wireOnly) + public static boolean plopAnywhere(Structure structure, ServerLevel world, BlockPos pos, ChunkGenerator generator, boolean wireOnly) { - final ThreadLocal checks = Vanilla.skipGenerationChecks(world); + ThreadLocal checks = Vanilla.skipGenerationChecks(world); checks.set(true); try { - final StructureStart start = structure.generate(world.registryAccess(), generator, generator.getBiomeSource(), world.getChunkSource().randomState(), world.getStructureManager(), world.getSeed(), new ChunkPos(pos), 0, world, b -> true); + StructureStart start = structure.generate(world.registryAccess(), generator, generator.getBiomeSource(), world.getChunkSource().randomState(), world.getStructureManager(), world.getSeed(), new ChunkPos(pos), 0, world, b -> true); if (start == StructureStart.INVALID_START) { return false; } - final RandomSource rand = RandomSource.create(world.getRandom().nextInt()); - final int j = pos.getX() >> 4; - final int k = pos.getZ() >> 4; - final long chId = ChunkPos.asLong(j, k); + RandomSource rand = RandomSource.create(world.getRandom().nextInt()); + int j = pos.getX() >> 4; + int k = pos.getZ() >> 4; + long chId = ChunkPos.asLong(j, k); world.getChunk(j, k).setStartForStructure(structure, start); world.getChunk(j, k).addReferenceForStructure(structure, chId); - final BoundingBox box = start.getBoundingBox(); + BoundingBox box = start.getBoundingBox(); if (!wireOnly) { - final Registry registry3 = world.registryAccess().registryOrThrow(Registries.STRUCTURE); + Registry registry3 = world.registryAccess().registryOrThrow(Registries.STRUCTURE); world.setCurrentlyGenerating(() -> { Objects.requireNonNull(structure); return registry3.getResourceKey(structure).map(Object::toString).orElseGet(structure::toString); @@ -441,7 +443,7 @@ public static boolean plopAnywhere(final Structure structure, final ServerLevel start.placeInChunk(world, world.structureManager(), generator, rand, box, new ChunkPos(j, k)); } //structurestart.notifyPostProcessAt(new ChunkPos(j, k)); - final int i = Math.max(box.getXSpan(), box.getZSpan()) / 16 + 1; + int i = Math.max(box.getXSpan(), box.getZSpan()) / 16 + 1; //int i = getRadius(); for (int k1 = j - i; k1 <= j + i; ++k1) @@ -459,7 +461,7 @@ public static boolean plopAnywhere(final Structure structure, final ServerLevel } } } - catch (final Exception booboo) + catch (Exception booboo) { CarpetScriptServer.LOG.error("Unknown Exception while plopping structure: " + booboo, booboo); return false; diff --git a/src/main/java/carpet/script/utils/GlocalFlag.java b/src/main/java/carpet/script/utils/GlocalFlag.java index 52aa05c340..05cced39be 100644 --- a/src/main/java/carpet/script/utils/GlocalFlag.java +++ b/src/main/java/carpet/script/utils/GlocalFlag.java @@ -1,12 +1,13 @@ package carpet.script.utils; +import javax.annotation.Nullable; import java.util.function.Supplier; public class GlocalFlag extends ThreadLocal { private final boolean initial; - public GlocalFlag(final boolean initial) + public GlocalFlag(boolean initial) { this.initial = initial; } @@ -24,15 +25,15 @@ public Boolean initialValue() * @param - returned value of that action, whatever that might be * @return result of the action */ - public T getWhileDisabled(final Supplier action) + public T getWhileDisabled(Supplier action) { return whileValueReturn(!initial, action); } - private T whileValueReturn(final boolean what, final Supplier action) + private T whileValueReturn(boolean what, Supplier action) { T result; - final boolean previous; + boolean previous; synchronized (this) { previous = get(); @@ -49,7 +50,8 @@ private T whileValueReturn(final boolean what, final Supplier action) return result; } - public T runIfEnabled(final Supplier action) + @Nullable + public T runIfEnabled(Supplier action) { synchronized (this) { diff --git a/src/main/java/carpet/script/utils/InputValidator.java b/src/main/java/carpet/script/utils/InputValidator.java index 2f71b30f82..b27527e278 100644 --- a/src/main/java/carpet/script/utils/InputValidator.java +++ b/src/main/java/carpet/script/utils/InputValidator.java @@ -9,9 +9,9 @@ public class InputValidator { - public static String validateSimpleString(final String input, final boolean strict) + public static String validateSimpleString(String input, boolean strict) { - final String simplified = input.toLowerCase(Locale.ROOT).replaceAll("[^A-Za-z0-9+_]", ""); + String simplified = input.toLowerCase(Locale.ROOT).replaceAll("[^A-Za-z0-9+_]", ""); if (simplified.isEmpty() || (strict && !simplified.equals(input))) { throw new InternalExpressionException("simple name can only contain numbers, letter and _"); @@ -19,13 +19,13 @@ public static String validateSimpleString(final String input, final boolean stri return simplified; } - public static ResourceLocation identifierOf(final String string) + public static ResourceLocation identifierOf(String string) { try { return new ResourceLocation(string); } - catch (final ResourceLocationException iie) + catch (ResourceLocationException iie) { throw new InternalExpressionException("Incorrect identifier format '" + string + "': " + iie.getMessage()); } diff --git a/src/main/java/carpet/script/utils/ParticleParser.java b/src/main/java/carpet/script/utils/ParticleParser.java index 6ca6b55837..94485d314c 100644 --- a/src/main/java/carpet/script/utils/ParticleParser.java +++ b/src/main/java/carpet/script/utils/ParticleParser.java @@ -7,6 +7,7 @@ import net.minecraft.core.particles.ParticleOptions; import net.minecraft.core.particles.ParticleType; +import javax.annotation.Nullable; import java.util.HashMap; import java.util.Map; @@ -14,19 +15,20 @@ public class ParticleParser { private static final Map particleCache = new HashMap<>(); // we reset this on reloads, but probably need something better - private static ParticleOptions parseParticle(final String name, final HolderLookup> lookup) + private static ParticleOptions parseParticle(String name, HolderLookup> lookup) { try { return ParticleArgument.readParticle(new StringReader(name), lookup); } - catch (final CommandSyntaxException e) + catch (CommandSyntaxException e) { throw new IllegalArgumentException("No such particle: " + name); } } - public static ParticleOptions getEffect(final String name, final HolderLookup> lookup) + @Nullable + public static ParticleOptions getEffect(@Nullable String name, HolderLookup> lookup) { if (name == null) { diff --git a/src/main/java/carpet/script/utils/PerlinNoiseSampler.java b/src/main/java/carpet/script/utils/PerlinNoiseSampler.java index 4fdb3f1a82..56903050e4 100644 --- a/src/main/java/carpet/script/utils/PerlinNoiseSampler.java +++ b/src/main/java/carpet/script/utils/PerlinNoiseSampler.java @@ -24,7 +24,7 @@ public class PerlinNoiseSampler public static PerlinNoiseSampler instance = new PerlinNoiseSampler(new Random(0)); public static Map samplers = new Long2ObjectOpenHashMap<>(); - public static PerlinNoiseSampler getPerlin(final long aLong) + public static PerlinNoiseSampler getPerlin(long aLong) { if (samplers.size() > 256) { @@ -33,7 +33,7 @@ public static PerlinNoiseSampler getPerlin(final long aLong) return samplers.computeIfAbsent(aLong, seed -> new PerlinNoiseSampler(new Random(seed))); } - public PerlinNoiseSampler(final Random random) + public PerlinNoiseSampler(Random random) { this.originX = random.nextDouble() * 256.0D; this.originY = random.nextDouble() * 256.0D; @@ -47,27 +47,27 @@ public PerlinNoiseSampler(final Random random) } for (j = 0; j < 256; ++j) { - final int k = random.nextInt(256 - j); - final byte b = this.permutations[j]; + int k = random.nextInt(256 - j); + byte b = this.permutations[j]; this.permutations[j] = this.permutations[j + k]; this.permutations[j + k] = b; } } //3D - public double sample3d(final double x, final double y, final double z) + public double sample3d(double x, double y, double z) {//, double d, double e) { - final double f = x + this.originX; - final double g = y + this.originY; - final double h = z + this.originZ; - final int i = floor(f); - final int j = floor(g); - final int k = floor(h); - final double l = f - (double) i; - final double m = g - (double) j; - final double n = h - (double) k; - final double o = perlinFade(l); - final double p = perlinFade(m); - final double q = perlinFade(n); + double f = x + this.originX; + double g = y + this.originY; + double h = z + this.originZ; + int i = floor(f); + int j = floor(g); + int k = floor(h); + double l = f - (double) i; + double m = g - (double) j; + double n = h - (double) k; + double o = perlinFade(l); + double p = perlinFade(m); + double q = perlinFade(n); //double t; /* if (d != 0.0D) { @@ -80,124 +80,124 @@ public double sample3d(final double x, final double y, final double z) return this.sample3d(i, j, k, l, m, n, o, p, q) / 2 + 0.5; } - private double sample3d(final int sectionX, final int sectionY, final int sectionZ, final double localX, final double localY, final double localZ, final double fadeLocalX, final double fadeLocalY, final double fadeLocalZ) - { - final int i = this.getGradient(sectionX) + sectionY; - final int j = this.getGradient(i) + sectionZ; - final int k = this.getGradient(i + 1) + sectionZ; - final int l = this.getGradient(sectionX + 1) + sectionY; - final int m = this.getGradient(l) + sectionZ; - final int n = this.getGradient(l + 1) + sectionZ; - final double d = grad3d(this.getGradient(j), localX, localY, localZ); - final double e = grad3d(this.getGradient(m), localX - 1.0D, localY, localZ); - final double f = grad3d(this.getGradient(k), localX, localY - 1.0D, localZ); - final double g = grad3d(this.getGradient(n), localX - 1.0D, localY - 1.0D, localZ); - final double h = grad3d(this.getGradient(j + 1), localX, localY, localZ - 1.0D); - final double o = grad3d(this.getGradient(m + 1), localX - 1.0D, localY, localZ - 1.0D); - final double p = grad3d(this.getGradient(k + 1), localX, localY - 1.0D, localZ - 1.0D); - final double q = grad3d(this.getGradient(n + 1), localX - 1.0D, localY - 1.0D, localZ - 1.0D); + private double sample3d(int sectionX, int sectionY, int sectionZ, double localX, double localY, double localZ, double fadeLocalX, double fadeLocalY, double fadeLocalZ) + { + int i = this.getGradient(sectionX) + sectionY; + int j = this.getGradient(i) + sectionZ; + int k = this.getGradient(i + 1) + sectionZ; + int l = this.getGradient(sectionX + 1) + sectionY; + int m = this.getGradient(l) + sectionZ; + int n = this.getGradient(l + 1) + sectionZ; + double d = grad3d(this.getGradient(j), localX, localY, localZ); + double e = grad3d(this.getGradient(m), localX - 1.0D, localY, localZ); + double f = grad3d(this.getGradient(k), localX, localY - 1.0D, localZ); + double g = grad3d(this.getGradient(n), localX - 1.0D, localY - 1.0D, localZ); + double h = grad3d(this.getGradient(j + 1), localX, localY, localZ - 1.0D); + double o = grad3d(this.getGradient(m + 1), localX - 1.0D, localY, localZ - 1.0D); + double p = grad3d(this.getGradient(k + 1), localX, localY - 1.0D, localZ - 1.0D); + double q = grad3d(this.getGradient(n + 1), localX - 1.0D, localY - 1.0D, localZ - 1.0D); return lerp3(fadeLocalX, fadeLocalY, fadeLocalZ, d, e, f, g, h, o, p, q); } - private static double grad3d(final int hash, final double x, final double y, final double z) + private static double grad3d(int hash, double x, double y, double z) { - final int i = hash & 15; + int i = hash & 15; return dot3d(gradients3d[i], x, y, z); } - protected static double dot3d(final int[] gArr, final double x, final double y, final double z) + protected static double dot3d(int[] gArr, double x, double y, double z) { return gArr[0] * x + gArr[1] * y + gArr[2] * z; } - public static double lerp3(final double deltaX, final double deltaY, final double deltaZ, final double d, final double e, final double f, final double g, final double h, final double i, final double j, final double k) + public static double lerp3(double deltaX, double deltaY, double deltaZ, double d, double e, double f, double g, double h, double i, double j, double k) { return lerp(deltaZ, lerp2(deltaX, deltaY, d, e, f, g), lerp2(deltaX, deltaY, h, i, j, k)); } //2D - public double sample2d(final double x, final double y) - { - final double f = x + this.originX; - final double g = y + this.originY; - final int i = floor(f); - final int j = floor(g); - final double l = f - (double) i; - final double m = g - (double) j; - final double o = perlinFade(l); - final double p = perlinFade(m); + public double sample2d(double x, double y) + { + double f = x + this.originX; + double g = y + this.originY; + int i = floor(f); + int j = floor(g); + double l = f - (double) i; + double m = g - (double) j; + double o = perlinFade(l); + double p = perlinFade(m); return this.sample2d(i, j, l, m, o, p) / 2 + 0.5; } - private double sample2d(final int sectionX, final int sectionY, final double localX, final double localY, final double fadeLocalX, final double fadeLocalY) + private double sample2d(int sectionX, int sectionY, double localX, double localY, double fadeLocalX, double fadeLocalY) { - final int j = this.getGradient(sectionX) + sectionY; - final int m = this.getGradient(sectionX + 1) + sectionY; - final double d = grad2d(this.getGradient(j), localX, localY); - final double e = grad2d(this.getGradient(m), localX - 1.0D, localY); - final double f = grad2d(this.getGradient(j + 1), localX, localY - 1.0D); - final double g = grad2d(this.getGradient(m + 1), localX - 1.0D, localY - 1.0D); + int j = this.getGradient(sectionX) + sectionY; + int m = this.getGradient(sectionX + 1) + sectionY; + double d = grad2d(this.getGradient(j), localX, localY); + double e = grad2d(this.getGradient(m), localX - 1.0D, localY); + double f = grad2d(this.getGradient(j + 1), localX, localY - 1.0D); + double g = grad2d(this.getGradient(m + 1), localX - 1.0D, localY - 1.0D); return lerp2(fadeLocalX, fadeLocalY, d, e, f, g); } - private static double grad2d(final int hash, final double x, final double y) + private static double grad2d(int hash, double x, double y) { - final int i = hash & 3; + int i = hash & 3; return dot2d(gradients2d[i], x, y); } - protected static double dot2d(final int[] gArr, final double x, final double y) + protected static double dot2d(int[] gArr, double x, double y) { return gArr[0] * x + gArr[1] * y; } - public static double lerp2(final double deltaX, final double deltaY, final double d, final double e, final double f, final double g) + public static double lerp2(double deltaX, double deltaY, double d, double e, double f, double g) { return lerp(deltaY, lerp(deltaX, d, e), lerp(deltaX, f, g)); } // 1D - public double sample1d(final double x) + public double sample1d(double x) { - final double f = x + this.originX; - final int i = floor(f); - final double l = f - i; - final double o = perlinFade(l); + double f = x + this.originX; + int i = floor(f); + double l = f - i; + double o = perlinFade(l); return this.sample1d(i, l, o) + 0.5; } - private double sample1d(final int sectionX, final double localX, final double fadeLocalX) + private double sample1d(int sectionX, double localX, double fadeLocalX) { - final double d = grad1d(this.getGradient(sectionX), localX); - final double e = grad1d(this.getGradient(sectionX + 1), localX - 1.0D); + double d = grad1d(this.getGradient(sectionX), localX); + double e = grad1d(this.getGradient(sectionX + 1), localX - 1.0D); return lerp(fadeLocalX, d, e); } - private static double grad1d(final int hash, final double x) + private static double grad1d(int hash, double x) { return ((hash & 1) == 0) ? x : -x; } - public static double lerp(final double delta, final double first, final double second) + public static double lerp(double delta, double first, double second) { return first + delta * (second - first); } // shared - public int getGradient(final int hash) + public int getGradient(int hash) { return this.permutations[hash & 255] & 255; } - public static double perlinFade(final double d) + public static double perlinFade(double d) { return d * d * d * (d * (d * 6.0D - 15.0D) + 10.0D); } - public static int floor(final double d) + public static int floor(double d) { - final int i = (int) d; + int i = (int) d; return d < i ? i - 1 : i; } } \ No newline at end of file diff --git a/src/main/java/carpet/script/utils/ScarpetJsonDeserializer.java b/src/main/java/carpet/script/utils/ScarpetJsonDeserializer.java index c6af60039e..39e63872c9 100644 --- a/src/main/java/carpet/script/utils/ScarpetJsonDeserializer.java +++ b/src/main/java/carpet/script/utils/ScarpetJsonDeserializer.java @@ -24,12 +24,12 @@ public class ScarpetJsonDeserializer implements JsonDeserializer { @Override - public Value deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException + public Value deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return parseElement(json); } - private Value parseElement(final JsonElement element) throws JsonParseException + private Value parseElement(JsonElement element) throws JsonParseException { if (element.isJsonObject()) { @@ -46,21 +46,21 @@ else if (element.isJsonPrimitive()) return Value.NULL; } - private Value parseMap(final JsonObject jsonMap) throws JsonParseException + private Value parseMap(JsonObject jsonMap) throws JsonParseException { - final Map map = new HashMap<>(); + Map map = new HashMap<>(); jsonMap.entrySet().forEach(entry -> map.put(new StringValue(entry.getKey()), parseElement(entry.getValue()))); return MapValue.wrap(map); } - private Value parseList(final JsonArray jsonList) throws JsonParseException + private Value parseList(JsonArray jsonList) throws JsonParseException { - final List list = new ArrayList<>(); + List list = new ArrayList<>(); jsonList.forEach(elem -> list.add(parseElement(elem))); return new ListValue(list); } - private Value parsePrimitive(final JsonPrimitive primitive) throws JsonParseException + private Value parsePrimitive(JsonPrimitive primitive) throws JsonParseException { if (primitive.isString()) { diff --git a/src/main/java/carpet/script/utils/ShapeDispatcher.java b/src/main/java/carpet/script/utils/ShapeDispatcher.java index 308b7cb90c..ce25aaac86 100644 --- a/src/main/java/carpet/script/utils/ShapeDispatcher.java +++ b/src/main/java/carpet/script/utils/ShapeDispatcher.java @@ -53,6 +53,7 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.Vec3; +import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -76,25 +77,25 @@ public record ShapeWithConfig(ExpiringShape shape, Map config) } public static ShapeWithConfig fromFunctionArgs( - final MinecraftServer server, final ServerLevel world, - final List lv, - final Set playerSet + MinecraftServer server, ServerLevel world, + List lv, + Set playerSet ) { if (lv.size() < 3) { throw new InternalExpressionException("'draw_shape' takes at least three parameters, shape name, duration, and its params"); } - final String shapeType = lv.get(0).getString(); - final Value duration = NumericValue.asNumber(lv.get(1), "duration"); - final Map params; + String shapeType = lv.get(0).getString(); + Value duration = NumericValue.asNumber(lv.get(1), "duration"); + Map params; if (lv.size() == 3) { - final Value paramValue = lv.get(2); + Value paramValue = lv.get(2); if (paramValue instanceof final MapValue map) { params = new HashMap<>(); - map.getMap().entrySet().forEach(e -> params.put(e.getKey().getString(), e.getValue())); + map.getMap().forEach((key, value) -> params.put(key.getString(), value)); } else if (paramValue instanceof final ListValue list) { @@ -107,7 +108,7 @@ else if (paramValue instanceof final ListValue list) } else { - final List paramList = new ArrayList<>(); + List paramList = new ArrayList<>(); for (int i = 2; i < lv.size(); i++) { paramList.add(lv.get(i)); @@ -119,8 +120,8 @@ else if (paramValue instanceof final ListValue list) if (params.containsKey("player")) { - final Value players = params.get("player"); - final List playerVals; + Value players = params.get("player"); + List playerVals; if (players instanceof final ListValue list) { playerVals = list.getItems(); @@ -129,9 +130,9 @@ else if (paramValue instanceof final ListValue list) { playerVals = Collections.singletonList(players); } - for (final Value pVal : playerVals) + for (Value pVal : playerVals) { - final ServerPlayer 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()); @@ -143,11 +144,11 @@ else if (paramValue instanceof final ListValue list) return new ShapeWithConfig(ShapeDispatcher.create(server, shapeType, params), params); } - public static void sendShape(final Collection players, final List shapes) + public static void sendShape(Collection players, List shapes) { - final List clientPlayers = new ArrayList<>(); - final List alternativePlayers = new ArrayList<>(); - for (final ServerPlayer player : players) + List clientPlayers = new ArrayList<>(); + List alternativePlayers = new ArrayList<>(); + for (ServerPlayer player : players) { (Carpet.isValidCarpetPlayer(player) ? clientPlayers : alternativePlayers).add(player); } @@ -155,18 +156,18 @@ public static void sendShape(final Collection players, final List< { ListTag tag = new ListTag(); int tagcount = 0; - for (final ShapeWithConfig s : shapes) + for (ShapeWithConfig s : shapes) { tag.add(ExpiringShape.toTag(s.config())); // 4000 shapes limit boxes if (tagcount++ > 1000) { tagcount = 0; - final Tag finalTag = tag; + Tag finalTag = tag; clientPlayers.forEach(p -> Vanilla.sendScarpetShapesDataToPlayer(p, finalTag)); tag = new ListTag(); } } - final Tag finalTag = tag; + Tag finalTag = tag; if (!tag.isEmpty()) { clientPlayers.forEach(p -> Vanilla.sendScarpetShapesDataToPlayer(p, finalTag)); @@ -174,55 +175,55 @@ public static void sendShape(final Collection players, final List< } if (!alternativePlayers.isEmpty()) { - final List> alternatives = new ArrayList<>(); + List> alternatives = new ArrayList<>(); shapes.forEach(s -> alternatives.add(s.shape().alternative())); alternativePlayers.forEach(p -> alternatives.forEach(a -> a.accept(p))); } } - public static ParticleOptions getParticleData(final String name, final RegistryAccess regs) + public static ParticleOptions getParticleData(String name, RegistryAccess regs) { try { return ParticleParser.getEffect(name, regs.lookupOrThrow(Registries.PARTICLE_TYPE)); } - catch (final IllegalArgumentException e) + catch (IllegalArgumentException e) { throw new ThrowStatement(name, Throwables.UNKNOWN_PARTICLE); } } - public static Map parseParams(final List items) + public static Map parseParams(List items) { // parses params from API function if (items.size() % 2 == 1) { throw new InternalExpressionException("Shape parameters list needs to be of even size"); } - final Map param = new HashMap<>(); + Map param = new HashMap<>(); int i = 0; while (i < items.size()) { - final String name = items.get(i).getString(); - final Value val = items.get(i + 1); + String name = items.get(i).getString(); + Value val = items.get(i + 1); param.put(name, val); i += 2; } return param; } - public static ExpiringShape create(final MinecraftServer server, final String shapeType, final Map userParams) + public static ExpiringShape create(MinecraftServer server, String shapeType, Map userParams) { userParams.put("shape", new StringValue(shapeType)); userParams.keySet().forEach(key -> { - final Param param = Param.of.get(key); + Param param = Param.of.get(key); if (param == null) { throw new InternalExpressionException("Unknown feature for shape: " + key); } userParams.put(key, param.validate(userParams, server, userParams.get(key))); }); - final BiFunction, RegistryAccess, ExpiringShape> factory = ExpiringShape.shapeProviders.get(shapeType); + BiFunction, RegistryAccess, ExpiringShape> factory = ExpiringShape.shapeProviders.get(shapeType); if (factory == null) { throw new InternalExpressionException("Unknown shape: " + shapeType); @@ -231,27 +232,28 @@ public static ExpiringShape create(final MinecraftServer server, final String sh } // client - public static ExpiringShape fromTag(final CompoundTag tag, final Level level) + @Nullable + public static ExpiringShape fromTag(CompoundTag tag, Level level) { - final Map options = new HashMap<>(); - for (final String key : tag.getAllKeys()) + Map options = new HashMap<>(); + for (String key : tag.getAllKeys()) { - final Param decoder = Param.of.get(key); + Param decoder = Param.of.get(key); if (decoder == null) { CarpetScriptServer.LOG.info("Unknown parameter for shape: " + key); return null; } - final Value decodedValue = decoder.decode(tag.get(key), level); + Value decodedValue = decoder.decode(tag.get(key), level); options.put(key, decodedValue); } - final Value shapeValue = options.get("shape"); + Value shapeValue = options.get("shape"); if (shapeValue == null) { CarpetScriptServer.LOG.info("Shape id missing in " + String.join(", ", tag.getAllKeys())); return null; } - final BiFunction, RegistryAccess, ExpiringShape> factory = ExpiringShape.shapeProviders.get(shapeValue.getString()); + BiFunction, RegistryAccess, ExpiringShape> factory = ExpiringShape.shapeProviders.get(shapeValue.getString()); if (factory == null) { CarpetScriptServer.LOG.info("Unknown shape: " + shapeValue.getString()); @@ -261,7 +263,7 @@ public static ExpiringShape fromTag(final CompoundTag tag, final Level level) { return factory.apply(options, level.registryAccess()); } - catch (final InternalExpressionException exc) + catch (InternalExpressionException exc) { CarpetScriptServer.LOG.info(exc.getMessage()); } @@ -282,10 +284,10 @@ public abstract static class ExpiringShape put("item", creator(() -> new DisplayedSprite(true))); }}; - private static BiFunction, RegistryAccess, ExpiringShape> creator(final Supplier shapeFactory) + private static BiFunction, RegistryAccess, ExpiringShape> creator(Supplier shapeFactory) { return (o, regs) -> { - final ExpiringShape shape = shapeFactory.get(); + ExpiringShape shape = shapeFactory.get(); shape.fromOptions(o, regs); return shape; }; @@ -310,11 +312,11 @@ protected ExpiringShape() { } - public static CompoundTag toTag(final Map params) + public static CompoundTag toTag(Map params) { - final CompoundTag tag = new CompoundTag(); + CompoundTag tag = new CompoundTag(); params.forEach((k, v) -> { - final Tag valTag = Param.of.get(k).toTag(v); + Tag valTag = Param.of.get(k).toTag(v); if (valTag != null) { tag.put(k, valTag); @@ -323,18 +325,18 @@ public static CompoundTag toTag(final Map params) return tag; } - private void fromOptions(final Map options, final RegistryAccess regs) + private void fromOptions(Map options, RegistryAccess regs) { - final Set optional = optionalParams(); - final Set required = requiredParams(); - final Set all = Sets.union(optional, required); + Set optionalParams = optionalParams(); + Set requiredParams = requiredParams(); + Set all = Sets.union(optionalParams, requiredParams); if (!all.containsAll(options.keySet())) { throw new InternalExpressionException("Received unexpected parameters for shape: " + Sets.difference(options.keySet(), all)); } - if (!options.keySet().containsAll(required)) + if (!options.keySet().containsAll(requiredParams)) { - throw new InternalExpressionException("Missing required parameters for shape: " + Sets.difference(required, options.keySet())); + throw new InternalExpressionException("Missing required parameters for shape: " + Sets.difference(requiredParams, options.keySet())); } options.keySet().forEach(k -> { if (!this.canTake(k)) @@ -346,7 +348,7 @@ private void fromOptions(final Map options, final RegistryAccess } - protected void init(final Map options, final RegistryAccess regs) + protected void init(Map options, RegistryAccess regs) { duration = NumericValue.asNumber(options.get("duration")).getInt(); @@ -392,7 +394,7 @@ public int getExpiry() return duration; } - public Vec3 toAbsolute(final Entity e, final Vec3 vec, final float partialTick) + public Vec3 toAbsolute(Entity e, Vec3 vec, float partialTick) { return vec.add( snapX ? (discreteX ? Mth.floor(e.getX()) : Mth.lerp(partialTick, e.xo, e.getX())) : 0.0, @@ -401,13 +403,13 @@ public Vec3 toAbsolute(final Entity e, final Vec3 vec, final float partialTick) ); } - public Vec3 relativiseRender(final Level world, final Vec3 vec, final float partialTick) + public Vec3 relativiseRender(Level world, Vec3 vec, float partialTick) { if (followEntity < 0) { return vec; } - final Entity e = world.getEntity(followEntity); + Entity e = world.getEntity(followEntity); if (e == null) { return vec; @@ -415,13 +417,13 @@ public Vec3 relativiseRender(final Level world, final Vec3 vec, final float part return toAbsolute(e, vec, partialTick); } - public Vec3 vecFromValue(final Value value) + public Vec3 vecFromValue(Value value) { if (!(value instanceof final ListValue list)) { throw new InternalExpressionException("decoded value of " + value.getPrettyString() + " is not a triple"); } - final List elements = list.getItems(); + List elements = list.getItems(); return new Vec3( NumericValue.asNumber(elements.get(0)).getDouble(), NumericValue.asNumber(elements.get(1)).getDouble(), @@ -429,9 +431,9 @@ public Vec3 vecFromValue(final Value value) ); } - protected ParticleOptions replacementParticle(final RegistryAccess regs) + protected ParticleOptions replacementParticle(RegistryAccess regs) { - final String particleName = fa == 0 ? + String particleName = fa == 0 ? String.format(Locale.ROOT, "dust %.1f %.1f %.1f 1.0", r, g, b) : String.format(Locale.ROOT, "dust %.1f %.1f %.1f 1.0", fr, fg, fb); return getParticleData(particleName, regs); @@ -440,7 +442,7 @@ protected ParticleOptions replacementParticle(final RegistryAccess regs) public abstract Consumer alternative(); - public long key(final RegistryAccess regs) + public long key(RegistryAccess regs) { if (key != 0) { @@ -450,7 +452,7 @@ public long key(final RegistryAccess regs) return key; } - protected long calcKey(final RegistryAccess regs) + protected long calcKey(RegistryAccess regs) { // using FNV-1a algorithm long hash = -3750763034362895579L; hash ^= shapeDimension.hashCode(); @@ -476,11 +478,11 @@ protected long calcKey(final RegistryAccess regs) return hash; } - private static final double xdif = new Random().nextDouble(); - private static final double ydif = new Random().nextDouble(); - private static final double zdif = new Random().nextDouble(); + private static final double xdif = new Random('x').nextDouble(); + private static final double ydif = new Random('y').nextDouble(); + private static final double zdif = new Random('z').nextDouble(); - int vec3dhash(final Vec3 vec) + int vec3dhash(Vec3 vec) { return vec.add(xdif, ydif, zdif).hashCode(); } @@ -507,7 +509,7 @@ protected Set optionalParams() return optional.keySet(); } - private boolean canTake(final String param) + private boolean canTake(String param) { return requiredParams().contains(param) || optionalParams().contains(param); } @@ -563,7 +565,7 @@ public DisplayedText() boolean doublesided; @Override - protected void init(final Map options, final RegistryAccess regs) + protected void init(Map options, RegistryAccess regs) { super.init(options, regs); pos = vecFromValue(options.get("pos")); @@ -575,12 +577,12 @@ protected void init(final Map options, final RegistryAccess regs) } textcolor = rgba2argb(color); textbck = rgba2argb(fillColor); - final String dir = options.getOrDefault("facing", optional.get("facing")).getString(); + String dir = options.getOrDefault("facing", optional.get("facing")).getString(); facing = ShapeDirection.fromString(dir); align = 0; if (options.containsKey("align")) { - final String alignStr = options.get("align").getString(); + String alignStr = options.get("align").getString(); if ("right".equalsIgnoreCase(alignStr)) { align = 1; @@ -606,12 +608,12 @@ else if ("left".equalsIgnoreCase(alignStr)) size = NumericValue.asNumber(options.getOrDefault("size", optional.get("size"))).getFloat(); } - private int rgba2argb(final int color) + private int rgba2argb(int color) { - final int r = Math.max(1, color >> 24 & 0xFF); - final int g = Math.max(1, color >> 16 & 0xFF); - final int b = Math.max(1, color >> 8 & 0xFF); - final int a = color & 0xFF; + int r = Math.max(1, color >> 24 & 0xFF); + int g = Math.max(1, color >> 16 & 0xFF); + int b = Math.max(1, color >> 8 & 0xFF); + int a = color & 0xFF; return (a << 24) + (r << 16) + (g << 8) + b; } @@ -623,7 +625,7 @@ public Consumer alternative() } @Override - public long calcKey(final RegistryAccess regs) + public long calcKey(RegistryAccess regs) { long hash = super.calcKey(regs); hash ^= 5; @@ -685,7 +687,7 @@ protected Set optionalParams() return Sets.union(Sets.union(super.optionalParams(), optional.keySet()), isitem ? Set.of("variant") : Set.of()); } - public DisplayedSprite(final boolean i) + public DisplayedSprite(boolean i) { isitem = i; } @@ -710,13 +712,13 @@ public DisplayedSprite(final boolean i) String itemTransformType; @Override - protected void init(final Map options, final RegistryAccess regs) + protected void init(Map options, RegistryAccess regs) { super.init(options, regs); pos = vecFromValue(options.get("pos")); if (!this.isitem) { - final BlockValue block = (BlockValue) options.get("block"); + BlockValue block = (BlockValue) options.get("block"); blockState = block.getBlockState(); blockEntity = block.getData(); } @@ -741,13 +743,13 @@ protected void init(final Map options, final RegistryAccess regs) itemTransformType = options.get("variant").getString().toLowerCase(Locale.ROOT); } - final String dir = options.getOrDefault("facing", optional.get("facing")).getString(); + String dir = options.getOrDefault("facing", optional.get("facing")).getString(); facing = ShapeDirection.fromString(dir); tilt = NumericValue.asNumber(options.getOrDefault("tilt", optional.get("tilt"))).getFloat(); lean = NumericValue.asNumber(options.getOrDefault("lean", optional.get("lean"))).getFloat(); turn = NumericValue.asNumber(options.getOrDefault("turn", optional.get("turn"))).getFloat(); - final List scale = ((ListValue) options.getOrDefault("scale", optional.get("scale"))).unpack(); + List scale = ((ListValue) options.getOrDefault("scale", optional.get("scale"))).unpack(); scaleY = NumericValue.asNumber(scale.get(1)).getFloat(); scaleX = NumericValue.asNumber(scale.get(0)).getFloat(); scaleZ = NumericValue.asNumber(scale.get(2)).getFloat(); @@ -757,8 +759,8 @@ protected void init(final Map options, final RegistryAccess regs) public Consumer alternative() { return p -> { - final ParticleOptions particle; - final Registry blocks = p.getServer().registryAccess().registryOrThrow(Registries.BLOCK); + ParticleOptions particle; + Registry blocks = p.getServer().registryAccess().registryOrThrow(Registries.BLOCK); if (this.isitem) { if (Block.byItem(this.item.getItem()).defaultBlockState().isAir()) @@ -772,13 +774,13 @@ public Consumer alternative() particle = getParticleData("block_marker " + blocks.getKey(this.blockState.getBlock()), p.level.registryAccess()); } - final Vec3 v = relativiseRender(p.level, this.pos, 0); + Vec3 v = relativiseRender(p.level, this.pos, 0); p.getLevel().sendParticles(p, particle, true, v.x, v.y, v.z, 1, 0.0, 0.0, 0.0, 0.0); }; } @Override - public long calcKey(final RegistryAccess regs) + public long calcKey(RegistryAccess regs) { long hash = super.calcKey(regs); hash ^= 7; @@ -853,7 +855,7 @@ public Box() Vec3 to; @Override - protected void init(final Map options, final RegistryAccess regs) + protected void init(Map options, RegistryAccess regs) { super.init(options, regs); from = vecFromValue(options.get("from")); @@ -863,7 +865,7 @@ protected void init(final Map options, final RegistryAccess regs) @Override public Consumer alternative() { - final double density = Math.max(2.0, from.distanceTo(to) / 50 / (a + 0.1)); + double density = Math.max(2.0, from.distanceTo(to) / 50 / (a + 0.1)); return p -> { if (p.level.dimension() == shapeDimension) @@ -880,7 +882,7 @@ public Consumer alternative() } @Override - public long calcKey(final RegistryAccess regs) + public long calcKey(RegistryAccess regs) { long hash = super.calcKey(regs); hash ^= 1; @@ -892,15 +894,15 @@ public long calcKey(final RegistryAccess regs) return hash; } - public static int particleMesh(final List playerList, final ParticleOptions particle, final double density, - final Vec3 from, final Vec3 to) + public static int particleMesh(List playerList, ParticleOptions particle, double density, + Vec3 from, Vec3 to) { - final double x1 = from.x; - final double y1 = from.y; - final double z1 = from.z; - final double x2 = to.x; - final double y2 = to.y; - final double z2 = to.z; + double x1 = from.x; + double y1 = from.y; + double z1 = from.z; + double x2 = to.x; + double y2 = to.y; + double z2 = to.z; return 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) + @@ -922,7 +924,7 @@ public static int particleMesh(final List playerList, final Partic public static class Polyface extends ExpiringShape { @Override - public long calcKey(final RegistryAccess regs) + public long calcKey(RegistryAccess regs) { long hash = super.calcKey(regs); hash ^= 6; @@ -931,97 +933,97 @@ public long calcKey(final RegistryAccess regs) hash *= 1099511628211L; hash ^= relative.hashCode(); hash *= 1099511628211L; - for (final Vec3 i : vertex_list) + for (Vec3 i : vertexList) { hash ^= vec3dhash(i); hash *= 1099511628211L; } hash ^= Boolean.hashCode(doublesided); hash *= 1099511628211L; - hash ^= Integer.hashCode(vertex_list.size()); + hash ^= Integer.hashCode(vertexList.size()); hash *= 1099511628211L; hash ^= Boolean.hashCode(inneredges); hash *= 1099511628211L; return hash; } - ArrayList alter_point = null; + ArrayList alterPoint = null; final Random random = new Random(); boolean doublesided; - ArrayList alter_point(final ServerPlayer p) + ArrayList getAlterPoint(ServerPlayer p) { - if (alter_point != null) + if (alterPoint != null) { - return alter_point; + return alterPoint; } - alter_point = new ArrayList<>(); + alterPoint = new ArrayList<>(); switch (mode) { case 4: - for (int i = 0; i < vertex_list.size(); i++) + for (int i = 0; i < vertexList.size(); i++) { - Vec3 vecA = vertex_list.get(i); + Vec3 vecA = vertexList.get(i); if (relative.get(i)) { vecA = relativiseRender(p.level, vecA, 0); } i++; - Vec3 vecB = vertex_list.get(i); + Vec3 vecB = vertexList.get(i); if (relative.get(i)) { vecB = relativiseRender(p.level, vecB, 0); } i++; - Vec3 vecC = vertex_list.get(i); + Vec3 vecC = vertexList.get(i); if (relative.get(i)) { vecC = relativiseRender(p.level, vecC, 0); } - alter_draw_triangles(vecA, vecB, vecC); + alterDrawTriangles(vecA, vecB, vecC); } break; case 6: - Vec3 vec0 = vertex_list.get(0); + Vec3 vec0 = vertexList.get(0); if (relative.get(0)) { vec0 = relativiseRender(p.level, vec0, 0); } - Vec3 vec1 = vertex_list.get(1); + Vec3 vec1 = vertexList.get(1); if (relative.get(1)) { vec1 = relativiseRender(p.level, vec1, 0); } - for (int i = 2; i < vertex_list.size(); i++) + for (int i = 2; i < vertexList.size(); i++) { - Vec3 vec = vertex_list.get(i); + Vec3 vec = vertexList.get(i); if (relative.get(i)) { vec = relativiseRender(p.level, vec, 0); } - alter_draw_triangles(vec0, vec1, vec); + alterDrawTriangles(vec0, vec1, vec); vec1 = vec; } break; case 5: - Vec3 vecA = vertex_list.get(0); + Vec3 vecA = vertexList.get(0); if (relative.get(0)) { vecA = relativiseRender(p.level, vecA, 0); } - Vec3 vecB = vertex_list.get(1); + Vec3 vecB = vertexList.get(1); if (relative.get(1)) { vecB = relativiseRender(p.level, vecB, 0); } - for (int i = 2; i < vertex_list.size(); i++) + for (int i = 2; i < vertexList.size(); i++) { - Vec3 vec = vertex_list.get(i); + Vec3 vec = vertexList.get(i); if (relative.get(i)) { vec = relativiseRender(p.level, vec, 0); } - alter_draw_triangles(vecA, vecB, vec); + alterDrawTriangles(vecA, vecB, vec); vecA = vecB; vecB = vec; } @@ -1030,27 +1032,27 @@ ArrayList alter_point(final ServerPlayer p) break; } - return alter_point; + return alterPoint; } - void alter_draw_triangles(final Vec3 a, final Vec3 b, final Vec3 c) + void alterDrawTriangles(Vec3 a, Vec3 b, Vec3 c) { - final Vec3 B = b.subtract(a); - final Vec3 C = c.subtract(a); - for (int i = 0; i / 8 < B.cross(C).length(); i++) + Vec3 bb = b.subtract(a); + Vec3 cc = c.subtract(a); + for (int i = 0; i / 8 < bb.cross(cc).length(); i++) { double x = random.nextDouble(); double y = random.nextDouble(); - alter_point.add(a.add(B.scale(x / 2)).add(C.scale(y / 2))); + alterPoint.add(a.add(bb.scale(x / 2)).add(cc.scale(y / 2))); if (x + y < 1) { - alter_point.add(a.add(B.scale((x + 1) / 2)).add(C.scale(y / 2))); + alterPoint.add(a.add(bb.scale((x + 1) / 2)).add(cc.scale(y / 2))); } else { x = 1 - x; y = 1 - y; - alter_point.add(a.add(B.scale(x / 2)).add(C.scale((y + 1) / 2))); + alterPoint.add(a.add(bb.scale(x / 2)).add(cc.scale((y + 1) / 2))); } } } @@ -1063,16 +1065,15 @@ public Consumer alternative() { return; } - if (!(fa > 0.0f)) + if (fa > 0.0f) { - return; - } - final ParticleOptions locparticledata = getParticleData(String.format(Locale.ROOT, "dust %.1f %.1f %.1f %.1f", fr, fg, fb, fa), p.level.registryAccess()); - for (final Vec3 v : alter_point(p)) - { - p.getLevel().sendParticles(p, locparticledata, true, - v.x, v.y, v.z, 1, - 0.0, 0.0, 0.0, 0.0); + ParticleOptions locparticledata = getParticleData(String.format(Locale.ROOT, "dust %.1f %.1f %.1f %.1f", fr, fg, fb, fa), p.level.registryAccess()); + for (Vec3 v : getAlterPoint(p)) + { + p.getLevel().sendParticles(p, locparticledata, true, + v.x, v.y, v.z, 1, + 0.0, 0.0, 0.0, 0.0); + } } }; } @@ -1097,13 +1098,13 @@ protected Set optionalParams() return Sets.union(super.optionalParams(), optional.keySet()); } - ArrayList vertex_list = new ArrayList<>(); + ArrayList vertexList = new ArrayList<>(); int mode; ArrayList relative = new ArrayList<>(); boolean inneredges; @Override - protected void init(final Map options, final RegistryAccess regs) + protected void init(Map options, RegistryAccess regs) { super.init(options, regs); @@ -1111,52 +1112,52 @@ protected void init(final Map options, final RegistryAccess regs) if (options.get("points") instanceof final AbstractListValue abl) { - abl.forEach(x -> vertex_list.add(vecFromValue(x))); + abl.forEach(x -> vertexList.add(vecFromValue(x))); } - final String _mode = options.getOrDefault("mode", optional.get("mode")).getString(); + String modeOption = options.getOrDefault("mode", optional.get("mode")).getString(); inneredges = options.getOrDefault("inner", optional.get("inner")).getBoolean(); - if (vertex_list.size() < 3) + if (vertexList.size() < 3) { - throw new IllegalArgumentException("Unexpected vertex list size: " + vertex_list.size()); + throw new IllegalArgumentException("Unexpected vertex list size: " + vertexList.size()); } - else if (vertex_list.size() < 4) + else if (vertexList.size() < 4) { inneredges = false; } - if ("polygon".equals(_mode)) + if ("polygon".equals(modeOption)) { - mode = 6; + this.mode = 6; } - else if ("strip".equals(_mode)) + else if ("strip".equals(modeOption)) { - mode = 5; + this.mode = 5; } - else if ("triangles".equals(_mode)) + else if ("triangles".equals(modeOption)) { - mode = 4; - if (vertex_list.size() % 3 != 0) + this.mode = 4; + if (vertexList.size() % 3 != 0) { - throw new IllegalArgumentException("Unexpected vertex list size: " + vertex_list.size()); + throw new IllegalArgumentException("Unexpected vertex list size: " + vertexList.size()); } } if (options.getOrDefault("relative", optional.get("relative")) instanceof final AbstractListValue abl) { - final Iterator it = abl.iterator(); - for (long i = 0L; i < vertex_list.size(); i++) + Iterator it = abl.iterator(); + for (long i = 0L; i < vertexList.size(); i++) { relative.add(it.hasNext() && it.next().getBoolean());//if part of it got defined. } } else if (options.getOrDefault("relative", optional.get("relative")) instanceof final BooleanValue boolv) { - for (long i = 0L; i < vertex_list.size(); i++) + for (long i = 0L; i < vertexList.size(); i++) { relative.add(boolv.getBoolean());//if it is a boolean. } } else { - for (long i = 0L; i < vertex_list.size(); i++) + for (long i = 0L; i < vertexList.size(); i++) { relative.add(true);//if there is nothing defined at all. } @@ -1191,7 +1192,7 @@ private Line() Vec3 to; @Override - protected void init(final Map options, final RegistryAccess regs) + protected void init(Map options, RegistryAccess regs) { super.init(options, regs); from = vecFromValue(options.get("from")); @@ -1201,7 +1202,7 @@ protected void init(final Map options, final RegistryAccess regs) @Override public Consumer alternative() { - final double density = Math.max(2.0, from.distanceTo(to) / 50) / (a + 0.1); + double density = Math.max(2.0, from.distanceTo(to) / 50) / (a + 0.1); return p -> { if (p.level.dimension() == shapeDimension) @@ -1218,7 +1219,7 @@ public Consumer alternative() } @Override - public long calcKey(final RegistryAccess regs) + public long calcKey(RegistryAccess regs) { long hash = super.calcKey(regs); hash ^= 2; @@ -1259,7 +1260,7 @@ private Sphere() int subdivisions; @Override - protected void init(final Map options, final RegistryAccess regs) + protected void init(Map options, RegistryAccess regs) { super.init(options, regs); center = vecFromValue(options.get("center")); @@ -1277,25 +1278,25 @@ public Consumer alternative() { return p -> { - final int partno = Math.min(1000, 20 * subdivisions); - final RandomSource rand = p.level.getRandom(); - final ServerLevel world = p.getLevel(); - final ParticleOptions particle = replacementParticle(world.registryAccess()); + int partno = Math.min(1000, 20 * subdivisions); + RandomSource rand = p.level.getRandom(); + ServerLevel world = p.getLevel(); + ParticleOptions particle = replacementParticle(world.registryAccess()); - final Vec3 ccenter = relativiseRender(world, center, 0); + Vec3 ccenter = relativiseRender(world, center, 0); - final double ccx = ccenter.x; - final double ccy = ccenter.y; - final double ccz = ccenter.z; + double ccx = ccenter.x; + double ccy = ccenter.y; + double ccz = ccenter.z; for (int i = 0; i < partno; i++) { - final float theta = (float) Math.asin(rand.nextDouble() * 2.0 - 1.0); - final float phi = (float) (2 * Math.PI * rand.nextDouble()); + float theta = (float) Math.asin(rand.nextDouble() * 2.0 - 1.0); + float phi = (float) (2 * Math.PI * rand.nextDouble()); - final double x = radius * Mth.cos(theta) * Mth.cos(phi); - final double y = radius * Mth.cos(theta) * Mth.sin(phi); - final double z = radius * Mth.sin(theta); + 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); @@ -1304,7 +1305,7 @@ public Consumer alternative() } @Override - public long calcKey(final RegistryAccess regs) + public long calcKey(RegistryAccess regs) { long hash = super.calcKey(regs); hash ^= 3; @@ -1353,7 +1354,7 @@ private Cylinder() } @Override - protected void init(final Map options, final RegistryAccess regs) + protected void init(Map options, RegistryAccess regs) { super.init(options, regs); center = vecFromValue(options.get("center")); @@ -1374,26 +1375,26 @@ public Consumer alternative() { return p -> { - final int partno = (int) Math.min(1000, Math.sqrt(20 * subdivisions * (1 + height))); - final RandomSource rand = p.level.getRandom(); - final ServerLevel world = p.getLevel(); - final ParticleOptions particle = replacementParticle(world.registryAccess()); + int partno = (int) Math.min(1000, Math.sqrt(20 * subdivisions * (1 + height))); + RandomSource rand = p.level.getRandom(); + ServerLevel world = p.getLevel(); + ParticleOptions particle = replacementParticle(world.registryAccess()); - final Vec3 ccenter = relativiseRender(world, center, 0); + Vec3 ccenter = relativiseRender(world, center, 0); - final double ccx = ccenter.x; - final double ccy = ccenter.y; - final double ccz = ccenter.z; + double ccx = ccenter.x; + double ccy = ccenter.y; + double ccz = ccenter.z; if (axis == Direction.Axis.Y) { for (int i = 0; i < partno; i++) { - final float d = rand.nextFloat() * height; - final float phi = (float) (2 * Math.PI * rand.nextDouble()); - final double x = radius * Mth.cos(phi); - final double y = d; - final double z = radius * Mth.sin(phi); + float d = rand.nextFloat() * height; + float phi = (float) (2 * Math.PI * rand.nextDouble()); + double x = radius * Mth.cos(phi); + double y = d; + 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); } } @@ -1401,11 +1402,11 @@ else if (axis == Direction.Axis.X) { for (int i = 0; i < partno; i++) { - final float d = rand.nextFloat() * height; - final float phi = (float) (2 * Math.PI * rand.nextDouble()); - final double x = d; - final double y = radius * Mth.cos(phi); - final double z = radius * Mth.sin(phi); + float d = rand.nextFloat() * height; + float phi = (float) (2 * Math.PI * rand.nextDouble()); + double x = d; + 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); } } @@ -1413,11 +1414,11 @@ else if (axis == Direction.Axis.X) { for (int i = 0; i < partno; i++) { - final float d = rand.nextFloat() * height; - final float phi = (float) (2 * Math.PI * rand.nextDouble()); - final double x = radius * Mth.sin(phi); - final double y = radius * Mth.cos(phi); - final double z = d; + float d = rand.nextFloat() * height; + float phi = (float) (2 * Math.PI * rand.nextDouble()); + double x = radius * Mth.sin(phi); + double y = radius * Mth.cos(phi); + double z = d; world.sendParticles(p, particle, true, x + ccx, y + ccy, z + ccz, 1, 0.0, 0.0, 0.0, 0.0); } } @@ -1425,7 +1426,7 @@ else if (axis == Direction.Axis.X) } @Override - public long calcKey(final RegistryAccess regs) + public long calcKey(RegistryAccess regs) { long hash = super.calcKey(regs); hash ^= 4; @@ -1445,7 +1446,7 @@ public long calcKey(final RegistryAccess regs) public abstract static class Param { - public static Map of = new HashMap() + public static final Map of = new HashMap<>() {{ put("mode", new StringChoiceParam("mode", "polygon", "strip", "triangles")); put("relative", new OptionalBoolListParam("relative")); @@ -1467,7 +1468,7 @@ public abstract static class Param "FIXED") { @Override - public Value validate(final Map o, final MinecraftServer s, final Value v) + public Value validate(Map o, MinecraftServer s, Value v) { return super.validate(o, s, new StringValue(v.getString().toUpperCase(Locale.ROOT))); } @@ -1492,7 +1493,7 @@ public Value validate(final Map o, final MinecraftServer s, final put("scale", new Vec3Param("scale", false) { @Override - public Value validate(final java.util.Map options, final MinecraftServer server, Value value) + public Value validate(java.util.Map options, MinecraftServer server, Value value) { if (value instanceof final NumericValue vn) { @@ -1525,11 +1526,12 @@ public Value validate(final java.util.Map options, final Minecraf }}; protected String id; - protected Param(final String id) + protected Param(String id) { this.id = id; } + @Nullable public abstract Tag toTag(Value value); //validates value, returning null if not necessary to keep it and serialize public abstract Value validate(Map options, MinecraftServer server, Value value); // makes sure the value is proper @@ -1539,19 +1541,19 @@ protected Param(final String id) public static class OptionalBoolListParam extends Param { - public OptionalBoolListParam(final String id) + public OptionalBoolListParam(String id) { super(id); } @Override - public Tag toTag(final Value value) + public Tag toTag(Value value) { return value.toTag(true); } @Override - public Value decode(final Tag tag, final Level level) + public Value decode(Tag tag, Level level) { if (tag instanceof final ListTag list) { @@ -1565,7 +1567,7 @@ public Value decode(final Tag tag, final Level level) } @Override - public Value validate(final Map options, final MinecraftServer server, final Value value) + public Value validate(Map options, MinecraftServer server, Value value) { if (value instanceof final AbstractListValue lv) { @@ -1581,19 +1583,19 @@ public Value validate(final Map options, final MinecraftServer se public abstract static class StringParam extends Param { - protected StringParam(final String id) + protected StringParam(String id) { super(id); } @Override - public Tag toTag(final Value value) + public Tag toTag(Value value) { return StringTag.valueOf(value.getString()); } @Override - public Value decode(final Tag tag, final Level level) + public Value decode(Tag tag, Level level) { return new StringValue(tag.getAsString()); } @@ -1602,13 +1604,13 @@ public Value decode(final Tag tag, final Level level) public static class BlockParam extends Param { - protected BlockParam(final String id) + protected BlockParam(String id) { super(id); } @Override - public Value validate(final Map options, final MinecraftServer server, final Value value) + public Value validate(Map options, MinecraftServer server, Value value) { if (value instanceof BlockValue) { @@ -1617,13 +1619,14 @@ public Value validate(final Map options, final MinecraftServer se return BlockValue.fromString(value.getString(), server.overworld()); } + @Nullable @Override - public Tag toTag(final Value value) + public Tag toTag(Value value) { if (value instanceof final BlockValue blv) { - final CompoundTag com = NbtUtils.writeBlockState(blv.getBlockState()); - final CompoundTag dataTag = blv.getData(); + CompoundTag com = NbtUtils.writeBlockState(blv.getBlockState()); + CompoundTag dataTag = blv.getData(); if (dataTag != null) { com.put("TileEntityData", dataTag); @@ -1634,41 +1637,41 @@ public Tag toTag(final Value value) } @Override - public Value decode(final Tag tag, final Level level) + public Value decode(Tag tag, Level level) { - final BlockState bs = NbtUtils.readBlockState(level.holderLookup(Registries.BLOCK), (CompoundTag) tag); + BlockState bs = NbtUtils.readBlockState(level.holderLookup(Registries.BLOCK), (CompoundTag) tag); CompoundTag compoundTag2 = null; if (((CompoundTag) tag).contains("TileEntityData", 10)) { compoundTag2 = ((CompoundTag) tag).getCompound("TileEntityData"); } - return new BlockValue(bs, level, null, compoundTag2); + return new BlockValue(bs, compoundTag2); } } public static class ItemParam extends Param { - protected ItemParam(final String id) + protected ItemParam(String id) { super(id); } @Override - public Value validate(final Map options, final MinecraftServer server, final Value value) + public Value validate(Map options, MinecraftServer server, Value value) { - final ItemStack item = ValueConversions.getItemStackFromValue(value, true, server.registryAccess()); + ItemStack item = ValueConversions.getItemStackFromValue(value, true, server.registryAccess()); return new NBTSerializableValue(item.save(new CompoundTag())); } @Override - public Tag toTag(final Value value) + public Tag toTag(Value value) { return ((NBTSerializableValue) value).getTag(); } @Override - public Value decode(final Tag tag, final Level level) + public Value decode(Tag tag, Level level) { return new NBTSerializableValue(tag); } @@ -1676,13 +1679,13 @@ public Value decode(final Tag tag, final Level level) public static class TextParam extends StringParam { - protected TextParam(final String id) + protected TextParam(String id) { super(id); } @Override - public Value validate(final Map options, final MinecraftServer server, final Value value) + public Value validate(Map options, MinecraftServer server, Value value) { return value; } @@ -1691,13 +1694,13 @@ public Value validate(final Map options, final MinecraftServer se public static class FormattedTextParam extends StringParam { - protected FormattedTextParam(final String id) + protected FormattedTextParam(String id) { super(id); } @Override - public Value validate(final Map options, final MinecraftServer server, Value value) + public Value validate(Map options, MinecraftServer server, Value value) { if (!(value instanceof FormattedTextValue)) { @@ -1717,7 +1720,7 @@ public Tag toTag(Value value) } @Override - public Value decode(final Tag tag, final Level level) + public Value decode(Tag tag, Level level) { return FormattedTextValue.deserialize(tag.getAsString()); } @@ -1728,15 +1731,15 @@ public static class StringChoiceParam extends StringParam { private final Set options; - public StringChoiceParam(final String id, final String... options) + public StringChoiceParam(String id, String... options) { super(id); this.options = Sets.newHashSet(options); } - + @Nullable @Override - public Value validate(final Map options, final MinecraftServer server, final Value value) + public Value validate(Map options, MinecraftServer server, Value value) { if (this.options.contains(value.getString())) { @@ -1754,7 +1757,7 @@ protected DimensionParam() } @Override - public Value validate(final Map options, final MinecraftServer server, final Value value) + public Value validate(Map options, MinecraftServer server, Value value) { return value; } @@ -1768,9 +1771,9 @@ protected ShapeParam() } @Override - public Value validate(final Map options, final MinecraftServer server, final Value value) + public Value validate(Map options, MinecraftServer server, Value value) { - final String shape = value.getString(); + String shape = value.getString(); if (!ExpiringShape.shapeProviders.containsKey(shape)) { throw new InternalExpressionException("Unknown shape: " + shape); @@ -1781,13 +1784,13 @@ public Value validate(final Map options, final MinecraftServer se public abstract static class NumericParam extends Param { - protected NumericParam(final String id) + protected NumericParam(String id) { super(id); } @Override - public Value validate(final Map options, final MinecraftServer server, final Value value) + public Value validate(Map options, MinecraftServer server, Value value) { if (!(value instanceof NumericValue)) { @@ -1799,19 +1802,19 @@ public Value validate(final Map options, final MinecraftServer se public static class BoolParam extends NumericParam { - protected BoolParam(final String id) + protected BoolParam(String id) { super(id); } @Override - public Tag toTag(final Value value) + public Tag toTag(Value value) { return ByteTag.valueOf(value.getBoolean()); } @Override - public Value decode(final Tag tag, final Level level) + public Value decode(Tag tag, Level level) { return BooleanValue.of(((ByteTag) tag).getAsByte() > 0); } @@ -1819,19 +1822,19 @@ public Value decode(final Tag tag, final Level level) public static class FloatParam extends NumericParam { - protected FloatParam(final String id) + protected FloatParam(String id) { super(id); } @Override - public Value decode(final Tag tag, final Level level) + public Value decode(Tag tag, Level level) { return new NumericValue(((FloatTag) tag).getAsFloat()); } @Override - public Tag toTag(final Value value) + public Tag toTag(Value value) { return FloatTag.valueOf(NumericValue.asNumber(value, id).getFloat()); } @@ -1839,15 +1842,15 @@ public Tag toTag(final Value value) public abstract static class PositiveParam extends NumericParam { - protected PositiveParam(final String id) + protected PositiveParam(String id) { super(id); } @Override - public Value validate(final Map options, final MinecraftServer server, final Value value) + public Value validate(Map options, MinecraftServer server, Value value) { - final Value ret = super.validate(options, server, value); + Value ret = super.validate(options, server, value); if (((NumericValue) ret).getDouble() <= 0) { throw new InternalExpressionException("'" + id + "' should be positive"); @@ -1858,19 +1861,19 @@ public Value validate(final Map options, final MinecraftServer se public static class PositiveFloatParam extends PositiveParam { - protected PositiveFloatParam(final String id) + protected PositiveFloatParam(String id) { super(id); } @Override - public Value decode(final Tag tag, final Level level) + public Value decode(Tag tag, Level level) { return new NumericValue(((FloatTag) tag).getAsFloat()); } @Override - public Tag toTag(final Value value) + public Tag toTag(Value value) { return FloatTag.valueOf(NumericValue.asNumber(value, id).getFloat()); } @@ -1879,19 +1882,19 @@ public Tag toTag(final Value value) public static class PositiveIntParam extends PositiveParam { - protected PositiveIntParam(final String id) + protected PositiveIntParam(String id) { super(id); } @Override - public Value decode(final Tag tag, final Level level) + public Value decode(Tag tag, Level level) { return new NumericValue(((IntTag) tag).getAsInt()); } @Override - public Tag toTag(final Value value) + public Tag toTag(Value value) { return IntTag.valueOf(NumericValue.asNumber(value, id).getInt()); } @@ -1900,27 +1903,27 @@ public Tag toTag(final Value value) public static class NonNegativeIntParam extends NumericParam { - protected NonNegativeIntParam(final String id) + protected NonNegativeIntParam(String id) { super(id); } @Override - public Value decode(final Tag tag, final Level level) + public Value decode(Tag tag, Level level) { return new NumericValue(((IntTag) tag).getAsInt()); } @Override - public Tag toTag(final Value value) + public Tag toTag(Value value) { return IntTag.valueOf(NumericValue.asNumber(value, id).getInt()); } @Override - public Value validate(final Map options, final MinecraftServer server, final Value value) + public Value validate(Map options, MinecraftServer server, Value value) { - final Value ret = super.validate(options, server, value); + Value ret = super.validate(options, server, value); if (((NumericValue) ret).getDouble() < 0) { throw new InternalExpressionException("'" + id + "' should be non-negative"); @@ -1931,27 +1934,27 @@ public Value validate(final Map options, final MinecraftServer se public static class NonNegativeFloatParam extends NumericParam { - protected NonNegativeFloatParam(final String id) + protected NonNegativeFloatParam(String id) { super(id); } @Override - public Value decode(final Tag tag, final Level level) + public Value decode(Tag tag, Level level) { return new NumericValue(((FloatTag) tag).getAsFloat()); } @Override - public Tag toTag(final Value value) + public Tag toTag(Value value) { return FloatTag.valueOf(NumericValue.asNumber(value, id).getFloat()); } @Override - public Value validate(final Map options, final MinecraftServer server, final Value value) + public Value validate(Map options, MinecraftServer server, Value value) { - final Value ret = super.validate(options, server, value); + Value ret = super.validate(options, server, value); if (((NumericValue) ret).getDouble() < 0) { throw new InternalExpressionException("'" + id + "' should be non-negative"); @@ -1965,19 +1968,19 @@ public static class Vec3Param extends Param { private final boolean roundsUpForBlocks; - protected Vec3Param(final String id, final boolean doesRoundUpForBlocks) + protected Vec3Param(String id, boolean doesRoundUpForBlocks) { super(id); roundsUpForBlocks = doesRoundUpForBlocks; } @Override - public Value validate(final Map options, final MinecraftServer server, final Value value) + public Value validate(Map options, MinecraftServer server, Value value) { return validate(this, options, value, roundsUpForBlocks); } - public static Value validate(final Param p, final Map options, final Value value, final boolean roundsUp) + public static Value validate(Param p, Map options, Value value, boolean roundsUp) { if (value instanceof final BlockValue bv) { @@ -1985,8 +1988,8 @@ public static Value validate(final Param p, final Map options, fi { throw new InternalExpressionException(p.id + " parameter cannot use blocks as positions for relative positioning due to 'follow' attribute being present"); } - final BlockPos pos = bv.getPos(); - final int offset = roundsUp ? 1 : 0; + BlockPos pos = bv.getPos(); + int offset = roundsUp ? 1 : 0; return ListValue.of( new NumericValue(pos.getX() + offset), new NumericValue(pos.getY() + offset), @@ -1995,12 +1998,12 @@ public static Value validate(final Param p, final Map options, fi } if (value instanceof final ListValue list) { - final List values = list.getItems(); + List values = list.getItems(); if (values.size() != 3) { throw new InternalExpressionException("'" + p.id + "' requires 3 numerical values"); } - for (final Value component : values) + for (Value component : values) { if (!(component instanceof NumericValue)) { @@ -2015,7 +2018,7 @@ public static Value validate(final Param p, final Map options, fi { throw new InternalExpressionException(p.id + " parameter cannot use entity as positions for relative positioning due to 'follow' attribute being present"); } - final Entity e = ev.getEntity(); + Entity e = ev.getEntity(); return ListValue.of( new NumericValue(e.getX()), new NumericValue(e.getY()), @@ -2027,9 +2030,9 @@ public static Value validate(final Param p, final Map options, fi } @Override - public Value decode(final Tag tag, final Level level) + public Value decode(Tag tag, Level level) { - final ListTag ctag = (ListTag) tag; + ListTag ctag = (ListTag) tag; return ListValue.of( new NumericValue(ctag.getDouble(0)), new NumericValue(ctag.getDouble(1)), @@ -2038,10 +2041,10 @@ public Value decode(final Tag tag, final Level level) } @Override - public Tag toTag(final Value value) + public Tag toTag(Value value) { - final List lv = ((ListValue) value).getItems(); - final ListTag tag = new ListTag(); + List lv = ((ListValue) value).getItems(); + 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())); @@ -2051,20 +2054,20 @@ public Tag toTag(final Value value) public static class PointsParam extends Param { - public PointsParam(final String id) + public PointsParam(String id) { super(id); } @Override - public Value validate(final Map options, final MinecraftServer server, final Value value) + public Value validate(Map options, MinecraftServer server, Value value) { if (!(value instanceof final ListValue list)) { throw new InternalExpressionException(id + " parameter should be a list"); } - final List points = new ArrayList<>(); - for (final Value point : list.getItems()) + List points = new ArrayList<>(); + for (Value point : list.getItems()) { points.add(Vec3Param.validate(this, options, point, false)); } @@ -2072,13 +2075,13 @@ public Value validate(final Map options, final MinecraftServer se } @Override - public Value decode(final Tag tag, final Level level) + public Value decode(Tag tag, Level level) { - final ListTag ltag = (ListTag) tag; - final List points = new ArrayList<>(); + ListTag ltag = (ListTag) tag; + List points = new ArrayList<>(); for (int i = 0, ll = ltag.size(); i < ll; i++) { - final ListTag ptag = ltag.getList(i); + ListTag ptag = ltag.getList(i); points.add(ListValue.of( new NumericValue(ptag.getDouble(0)), new NumericValue(ptag.getDouble(1)), @@ -2089,14 +2092,14 @@ public Value decode(final Tag tag, final Level level) } @Override - public Tag toTag(final Value pointsValue) + public Tag toTag(Value pointsValue) { - final List lv = ((ListValue) pointsValue).getItems(); - final ListTag ltag = new ListTag(); - for (final Value value : lv) + List lv = ((ListValue) pointsValue).getItems(); + ListTag ltag = new ListTag(); + for (Value value : lv) { - final List coords = ((ListValue) value).getItems(); - final ListTag tag = new ListTag(); + List coords = ((ListValue) value).getItems(); + ListTag tag = new ListTag(); tag.add(DoubleTag.valueOf(NumericValue.asNumber(coords.get(0), "x").getDouble())); tag.add(DoubleTag.valueOf(NumericValue.asNumber(coords.get(1), "y").getDouble())); tag.add(DoubleTag.valueOf(NumericValue.asNumber(coords.get(2), "z").getDouble())); @@ -2109,19 +2112,19 @@ public Tag toTag(final Value pointsValue) public static class ColorParam extends NumericParam { - protected ColorParam(final String id) + protected ColorParam(String id) { super(id); } @Override - public Value decode(final Tag tag, final Level level) + public Value decode(Tag tag, Level level) { return new NumericValue(((IntTag) tag).getAsInt()); } @Override - public Tag toTag(final Value value) + public Tag toTag(Value value) { return IntTag.valueOf(NumericValue.asNumber(value, id).getInt()); } @@ -2130,25 +2133,25 @@ public Tag toTag(final Value value) public static class EntityParam extends Param { - protected EntityParam(final String id) + protected EntityParam(String id) { super(id); } @Override - public Tag toTag(final Value value) + public Tag toTag(Value value) { return IntTag.valueOf(NumericValue.asNumber(value, id).getInt()); } @Override - public Value validate(final Map options, final MinecraftServer server, final Value value) + public Value validate(Map options, MinecraftServer server, Value value) { if (value instanceof final EntityValue ev) { return new NumericValue(ev.getEntity().getId()); } - final ServerPlayer 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"); @@ -2157,13 +2160,13 @@ public Value validate(final Map options, final MinecraftServer se } @Override - public Value decode(final Tag tag, final Level level) + public Value decode(Tag tag, Level level) { return new NumericValue(((IntTag) tag).getAsInt()); } } - private static boolean isStraight(final Vec3 from, final Vec3 to, final 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)) { @@ -2172,15 +2175,15 @@ private static boolean isStraight(final Vec3 from, final Vec3 to, final double d return false; } - private static int drawOptimizedParticleLine(final List playerList, final ParticleOptions particle, final Vec3 from, final Vec3 to, final double density) + private static int drawOptimizedParticleLine(List playerList, ParticleOptions particle, Vec3 from, Vec3 to, double density) { - final double distance = from.distanceTo(to); - final int particles = (int) (distance / density); - final Vec3 towards = to.subtract(from); + double distance = from.distanceTo(to); + int particles = (int) (distance / density); + Vec3 towards = to.subtract(from); int parts = 0; - for (final ServerPlayer player : playerList) + for (ServerPlayer player : playerList) { - final ServerLevel world = player.getLevel(); + 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); @@ -2193,11 +2196,11 @@ private static int drawOptimizedParticleLine(final List playerList int divider = 6; while (particles / divider > 1) { - final int center = (divider * 2) / 3; - final int dev = 2 * divider; - for (final ServerPlayer player : playerList) + int center = (divider * 2) / 3; + int dev = 2 * divider; + for (ServerPlayer player : playerList) { - final ServerLevel world = player.getLevel(); + 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); @@ -2211,9 +2214,9 @@ private static int drawOptimizedParticleLine(final List playerList return parts; } - public static int drawParticleLine(final List players, final ParticleOptions particle, final Vec3 from, final Vec3 to, final double density) + public static int drawParticleLine(List players, ParticleOptions particle, Vec3 from, Vec3 to, double density) { - final double distance = from.distanceToSqr(to); + double distance = from.distanceToSqr(to); if (distance == 0) { return 0; @@ -2221,13 +2224,13 @@ public static int drawParticleLine(final List players, final Parti int pcount = 0; if (distance < 100) { - final RandomSource rand = players.get(0).level.random; - final int particles = (int) (distance / density) + 1; - final Vec3 towards = to.subtract(from); + RandomSource rand = players.get(0).level.random; + int particles = (int) (distance / density) + 1; + Vec3 towards = to.subtract(from); for (int i = 0; i < particles; i++) { - final Vec3 at = from.add(towards.scale(rand.nextDouble())); - for (final ServerPlayer player : players) + Vec3 at = from.add(towards.scale(rand.nextDouble())); + for (ServerPlayer player : players) { player.getLevel().sendParticles(player, particle, true, at.x, at.y, at.z, 1, @@ -2242,13 +2245,13 @@ public static int drawParticleLine(final List players, final Parti { return drawOptimizedParticleLine(players, particle, from, to, density); } - final Vec3 incvec = to.subtract(from).scale(2 * density / Math.sqrt(distance)); + Vec3 incvec = to.subtract(from).scale(2 * density / Math.sqrt(distance)); for (Vec3 delta = new Vec3(0.0, 0.0, 0.0); delta.lengthSqr() < distance; delta = delta.add(incvec.scale(Sys.randomizer.nextFloat()))) { - for (final ServerPlayer player : players) + for (ServerPlayer player : players) { player.getLevel().sendParticles(player, particle, true, delta.x + from.x, delta.y + from.y, delta.z + from.z, 1, diff --git a/src/main/java/carpet/script/utils/ShapesRenderer.java b/src/main/java/carpet/script/utils/ShapesRenderer.java index 3505513fc3..e2336c33cb 100644 --- a/src/main/java/carpet/script/utils/ShapesRenderer.java +++ b/src/main/java/carpet/script/utils/ShapesRenderer.java @@ -73,25 +73,25 @@ public class ShapesRenderer put("item", (c, s) -> new RenderedSprite(c, s, true)); }}; - public ShapesRenderer(final Minecraft minecraftClient) + public ShapesRenderer(Minecraft minecraftClient) { this.client = minecraftClient; shapes = new HashMap<>(); labels = new HashMap<>(); } - public void render(final PoseStack matrices, final Camera camera, final float partialTick) + public void render(PoseStack matrices, Camera camera, float partialTick) { - final Runnable token = Carpet.startProfilerSection("Scarpet client"); + Runnable token = Carpet.startProfilerSection("Scarpet client"); //Camera camera = this.client.gameRenderer.getCamera(); - final ClientLevel iWorld = this.client.level; - final ResourceKey dimensionType = iWorld.dimension(); + ClientLevel iWorld = this.client.level; + ResourceKey dimensionType = iWorld.dimension(); if ((shapes.get(dimensionType) == null || shapes.get(dimensionType).isEmpty()) && (labels.get(dimensionType) == null || labels.get(dimensionType).isEmpty())) { return; } - final long currentTime = client.level.getGameTime(); + long currentTime = client.level.getGameTime(); RenderSystem.enableDepthTest(); RenderSystem.setShader(GameRenderer::getPositionColorShader); RenderSystem.depthFunc(515); @@ -107,21 +107,21 @@ public void render(final PoseStack matrices, final Camera camera, final float pa //RenderSystem.polygonOffset(-3f, -3f); //RenderSystem.enablePolygonOffset(); - final Tesselator tessellator = Tesselator.getInstance(); - final BufferBuilder bufferBuilder = tessellator.getBuilder(); + Tesselator tessellator = Tesselator.getInstance(); + BufferBuilder bufferBuilder = tessellator.getBuilder(); // render - final double cameraX = camera.getPosition().x; - final double cameraY = camera.getPosition().y; - final double cameraZ = camera.getPosition().z; - final boolean entityBoxes = client.getEntityRenderDispatcher().shouldRenderHitBoxes(); + double cameraX = camera.getPosition().x; + double cameraY = camera.getPosition().y; + double cameraZ = camera.getPosition().z; + boolean entityBoxes = client.getEntityRenderDispatcher().shouldRenderHitBoxes(); - if (shapes.size() != 0) + if (!shapes.isEmpty()) { shapes.get(dimensionType).long2ObjectEntrySet().removeIf( entry -> entry.getValue().isExpired(currentTime) ); - final PoseStack matrixStack = RenderSystem.getModelViewStack(); + PoseStack matrixStack = RenderSystem.getModelViewStack(); matrixStack.pushPose(); matrixStack.mulPoseMatrix(matrices.last().pose()); RenderSystem.applyModelViewMatrix(); @@ -147,7 +147,7 @@ public void render(final PoseStack matrices, final Camera camera, final float pa RenderSystem.applyModelViewMatrix(); } - if (labels.size() != 0) + if (!labels.isEmpty()) { labels.get(dimensionType).long2ObjectEntrySet().removeIf( entry -> entry.getValue().isExpired(currentTime) @@ -166,9 +166,9 @@ public void render(final PoseStack matrices, final Camera camera, final float pa token.run(); } - public void addShapes(final ListTag tag) + public void addShapes(ListTag tag) { - final Runnable token = Carpet.startProfilerSection("Scarpet client"); + Runnable token = Carpet.startProfilerSection("Scarpet client"); for (int i = 0, count = tag.size(); i < count; i++) { addShape(tag.getCompound(i)); @@ -176,14 +176,14 @@ public void addShapes(final ListTag tag) token.run(); } - public void addShape(final CompoundTag tag) + public void addShape(CompoundTag tag) { - final ShapeDispatcher.ExpiringShape shape = ShapeDispatcher.fromTag(tag, client.level); + ShapeDispatcher.ExpiringShape shape = ShapeDispatcher.fromTag(tag, client.level); if (shape == null) { return; } - final BiFunction> shapeFactory; + BiFunction> shapeFactory; shapeFactory = renderedShapes.get(tag.getString("shape")); if (shapeFactory == null) { @@ -191,12 +191,12 @@ public void addShape(final CompoundTag tag) } else { - final RenderedShape rshape = shapeFactory.apply(client, shape); - final ResourceKey dim = shape.shapeDimension; - final long key = rshape.key(); - final Map, Long2ObjectOpenHashMap>> container = + RenderedShape rshape = shapeFactory.apply(client, shape); + ResourceKey dim = shape.shapeDimension; + long key = rshape.key(); + Map, Long2ObjectOpenHashMap>> container = rshape.stageDeux() ? labels : shapes; - final RenderedShape existing = container.computeIfAbsent(dim, d -> new Long2ObjectOpenHashMap<>()).get(key); + RenderedShape existing = container.computeIfAbsent(dim, d -> new Long2ObjectOpenHashMap<>()).get(key); if (existing != null) { // promoting previous shape existing.promoteWith(rshape); @@ -217,7 +217,7 @@ public void reset() public void renewShapes() { - final Runnable token = Carpet.startProfilerSection("Scarpet client"); + Runnable token = Carpet.startProfilerSection("Scarpet client"); shapes.values().forEach(el -> el.values().forEach(shape -> shape.expiryTick++)); labels.values().forEach(el -> el.values().forEach(shape -> shape.expiryTick++)); @@ -229,15 +229,15 @@ public abstract static class RenderedShape dim) + public boolean shouldRender(ResourceKey dim) { if (shape.followEntity <= 0) { @@ -277,7 +277,7 @@ public boolean stageDeux() return false; } - public void promoteWith(final RenderedShape rshape) + public void promoteWith(RenderedShape rshape) { expiryTick = rshape.expiryTick; } @@ -293,7 +293,7 @@ public static class RenderedSprite extends RenderedShape> 16 & 0xFF) / 255.0F; - final float green = (color >> 8 & 0xFF) / 255.0F; - final float blue = (color & 0xFF) / 255.0F; + float red = (color >> 16 & 0xFF) / 255.0F; + float green = (color >> 8 & 0xFF) / 255.0F; + float blue = (color & 0xFF) / 255.0F; client.getBlockRenderer().getModelRenderer().renderModel(matrices.last(), immediate.getBuffer(ItemBlockRenderTypes.getRenderType(blockState, false)), blockState, bakedModel, red, green, blue, light, OverlayTexture.NO_OVERLAY); } @@ -406,7 +406,7 @@ public void renderLines(final PoseStack matrices, final Tesselator tessellator, { if (BlockEntity != null) { - final BlockEntityRenderer blockEntityRenderer = client.getBlockEntityRenderDispatcher().getRenderer(BlockEntity); + BlockEntityRenderer blockEntityRenderer = client.getBlockEntityRenderDispatcher().getRenderer(BlockEntity); if (blockEntityRenderer != null) { blockEntityRenderer.render(BlockEntity, partialTick, @@ -440,19 +440,19 @@ public boolean stageDeux() } // copy and modifiy a bit from net.minecraft.client.renderer.blockentity.ShulkerBoxRenderer.render - public void sbrender(final ShulkerBoxBlockEntity shulkerBoxBlockEntity, final float f, final PoseStack poseStack, final MultiBufferSource multiBufferSource, final int i, final int j) + public void sbrender(ShulkerBoxBlockEntity shulkerBoxBlockEntity, float f, PoseStack poseStack, MultiBufferSource multiBufferSource, int i, int j) { Direction direction = Direction.UP; if (shulkerBoxBlockEntity.hasLevel()) { - final BlockState blockState = shulkerBoxBlockEntity.getBlockState(); + BlockState blockState = shulkerBoxBlockEntity.getBlockState(); if (blockState.getBlock() instanceof ShulkerBoxBlock) { direction = blockState.getValue(ShulkerBoxBlock.FACING); } } - final DyeColor dyeColor = shulkerBoxBlockEntity.getColor(); - final Material material; + DyeColor dyeColor = shulkerBoxBlockEntity.getColor(); + Material material; if (dyeColor == null) { material = Sheets.DEFAULT_SHULKER_TEXTURE_LOCATION; @@ -468,11 +468,11 @@ public void sbrender(final ShulkerBoxBlockEntity shulkerBoxBlockEntity, final fl poseStack.mulPose(direction.getRotation()); poseStack.scale(1.0F, -1.0F, -1.0F); poseStack.translate(0.0, -1.0, 0.0); - final ShulkerModel model = VanillaClient.ShulkerBoxRenderer_model(client.getBlockEntityRenderDispatcher().getRenderer(shulkerBoxBlockEntity)); - final ModelPart modelPart = model.getLid(); + ShulkerModel model = VanillaClient.ShulkerBoxRenderer_model(client.getBlockEntityRenderDispatcher().getRenderer(shulkerBoxBlockEntity)); + ModelPart modelPart = model.getLid(); modelPart.setPos(0.0F, 24.0F - shulkerBoxBlockEntity.getProgress(f) * 0.5F * 16.0F, 0.0F); modelPart.yRot = 270.0F * shulkerBoxBlockEntity.getProgress(f) * (float) (Math.PI / 180.0); - final VertexConsumer vertexConsumer = material.buffer(multiBufferSource, RenderType::entityCutoutNoCull); + VertexConsumer vertexConsumer = material.buffer(multiBufferSource, RenderType::entityCutoutNoCull); model.renderToBuffer(poseStack, vertexConsumer, i, j, 1.0F, 1.0F, 1.0F, 1.0F); poseStack.popPose(); } @@ -482,21 +482,21 @@ public void sbrender(final ShulkerBoxBlockEntity shulkerBoxBlockEntity, final fl public static class RenderedText extends RenderedShape { - protected RenderedText(final Minecraft client, final ShapeDispatcher.ExpiringShape shape) + protected RenderedText(Minecraft client, ShapeDispatcher.ExpiringShape shape) { super(client, (ShapeDispatcher.DisplayedText) shape); } @Override - public void renderLines(final PoseStack matrices, final Tesselator tessellator, final BufferBuilder builder, final double cx, final double cy, final double cz, final float partialTick) + public void renderLines(PoseStack matrices, Tesselator tessellator, BufferBuilder builder, double cx, double cy, double cz, float partialTick) { if (shape.a == 0.0) { return; } - final Vec3 v1 = shape.relativiseRender(client.level, shape.pos, partialTick); - final Camera camera1 = client.gameRenderer.getMainCamera(); - final Font textRenderer = client.font; + Vec3 v1 = shape.relativiseRender(client.level, shape.pos, partialTick); + Camera camera1 = client.gameRenderer.getMainCamera(); + Font textRenderer = client.font; if (shape.doublesided) { RenderSystem.disableCull(); @@ -538,7 +538,7 @@ else if (shape.align == 1) { text_x = (float) (-textRenderer.width(shape.value.getString())); } - final MultiBufferSource.BufferSource immediate = MultiBufferSource.immediate(builder); + MultiBufferSource.BufferSource immediate = MultiBufferSource.immediate(builder); textRenderer.drawInBatch(shape.value, text_x, 0.0F, shape.textcolor, false, matrices.last().pose(), immediate, false, shape.textbck, 15728880); immediate.endBatch(); matrices.popPose(); @@ -552,14 +552,14 @@ public boolean stageDeux() } @Override - public void promoteWith(final RenderedShape rshape) + public void promoteWith(RenderedShape rshape) { super.promoteWith(rshape); try { this.shape.value = ((ShapeDispatcher.DisplayedText) rshape.shape).value; } - catch (final ClassCastException ignored) + catch (ClassCastException ignored) { CarpetScriptServer.LOG.error("shape " + rshape.shape.getClass() + " cannot cast to a Label"); } @@ -569,20 +569,20 @@ public void promoteWith(final RenderedShape rshape) public static class RenderedBox extends RenderedShape { - private RenderedBox(final Minecraft client, final ShapeDispatcher.ExpiringShape shape) + private RenderedBox(Minecraft client, ShapeDispatcher.ExpiringShape shape) { super(client, (ShapeDispatcher.Box) shape); } @Override - public void renderLines(final PoseStack matrices, final Tesselator tessellator, final BufferBuilder bufferBuilder, final double cx, final double cy, final double cz, final float partialTick) + public void renderLines(PoseStack matrices, Tesselator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) { if (shape.a == 0.0) { return; } - final Vec3 v1 = shape.relativiseRender(client.level, shape.from, partialTick); - final Vec3 v2 = shape.relativiseRender(client.level, shape.to, partialTick); + Vec3 v1 = shape.relativiseRender(client.level, shape.from, partialTick); + Vec3 v2 = shape.relativiseRender(client.level, shape.to, partialTick); drawBoxWireGLLines(tessellator, bufferBuilder, (float) (v1.x - cx - renderEpsilon), (float) (v1.y - cy - renderEpsilon), (float) (v1.z - cz - renderEpsilon), (float) (v2.x - cx + renderEpsilon), (float) (v2.y - cy + renderEpsilon), (float) (v2.z - cz + renderEpsilon), @@ -592,14 +592,14 @@ public void renderLines(final PoseStack matrices, final Tesselator tessellator, } @Override - public void renderFaces(final Tesselator tessellator, final BufferBuilder bufferBuilder, final double cx, final double cy, final double cz, final float partialTick) + public void renderFaces(Tesselator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) { if (shape.fa == 0.0) { return; } - final Vec3 v1 = shape.relativiseRender(client.level, shape.from, partialTick); - final Vec3 v2 = shape.relativiseRender(client.level, shape.to, partialTick); + Vec3 v1 = shape.relativiseRender(client.level, shape.from, partialTick); + Vec3 v2 = shape.relativiseRender(client.level, shape.to, partialTick); // consider using built-ins //DebugRenderer.drawBox(new Box(v1.x, v1.y, v1.z, v2.x, v2.y, v2.z), 0.5f, 0.5f, 0.5f, 0.5f);//shape.r, shape.g, shape.b, shape.a); drawBoxFaces(tessellator, bufferBuilder, @@ -613,16 +613,16 @@ public void renderFaces(final Tesselator tessellator, final BufferBuilder buffer public static class RenderedLine extends RenderedShape { - public RenderedLine(final Minecraft client, final ShapeDispatcher.ExpiringShape shape) + public RenderedLine(Minecraft client, ShapeDispatcher.ExpiringShape shape) { super(client, (ShapeDispatcher.Line) shape); } @Override - public void renderLines(final PoseStack matrices, final Tesselator tessellator, final BufferBuilder bufferBuilder, final double cx, final double cy, final double cz, final float partialTick) + public void renderLines(PoseStack matrices, Tesselator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) { - final Vec3 v1 = shape.relativiseRender(client.level, shape.from, partialTick); - final Vec3 v2 = shape.relativiseRender(client.level, shape.to, partialTick); + Vec3 v1 = shape.relativiseRender(client.level, shape.from, partialTick); + Vec3 v2 = shape.relativiseRender(client.level, shape.to, partialTick); drawLine(tessellator, bufferBuilder, (float) (v1.x - cx - renderEpsilon), (float) (v1.y - cy - renderEpsilon), (float) (v1.z - cz - renderEpsilon), (float) (v2.x - cx + renderEpsilon), (float) (v2.y - cy + renderEpsilon), (float) (v2.z - cz + renderEpsilon), @@ -636,13 +636,13 @@ public static class RenderedPolyface extends RenderedShape 0; i -= 2) { - vec = shape.vertex_list.get(i); + vec = shape.vertexList.get(i); if (shape.relative.get(i)) { vec = shape.relativiseRender(client.level, vec, partialTick); @@ -754,9 +754,9 @@ public void renderLines(final PoseStack matrices, final Tesselator tessellator, } if (shape.inneredges) { - for (i = 2; i < shape.vertex_list.size() - 1; i++) + for (i = 2; i < shape.vertexList.size() - 1; i++) { - vec = shape.vertex_list.get(i); + vec = shape.vertexList.get(i); if (shape.relative.get(i)) { vec = shape.relativiseRender(client.level, vec, partialTick); @@ -770,21 +770,21 @@ public void renderLines(final PoseStack matrices, final Tesselator tessellator, if (shape.mode == 4) { builder.begin(VertexFormat.Mode.DEBUG_LINES, DefaultVertexFormat.POSITION_COLOR); - for (int i = 0; i < shape.vertex_list.size(); i++) + for (int i = 0; i < shape.vertexList.size(); i++) { - Vec3 vecA = shape.vertex_list.get(i); + Vec3 vecA = shape.vertexList.get(i); if (shape.relative.get(i)) { vecA = shape.relativiseRender(client.level, vecA, partialTick); } i++; - Vec3 vecB = shape.vertex_list.get(i); + Vec3 vecB = shape.vertexList.get(i); if (shape.relative.get(i)) { vecB = shape.relativiseRender(client.level, vecB, partialTick); } i++; - Vec3 vecC = shape.vertex_list.get(i); + Vec3 vecC = shape.vertexList.get(i); if (shape.relative.get(i)) { vecC = shape.relativiseRender(client.level, vecC, partialTick); @@ -805,19 +805,19 @@ public void renderLines(final PoseStack matrices, final Tesselator tessellator, public static class RenderedSphere extends RenderedShape { - public RenderedSphere(final Minecraft client, final ShapeDispatcher.ExpiringShape shape) + public RenderedSphere(Minecraft client, ShapeDispatcher.ExpiringShape shape) { super(client, (ShapeDispatcher.Sphere) shape); } @Override - public void renderLines(final PoseStack matrices, final Tesselator tessellator, final BufferBuilder bufferBuilder, final double cx, final double cy, final double cz, final float partialTick) + public void renderLines(PoseStack matrices, Tesselator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) { if (shape.a == 0.0) { return; } - final Vec3 vc = shape.relativiseRender(client.level, shape.center, partialTick); + Vec3 vc = shape.relativiseRender(client.level, shape.center, partialTick); drawSphereWireframe(tessellator, bufferBuilder, (float) (vc.x - cx), (float) (vc.y - cy), (float) (vc.z - cz), (float) (shape.radius + renderEpsilon), shape.subdivisions, @@ -825,13 +825,13 @@ public void renderLines(final PoseStack matrices, final Tesselator tessellator, } @Override - public void renderFaces(final Tesselator tessellator, final BufferBuilder bufferBuilder, final double cx, final double cy, final double cz, final float partialTick) + public void renderFaces(Tesselator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) { if (shape.fa == 0.0) { return; } - final Vec3 vc = shape.relativiseRender(client.level, shape.center, partialTick); + Vec3 vc = shape.relativiseRender(client.level, shape.center, partialTick); drawSphereFaces(tessellator, bufferBuilder, (float) (vc.x - cx), (float) (vc.y - cy), (float) (vc.z - cz), (float) (shape.radius + renderEpsilon), shape.subdivisions, @@ -841,20 +841,20 @@ public void renderFaces(final Tesselator tessellator, final BufferBuilder buffer public static class RenderedCylinder extends RenderedShape { - public RenderedCylinder(final Minecraft client, final ShapeDispatcher.ExpiringShape shape) + public RenderedCylinder(Minecraft client, ShapeDispatcher.ExpiringShape shape) { super(client, (ShapeDispatcher.Cylinder) shape); } @Override - public void renderLines(final PoseStack matrices, final Tesselator tessellator, final BufferBuilder bufferBuilder, final double cx, final double cy, final double cz, final float partialTick) + public void renderLines(PoseStack matrices, Tesselator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) { if (shape.a == 0.0) { return; } - final Vec3 vc = shape.relativiseRender(client.level, shape.center, partialTick); - final double dir = Mth.sign(shape.height); + Vec3 vc = shape.relativiseRender(client.level, shape.center, partialTick); + double dir = Mth.sign(shape.height); drawCylinderWireframe(tessellator, bufferBuilder, (float) (vc.x - cx - dir * renderEpsilon), (float) (vc.y - cy - dir * renderEpsilon), (float) (vc.z - cz - dir * renderEpsilon), (float) (shape.radius + renderEpsilon), (float) (shape.height + 2 * dir * renderEpsilon), shape.axis, @@ -864,14 +864,14 @@ public void renderLines(final PoseStack matrices, final Tesselator tessellator, } @Override - public void renderFaces(final Tesselator tessellator, final BufferBuilder bufferBuilder, final double cx, final double cy, final double cz, final float partialTick) + public void renderFaces(Tesselator tessellator, BufferBuilder bufferBuilder, double cx, double cy, double cz, float partialTick) { if (shape.fa == 0.0) { return; } - final Vec3 vc = shape.relativiseRender(client.level, shape.center, partialTick); - final double dir = Mth.sign(shape.height); + Vec3 vc = shape.relativiseRender(client.level, shape.center, partialTick); + double dir = Mth.sign(shape.height); drawCylinderFaces(tessellator, bufferBuilder, (float) (vc.x - cx - dir * renderEpsilon), (float) (vc.y - cy - dir * renderEpsilon), (float) (vc.z - cz - dir * renderEpsilon), (float) (shape.radius + renderEpsilon), (float) (shape.height + 2 * dir * renderEpsilon), shape.axis, @@ -882,7 +882,7 @@ public void renderFaces(final Tesselator tessellator, final BufferBuilder buffer // some raw shit - public static void drawLine(final Tesselator tessellator, final BufferBuilder builder, final float x1, final float y1, final float z1, final float x2, final float y2, final float z2, final float red1, final float grn1, final float blu1, final float alpha) + public static void drawLine(Tesselator tessellator, BufferBuilder builder, float x1, float y1, float z1, float x2, float y2, float z2, float red1, float grn1, float blu1, float alpha) { builder.begin(VertexFormat.Mode.DEBUG_LINES, DefaultVertexFormat.POSITION_COLOR); builder.vertex(x1, y1, z1).color(red1, grn1, blu1, alpha).endVertex(); @@ -891,11 +891,11 @@ public static void drawLine(final Tesselator tessellator, final BufferBuilder bu } public static void drawBoxWireGLLines( - final Tesselator tessellator, final BufferBuilder builder, - final float x1, final float y1, final float z1, - final float x2, final float y2, final float z2, - final boolean xthick, final boolean ythick, final boolean zthick, - final float red1, final float grn1, final float blu1, final float alpha, final float red2, final float grn2, final float blu2) + Tesselator tessellator, BufferBuilder builder, + float x1, float y1, float z1, + float x2, float y2, float z2, + boolean xthick, boolean ythick, boolean zthick, + float red1, float grn1, float blu1, float alpha, float red2, float grn2, float blu2) { builder.begin(VertexFormat.Mode.DEBUG_LINES, DefaultVertexFormat.POSITION_COLOR); if (xthick) @@ -944,11 +944,11 @@ public static void drawBoxWireGLLines( } public static void drawBoxFaces( - final Tesselator tessellator, final BufferBuilder builder, - final float x1, final float y1, final float z1, - final float x2, final float y2, final float z2, - final boolean xthick, final boolean ythick, final boolean zthick, - final float red1, final float grn1, final float blu1, final float alpha) + Tesselator tessellator, BufferBuilder builder, + float x1, float y1, float z1, + float x2, float y2, float z2, + boolean xthick, boolean ythick, boolean zthick, + float red1, float grn1, float blu1, float alpha) { builder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); @@ -1004,14 +1004,14 @@ public static void drawBoxFaces( tessellator.end(); } - public static void drawCylinderWireframe(final Tesselator tessellator, final BufferBuilder builder, - final float cx, final float cy, final float cz, - final float r, final float h, final Direction.Axis axis, final int subd, final boolean isFlat, - final float red, final float grn, final float blu, final float alpha) + public static void drawCylinderWireframe(Tesselator tessellator, BufferBuilder builder, + float cx, float cy, float cz, + float r, float h, Direction.Axis axis, int subd, boolean isFlat, + float red, float grn, float blu, float alpha) { - final float step = (float) Math.PI / (subd / 2); - final int num_steps180 = (int) (Math.PI / step) + 1; - final int num_steps360 = (int) (2 * Math.PI / step); + float step = (float) Math.PI / (subd / 2); + int num_steps180 = (int) (Math.PI / step) + 1; + int num_steps360 = (int) (2 * Math.PI / step); int hsteps = 1; float hstep = 1.0f; if (!isFlat) @@ -1024,14 +1024,14 @@ public static void drawCylinderWireframe(final Tesselator tessellator, final Buf { for (int dh = 0; dh < hsteps; dh++) { - final float hh = dh * hstep; + float hh = dh * hstep; builder.begin(VertexFormat.Mode.DEBUG_LINE_STRIP, DefaultVertexFormat.POSITION_COLOR); // line loop to line strip for (int i = 0; i <= num_steps360 + 1; i++) { - final float theta = step * i; - final float x = r * Mth.cos(theta); - final float y = hh; - final float z = r * Mth.sin(theta); + float theta = step * i; + float x = r * Mth.cos(theta); + float y = hh; + float z = r * Mth.sin(theta); builder.vertex(x + cx, y + cy, z + cz).color(red, grn, blu, alpha).endVertex(); } tessellator.end(); @@ -1042,10 +1042,10 @@ public static void drawCylinderWireframe(final Tesselator tessellator, final Buf for (int i = 0; i <= num_steps180; i++) { builder.begin(VertexFormat.Mode.DEBUG_LINE_STRIP, DefaultVertexFormat.POSITION_COLOR); // line loop to line strip - final float theta = step * i; - final float x = r * Mth.cos(theta); + float theta = step * i; + float x = r * Mth.cos(theta); - final float z = r * Mth.sin(theta); + float z = r * Mth.sin(theta); builder.vertex(cx - x, cy + 0, cz + z).color(red, grn, blu, alpha).endVertex(); builder.vertex(cx + x, cy + 0, cz - z).color(red, grn, blu, alpha).endVertex(); @@ -1060,9 +1060,9 @@ public static void drawCylinderWireframe(final Tesselator tessellator, final Buf builder.begin(VertexFormat.Mode.DEBUG_LINES, DefaultVertexFormat.POSITION_COLOR); for (int i = 0; i <= num_steps180; i++) { - final float theta = step * i; - final float x = r * Mth.cos(theta); - final float z = r * Mth.sin(theta); + float theta = step * i; + float x = r * Mth.cos(theta); + float z = r * Mth.sin(theta); builder.vertex(cx - x, cy, cz + z).color(red, grn, blu, alpha).endVertex(); builder.vertex(cx + x, cy, cz - z).color(red, grn, blu, alpha).endVertex(); } @@ -1074,14 +1074,14 @@ else if (axis == Direction.Axis.X) { for (int dh = 0; dh < hsteps; dh++) { - final float hh = dh * hstep; + float hh = dh * hstep; builder.begin(VertexFormat.Mode.DEBUG_LINE_STRIP, DefaultVertexFormat.POSITION_COLOR); // line loop to line strip for (int i = 0; i <= num_steps360; i++) { - final float theta = step * i; - final float z = r * Mth.cos(theta); - final float x = hh; - final float y = r * Mth.sin(theta); + float theta = step * i; + float z = r * Mth.cos(theta); + float x = hh; + float y = r * Mth.sin(theta); builder.vertex(x + cx, y + cy, z + cz).color(red, grn, blu, alpha).endVertex(); } tessellator.end(); @@ -1092,10 +1092,10 @@ else if (axis == Direction.Axis.X) for (int i = 0; i <= num_steps180; i++) { builder.begin(VertexFormat.Mode.DEBUG_LINE_STRIP, DefaultVertexFormat.POSITION_COLOR); // line loop to line strip - final float theta = step * i; - final float y = r * Mth.cos(theta); + float theta = step * i; + float y = r * Mth.cos(theta); - final float z = r * Mth.sin(theta); + float z = r * Mth.sin(theta); builder.vertex(cx + 0, cy - y, cz + z).color(red, grn, blu, alpha).endVertex(); builder.vertex(cx + 0, cy + y, cz - z).color(red, grn, blu, alpha).endVertex(); @@ -1109,9 +1109,9 @@ else if (axis == Direction.Axis.X) builder.begin(VertexFormat.Mode.DEBUG_LINES, DefaultVertexFormat.POSITION_COLOR); for (int i = 0; i <= num_steps180; i++) { - final float theta = step * i; - final float y = r * Mth.cos(theta); - final float z = r * Mth.sin(theta); + float theta = step * i; + float y = r * Mth.cos(theta); + float z = r * Mth.sin(theta); builder.vertex(cx, cy - y, cz + z).color(red, grn, blu, alpha).endVertex(); builder.vertex(cx, cy + y, cz - z).color(red, grn, blu, alpha).endVertex(); } @@ -1122,14 +1122,14 @@ else if (axis == Direction.Axis.Z) { for (int dh = 0; dh < hsteps; dh++) { - final float hh = dh * hstep; + float hh = dh * hstep; builder.begin(VertexFormat.Mode.DEBUG_LINE_STRIP, DefaultVertexFormat.POSITION_COLOR); // line loop to line strip for (int i = 0; i <= num_steps360; i++) { - final float theta = step * i; - final float y = r * Mth.cos(theta); - final float z = hh; - final float x = r * Mth.sin(theta); + float theta = step * i; + float y = r * Mth.cos(theta); + float z = hh; + float x = r * Mth.sin(theta); builder.vertex(x + cx, y + cy, z + cz).color(red, grn, blu, alpha).endVertex(); } tessellator.end(); @@ -1139,10 +1139,10 @@ else if (axis == Direction.Axis.Z) for (int i = 0; i <= num_steps180; i++) { builder.begin(VertexFormat.Mode.DEBUG_LINE_STRIP, DefaultVertexFormat.POSITION_COLOR); // line loop to line strip - final float theta = step * i; - final float x = r * Mth.cos(theta); + float theta = step * i; + float x = r * Mth.cos(theta); - final float y = r * Mth.sin(theta); + float y = r * Mth.sin(theta); builder.vertex(cx + x, cy - y, cz + 0).color(red, grn, blu, alpha).endVertex(); builder.vertex(cx - x, cy + y, cz + 0).color(red, grn, blu, alpha).endVertex(); @@ -1156,9 +1156,9 @@ else if (axis == Direction.Axis.Z) builder.begin(VertexFormat.Mode.DEBUG_LINES, DefaultVertexFormat.POSITION_COLOR); for (int i = 0; i <= num_steps180; i++) { - final float theta = step * i; - final float x = r * Mth.cos(theta); - final float y = r * Mth.sin(theta); + float theta = step * i; + float x = r * Mth.cos(theta); + float y = r * Mth.sin(theta); builder.vertex(cx + x, cy - y, cz).color(red, grn, blu, alpha).endVertex(); builder.vertex(cx - x, cy + y, cz).color(red, grn, blu, alpha).endVertex(); } @@ -1168,14 +1168,14 @@ else if (axis == Direction.Axis.Z) } } - public static void drawCylinderFaces(final Tesselator tessellator, final BufferBuilder builder, - final float cx, final float cy, final float cz, - final float r, final float h, final Direction.Axis axis, final int subd, final boolean isFlat, - final float red, final float grn, final float blu, final float alpha) + public static void drawCylinderFaces(Tesselator tessellator, BufferBuilder builder, + float cx, float cy, float cz, + float r, float h, Direction.Axis axis, int subd, boolean isFlat, + float red, float grn, float blu, float alpha) { - final float step = (float) Math.PI / (subd / 2); + float step = (float) Math.PI / (subd / 2); //final int num_steps180 = (int) (Math.PI / step) + 1; - final int num_steps360 = (int) (2 * Math.PI / step) + 1; + int num_steps360 = (int) (2 * Math.PI / step) + 1; if (axis == Direction.Axis.Y) { @@ -1184,9 +1184,9 @@ public static void drawCylinderFaces(final Tesselator tessellator, final BufferB builder.vertex(cx, cy, cz).color(red, grn, blu, alpha).endVertex(); for (int i = 0; i <= num_steps360; i++) { - final float theta = step * i; - final float x = r * Mth.cos(theta); - final float z = r * Mth.sin(theta); + float theta = step * i; + float x = r * Mth.cos(theta); + float z = r * Mth.sin(theta); builder.vertex(x + cx, cy, z + cz).color(red, grn, blu, alpha).endVertex(); } tessellator.end(); @@ -1196,9 +1196,9 @@ public static void drawCylinderFaces(final Tesselator tessellator, final BufferB builder.vertex(cx, cy + h, cz).color(red, grn, blu, alpha).endVertex(); for (int i = 0; i <= num_steps360; i++) { - final float theta = step * i; - final float x = r * Mth.cos(theta); - final float z = r * Mth.sin(theta); + float theta = step * i; + float x = r * Mth.cos(theta); + float z = r * Mth.sin(theta); builder.vertex(x + cx, cy + h, z + cz).color(red, grn, blu, alpha).endVertex(); } tessellator.end(); @@ -1208,9 +1208,9 @@ public static void drawCylinderFaces(final Tesselator tessellator, final BufferB float zp = r * 0; for (int i = 1; i <= num_steps360; i++) { - final float theta = step * i; - final float x = r * Mth.cos(theta); - final float z = r * Mth.sin(theta); + float theta = step * i; + float x = r * Mth.cos(theta); + float z = r * Mth.sin(theta); builder.vertex(cx + xp, cy + 0, cz + zp).color(red, grn, blu, alpha).endVertex(); builder.vertex(cx + xp, cy + h, cz + zp).color(red, grn, blu, alpha).endVertex(); builder.vertex(cx + x, cy + h, cz + z).color(red, grn, blu, alpha).endVertex(); @@ -1228,9 +1228,9 @@ else if (axis == Direction.Axis.X) builder.vertex(cx, cy, cz).color(red, grn, blu, alpha).endVertex(); for (int i = 0; i <= num_steps360; i++) { - final float theta = step * i; - final float y = r * Mth.cos(theta); - final float z = r * Mth.sin(theta); + float theta = step * i; + float y = r * Mth.cos(theta); + float z = r * Mth.sin(theta); builder.vertex(cx, cy + y, z + cz).color(red, grn, blu, alpha).endVertex(); } tessellator.end(); @@ -1240,9 +1240,9 @@ else if (axis == Direction.Axis.X) builder.vertex(cx + h, cy, cz).color(red, grn, blu, alpha).endVertex(); for (int i = 0; i <= num_steps360; i++) { - final float theta = step * i; - final float y = r * Mth.cos(theta); - final float z = r * Mth.sin(theta); + float theta = step * i; + float y = r * Mth.cos(theta); + float z = r * Mth.sin(theta); builder.vertex(cx + h, cy + y, cz + z).color(red, grn, blu, alpha).endVertex(); } tessellator.end(); @@ -1252,9 +1252,9 @@ else if (axis == Direction.Axis.X) float zp = r * 0; for (int i = 1; i <= num_steps360; i++) { - final float theta = step * i; - final float y = r * Mth.cos(theta); - final float z = r * Mth.sin(theta); + float theta = step * i; + float y = r * Mth.cos(theta); + float z = r * Mth.sin(theta); builder.vertex(cx + 0, cy + yp, cz + zp).color(red, grn, blu, alpha).endVertex(); builder.vertex(cx + h, cy + yp, cz + zp).color(red, grn, blu, alpha).endVertex(); builder.vertex(cx + h, cy + y, cz + z).color(red, grn, blu, alpha).endVertex(); @@ -1271,9 +1271,9 @@ else if (axis == Direction.Axis.Z) builder.vertex(cx, cy, cz).color(red, grn, blu, alpha).endVertex(); for (int i = 0; i <= num_steps360; i++) { - final float theta = step * i; - final float x = r * Mth.cos(theta); - final float y = r * Mth.sin(theta); + float theta = step * i; + float x = r * Mth.cos(theta); + float y = r * Mth.sin(theta); builder.vertex(x + cx, cy + y, cz).color(red, grn, blu, alpha).endVertex(); } tessellator.end(); @@ -1283,9 +1283,9 @@ else if (axis == Direction.Axis.Z) builder.vertex(cx, cy, cz + h).color(red, grn, blu, alpha).endVertex(); for (int i = 0; i <= num_steps360; i++) { - final float theta = step * i; - final float x = r * Mth.cos(theta); - final float y = r * Mth.sin(theta); + float theta = step * i; + float x = r * Mth.cos(theta); + float y = r * Mth.sin(theta); builder.vertex(x + cx, cy + y, cz + h).color(red, grn, blu, alpha).endVertex(); } tessellator.end(); @@ -1295,9 +1295,9 @@ else if (axis == Direction.Axis.Z) float yp = 0; for (int i = 1; i <= num_steps360; i++) { - final float theta = step * i; - final float x = r * Mth.cos(theta); - final float y = r * Mth.sin(theta); + float theta = step * i; + float x = r * Mth.cos(theta); + float y = r * Mth.sin(theta); builder.vertex(cx + xp, cy + yp, cz + 0).color(red, grn, blu, alpha).endVertex(); builder.vertex(cx + xp, cy + yp, cz + h).color(red, grn, blu, alpha).endVertex(); builder.vertex(cx + x, cy + y, cz + h).color(red, grn, blu, alpha).endVertex(); @@ -1310,24 +1310,24 @@ else if (axis == Direction.Axis.Z) } } - public static void drawSphereWireframe(final Tesselator tessellator, final BufferBuilder builder, - final float cx, final float cy, final float cz, - final float r, final int subd, - final float red, final float grn, final float blu, final float alpha) + public static void drawSphereWireframe(Tesselator tessellator, BufferBuilder builder, + float cx, float cy, float cz, + float r, int subd, + float red, float grn, float blu, float alpha) { - final float step = (float) Math.PI / (subd / 2); - final int num_steps180 = (int) (Math.PI / step) + 1; - final int num_steps360 = (int) (2 * Math.PI / step) + 1; + float step = (float) Math.PI / (subd / 2); + int num_steps180 = (int) (Math.PI / step) + 1; + int num_steps360 = (int) (2 * Math.PI / step) + 1; for (int i = 0; i <= num_steps360; i++) { builder.begin(VertexFormat.Mode.DEBUG_LINE_STRIP, DefaultVertexFormat.POSITION_COLOR); - final float theta = step * i; + float theta = step * i; for (int j = 0; j <= num_steps180; j++) { - final float phi = step * j; - final float x = r * Mth.sin(phi) * Mth.cos(theta); - final float z = r * Mth.sin(phi) * Mth.sin(theta); - final float y = r * Mth.cos(phi); + float phi = step * j; + float x = r * Mth.sin(phi) * Mth.cos(theta); + float z = r * Mth.sin(phi) * Mth.sin(theta); + float y = r * Mth.cos(phi); builder.vertex(x + cx, y + cy, z + cz).color(red, grn, blu, alpha).endVertex(); } tessellator.end(); @@ -1335,14 +1335,14 @@ public static void drawSphereWireframe(final Tesselator tessellator, final Buffe for (int j = 0; j <= num_steps180; j++) { builder.begin(VertexFormat.Mode.DEBUG_LINE_STRIP, DefaultVertexFormat.POSITION_COLOR); // line loop to line strip - final float phi = step * j; + float phi = step * j; for (int i = 0; i <= num_steps360; i++) { - final float theta = step * i; - final float x = r * Mth.sin(phi) * Mth.cos(theta); - final float z = r * Mth.sin(phi) * Mth.sin(theta); - final float y = r * Mth.cos(phi); + float theta = step * i; + float x = r * Mth.sin(phi) * Mth.cos(theta); + float z = r * Mth.sin(phi) * Mth.sin(theta); + float y = r * Mth.cos(phi); builder.vertex(x + cx, y + cy, z + cz).color(red, grn, blu, alpha).endVertex(); } tessellator.end(); @@ -1350,19 +1350,19 @@ public static void drawSphereWireframe(final Tesselator tessellator, final Buffe } - public static void drawSphereFaces(final Tesselator tessellator, final BufferBuilder builder, - final float cx, final float cy, final float cz, - final float r, final int subd, - final float red, final float grn, final float blu, final float alpha) + public static void drawSphereFaces(Tesselator tessellator, BufferBuilder builder, + float cx, float cy, float cz, + float r, int subd, + float red, float grn, float blu, float alpha) { - final float step = (float) Math.PI / (subd / 2); - final int num_steps180 = (int) (Math.PI / step) + 1; - final int num_steps360 = (int) (2 * Math.PI / step); + float step = (float) Math.PI / (subd / 2); + int num_steps180 = (int) (Math.PI / step) + 1; + int num_steps360 = (int) (2 * Math.PI / step); for (int i = 0; i <= num_steps360; i++) { - final float theta = i * step; - final float thetaprime = theta + step; + float theta = i * step; + float thetaprime = theta + step; builder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); // quad strip to quads float xb = 0; float zb = 0; @@ -1371,12 +1371,12 @@ public static void drawSphereFaces(final Tesselator tessellator, final BufferBui float yp = r; for (int j = 0; j <= num_steps180; j++) { - final float phi = j * step; - final float x = r * Mth.sin(phi) * Mth.cos(theta); - final float z = r * Mth.sin(phi) * Mth.sin(theta); - final float y = r * Mth.cos(phi); - final float xp = r * Mth.sin(phi) * Mth.cos(thetaprime); - final float zp = r * Mth.sin(phi) * Mth.sin(thetaprime); + float phi = j * step; + float x = r * Mth.sin(phi) * Mth.cos(theta); + float z = r * Mth.sin(phi) * Mth.sin(theta); + float y = r * Mth.cos(phi); + float xp = r * Mth.sin(phi) * Mth.cos(thetaprime); + float zp = r * Mth.sin(phi) * Mth.sin(thetaprime); builder.vertex(xb + cx, yp + cy, zb + cz).color(red, grn, blu, alpha).endVertex(); builder.vertex(xbp + cx, yp + cy, zbp + cz).color(red, grn, blu, alpha).endVertex(); builder.vertex(xp + cx, y + cy, zp + cz).color(red, grn, blu, alpha).endVertex(); diff --git a/src/main/java/carpet/script/utils/SimplexNoiseSampler.java b/src/main/java/carpet/script/utils/SimplexNoiseSampler.java index c56f955a26..5b16882ec0 100644 --- a/src/main/java/carpet/script/utils/SimplexNoiseSampler.java +++ b/src/main/java/carpet/script/utils/SimplexNoiseSampler.java @@ -15,7 +15,7 @@ public class SimplexNoiseSampler extends PerlinNoiseSampler public static SimplexNoiseSampler instance = new SimplexNoiseSampler(new Random(0)); public static Map samplers = new Long2ObjectOpenHashMap<>(); - public static SimplexNoiseSampler getSimplex(final long aLong) + public static SimplexNoiseSampler getSimplex(long aLong) { if (samplers.size() > 256) { @@ -24,15 +24,15 @@ public static SimplexNoiseSampler getSimplex(final long aLong) return samplers.computeIfAbsent(aLong, seed -> new SimplexNoiseSampler(new Random(seed))); } - public SimplexNoiseSampler(final Random random) + public SimplexNoiseSampler(Random random) { super(random); } - private double grad(final int hash, final double x, final double y, final double z, final double d) + private double grad(int hash, double x, double y, double z, double d) { double e = d - x * x - y * y - z * z; - final double g; + double g; if (e < 0.0D) { g = 0.0D; @@ -51,16 +51,16 @@ public double sample2d(double x, double y) { x = x / 2; y = y / 2; - final double d = (x + y) * SKEW_FACTOR_2D; - final int i = PerlinNoiseSampler.floor(x + d); - final int j = PerlinNoiseSampler.floor(y + d); - final double e = (i + j) * UNSKEW_FACTOR_2D; - final double f = i - e; - final double g = j - e; - final double h = x - f; - final double k = y - g; - final byte n; - final byte o; + double d = (x + y) * SKEW_FACTOR_2D; + int i = PerlinNoiseSampler.floor(x + d); + int j = PerlinNoiseSampler.floor(y + d); + double e = (i + j) * UNSKEW_FACTOR_2D; + double f = i - e; + double g = j - e; + double h = x - f; + double k = y - g; + byte n; + byte o; if (h > k) { n = 1; @@ -72,18 +72,18 @@ public double sample2d(double x, double y) o = 1; } - final double p = h - n + UNSKEW_FACTOR_2D; - final double q = k - o + UNSKEW_FACTOR_2D; - final double r = h - 1.0D + 2.0D * UNSKEW_FACTOR_2D; - final double s = k - 1.0D + 2.0D * UNSKEW_FACTOR_2D; - final int t = i & 255; - final int u = j & 255; - final int v = this.getGradient(t + this.getGradient(u)) % 12; - final int w = this.getGradient(t + n + this.getGradient(u + o)) % 12; - final int z = this.getGradient(t + 1 + this.getGradient(u + 1)) % 12; - final double aa = this.grad(v, h, k, 0.0D, 0.5D); - final double ab = this.grad(w, p, q, 0.0D, 0.5D); - final double ac = this.grad(z, r, s, 0.0D, 0.5D); + double p = h - n + UNSKEW_FACTOR_2D; + double q = k - o + UNSKEW_FACTOR_2D; + double r = h - 1.0D + 2.0D * UNSKEW_FACTOR_2D; + double s = k - 1.0D + 2.0D * UNSKEW_FACTOR_2D; + int t = i & 255; + int u = j & 255; + int v = this.getGradient(t + this.getGradient(u)) % 12; + int w = this.getGradient(t + n + this.getGradient(u + o)) % 12; + int z = this.getGradient(t + 1 + this.getGradient(u + 1)) % 12; + double aa = this.grad(v, h, k, 0.0D, 0.5D); + double ab = this.grad(w, p, q, 0.0D, 0.5D); + double ac = this.grad(z, r, s, 0.0D, 0.5D); //return 70.0D * (aa + ab + ac); return 35.0D * (aa + ab + ac) + 0.5; } @@ -95,24 +95,24 @@ public double sample3d(double d, double e, double f) e = e / 2; f = f / 2; //final double g = 0.3333333333333333D; - final double h = (d + e + f) * 0.3333333333333333D; - final int i = floor(d + h); - final int j = floor(e + h); - final int k = floor(f + h); + double h = (d + e + f) * 0.3333333333333333D; + int i = floor(d + h); + int j = floor(e + h); + int k = floor(f + h); //final double l = 0.16666666666666666D; - final double m = (i + j + k) * 0.16666666666666666D; - final double n = i - m; - final double o = j - m; - final double p = k - m; - final double q = d - n; - final double r = e - o; - final double s = f - p; - final byte z; - final byte aa; - final byte ab; - final byte ac; - final byte ad; - final byte bc; + double m = (i + j + k) * 0.16666666666666666D; + double n = i - m; + double o = j - m; + double p = k - m; + double q = d - n; + double r = e - o; + double s = f - p; + byte z; + byte aa; + byte ab; + byte ac; + byte ad; + byte bc; if (q >= r) { if (r >= s) @@ -171,26 +171,26 @@ else if (q < s) bc = 0; } - final double bd = q - z + 0.16666666666666666D; - final double be = r - aa + 0.16666666666666666D; - final double bf = s - ab + 0.16666666666666666D; - final double bg = q - ac + 0.3333333333333333D; - final double bh = r - ad + 0.3333333333333333D; - final double bi = s - bc + 0.3333333333333333D; - final double bj = q - 1.0D + 0.5D; - final double bk = r - 1.0D + 0.5D; - final double bl = s - 1.0D + 0.5D; - final int bm = i & 255; - final int bn = j & 255; - final int bo = k & 255; - final int bp = this.getGradient(bm + this.getGradient(bn + this.getGradient(bo))) % 12; - final int bq = this.getGradient(bm + z + this.getGradient(bn + aa + this.getGradient(bo + ab))) % 12; - final int br = this.getGradient(bm + ac + this.getGradient(bn + ad + this.getGradient(bo + bc))) % 12; - final int bs = this.getGradient(bm + 1 + this.getGradient(bn + 1 + this.getGradient(bo + 1))) % 12; - final double bt = this.grad(bp, q, r, s, 0.6D); - final double bu = this.grad(bq, bd, be, bf, 0.6D); - final double bv = this.grad(br, bg, bh, bi, 0.6D); - final double bw = this.grad(bs, bj, bk, bl, 0.6D); + double bd = q - z + 0.16666666666666666D; + double be = r - aa + 0.16666666666666666D; + double bf = s - ab + 0.16666666666666666D; + double bg = q - ac + 0.3333333333333333D; + double bh = r - ad + 0.3333333333333333D; + double bi = s - bc + 0.3333333333333333D; + double bj = q - 1.0D + 0.5D; + double bk = r - 1.0D + 0.5D; + double bl = s - 1.0D + 0.5D; + int bm = i & 255; + int bn = j & 255; + int bo = k & 255; + int bp = this.getGradient(bm + this.getGradient(bn + this.getGradient(bo))) % 12; + int bq = this.getGradient(bm + z + this.getGradient(bn + aa + this.getGradient(bo + ab))) % 12; + int br = this.getGradient(bm + ac + this.getGradient(bn + ad + this.getGradient(bo + bc))) % 12; + int bs = this.getGradient(bm + 1 + this.getGradient(bn + 1 + this.getGradient(bo + 1))) % 12; + double bt = this.grad(bp, q, r, s, 0.6D); + double bu = this.grad(bq, bd, be, bf, 0.6D); + double bv = this.grad(br, bg, bh, bi, 0.6D); + double bw = this.grad(bs, bj, bk, bl, 0.6D); return 16.0D * (bt + bu + bv + bw) + 0.5; } diff --git a/src/main/java/carpet/script/utils/SnoopyCommandSource.java b/src/main/java/carpet/script/utils/SnoopyCommandSource.java index a462bce5b6..b656a9970f 100644 --- a/src/main/java/carpet/script/utils/SnoopyCommandSource.java +++ b/src/main/java/carpet/script/utils/SnoopyCommandSource.java @@ -40,7 +40,7 @@ public class SnoopyCommandSource extends CommandSourceStack private final List chatOutput; private final CommandSigningContext signingContext; - public SnoopyCommandSource(final CommandSourceStack original, final Component[] error, final List chatOutput) + public SnoopyCommandSource(CommandSourceStack original, Component[] error, List chatOutput) { super(CommandSource.NULL, original.getPosition(), original.getRotation(), original.getLevel(), Vanilla.MinecraftServer_getRunPermissionLevel(original.getServer()), original.getTextName(), original.getDisplayName(), original.getServer(), original.getEntity(), false, @@ -63,7 +63,7 @@ public SnoopyCommandSource(final CommandSourceStack original, final Component[] this.signingContext = original.getSigningContext(); } - public SnoopyCommandSource(final ServerPlayer player, final Component[] error, final List output) + public SnoopyCommandSource(ServerPlayer player, Component[] error, List output) { super(player, player.position(), player.getRotationVector(), player.level instanceof final ServerLevel serverLevel ? serverLevel : null, @@ -86,8 +86,8 @@ public SnoopyCommandSource(final ServerPlayer player, final Component[] error, f this.signingContext = CommandSigningContext.ANONYMOUS; } - private SnoopyCommandSource(final CommandSource output, final Vec3 pos, final Vec2 rot, final ServerLevel world, final int level, final String simpleName, final Component name, final MinecraftServer server, @Nullable final Entity entity, final ResultConsumer consumer, final EntityAnchorArgument.Anchor entityAnchor, final CommandSigningContext context, - final Component[] error, final List chatOutput + private SnoopyCommandSource(CommandSource output, Vec3 pos, Vec2 rot, ServerLevel world, int level, String simpleName, Component name, MinecraftServer server, @Nullable Entity entity, ResultConsumer consumer, EntityAnchorArgument.Anchor entityAnchor, CommandSigningContext context, + Component[] error, List chatOutput ) { super(output, pos, rot, world, level, @@ -110,33 +110,33 @@ private SnoopyCommandSource(final CommandSource output, final Vec3 pos, final Ve } @Override - public CommandSourceStack withEntity(final Entity entity) + public CommandSourceStack withEntity(Entity entity) { return new SnoopyCommandSource(output, position, rotation, world, level, entity.getName().getString(), entity.getDisplayName(), server, entity, resultConsumer, entityAnchor, signingContext, error, chatOutput); } @Override - public CommandSourceStack withPosition(final Vec3 position) + public CommandSourceStack withPosition(Vec3 position) { return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, resultConsumer, entityAnchor, signingContext, error, chatOutput); } @Override - public CommandSourceStack withRotation(final Vec2 rotation) + public CommandSourceStack withRotation(Vec2 rotation) { return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, resultConsumer, entityAnchor, signingContext, error, chatOutput); } @Override - public CommandSourceStack withCallback(final ResultConsumer consumer) + public CommandSourceStack withCallback(ResultConsumer consumer) { return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, consumer, entityAnchor, signingContext, error, chatOutput); } @Override - public CommandSourceStack withCallback(final ResultConsumer consumer, final BinaryOperator> binaryOperator) + public CommandSourceStack withCallback(ResultConsumer consumer, BinaryOperator> binaryOperator) { - final ResultConsumer resultConsumer = binaryOperator.apply(this.resultConsumer, consumer); + ResultConsumer resultConsumer = binaryOperator.apply(this.resultConsumer, consumer); return this.withCallback(resultConsumer); } @@ -145,58 +145,58 @@ public CommandSourceStack withCallback(final ResultConsumer //public ServerCommandSource withSilent() { return this; } @Override - public CommandSourceStack withPermission(final int level) + public CommandSourceStack withPermission(int level) { return this; } @Override - public CommandSourceStack withMaximumPermission(final int level) + public CommandSourceStack withMaximumPermission(int level) { return this; } @Override - public CommandSourceStack withAnchor(final EntityAnchorArgument.Anchor anchor) + public CommandSourceStack withAnchor(EntityAnchorArgument.Anchor anchor) { return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, resultConsumer, anchor, signingContext, error, chatOutput); } @Override - public CommandSourceStack withSigningContext(final CommandSigningContext commandSigningContext) + public CommandSourceStack withSigningContext(CommandSigningContext commandSigningContext) { return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, resultConsumer, entityAnchor, commandSigningContext, error, chatOutput); } @Override - public CommandSourceStack withLevel(final ServerLevel world) + public CommandSourceStack withLevel(ServerLevel world) { - final double d = DimensionType.getTeleportationScale(this.world.dimensionType(), world.dimensionType()); - final Vec3 position = new Vec3(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, signingContext, error, chatOutput); } @Override - public CommandSourceStack facing(final Vec3 position) - { - final Vec3 vec3d = this.entityAnchor.apply(this); - final double d = position.x - vec3d.x; - final double e = position.y - vec3d.y; - final double f = position.z - vec3d.z; - final double g = Math.sqrt(d * d + f * f); - final float h = Mth.wrapDegrees((float) (-(Mth.atan2(e, g) * 57.2957763671875D))); - final float i = Mth.wrapDegrees((float) (Mth.atan2(f, d) * 57.2957763671875D) - 90.0F); + public CommandSourceStack facing(Vec3 position) + { + 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 = Math.sqrt(d * d + f * f); + 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 sendFailure(final Component message) + public void sendFailure(Component message) { error[0] = message; } @Override - public void sendSuccess(final Component message, final boolean broadcastToOps) + public void sendSuccess(Component message, boolean broadcastToOps) { chatOutput.add(message); } diff --git a/src/main/java/carpet/script/utils/SystemInfo.java b/src/main/java/carpet/script/utils/SystemInfo.java index fafa59e189..03fa8f30de 100644 --- a/src/main/java/carpet/script/utils/SystemInfo.java +++ b/src/main/java/carpet/script/utils/SystemInfo.java @@ -37,7 +37,7 @@ public class SystemInfo {{ put("app_name", c -> { - final String name = c.host.getName(); + String name = c.host.getName(); return name == null ? Value.NULL : new StringValue(name); }); put("app_list", c -> ListValue.wrap(((CarpetScriptHost) c.host).scriptServer().modules.keySet().stream().filter(Objects::nonNull).map(StringValue::new))); @@ -49,18 +49,18 @@ public class SystemInfo put("server_motd", c -> StringValue.of(c.server().getMotd())); put("world_path", c -> StringValue.of(c.server().getWorldPath(LevelResource.ROOT).toString())); put("world_folder", c -> { - final Path serverPath = c.server().getWorldPath(LevelResource.ROOT); - final int nodeCount = serverPath.getNameCount(); + Path serverPath = c.server().getWorldPath(LevelResource.ROOT); + int nodeCount = serverPath.getNameCount(); if (nodeCount < 2) { return Value.NULL; } - final String tlf = serverPath.getName(nodeCount - 2).toString(); + String tlf = serverPath.getName(nodeCount - 2).toString(); return StringValue.of(tlf); }); put("world_dimensions", c -> ListValue.wrap(c.server().levelKeys().stream().map(k -> ValueConversions.of(k.location())))); put("world_spawn_point", c -> { - final LevelData prop = c.server().overworld().getLevelData(); + LevelData prop = c.server().overworld().getLevelData(); return ListValue.of(NumericValue.of(prop.getXSpawn()), NumericValue.of(prop.getYSpawn()), NumericValue.of(prop.getZSpawn())); }); @@ -69,7 +69,7 @@ public class SystemInfo put("world_top", c -> new NumericValue(c.level().getMaxBuildHeight())); put("world_center", c -> { - final WorldBorder worldBorder = c.level().getWorldBorder(); + WorldBorder worldBorder = c.level().getWorldBorder(); return ListValue.fromTriple(worldBorder.getCenterX(), 0, worldBorder.getCenterZ()); }); @@ -90,11 +90,11 @@ public class SystemInfo put("game_target", c -> StringValue.of(Vanilla.MinecraftServer_getReleaseTarget(c.server()))); put("game_protocol", c -> NumericValue.of(SharedConstants.getProtocolVersion())); put("game_major_target", c -> { - final String[] vers = Vanilla.MinecraftServer_getReleaseTarget(c.server()).split("\\."); + String[] vers = Vanilla.MinecraftServer_getReleaseTarget(c.server()).split("\\."); return NumericValue.of((vers.length > 1) ? Integer.parseInt(vers[1]) : 0); }); put("game_minor_target", c -> { - final String[] vers = Vanilla.MinecraftServer_getReleaseTarget(c.server()).split("\\."); + String[] vers = Vanilla.MinecraftServer_getReleaseTarget(c.server()).split("\\."); return NumericValue.of((vers.length > 2) ? Integer.parseInt(vers[2]) : 0); }); put("game_stable", c -> BooleanValue.of(SharedConstants.getCurrentVersion().isStable())); @@ -104,24 +104,24 @@ public class SystemInfo put("server_ip", c -> StringValue.of(c.server().getLocalIp())); put("server_whitelisted", c -> BooleanValue.of(c.server().isEnforceWhitelist())); put("server_whitelist", c -> { - final MapValue whitelist = new MapValue(Collections.emptyList()); - for (final String s : c.server().getPlayerList().getWhiteListNames()) + MapValue whitelist = new MapValue(Collections.emptyList()); + for (String s : c.server().getPlayerList().getWhiteListNames()) { whitelist.append(StringValue.of(s)); } return whitelist; }); put("server_banned_players", c -> { - final MapValue whitelist = new MapValue(Collections.emptyList()); - for (final String s : c.server().getPlayerList().getBans().getUserList()) + MapValue whitelist = new MapValue(Collections.emptyList()); + for (String s : c.server().getPlayerList().getBans().getUserList()) { whitelist.append(StringValue.of(s)); } return whitelist; }); put("server_banned_ips", c -> { - final MapValue whitelist = new MapValue(Collections.emptyList()); - for (final String s : c.server().getPlayerList().getIpBans().getUserList()) + MapValue whitelist = new MapValue(Collections.emptyList()); + for (String s : c.server().getPlayerList().getIpBans().getUserList()) { whitelist.append(StringValue.of(s)); } @@ -132,9 +132,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. - final int currentReportedTick = c.server().getTickCount() - 1; - final List ticks = new ArrayList<>(100); - final long[] tickArray = c.server().tickTimes; + int currentReportedTick = c.server().getTickCount() - 1; + List ticks = new ArrayList<>(100); + long[] tickArray = c.server().tickTimes; for (int i = currentReportedTick + 100; i > currentReportedTick; i--) { ticks.add(new NumericValue((tickArray[i % 100]) / 1000000.0)); @@ -148,9 +148,9 @@ public class SystemInfo put("java_cpu_count", c -> new NumericValue(Runtime.getRuntime().availableProcessors())); put("java_version", c -> StringValue.of(System.getProperty("java.version"))); put("java_bits", c -> { - for (final String property : new String[]{"sun.arch.data.model", "com.ibm.vm.bitmode", "os.arch"}) + for (String property : new String[]{"sun.arch.data.model", "com.ibm.vm.bitmode", "os.arch"}) { - final String value = System.getProperty(property); + String value = System.getProperty(property); if (value != null && value.contains("64")) { return new NumericValue(64); @@ -159,23 +159,23 @@ public class SystemInfo return new NumericValue(32); }); put("java_system_cpu_load", c -> { - final OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean( + OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean( OperatingSystemMXBean.class); return new NumericValue(osBean.getCpuLoad()); }); put("java_process_cpu_load", c -> { - final OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean( + OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean( OperatingSystemMXBean.class); return new NumericValue(osBean.getProcessCpuLoad()); }); put("world_carpet_rules", c -> Carpet.getAllCarpetRules()); put("world_gamerules", c -> { - final Map rules = new HashMap<>(); - final GameRules gameRules = c.level().getGameRules(); + Map rules = new HashMap<>(); + GameRules gameRules = c.level().getGameRules(); GameRules.visitGameRuleTypes(new GameRules.GameRuleTypeVisitor() { @Override - public > void visit(final GameRules.Key key, final GameRules.Type type) + public > void visit(GameRules.Key key, GameRules.Type type) { rules.put(StringValue.of(key.getId()), StringValue.of(gameRules.getRule(key).toString())); } @@ -188,13 +188,13 @@ public > void visit(final GameRules.Key key, fin put("source_position", c -> ValueConversions.of(c.source().getPosition())); put("source_dimension", c -> ValueConversions.of(c.level())); put("source_rotation", c -> { - final Vec2 rotation = c.source().getRotation(); + Vec2 rotation = c.source().getRotation(); return ListValue.of(new NumericValue(rotation.x), new NumericValue(rotation.y)); }); put("scarpet_version", c -> StringValue.of(Carpet.getCarpetVersion())); }}; - public static Value get(final String what, final CarpetContext cc) + public static Value get(String what, CarpetContext cc) { return options.getOrDefault(what, c -> null).apply(cc); } diff --git a/src/main/java/carpet/script/utils/Tracer.java b/src/main/java/carpet/script/utils/Tracer.java index 396e664555..e4f4998a33 100644 --- a/src/main/java/carpet/script/utils/Tracer.java +++ b/src/main/java/carpet/script/utils/Tracer.java @@ -14,45 +14,45 @@ public class Tracer { - public static HitResult rayTrace(final Entity source, final float partialTicks, final double reach, final boolean fluids) + public static HitResult rayTrace(Entity source, float partialTicks, double reach, boolean fluids) { - final BlockHitResult blockHit = rayTraceBlocks(source, partialTicks, reach, fluids); + BlockHitResult blockHit = rayTraceBlocks(source, partialTicks, reach, fluids); double maxSqDist = reach * reach; if (blockHit != null) { maxSqDist = blockHit.getLocation().distanceToSqr(source.getEyePosition(partialTicks)); } - final EntityHitResult entityHit = rayTraceEntities(source, partialTicks, reach, maxSqDist); + EntityHitResult entityHit = rayTraceEntities(source, partialTicks, reach, maxSqDist); return entityHit == null ? blockHit : entityHit; } - public static BlockHitResult rayTraceBlocks(final Entity source, final float partialTicks, final double reach, final boolean fluids) + public static BlockHitResult rayTraceBlocks(Entity source, float partialTicks, double reach, boolean fluids) { - final Vec3 pos = source.getEyePosition(partialTicks); - final Vec3 rotation = source.getViewVector(partialTicks); - final Vec3 reachEnd = pos.add(rotation.x * reach, rotation.y * reach, rotation.z * reach); + Vec3 pos = source.getEyePosition(partialTicks); + Vec3 rotation = source.getViewVector(partialTicks); + Vec3 reachEnd = pos.add(rotation.x * reach, rotation.y * reach, rotation.z * reach); return source.level.clip(new ClipContext(pos, reachEnd, ClipContext.Block.OUTLINE, fluids ? ClipContext.Fluid.ANY : ClipContext.Fluid.NONE, source)); } - public static EntityHitResult rayTraceEntities(final Entity source, final float partialTicks, final double reach, final double maxSqDist) + public static EntityHitResult rayTraceEntities(Entity source, float partialTicks, double reach, double maxSqDist) { - final Vec3 pos = source.getEyePosition(partialTicks); - final Vec3 reachVec = source.getViewVector(partialTicks).scale(reach); - final AABB box = source.getBoundingBox().expandTowards(reachVec).inflate(1); + Vec3 pos = source.getEyePosition(partialTicks); + Vec3 reachVec = source.getViewVector(partialTicks).scale(reach); + AABB box = source.getBoundingBox().expandTowards(reachVec).inflate(1); return rayTraceEntities(source, pos, pos.add(reachVec), box, e -> !e.isSpectator() && e.isPickable(), maxSqDist); } - public static EntityHitResult rayTraceEntities(final Entity source, final Vec3 start, final Vec3 end, final AABB box, final Predicate predicate, final double maxSqDistance) + public static EntityHitResult rayTraceEntities(Entity source, Vec3 start, Vec3 end, AABB box, Predicate predicate, double maxSqDistance) { - final Level world = source.level; + Level world = source.level; double targetDistance = maxSqDistance; Entity target = null; Vec3 targetHitPos = null; - for (final Entity current : world.getEntities(source, box, predicate)) + for (Entity current : world.getEntities(source, box, predicate)) { - final AABB currentBox = current.getBoundingBox().inflate(current.getPickRadius()); - final Optional currentHit = currentBox.clip(start, end); + AABB currentBox = current.getBoundingBox().inflate(current.getPickRadius()); + Optional currentHit = currentBox.clip(start, end); if (currentBox.contains(start)) { if (targetDistance >= 0) @@ -64,8 +64,8 @@ public static EntityHitResult rayTraceEntities(final Entity source, final Vec3 s } else if (currentHit.isPresent()) { - final Vec3 currentHitPos = currentHit.get(); - final double currentDistance = start.distanceToSqr(currentHitPos); + Vec3 currentHitPos = currentHit.get(); + double currentDistance = start.distanceToSqr(currentHitPos); if (currentDistance < targetDistance || targetDistance == 0) { if (current.getRootVehicle() == source.getRootVehicle()) diff --git a/src/main/java/carpet/script/utils/WorldTools.java b/src/main/java/carpet/script/utils/WorldTools.java index fc246cb4e5..ce5ff43700 100644 --- a/src/main/java/carpet/script/utils/WorldTools.java +++ b/src/main/java/carpet/script/utils/WorldTools.java @@ -34,6 +34,7 @@ import net.minecraft.world.level.storage.DerivedLevelData; import net.minecraft.world.level.storage.ServerLevelData; +import javax.annotation.Nullable; import java.io.IOException; import java.nio.file.Path; import java.util.List; @@ -44,24 +45,24 @@ public class WorldTools { - public static boolean canHasChunk(final ServerLevel world, final ChunkPos chpos, final Map regionCache, final boolean deepcheck) + public static boolean canHasChunk(ServerLevel world, ChunkPos chpos, @Nullable Map regionCache, boolean deepcheck) { if (world.getChunk(chpos.x, chpos.z, ChunkStatus.STRUCTURE_STARTS, false) != null) { return true; } - final String currentRegionName = "r." + chpos.getRegionX() + "." + chpos.getRegionZ() + ".mca"; + String currentRegionName = "r." + chpos.getRegionX() + "." + chpos.getRegionZ() + ".mca"; if (regionCache != null && regionCache.containsKey(currentRegionName)) { - final RegionFile region = regionCache.get(currentRegionName); + RegionFile region = regionCache.get(currentRegionName); if (region == null) { return false; } return region.hasChunk(chpos); } - final Path regionsFolder = Vanilla.MinecraftServer_storageSource(world.getServer()).getDimensionPath(world.dimension()).resolve("region"); - final Path regionPath = regionsFolder.resolve(currentRegionName); + Path regionsFolder = Vanilla.MinecraftServer_storageSource(world.getServer()).getDimensionPath(world.dimension()).resolve("region"); + Path regionPath = regionsFolder.resolve(currentRegionName); if (!regionPath.toFile().exists()) { if (regionCache != null) @@ -76,14 +77,14 @@ public static boolean canHasChunk(final ServerLevel world, final ChunkPos chpos, } try { - final RegionFile region = new RegionFile(regionPath, regionsFolder, true); + RegionFile region = new RegionFile(regionPath, regionsFolder, true); if (regionCache != null) { regionCache.put(currentRegionName, region); } return region.hasChunk(chpos); } - catch (final IOException ignored) + catch (IOException ignored) { } return true; @@ -155,16 +156,16 @@ public static boolean createWorld(MinecraftServer server, String worldKey, Long return true; }*/ - public static void forceChunkUpdate(final BlockPos pos, final ServerLevel world) + public static void forceChunkUpdate(BlockPos pos, ServerLevel world) { - final ChunkPos chunkPos = new ChunkPos(pos); - final LevelChunk worldChunk = world.getChunkSource().getChunk(chunkPos.x, chunkPos.z, false); + ChunkPos chunkPos = new ChunkPos(pos); + LevelChunk worldChunk = world.getChunkSource().getChunk(chunkPos.x, chunkPos.z, false); if (worldChunk != null) { - final List players = world.getChunkSource().chunkMap.getPlayers(chunkPos, false); + List players = world.getChunkSource().chunkMap.getPlayers(chunkPos, false); if (!players.isEmpty()) { - final ClientboundLevelChunkWithLightPacket packet = new ClientboundLevelChunkWithLightPacket(worldChunk, world.getLightEngine(), 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. players.forEach(p -> p.connection.send(packet)); } } diff --git a/src/main/java/carpet/script/utils/shapes/ShapeDirection.java b/src/main/java/carpet/script/utils/shapes/ShapeDirection.java index 9b7f33334f..54774263cf 100644 --- a/src/main/java/carpet/script/utils/shapes/ShapeDirection.java +++ b/src/main/java/carpet/script/utils/shapes/ShapeDirection.java @@ -5,6 +5,7 @@ import net.minecraft.client.Camera; import net.minecraft.world.phys.Vec3; +import javax.annotation.Nullable; import java.util.Locale; public enum ShapeDirection @@ -18,7 +19,8 @@ public enum ShapeDirection CAMERA, PLAYER; - public static ShapeDirection fromString(final String direction) + @Nullable + public static ShapeDirection fromString(String direction) { return switch (direction.toLowerCase(Locale.ROOT)) { @@ -34,7 +36,7 @@ public static ShapeDirection fromString(final String direction) }; } - public static void rotatePoseStackByShapeDirection(final PoseStack poseStack, final ShapeDirection shapeDirection, final Camera camera, final Vec3 objectPos) + public static void rotatePoseStackByShapeDirection(PoseStack poseStack, ShapeDirection shapeDirection, Camera camera, Vec3 objectPos) { switch (shapeDirection) { @@ -46,13 +48,13 @@ public static void rotatePoseStackByShapeDirection(final PoseStack poseStack, fi case DOWN -> poseStack.mulPose(Axis.XP.rotationDegrees(-90)); case CAMERA -> poseStack.mulPose(camera.rotation()); case PLAYER -> { - final Vec3 vector = objectPos.subtract(camera.getPosition()); - final double x = vector.x; - final double y = vector.y; - final double z = vector.z; - final double d = Math.sqrt(x * x + z * z); - final float rotX = (float) (Math.atan2(x, z)); - final float rotY = (float) (Math.atan2(y, d)); + Vec3 vector = objectPos.subtract(camera.getPosition()); + double x = vector.x; + double y = vector.y; + double z = vector.z; + double d = Math.sqrt(x * x + z * z); + float rotX = (float) (Math.atan2(x, z)); + float rotY = (float) (Math.atan2(y, d)); // that should work somehow but it doesn't for some reason //matrices.mulPose(new Quaternion( -rotY, rotX, 0, false)); diff --git a/src/main/java/carpet/script/value/AbstractListValue.java b/src/main/java/carpet/script/value/AbstractListValue.java index cb6a7ab890..511ccad01b 100644 --- a/src/main/java/carpet/script/value/AbstractListValue.java +++ b/src/main/java/carpet/script/value/AbstractListValue.java @@ -9,7 +9,7 @@ public abstract class AbstractListValue extends Value implements Iterable { public List unpack() { - final List retVal = Lists.newArrayList(iterator()); + List retVal = Lists.newArrayList(iterator()); fatality(); return retVal; } @@ -18,7 +18,7 @@ public void fatality() { } - public void append(final Value v) + public void append(Value v) { throw new InternalExpressionException("Cannot append a value to an abstract list"); } diff --git a/src/main/java/carpet/script/value/BlockValue.java b/src/main/java/carpet/script/value/BlockValue.java index 6d7e85637d..b4e47e54ca 100644 --- a/src/main/java/carpet/script/value/BlockValue.java +++ b/src/main/java/carpet/script/value/BlockValue.java @@ -31,6 +31,7 @@ import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.Property; @@ -38,24 +39,30 @@ import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.Vec3; +import javax.annotation.Nullable; + import static carpet.script.value.NBTSerializableValue.nameFromRegistryId; +import static carpet.script.value.NBTSerializableValue.nameFromResource; public class BlockValue extends Value { private BlockState blockState; private final BlockPos pos; - private final Level world; + private final ServerLevel world; private CompoundTag data; - public static BlockValue fromCoords(final CarpetContext c, final int x, final int y, final int z) + // we only care for null values a few times, most of the time we would assume its all present + public static final BlockValue NONE = new BlockValue(Blocks.AIR.defaultBlockState(), null, BlockPos.ZERO, null); + + public static BlockValue fromCoords(CarpetContext c, int x, int y, int z) { - final BlockPos pos = locateBlockPos(c, x, y, z); + BlockPos pos = locateBlockPos(c, x, y, z); return new BlockValue(null, c.level(), pos); } private static final Map bvCache = new HashMap<>(); - public static BlockValue fromString(final String str, final Level level) + public static BlockValue fromString(String str, ServerLevel level) { try { @@ -64,7 +71,7 @@ public static BlockValue fromString(final String str, final Level level) { return bv; } - final BlockStateParser.BlockResult foo = BlockStateParser.parseForBlock(level.registryAccess().lookupOrThrow(Registries.BLOCK), new StringReader(str), true); + BlockStateParser.BlockResult foo = BlockStateParser.parseForBlock(level.registryAccess().lookupOrThrow(Registries.BLOCK), new StringReader(str), true); if (foo.blockState() != null) { CompoundTag bd = foo.nbt(); @@ -81,15 +88,15 @@ public static BlockValue fromString(final String str, final Level level) return bv; } } - catch (final CommandSyntaxException ignored) + catch (CommandSyntaxException ignored) { } throw new ThrowStatement(str, Throwables.UNKNOWN_BLOCK); } - public static BlockPos locateBlockPos(final CarpetContext c, final int xpos, final int ypos, final int zpos) + public static BlockPos locateBlockPos(CarpetContext c, int xpos, int ypos, int zpos) { - final BlockPos pos = c.origin(); + BlockPos pos = c.origin(); return new BlockPos(pos.getX() + xpos, pos.getY() + ypos, pos.getZ() + zpos); } @@ -107,7 +114,7 @@ public BlockState getBlockState() throw new InternalExpressionException("Attempted to fetch block state without world or stored block state"); } - public static BlockEntity getBlockEntity(final Level level, final BlockPos pos) + public static BlockEntity getBlockEntity(Level level, BlockPos pos) { if (level instanceof final ServerLevel serverLevel) { @@ -127,7 +134,7 @@ public CompoundTag getData() } if (pos != null) { - final BlockEntity be = getBlockEntity(world, pos); + BlockEntity be = getBlockEntity(world, pos); if (be == null) { data = new CompoundTag(); @@ -140,7 +147,7 @@ public CompoundTag getData() } - public BlockValue(final BlockState state, final Level world, final BlockPos position) + public BlockValue(BlockState state, ServerLevel world, BlockPos position) { this.world = world; blockState = state; @@ -148,7 +155,39 @@ public BlockValue(final BlockState state, final Level world, final BlockPos posi data = null; } - public BlockValue(final BlockState state, final Level world, final BlockPos position, final CompoundTag nbt) + public BlockValue(BlockState state) + { + this.world = null; + blockState = state; + pos = null; + data = null; + } + + public BlockValue(ServerLevel world, BlockPos position) + { + this.world = world; + blockState = null; + pos = position; + data = null; + } + + public BlockValue(BlockState state, CompoundTag nbt) + { + this.world = null; + blockState = state; + pos = null; + data = nbt; + } + + public BlockValue(BlockState state, ServerLevel world, CompoundTag nbt) + { + this.world = world; + blockState = state; + pos = null; + data = nbt; + } + + private BlockValue(@Nullable BlockState state, @Nullable ServerLevel world, @Nullable BlockPos position, @Nullable CompoundTag nbt) { this.world = world; blockState = state; @@ -160,8 +199,8 @@ public BlockValue(final BlockState state, final Level world, final BlockPos posi @Override public String getString() { - final Registry blockRegistry = world.registryAccess().registryOrThrow(Registries.BLOCK); - return nameFromRegistryId(blockRegistry.getKey(getBlockState().getBlock())); + Registry blockRegistry = world.registryAccess().registryOrThrow(Registries.BLOCK); + return nameFromResource(blockRegistry.getKey(getBlockState().getBlock())); } @Override @@ -201,29 +240,29 @@ public Level getWorld() } @Override - public Tag toTag(final boolean force) + public Tag toTag(boolean force) { if (!force) { throw new NBTSerializableValue.IncompatibleTypeException(this); } // follows falling block convertion - final CompoundTag tag = new CompoundTag(); - final CompoundTag state = new CompoundTag(); - final BlockState s = getBlockState(); + CompoundTag tag = new CompoundTag(); + CompoundTag state = new CompoundTag(); + BlockState s = getBlockState(); state.put("Name", StringTag.valueOf(world.registryAccess().registryOrThrow(Registries.BLOCK).getKey(s.getBlock()).toString())); - final Collection> properties = s.getProperties(); + Collection> properties = s.getProperties(); if (!properties.isEmpty()) { - final CompoundTag props = new CompoundTag(); - for (final Property p : properties) + CompoundTag props = new CompoundTag(); + for (Property p : properties) { props.put(p.getName(), StringTag.valueOf(s.getValue(p).toString().toLowerCase(Locale.ROOT))); } state.put("Properties", props); } tag.put("BlockState", state); - final CompoundTag dataTag = getData(); + CompoundTag dataTag = getData(); if (dataTag != null) { tag.put("TileEntityData", dataTag); @@ -265,7 +304,7 @@ public enum SpecificDirection private static final Map DIRECTION_MAP = Arrays.stream(values()).collect(Collectors.toMap(SpecificDirection::getName, d -> d)); - SpecificDirection(final String name, final double hitx, final double hity, final double hitz, final Direction blockFacing) + SpecificDirection(String name, double hitx, double hity, double hitz, Direction blockFacing) { this.name = name; this.hitOffset = new Vec3(hitx, hity, hitz); @@ -283,18 +322,18 @@ public static class PlacementContext extends BlockPlaceContext private final Direction facing; private final boolean sneakPlace; - public static PlacementContext from(final Level world, final BlockPos pos, final String direction, final boolean sneakPlace, final ItemStack itemStack) + public static PlacementContext from(Level world, BlockPos pos, String direction, boolean sneakPlace, ItemStack itemStack) { - final SpecificDirection dir = SpecificDirection.DIRECTION_MAP.get(direction); + SpecificDirection dir = SpecificDirection.DIRECTION_MAP.get(direction); if (dir == null) { throw new InternalExpressionException("unknown block placement direction: " + direction); } - final BlockHitResult hitres = new BlockHitResult(Vec3.atLowerCornerOf(pos).add(dir.hitOffset), dir.facing, pos, false); + BlockHitResult hitres = new BlockHitResult(Vec3.atLowerCornerOf(pos).add(dir.hitOffset), dir.facing, pos, false); return new PlacementContext(world, dir.facing, sneakPlace, itemStack, hitres); } - private PlacementContext(final Level world_1, final Direction direction_1, final boolean sneakPlace, final ItemStack itemStack_1, final BlockHitResult hitres) + private PlacementContext(Level world_1, Direction direction_1, boolean sneakPlace, ItemStack itemStack_1, BlockHitResult hitres) { super(world_1, null, InteractionHand.MAIN_HAND, itemStack_1, hitres); this.facing = direction_1; @@ -304,9 +343,9 @@ private PlacementContext(final Level world_1, final Direction direction_1, final @Override public BlockPos getClickedPos() { - final boolean prevcanReplaceExisting = replaceClicked; + boolean prevcanReplaceExisting = replaceClicked; replaceClicked = true; - final BlockPos ret = super.getClickedPos(); + BlockPos ret = super.getClickedPos(); replaceClicked = prevcanReplaceExisting; return ret; } diff --git a/src/main/java/carpet/script/value/BooleanValue.java b/src/main/java/carpet/script/value/BooleanValue.java index d869590d21..fc65912bc1 100644 --- a/src/main/java/carpet/script/value/BooleanValue.java +++ b/src/main/java/carpet/script/value/BooleanValue.java @@ -12,13 +12,13 @@ public class BooleanValue extends NumericValue boolean boolValue; - private BooleanValue(final boolean boolval) + private BooleanValue(boolean boolval) { super(boolval ? 1L : 0L); boolValue = boolval; } - public static BooleanValue of(final boolean value) + public static BooleanValue of(boolean value) { return value ? TRUE : FALSE; } @@ -54,7 +54,7 @@ public int hashCode() } @Override - public Tag toTag(final boolean force) + public Tag toTag(boolean force) { return ByteTag.valueOf(boolValue); } diff --git a/src/main/java/carpet/script/value/ContainerValueInterface.java b/src/main/java/carpet/script/value/ContainerValueInterface.java index 55bbfc4e2e..86db50d767 100644 --- a/src/main/java/carpet/script/value/ContainerValueInterface.java +++ b/src/main/java/carpet/script/value/ContainerValueInterface.java @@ -4,7 +4,7 @@ public interface ContainerValueInterface { boolean put(Value where, Value value); - default boolean put(final Value where, final Value value, final Value conditions) + default boolean put(Value where, Value value, Value conditions) { return put(where, value); } diff --git a/src/main/java/carpet/script/value/EntityValue.java b/src/main/java/carpet/script/value/EntityValue.java index 38c44f90b4..2acf6b82cb 100644 --- a/src/main/java/carpet/script/value/EntityValue.java +++ b/src/main/java/carpet/script/value/EntityValue.java @@ -74,6 +74,7 @@ import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.Vec3; +import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.EnumSet; @@ -97,19 +98,19 @@ public class EntityValue extends Value { private Entity entity; - public EntityValue(final Entity e) + public EntityValue(Entity e) { entity = e; } - public static Value of(final Entity e) + public static Value of(@Nullable Entity e) { return e == null ? Value.NULL : new EntityValue(e); } private static final Map selectorCache = new HashMap<>(); - public static Collection getEntitiesFromSelector(final CommandSourceStack source, final String selector) + public static Collection getEntitiesFromSelector(CommandSourceStack source, String selector) { try { @@ -122,7 +123,7 @@ public static Collection getEntitiesFromSelector(final Command selectorCache.put(selector, entitySelector); return entitySelector.findEntities(source.withMaximumPermission(4)); } - catch (final CommandSyntaxException e) + catch (CommandSyntaxException e) { throw new InternalExpressionException("Cannot select entities from " + selector); } @@ -132,7 +133,7 @@ public Entity getEntity() { if (entity instanceof final ServerPlayer serverPlayer && Vanilla.ServerPlayer_isInvalidEntityObject(serverPlayer)) { - final ServerPlayer newPlayer = entity.getServer().getPlayerList().getPlayer(entity.getUUID()); + ServerPlayer newPlayer = entity.getServer().getPlayerList().getPlayer(entity.getUUID()); if (newPlayer != null) { entity = newPlayer; @@ -141,7 +142,7 @@ public Entity getEntity() return entity; } - public static ServerPlayer getPlayerByValue(final MinecraftServer server, final Value value) + public static ServerPlayer getPlayerByValue(MinecraftServer server, Value value) { if (value instanceof final EntityValue ev && ev.getEntity() instanceof final ServerPlayer sp) { @@ -151,11 +152,11 @@ public static ServerPlayer getPlayerByValue(final MinecraftServer server, final { return null; } - final String playerName = value.getString(); + String playerName = value.getString(); return server.getPlayerList().getPlayerByName(playerName); } - public static String getPlayerNameByValue(final Value value) + public static String getPlayerNameByValue(Value value) { if (value instanceof final EntityValue ev && ev.getEntity() instanceof final ServerPlayer sp) { @@ -181,7 +182,7 @@ public boolean getBoolean() } @Override - public boolean equals(final Object v) + public boolean equals(Object v) { if (v instanceof final EntityValue ev) { @@ -191,12 +192,12 @@ public boolean equals(final Object v) } @Override - public Value in(final Value v) + public Value in(Value v) { if (v instanceof final ListValue lv) { - final List values = lv.getItems(); - final String what = values.get(0).getString(); + List values = lv.getItems(); + String what = values.get(0).getString(); Value arg = null; if (values.size() == 2) { @@ -208,7 +209,7 @@ else if (values.size() > 2) } return this.get(what, arg); } - final String what = v.getString(); + String what = v.getString(); return this.get(what, null); } @@ -226,9 +227,9 @@ public int hashCode() public static final EntityTypeTest ANY = EntityTypeTest.forClass(Entity.class); - public static EntityClassDescriptor getEntityDescriptor(String who, final MinecraftServer server) + public static EntityClassDescriptor getEntityDescriptor(String who, MinecraftServer server) { - final EntityClassDescriptor eDesc = EntityClassDescriptor.byName.get(who); + EntityClassDescriptor eDesc = EntityClassDescriptor.byName.get(who); if (eDesc == null) { boolean positive = true; @@ -237,16 +238,16 @@ public static EntityClassDescriptor getEntityDescriptor(String who, final Minecr positive = false; who = who.substring(1); } - final String booWho = who; - final HolderSet.Named> eTagValue = server.registryAccess().registryOrThrow(Registries.ENTITY_TYPE) + String booWho = who; + HolderSet.Named> eTagValue = server.registryAccess().registryOrThrow(Registries.ENTITY_TYPE) .getTag(TagKey.create(Registries.ENTITY_TYPE, InputValidator.identifierOf(who))) .orElseThrow(() -> new InternalExpressionException(booWho + " is not a valid entity descriptor")); - final Set> eTag = eTagValue.stream().map(Holder::value).collect(Collectors.toUnmodifiableSet()); + Set> eTag = eTagValue.stream().map(Holder::value).collect(Collectors.toUnmodifiableSet()); if (positive) { if (eTag.size() == 1) { - final EntityType type = eTag.iterator().next(); + EntityType type = eTag.iterator().next(); return new EntityClassDescriptor(type, Entity::isAlive, eTag.stream()); } else @@ -270,36 +271,36 @@ public static class EntityClassDescriptor public final Predicate filteringPredicate; public final List> types; - EntityClassDescriptor(final EntityTypeTest type, final Predicate predicate, final List> types) + EntityClassDescriptor(EntityTypeTest type, Predicate predicate, List> types) { this.directType = type; this.filteringPredicate = predicate; this.types = types; } - EntityClassDescriptor(final EntityTypeTest type, final Predicate predicate, final Stream> types) + EntityClassDescriptor(EntityTypeTest type, Predicate predicate, Stream> types) { this(type, predicate, types.toList()); } - public Value listValue(final RegistryAccess regs) + public Value listValue(RegistryAccess regs) { - final Registry entityRegs = regs.registryOrThrow(Registries.ENTITY_TYPE); - return ListValue.wrap(types.stream().map(et -> StringValue.of(nameFromRegistryId(entityRegs.getKey(et))))); + Registry> entityRegs = regs.registryOrThrow(Registries.ENTITY_TYPE); + return ListValue.wrap(types.stream().map(et -> nameFromRegistryId(entityRegs.getKey(et)))); } public static final Map byName = new HashMap<>() {{ - final List> allTypes = BuiltInRegistries.ENTITY_TYPE.stream().toList(); + List> allTypes = BuiltInRegistries.ENTITY_TYPE.stream().toList(); // nonliving types - final Set> projectiles = Set.of( + Set> projectiles = Set.of( EntityType.ARROW, EntityType.DRAGON_FIREBALL, EntityType.FIREWORK_ROCKET, EntityType.FIREBALL, EntityType.LLAMA_SPIT, EntityType.SMALL_FIREBALL, EntityType.SNOWBALL, EntityType.SPECTRAL_ARROW, EntityType.EGG, EntityType.ENDER_PEARL, EntityType.EXPERIENCE_BOTTLE, EntityType.POTION, EntityType.TRIDENT, EntityType.WITHER_SKULL, EntityType.FISHING_BOBBER, EntityType.SHULKER_BULLET ); - final Set> deads = Set.of( + Set> deads = Set.of( EntityType.AREA_EFFECT_CLOUD, EntityType.MARKER, EntityType.BOAT, EntityType.END_CRYSTAL, EntityType.EVOKER_FANGS, EntityType.EXPERIENCE_ORB, EntityType.EYE_OF_ENDER, EntityType.FALLING_BLOCK, EntityType.ITEM, EntityType.ITEM_FRAME, EntityType.GLOW_ITEM_FRAME, @@ -307,37 +308,37 @@ public Value listValue(final RegistryAccess regs) EntityType.TNT, EntityType.ARMOR_STAND, EntityType.CHEST_BOAT ); - final Set> minecarts = Set.of( + Set> minecarts = Set.of( EntityType.MINECART, EntityType.CHEST_MINECART, EntityType.COMMAND_BLOCK_MINECART, EntityType.FURNACE_MINECART, EntityType.HOPPER_MINECART, EntityType.SPAWNER_MINECART, EntityType.TNT_MINECART ); // living mob groups - non-defeault - final Set> undeads = Set.of( + Set> undeads = Set.of( EntityType.STRAY, EntityType.SKELETON, EntityType.WITHER_SKELETON, EntityType.ZOMBIE, EntityType.DROWNED, EntityType.ZOMBIE_VILLAGER, EntityType.ZOMBIE_HORSE, EntityType.SKELETON_HORSE, EntityType.PHANTOM, EntityType.WITHER, EntityType.ZOGLIN, EntityType.HUSK, EntityType.ZOMBIFIED_PIGLIN ); - final Set> arthropods = Set.of( + Set> arthropods = Set.of( EntityType.BEE, EntityType.ENDERMITE, EntityType.SILVERFISH, EntityType.SPIDER, EntityType.CAVE_SPIDER ); - final Set> aquatique = Set.of( + Set> aquatique = Set.of( EntityType.GUARDIAN, EntityType.TURTLE, EntityType.COD, EntityType.DOLPHIN, EntityType.PUFFERFISH, EntityType.SALMON, EntityType.SQUID, EntityType.TROPICAL_FISH ); - final Set> illagers = Set.of( + Set> illagers = Set.of( EntityType.PILLAGER, EntityType.ILLUSIONER, EntityType.VINDICATOR, EntityType.EVOKER, EntityType.RAVAGER, EntityType.WITCH ); - final Set> living = allTypes.stream().filter(et -> + Set> living = allTypes.stream().filter(et -> !deads.contains(et) && !projectiles.contains(et) && !minecarts.contains(et) ).collect(Collectors.toSet()); - final Set> regular = allTypes.stream().filter(et -> + Set> regular = allTypes.stream().filter(et -> living.contains(et) && !undeads.contains(et) && !arthropods.contains(et) && !aquatique.contains(et) && !illagers.contains(et) ).collect(Collectors.toSet()); @@ -373,23 +374,23 @@ public Value listValue(final RegistryAccess regs) put("regular", new EntityClassDescriptor(EntityTypeTest.forClass(LivingEntity.class), e -> (((LivingEntity) e).getMobType() == MobType.UNDEFINED && e.isAlive()), allTypes.stream().filter(regular::contains))); put("!regular", new EntityClassDescriptor(EntityTypeTest.forClass(LivingEntity.class), e -> (((LivingEntity) e).getMobType() != MobType.UNDEFINED && e.isAlive()), allTypes.stream().filter(et -> !regular.contains(et) && living.contains(et)))); - for (final ResourceLocation typeId : BuiltInRegistries.ENTITY_TYPE.keySet()) + for (ResourceLocation typeId : BuiltInRegistries.ENTITY_TYPE.keySet()) { - final EntityType type = BuiltInRegistries.ENTITY_TYPE.get(typeId); - final String mobType = ValueConversions.simplify(typeId); + EntityType type = BuiltInRegistries.ENTITY_TYPE.get(typeId); + String mobType = ValueConversions.simplify(typeId); put(mobType, new EntityClassDescriptor(type, net.minecraft.world.entity.EntitySelector.ENTITY_STILL_ALIVE, Stream.of(type))); put("!" + mobType, new EntityClassDescriptor(ANY, (e) -> e.getType() != type && e.isAlive(), allTypes.stream().filter(et -> et != type))); } - for (final MobCategory catId : MobCategory.values()) + for (MobCategory catId : MobCategory.values()) { - final String catStr = catId.getName(); + String catStr = catId.getName(); put(catStr, new EntityClassDescriptor(ANY, e -> ((e.getType().getCategory() == catId) && e.isAlive()), allTypes.stream().filter(et -> et.getCategory() == catId))); put("!" + catStr, new EntityClassDescriptor(ANY, e -> ((e.getType().getCategory() != catId) && e.isAlive()), allTypes.stream().filter(et -> et.getCategory() != catId))); } }}; } - public Value get(final String what, final Value arg) + public Value get(String what, @Nullable Value arg) { if (!(featureAccessors.containsKey(what))) { @@ -399,7 +400,7 @@ public Value get(final String what, final Value arg) { return featureAccessors.get(what).apply(getEntity(), arg); } - catch (final NullPointerException npe) + catch (NullPointerException npe) { throw new InternalExpressionException("Cannot fetch '" + what + "' with these arguments"); } @@ -427,7 +428,7 @@ public Value get(final String what, final Value arg) put("z", (e, a) -> new NumericValue(e.getZ())); put("motion", (e, a) -> { - final Vec3 velocity = e.getDeltaMovement(); + Vec3 velocity = e.getDeltaMovement(); return ListValue.of(new NumericValue(velocity.x), new NumericValue(velocity.y), new NumericValue(velocity.z)); }); put("motion_x", (e, a) -> new NumericValue(e.getDeltaMovement().x)); @@ -438,7 +439,7 @@ public Value get(final String what, final Value arg) put("display_name", (e, a) -> new FormattedTextValue(e.getDisplayName())); put("command_name", (e, a) -> new StringValue(e.getScoreboardName())); put("custom_name", (e, a) -> e.hasCustomName() ? new StringValue(e.getCustomName().getString()) : Value.NULL); - put("type", (e, a) -> new StringValue(nameFromRegistryId(e.getLevel().registryAccess().registryOrThrow(Registries.ENTITY_TYPE).getKey(e.getType())))); + put("type", (e, a) -> nameFromRegistryId(e.getLevel().registryAccess().registryOrThrow(Registries.ENTITY_TYPE).getKey(e.getType()))); put("is_riding", (e, a) -> BooleanValue.of(e.isPassenger())); put("is_ridden", (e, a) -> BooleanValue.of(e.isVehicle())); put("passengers", (e, a) -> ListValue.wrap(e.getPassengers().stream().map(EntityValue::new))); @@ -449,7 +450,7 @@ public Value get(final String what, final Value arg) put("scoreboard_tags", (e, a) -> ListValue.wrap(e.getTags().stream().map(StringValue::new))); put("entity_tags", (e, a) -> { - final EntityType type = e.getType(); + EntityType type = e.getType(); return ListValue.wrap(e.getServer().registryAccess().registryOrThrow(Registries.ENTITY_TYPE).getTags().filter(entry -> entry.getSecond().stream().anyMatch(h -> h.value() == type)).map(entry -> ValueConversions.of(entry.getFirst()))); }); // deprecated @@ -457,7 +458,7 @@ public Value get(final String what, final Value arg) put("has_scoreboard_tag", (e, a) -> BooleanValue.of(e.getTags().contains(a.getString()))); put("has_entity_tag", (e, a) -> { - final Optional>> tag = e.getServer().registryAccess().registryOrThrow(Registries.ENTITY_TYPE).getTag(TagKey.create(Registries.ENTITY_TYPE, InputValidator.identifierOf(a.getString()))); + Optional>> tag = e.getServer().registryAccess().registryOrThrow(Registries.ENTITY_TYPE).getTag(TagKey.create(Registries.ENTITY_TYPE, InputValidator.identifierOf(a.getString()))); if (tag.isEmpty()) { return Value.NULL; @@ -465,7 +466,7 @@ public Value get(final String what, final Value arg) //Tag> tag = e.getServer().getTags().getOrEmpty(Registry.ENTITY_TYPE_REGISTRY).getTag(InputValidator.identifierOf(a.getString())); //if (tag == null) return Value.NULL; //return BooleanValue.of(e.getType().is(tag)); - final EntityType type = e.getType(); + EntityType type = e.getType(); return BooleanValue.of(tag.get().stream().anyMatch(h -> h.value() == type)); }); @@ -475,7 +476,7 @@ public Value get(final String what, final Value arg) put("pitch", (e, a) -> new NumericValue(e.getXRot())); put("look", (e, a) -> { - final Vec3 look = e.getLookAngle(); + Vec3 look = e.getLookAngle(); return ListValue.of(new NumericValue(look.x), new NumericValue(look.y), new NumericValue(look.z)); }); put("is_burning", (e, a) -> BooleanValue.of(e.isOnFire())); @@ -488,7 +489,7 @@ public Value get(final String what, final Value arg) put("immune_to_frost", (e, a) -> BooleanValue.of(!e.canFreeze())); put("invulnerable", (e, a) -> BooleanValue.of(e.isInvulnerable())); - put("dimension", (e, a) -> new StringValue(nameFromRegistryId(e.level.dimension().location()))); // getDimId + put("dimension", (e, a) -> nameFromRegistryId(e.level.dimension().location())); // getDimId put("height", (e, a) -> new NumericValue(e.getDimensions(Pose.STANDING).height)); put("width", (e, a) -> new NumericValue(e.getDimensions(Pose.STANDING).width)); put("eye_height", (e, a) -> new NumericValue(e.getEyeHeight())); @@ -507,7 +508,7 @@ public Value get(final String what, final Value arg) put("target", (e, a) -> { if (e instanceof final Mob mob) { - final LivingEntity target = mob.getTarget(); // there is also getAttacking in living.... + LivingEntity target = mob.getTarget(); // there is also getAttacking in living.... if (target != null) { return new EntityValue(target); @@ -515,7 +516,7 @@ public Value get(final String what, final Value arg) } return Value.NULL; }); - put("home", (e, a) -> e instanceof final Mob mob ? (mob.getRestrictRadius() > 0) ? new BlockValue(null, e.getCommandSenderWorld(), mob.getRestrictCenter()) : Value.FALSE : Value.NULL); + put("home", (e, a) -> e instanceof final Mob mob ? (mob.getRestrictRadius() > 0) ? new BlockValue(null, (ServerLevel) e.getLevel(), mob.getRestrictCenter()) : Value.FALSE : Value.NULL); put("spawn_point", (e, a) -> { if (e instanceof final ServerPlayer spe) { @@ -553,7 +554,7 @@ public Value get(final String what, final Value arg) put("path", (e, a) -> { if (e instanceof final Mob mob) { - final Path path = mob.getNavigation().getPath(); + Path path = mob.getNavigation().getPath(); if (path == null) { return Value.NULL; @@ -564,22 +565,22 @@ public Value get(final String what, final Value arg) }); put("brain", (e, a) -> { - final String module = a.getString(); - final MemoryModuleType moduleType = e.getLevel().registryAccess().registryOrThrow(Registries.MEMORY_MODULE_TYPE).get(InputValidator.identifierOf(module)); + String module = a.getString(); + MemoryModuleType moduleType = e.getLevel().registryAccess().registryOrThrow(Registries.MEMORY_MODULE_TYPE).get(InputValidator.identifierOf(module)); if (moduleType == MemoryModuleType.DUMMY) { return Value.NULL; } if (e instanceof final LivingEntity livingEntity) { - final Brain brain = livingEntity.getBrain(); - final Map, Optional>> memories = brain.getMemories(); - final Optional> optmemory = memories.get(moduleType); + Brain brain = livingEntity.getBrain(); + Map, Optional>> memories = brain.getMemories(); + Optional> optmemory = memories.get(moduleType); if (optmemory == null || !optmemory.isPresent()) { return Value.NULL; } - final ExpirableValue memory = optmemory.get(); + ExpirableValue memory = optmemory.get(); return ValueConversions.fromTimedMemory(e, memory.getTimeToLive(), memory.getValue()); } return Value.NULL; @@ -604,22 +605,22 @@ public Value get(final String what, final Value arg) put("player_type", (e, a) -> { if (e instanceof final Player p) { - final String moddedType = Carpet.isModdedPlayer(p); + String moddedType = Carpet.isModdedPlayer(p); if (moddedType != null) { return StringValue.of(moddedType); } - final MinecraftServer server = p.getCommandSenderWorld().getServer(); + MinecraftServer server = p.getCommandSenderWorld().getServer(); if (server.isDedicatedServer()) { return new StringValue("multiplayer"); } - final boolean runningLan = server.isPublished(); + boolean runningLan = server.isPublished(); if (!runningLan) { return new StringValue("singleplayer"); } - final boolean isowner = server.isSingleplayerOwner(p.getGameProfile()); + boolean isowner = server.isSingleplayerOwner(p.getGameProfile()); if (isowner) { return new StringValue("lan_host"); @@ -644,8 +645,8 @@ public Value get(final String what, final Value arg) } if (a == null) { - final List effects = new ArrayList<>(); - for (final MobEffectInstance p : le.getActiveEffects()) + List effects = new ArrayList<>(); + for (MobEffectInstance p : le.getActiveEffects()) { effects.add(ListValue.of( new StringValue(p.getDescriptionId().replaceFirst("^effect\\.minecraft\\.", "")), @@ -655,8 +656,8 @@ public Value get(final String what, final Value arg) } return ListValue.wrap(effects); } - final String effectName = a.getString(); - final MobEffect potion = BuiltInRegistries.MOB_EFFECT.get(InputValidator.identifierOf(effectName)); + String effectName = a.getString(); + MobEffect potion = BuiltInRegistries.MOB_EFFECT.get(InputValidator.identifierOf(effectName)); if (potion == null) { throw new InternalExpressionException("No such an effect: " + effectName); @@ -665,7 +666,7 @@ public Value get(final String what, final Value arg) { return Value.NULL; } - final MobEffectInstance pe = le.getEffect(potion); + MobEffectInstance pe = le.getEffect(potion); return ListValue.of(new NumericValue(pe.getAmplifier()), new NumericValue(pe.getDuration())); }); @@ -698,12 +699,12 @@ public Value get(final String what, final Value arg) put("active_block", (e, a) -> { if (e instanceof final ServerPlayer sp) { - final BlockPos pos = Vanilla.ServerPlayerGameMode_getCurrentBlockPosition(sp.gameMode); + BlockPos pos = Vanilla.ServerPlayerGameMode_getCurrentBlockPosition(sp.gameMode); if (pos == null) { return Value.NULL; } - return new BlockValue(null, e.level, pos); + return new BlockValue(null, sp.getLevel(), pos); } return Value.NULL; }); @@ -711,7 +712,7 @@ public Value get(final String what, final Value arg) put("breaking_progress", (e, a) -> { if (e instanceof final ServerPlayer sp) { - final int progress = Vanilla.ServerPlayerGameMode_getCurrentBlockBreakingProgress (sp.gameMode); + int progress = Vanilla.ServerPlayerGameMode_getCurrentBlockBreakingProgress (sp.gameMode); return progress < 0 ? Value.NULL : new NumericValue(progress); } return Value.NULL; @@ -748,7 +749,7 @@ public Value get(final String what, final Value arg) } else { - final List args = lv.getItems(); + List args = lv.getItems(); if (args.size() == 0) { throw new InternalExpressionException("'trace' needs more arguments"); @@ -760,7 +761,7 @@ public Value get(final String what, final Value arg) blocks = false; for (int i = 1; i < args.size(); i++) { - final String what = args.get(i).getString(); + String what = args.get(i).getString(); if (what.equalsIgnoreCase("entities")) { entities = true; @@ -791,7 +792,7 @@ else if (e instanceof final ServerPlayer sp && sp.gameMode.isCreative()) reach = 5.0f; } - final HitResult hitres; + HitResult hitres; if (entities && !blocks) { hitres = Tracer.rayTraceEntities(e, 1, reach, reach * reach); @@ -818,7 +819,7 @@ else if (entities) case MISS: return Value.NULL; case BLOCK: - return new BlockValue(null, e.getCommandSenderWorld(), ((BlockHitResult) hitres).getBlockPos()); + return new BlockValue((ServerLevel) e.getCommandSenderWorld(), ((BlockHitResult) hitres).getBlockPos()); case ENTITY: return new EntityValue(((EntityHitResult) hitres).getEntity()); } @@ -830,14 +831,14 @@ else if (entities) { return Value.NULL; } - final Registry attributes = e.getLevel().registryAccess().registryOrThrow(Registries.ATTRIBUTE); + Registry attributes = e.getLevel().registryAccess().registryOrThrow(Registries.ATTRIBUTE); if (a == null) { - final AttributeMap container = el.getAttributes(); + AttributeMap container = el.getAttributes(); return MapValue.wrap(attributes.stream().filter(container::hasAttribute).collect(Collectors.toMap(aa -> ValueConversions.of(attributes.getKey(aa)), aa -> NumericValue.of(container.getValue(aa))))); } - final ResourceLocation id = InputValidator.identifierOf(a.getString()); - final Attribute attrib = attributes.getOptional(id).orElseThrow( + ResourceLocation id = InputValidator.identifierOf(a.getString()); + Attribute attrib = attributes.getOptional(id).orElseThrow( () -> new InternalExpressionException("Unknown attribute: " + a.getString()) ); if (!el.getAttributes().hasAttribute(attrib)) @@ -848,7 +849,7 @@ else if (entities) }); put("nbt", (e, a) -> { - final CompoundTag nbttagcompound = e.saveWithoutId((new CompoundTag())); + CompoundTag nbttagcompound = e.saveWithoutId((new CompoundTag())); if (a == null) { return new NBTSerializableValue(nbttagcompound); @@ -861,7 +862,7 @@ else if (entities) }); }}; - public void set(final String what, final Value toWhat) + public void set(String what, @Nullable Value toWhat) { if (!(featureModifiers.containsKey(what))) { @@ -871,17 +872,17 @@ public void set(final String what, final Value toWhat) { featureModifiers.get(what).accept(getEntity(), toWhat); } - catch (final NullPointerException npe) + catch (NullPointerException npe) { throw new InternalExpressionException("'modify' for '" + what + "' expects a value"); } - catch (final IndexOutOfBoundsException ind) + catch (IndexOutOfBoundsException ind) { throw new InternalExpressionException("Wrong number of arguments for `modify` option: " + what); } } - private static void updatePosition(final Entity e, final double x, final double y, final double z, final float yaw, final float pitch) + private static void updatePosition(Entity e, double x, double y, double z, float yaw, float pitch) { if ( !Double.isFinite(x) || Double.isNaN(x) || @@ -896,7 +897,7 @@ private static void updatePosition(final Entity e, final double x, final double if (e instanceof final ServerPlayer sp) { // this forces position but doesn't angles for some reason. Need both in the API in the future. - final EnumSet set = EnumSet.noneOf(RelativeMovement.class); + EnumSet set = EnumSet.noneOf(RelativeMovement.class); set.add(RelativeMovement.X_ROT); set.add(RelativeMovement.Y_ROT); sp.connection.teleport(x, y, z, yaw, pitch, set); @@ -921,7 +922,7 @@ private static void updatePosition(final Entity e, final double x, final double } } - private static void updateVelocity(final Entity e, final double scale) + private static void updateVelocity(Entity e, double scale) { e.hurtMarked = true; if (Math.abs(scale) > 10000) @@ -935,7 +936,7 @@ private static void updateVelocity(final Entity e, final double scale) put("remove", (entity, value) -> entity.discard()); // using discard here - will see other options if valid put("age", (e, v) -> e.tickCount = Math.abs((int) NumericValue.asNumber(v).getLong())); put("health", (e, v) -> { - final float health = (float) NumericValue.asNumber(v).getDouble(); + float health = (float) NumericValue.asNumber(v).getDouble(); if (health <= 0f && e instanceof final ServerPlayer player) { if (player.containerMenu != null) @@ -954,7 +955,7 @@ private static void updateVelocity(final Entity e, final double scale) }); put("may_fly", (e, v) -> { - final boolean mayFly = v.getBoolean(); + boolean mayFly = v.getBoolean(); if (e instanceof final ServerPlayer player) { player.getAbilities().mayfly = mayFly; @@ -967,7 +968,7 @@ private static void updateVelocity(final Entity e, final double scale) }); put("flying", (e, v) -> { - final boolean flying = v.getBoolean(); + boolean flying = v.getBoolean(); if (e instanceof final ServerPlayer player) { player.getAbilities().flying = flying; @@ -976,7 +977,7 @@ private static void updateVelocity(final Entity e, final double scale) }); put("may_build", (e, v) -> { - final boolean mayBuild = v.getBoolean(); + boolean mayBuild = v.getBoolean(); if (e instanceof final ServerPlayer player) { player.getAbilities().mayBuild = mayBuild; @@ -985,7 +986,7 @@ private static void updateVelocity(final Entity e, final double scale) }); put("insta_build", (e, v) -> { - final boolean instaBuild = v.getBoolean(); + boolean instaBuild = v.getBoolean(); if (e instanceof final ServerPlayer player) { player.getAbilities().instabuild = instaBuild; @@ -994,7 +995,7 @@ private static void updateVelocity(final Entity e, final double scale) }); put("fly_speed", (e, v) -> { - final float flySpeed = NumericValue.asNumber(v).getFloat(); + float flySpeed = NumericValue.asNumber(v).getFloat(); if (e instanceof final ServerPlayer player) { player.getAbilities().setFlyingSpeed(flySpeed); @@ -1003,7 +1004,7 @@ private static void updateVelocity(final Entity e, final double scale) }); put("walk_speed", (e, v) -> { - final float walkSpeed = NumericValue.asNumber(v).getFloat(); + float walkSpeed = NumericValue.asNumber(v).getFloat(); if (e instanceof final ServerPlayer player) { player.getAbilities().setWalkingSpeed(walkSpeed); @@ -1015,7 +1016,7 @@ private static void updateVelocity(final Entity e, final double scale) { if (e instanceof final ServerPlayer player) { - final int slot = NumericValue.asNumber(v).getInt(); + int slot = NumericValue.asNumber(v).getInt(); player.connection.send(new ClientboundSetCarriedItemPacket(slot)); } }); @@ -1042,7 +1043,7 @@ private static void updateVelocity(final Entity e, final double scale) { throw new InternalExpressionException("Expected a list of 5 parameters as a second argument"); } - final List coords = lv.getItems(); + List coords = lv.getItems(); updatePosition(e, NumericValue.asNumber(coords.get(0)).getDouble(), NumericValue.asNumber(coords.get(1)).getDouble(), @@ -1057,7 +1058,7 @@ private static void updateVelocity(final Entity e, final double scale) { throw new InternalExpressionException("Expected a list of 3 parameters as a second argument"); } - final List coords = lv.getItems(); + List coords = lv.getItems(); updatePosition(e, NumericValue.asNumber(coords.get(0)).getDouble(), NumericValue.asNumber(coords.get(1)).getDouble(), @@ -1092,11 +1093,11 @@ private static void updateVelocity(final Entity e, final double scale) { throw new InternalExpressionException("Expected a list of 3 parameters as a second argument"); } - final List vec = lv.getItems(); + List vec = lv.getItems(); float x = NumericValue.asNumber(vec.get(0)).getFloat(); float y = NumericValue.asNumber(vec.get(1)).getFloat(); float z = NumericValue.asNumber(vec.get(2)).getFloat(); - final float l = Mth.sqrt(x * x + y * y + z * z); + float l = Mth.sqrt(x * x + y * y + z * z); if (l == 0) { return; @@ -1104,8 +1105,8 @@ private static void updateVelocity(final Entity e, final double scale) x /= l; y /= l; z /= l; - final float pitch = (float) -Math.asin(y) / 0.017453292F; - final float yaw = (float) (x == 0 && z == 0 ? e.getYRot() : Mth.atan2(-x, z) / 0.017453292F); + float pitch = (float) -Math.asin(y) / 0.017453292F; + float yaw = (float) (x == 0 && z == 0 ? e.getYRot() : Mth.atan2(-x, z) / 0.017453292F); updatePosition(e, e.getX(), e.getY(), e.getZ(), yaw, pitch); }); @@ -1118,7 +1119,7 @@ private static void updateVelocity(final Entity e, final double scale) { throw new InternalExpressionException("Expected a list of 3 parameters as a second argument"); } - final List coords = lv.getItems(); + List coords = lv.getItems(); updatePosition(e, e.getX() + NumericValue.asNumber(coords.get(0)).getDouble(), e.getY() + NumericValue.asNumber(coords.get(1)).getDouble(), @@ -1134,31 +1135,31 @@ private static void updateVelocity(final Entity e, final double scale) { throw new InternalExpressionException("Expected a list of 3 parameters as a second argument"); } - final List coords = lv.getItems(); - final double dx = NumericValue.asNumber(coords.get(0)).getDouble(); - final double dy = NumericValue.asNumber(coords.get(1)).getDouble(); - final double dz = NumericValue.asNumber(coords.get(2)).getDouble(); + List coords = lv.getItems(); + double dx = NumericValue.asNumber(coords.get(0)).getDouble(); + double dy = NumericValue.asNumber(coords.get(1)).getDouble(); + double dz = NumericValue.asNumber(coords.get(2)).getDouble(); e.setDeltaMovement(dx, dy, dz); updateVelocity(e, Mth.absMax(Mth.absMax(dx, dy), dz)); }); put("motion_x", (e, v) -> { - final Vec3 velocity = e.getDeltaMovement(); - final double dv = NumericValue.asNumber(v).getDouble(); + Vec3 velocity = e.getDeltaMovement(); + double dv = NumericValue.asNumber(v).getDouble(); e.setDeltaMovement(dv, velocity.y, velocity.z); updateVelocity(e, dv); }); put("motion_y", (e, v) -> { - final Vec3 velocity = e.getDeltaMovement(); - final double dv = NumericValue.asNumber(v).getDouble(); + Vec3 velocity = e.getDeltaMovement(); + double dv = NumericValue.asNumber(v).getDouble(); e.setDeltaMovement(velocity.x, dv, velocity.z); updateVelocity(e, dv); }); put("motion_z", (e, v) -> { - final Vec3 velocity = e.getDeltaMovement(); - final double dv = NumericValue.asNumber(v).getDouble(); + Vec3 velocity = e.getDeltaMovement(); + double dv = NumericValue.asNumber(v).getDouble(); e.setDeltaMovement(velocity.x, velocity.y, dv); updateVelocity(e, dv); }); @@ -1169,7 +1170,7 @@ private static void updateVelocity(final Entity e, final double scale) { throw new InternalExpressionException("Expected a list of 3 parameters as a second argument"); } - final List coords = lv.getItems(); + List coords = lv.getItems(); e.push( NumericValue.asNumber(coords.get(0)).getDouble(), NumericValue.asNumber(coords.get(1)).getDouble(), @@ -1232,7 +1233,7 @@ private static void updateVelocity(final Entity e, final double scale) } else if (v instanceof final ListValue lv) { - for (final Value element : lv.getItems()) + for (Value element : lv.getItems()) { if (element instanceof final EntityValue ev) { @@ -1248,7 +1249,7 @@ else if (v instanceof final ListValue lv) } if (v instanceof final ListValue lv) { - for (final Value element : lv.getItems()) + for (Value element : lv.getItems()) { e.addTag(element.getString()); } @@ -1265,7 +1266,7 @@ else if (v instanceof final ListValue lv) } if (v instanceof final ListValue lv) { - for (final Value element : lv.getItems()) + for (Value element : lv.getItems()) { e.removeTag(element.getString()); } @@ -1309,13 +1310,13 @@ else if (v instanceof final ListValue lv) if (v.isNull()) { ec.restrictTo(BlockPos.ZERO, -1); - final Map tasks = Vanilla.Mob_getTemporaryTasks(ec); + Map tasks = Vanilla.Mob_getTemporaryTasks(ec); Vanilla.Mob_getAI(ec, false).removeGoal(tasks.get("home")); tasks.remove("home"); return; } - final BlockPos pos; + BlockPos pos; int distance = 16; if (v instanceof final BlockValue bv) @@ -1328,8 +1329,8 @@ else if (v instanceof final ListValue lv) } else if (v instanceof final ListValue lv) { - final List list = lv.getItems(); - final Vector3Argument locator = Vector3Argument.findIn(list, 0, false, false); + List list = lv.getItems(); + Vector3Argument locator = Vector3Argument.findIn(list, 0, false, false); pos = new BlockPos(locator.vec.x, locator.vec.y, locator.vec.z); if (list.size() > locator.offset) { @@ -1342,10 +1343,10 @@ else if (v instanceof final ListValue lv) } ec.restrictTo(pos, distance); - final Map tasks = Vanilla.Mob_getTemporaryTasks(ec); + Map tasks = Vanilla.Mob_getTemporaryTasks(ec); if (!tasks.containsKey("home")) { - final Goal task = new MoveTowardsRestrictionGoal(ec, 1.0D); + Goal task = new MoveTowardsRestrictionGoal(ec, 1.0D); tasks.put("home", task); Vanilla.Mob_getAI(ec, false).addGoal(10, task); } @@ -1362,15 +1363,15 @@ else if (v instanceof final ListValue lv) } else if (a instanceof final ListValue lv) { - final List params = lv.getItems(); - final Vector3Argument blockLocator = Vector3Argument.findIn(params, 0, false, false); - final BlockPos pos = new BlockPos(blockLocator.vec); + List params = lv.getItems(); + Vector3Argument blockLocator = Vector3Argument.findIn(params, 0, false, false); + BlockPos pos = new BlockPos(blockLocator.vec); ResourceKey world = spe.getCommandSenderWorld().dimension(); float angle = spe.getYHeadRot(); boolean forced = false; if (params.size() > blockLocator.offset) { - final Value worldValue = params.get(blockLocator.offset + 0); + Value worldValue = params.get(blockLocator.offset + 0); world = ValueConversions.dimFromValue(worldValue, spe.getServer()).dimension(); if (params.size() > blockLocator.offset + 1) { @@ -1467,11 +1468,11 @@ else if (a.isNull()) } else if (v instanceof final ListValue lv) { - final List list = lv.getItems(); + List list = lv.getItems(); if (list.size() >= 1 && list.size() <= 6) { - final String effectName = list.get(0).getString(); - final MobEffect effect = BuiltInRegistries.MOB_EFFECT.get(InputValidator.identifierOf(effectName)); + String effectName = list.get(0).getString(); + MobEffect effect = BuiltInRegistries.MOB_EFFECT.get(InputValidator.identifierOf(effectName)); if (effect == null) { throw new InternalExpressionException("Wrong effect name: " + effectName); @@ -1481,7 +1482,7 @@ else if (v instanceof final ListValue lv) le.removeEffect(effect); return; } - final int duration = (int) NumericValue.asNumber(list.get(1)).getLong(); + int duration = (int) NumericValue.asNumber(list.get(1)).getLong(); if (duration <= 0) { le.removeEffect(effect); @@ -1513,8 +1514,8 @@ else if (v instanceof final ListValue lv) } else { - final String effectName = v.getString(); - final MobEffect effect = BuiltInRegistries.MOB_EFFECT.get(InputValidator.identifierOf(effectName)); + String effectName = v.getString(); + MobEffect effect = BuiltInRegistries.MOB_EFFECT.get(InputValidator.identifierOf(effectName)); if (effect == null) { throw new InternalExpressionException("Wrong effect name: " + effectName); @@ -1530,7 +1531,7 @@ else if (v instanceof final ListValue lv) { return; } - final GameType toSet = v instanceof NumericValue ? + GameType toSet = v instanceof NumericValue ? GameType.byId(((NumericValue) v).getInt()) : GameType.byName(v.getString().toLowerCase(Locale.ROOT), null); if (toSet != null) @@ -1564,7 +1565,7 @@ else if (v instanceof final ListValue lv) InteractionHand hand = InteractionHand.MAIN_HAND; if (v != null) { - final String handString = v.getString().toLowerCase(Locale.ROOT); + String handString = v.getString().toLowerCase(Locale.ROOT); if (handString.equals("offhand") || handString.equals("off_hand")) { hand = InteractionHand.OFF_HAND; @@ -1579,7 +1580,7 @@ else if (v instanceof final ListValue lv) put("gravity", (e, v) -> e.setNoGravity(!v.getBoolean())); put("invulnerable", (e, v) -> { - final boolean invulnerable = v.getBoolean(); + boolean invulnerable = v.getBoolean(); if (e instanceof final ServerPlayer player) { player.getAbilities().invulnerable = invulnerable; @@ -1663,7 +1664,7 @@ else if (v instanceof final ListValue lv) put("breaking_progress", (e, a) -> { if (e instanceof final ServerPlayer sp) { - final int progress = (a == null || a.isNull()) ? -1 : NumericValue.asNumber(a).getInt(); + int progress = (a == null || a.isNull()) ? -1 : NumericValue.asNumber(a).getInt(); Vanilla.ServerPlayerGameMode_setBlockBreakingProgress(sp.gameMode, progress); } }); @@ -1671,8 +1672,8 @@ else if (v instanceof final ListValue lv) put("nbt", (e, v) -> { if (!(e instanceof Player)) { - final UUID uUID = e.getUUID(); - final Value tagValue = NBTSerializableValue.fromValue(v); + UUID uUID = e.getUUID(); + Value tagValue = NBTSerializableValue.fromValue(v); if (tagValue instanceof final NBTSerializableValue nbtsv) { e.load(nbtsv.getCompoundTag()); @@ -1683,11 +1684,11 @@ else if (v instanceof final ListValue lv) put("nbt_merge", (e, v) -> { if (!(e instanceof Player)) { - final UUID uUID = e.getUUID(); - final Value tagValue = NBTSerializableValue.fromValue(v); + UUID uUID = e.getUUID(); + Value tagValue = NBTSerializableValue.fromValue(v); if (tagValue instanceof final NBTSerializableValue nbtsv) { - final CompoundTag nbttagcompound = e.saveWithoutId((new CompoundTag())); + CompoundTag nbttagcompound = e.saveWithoutId((new CompoundTag())); nbttagcompound.merge(nbtsv.getCompoundTag()); e.load(nbttagcompound); e.setUUID(uUID); @@ -1710,7 +1711,7 @@ else if (v instanceof final ListValue lv) }); put("item", (e, v) -> { - final ItemStack item = ValueConversions.getItemStackFromValue(v, true, e.level.registryAccess()); + ItemStack item = ValueConversions.getItemStackFromValue(v, true, e.level.registryAccess()); if (e instanceof final ItemEntity itementity) { itementity.setItem(item); @@ -1725,9 +1726,9 @@ else if (v instanceof final ListValue lv) // "effect_"name [] }}; - public void setEvent(final CarpetContext cc, final String eventName, final FunctionValue fun, final List args) + public void setEvent(CarpetContext cc, String eventName, FunctionValue fun, List args) { - final EntityEventsGroup.Event event = EntityEventsGroup.Event.byName.get(eventName); + EntityEventsGroup.Event event = EntityEventsGroup.Event.byName.get(eventName); if (event == null) { throw new InternalExpressionException("Unknown entity event: " + eventName); @@ -1736,15 +1737,15 @@ public void setEvent(final CarpetContext cc, final String eventName, final Funct } @Override - public net.minecraft.nbt.Tag toTag(final boolean force) + public net.minecraft.nbt.Tag toTag(boolean force) { if (!force) { throw new NBTSerializableValue.IncompatibleTypeException(this); } - final CompoundTag tag = new CompoundTag(); + CompoundTag tag = new CompoundTag(); tag.put("Data", getEntity().saveWithoutId(new CompoundTag())); - final Registry> reg = getEntity().level.registryAccess().registryOrThrow(Registries.ENTITY_TYPE); + Registry> reg = getEntity().level.registryAccess().registryOrThrow(Registries.ENTITY_TYPE); tag.put("Name", StringTag.valueOf(reg.getKey(getEntity().getType()).toString())); return tag; } diff --git a/src/main/java/carpet/script/value/FormattedTextValue.java b/src/main/java/carpet/script/value/FormattedTextValue.java index d55e3190ab..bc93f4805e 100644 --- a/src/main/java/carpet/script/value/FormattedTextValue.java +++ b/src/main/java/carpet/script/value/FormattedTextValue.java @@ -10,15 +10,15 @@ public class FormattedTextValue extends StringValue { Component text; - public FormattedTextValue(final Component text) + public FormattedTextValue(Component text) { super(null); this.text = text; } - public static Value combine(final Value left, final Value right) + public static Value combine(Value left, Value right) { - final MutableComponent text; + MutableComponent text; if (left instanceof final FormattedTextValue ftv) { text = ftv.getText().copy(); @@ -45,7 +45,7 @@ public static Value combine(final Value left, final Value right) return new FormattedTextValue(text); } - public static Value of(final Component text) + public static Value of(Component text) { return text == null ? Value.NULL : new FormattedTextValue(text); } @@ -80,7 +80,7 @@ public Component getText() } @Override - public Tag toTag(final boolean force) + public Tag toTag(boolean force) { if (!force) { @@ -96,7 +96,7 @@ public JsonElement toJson() } @Override - public Value add(final Value o) + public Value add(Value o) { return combine(this, o); } @@ -106,12 +106,12 @@ public String serialize() return Component.Serializer.toJson(text); } - public static FormattedTextValue deserialize(final String serialized) + public static FormattedTextValue deserialize(String serialized) { return new FormattedTextValue(Component.Serializer.fromJson(serialized)); } - public static Component getTextByValue(final Value value) + public static Component getTextByValue(Value value) { return (value instanceof final FormattedTextValue ftv) ? ftv.getText() : Component.literal(value.getString()); } diff --git a/src/main/java/carpet/script/value/FrameworkValue.java b/src/main/java/carpet/script/value/FrameworkValue.java index c1987711f2..a432974e5c 100644 --- a/src/main/java/carpet/script/value/FrameworkValue.java +++ b/src/main/java/carpet/script/value/FrameworkValue.java @@ -29,7 +29,7 @@ public int hashCode() } @Override - public Tag toTag(final boolean force) + public Tag toTag(boolean force) { throw new UnsupportedOperationException("Scarpet language component cannot be serialized to the tag"); } diff --git a/src/main/java/carpet/script/value/FunctionAnnotationValue.java b/src/main/java/carpet/script/value/FunctionAnnotationValue.java index 83b8f2f16e..0baede8794 100644 --- a/src/main/java/carpet/script/value/FunctionAnnotationValue.java +++ b/src/main/java/carpet/script/value/FunctionAnnotationValue.java @@ -12,7 +12,7 @@ public enum Type public Type type; - public FunctionAnnotationValue(final Value variable, final Type type) + public FunctionAnnotationValue(Value variable, Type type) { if (variable.boundVariable == null) { @@ -41,7 +41,7 @@ public int hashCode() } @Override - public Tag toTag(final boolean force) + public Tag toTag(boolean force) { throw new UnsupportedOperationException("Global value cannot be serialized to the tag"); } diff --git a/src/main/java/carpet/script/value/FunctionSignatureValue.java b/src/main/java/carpet/script/value/FunctionSignatureValue.java index 59ed5290a9..e1d9fd1c33 100644 --- a/src/main/java/carpet/script/value/FunctionSignatureValue.java +++ b/src/main/java/carpet/script/value/FunctionSignatureValue.java @@ -4,12 +4,12 @@ public class FunctionSignatureValue extends FrameworkValue { - private String identifier; - private List arguments; - private List globals; - private String varArgs; + private final String identifier; + private final List arguments; + private final List globals; + private final String varArgs; - public FunctionSignatureValue(final String name, final List args, final String varArgs, final List globals) + public FunctionSignatureValue(String name, List args, String varArgs, List globals) { this.identifier = name; this.arguments = args; diff --git a/src/main/java/carpet/script/value/FunctionUnpackedArgumentsValue.java b/src/main/java/carpet/script/value/FunctionUnpackedArgumentsValue.java index 4e00ecc94f..d44563c5a9 100644 --- a/src/main/java/carpet/script/value/FunctionUnpackedArgumentsValue.java +++ b/src/main/java/carpet/script/value/FunctionUnpackedArgumentsValue.java @@ -4,7 +4,7 @@ public class FunctionUnpackedArgumentsValue extends ListValue { - public FunctionUnpackedArgumentsValue(final List list) + public FunctionUnpackedArgumentsValue(List list) { super(list); } diff --git a/src/main/java/carpet/script/value/FunctionValue.java b/src/main/java/carpet/script/value/FunctionValue.java index 566471e955..010dedecc4 100644 --- a/src/main/java/carpet/script/value/FunctionValue.java +++ b/src/main/java/carpet/script/value/FunctionValue.java @@ -34,7 +34,7 @@ public class FunctionValue extends Value implements Fluff.ILazyFunction private static long variantCounter = 1; private long variant; - private FunctionValue(final Expression expression, final Tokenizer.Token token, final String name, final LazyValue body, final List args, final String varArgs) + private FunctionValue(Expression expression, Tokenizer.Token token, String name, LazyValue body, List args, String varArgs) { this.expression = expression; this.token = token; @@ -46,7 +46,7 @@ private FunctionValue(final Expression expression, final Tokenizer.Token token, variant = 0L; } - public FunctionValue(final Expression expression, final Tokenizer.Token token, final String name, final LazyValue body, final List args, final String varArgs, final Map outerState) + public FunctionValue(Expression expression, Tokenizer.Token token, String name, LazyValue body, List args, String varArgs, Map outerState) { this.expression = expression; this.token = token; @@ -72,7 +72,7 @@ public Module getModule() @Override public String getPrettyString() { - final List stringArgs = new ArrayList<>(args); + List stringArgs = new ArrayList<>(args); if (outerState != null) { stringArgs.addAll(outerState.entrySet().stream().map(e -> @@ -95,7 +95,7 @@ public boolean getBoolean() @Override protected Value clone() { - final FunctionValue ret = new FunctionValue(expression, token, name, body, args, varArgs); + FunctionValue ret = new FunctionValue(expression, token, name, body, args, varArgs); ret.outerState = this.outerState; ret.variant = this.variant; return ret; @@ -108,17 +108,17 @@ public int hashCode() } @Override - public boolean equals(final Object o) + public boolean equals(Object o) { return o instanceof final FunctionValue fv && name.equals(fv.name) && variant == fv.variant; } @Override - public int compareTo(final Value o) + public int compareTo(Value o) { if (o instanceof final FunctionValue fv) { - final int nameSame = this.name.compareTo(fv.name); + int nameSame = this.name.compareTo(fv.name); return nameSame != 0 ? nameSame : (int) (variant - fv.variant); } return getString().compareTo(o.getString()); @@ -137,7 +137,7 @@ public String getTypeString() } @Override - public Value slice(final long from, final Long to) + public Value slice(long from, Long to) { throw new InternalExpressionException("Cannot slice a function"); } @@ -154,31 +154,31 @@ public boolean numParamsVaries() return varArgs != null; } - public LazyValue callInContext(final Context c, final Context.Type type, final List params) + public LazyValue callInContext(Context c, Context.Type type, List params) { try { return execute(c, type, expression, token, params); } - catch (final ExpressionException exc) + catch (ExpressionException exc) { exc.stack.add(this); throw exc; } - catch (final InternalExpressionException exc) + catch (InternalExpressionException exc) { exc.stack.add(this); throw new ExpressionException(c, expression, token, exc.getMessage(), exc.stack); } - catch (final ArithmeticException exc) + catch (ArithmeticException exc) { throw new ExpressionException(c, expression, token, "Your math is wrong, " + exc.getMessage(), Collections.singletonList(this)); } } - public void checkArgs(final int candidates) + public void checkArgs(int candidates) { - final int actual = getArguments().size(); + int actual = getArguments().size(); if (candidates < actual) { @@ -190,13 +190,13 @@ public void checkArgs(final int candidates) } } - public static List unpackArgs(final List lazyParams, final Context c) + public static List unpackArgs(List lazyParams, Context c) { // TODO we shoudn't need that if all fuctions are not lazy really - final List params = new ArrayList<>(); - for (final LazyValue lv : lazyParams) + List params = new ArrayList<>(); + for (LazyValue lv : lazyParams) { - final Value param = lv.evalValue(c, Context.NONE); + Value param = lv.evalValue(c, Context.NONE); if (param instanceof FunctionUnpackedArgumentsValue) { CarpetScriptServer.LOG.error("How did we get here?"); @@ -211,13 +211,13 @@ public static List unpackArgs(final List lazyParams, final Con } @Override - public LazyValue lazyEval(final Context c, final Context.Type type, final Expression e, final Tokenizer.Token t, final List lazyParams) + public LazyValue lazyEval(Context c, Context.Type type, Expression e, Tokenizer.Token t, List lazyParams) { - final List resolvedParams = unpackArgs(lazyParams, c); + List resolvedParams = unpackArgs(lazyParams, c); return execute(c, type, e, t, resolvedParams); } - public LazyValue execute(final Context c, final Context.Type type, final Expression e, final Tokenizer.Token t, final List params) + public LazyValue execute(Context c, Context.Type type, Expression e, Tokenizer.Token t, List params) { assertArgsOk(params, fixedArgs -> { if (fixedArgs) // wrong number of args for fixed args @@ -229,14 +229,14 @@ public LazyValue execute(final Context c, final Context.Type type, final Express } // too few args for varargs - final List argList = new ArrayList<>(args); + List argList = new ArrayList<>(args); argList.add("... " + varArgs); throw new ExpressionException(c, e, t, "Incorrect number of arguments for function " + name + ". Should be at least " + args.size() + ", not " + params.size() + " like " + argList ); }); - final Context newFrame = c.recreate(); + Context newFrame = c.recreate(); if (outerState != null) { @@ -244,18 +244,18 @@ public LazyValue execute(final Context c, final Context.Type type, final Express } for (int i = 0; i < args.size(); i++) { - final String arg = args.get(i); - final Value val = params.get(i).reboundedTo(arg); // todo check if we need to copy that + String arg = args.get(i); + Value val = params.get(i).reboundedTo(arg); // todo check if we need to copy that newFrame.setVariable(arg, (cc, tt) -> val); } if (varArgs != null) { - final List extraParams = new ArrayList<>(); + List extraParams = new ArrayList<>(); for (int i = args.size(), mx = params.size(); i < mx; i++) { extraParams.add(params.get(i).reboundedTo(null)); // copy by value I guess } - final Value rest = ListValue.wrap(extraParams).bindTo(varArgs); // didn't we just copied that? + Value rest = ListValue.wrap(extraParams).bindTo(varArgs); // didn't we just copied that? newFrame.setVariable(varArgs, (cc, tt) -> rest); } @@ -264,15 +264,15 @@ public LazyValue execute(final Context c, final Context.Type type, final Express { retVal = body.evalValue(newFrame, type); // todo not sure if we need to propagete type / consider boolean context in defined functions - answer seems ye } - catch (final BreakStatement | ContinueStatement exc) + catch (BreakStatement | ContinueStatement exc) { throw new ExpressionException(c, e, t, "'continue' and 'break' can only be called inside loop function bodies"); } - catch (final ReturnStatement returnStatement) + catch (ReturnStatement returnStatement) { retVal = returnStatement.retval; } - final Value otherRetVal = retVal; + Value otherRetVal = retVal; return (cc, tt) -> otherRetVal; } @@ -297,7 +297,7 @@ public String getVarArgs() } @Override - public Tag toTag(final boolean force) + public Tag toTag(boolean force) { if (!force) { @@ -306,9 +306,9 @@ public Tag toTag(final boolean force) return StringTag.valueOf(getString()); } - public void assertArgsOk(final List list, final Consumer feedback) + public void assertArgsOk(List list, Consumer feedback) { - final int size = list.size(); + int size = list.size(); if (varArgs == null && args.size() != size) // wrong number of args for fixed args { feedback.accept(true); diff --git a/src/main/java/carpet/script/value/LContainerValue.java b/src/main/java/carpet/script/value/LContainerValue.java index 6047126475..e6b8bee343 100644 --- a/src/main/java/carpet/script/value/LContainerValue.java +++ b/src/main/java/carpet/script/value/LContainerValue.java @@ -6,7 +6,7 @@ public class LContainerValue extends FrameworkValue private final Value address; public static final LContainerValue NULL_CONTAINER = new LContainerValue(null, null); - public LContainerValue(final ContainerValueInterface c, final Value v) + public LContainerValue(ContainerValueInterface c, Value v) { container = c; address = v; diff --git a/src/main/java/carpet/script/value/LazyListValue.java b/src/main/java/carpet/script/value/LazyListValue.java index 00dc9cf0fb..f3984ac094 100644 --- a/src/main/java/carpet/script/value/LazyListValue.java +++ b/src/main/java/carpet/script/value/LazyListValue.java @@ -12,7 +12,7 @@ public abstract class LazyListValue extends AbstractListValue implements Iterator { - public static LazyListValue rangeDouble(final double from, final double to, final double step) + public static LazyListValue rangeDouble(double from, double to, double step) { return new LazyListValue() { @@ -35,7 +35,7 @@ public static LazyListValue rangeDouble(final double from, final double to, fina @Override public Value next() { - final Value val = new NumericValue(current); + Value val = new NumericValue(current); current += stepp; return val; } @@ -60,7 +60,7 @@ public String getString() }; } - public static LazyListValue rangeLong(final long from, final long to, final long step) + public static LazyListValue rangeLong(long from, long to, long step) { return new LazyListValue() { @@ -83,7 +83,7 @@ public static LazyListValue rangeLong(final long from, final long to, final long @Override public Value next() { - final Value val = new NumericValue(current); + Value val = new NumericValue(current); current += stepp; return val; } @@ -136,7 +136,7 @@ public Iterator iterator() public List unroll() { - final List result = new ArrayList<>(); + List result = new ArrayList<>(); this.forEachRemaining(result::add); fatality(); return result; @@ -157,7 +157,7 @@ public Value slice(long from, Long to) { return ListValue.of(); } - final List result = new ArrayList<>(); + List result = new ArrayList<>(); int i; for (i = 0; i < from; i++) { @@ -187,13 +187,13 @@ public Value slice(long from, Long to) } @Override - public Value add(final Value other) + public Value add(Value other) { throw new InternalExpressionException("Cannot add to iterators"); } @Override - public boolean equals(final Object o) + public boolean equals(Object o) { return false; } @@ -207,12 +207,12 @@ public String getTypeString() @Override public Object clone() { - final Object copy; + Object copy; try { copy = super.clone(); } - catch (final CloneNotSupportedException e) + catch (CloneNotSupportedException e) { throw new InternalExpressionException("Cannot copy iterators"); } @@ -233,7 +233,7 @@ public int hashCode() } @Override - public Tag toTag(final boolean force) + public Tag toTag(boolean force) { if (!force) { diff --git a/src/main/java/carpet/script/value/ListValue.java b/src/main/java/carpet/script/value/ListValue.java index f31fa11160..25e27913ea 100644 --- a/src/main/java/carpet/script/value/ListValue.java +++ b/src/main/java/carpet/script/value/ListValue.java @@ -60,54 +60,54 @@ public Value clone() @Override public Value deepcopy() { - final List copyItems = new ArrayList<>(items.size()); - for (final Value entry : items) + List copyItems = new ArrayList<>(items.size()); + for (Value entry : items) { copyItems.add(entry.deepcopy()); } return new ListValue(copyItems); } - public ListValue(final Collection list) + public ListValue(Collection list) { items = new ArrayList<>(list); } - protected ListValue(final List list) + protected ListValue(List list) { items = list; } - public static Value fromTriple(final double a, final double b, final double c) + public static Value fromTriple(double a, double b, double c) { return ListValue.of(new NumericValue(a), new NumericValue(b), new NumericValue(c)); } - public static Value fromTriple(final int a, final int b, final int c) + public static Value fromTriple(int a, int b, int c) { return fromTriple((double) a, b, c); } - public static ListValue wrap(final Stream stream) + public static ListValue wrap(Stream stream) { return wrap(stream.collect(Collectors.toList())); } - public static ListValue wrap(final List list) + public static ListValue wrap(List list) { return new ListValue(list); } - public static ListValue of(final Value... list) + public static ListValue of(Value... list) { return new ListValue(new ArrayList<>(Arrays.asList(list))); } - public static ListValue ofNums(final Number... list) + public static ListValue ofNums(Number... list) { - final List valList = new ArrayList<>(); - for (final Number i : list) + List valList = new ArrayList<>(); + for (Number i : list) { valList.add(new NumericValue(i.doubleValue())); } @@ -116,7 +116,7 @@ public static ListValue ofNums(final Number... list) public static LazyValue lazyEmpty() { - final Value ret = new ListValue(); + Value ret = new ListValue(); return (c, t) -> ret; } @@ -126,12 +126,12 @@ private ListValue() } @Override - public Value add(final Value other) + public Value add(Value other) { - final ListValue output = new ListValue(); + ListValue output = new ListValue(); if (other instanceof final ListValue list) { - final List otherItems = list.items; + List otherItems = list.items; if (otherItems.size() == items.size()) { for (int i = 0, size = items.size(); i < size; i++) @@ -146,7 +146,7 @@ public Value add(final Value other) } else { - for (final Value v : items) + for (Value v : items) { output.items.add(v.add(other)); } @@ -155,18 +155,18 @@ public Value add(final Value other) } @Override - public void append(final Value v) + public void append(Value v) { items.add(v); } @Override - public Value subtract(final Value other) + public Value subtract(Value other) { - final ListValue output = new ListValue(); + ListValue output = new ListValue(); if (other instanceof final ListValue list) { - final List otherItems = list.items; + List otherItems = list.items; if (otherItems.size() == items.size()) { for (int i = 0, size = items.size(); i < size; i++) @@ -181,7 +181,7 @@ public Value subtract(final Value other) } else { - for (final Value v : items) + for (Value v : items) { output.items.add(v.subtract(other)); } @@ -189,19 +189,19 @@ public Value subtract(final Value other) return output; } - public void subtractFrom(final Value v) // if I ever do -= then it wouod remove items + public void subtractFrom(Value v) // if I ever do -= then it wouod remove items { throw new UnsupportedOperationException(); // TODO } @Override - public Value multiply(final Value other) + public Value multiply(Value other) { - final ListValue output = new ListValue(); + ListValue output = new ListValue(); if (other instanceof final ListValue list) { - final List otherItems = list.items; + List otherItems = list.items; if (otherItems.size() == items.size()) { for (int i = 0, size = items.size(); i < size; i++) @@ -216,7 +216,7 @@ public Value multiply(final Value other) } else { - for (final Value v : items) + for (Value v : items) { output.items.add(v.multiply(other)); } @@ -225,12 +225,12 @@ public Value multiply(final Value other) } @Override - public Value divide(final Value other) + public Value divide(Value other) { - final ListValue output = new ListValue(); + ListValue output = new ListValue(); if (other instanceof final ListValue list) { - final List otherItems = list.items; + List otherItems = list.items; if (otherItems.size() == items.size()) { for (int i = 0, size = items.size(); i < size; i++) @@ -245,7 +245,7 @@ public Value divide(final Value other) } else { - for (final Value v : items) + for (Value v : items) { output.items.add(v.divide(other)); } @@ -254,12 +254,12 @@ public Value divide(final Value other) } @Override - public int compareTo(final Value o) + public int compareTo(Value o) { if (o instanceof final ListValue ol) { - final int size = this.getItems().size(); - final int otherSize = ol.getItems().size(); + int size = this.getItems().size(); + int otherSize = ol.getItems().size(); if (size != otherSize) { return size - otherSize; @@ -270,7 +270,7 @@ public int compareTo(final Value o) } for (int i = 0; i < size; i++) { - final int res = this.items.get(i).compareTo(ol.items.get(i)); + int res = this.items.get(i).compareTo(ol.items.get(i)); if (res != 0) { return res; @@ -282,7 +282,7 @@ public int compareTo(final Value o) } @Override - public boolean equals(final Object o) + public boolean equals(Object o) { return o instanceof final ListValue list && getItems().equals(list.getItems()); } @@ -304,7 +304,7 @@ public List unpack() return new ArrayList<>(items); } - public void extend(final List subList) + public void extend(List subList) { items.addAll(subList); } @@ -316,13 +316,13 @@ public void extend(final List subList) * @param len * @return */ - public static int normalizeIndex(long idx, final int len) + public static int normalizeIndex(long idx, int len) { if (idx >= 0 && idx < len) { return (int) idx; } - final long range = abs(idx) / len; + long range = abs(idx) / len; idx += (range + 2) * len; idx = idx % len; return (int) idx; @@ -330,7 +330,7 @@ public static int normalizeIndex(long idx, final int len) public static class ListConstructorValue extends ListValue { - public ListConstructorValue(final Collection list) + public ListConstructorValue(Collection list) { super(list); } @@ -343,11 +343,11 @@ public int length() } @Override - public Value in(final Value value1) + public Value in(Value value1) { for (int i = 0; i < items.size(); i++) { - final Value v = items.get(i); + Value v = items.get(i); if (v.equals(value1)) { return new NumericValue(i); @@ -357,16 +357,16 @@ public Value in(final Value value1) } @Override - public Value slice(final long fromDesc, final Long toDesc) + public Value slice(long fromDesc, Long toDesc) { - final List items = getItems(); - final int size = items.size(); - final int from = normalizeIndex(fromDesc, size); + List items = getItems(); + int size = items.size(); + int from = normalizeIndex(fromDesc, size); if (toDesc == null) { return new ListValue(new ArrayList<>(getItems().subList(from, size))); } - final int to = normalizeIndex(toDesc, size + 1); + int to = normalizeIndex(toDesc, size + 1); if (from > to) { return ListValue.of(); @@ -375,9 +375,9 @@ public Value slice(final long fromDesc, final Long toDesc) } @Override - public Value split(final Value delimiter) + public Value split(Value delimiter) { - final ListValue result = new ListValue(); + ListValue result = new ListValue(); if (delimiter == null) { this.forEach(item -> result.items.add(of(item))); @@ -385,7 +385,7 @@ public Value split(final Value delimiter) } int startIndex = 0; int index = 0; - for (final Value val : this.items) + for (Value val : this.items) { index++; if (val.equals(delimiter)) @@ -405,9 +405,9 @@ public double readDoubleNumber() } @Override - public boolean put(final Value where, final Value value, final Value conditionValue) + public boolean put(Value where, Value value, Value conditionValue) { - final String condition = conditionValue.getString(); + String condition = conditionValue.getString(); if (condition.equalsIgnoreCase("insert")) { return put(where, value, false, false); @@ -424,12 +424,12 @@ public boolean put(final Value where, final Value value, final Value conditionVa } @Override - public boolean put(final Value ind, final Value value) + public boolean put(Value ind, Value value) { return put(ind, value, true, false); } - private boolean put(final Value ind, final Value value, final boolean replace, final boolean extend) + private boolean put(Value ind, Value value, boolean replace, boolean extend) { if (ind.isNull()) { @@ -444,7 +444,7 @@ private boolean put(final Value ind, final Value value, final boolean replace, f } else { - final int numitems = items.size(); + int numitems = items.size(); if (!(ind instanceof NumericValue)) { return false; @@ -470,8 +470,8 @@ private boolean put(final Value ind, final Value value, final boolean replace, f if (extend && value instanceof AbstractListValue) { - final Iterable iterable = ((AbstractListValue) value)::iterator; - final List appendix = StreamSupport.stream(iterable.spliterator(), false).collect(Collectors.toList()); + Iterable iterable = ((AbstractListValue) value)::iterator; + List appendix = StreamSupport.stream(iterable.spliterator(), false).collect(Collectors.toList()); items.addAll(index, appendix); return true; } @@ -481,27 +481,27 @@ private boolean put(final Value ind, final Value value, final boolean replace, f } @Override - public Value get(final Value value) + public Value get(Value value) { - final int size = items.size(); + int size = items.size(); return size == 0 ? Value.NULL : items.get(normalizeIndex(NumericValue.asNumber(value, "'address' to a list index").getLong(), size)); } @Override - public boolean has(final Value where) + public boolean has(Value where) { - final long index = NumericValue.asNumber(where, "'address' to a list index").getLong(); + long index = NumericValue.asNumber(where, "'address' to a list index").getLong(); return index >= 0 && index < items.size(); } @Override - public boolean delete(final Value where) + public boolean delete(Value where) { if (!(where instanceof NumericValue) || items.isEmpty()) { return false; } - final long index = ((NumericValue) where).getLong(); + long index = ((NumericValue) where).getLong(); items.remove(normalizeIndex(index, items.size())); return true; } @@ -527,7 +527,7 @@ private enum TagTypeCompat MAP, STRING; - private static TagTypeCompat getType(final Tag tag) + private static TagTypeCompat getType(Tag tag) { if (tag instanceof IntTag) { @@ -555,23 +555,23 @@ private static TagTypeCompat getType(final Tag tag) @Override - public Tag toTag(final boolean force) + public Tag toTag(boolean force) { - final int argSize = items.size(); + int argSize = items.size(); if (argSize == 0) { return new ListTag(); } - final ListTag tag = new ListTag(); + ListTag tag = new ListTag(); if (argSize == 1) { tag.add(items.get(0).toTag(force)); return tag; } // figuring out the types - final List tags = new ArrayList<>(); + List tags = new ArrayList<>(); items.forEach(v -> tags.add(v.toTag(force))); - final Set cases = EnumSet.noneOf(TagTypeCompat.class); + Set cases = EnumSet.noneOf(TagTypeCompat.class); tags.forEach(t -> cases.add(TagTypeCompat.getType(t))); if (cases.size() == 1) // well, one type of items { @@ -599,8 +599,8 @@ public Tag toTag(final boolean force) @Override public JsonElement toJson() { - final JsonArray array = new JsonArray(); - for (final Value el : items) + JsonArray array = new JsonArray(); + for (Value el : items) { array.add(el.toJson()); } diff --git a/src/main/java/carpet/script/value/MapValue.java b/src/main/java/carpet/script/value/MapValue.java index 95f7513192..b4c25d8822 100644 --- a/src/main/java/carpet/script/value/MapValue.java +++ b/src/main/java/carpet/script/value/MapValue.java @@ -25,13 +25,13 @@ private MapValue() map = new HashMap<>(); } - public MapValue(final List kvPairs) + public MapValue(List kvPairs) { this(); kvPairs.forEach(this::put); } - public MapValue(final Set keySet) + public MapValue(Set keySet) { this(); keySet.forEach(v -> map.put(v, Value.NULL)); @@ -62,8 +62,8 @@ public String getPrettyString() { return "{" + map.entrySet().stream().map(p -> p.getKey().getPrettyString() + ": " + p.getValue().getPrettyString()).collect(Collectors.joining(", ")) + "}"; } - final List keys = new ArrayList<>(map.keySet()); - final int max = keys.size(); + List keys = new ArrayList<>(map.keySet()); + int max = keys.size(); return "{" + keys.get(0).getPrettyString() + ": " + map.get(keys.get(0)).getPrettyString() + ", " + keys.get(1).getPrettyString() + ": " + map.get(keys.get(1)).getPrettyString() + ", ..., " + keys.get(max - 2).getPrettyString() + ": " + map.get(keys.get(max - 2)).getPrettyString() + ", " + @@ -85,32 +85,32 @@ public Value clone() @Override public Value deepcopy() { - final Map copyMap = new HashMap<>(); + Map copyMap = new HashMap<>(); map.forEach((key, value) -> copyMap.put(key.deepcopy(), value.deepcopy())); return new MapValue(copyMap); } - private MapValue(final Map other) + private MapValue(Map other) { map = other; } - public static MapValue wrap(final Map other) + public static MapValue wrap(Map other) { return new MapValue(other); } @Override - public Value add(final Value o) + public Value add(Value o) { - final Map newItems = new HashMap<>(map); + Map newItems = new HashMap<>(map); if (o instanceof final MapValue mapValue) { newItems.putAll(mapValue.map); } else if (o instanceof final AbstractListValue alv) { - for (final Value value : alv) + for (Value value : alv) { newItems.put(value, Value.NULL); } @@ -123,24 +123,24 @@ else if (o instanceof final AbstractListValue alv) } @Override - public Value subtract(final Value v) + public Value subtract(Value v) { throw new InternalExpressionException("Cannot subtract from a map value"); } @Override - public Value multiply(final Value v) + public Value multiply(Value v) { throw new InternalExpressionException("Cannot multiply with a map value"); } @Override - public Value divide(final Value v) + public Value divide(Value v) { throw new InternalExpressionException("Cannot divide a map value"); } - public void put(final Value v) + public void put(Value v) { if (!(v instanceof final ListValue pair)) { @@ -155,19 +155,19 @@ public void put(final Value v) } @Override - public void append(final Value v) + public void append(Value v) { map.put(v, Value.NULL); } @Override - public int compareTo(final Value o) + public int compareTo(Value o) { throw new InternalExpressionException("Cannot compare with a map value"); } @Override - public boolean equals(final Object o) + public boolean equals(Object o) { return o instanceof final MapValue mapValue && map.equals(mapValue.map); } @@ -177,7 +177,7 @@ public Map getMap() return map; } - public void extend(final List subList) + public void extend(List subList) { subList.forEach(this::put); } @@ -189,19 +189,19 @@ public int length() } @Override - public Value in(final Value value) + public Value in(Value value) { return map.containsKey(value) ? value : Value.NULL; } @Override - public Value slice(final long from, final Long to) + public Value slice(long from, Long to) { throw new InternalExpressionException("Cannot slice a map value"); } @Override - public Value split(final Value delimiter) + public Value split(Value delimiter) { throw new InternalExpressionException("Cannot split a map value"); } @@ -213,25 +213,25 @@ public double readDoubleNumber() } @Override - public Value get(final Value v2) + public Value get(Value v2) { return map.getOrDefault(v2, Value.NULL); } @Override - public boolean has(final Value where) + public boolean has(Value where) { return map.containsKey(where); } @Override - public boolean delete(final Value where) + public boolean delete(Value where) { return map.remove(where) != null; } @Override - public boolean put(final Value key, final Value value) + public boolean put(Value key, Value value) { return map.put(key, value) != null; } @@ -249,9 +249,9 @@ public int hashCode() } @Override - public Tag toTag(final boolean force) + public Tag toTag(boolean force) { - final CompoundTag tag = new CompoundTag(); + CompoundTag tag = new CompoundTag(); map.forEach((k, v) -> { if (!force && !(k instanceof StringValue)) @@ -266,8 +266,8 @@ public Tag toTag(final boolean force) @Override public JsonElement toJson() { - final JsonObject jsonMap = new JsonObject(); - final List keys = new ArrayList<>(map.keySet()); + JsonObject jsonMap = new JsonObject(); + List keys = new ArrayList<>(map.keySet()); Collections.sort(keys); keys.forEach(k -> jsonMap.add(k.getString(), map.get(k).toJson())); return jsonMap; diff --git a/src/main/java/carpet/script/value/NBTSerializableValue.java b/src/main/java/carpet/script/value/NBTSerializableValue.java index cfd8eb2ad9..2befcd609d 100644 --- a/src/main/java/carpet/script/value/NBTSerializableValue.java +++ b/src/main/java/carpet/script/value/NBTSerializableValue.java @@ -55,6 +55,8 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; +import javax.annotation.Nullable; + public class NBTSerializableValue extends Value implements ContainerValueInterface { private String nbtString = null; @@ -66,7 +68,7 @@ private NBTSerializableValue() { } - public NBTSerializableValue(final String nbtString) + public NBTSerializableValue(String nbtString) { nbtSupplier = () -> { @@ -74,7 +76,7 @@ public NBTSerializableValue(final String nbtString) { return (new TagParser(new StringReader(nbtString))).readValue(); } - catch (final CommandSyntaxException e) + catch (CommandSyntaxException e) { throw new InternalExpressionException("Incorrect NBT data: " + nbtString); } @@ -82,13 +84,13 @@ public NBTSerializableValue(final String nbtString) owned = true; } - public NBTSerializableValue(final Tag tag) + public NBTSerializableValue(Tag tag) { nbtTag = tag; owned = true; } - public static Value of(final Tag tag) + public static Value of(Tag tag) { if (tag == null) { @@ -97,49 +99,57 @@ public static Value of(final Tag tag) return new NBTSerializableValue(tag); } - public NBTSerializableValue(final Supplier tagSupplier) + public NBTSerializableValue(Supplier tagSupplier) { nbtSupplier = tagSupplier; } - public static Value fromStack(final ItemStack stack) + public static Value fromStack(ItemStack stack) { if (stack.hasTag()) { - final NBTSerializableValue value = new NBTSerializableValue(); + NBTSerializableValue value = new NBTSerializableValue(); value.nbtSupplier = stack::getTag; return value; } return Value.NULL; } - public static String nameFromRegistryId(final ResourceLocation id) + public static Value nameFromRegistryId(@Nullable ResourceLocation id) { - if (id == null) // should be Value.NULL - { - return ""; - } - return id.getNamespace().equals("minecraft") ? id.getPath() : id.toString(); + return StringValue.of(nameFromResource(id)); } - public static NBTSerializableValue parseString(final String nbtString, final boolean fail) + @Nullable + public static String nameFromResource(@Nullable ResourceLocation id) + { + return id == null ? null : id.getNamespace().equals("minecraft") ? id.getPath() : id.toString(); + } + + @Nullable + public static NBTSerializableValue parseString(String nbtString) { - final Tag tag; try { - tag = (new TagParser(new StringReader(nbtString))).readValue(); + Tag tag = (new TagParser(new StringReader(nbtString))).readValue(); + NBTSerializableValue value = new NBTSerializableValue(tag); + value.nbtString = null; + return value; } - catch (final CommandSyntaxException e) + catch (CommandSyntaxException e) { - if (fail) - { - throw new InternalExpressionException("Incorrect NBT tag: " + nbtString); - } return null; } - final NBTSerializableValue value = new NBTSerializableValue(tag); - value.nbtString = null; - return value; + } + + public static NBTSerializableValue parseStringOrFail(String nbtString) + { + NBTSerializableValue result = parseString(nbtString); + if (result == null) + { + throw new InternalExpressionException("Incorrect NBT tag: " + nbtString); + } + return result; } @@ -147,7 +157,7 @@ public static NBTSerializableValue parseString(final String nbtString, final boo public Value clone() { // sets only nbttag, even if emtpy; - final NBTSerializableValue copy = new NBTSerializableValue(nbtTag); + NBTSerializableValue copy = new NBTSerializableValue(nbtTag); copy.nbtSupplier = this.nbtSupplier; copy.nbtString = this.nbtString; copy.owned = this.owned; @@ -157,7 +167,7 @@ public Value clone() @Override public Value deepcopy() { - final NBTSerializableValue copy = (NBTSerializableValue) clone(); + NBTSerializableValue copy = (NBTSerializableValue) clone(); copy.owned = false; ensureOwnership(); return copy; @@ -170,18 +180,18 @@ public Value fromConstant() } // stolen from HopperBlockEntity, adjusted for threaded operation - public static Container getInventoryAt(final ServerLevel world, final BlockPos blockPos) + public static Container getInventoryAt(ServerLevel world, BlockPos blockPos) { Container inventory = null; - final BlockState blockState = world.getBlockState(blockPos); - final Block block = blockState.getBlock(); + BlockState blockState = world.getBlockState(blockPos); + Block block = blockState.getBlock(); if (block instanceof final WorldlyContainerHolder containerHolder) { inventory = containerHolder.getContainer(blockState, world, blockPos); } else if (blockState.hasBlockEntity()) { - final BlockEntity blockEntity = BlockValue.getBlockEntity(world, blockPos); + BlockEntity blockEntity = BlockValue.getBlockEntity(world, blockPos); if (blockEntity instanceof final Container inventoryHolder) { inventory = inventoryHolder; @@ -194,7 +204,7 @@ else if (blockState.hasBlockEntity()) if (inventory == null) { - final List list = world.getEntities( + List list = world.getEntities( (Entity) null, //TODO check this matches the correct method new AABB( blockPos.getX() - 0.5D, blockPos.getY() - 0.5D, blockPos.getZ() - 0.5D, @@ -210,7 +220,7 @@ else if (blockState.hasBlockEntity()) return inventory; } - public static InventoryLocator locateInventory(final CarpetContext c, final List params, int offset) + public static InventoryLocator locateInventory(CarpetContext c, List params, int offset) { try { @@ -225,8 +235,8 @@ else if (v1 instanceof StringValue) String strVal = v1.getString().toLowerCase(Locale.ROOT); if (strVal.equals("enderchest")) { - final Value v2 = params.get(1 + offset); - final ServerPlayer player = EntityValue.getPlayerByValue(c.server(), v2); + Value v2 = params.get(1 + offset); + ServerPlayer player = EntityValue.getPlayerByValue(c.server(), v2); if (player == null) { throw new InternalExpressionException("enderchest inventory requires player argument"); @@ -235,24 +245,24 @@ else if (v1 instanceof StringValue) } if (strVal.equals("equipment")) { - final Value v2 = params.get(1 + offset); + Value v2 = params.get(1 + offset); if (!(v2 instanceof final EntityValue ev)) { throw new InternalExpressionException("Equipment inventory requires a living entity argument"); } - final Entity e = ev.getEntity(); + Entity e = ev.getEntity(); if (!(e instanceof final LivingEntity le)) { throw new InternalExpressionException("Equipment inventory requires a living entity argument"); } return new InventoryLocator(e, e.blockPosition(), new EquipmentInventory(le), offset + 2); } - final boolean isEnder = strVal.startsWith("enderchest_"); + boolean isEnder = strVal.startsWith("enderchest_"); if (isEnder) { strVal = strVal.substring(11); // len("enderchest_") } - final ServerPlayer player = c.server().getPlayerList().getPlayerByName(strVal); + ServerPlayer player = c.server().getPlayerList().getPlayerByName(strVal); if (player == null) { throw new InternalExpressionException("String description of an inventory should either denote a player or player's enderchest"); @@ -268,7 +278,7 @@ else if (v1 instanceof StringValue) if (v1 instanceof final EntityValue ev) { Container inv = null; - final Entity e = ev.getEntity(); + Entity e = ev.getEntity(); if (e instanceof final Player pe) { inv = pe.getInventory(); @@ -294,36 +304,36 @@ else if (e instanceof final LivingEntity le) } if (v1 instanceof final BlockValue bv) { - final BlockPos pos = bv.getPos(); + BlockPos pos = bv.getPos(); if (pos == null) { throw new InternalExpressionException("Block to access inventory needs to be positioned in the world"); } - final Container inv = getInventoryAt(c.level(), pos); + Container inv = getInventoryAt(c.level(), pos); return inv == null ? null : new InventoryLocator(pos, pos, inv, offset + 1); } if (v1 instanceof final ListValue lv) { - final List args = lv.getItems(); - final BlockPos pos = new BlockPos( + List args = lv.getItems(); + BlockPos pos = new BlockPos( NumericValue.asNumber(args.get(0)).getDouble(), NumericValue.asNumber(args.get(1)).getDouble(), NumericValue.asNumber(args.get(2)).getDouble()); - final Container inv = getInventoryAt(c.level(), pos); + Container inv = getInventoryAt(c.level(), pos); return inv == null ? null : new InventoryLocator(pos, pos, inv, offset + 1); } if (v1 instanceof final ScreenValue screenValue) { return !screenValue.isOpen() ? null : new InventoryLocator(screenValue.getPlayer(), screenValue.getPlayer().blockPosition(), screenValue.getInventory(), offset + 1); } - final BlockPos pos = new BlockPos( + BlockPos pos = new BlockPos( NumericValue.asNumber(v1).getDouble(), NumericValue.asNumber(params.get(1 + offset)).getDouble(), NumericValue.asNumber(params.get(2 + offset)).getDouble()); - final Container inv = getInventoryAt(c.level(), pos); + Container inv = getInventoryAt(c.level(), pos); return inv == null ? null : new InventoryLocator(pos, pos, inv, offset + 3); } - catch (final IndexOutOfBoundsException e) + catch (IndexOutOfBoundsException e) { throw new InternalExpressionException("Inventory should be defined either by three coordinates, a block value, an entity, or a screen"); } @@ -331,12 +341,12 @@ else if (e instanceof final LivingEntity le) private static final Map itemCache = new HashMap<>(); - public static ItemInput parseItem(final String itemString, final RegistryAccess regs) + public static ItemInput parseItem(String itemString, RegistryAccess regs) { return parseItem(itemString, null, regs); } - public static ItemInput parseItem(final String itemString, final CompoundTag customTag, final RegistryAccess regs) + public static ItemInput parseItem(String itemString, @Nullable CompoundTag customTag, RegistryAccess regs) { try { @@ -345,7 +355,7 @@ public static ItemInput parseItem(final String itemString, final CompoundTag cus { return customTag == null ? res : new ItemInput(Holder.direct(res.getItem()), customTag); } - final ItemParser.ItemResult parser = ItemParser.parseForItem(regs.lookupOrThrow(Registries.ITEM), new StringReader(itemString)); + ItemParser.ItemResult parser = ItemParser.parseForItem(regs.lookupOrThrow(Registries.ITEM), new StringReader(itemString)); res = new ItemInput(parser.item(), parser.nbt()); itemCache.put(itemString, res); @@ -355,15 +365,15 @@ public static ItemInput parseItem(final String itemString, final CompoundTag cus } return customTag == null ? res : new ItemInput(Holder.direct(res.getItem()), customTag); } - catch (final CommandSyntaxException e) + catch (CommandSyntaxException e) { throw new ThrowStatement(itemString, Throwables.UNKNOWN_ITEM); } } - public static int validateSlot(int slot, final Container inv) + public static int validateSlot(int slot, Container inv) { - final int invSize = inv.getContainerSize(); + int invSize = inv.getContainerSize(); if (slot < 0) { slot = invSize + slot; @@ -371,7 +381,7 @@ public static int validateSlot(int slot, final Container inv) return slot < 0 || slot >= invSize ? inv.getContainerSize() : slot; // outside of inventory } - private static Value decodeSimpleTag(final Tag t) + private static Value decodeSimpleTag(Tag t) { if (t instanceof final NumericTag number) { @@ -389,17 +399,17 @@ private static Value decodeSimpleTag(final Tag t) throw new InternalExpressionException("How did we get here: Unknown nbt element class: " + t.getType().getName()); } - private static Value decodeTag(final Tag t) + private static Value decodeTag(Tag t) { return t instanceof CompoundTag || t instanceof CollectionTag ? new NBTSerializableValue(() -> t) : decodeSimpleTag(t); } - private static Value decodeTagDeep(final Tag t) + private static Value decodeTagDeep(Tag t) { if (t instanceof final CompoundTag ctag) { - final Map pairs = new HashMap<>(); - for (final String key : ctag.getAllKeys()) + Map pairs = new HashMap<>(); + for (String key : ctag.getAllKeys()) { pairs.put(new StringValue(key), decodeTagDeep(ctag.get(key))); } @@ -407,8 +417,8 @@ private static Value decodeTagDeep(final Tag t) } if (t instanceof final CollectionTag ltag) { - final List elems = new ArrayList<>(); - for (final Tag elem : ltag) + List elems = new ArrayList<>(); + for (Tag elem : ltag) { elems.add(decodeTagDeep(elem)); } @@ -422,7 +432,7 @@ public Value toValue() return decodeTagDeep(this.getTag()); } - public static Value fromValue(final Value v) + public static Value fromValue(Value v) { if (v instanceof NBTSerializableValue) { @@ -432,7 +442,7 @@ public static Value fromValue(final Value v) { return Value.NULL; } - return NBTSerializableValue.parseString(v.getString(), true); + return NBTSerializableValue.parseStringOrFail(v.getString()); } public Tag getTag() @@ -445,7 +455,7 @@ public Tag getTag() } @Override - public boolean equals(final Object o) + public boolean equals(Object o) { return o instanceof final NBTSerializableValue nbtsv ? getTag().equals(nbtsv.getTag()) : super.equals(o); } @@ -463,7 +473,7 @@ public String getString() @Override public boolean getBoolean() { - final Tag tag = getTag(); + Tag tag = getTag(); if (tag instanceof final CompoundTag ctag) { return !(ctag).isEmpty(); @@ -490,35 +500,35 @@ public CompoundTag getCompoundTag() ensureOwnership(); return (CompoundTag) getTag(); } - catch (final ClassCastException e) + catch (ClassCastException e) { throw new InternalExpressionException(getString() + " is not a valid compound tag"); } } @Override - public boolean put(final Value where, final Value value) + public boolean put(Value where, Value value) { return put(where, value, new StringValue("replace")); } @Override - public boolean put(final Value where, final Value value, final Value conditions) + public boolean put(Value where, Value value, Value conditions) { /// WIP ensureOwnership(); - final NbtPathArgument.NbtPath path = cachePath(where.getString()); - final Tag tagToInsert = value instanceof final NBTSerializableValue nbtsv + NbtPathArgument.NbtPath path = cachePath(where.getString()); + Tag tagToInsert = value instanceof final NBTSerializableValue nbtsv ? nbtsv.getTag() : new NBTSerializableValue(value.getString()).getTag(); - final boolean modifiedTag; + boolean modifiedTag; if (conditions instanceof final NumericValue number) { modifiedTag = modifyInsert((int) number.getLong(), path, tagToInsert); } else { - final String ops = conditions.getString(); + String ops = conditions.getString(); if (ops.equalsIgnoreCase("merge")) { modifiedTag = modifyMerge(path, tagToInsert); @@ -540,25 +550,25 @@ else if (ops.equalsIgnoreCase("replace")) } - private boolean modifyInsert(final int index, final NbtPathArgument.NbtPath nbtPath, final Tag newElement) + private boolean modifyInsert(int index, NbtPathArgument.NbtPath nbtPath, Tag newElement) { return modifyInsert(index, nbtPath, newElement, this.getTag()); } - private boolean modifyInsert(final int index, final NbtPathArgument.NbtPath nbtPath, final Tag newElement, final Tag currentTag) + private boolean modifyInsert(int index, NbtPathArgument.NbtPath nbtPath, Tag newElement, Tag currentTag) { - final Collection targets; + Collection targets; try { targets = nbtPath.getOrCreate(currentTag, ListTag::new); } - catch (final CommandSyntaxException e) + catch (CommandSyntaxException e) { return false; } boolean modified = false; - for (final Tag target : targets) + for (Tag target : targets) { if (!(target instanceof final CollectionTag targetList)) { @@ -572,7 +582,7 @@ private boolean modifyInsert(final int index, final NbtPathArgument.NbtPath nbtP } modified = true; } - catch (final IndexOutOfBoundsException ignored) + catch (IndexOutOfBoundsException ignored) { } } @@ -580,16 +590,16 @@ private boolean modifyInsert(final int index, final NbtPathArgument.NbtPath nbtP } - private boolean modifyMerge(final NbtPathArgument.NbtPath nbtPath, final Tag replacement) //nbtPathArgumentType$NbtPath_1, list_1) + private boolean modifyMerge(NbtPathArgument.NbtPath nbtPath, Tag replacement) //nbtPathArgumentType$NbtPath_1, list_1) { if (!(replacement instanceof final CompoundTag replacementCompound)) { return false; } - final Tag ownTag = getTag(); + Tag ownTag = getTag(); try { - for (final Tag target : nbtPath.getOrCreate(ownTag, CompoundTag::new)) + for (Tag target : nbtPath.getOrCreate(ownTag, CompoundTag::new)) { if (!(target instanceof final CompoundTag targetCompound)) { @@ -598,31 +608,31 @@ private boolean modifyMerge(final NbtPathArgument.NbtPath nbtPath, final Tag rep targetCompound.merge(replacementCompound); } } - catch (final CommandSyntaxException ignored) + catch (CommandSyntaxException ignored) { return false; } return true; } - private boolean modifyReplace(final NbtPathArgument.NbtPath nbtPath, final Tag replacement) //nbtPathArgumentType$NbtPath_1, list_1) + private boolean modifyReplace(NbtPathArgument.NbtPath nbtPath, Tag replacement) //nbtPathArgumentType$NbtPath_1, list_1) { - final Tag tag = getTag(); - final String pathText = nbtPath.toString(); + Tag tag = getTag(); + String pathText = nbtPath.toString(); if (pathText.endsWith("]")) // workaround for array replacement or item in the array replacement { if (nbtPath.remove(tag) == 0) { return false; } - final Pattern pattern = Pattern.compile("\\[[^\\[]*]$"); - final Matcher matcher = pattern.matcher(pathText); + Pattern pattern = Pattern.compile("\\[[^\\[]*]$"); + Matcher matcher = pattern.matcher(pathText); if (!matcher.find()) // malformed path { return false; } - final String arrAccess = matcher.group(); - final int pos; + String arrAccess = matcher.group(); + int pos; if (arrAccess.length() == 2) // we just removed entire array { pos = 0; @@ -633,19 +643,19 @@ private boolean modifyReplace(final NbtPathArgument.NbtPath nbtPath, final Tag r { pos = Integer.parseInt(arrAccess.substring(1, arrAccess.length() - 1)); } - catch (final NumberFormatException e) + catch (NumberFormatException e) { return false; } } - final NbtPathArgument.NbtPath newPath = cachePath(pathText.substring(0, pathText.length() - arrAccess.length())); + NbtPathArgument.NbtPath newPath = cachePath(pathText.substring(0, pathText.length() - arrAccess.length())); return modifyInsert(pos, newPath, replacement, tag); } try { nbtPath.set(tag, replacement); } - catch (final CommandSyntaxException e) + catch (CommandSyntaxException e) { return false; } @@ -653,13 +663,13 @@ private boolean modifyReplace(final NbtPathArgument.NbtPath nbtPath, final Tag r } @Override - public Value get(final Value value) + public Value get(Value value) { - final String valString = value.getString(); - final NbtPathArgument.NbtPath path = cachePath(valString); + String valString = value.getString(); + NbtPathArgument.NbtPath path = cachePath(valString); try { - final List tags = path.get(getTag()); + List tags = path.get(getTag()); if (tags.isEmpty()) { return Value.NULL; @@ -670,14 +680,14 @@ public Value get(final Value value) } return ListValue.wrap(tags.stream().map(NBTSerializableValue::decodeTag)); } - catch (final CommandSyntaxException ignored) + catch (CommandSyntaxException ignored) { } return Value.NULL; } @Override - public boolean has(final Value where) + public boolean has(Value where) { return cachePath(where.getString()).countMatching(getTag()) > 0; } @@ -699,11 +709,11 @@ private void dirty() } @Override - public boolean delete(final Value where) + public boolean delete(Value where) { - final NbtPathArgument.NbtPath path = cachePath(where.getString()); + NbtPathArgument.NbtPath path = cachePath(where.getString()); ensureOwnership(); - final int removed = path.remove(getTag()); + int removed = path.remove(getTag()); if (removed > 0) { dirty(); @@ -715,7 +725,7 @@ public boolean delete(final Value where) public record InventoryLocator(Object owner, BlockPos position, Container inventory, int offset, boolean isEnder) { - InventoryLocator(final Object owner, final BlockPos pos, final Container i, final int o) + InventoryLocator(Object owner, BlockPos pos, Container i, int o) { this(owner, pos, i, o, false); } @@ -723,7 +733,7 @@ public record InventoryLocator(Object owner, BlockPos position, Container invent private static final Map pathCache = new HashMap<>(); - private static NbtPathArgument.NbtPath cachePath(final String arg) + private static NbtPathArgument.NbtPath cachePath(String arg) { NbtPathArgument.NbtPath res = pathCache.get(arg); if (res != null) @@ -734,7 +744,7 @@ private static NbtPathArgument.NbtPath cachePath(final String arg) { res = NbtPathArgument.nbtPath().parse(new StringReader(arg)); } - catch (final CommandSyntaxException exc) + catch (CommandSyntaxException exc) { throw new InternalExpressionException("Incorrect nbt path: " + arg); } @@ -754,7 +764,7 @@ public String getTypeString() @Override - public Tag toTag(final boolean force) + public Tag toTag(boolean force) { if (!force) { @@ -768,7 +778,7 @@ public static class IncompatibleTypeException extends RuntimeException { public final Value val; - public IncompatibleTypeException(final Value val) + public IncompatibleTypeException(Value val) { this.val = val; } diff --git a/src/main/java/carpet/script/value/NullValue.java b/src/main/java/carpet/script/value/NullValue.java index 426a0f183f..ba385df542 100644 --- a/src/main/java/carpet/script/value/NullValue.java +++ b/src/main/java/carpet/script/value/NullValue.java @@ -41,13 +41,13 @@ protected NullValue() } @Override - public boolean equals(final Object o) + public boolean equals(Object o) { return o instanceof Value value && value.isNull(); } @Override - public Value slice(final long fromDesc, final Long toDesc) + public Value slice(long fromDesc, Long toDesc) { return Value.NULL; } @@ -65,13 +65,13 @@ public int length() } @Override - public int compareTo(final Value o) + public int compareTo(Value o) { return o.isNull() ? 0 : -1; } @Override - public Value in(final Value value) + public Value in(Value value) { return Value.NULL; } @@ -89,7 +89,7 @@ public int hashCode() } @Override - public Tag toTag(final boolean force) + public Tag toTag(boolean force) { if (!force) { @@ -99,7 +99,7 @@ public Tag toTag(final boolean force) } @Override - public Value split(final Value delimiter) + public Value split(Value delimiter) { return ListValue.wrap(new ArrayList<>()); } diff --git a/src/main/java/carpet/script/value/NumericValue.java b/src/main/java/carpet/script/value/NumericValue.java index 9a1a1b5909..3cbd99a85c 100644 --- a/src/main/java/carpet/script/value/NumericValue.java +++ b/src/main/java/carpet/script/value/NumericValue.java @@ -25,7 +25,7 @@ public class NumericValue extends Value private static final double epsilon = abs(32 * ((7 * 0.1) * 10 - 7)); private static final MathContext displayRounding = new MathContext(12, RoundingMode.HALF_EVEN); - public static NumericValue asNumber(final Value v1, final String id) + public static NumericValue asNumber(Value v1, String id) { if (v1 instanceof final NumericValue nv) { @@ -34,7 +34,7 @@ public static NumericValue asNumber(final Value v1, final String id) throw new InternalExpressionException("Argument " + id + " has to be of a numeric type"); } - public static NumericValue asNumber(final Value v1) + public static NumericValue asNumber(Value v1) { if (v1 instanceof final NumericValue nv) { @@ -43,7 +43,7 @@ public static NumericValue asNumber(final Value v1) throw new InternalExpressionException("Operand has to be of a numeric type"); } - public static Value of(final T value) + public static Value of(T value) { if (value == null) { @@ -85,7 +85,7 @@ public String getString() // dobules have 16 point precision, 12 is plenty to display return BigDecimal.valueOf(value).round(displayRounding).stripTrailingZeros().toPlainString(); } - catch (final NumberFormatException exc) + catch (NumberFormatException exc) { throw new InternalExpressionException("Incorrect number format for " + value); } @@ -115,9 +115,9 @@ public float getFloat() return (float) value; } - private static long floor(final double v) + private static long floor(double v) { - final long invValue = (long) v; + long invValue = (long) v; return v < invValue ? invValue - 1 : invValue; } @@ -127,7 +127,7 @@ public long getLong() } @Override - public Value add(final Value v) + public Value add(Value v) { // TODO test if definintn add(NumericVlaue) woud solve the casting if (v instanceof final NumericValue nv) { @@ -137,7 +137,7 @@ public Value add(final Value v) } @Override - public Value subtract(final Value v) + public Value subtract(Value v) { // TODO test if definintn add(NumericVlaue) woud solve the casting if (v instanceof final NumericValue nv) { @@ -147,7 +147,7 @@ public Value subtract(final Value v) } @Override - public Value multiply(final Value v) + public Value multiply(Value v) { if (v instanceof final NumericValue nv) { @@ -157,7 +157,7 @@ public Value multiply(final Value v) } @Override - public Value divide(final Value v) + public Value divide(Value v) { return v instanceof final NumericValue nv ? new NumericValue(getDouble() / nv.getDouble()) : super.divide(v); } @@ -169,7 +169,7 @@ public Value clone() } @Override - public int compareTo(final Value o) + public int compareTo(Value o) { if (o.isNull()) { @@ -183,7 +183,7 @@ public int compareTo(final Value o) } @Override - public boolean equals(final Object o) + public boolean equals(Object o) { if (o instanceof final Value otherValue) { @@ -200,34 +200,34 @@ public boolean equals(final Object o) return false; } - public NumericValue(final double value) + public NumericValue(double value) { this.value = value; } - private NumericValue(final double value, final Long longValue) + private NumericValue(double value, Long longValue) { this.value = value; this.longValue = longValue; } - public NumericValue(final String value) + public NumericValue(String value) { - final BigDecimal decimal = new BigDecimal(value); + BigDecimal decimal = new BigDecimal(value); if (decimal.stripTrailingZeros().scale() <= 0) { try { longValue = decimal.longValueExact(); } - catch (final ArithmeticException ignored) + catch (ArithmeticException ignored) { } } this.value = decimal.doubleValue(); } - public NumericValue(final long value) + public NumericValue(long value) { this.longValue = value; this.value = (double) value; @@ -271,7 +271,7 @@ public int getInt() } @Override - public Tag toTag(final boolean force) + public Tag toTag(boolean force) { if (longValue != null) { @@ -281,7 +281,7 @@ public Tag toTag(final boolean force) } return LongTag.valueOf(longValue); } - final long lv = getLong(); + long lv = getLong(); if (value == (double) lv) { if (abs(value) < Integer.MAX_VALUE - 2) @@ -303,7 +303,7 @@ public JsonElement toJson() { return new JsonPrimitive(longValue); } - final long lv = getLong(); + long lv = getLong(); return new JsonPrimitive(value == lv ? getLong() : value); } @@ -317,14 +317,14 @@ public boolean isInteger() return longValue != null || getDouble() == getLong(); } - public Value mod(final NumericValue n2) + public Value mod(NumericValue n2) { if (this.longValue != null && n2.longValue != null) { return new NumericValue(Math.floorMod(longValue, n2.longValue)); } - final double x = value; - final double y = n2.value; + double x = value; + double y = n2.value; if (y == 0) { throw new ArithmeticException("Division by zero"); diff --git a/src/main/java/carpet/script/value/ScreenValue.java b/src/main/java/carpet/script/value/ScreenValue.java index b24d290dd3..9eb2702f9e 100644 --- a/src/main/java/carpet/script/value/ScreenValue.java +++ b/src/main/java/carpet/script/value/ScreenValue.java @@ -57,6 +57,8 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Recipe; +import javax.annotation.Nullable; + import static net.minecraft.world.inventory.MenuType.*; public class ScreenValue extends Value @@ -109,7 +111,7 @@ protected interface ScarpetScreenHandlerFactory AbstractContainerMenu create(int syncId, Inventory playerInventory); } - public ScreenValue(final ServerPlayer player, final String type, final Component name, final FunctionValue callback, final Context c) + public ScreenValue(ServerPlayer player, String type, Component name, @Nullable FunctionValue callback, Context c) { this.name = name; this.typestring = type.toLowerCase(); @@ -121,7 +123,7 @@ public ScreenValue(final ServerPlayer player, final String type, final Component this.hostname = c.host.getName(); this.scriptServer = (CarpetScriptServer) c.host.scriptServer(); this.player = player; - final MenuProvider factory = this.createScreenHandlerFactory(); + MenuProvider factory = this.createScreenHandlerFactory(); if (factory == null) { throw new ThrowStatement(type, Throwables.UNKNOWN_SCREEN); @@ -138,20 +140,20 @@ private MenuProvider createScreenHandlerFactory() } return new SimpleMenuProvider((i, playerInventory, playerEntity) -> { - final AbstractContainerMenu screen = screenHandlerFactories.get(ScreenValue.this.typestring).create(i, playerInventory); + AbstractContainerMenu screen = screenHandlerFactories.get(ScreenValue.this.typestring).create(i, playerInventory); ScreenValue.this.addListenerCallback(screen); ScreenValue.this.screenHandler = screen; return screen; }, this.name); } - private void openScreen(final MenuProvider factory) + private void openScreen(MenuProvider factory) { if (this.player == null) { return; } - final OptionalInt optionalSyncId = this.player.openMenu(factory); + OptionalInt optionalSyncId = this.player.openMenu(factory); if (optionalSyncId.isPresent() && this.player.containerMenu.containerId == optionalSyncId.getAsInt()) { this.screenHandler = this.player.containerMenu; @@ -185,35 +187,35 @@ public boolean isOpen() } - private boolean callListener(final ServerPlayer player, final String action, final Map data) + private boolean callListener(ServerPlayer player, String action, Map data) { - final Value playerValue = EntityValue.of(player); - final Value actionValue = StringValue.of(action); - final Value dataValue = MapValue.wrap(data); - final List args = Arrays.asList(this, playerValue, actionValue, dataValue); - final CarpetScriptHost appHost = scriptServer.getAppHostByName(this.hostname); + Value playerValue = EntityValue.of(player); + Value actionValue = StringValue.of(action); + Value dataValue = MapValue.wrap(data); + List args = Arrays.asList(this, playerValue, actionValue, dataValue); + CarpetScriptHost appHost = scriptServer.getAppHostByName(this.hostname); if (appHost == null) { this.close(); this.screenHandler = null; return false; } - final int runPermissionLevel = Vanilla.MinecraftServer_getRunPermissionLevel(player.server); - final CommandSourceStack source = player.createCommandSourceStack().withPermission(runPermissionLevel); - final CarpetScriptHost executingHost = appHost.retrieveForExecution(source, player); + int runPermissionLevel = Vanilla.MinecraftServer_getRunPermissionLevel(player.server); + CommandSourceStack source = player.createCommandSourceStack().withPermission(runPermissionLevel); + CarpetScriptHost executingHost = appHost.retrieveForExecution(source, player); try { - final Value cancelValue = executingHost.callUDF(source, callback, args); + Value cancelValue = executingHost.callUDF(source, callback, args); return cancelValue.getString().equals("cancel"); } - catch (final NullPointerException | InvalidCallbackException | IntegrityException error) + catch (NullPointerException | InvalidCallbackException | IntegrityException error) { CarpetScriptServer.LOG.error("Got exception when running screen event call ", error); return false; } } - private void addListenerCallback(final AbstractContainerMenu screenHandler) + private void addListenerCallback(AbstractContainerMenu screenHandler) { if (this.callback == null) { @@ -223,9 +225,9 @@ private void addListenerCallback(final AbstractContainerMenu screenHandler) screenHandler.addSlotListener(new ScarpetScreenHandlerListener() { @Override - public boolean onSlotClick(final ServerPlayer player, final ClickType actionType, final int slot, int button) + public boolean onSlotClick(ServerPlayer player, ClickType actionType, int slot, int button) { - final Map data = new HashMap<>(); + Map data = new HashMap<>(); data.put(StringValue.of("slot"), slot == AbstractContainerMenu.SLOT_CLICKED_OUTSIDE ? Value.NULL : NumericValue.of(slot)); if (actionType == ClickType.QUICK_CRAFT) { @@ -237,46 +239,46 @@ public boolean onSlotClick(final ServerPlayer player, final ClickType actionType } @Override - public boolean onButtonClick(final ServerPlayer player, final int button) + public boolean onButtonClick(ServerPlayer player, int button) { - final Map data = new HashMap<>(); + Map data = new HashMap<>(); data.put(StringValue.of("button"), NumericValue.of(button)); return ScreenValue.this.callListener(player, "button", data); } @Override - public void onClose(final ServerPlayer player) + public void onClose(ServerPlayer player) { - final Map data = new HashMap<>(); + Map data = new HashMap<>(); ScreenValue.this.callListener(player, "close", data); } @Override - public boolean onSelectRecipe(final ServerPlayer player, final Recipe recipe, final boolean craftAll) + public boolean onSelectRecipe(ServerPlayer player, Recipe recipe, boolean craftAll) { - final Map data = new HashMap<>(); + Map data = new HashMap<>(); data.put(StringValue.of("recipe"), StringValue.of(recipe.getId().toString())); data.put(StringValue.of("craft_all"), BooleanValue.of(craftAll)); return ScreenValue.this.callListener(player, "select_recipe", data); } @Override - public void slotChanged(final AbstractContainerMenu handler, final int slotId, final ItemStack stack) + public void slotChanged(AbstractContainerMenu handler, int slotId, ItemStack stack) { - final Map data = new HashMap<>(); + Map data = new HashMap<>(); data.put(StringValue.of("slot"), NumericValue.of(slotId)); data.put(StringValue.of("stack"), ValueConversions.of(stack, player.level.registryAccess())); ScreenValue.this.callListener(ScreenValue.this.player, "slot_update", data); } @Override - public void dataChanged(final AbstractContainerMenu handler, final int property, final int value) + public void dataChanged(AbstractContainerMenu handler, int property, int value) { } }); } - private DataSlot getPropertyForType(final Class screenHandlerClass, final String requiredType, final int propertyIndex, final String propertyName) + private DataSlot getPropertyForType(Class screenHandlerClass, String requiredType, int propertyIndex, String propertyName) { if (screenHandlerClass.isInstance(this.screenHandler)) { @@ -289,7 +291,7 @@ private DataSlot getPropertyForType(final Class throw new InternalExpressionException("Screen property " + propertyName + " expected a " + requiredType + " screen."); } - private DataSlot getProperty(final String propertyName) + private DataSlot getProperty(String propertyName) { return switch (propertyName) { @@ -321,7 +323,7 @@ private DataSlot getProperty(final String propertyName) } - public Value queryProperty(final String propertyName) + public Value queryProperty(String propertyName) { if (propertyName.equals("name")) { @@ -331,14 +333,14 @@ public Value queryProperty(final String propertyName) { return BooleanValue.of(this.isOpen()); } - final DataSlot property = getProperty(propertyName); + DataSlot property = getProperty(propertyName); return NumericValue.of(property.get()); } - public Value modifyProperty(final String propertyName, final List lv) + public Value modifyProperty(String propertyName, List lv) { - final DataSlot property = getProperty(propertyName); - final int intValue = NumericValue.asNumber(lv.get(0)).getInt(); + DataSlot property = getProperty(propertyName); + int intValue = NumericValue.asNumber(lv.get(0)).getInt(); property.set(intValue); this.screenHandler.sendAllDataToRemote(); return Value.TRUE; @@ -373,17 +375,17 @@ public String getTypeString() } @Override - public Tag toTag(final boolean force) + public Tag toTag(boolean force) { if (this.screenHandler == null) { return Value.NULL.toTag(true); } - final ListTag nbtList = new ListTag(); + ListTag nbtList = new ListTag(); for (int i = 0; i < this.screenHandler.slots.size(); i++) { - final ItemStack itemStack = this.screenHandler.getSlot(i).getItem(); + ItemStack itemStack = this.screenHandler.getSlot(i).getItem(); nbtList.add(itemStack.save(new CompoundTag())); } return nbtList; @@ -405,7 +407,7 @@ public static class ScreenHandlerInventory implements Container { protected AbstractContainerMenu screenHandler; - public ScreenHandlerInventory(final AbstractContainerMenu screenHandler) + public ScreenHandlerInventory(AbstractContainerMenu screenHandler) { this.screenHandler = screenHandler; } @@ -419,7 +421,7 @@ public int getContainerSize() @Override public boolean isEmpty() { - for (final Slot slot : this.screenHandler.slots) + for (Slot slot : this.screenHandler.slots) { if (slot.hasItem() && !slot.getItem().isEmpty()) { @@ -430,7 +432,7 @@ public boolean isEmpty() } @Override - public ItemStack getItem(final int slot) + public ItemStack getItem(int slot) { if (slot == this.getContainerSize() - 1) { @@ -440,9 +442,9 @@ public ItemStack getItem(final int slot) } @Override - public ItemStack removeItem(final int slot, final int amount) + public ItemStack removeItem(int slot, int amount) { - final ItemStack itemStack; + ItemStack itemStack; if (slot == this.getContainerSize() - 1) { itemStack = this.screenHandler.getCarried().split(amount); @@ -459,9 +461,9 @@ public ItemStack removeItem(final int slot, final int amount) } @Override - public ItemStack removeItemNoUpdate(final int slot) + public ItemStack removeItemNoUpdate(int slot) { - final ItemStack itemStack; + ItemStack itemStack; if (slot == this.getContainerSize() - 1) { itemStack = this.screenHandler.getCarried(); @@ -489,7 +491,7 @@ public ItemStack removeItemNoUpdate(final int slot) } @Override - public void setItem(final int slot, final ItemStack stack) + public void setItem(int slot, ItemStack stack) { if (slot == this.getContainerSize() - 1) { @@ -513,7 +515,7 @@ public void setChanged() } @Override - public boolean stillValid(final Player player) + public boolean stillValid(Player player) { return true; } @@ -521,7 +523,7 @@ public boolean stillValid(final Player player) @Override public void clearContent() { - for (final Slot slot : this.screenHandler.slots) + for (Slot slot : this.screenHandler.slots) { slot.set(ItemStack.EMPTY); } @@ -530,13 +532,13 @@ public void clearContent() } - public static ItemStack splitStack(final List slots, final int slot, final int amount) + public static ItemStack splitStack(List slots, int slot, int amount) { return slot >= 0 && slot < slots.size() && !slots.get(slot).getItem().isEmpty() && amount > 0 ? slots.get(slot).getItem().split(amount) : ItemStack.EMPTY; } } - private static String actionTypeToString(final ClickType actionType) + private static String actionTypeToString(ClickType actionType) { return switch (actionType) { diff --git a/src/main/java/carpet/script/value/StringValue.java b/src/main/java/carpet/script/value/StringValue.java index 65b7dc7ff0..f9707f9eb7 100644 --- a/src/main/java/carpet/script/value/StringValue.java +++ b/src/main/java/carpet/script/value/StringValue.java @@ -3,6 +3,8 @@ import net.minecraft.nbt.StringTag; import net.minecraft.nbt.Tag; +import javax.annotation.Nullable; + public class StringValue extends Value { public static Value EMPTY = StringValue.of(""); @@ -27,12 +29,12 @@ public Value clone() return new StringValue(str); } - public StringValue(final String str) + public StringValue(String str) { this.str = str; } - public static Value of(final String value) + public static Value of(@Nullable String value) { return value == null ? Value.NULL : new StringValue(value); } @@ -44,7 +46,7 @@ public String getTypeString() } @Override - public Tag toTag(final boolean force) + public Tag toTag(boolean force) { return StringTag.valueOf(str); } diff --git a/src/main/java/carpet/script/value/ThreadValue.java b/src/main/java/carpet/script/value/ThreadValue.java index 5423194240..4b1c856dfd 100644 --- a/src/main/java/carpet/script/value/ThreadValue.java +++ b/src/main/java/carpet/script/value/ThreadValue.java @@ -20,21 +20,21 @@ public class ThreadValue extends Value private final long id; private static long sequence = 0L; - public ThreadValue(final CompletableFuture taskFuture) + public ThreadValue(CompletableFuture taskFuture) { this.taskFuture = taskFuture; this.id = sequence++; } - public ThreadValue(final Value pool, final FunctionValue function, final Expression expr, final Tokenizer.Token token, final Context ctx, final List args) + public ThreadValue(Value pool, FunctionValue function, Expression expr, Tokenizer.Token token, Context ctx, List args) { this(getCompletableFutureFromFunction(pool, function, expr, token, ctx, args)); Thread.yield(); } - public static CompletableFuture getCompletableFutureFromFunction(final Value pool, final FunctionValue function, final Expression expr, final Tokenizer.Token token, final Context ctx, final List args) + public static CompletableFuture getCompletableFutureFromFunction(Value pool, FunctionValue function, Expression expr, Tokenizer.Token token, Context ctx, List args) { - final ExecutorService executor = ctx.host.getExecutor(pool); + ExecutorService executor = ctx.host.getExecutor(pool); if (executor == null) { // app is shutting down - no more threads can be spawned. @@ -47,12 +47,12 @@ public static CompletableFuture getCompletableFutureFromFunction(final Va { return function.execute(ctx, Context.NONE, expr, token, args).evalValue(ctx); } - catch (final ExitStatement exit) + catch (ExitStatement exit) { // app stopped return exit.retval; } - catch (final ExpressionException exc) + catch (ExpressionException exc) { ctx.host.handleExpressionException("Thread failed\n", exc); return Value.NULL; @@ -84,12 +84,12 @@ public Value join() { return taskFuture.get(); } - catch (final ExitStatement exit) + catch (ExitStatement exit) { taskFuture.complete(exit.retval); return exit.retval; } - catch (final InterruptedException | ExecutionException e) + catch (InterruptedException | ExecutionException e) { return Value.NULL; } @@ -101,13 +101,13 @@ public boolean isFinished() } @Override - public boolean equals(final Object o) + public boolean equals(Object o) { return o instanceof final ThreadValue tv && tv.id == this.id; } @Override - public int compareTo(final Value o) + public int compareTo(Value o) { if (!(o instanceof final ThreadValue tv)) { @@ -123,7 +123,7 @@ public int hashCode() } @Override - public Tag toTag(final boolean force) + public Tag toTag(boolean force) { if (!force) { diff --git a/src/main/java/carpet/script/value/UndefValue.java b/src/main/java/carpet/script/value/UndefValue.java index b41ae53b48..69c96b2727 100644 --- a/src/main/java/carpet/script/value/UndefValue.java +++ b/src/main/java/carpet/script/value/UndefValue.java @@ -38,13 +38,13 @@ public Value clone() } @Override - public boolean equals(final Object o) + public boolean equals(Object o) { throw getError(); } @Override - public Value slice(final long fromDesc, final Long toDesc) + public Value slice(long fromDesc, Long toDesc) { throw getError(); } @@ -62,13 +62,13 @@ public int length() } @Override - public int compareTo(final Value o) + public int compareTo(Value o) { throw getError(); } @Override - public Value in(final Value value) + public Value in(Value value) { throw getError(); } @@ -86,13 +86,13 @@ public int hashCode() } @Override - public Tag toTag(final boolean force) + public Tag toTag(boolean force) { throw getError(); } @Override - public Value split(final Value delimiter) + public Value split(Value delimiter) { throw getError(); } @@ -110,25 +110,25 @@ public boolean isNull() } @Override - public Value add(final Value v) + public Value add(Value v) { throw getError(); } @Override - public Value subtract(final Value v) + public Value subtract(Value v) { throw getError(); } @Override - public Value multiply(final Value v) + public Value multiply(Value v) { throw getError(); } @Override - public Value divide(final Value v) + public Value divide(Value v) { throw getError(); } diff --git a/src/main/java/carpet/script/value/Value.java b/src/main/java/carpet/script/value/Value.java index f29b53425e..2f1b89bfee 100644 --- a/src/main/java/carpet/script/value/Value.java +++ b/src/main/java/carpet/script/value/Value.java @@ -14,6 +14,8 @@ import net.minecraft.nbt.Tag; +import javax.annotation.Nullable; + public abstract class Value implements Comparable, Cloneable { public static final NumericValue FALSE = BooleanValue.FALSE; @@ -36,14 +38,14 @@ public String getVariable() return boundVariable; } - public Value reboundedTo(final String value) + public Value reboundedTo(String value) { - final Value copy; + Value copy; try { copy = (Value) clone(); } - catch (final CloneNotSupportedException e) + catch (CloneNotSupportedException e) { // should not happen CarpetScriptServer.LOG.error("Failed to clone variable", e); @@ -53,7 +55,7 @@ public Value reboundedTo(final String value) return copy; } - public Value bindTo(final String value) + public Value bindTo(String value) { this.boundVariable = value; return this; @@ -69,34 +71,34 @@ public String getPrettyString() public abstract boolean getBoolean(); - public Value add(final Value o) + public Value add(Value o) { if (o instanceof FormattedTextValue) { return FormattedTextValue.combine(this, o); } - final String leftStr = this.getString(); - final String rightStr = o.getString(); + String leftStr = this.getString(); + String rightStr = o.getString(); return new StringValue(leftStr + rightStr); } - public Value subtract(final Value v) + public Value subtract(Value v) { return new StringValue(this.getString().replace(v.getString(), "")); } - public Value multiply(final Value v) + public Value multiply(Value v) { return v instanceof NumericValue || v instanceof ListValue ? v.multiply(this) : new StringValue(this.getString() + "." + v.getString()); } - public Value divide(final Value v) + public Value divide(Value v) { if (v instanceof final NumericValue number) { - final String lstr = getString(); + String lstr = getString(); return new StringValue(lstr.substring(0, (int) (lstr.length() / number.getDouble()))); } return new StringValue(getString() + "/" + v.getString()); @@ -108,7 +110,7 @@ public Value() } @Override - public int compareTo(final Value o) + public int compareTo(Value o) { return o instanceof NumericValue || o instanceof ListValue || o instanceof ThreadValue ? -o.compareTo(this) @@ -116,7 +118,7 @@ public int compareTo(final Value o) } @Override // for hashmap key access, and == operator - public boolean equals(final Object o) + public boolean equals(Object o) { if (o instanceof final Value v) { @@ -137,23 +139,23 @@ public void assertAssignable() } } - public Value in(final Value value1) + public Value in(Value value1) { - final Pattern p; + Pattern p; try { p = Pattern.compile(value1.getString()); } - catch (final PatternSyntaxException pse) + catch (PatternSyntaxException pse) { throw new InternalExpressionException("Incorrect matching pattern: " + pse.getMessage()); } - final Matcher m = p.matcher(this.getString()); + Matcher m = p.matcher(this.getString()); if (!m.find()) { return Value.NULL; } - final int gc = m.groupCount(); + int gc = m.groupCount(); if (gc == 0) { return new StringValue(m.group()); @@ -162,7 +164,7 @@ public Value in(final Value value1) { return StringValue.of(m.group(1)); } - final List groups = new ArrayList<>(gc); + List groups = new ArrayList<>(gc); for (int i = 1; i <= gc; i++) { groups.add(StringValue.of(m.group(i))); @@ -175,16 +177,16 @@ public int length() return getString().length(); } - public Value slice(final long fromDesc, final Long toDesc) + public Value slice(long fromDesc, @Nullable Long toDesc) { - final String value = this.getString(); - final int size = value.length(); - final int from = ListValue.normalizeIndex(fromDesc, size); + String value = this.getString(); + int size = value.length(); + int from = ListValue.normalizeIndex(fromDesc, size); if (toDesc == null) { return new StringValue(value.substring(from)); } - final int to = ListValue.normalizeIndex(toDesc, size + 1); + int to = ListValue.normalizeIndex(toDesc, size + 1); if (from > to) { return StringValue.EMPTY; @@ -192,7 +194,7 @@ public Value slice(final long fromDesc, final Long toDesc) return new StringValue(value.substring(from, to)); } - public Value split(Value delimiter) + public Value split(@Nullable Value delimiter) { if (delimiter == null) { @@ -202,7 +204,7 @@ public Value split(Value delimiter) { return ListValue.wrap(Arrays.stream(getString().split(delimiter.getString())).map(StringValue::new)); } - catch (final PatternSyntaxException pse) + catch (PatternSyntaxException pse) { throw new InternalExpressionException("Incorrect pattern for 'split': " + pse.getMessage()); } @@ -210,12 +212,12 @@ public Value split(Value delimiter) public double readDoubleNumber() { - final String s = getString(); + String s = getString(); try { return Double.parseDouble(s); } - catch (final NumberFormatException e) + catch (NumberFormatException e) { return Double.NaN; } @@ -234,7 +236,7 @@ public String getTypeString() @Override public int hashCode() { - final String stringVal = getString(); + String stringVal = getString(); return stringVal.isEmpty() ? 0 : ("s" + stringVal).hashCode(); } @@ -244,7 +246,7 @@ public Value deepcopy() { return (Value) this.clone(); } - catch (final CloneNotSupportedException e) + catch (CloneNotSupportedException e) { // should never happen throw new InternalExpressionException("Cannot make a copy of value: " + this); diff --git a/src/main/java/carpet/script/value/ValueConversions.java b/src/main/java/carpet/script/value/ValueConversions.java index 9ffcaff717..646ec1af74 100644 --- a/src/main/java/carpet/script/value/ValueConversions.java +++ b/src/main/java/carpet/script/value/ValueConversions.java @@ -59,40 +59,42 @@ import com.mojang.brigadier.exceptions.CommandSyntaxException; +import javax.annotation.Nullable; + public class ValueConversions { - public static Value of(final BlockPos pos) + public static Value of(BlockPos pos) { return ListValue.of(new NumericValue(pos.getX()), new NumericValue(pos.getY()), new NumericValue(pos.getZ())); } - public static Value of(final Vec3 vec) + public static Value of(Vec3 vec) { return ListValue.of(new NumericValue(vec.x), new NumericValue(vec.y), new NumericValue(vec.z)); } - public static Value of(final ColumnPos cpos) + public static Value of(ColumnPos cpos) { return ListValue.of(new NumericValue(cpos.x()), new NumericValue(cpos.z())); } - public static Value of(final ServerLevel world) + public static Value of(ServerLevel world) { return of(world.dimension().location()); } - public static Value of(final MaterialColor color) + public static Value of(MaterialColor color) { return ListValue.of(StringValue.of(Carpet.getMapColorNames().get(color)), ofRGB(color.col)); } - public static Value of(final MinMaxBounds range) + public static Value of(MinMaxBounds range) { return ListValue.of(NumericValue.of(range.getMin()), NumericValue.of(range.getMax())); } @Deprecated - public static Value of(final ItemStack stack) + public static Value of(ItemStack stack) { return stack == null || stack.isEmpty() ? Value.NULL : ListValue.of( of(BuiltInRegistries.ITEM.getKey(stack.getItem())), @@ -101,7 +103,7 @@ public static Value of(final ItemStack stack) ); } - public static Value of(final ItemStack stack, final RegistryAccess regs) + public static Value of(ItemStack stack, RegistryAccess regs) { return stack == null || stack.isEmpty() ? Value.NULL : ListValue.of( of(regs.registryOrThrow(Registries.ITEM).getKey(stack.getItem())), @@ -110,7 +112,7 @@ public static Value of(final ItemStack stack, final RegistryAccess regs) ); } - public static Value of(final Objective objective) + public static Value of(Objective objective) { return ListValue.of( StringValue.of(objective.getName()), @@ -119,7 +121,7 @@ public static Value of(final Objective objective) } - public static Value of(final ObjectiveCriteria criteria) + public static Value of(ObjectiveCriteria criteria) { return ListValue.of( StringValue.of(criteria.getName()), @@ -128,18 +130,18 @@ public static Value of(final ObjectiveCriteria criteria) } - public static Value of(final ParticleOptions particle) + public static Value of(ParticleOptions particle) { - final String repr = particle.writeToString(); + String repr = particle.writeToString(); return StringValue.of(repr.startsWith("minecraft:") ? repr.substring(10) : repr); } - public static Value ofRGB(final int value) + public static Value ofRGB(int value) { return new NumericValue(value * 256 + 255); } - public static Level dimFromValue(final Value dimensionValue, final MinecraftServer server) + public static Level dimFromValue(Value dimensionValue, MinecraftServer server) { if (dimensionValue instanceof EntityValue) { @@ -158,16 +160,16 @@ else if (dimensionValue instanceof BlockValue bv) } else { - final String dimString = dimensionValue.getString().toLowerCase(Locale.ROOT); + String dimString = dimensionValue.getString().toLowerCase(Locale.ROOT); return switch (dimString) { case "nether", "the_nether" -> server.getLevel(Level.NETHER); case "end", "the_end" -> server.getLevel(Level.END); case "overworld", "over_world" -> server.getLevel(Level.OVERWORLD); default -> { ResourceKey dim = null; - final ResourceLocation id = new ResourceLocation(dimString); + ResourceLocation id = new ResourceLocation(dimString); // not using RegistryKey.of since that one creates on check - for (final ResourceKey world : (server.levelKeys())) + for (ResourceKey world : (server.levelKeys())) { if (id.equals(world.location())) { @@ -185,17 +187,17 @@ else if (dimensionValue instanceof BlockValue bv) } } - public static Value of(final ResourceKey dim) + public static Value of(ResourceKey dim) { return of(dim.location()); } - public static Value of(final TagKey tagKey) + public static Value of(TagKey tagKey) { return of(tagKey.location()); } - public static Value of(final ResourceLocation id) + public static Value of(@Nullable ResourceLocation id) { if (id == null) // should be Value.NULL { @@ -204,7 +206,7 @@ public static Value of(final ResourceLocation id) return new StringValue(simplify(id)); } - public static String simplify(final ResourceLocation id) + public static String simplify(ResourceLocation id) { if (id == null) // should be Value.NULL { @@ -217,7 +219,7 @@ public static String simplify(final ResourceLocation id) return id.toString(); } - public static Value of(final GlobalPos pos) + public static Value of(GlobalPos pos) { return ListValue.of( ValueConversions.of(pos.dimension()), @@ -225,12 +227,12 @@ public static Value of(final GlobalPos pos) ); } - public static Value fromPath(final ServerLevel world, final Path path) + public static Value fromPath(ServerLevel world, Path path) { - final List nodes = new ArrayList<>(); + List nodes = new ArrayList<>(); for (int i = 0, len = path.getNodeCount(); i < len; i++) { - final Node node = path.getNode(i); + Node node = path.getNode(i); nodes.add(ListValue.of( new BlockValue(null, world, node.asBlockPos()), new StringValue(node.type.name().toLowerCase(Locale.ROOT)), @@ -241,13 +243,13 @@ public static Value fromPath(final ServerLevel world, final Path path) return ListValue.wrap(nodes); } - public static Value fromTimedMemory(final Entity e, final long expiry, final Object v) + public static Value fromTimedMemory(Entity e, long expiry, Object v) { - final Value ret = fromEntityMemory(e, v); + Value ret = fromEntityMemory(e, v); return ret.isNull() || expiry == Long.MAX_VALUE ? ret : ListValue.of(ret, new NumericValue(expiry)); } - private static Value fromEntityMemory(final Entity e, Object v) + private static Value fromEntityMemory(Entity e, Object v) { if (v instanceof GlobalPos pos) { @@ -259,7 +261,7 @@ private static Value fromEntityMemory(final Entity e, Object v) } if (v instanceof final BlockPos pos) { - return new BlockValue(null, e.getCommandSenderWorld(), pos); + return new BlockValue(null, (ServerLevel) e.getCommandSenderWorld(), pos); } if (v instanceof final Number number) { @@ -286,12 +288,12 @@ private static Value fromEntityMemory(final Entity e, Object v) } if (v instanceof final PositionTracker tracker) { - return new BlockValue(null, e.getCommandSenderWorld(), tracker.currentBlockPosition()); + return new BlockValue(null, (ServerLevel) e.getCommandSenderWorld(), tracker.currentBlockPosition()); } if (v instanceof final WalkTarget target) { return ListValue.of( - new BlockValue(null, e.getCommandSenderWorld(), target.getTarget().currentBlockPosition()), + new BlockValue(null, (ServerLevel) e.getCommandSenderWorld(), target.getTarget().currentBlockPosition()), new NumericValue(target.getSpeedModifier()), new NumericValue(target.getCloseEnoughDist()) ); @@ -310,7 +312,7 @@ private static Value fromEntityMemory(final Entity e, Object v) { return ListValue.of(); } - final Object el = l.get(0); + Object el = l.get(0); if (el instanceof final Entity entity) { return ListValue.wrap(l.stream().map(o -> new EntityValue(entity))); @@ -323,16 +325,16 @@ private static Value fromEntityMemory(final Entity e, Object v) return Value.NULL; } - private static Value ofUUID(final ServerLevel entityWorld, final UUID uuid) + private static Value ofUUID(ServerLevel entityWorld, UUID uuid) { - final Entity current = entityWorld.getEntity(uuid); + Entity current = entityWorld.getEntity(uuid); return ListValue.of( current == null ? Value.NULL : new EntityValue(current), new StringValue(uuid.toString()) ); } - public static Value of(final AABB box) + public static Value of(AABB box) { return ListValue.of( ListValue.fromTriple(box.minX, box.minY, box.minZ), @@ -340,7 +342,7 @@ public static Value of(final AABB box) ); } - public static Value of(final BoundingBox box) + public static Value of(BoundingBox box) { return ListValue.of( ListValue.fromTriple(box.minX(), box.minY(), box.minZ()), @@ -348,27 +350,27 @@ public static Value of(final BoundingBox box) ); } - public static Value of(final StructureStart structure, final RegistryAccess regs) + public static Value of(StructureStart structure, RegistryAccess regs) { if (structure == null || structure == StructureStart.INVALID_START) { return Value.NULL; } - final BoundingBox boundingBox = structure.getBoundingBox(); + BoundingBox boundingBox = structure.getBoundingBox(); if (boundingBox.maxX() < boundingBox.minX() || boundingBox.maxY() < boundingBox.minY() || boundingBox.maxZ() < boundingBox.minZ()) { return Value.NULL; } - final Map ret = new HashMap<>(); + Map ret = new HashMap<>(); ret.put(new StringValue("box"), of(boundingBox)); - final List pieces = new ArrayList<>(); - for (final StructurePiece piece : structure.getPieces()) + List pieces = new ArrayList<>(); + for (StructurePiece piece : structure.getPieces()) { - final BoundingBox box = piece.getBoundingBox(); + BoundingBox box = piece.getBoundingBox(); if (box.maxX() >= box.minX() && box.maxY() >= box.minY() && box.maxZ() >= box.minZ()) { pieces.add(ListValue.of( - new StringValue(NBTSerializableValue.nameFromRegistryId(regs.registryOrThrow(Registries.STRUCTURE_PIECE).getKey(piece.getType()))), + NBTSerializableValue.nameFromRegistryId(regs.registryOrThrow(Registries.STRUCTURE_PIECE).getKey(piece.getType())), (piece.getOrientation() == null) ? Value.NULL : new StringValue(piece.getOrientation().getName()), ListValue.fromTriple(box.minX(), box.minY(), box.minZ()), ListValue.fromTriple(box.maxX(), box.maxY(), box.maxZ()) @@ -379,9 +381,9 @@ public static Value of(final StructureStart structure, final RegistryAccess regs return MapValue.wrap(ret); } - public static Value fromProperty(final BlockState state, final Property p) + public static Value fromProperty(BlockState state, Property p) { - final Comparable object = state.getValue(p); + Comparable object = state.getValue(p); if (object instanceof Boolean || object instanceof Number) { return StringValue.of(object.toString()); @@ -443,16 +445,16 @@ public ListValue build() //hashMap.put("horse.chest", 499); }}; - public static Value ofVanillaSlotResult(final int itemSlot) + public static Value ofVanillaSlotResult(int itemSlot) { - final SlotParam ret = slotIdsToSlotParams.get(itemSlot); + SlotParam ret = slotIdsToSlotParams.get(itemSlot); return ret == null ? ListValue.of(Value.NULL, new NumericValue(itemSlot)) : ret.build(); } - public static Value ofBlockPredicate(final RegistryAccess registryAccess, final Predicate blockPredicate) + public static Value ofBlockPredicate(RegistryAccess registryAccess, Predicate blockPredicate) { - final Vanilla.BlockPredicatePayload payload = Vanilla.BlockPredicatePayload.of(blockPredicate); - final Registry blocks = registryAccess.registryOrThrow(Registries.BLOCK); + Vanilla.BlockPredicatePayload payload = Vanilla.BlockPredicatePayload.of(blockPredicate); + Registry blocks = registryAccess.registryOrThrow(Registries.BLOCK); return ListValue.of( payload.state() == null ? Value.NULL : of(blocks.getKey(payload.state().getBlock())), payload.tagKey() == null ? Value.NULL : of(blocks.getTag(payload.tagKey()).get().key()), @@ -461,13 +463,13 @@ public static Value ofBlockPredicate(final RegistryAccess registryAccess, final ); } - public static ItemStack getItemStackFromValue(final Value value, final boolean withCount, final RegistryAccess regs) + public static ItemStack getItemStackFromValue(Value value, boolean withCount, RegistryAccess regs) { if (value.isNull()) { return ItemStack.EMPTY; } - final String name; + String name; int count = 1; CompoundTag nbtTag = null; if (value instanceof ListValue list) @@ -476,13 +478,13 @@ public static ItemStack getItemStackFromValue(final Value value, final boolean w { throw new ThrowStatement("item definition from list of size " + list.length(), Throwables.UNKNOWN_ITEM); } - final List items = list.getItems(); + List items = list.getItems(); name = items.get(0).getString(); if (withCount) { count = NumericValue.asNumber(items.get(1)).getInt(); } - final Value nbtValue = items.get(2); + Value nbtValue = items.get(2); if (!nbtValue.isNull()) { nbtTag = ((NBTSerializableValue) NBTSerializableValue.fromValue(nbtValue)).getCompoundTag(); @@ -492,12 +494,12 @@ public static ItemStack getItemStackFromValue(final Value value, final boolean w { name = value.getString(); } - final ItemInput itemInput = NBTSerializableValue.parseItem(name, nbtTag, regs); + ItemInput itemInput = NBTSerializableValue.parseItem(name, nbtTag, regs); try { return itemInput.createItemStack(count, false); } - catch (final CommandSyntaxException cse) + catch (CommandSyntaxException cse) { if (!withCount) { @@ -510,7 +512,7 @@ public static ItemStack getItemStackFromValue(final Value value, final boolean w } } - public static Value guess(final ServerLevel serverWorld, final Object o) + public static Value guess(ServerLevel serverWorld, Object o) { if (o == null) { From 41e33503fbe484b3e2c59d87f3bd2478d33f98bf Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 8 Feb 2023 21:44:15 +0100 Subject: [PATCH 049/233] 23w06a --- docs/scarpet/api/Auxiliary.md | 4 ++-- gradle.properties | 6 +++--- .../carpet/mixins/LivingEntity_maxCollisionsMixin.java | 3 +-- .../carpet/mixins/LivingEntity_scarpetEventsMixin.java | 2 +- src/main/java/carpet/mixins/ServerLevel_scarpetMixin.java | 6 ++++-- src/main/java/carpet/mixins/ServerLevel_tickMixin.java | 7 +++---- .../java/carpet/mixins/ServerPlayer_scarpetEventMixin.java | 4 ++-- .../java/carpet/mixins/SummonCommand_lightningMixin.java | 2 +- src/main/java/carpet/script/utils/ShapesRenderer.java | 6 +++--- 9 files changed, 20 insertions(+), 20 deletions(-) diff --git a/docs/scarpet/api/Auxiliary.md b/docs/scarpet/api/Auxiliary.md index d9589c9974..3fad58260b 100644 --- a/docs/scarpet/api/Auxiliary.md +++ b/docs/scarpet/api/Auxiliary.md @@ -171,8 +171,8 @@ Available shapes: * `tilt`, `lean`, `turn` - additional rotations along all three axis. for `block`, it use its block center as the origin. * `scale` - scale of it in 3 axis-direction. should be a number or a list of 3 numbers (x,y,z). * `skylight`, `blocklight` - light level. omit it to use local light level. should between 0~15. - * `variant` - one of `'none'`, `'third_person_left_hand'`, `'third_person_right_hand'`, `'first_person_left_hand'`, - `'first_person_right_hand'`, `'head'`, `'gui'`, `'ground'`, `'fixed'`. In addition to the literal meaning, + * `variant` - one of `'none'`, `'thirdperson_lefthand'`, `'thirdperson_righthand'`, `'firstperson_lefthand'`, + `'firstperson_righthand'`, `'head'`, `'gui'`, `'ground'`, `'fixed'`. In addition to the literal meaning, it can also be used to use special models of tridents and telescopes. This attribute is experimental and use of it will change in the future. diff --git a/gradle.properties b/gradle.properties index d3691f3d91..ddbea677fc 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,10 +4,10 @@ org.gradle.jvmargs=-Xmx1G # Fabric Properties # check these on https://fabricmc.net/use # or better: https://modmuss50.me/fabric.html - minecraft_version=23w05a - loader_version=0.14.13 + minecraft_version=23w06a + loader_version=0.14.14 jsr305_version=3.0.2 - fabric_version=0.73.3+1.19.4 + fabric_version=0.73.5+1.19.4 # Mod Properties mod_version = 1.4.96 diff --git a/src/main/java/carpet/mixins/LivingEntity_maxCollisionsMixin.java b/src/main/java/carpet/mixins/LivingEntity_maxCollisionsMixin.java index 4a65060cdb..e237b3aa5c 100644 --- a/src/main/java/carpet/mixins/LivingEntity_maxCollisionsMixin.java +++ b/src/main/java/carpet/mixins/LivingEntity_maxCollisionsMixin.java @@ -9,7 +9,6 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.util.List; -import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntitySelector; import net.minecraft.world.entity.EntityType; @@ -62,7 +61,7 @@ private void tickPushingReplacement(CallbackInfo ci) { } if (candidates > maxEntityCramming - 1) { - this.hurt(DamageSource.CRAMMING, 6.0F); + this.hurt(damageSources().cramming(), 6.0F); } } if (CarpetSettings.maxEntityCollisions > 0 && entities.size() > CarpetSettings.maxEntityCollisions) diff --git a/src/main/java/carpet/mixins/LivingEntity_scarpetEventsMixin.java b/src/main/java/carpet/mixins/LivingEntity_scarpetEventsMixin.java index 57c66d84b2..fe4614205f 100644 --- a/src/main/java/carpet/mixins/LivingEntity_scarpetEventsMixin.java +++ b/src/main/java/carpet/mixins/LivingEntity_scarpetEventsMixin.java @@ -34,7 +34,7 @@ public LivingEntity_scarpetEventsMixin(EntityType type, Level world) @Inject(method = "die", at = @At("HEAD")) private void onDeathCall(DamageSource damageSource_1, CallbackInfo ci) { - ((EntityInterface)this).getEventContainer().onEvent(EntityEventsGroup.Event.ON_DEATH, damageSource_1.msgId); + ((EntityInterface)this).getEventContainer().onEvent(EntityEventsGroup.Event.ON_DEATH, damageSource_1.getMsgId()); } @Inject(method = "actuallyHurt", cancellable = true, locals = LocalCapture.CAPTURE_FAILHARD, at = @At( diff --git a/src/main/java/carpet/mixins/ServerLevel_scarpetMixin.java b/src/main/java/carpet/mixins/ServerLevel_scarpetMixin.java index 9ace41bbc2..927f3a2fea 100644 --- a/src/main/java/carpet/mixins/ServerLevel_scarpetMixin.java +++ b/src/main/java/carpet/mixins/ServerLevel_scarpetMixin.java @@ -3,6 +3,7 @@ import carpet.fakes.ServerWorldInterface; import net.minecraft.core.BlockPos; import net.minecraft.core.Holder; +import net.minecraft.core.RegistryAccess; import net.minecraft.resources.ResourceKey; import net.minecraft.server.level.ServerLevel; import net.minecraft.util.profiling.ProfilerFiller; @@ -40,8 +41,9 @@ @Mixin(ServerLevel.class) public abstract class ServerLevel_scarpetMixin extends Level implements ServerWorldInterface { - protected ServerLevel_scarpetMixin(WritableLevelData writableLevelData, ResourceKey resourceKey, Holder holder, Supplier supplier, boolean bl, boolean bl2, long l, int i) { - super(writableLevelData, resourceKey, holder, supplier, bl, bl2, l, i); + protected ServerLevel_scarpetMixin(WritableLevelData writableLevelData, ResourceKey resourceKey, RegistryAccess registryAccess, Holder holder, Supplier supplier, boolean bl, boolean bl2, long l, int i) + { + super(writableLevelData, resourceKey, registryAccess, holder, supplier, bl, bl2, l, i); } @Inject(method = "tickChunk", locals = LocalCapture.CAPTURE_FAILHARD, at = @At( diff --git a/src/main/java/carpet/mixins/ServerLevel_tickMixin.java b/src/main/java/carpet/mixins/ServerLevel_tickMixin.java index 9f56168fc3..fd6a874827 100644 --- a/src/main/java/carpet/mixins/ServerLevel_tickMixin.java +++ b/src/main/java/carpet/mixins/ServerLevel_tickMixin.java @@ -3,6 +3,7 @@ import carpet.helpers.TickSpeed; import carpet.utils.CarpetProfiler; import net.minecraft.core.Holder; +import net.minecraft.core.RegistryAccess; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; @@ -24,11 +25,9 @@ @Mixin(ServerLevel.class) public abstract class ServerLevel_tickMixin extends Level { - - - protected ServerLevel_tickMixin(WritableLevelData writableLevelData, ResourceKey resourceKey, Holder holder, Supplier supplier, boolean bl, boolean bl2, long l, int i) + protected ServerLevel_tickMixin(final WritableLevelData writableLevelData, final ResourceKey resourceKey, final RegistryAccess registryAccess, final Holder holder, final Supplier supplier, final boolean bl, final boolean bl2, final long l, final int i) { - super(writableLevelData, resourceKey, holder, supplier, bl, bl2, l, i); + super(writableLevelData, resourceKey, registryAccess, holder, supplier, bl, bl2, l, i); } @Shadow protected abstract void runBlockEvents(); diff --git a/src/main/java/carpet/mixins/ServerPlayer_scarpetEventMixin.java b/src/main/java/carpet/mixins/ServerPlayer_scarpetEventMixin.java index a1a76b0ac1..0a76eb7b82 100644 --- a/src/main/java/carpet/mixins/ServerPlayer_scarpetEventMixin.java +++ b/src/main/java/carpet/mixins/ServerPlayer_scarpetEventMixin.java @@ -42,7 +42,7 @@ public ServerPlayer_scarpetEventMixin(Level level, BlockPos blockPos, float f, G super(level, blockPos, f, gameProfile); } - @Shadow protected abstract void completeUsingItem(); + //@Shadow protected abstract void completeUsingItem(); @Shadow public boolean wonGame; @@ -76,7 +76,7 @@ private void grabStat(Stat stat, int amount, CallbackInfo ci) @Inject(method = "die", at = @At("HEAD")) private void onDeathEvent(DamageSource source, CallbackInfo ci) { - ((EntityInterface)this).getEventContainer().onEvent(EntityEventsGroup.Event.ON_DEATH, source.msgId); + ((EntityInterface)this).getEventContainer().onEvent(EntityEventsGroup.Event.ON_DEATH, source.getMsgId()); if (PLAYER_DIES.isNeeded()) { PLAYER_DIES.onPlayerEvent((ServerPlayer) (Object)this); diff --git a/src/main/java/carpet/mixins/SummonCommand_lightningMixin.java b/src/main/java/carpet/mixins/SummonCommand_lightningMixin.java index c71037affa..97c4d45011 100644 --- a/src/main/java/carpet/mixins/SummonCommand_lightningMixin.java +++ b/src/main/java/carpet/mixins/SummonCommand_lightningMixin.java @@ -17,7 +17,7 @@ @Mixin(SummonCommand.class) public class SummonCommand_lightningMixin { - @Redirect(method = "spawnEntity", at = @At( + @Redirect(method = "createEntity", at = @At( value = "INVOKE", target = "Lnet/minecraft/world/entity/Entity;blockPosition()Lnet/minecraft/core/BlockPos;" )) diff --git a/src/main/java/carpet/script/utils/ShapesRenderer.java b/src/main/java/carpet/script/utils/ShapesRenderer.java index e2336c33cb..45c1100ee7 100644 --- a/src/main/java/carpet/script/utils/ShapesRenderer.java +++ b/src/main/java/carpet/script/utils/ShapesRenderer.java @@ -33,7 +33,6 @@ import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.Sheets; -import net.minecraft.client.renderer.block.model.ItemTransforms; import net.minecraft.client.renderer.blockentity.BlockEntityRenderer; import net.minecraft.client.renderer.texture.OverlayTexture; import net.minecraft.client.resources.model.Material; @@ -44,6 +43,7 @@ import net.minecraft.resources.ResourceKey; import net.minecraft.util.Mth; import net.minecraft.world.item.DyeColor; +import net.minecraft.world.item.ItemDisplayContext; import net.minecraft.world.level.Level; import net.minecraft.world.level.LightLayer; import net.minecraft.world.level.block.EntityBlock; @@ -287,7 +287,7 @@ public static class RenderedSprite extends RenderedShape Date: Wed, 8 Feb 2023 21:44:53 +0100 Subject: [PATCH 050/233] 1.4.97 --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index ddbea677fc..21e3d6807e 100644 --- a/gradle.properties +++ b/gradle.properties @@ -10,7 +10,7 @@ org.gradle.jvmargs=-Xmx1G fabric_version=0.73.5+1.19.4 # Mod Properties - mod_version = 1.4.96 + mod_version = 1.4.97 maven_group = carpet archives_base_name = fabric-carpet From c64a28ff1bf3bf8acb64b6b73e4af80ff5111fde Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Wed, 8 Feb 2023 20:48:44 +0000 Subject: [PATCH 051/233] Merge docs for 'Carpet Mod 1.4.97 for Minecraft 23w06a' --- docs/scarpet/Full.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/scarpet/Full.md b/docs/scarpet/Full.md index f77fda7084..c6de52acc9 100644 --- a/docs/scarpet/Full.md +++ b/docs/scarpet/Full.md @@ -5463,8 +5463,8 @@ Available shapes: * `tilt`, `lean`, `turn` - additional rotations along all three axis. for `block`, it use its block center as the origin. * `scale` - scale of it in 3 axis-direction. should be a number or a list of 3 numbers (x,y,z). * `skylight`, `blocklight` - light level. omit it to use local light level. should between 0~15. - * `variant` - one of `'none'`, `'third_person_left_hand'`, `'third_person_right_hand'`, `'first_person_left_hand'`, - `'first_person_right_hand'`, `'head'`, `'gui'`, `'ground'`, `'fixed'`. In addition to the literal meaning, + * `variant` - one of `'none'`, `'thirdperson_lefthand'`, `'thirdperson_righthand'`, `'firstperson_lefthand'`, + `'firstperson_righthand'`, `'head'`, `'gui'`, `'ground'`, `'fixed'`. In addition to the literal meaning, it can also be used to use special models of tridents and telescopes. This attribute is experimental and use of it will change in the future. From 2b1bb9652bd17f2f587fd1a4bc048436ea39bf7e Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Sat, 11 Feb 2023 01:24:13 +0100 Subject: [PATCH 052/233] added ON_TICK support for display entities --- .../mixins/Display_scarpetEventMixin.java | 28 +++++++++++++++++++ src/main/resources/carpet.mixins.json | 1 + 2 files changed, 29 insertions(+) create mode 100644 src/main/java/carpet/mixins/Display_scarpetEventMixin.java diff --git a/src/main/java/carpet/mixins/Display_scarpetEventMixin.java b/src/main/java/carpet/mixins/Display_scarpetEventMixin.java new file mode 100644 index 0000000000..c69feb098a --- /dev/null +++ b/src/main/java/carpet/mixins/Display_scarpetEventMixin.java @@ -0,0 +1,28 @@ +package carpet.mixins; + +import carpet.fakes.EntityInterface; +import carpet.script.EntityEventsGroup; +import net.minecraft.world.entity.Display; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.level.Level; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(Display.class) +public abstract class Display_scarpetEventMixin extends Entity +{ + public Display_scarpetEventMixin(final EntityType entityType, final Level level) + { + super(entityType, level); + } + + @Inject(method = "tick", at = @At("HEAD")) + private void onTickCall(CallbackInfo ci) + { + // calling extra on_tick because displays don't tick + ((EntityInterface)this).getEventContainer().onEvent(EntityEventsGroup.Event.ON_TICK); + } +} diff --git a/src/main/resources/carpet.mixins.json b/src/main/resources/carpet.mixins.json index dc971d3b1b..5b0bd9eb1f 100644 --- a/src/main/resources/carpet.mixins.json +++ b/src/main/resources/carpet.mixins.json @@ -138,6 +138,7 @@ "FallingBlockEntity_scarpetEventsMixin", "HangingEntity_scarpetEventsMixin", "PrimedTnt_scarpetEventsMixin", + "Display_scarpetEventMixin", "BlockItem_scarpetEventMixin", "PlayerList_scarpetEventsMixin", "Inventory_scarpetEventMixin", From e4c090c355dc2af4fd1027881ddbe5c72204ec9a Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Sat, 11 Feb 2023 01:26:04 +0100 Subject: [PATCH 053/233] fxied player_interacts_with_blocks not triggering --- .../mixins/ServerPlayerGameMode_scarpetEventsMixin.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/carpet/mixins/ServerPlayerGameMode_scarpetEventsMixin.java b/src/main/java/carpet/mixins/ServerPlayerGameMode_scarpetEventsMixin.java index 98f0ffecdc..91eb674f66 100644 --- a/src/main/java/carpet/mixins/ServerPlayerGameMode_scarpetEventsMixin.java +++ b/src/main/java/carpet/mixins/ServerPlayerGameMode_scarpetEventsMixin.java @@ -53,8 +53,9 @@ private void onBlockBroken(BlockPos blockPos_1, CallbackInfoReturnable } @Inject(method = "useItemOn", at = @At( - value = "RETURN", - ordinal = 2 + value = "INVOKE", + target = "Lnet/minecraft/advancements/critereon/ItemInteractWithBlockTrigger;trigger(Lnet/minecraft/server/level/ServerPlayer;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/item/ItemStack;)V", + shift = At.Shift.BEFORE )) private void onBlockActivated(ServerPlayer serverPlayerEntity, Level world, ItemStack stack, InteractionHand hand, BlockHitResult hitResult, CallbackInfoReturnable cir) { From 2ff1f4fb71fe267355ef1f61c7faff811026dbdb Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Sat, 11 Feb 2023 01:33:01 +0100 Subject: [PATCH 054/233] refactored nonscarpet references yeet --- src/main/java/carpet/CarpetServer.java | 20 +- .../fakes/ServerChunkManagerInterface.java | 8 - .../mixins/BlockItem_scarpetEventMixin.java | 6 +- .../carpet/mixins/PlayerList_coreMixin.java | 3 - .../mixins/PlayerList_scarpetEventsMixin.java | 9 +- .../carpet/mixins/ServerChunkCacheMixin.java | 9 +- ...erverGamePacketListenerImpl_coreMixin.java | 5 +- ...PacketListenerImpl_scarpetEventsMixin.java | 19 -- .../java/carpet/script/CarpetScriptHost.java | 28 +-- .../carpet/script/CarpetScriptServer.java | 54 ++--- .../script/annotation/AnnotationParser.java | 3 +- .../java/carpet/script/annotation/Param.java | 3 +- .../java/carpet/script/api/WorldAccess.java | 16 +- .../java/carpet/script/external/Carpet.java | 104 +++++++-- .../java/carpet/script/external/Vanilla.java | 19 +- .../carpet/script/utils/AppStoreManager.java | 15 +- src/main/java/carpet/script/utils/Colors.java | 207 +++++++++++++++++ .../carpet/script/utils/ShapesRenderer.java | 33 ++- .../script/utils/shapes/ShapeDirection.java | 34 --- .../carpet/script/value/ValueConversions.java | 3 +- src/main/java/carpet/utils/BlockInfo.java | 209 +----------------- src/main/java/carpet/utils/SpawnChunks.java | 3 +- 22 files changed, 409 insertions(+), 401 deletions(-) delete mode 100644 src/main/java/carpet/fakes/ServerChunkManagerInterface.java create mode 100644 src/main/java/carpet/script/utils/Colors.java diff --git a/src/main/java/carpet/CarpetServer.java b/src/main/java/carpet/CarpetServer.java index 2b9aa05ea8..27fa84e1f1 100644 --- a/src/main/java/carpet/CarpetServer.java +++ b/src/main/java/carpet/CarpetServer.java @@ -26,6 +26,7 @@ import carpet.api.settings.SettingsManager; import carpet.logging.HUDController; import carpet.script.external.Carpet; +import carpet.script.external.Vanilla; import carpet.script.utils.ParticleParser; import carpet.utils.MobAI; import carpet.utils.SpawnReporter; @@ -35,6 +36,7 @@ import net.minecraft.commands.CommandBuildContext; import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.Commands; +import net.minecraft.network.chat.Component; import net.minecraft.server.MinecraftServer; import net.minecraft.server.commands.PerfCommand; import net.minecraft.server.level.ServerPlayer; @@ -164,16 +166,25 @@ public static void onPlayerLoggedIn(ServerPlayer player) { ServerNetworkHandler.onPlayerJoin(player); LoggerRegistry.playerConnected(player); - scriptServer.onPlayerJoin(player); extensions.forEach(e -> e.onPlayerLoggedIn(player)); - + scriptServer.onPlayerJoin(player); } + @Deprecated(forRemoval = true) public static void onPlayerLoggedOut(ServerPlayer player) + { + onPlayerLoggedOut(player, Component.translatable("multiplayer.player.left")); + } + public static void onPlayerLoggedOut(ServerPlayer player, Component reason) { ServerNetworkHandler.onPlayerLoggedOut(player); LoggerRegistry.playerDisconnected(player); extensions.forEach(e -> e.onPlayerLoggedOut(player)); + // first case client, second case server + CarpetScriptServer runningScriptServer = (player.getServer() == null) ? scriptServer : Vanilla.MinecraftServer_getScriptServer(player.getServer()); + if (runningScriptServer != null && !runningScriptServer.stopAll) { + runningScriptServer.onPlayerLoggedOut(player, reason); + } } public static void clientPreClosing() @@ -189,6 +200,11 @@ public static void onServerClosed(MinecraftServer server) if (minecraft_server != null) { if (scriptServer != null) scriptServer.onClose(); + // this is a mess, will cleanip onlly when global reference is gone + if (!Vanilla.MinecraftServer_getScriptServer(server).stopAll) { + Vanilla.MinecraftServer_getScriptServer(server).onClose(); + } + scriptServer = null; ServerNetworkHandler.close(); diff --git a/src/main/java/carpet/fakes/ServerChunkManagerInterface.java b/src/main/java/carpet/fakes/ServerChunkManagerInterface.java deleted file mode 100644 index a65de7bf9d..0000000000 --- a/src/main/java/carpet/fakes/ServerChunkManagerInterface.java +++ /dev/null @@ -1,8 +0,0 @@ -package carpet.fakes; - -import net.minecraft.server.level.DistanceManager; - -public interface ServerChunkManagerInterface -{ - DistanceManager getCMTicketManager(); -} diff --git a/src/main/java/carpet/mixins/BlockItem_scarpetEventMixin.java b/src/main/java/carpet/mixins/BlockItem_scarpetEventMixin.java index 2b34ecaca5..2a2d43bd95 100644 --- a/src/main/java/carpet/mixins/BlockItem_scarpetEventMixin.java +++ b/src/main/java/carpet/mixins/BlockItem_scarpetEventMixin.java @@ -29,9 +29,9 @@ private void afterPlacement(BlockPlaceContext context, CallbackInfoReturnable cir) { - if (blockPlaceContext.getPlayer() instanceof ServerPlayer && PLAYER_PLACING_BLOCK.isNeeded()) { - if (PLAYER_PLACING_BLOCK.onBlockPlaced((ServerPlayer) blockPlaceContext.getPlayer(), blockPlaceContext.getClickedPos(), blockPlaceContext.getHand(), blockPlaceContext.getItemInHand())) { + private void beforePlacement(BlockPlaceContext context, BlockState placementState, CallbackInfoReturnable cir) { + if (context.getPlayer() instanceof ServerPlayer && PLAYER_PLACING_BLOCK.isNeeded()) { + if (PLAYER_PLACING_BLOCK.onBlockPlaced((ServerPlayer) context.getPlayer(), context.getClickedPos(), context.getHand(), context.getItemInHand())) { cir.setReturnValue(false); cir.cancel(); } diff --git a/src/main/java/carpet/mixins/PlayerList_coreMixin.java b/src/main/java/carpet/mixins/PlayerList_coreMixin.java index 27f095aef1..e547f6b6f7 100644 --- a/src/main/java/carpet/mixins/PlayerList_coreMixin.java +++ b/src/main/java/carpet/mixins/PlayerList_coreMixin.java @@ -9,8 +9,6 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import static carpet.script.CarpetEventServer.Event.PLAYER_CONNECTS; - @Mixin(PlayerList.class) public class PlayerList_coreMixin { @@ -19,6 +17,5 @@ public class PlayerList_coreMixin private void onPlayerConnected(Connection connection, ServerPlayer player, CallbackInfo ci) { CarpetServer.onPlayerLoggedIn(player); - PLAYER_CONNECTS.onPlayerEvent(player); } } diff --git a/src/main/java/carpet/mixins/PlayerList_scarpetEventsMixin.java b/src/main/java/carpet/mixins/PlayerList_scarpetEventsMixin.java index 5ca7afb479..99915f0585 100644 --- a/src/main/java/carpet/mixins/PlayerList_scarpetEventsMixin.java +++ b/src/main/java/carpet/mixins/PlayerList_scarpetEventsMixin.java @@ -1,10 +1,13 @@ package carpet.mixins; -import carpet.CarpetServer; import carpet.fakes.ServerPlayerInterface; +import carpet.script.external.Vanilla; +import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.players.PlayerList; +import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @@ -15,6 +18,8 @@ @Mixin(PlayerList.class) public class PlayerList_scarpetEventsMixin { + @Shadow @Final private MinecraftServer server; + @Inject(method = "respawn", at = @At("HEAD")) private void onRespawn(ServerPlayer player, boolean olive, CallbackInfoReturnable cir) { @@ -33,6 +38,6 @@ private void invalidatePreviousInstance(ServerPlayer player, boolean alive, Call @Inject(method = "reloadResources", at = @At("HEAD")) private void reloadCommands(CallbackInfo ci) { - CarpetServer.scriptServer.reAddCommands(); + Vanilla.MinecraftServer_getScriptServer(server).reAddCommands(); } } diff --git a/src/main/java/carpet/mixins/ServerChunkCacheMixin.java b/src/main/java/carpet/mixins/ServerChunkCacheMixin.java index 9bedf71433..2724b6508f 100644 --- a/src/main/java/carpet/mixins/ServerChunkCacheMixin.java +++ b/src/main/java/carpet/mixins/ServerChunkCacheMixin.java @@ -1,6 +1,5 @@ package carpet.mixins; -import carpet.fakes.ServerChunkManagerInterface; import carpet.utils.SpawnReporter; import org.apache.commons.lang3.tuple.Pair; import org.spongepowered.asm.mixin.Final; @@ -22,18 +21,12 @@ import net.minecraft.world.level.storage.LevelData; @Mixin(ServerChunkCache.class) -public abstract class ServerChunkCacheMixin implements ServerChunkManagerInterface +public abstract class ServerChunkCacheMixin { @Shadow @Final private ServerLevel level; @Shadow @Final private DistanceManager distanceManager; - @Override // shared between scarpet and spawnChunks setting - public DistanceManager getCMTicketManager() - { - return distanceManager; - } - @Redirect(method = "tickChunks", at = @At( value = "INVOKE", target = "Lnet/minecraft/server/level/DistanceManager;getNaturalSpawnChunkCount()I" diff --git a/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_coreMixin.java b/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_coreMixin.java index b7278c60ef..d9a8efcf2d 100644 --- a/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_coreMixin.java +++ b/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_coreMixin.java @@ -13,8 +13,6 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import static carpet.script.CarpetEventServer.Event.PLAYER_DISCONNECTS; - @Mixin(ServerGamePacketListenerImpl.class) public class ServerGamePacketListenerImpl_coreMixin implements ServerGamePacketListenerImplInterface { @Shadow @@ -24,8 +22,7 @@ public class ServerGamePacketListenerImpl_coreMixin implements ServerGamePacketL @Inject(method = "onDisconnect", at = @At("HEAD")) private void onPlayerDisconnect(Component reason, CallbackInfo ci) { - CarpetServer.onPlayerLoggedOut(this.player); - if (PLAYER_DISCONNECTS.isNeeded()) PLAYER_DISCONNECTS.onPlayerMessage(player, reason.getContents().toString()); + CarpetServer.onPlayerLoggedOut(this.player, reason); } @Override diff --git a/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_scarpetEventsMixin.java b/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_scarpetEventsMixin.java index b70a1f8c1c..26749b59f7 100644 --- a/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_scarpetEventsMixin.java +++ b/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_scarpetEventsMixin.java @@ -237,25 +237,6 @@ private void onElytraEngage(ServerboundPlayerCommandPacket clientCommandC2SPacke PLAYER_DEPLOYS_ELYTRA.onPlayerEvent(player); } - /*@Inject(method = "onPlayerInteractEntity", at = @At( - value = "INVOKE", - target = "Lnet/minecraft/server/network/ServerPlayerEntity;interact(Lnet/minecraft/entity/Entity;Lnet/minecraft/util/Hand;)Lnet/minecraft/util/ActionResult;" - )) - private void onEntityInteract(PlayerInteractEntityC2SPacket playerInteractEntityC2SPacket_1, CallbackInfo ci) - { - PLAYER_INTERACTS_WITH_ENTITY.onEntityHandAction(player, playerInteractEntityC2SPacket_1.getEntity(player.getWorld()), playerInteractEntityC2SPacket_1.getHand()); - }*/ - - /*@Inject(method = "onPlayerInteractEntity", at = @At( - value = "INVOKE", - target = "Lnet/minecraft/server/network/ServerPlayerEntity;attack(Lnet/minecraft/entity/Entity;)V" - )) - private void onEntityAttack(PlayerInteractEntityC2SPacket playerInteractEntityC2SPacket_1, CallbackInfo ci) - { - //todo add hit and hand in the future - PLAYER_ATTACKS_ENTITY.onEntityHandAction(player, playerInteractEntityC2SPacket_1.getEntity(player.getWorld()), null); - }*/ - @Inject(method = "handleContainerButtonClick", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/level/ServerPlayer;resetLastActionTime()V")) private void onItemBeingPickedFromInventory(ServerboundContainerButtonClickPacket packet, CallbackInfo ci) { diff --git a/src/main/java/carpet/script/CarpetScriptHost.java b/src/main/java/carpet/script/CarpetScriptHost.java index 1353971af9..eba433779f 100644 --- a/src/main/java/carpet/script/CarpetScriptHost.java +++ b/src/main/java/carpet/script/CarpetScriptHost.java @@ -30,12 +30,6 @@ import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; -import net.fabricmc.loader.api.FabricLoader; -import net.fabricmc.loader.api.ModContainer; -import net.fabricmc.loader.api.SemanticVersion; -import net.fabricmc.loader.api.Version; -import net.fabricmc.loader.api.VersionParsingException; -import net.fabricmc.loader.api.metadata.version.VersionPredicate; import net.minecraft.commands.CommandSourceStack; import net.minecraft.core.BlockPos; import net.minecraft.nbt.Tag; @@ -474,31 +468,13 @@ public void checkModVersionRequirements(Value reqs) { throw new InternalExpressionException("`requires` field must be a map of mod dependencies or a function to be executed"); } + Map requirements = map.getMap(); for (Entry requirement : requirements.entrySet()) { String requiredModId = requirement.getKey().getString(); String stringPredicate = requirement.getValue().getString(); - VersionPredicate predicate; - try - { - predicate = VersionPredicate.parse(stringPredicate); - } - catch (VersionParsingException e) - { - throw new InternalExpressionException("Failed to parse version conditions for '" + requiredModId + "' in 'requires': " + e.getMessage()); - } - - ModContainer mod = FabricLoader.getInstance().getModContainer(requiredModId).orElse(null); - if (mod != null) - { - Version presentVersion = mod.getMetadata().getVersion(); - if (predicate.test(presentVersion) || (FabricLoader.getInstance().isDevelopmentEnvironment() && !(presentVersion instanceof SemanticVersion))) - { // in a dev env, mod version is usually replaced with ${version}, and that isn't semantic - continue; - } - } - throw new LoadException(String.format("%s requires a version of mod '%s' matching '%s', which is missing!", getName(), requiredModId, stringPredicate)); + Carpet.assertRequirementMet(this, requiredModId, stringPredicate); } } diff --git a/src/main/java/carpet/script/CarpetScriptServer.java b/src/main/java/carpet/script/CarpetScriptServer.java index aa4f7a7488..5345ceaede 100644 --- a/src/main/java/carpet/script/CarpetScriptServer.java +++ b/src/main/java/carpet/script/CarpetScriptServer.java @@ -23,9 +23,8 @@ import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.tree.CommandNode; -import net.fabricmc.api.EnvType; -import net.fabricmc.loader.api.FabricLoader; import net.minecraft.commands.CommandSourceStack; +import net.minecraft.network.chat.Component; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.level.storage.LevelResource; @@ -51,6 +50,9 @@ import java.util.stream.Collectors; import java.util.stream.Stream; +import static carpet.script.CarpetEventServer.Event.PLAYER_CONNECTS; +import static carpet.script.CarpetEventServer.Event.PLAYER_DISCONNECTS; + public class CarpetScriptServer extends ScriptServer { //make static for now, but will change that later: @@ -156,24 +158,10 @@ public Module getModule(String name, boolean allowLibraries) } } - if (FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT) + Module globalModule = Carpet.fetchGlobalModule(name, allowLibraries); + if (globalModule != null) { - Path globalFolder = FabricLoader.getInstance().getConfigDir().resolve("carpet/scripts"); - if (!Files.exists(globalFolder)) - { - Files.createDirectories(globalFolder); - } - try (Stream folderWalker = Files.walk(globalFolder)) - { - Optional scriptPath = folderWalker - .filter(script -> script.getFileName().toString().equalsIgnoreCase(name + ".sc") || - (allowLibraries && script.getFileName().toString().equalsIgnoreCase(name + ".scl"))) - .findFirst(); - if (scriptPath.isPresent()) - { - return Module.fromPath(scriptPath.get()); - } - } + return globalModule; } } catch (IOException e) @@ -229,20 +217,8 @@ public List listAvailableModules(boolean includeBuiltIns) .forEach(f -> moduleNames.add(f.getFileName().toString().replaceFirst("\\.sc$", "").toLowerCase(Locale.ROOT))); } - if (includeBuiltIns && (FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT)) - { - Path globalScripts = FabricLoader.getInstance().getConfigDir().resolve("carpet/scripts"); - if (!Files.exists(globalScripts)) - { - Files.createDirectories(globalScripts); - } - try (Stream folderWalker = Files.walk(globalScripts, FileVisitOption.FOLLOW_LINKS)) - { - folderWalker - .filter(f -> f.toString().endsWith(".sc")) - .forEach(f -> moduleNames.add(f.getFileName().toString().replaceFirst("\\.sc$", "").toLowerCase(Locale.ROOT))); - } - } + Carpet.addGlobalModules(moduleNames, includeBuiltIns); + } catch (IOException e) { @@ -451,6 +427,7 @@ public void onClose() public void onPlayerJoin(ServerPlayer player) { + PLAYER_CONNECTS.onPlayerEvent(player); modules.values().forEach(h -> { if (h.isPerUser()) @@ -472,6 +449,14 @@ public Path resolveResource(String suffix) return server.getWorldPath(LevelResource.ROOT).resolve("scripts/" + suffix); } + public void onPlayerLoggedOut(ServerPlayer player, Component reason) + { + if (PLAYER_DISCONNECTS.isNeeded()) + { + PLAYER_DISCONNECTS.onPlayerMessage(player, reason.getContents().toString()); + } + } + private record TransferData(boolean perUser, Predicate commandValidator, boolean isRuleApp) { @@ -497,8 +482,11 @@ public void reAddCommands() })); } + private static boolean bootstrapDone = false; public static void parseFunctionClasses() { + if (bootstrapDone) return; + bootstrapDone = true; ExpressionException.prepareForDoom(); // see fc-#1172 // Language AnnotationParser.parseFunctionClass(Arithmetic.class); diff --git a/src/main/java/carpet/script/annotation/AnnotationParser.java b/src/main/java/carpet/script/annotation/AnnotationParser.java index 1e98ed67c2..2d64a0c0b3 100644 --- a/src/main/java/carpet/script/annotation/AnnotationParser.java +++ b/src/main/java/carpet/script/annotation/AnnotationParser.java @@ -28,7 +28,6 @@ import carpet.script.exception.InternalExpressionException; import carpet.script.LazyValue; import carpet.script.value.Value; -import net.fabricmc.api.ModInitializer; /** *

This class parses methods annotated with the {@link ScarpetFunction} annotation in a given {@link Class}, generating @@ -85,7 +84,7 @@ public final class AnnotationParser * to be used in the Scarpet language.

* *

Only call this method once per class per lifetime of the JVM! (for example, at {@link carpet.CarpetExtension#onGameStarted()} or - * {@link ModInitializer#onInitialize()}).

+ * {@link net.fabricmc.api.ModInitializer#onInitialize()}).

* *

There is a set of requirements for the class and its methods:

*
    diff --git a/src/main/java/carpet/script/annotation/Param.java b/src/main/java/carpet/script/annotation/Param.java index 28185963f1..665d6029d9 100644 --- a/src/main/java/carpet/script/annotation/Param.java +++ b/src/main/java/carpet/script/annotation/Param.java @@ -12,7 +12,6 @@ import java.util.Optional; import java.util.function.BiFunction; -import carpet.CarpetServer; import carpet.script.Context; import carpet.script.value.BooleanValue; import carpet.script.value.EntityValue; @@ -213,7 +212,7 @@ record StrictConverterInfo(Class type, boolean shallow) {} registerStrictConverter(Component.class, false, new SimpleTypeConverter<>(FormattedTextValue.class, FormattedTextValue::getText, "text")); registerStrictConverter(Component.class, true, new SimpleTypeConverter<>(StringValue.class, FormattedTextValue::getTextByValue, "text")); registerStrictConverter(ServerPlayer.class, false, new SimpleTypeConverter<>(EntityValue.class, - v -> EntityValue.getPlayerByValue(CarpetServer.minecraft_server, v), "online player entity")); + v -> EntityValue.getPlayerByValue(v.getEntity().getServer(), v), "online player entity")); registerStrictConverter(Boolean.class, false, new SimpleTypeConverter<>(BooleanValue.class, BooleanValue::getBoolean, "boolean")); registerStrictConverter(Boolean.class, true, new SimpleTypeConverter<>(NumericValue.class, NumericValue::getBoolean, "boolean")); } diff --git a/src/main/java/carpet/script/api/WorldAccess.java b/src/main/java/carpet/script/api/WorldAccess.java index cc9f43ca19..6139c2ae5a 100644 --- a/src/main/java/carpet/script/api/WorldAccess.java +++ b/src/main/java/carpet/script/api/WorldAccess.java @@ -7,8 +7,8 @@ import carpet.script.Fluff; import carpet.script.external.Carpet; import carpet.script.external.Vanilla; +import carpet.script.utils.Colors; import carpet.script.utils.FeatureGenerator; -import carpet.mixins.PoiRecord_scarpetMixin; import carpet.script.argument.BlockArgument; import carpet.script.argument.Vector3Argument; import carpet.script.exception.InternalExpressionException; @@ -311,7 +311,7 @@ public static void apply(Expression expression) ).filter(p -> p.getPos().equals(pos)).findFirst().orElse(null); return poi == null ? Value.NULL : ListValue.of( ValueConversions.of(poiReg.getKey(poi.getPoiType().value())), - new NumericValue(poiType.maxTickets() - ((PoiRecord_scarpetMixin) poi).getFreeTickets()) + new NumericValue(poiType.maxTickets() - Vanilla.PoiRecord_getFreeTickets(poi)) ); } int radius = NumericValue.asNumber(lv.get(locator.offset)).getInt(); @@ -360,7 +360,7 @@ else if (!("any".equals(statusString))) return ListValue.wrap(pois.sorted(Comparator.comparingDouble(p -> p.getPos().distSqr(pos))).map(p -> ListValue.of( ValueConversions.of(poiReg.getKey(p.getPoiType().value())), - new NumericValue(p.getPoiType().value().maxTickets() - ((PoiRecord_scarpetMixin) p).getFreeTickets()), + new NumericValue(p.getPoiType().value().maxTickets() - Vanilla.PoiRecord_getFreeTickets(p)), ValueConversions.of(p.getPos()) ) )); @@ -421,7 +421,7 @@ else if (!("any".equals(statusString))) ).filter(p -> p.getPos().equals(pos)).findFirst().ifPresent(p -> { for (int i = 0; i < finalO; i++) { - ((PoiRecord_scarpetMixin) p).callAcquireTicket(); + Vanilla.PoiRecord_callAcquireTicket(p); } }); } @@ -638,7 +638,7 @@ else if (!("any".equals(statusString))) expression.addContextFunction("chunk_tickets", -1, (c, t, lv) -> { ServerLevel world = ((CarpetContext) c).level(); - DistanceManager foo = Vanilla.ServerChunkCache_getCMTicketManager(world.getChunkSource()); + DistanceManager foo = world.getChunkSource().chunkMap.getDistanceManager(); Long2ObjectOpenHashMap>> levelTickets = Vanilla.ChunkTicketManager_getTicketsByPosition(foo); List res = new ArrayList<>(); @@ -1158,15 +1158,15 @@ LivingEntity getIndirectSourceEntity() expression.addContextFunction("block_sound", -1, (c, t, lv) -> stateStringQuery(c, "block_sound", lv, (s, p) -> - Carpet.getSoundTypeNames().get(s.getSoundType()))); + Colors.soundName.get(s.getSoundType()))); expression.addContextFunction("material", -1, (c, t, lv) -> stateStringQuery(c, "material", lv, (s, p) -> - Carpet.getMaterialNames().get(s.getMaterial()))); + Colors.materialName.get(s.getMaterial()))); expression.addContextFunction("map_colour", -1, (c, t, lv) -> stateStringQuery(c, "map_colour", lv, (s, p) -> - Carpet.getMapColorNames().get(s.getMapColor(((CarpetContext) c).level(), p)))); + Colors.materialName.get(s.getMapColor(((CarpetContext) c).level(), p)))); // Deprecated for block_state() diff --git a/src/main/java/carpet/script/external/Carpet.java b/src/main/java/carpet/script/external/Carpet.java index eafd1cd036..cc692d194b 100644 --- a/src/main/java/carpet/script/external/Carpet.java +++ b/src/main/java/carpet/script/external/Carpet.java @@ -12,27 +12,41 @@ import carpet.network.ServerNetworkHandler; import carpet.patches.EntityPlayerMPFake; import carpet.script.CarpetExpression; +import carpet.script.CarpetScriptHost; import carpet.script.CarpetScriptServer; +import carpet.script.Module; +import carpet.script.exception.InternalExpressionException; +import carpet.script.exception.LoadException; import carpet.script.utils.AppStoreManager; import carpet.script.value.MapValue; import carpet.script.value.StringValue; -import carpet.utils.BlockInfo; import carpet.utils.CarpetProfiler; import carpet.utils.Messenger; +import net.fabricmc.api.EnvType; +import net.fabricmc.loader.api.FabricLoader; +import net.fabricmc.loader.api.ModContainer; +import net.fabricmc.loader.api.SemanticVersion; +import net.fabricmc.loader.api.Version; +import net.fabricmc.loader.api.VersionParsingException; +import net.fabricmc.loader.api.metadata.version.VersionPredicate; import net.minecraft.commands.CommandSourceStack; import net.minecraft.network.chat.Component; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.player.Player; -import net.minecraft.world.level.block.SoundType; -import net.minecraft.world.level.material.Material; -import net.minecraft.world.level.material.MaterialColor; import javax.annotation.Nullable; +import java.io.IOException; +import java.nio.file.FileVisitOption; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.Collection; import java.util.Collections; import java.util.List; +import java.util.Locale; import java.util.Map; +import java.util.Optional; +import java.util.stream.Stream; public class Carpet { @@ -66,21 +80,6 @@ public static ThreadLocal getImpendingFillSkipUpdates() return CarpetSettings.impendingFillSkipUpdates; } - public static Map getSoundTypeNames() - { - return BlockInfo.soundName; - } - - public static Map getMapColorNames() - { - return BlockInfo.mapColourName; - } - - public static Map getMaterialNames() - { - return BlockInfo.materialName; - } - public static Runnable startProfilerSection(String name) { CarpetProfiler.ProfilerToken token = CarpetProfiler.start_section(null, name, CarpetProfiler.TYPE.GENERAL); @@ -148,6 +147,73 @@ public static boolean getFillUpdates() return CarpetSettings.fillUpdates; } + @Nullable + public static Module fetchGlobalModule(String name, boolean allowLibraries) throws IOException + { + if (FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT) + { + Path globalFolder = FabricLoader.getInstance().getConfigDir().resolve("carpet/scripts"); + if (!Files.exists(globalFolder)) + { + Files.createDirectories(globalFolder); + } + try (Stream folderWalker = Files.walk(globalFolder)) + { + Optional scriptPath = folderWalker + .filter(script -> script.getFileName().toString().equalsIgnoreCase(name + ".sc") || + (allowLibraries && script.getFileName().toString().equalsIgnoreCase(name + ".scl"))) + .findFirst(); + if (scriptPath.isPresent()) + { + return Module.fromPath(scriptPath.get()); + } + } + } + return null; + } + + public static void addGlobalModules(final List moduleNames, boolean includeBuiltIns) throws IOException + { + if (includeBuiltIns && (FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT)) + { + Path globalScripts = FabricLoader.getInstance().getConfigDir().resolve("carpet/scripts"); + if (!Files.exists(globalScripts)) + { + Files.createDirectories(globalScripts); + } + try (Stream folderWalker = Files.walk(globalScripts, FileVisitOption.FOLLOW_LINKS)) + { + folderWalker + .filter(f -> f.toString().endsWith(".sc")) + .forEach(f -> moduleNames.add(f.getFileName().toString().replaceFirst("\\.sc$", "").toLowerCase(Locale.ROOT))); + } + } + } + + public static void assertRequirementMet(CarpetScriptHost host, String requiredModId, String stringPredicate) + { + VersionPredicate predicate; + try + { + predicate = VersionPredicate.parse(stringPredicate); + } + catch (VersionParsingException e) + { + throw new InternalExpressionException("Failed to parse version conditions for '" + requiredModId + "' in 'requires': " + e.getMessage()); + } + + ModContainer mod = FabricLoader.getInstance().getModContainer(requiredModId).orElse(null); + if (mod != null) + { + Version presentVersion = mod.getMetadata().getVersion(); + if (predicate.test(presentVersion) || (FabricLoader.getInstance().isDevelopmentEnvironment() && !(presentVersion instanceof SemanticVersion))) + { // in a dev env, mod version is usually replaced with ${version}, and that isn't semantic + return; + } + } + throw new LoadException(String.format("%s requires a version of mod '%s' matching '%s', which is missing!", host.getName(), requiredModId, stringPredicate)); + } + public static class ScarpetAppStoreValidator extends Validator { @Override diff --git a/src/main/java/carpet/script/external/Vanilla.java b/src/main/java/carpet/script/external/Vanilla.java index 79f2e00995..67470b4d62 100644 --- a/src/main/java/carpet/script/external/Vanilla.java +++ b/src/main/java/carpet/script/external/Vanilla.java @@ -16,13 +16,13 @@ import carpet.fakes.RandomStateVisitorAccessor; import carpet.fakes.RecipeManagerInterface; import carpet.fakes.AbstractContainerMenuInterface; -import carpet.fakes.ServerChunkManagerInterface; import carpet.fakes.ServerPlayerInterface; import carpet.fakes.ServerPlayerInteractionManagerInterface; import carpet.fakes.ServerWorldInterface; import carpet.fakes.SpawnHelperInnerInterface; import carpet.fakes.ThreadedAnvilChunkStorageInterface; import carpet.mixins.Objective_scarpetMixin; +import carpet.mixins.PoiRecord_scarpetMixin; import carpet.mixins.Scoreboard_scarpetMixin; import carpet.network.ServerNetworkHandler; import carpet.script.CarpetScriptServer; @@ -46,7 +46,6 @@ import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ChunkMap; import net.minecraft.server.level.DistanceManager; -import net.minecraft.server.level.ServerChunkCache; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.level.ServerPlayerGameMode; @@ -59,6 +58,7 @@ import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.ai.goal.Goal; import net.minecraft.world.entity.ai.goal.GoalSelector; +import net.minecraft.world.entity.ai.village.poi.PoiRecord; import net.minecraft.world.entity.animal.horse.AbstractHorse; import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.inventory.AbstractContainerMenu; @@ -143,11 +143,6 @@ public static ServerLevelData ServerLevel_getWorldProperties(ServerLevel world) return ((ServerWorldInterface) world).getWorldPropertiesCM(); } - public static DistanceManager ServerChunkCache_getCMTicketManager(ServerChunkCache chunkCache) - { - return ((ServerChunkManagerInterface) chunkCache).getCMTicketManager(); - } - public static Long2ObjectOpenHashMap>> ChunkTicketManager_getTicketsByPosition(DistanceManager ticketManager) { return ((ChunkTicketManagerInterface) ticketManager).getTicketsByPosition(); @@ -353,6 +348,16 @@ public static int MinecraftServer_getFillLimit(MinecraftServer server) return Math.max(server.getGameRules().getInt(GameRules.RULE_COMMAND_MODIFICATION_BLOCK_LIMIT), CarpetSettings.fillLimit); } + public static int PoiRecord_getFreeTickets(PoiRecord record) + { + return ((PoiRecord_scarpetMixin) record).getFreeTickets(); + } + + public static void PoiRecord_callAcquireTicket(PoiRecord record) + { + ((PoiRecord_scarpetMixin) record).callAcquireTicket(); + } + public record BlockPredicatePayload(BlockState state, TagKey tagKey, Map properties, CompoundTag tag) { public static BlockPredicatePayload of(Predicate blockPredicate) { diff --git a/src/main/java/carpet/script/utils/AppStoreManager.java b/src/main/java/carpet/script/utils/AppStoreManager.java index 9a5f387884..e5ab6aecab 100644 --- a/src/main/java/carpet/script/utils/AppStoreManager.java +++ b/src/main/java/carpet/script/utils/AppStoreManager.java @@ -12,7 +12,6 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; -import net.fabricmc.loader.api.FabricLoader; import net.minecraft.commands.CommandRuntimeException; import net.minecraft.commands.CommandSourceStack; import net.minecraft.world.level.storage.LevelResource; @@ -262,7 +261,7 @@ private static int downloadScript(CommandSourceStack source, String path, AppInf { throw new CommandRuntimeException(Carpet.Messenger_compose("rb Failed to obtain app file content: " + e.getMessage())); } - if (!saveScriptToFile(source, path, nodeInfo.name(), code, false, useTrash)) + if (!saveScriptToFile(source, path, nodeInfo.name(), code, useTrash)) { return 0; } @@ -302,17 +301,9 @@ public static AppInfo getFileNodeFrom(StoreNode start, String appPath) } - public static boolean saveScriptToFile(CommandSourceStack source, String path, String appFileName, String code, boolean globalSavePath, boolean useTrash) + public static boolean saveScriptToFile(CommandSourceStack source, String path, String appFileName, String code, boolean useTrash) { - Path scriptLocation; - 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().getWorldPath(LevelResource.ROOT).resolve("scripts").toAbsolutePath().resolve(appFileName); - } + Path scriptLocation = source.getServer().getWorldPath(LevelResource.ROOT).resolve("scripts").toAbsolutePath().resolve(appFileName); try { Files.createDirectories(scriptLocation.getParent()); diff --git a/src/main/java/carpet/script/utils/Colors.java b/src/main/java/carpet/script/utils/Colors.java new file mode 100644 index 0000000000..a746a7d7bc --- /dev/null +++ b/src/main/java/carpet/script/utils/Colors.java @@ -0,0 +1,207 @@ +package carpet.script.utils; + +import net.minecraft.world.level.block.SoundType; +import net.minecraft.world.level.material.Material; +import net.minecraft.world.level.material.MaterialColor; + +import java.util.Map; + +import static java.util.Map.entry; + +public class Colors +{ + public static final Map soundName = Map.ofEntries( + entry(SoundType.WOOD, "wood" ), + entry(SoundType.GRAVEL, "gravel"), + entry(SoundType.GRASS, "grass" ), + entry(SoundType.LILY_PAD, "lily_pad"), + entry(SoundType.STONE, "stone" ), + entry(SoundType.METAL, "metal" ), + entry(SoundType.GLASS , "glass" ), + entry(SoundType.WOOL , "wool" ), + entry(SoundType.SAND , "sand" ), + entry(SoundType.SNOW , "snow" ), + entry(SoundType.POWDER_SNOW , "powder_snow" ), + entry(SoundType.LADDER, "ladder"), + entry(SoundType.ANVIL , "anvil" ), + entry(SoundType.SLIME_BLOCK , "slime" ), + entry(SoundType.HONEY_BLOCK , "honey" ), + entry(SoundType.WET_GRASS , "sea_grass" ), + entry(SoundType.CORAL_BLOCK , "coral" ), + entry(SoundType.BAMBOO , "bamboo" ), + entry(SoundType.BAMBOO_SAPLING , "shoots" ), + entry(SoundType.SCAFFOLDING , "scaffolding" ), + entry(SoundType.SWEET_BERRY_BUSH , "berry" ), + entry(SoundType.CROP , "crop" ), + entry(SoundType.HARD_CROP , "stem" ), + entry(SoundType.VINE , "vine" ), + entry(SoundType.NETHER_WART , "wart" ), + entry(SoundType.LANTERN , "lantern" ), + entry(SoundType.STEM, "fungi_stem"), + entry(SoundType.NYLIUM, "nylium"), + entry(SoundType.FUNGUS, "fungus"), + entry(SoundType.ROOTS, "roots"), + entry(SoundType.SHROOMLIGHT, "shroomlight"), + entry(SoundType.WEEPING_VINES, "weeping_vine"), + entry(SoundType.TWISTING_VINES, "twisting_vine"), + entry(SoundType.SOUL_SAND, "soul_sand"), + entry(SoundType.SOUL_SOIL, "soul_soil"), + entry(SoundType.BASALT, "basalt"), + entry(SoundType.WART_BLOCK, "wart"), + entry(SoundType.NETHERRACK, "netherrack"), + entry(SoundType.NETHER_BRICKS, "nether_bricks"), + entry(SoundType.NETHER_SPROUTS, "nether_sprouts"), + entry(SoundType.NETHER_ORE, "nether_ore"), + entry(SoundType.BONE_BLOCK, "bone"), + entry(SoundType.NETHERITE_BLOCK, "netherite"), + entry(SoundType.ANCIENT_DEBRIS, "ancient_debris"), + entry(SoundType.LODESTONE, "lodestone"), + entry(SoundType.CHAIN, "chain"), + entry(SoundType.NETHER_GOLD_ORE, "nether_gold_ore"), + entry(SoundType.GILDED_BLACKSTONE, "gilded_blackstone"), + entry(SoundType.CANDLE, "candle"), + entry(SoundType.AMETHYST, "amethyst"), + entry(SoundType.AMETHYST_CLUSTER, "amethyst_cluster"), + entry(SoundType.SMALL_AMETHYST_BUD, "small_amethyst_bud"), + entry(SoundType.MEDIUM_AMETHYST_BUD, "medium_amethyst_bud"), + entry(SoundType.LARGE_AMETHYST_BUD, "large_amethyst_bud"), + + entry(SoundType.TUFF, "tuff"), + entry(SoundType.CALCITE, "calcite"), + entry(SoundType.DRIPSTONE_BLOCK, "dripstone"), + entry(SoundType.POINTED_DRIPSTONE, "pointed_dripstone"), + entry(SoundType.COPPER, "copper"), + entry(SoundType.CAVE_VINES, "cave_vine"), + entry(SoundType.SPORE_BLOSSOM, "spore_blossom"), + entry(SoundType.AZALEA, "azalea"), + entry(SoundType.FLOWERING_AZALEA, "flowering_azalea"), + entry(SoundType.MOSS_CARPET, "moss_carpet"), + entry(SoundType.MOSS, "moss"), + entry(SoundType.BIG_DRIPLEAF, "big_dripleaf"), + entry(SoundType.SMALL_DRIPLEAF, "small_dripleaf"), + entry(SoundType.ROOTED_DIRT, "rooted_dirt"), + entry(SoundType.HANGING_ROOTS, "hanging_roots"), + entry(SoundType.AZALEA_LEAVES, "azalea_leaves"), + entry(SoundType.SCULK_SENSOR, "sculk_sensor"), + entry(SoundType.GLOW_LICHEN, "glow_lichen"), + entry(SoundType.DEEPSLATE, "deepslate"), + entry(SoundType.DEEPSLATE_BRICKS, "deepslate_bricks"), + entry(SoundType.DEEPSLATE_TILES, "deepslate_tiles"), + entry(SoundType.POLISHED_DEEPSLATE, "polished_deepslate") + ); + + public static final Map mapColourName = Map.ofEntries( + entry(MaterialColor.NONE , "air" ), + entry(MaterialColor.GRASS , "grass" ), + entry(MaterialColor.SAND , "sand" ), + entry(MaterialColor.WOOL , "wool" ), + entry(MaterialColor.FIRE , "tnt" ), + entry(MaterialColor.ICE , "ice" ), + entry(MaterialColor.METAL , "iron" ), + entry(MaterialColor.PLANT , "foliage" ), + entry(MaterialColor.SNOW , "snow" ), + entry(MaterialColor.CLAY , "clay" ), + entry(MaterialColor.DIRT , "dirt" ), + entry(MaterialColor.STONE , "stone" ), + entry(MaterialColor.WATER , "water" ), + entry(MaterialColor.WOOD , "wood" ), + entry(MaterialColor.QUARTZ , "quartz" ), + entry(MaterialColor.COLOR_ORANGE , "adobe" ), + entry(MaterialColor.COLOR_MAGENTA , "magenta" ), + entry(MaterialColor.COLOR_LIGHT_BLUE, "light_blue"), + entry(MaterialColor.COLOR_YELLOW , "yellow" ), + entry(MaterialColor.COLOR_LIGHT_GREEN , "lime" ), + entry(MaterialColor.COLOR_PINK , "pink" ), + entry(MaterialColor.COLOR_GRAY , "gray" ), + entry(MaterialColor.COLOR_LIGHT_GRAY, "light_gray"), + entry(MaterialColor.COLOR_CYAN , "cyan" ), + entry(MaterialColor.COLOR_PURPLE , "purple" ), + entry(MaterialColor.COLOR_BLUE , "blue" ), + entry(MaterialColor.COLOR_BROWN , "brown" ), + entry(MaterialColor.COLOR_GREEN , "green" ), + entry(MaterialColor.COLOR_RED , "red" ), + entry(MaterialColor.COLOR_BLACK , "black" ), + entry(MaterialColor.GOLD , "gold" ), + entry(MaterialColor.DIAMOND , "diamond" ), + entry(MaterialColor.LAPIS , "lapis" ), + entry(MaterialColor.EMERALD , "emerald" ), + entry(MaterialColor.PODZOL , "obsidian" ), + entry(MaterialColor.NETHER , "netherrack"), //TODO fix these + entry(MaterialColor.TERRACOTTA_WHITE , "white_terracotta" ), + entry(MaterialColor.TERRACOTTA_ORANGE , "orange_terracotta" ), + entry(MaterialColor.TERRACOTTA_MAGENTA , "magenta_terracotta" ), + entry(MaterialColor.TERRACOTTA_LIGHT_BLUE, "light_blue_terracotta" ), + entry(MaterialColor.TERRACOTTA_YELLOW , "yellow_terracotta" ), + entry(MaterialColor.TERRACOTTA_LIGHT_GREEN , "lime_terracotta" ), + entry(MaterialColor.TERRACOTTA_PINK , "pink_terracotta" ), + entry(MaterialColor.TERRACOTTA_GRAY , "gray_terracotta" ), + entry(MaterialColor.TERRACOTTA_LIGHT_GRAY, "light_gray_terracotta" ), + entry(MaterialColor.TERRACOTTA_CYAN , "cyan_terracotta" ), + entry(MaterialColor.TERRACOTTA_PURPLE , "purple_terracotta" ), + entry(MaterialColor.TERRACOTTA_BLUE , "blue_terracotta" ), + entry(MaterialColor.TERRACOTTA_BROWN , "brown_terracotta" ), + entry(MaterialColor.TERRACOTTA_GREEN , "green_terracotta" ), + entry(MaterialColor.TERRACOTTA_RED , "red_terracotta" ), + entry(MaterialColor.TERRACOTTA_BLACK , "black_terracotta" ), + entry(MaterialColor.CRIMSON_NYLIUM , "crimson_nylium" ), + entry(MaterialColor.CRIMSON_STEM , "crimson_stem" ), + entry(MaterialColor.CRIMSON_HYPHAE , "crimson_hyphae" ), + entry(MaterialColor.WARPED_NYLIUM , "warped_nylium" ), + entry(MaterialColor.WARPED_STEM , "warped_stem" ), + entry(MaterialColor.WARPED_HYPHAE , "warped_hyphae" ), + entry(MaterialColor.WARPED_WART_BLOCK , "warped_wart" ), + entry(MaterialColor.DEEPSLATE , "deepslate" ), + entry(MaterialColor.RAW_IRON , "raw_iron" ), + entry(MaterialColor.GLOW_LICHEN , "glow_lichen" ) + ); + + public static final Map materialName = Map.ofEntries( + entry(Material.AIR , "air" ), + entry(Material.STRUCTURAL_AIR , "void" ), + entry(Material.PORTAL , "portal" ), + entry(Material.CLOTH_DECORATION , "carpet" ), + entry(Material.PLANT , "plant" ), + entry(Material.WATER_PLANT, "water_plant" ), + entry(Material.REPLACEABLE_PLANT, "vegetation" ), + entry(Material.REPLACEABLE_FIREPROOF_PLANT, "nether_shoots" ), + entry(Material.REPLACEABLE_WATER_PLANT, "sea_grass" ), + entry(Material.WATER , "water" ), + entry(Material.BUBBLE_COLUMN , "bubble_column"), + entry(Material.LAVA , "lava" ), + entry(Material.TOP_SNOW , "snow_layer" ), + entry(Material.FIRE , "fire" ), + entry(Material.DECORATION , "decoration" ), + entry(Material.WEB , "cobweb" ), + entry(Material.SCULK , "sculk" ), + entry(Material.BUILDABLE_GLASS , "redstone_lamp"), + entry(Material.CLAY, "clay" ), + entry(Material.DIRT , "dirt" ), + entry(Material.GRASS , "grass" ), + entry(Material.ICE_SOLID , "packed_ice" ), + entry(Material.SAND , "sand" ), + entry(Material.SPONGE , "sponge" ), + entry(Material.SHULKER_SHELL , "shulker" ), + entry(Material.WOOD , "wood" ), + entry(Material.NETHER_WOOD , "nether_wood" ), + entry(Material.BAMBOO_SAPLING , "shoots" ), + entry(Material.BAMBOO , "bamboo" ), + entry(Material.WOOL , "wool" ), + entry(Material.EXPLOSIVE , "tnt" ), + entry(Material.LEAVES , "leaves" ), + entry(Material.GLASS , "glass" ), + entry(Material.ICE , "ice" ), + entry(Material.CACTUS , "cactus" ), + entry(Material.STONE , "stone" ), + entry(Material.METAL , "metal" ), + entry(Material.SNOW , "snow" ), + entry(Material.HEAVY_METAL , "anvil" ), + entry(Material.BARRIER , "barrier" ), + entry(Material.PISTON , "piston" ), + entry(Material.MOSS , "moss" ), + entry(Material.VEGETABLE , "gourd" ), + entry(Material.EGG , "dragon_egg" ), + entry(Material.CAKE , "cake" ), + entry(Material.AMETHYST , "amethyst" ), + entry(Material.POWDER_SNOW , "powder_snow") + ); +} diff --git a/src/main/java/carpet/script/utils/ShapesRenderer.java b/src/main/java/carpet/script/utils/ShapesRenderer.java index 45c1100ee7..a83851a711 100644 --- a/src/main/java/carpet/script/utils/ShapesRenderer.java +++ b/src/main/java/carpet/script/utils/ShapesRenderer.java @@ -73,6 +73,35 @@ public class ShapesRenderer put("item", (c, s) -> new RenderedSprite(c, s, true)); }}; + public static void rotatePoseStackByShapeDirection(PoseStack poseStack, ShapeDirection shapeDirection, Camera camera, Vec3 objectPos) + { + switch (shapeDirection) + { + case NORTH -> {} + case SOUTH -> poseStack.mulPose(Axis.YP.rotationDegrees(180)); + case EAST -> poseStack.mulPose(Axis.YP.rotationDegrees(270)); + case WEST -> poseStack.mulPose(Axis.YP.rotationDegrees(90)); + case UP -> poseStack.mulPose(Axis.XP.rotationDegrees(90)); + case DOWN -> poseStack.mulPose(Axis.XP.rotationDegrees(-90)); + case CAMERA -> poseStack.mulPose(camera.rotation()); + case PLAYER -> { + Vec3 vector = objectPos.subtract(camera.getPosition()); + double x = vector.x; + double y = vector.y; + double z = vector.z; + double d = Math.sqrt(x * x + z * z); + float rotX = (float) (Math.atan2(x, z)); + float rotY = (float) (Math.atan2(y, d)); + + // that should work somehow but it doesn't for some reason + //matrices.mulPose(new Quaternion( -rotY, rotX, 0, false)); + + poseStack.mulPose(Axis.YP.rotation(rotX)); + poseStack.mulPose(Axis.XP.rotation(-rotY)); + } + } + } + public ShapesRenderer(Minecraft minecraftClient) { this.client = minecraftClient; @@ -322,7 +351,7 @@ public void renderLines(PoseStack matrices, Tesselator tessellator, BufferBuilde } matrices.translate(v1.x - cx, v1.y - cy, v1.z - cz); - ShapeDirection.rotatePoseStackByShapeDirection(matrices, shape.facing, camera1, isitem ? v1 : v1.add(0.5, 0.5, 0.5)); + rotatePoseStackByShapeDirection(matrices, shape.facing, camera1, isitem ? v1 : v1.add(0.5, 0.5, 0.5)); if (shape.tilt != 0.0f) { matrices.mulPose(Axis.ZP.rotationDegrees(-shape.tilt)); @@ -508,7 +537,7 @@ public void renderLines(PoseStack matrices, Tesselator tessellator, BufferBuilde matrices.pushPose(); matrices.translate(v1.x - cx, v1.y - cy, v1.z - cz); - ShapeDirection.rotatePoseStackByShapeDirection(matrices, shape.facing, camera1, v1); + rotatePoseStackByShapeDirection(matrices, shape.facing, camera1, v1); matrices.scale(shape.size * 0.0025f, -shape.size * 0.0025f, shape.size * 0.0025f); //RenderSystem.scalef(shape.size* 0.0025f, -shape.size*0.0025f, shape.size*0.0025f); diff --git a/src/main/java/carpet/script/utils/shapes/ShapeDirection.java b/src/main/java/carpet/script/utils/shapes/ShapeDirection.java index 54774263cf..29bc08a6d1 100644 --- a/src/main/java/carpet/script/utils/shapes/ShapeDirection.java +++ b/src/main/java/carpet/script/utils/shapes/ShapeDirection.java @@ -1,10 +1,5 @@ package carpet.script.utils.shapes; -import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.math.Axis; -import net.minecraft.client.Camera; -import net.minecraft.world.phys.Vec3; - import javax.annotation.Nullable; import java.util.Locale; @@ -35,33 +30,4 @@ public static ShapeDirection fromString(String direction) default -> null; }; } - - public static void rotatePoseStackByShapeDirection(PoseStack poseStack, ShapeDirection shapeDirection, Camera camera, Vec3 objectPos) - { - switch (shapeDirection) - { - case NORTH -> {} - case SOUTH -> poseStack.mulPose(Axis.YP.rotationDegrees(180)); - case EAST -> poseStack.mulPose(Axis.YP.rotationDegrees(270)); - case WEST -> poseStack.mulPose(Axis.YP.rotationDegrees(90)); - case UP -> poseStack.mulPose(Axis.XP.rotationDegrees(90)); - case DOWN -> poseStack.mulPose(Axis.XP.rotationDegrees(-90)); - case CAMERA -> poseStack.mulPose(camera.rotation()); - case PLAYER -> { - Vec3 vector = objectPos.subtract(camera.getPosition()); - double x = vector.x; - double y = vector.y; - double z = vector.z; - double d = Math.sqrt(x * x + z * z); - float rotX = (float) (Math.atan2(x, z)); - float rotY = (float) (Math.atan2(y, d)); - - // that should work somehow but it doesn't for some reason - //matrices.mulPose(new Quaternion( -rotY, rotX, 0, false)); - - poseStack.mulPose(Axis.YP.rotation(rotX)); - poseStack.mulPose(Axis.XP.rotation(-rotY)); - } - } - } } diff --git a/src/main/java/carpet/script/value/ValueConversions.java b/src/main/java/carpet/script/value/ValueConversions.java index 646ec1af74..d93bcb160b 100644 --- a/src/main/java/carpet/script/value/ValueConversions.java +++ b/src/main/java/carpet/script/value/ValueConversions.java @@ -5,6 +5,7 @@ import carpet.script.exception.Throwables; import carpet.script.external.Carpet; import carpet.script.external.Vanilla; +import carpet.script.utils.Colors; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import net.minecraft.advancements.critereon.MinMaxBounds; @@ -85,7 +86,7 @@ public static Value of(ServerLevel world) public static Value of(MaterialColor color) { - return ListValue.of(StringValue.of(Carpet.getMapColorNames().get(color)), ofRGB(color.col)); + return ListValue.of(StringValue.of(Colors.mapColourName.get(color)), ofRGB(color.col)); } public static Value of(MinMaxBounds range) diff --git a/src/main/java/carpet/utils/BlockInfo.java b/src/main/java/carpet/utils/BlockInfo.java index e1c01773c4..c000acdc73 100644 --- a/src/main/java/carpet/utils/BlockInfo.java +++ b/src/main/java/carpet/utils/BlockInfo.java @@ -2,10 +2,10 @@ import java.util.ArrayList; import java.util.List; -import java.util.Map; + +import carpet.script.utils.Colors; import net.minecraft.core.BlockPos; import net.minecraft.core.Registry; -import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.Registries; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerLevel; @@ -17,212 +17,13 @@ import net.minecraft.world.entity.monster.ZombifiedPiglin; import net.minecraft.world.level.LightLayer; import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.SoundType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.Material; -import net.minecraft.world.level.material.MaterialColor; import net.minecraft.world.level.pathfinder.PathComputationType; import net.minecraft.world.phys.Vec3; -import static java.util.Map.entry; - public class BlockInfo { - public static final Map soundName = Map.ofEntries( - entry(SoundType.WOOD, "wood" ), - entry(SoundType.GRAVEL, "gravel"), - entry(SoundType.GRASS, "grass" ), - entry(SoundType.LILY_PAD, "lily_pad"), - entry(SoundType.STONE, "stone" ), - entry(SoundType.METAL, "metal" ), - entry(SoundType.GLASS , "glass" ), - entry(SoundType.WOOL , "wool" ), - entry(SoundType.SAND , "sand" ), - entry(SoundType.SNOW , "snow" ), - entry(SoundType.POWDER_SNOW , "powder_snow" ), - entry(SoundType.LADDER, "ladder"), - entry(SoundType.ANVIL , "anvil" ), - entry(SoundType.SLIME_BLOCK , "slime" ), - entry(SoundType.HONEY_BLOCK , "honey" ), - entry(SoundType.WET_GRASS , "sea_grass" ), - entry(SoundType.CORAL_BLOCK , "coral" ), - entry(SoundType.BAMBOO , "bamboo" ), - entry(SoundType.BAMBOO_SAPLING , "shoots" ), - entry(SoundType.SCAFFOLDING , "scaffolding" ), - entry(SoundType.SWEET_BERRY_BUSH , "berry" ), - entry(SoundType.CROP , "crop" ), - entry(SoundType.HARD_CROP , "stem" ), - entry(SoundType.VINE , "vine" ), - entry(SoundType.NETHER_WART , "wart" ), - entry(SoundType.LANTERN , "lantern" ), - entry(SoundType.STEM, "fungi_stem"), - entry(SoundType.NYLIUM, "nylium"), - entry(SoundType.FUNGUS, "fungus"), - entry(SoundType.ROOTS, "roots"), - entry(SoundType.SHROOMLIGHT, "shroomlight"), - entry(SoundType.WEEPING_VINES, "weeping_vine"), - entry(SoundType.TWISTING_VINES, "twisting_vine"), - entry(SoundType.SOUL_SAND, "soul_sand"), - entry(SoundType.SOUL_SOIL, "soul_soil"), - entry(SoundType.BASALT, "basalt"), - entry(SoundType.WART_BLOCK, "wart"), - entry(SoundType.NETHERRACK, "netherrack"), - entry(SoundType.NETHER_BRICKS, "nether_bricks"), - entry(SoundType.NETHER_SPROUTS, "nether_sprouts"), - entry(SoundType.NETHER_ORE, "nether_ore"), - entry(SoundType.BONE_BLOCK, "bone"), - entry(SoundType.NETHERITE_BLOCK, "netherite"), - entry(SoundType.ANCIENT_DEBRIS, "ancient_debris"), - entry(SoundType.LODESTONE, "lodestone"), - entry(SoundType.CHAIN, "chain"), - entry(SoundType.NETHER_GOLD_ORE, "nether_gold_ore"), - entry(SoundType.GILDED_BLACKSTONE, "gilded_blackstone"), - entry(SoundType.CANDLE, "candle"), - entry(SoundType.AMETHYST, "amethyst"), - entry(SoundType.AMETHYST_CLUSTER, "amethyst_cluster"), - entry(SoundType.SMALL_AMETHYST_BUD, "small_amethyst_bud"), - entry(SoundType.MEDIUM_AMETHYST_BUD, "medium_amethyst_bud"), - entry(SoundType.LARGE_AMETHYST_BUD, "large_amethyst_bud"), - - entry(SoundType.TUFF, "tuff"), - entry(SoundType.CALCITE, "calcite"), - entry(SoundType.DRIPSTONE_BLOCK, "dripstone"), - entry(SoundType.POINTED_DRIPSTONE, "pointed_dripstone"), - entry(SoundType.COPPER, "copper"), - entry(SoundType.CAVE_VINES, "cave_vine"), - entry(SoundType.SPORE_BLOSSOM, "spore_blossom"), - entry(SoundType.AZALEA, "azalea"), - entry(SoundType.FLOWERING_AZALEA, "flowering_azalea"), - entry(SoundType.MOSS_CARPET, "moss_carpet"), - entry(SoundType.MOSS, "moss"), - entry(SoundType.BIG_DRIPLEAF, "big_dripleaf"), - entry(SoundType.SMALL_DRIPLEAF, "small_dripleaf"), - entry(SoundType.ROOTED_DIRT, "rooted_dirt"), - entry(SoundType.HANGING_ROOTS, "hanging_roots"), - entry(SoundType.AZALEA_LEAVES, "azalea_leaves"), - entry(SoundType.SCULK_SENSOR, "sculk_sensor"), - entry(SoundType.GLOW_LICHEN, "glow_lichen"), - entry(SoundType.DEEPSLATE, "deepslate"), - entry(SoundType.DEEPSLATE_BRICKS, "deepslate_bricks"), - entry(SoundType.DEEPSLATE_TILES, "deepslate_tiles"), - entry(SoundType.POLISHED_DEEPSLATE, "polished_deepslate") - ); - - public static final Map mapColourName = Map.ofEntries( - entry(MaterialColor.NONE , "air" ), - entry(MaterialColor.GRASS , "grass" ), - entry(MaterialColor.SAND , "sand" ), - entry(MaterialColor.WOOL , "wool" ), - entry(MaterialColor.FIRE , "tnt" ), - entry(MaterialColor.ICE , "ice" ), - entry(MaterialColor.METAL , "iron" ), - entry(MaterialColor.PLANT , "foliage" ), - entry(MaterialColor.SNOW , "snow" ), - entry(MaterialColor.CLAY , "clay" ), - entry(MaterialColor.DIRT , "dirt" ), - entry(MaterialColor.STONE , "stone" ), - entry(MaterialColor.WATER , "water" ), - entry(MaterialColor.WOOD , "wood" ), - entry(MaterialColor.QUARTZ , "quartz" ), - entry(MaterialColor.COLOR_ORANGE , "adobe" ), - entry(MaterialColor.COLOR_MAGENTA , "magenta" ), - entry(MaterialColor.COLOR_LIGHT_BLUE, "light_blue"), - entry(MaterialColor.COLOR_YELLOW , "yellow" ), - entry(MaterialColor.COLOR_LIGHT_GREEN , "lime" ), - entry(MaterialColor.COLOR_PINK , "pink" ), - entry(MaterialColor.COLOR_GRAY , "gray" ), - entry(MaterialColor.COLOR_LIGHT_GRAY, "light_gray"), - entry(MaterialColor.COLOR_CYAN , "cyan" ), - entry(MaterialColor.COLOR_PURPLE , "purple" ), - entry(MaterialColor.COLOR_BLUE , "blue" ), - entry(MaterialColor.COLOR_BROWN , "brown" ), - entry(MaterialColor.COLOR_GREEN , "green" ), - entry(MaterialColor.COLOR_RED , "red" ), - entry(MaterialColor.COLOR_BLACK , "black" ), - entry(MaterialColor.GOLD , "gold" ), - entry(MaterialColor.DIAMOND , "diamond" ), - entry(MaterialColor.LAPIS , "lapis" ), - entry(MaterialColor.EMERALD , "emerald" ), - entry(MaterialColor.PODZOL , "obsidian" ), - entry(MaterialColor.NETHER , "netherrack"), //TODO fix these - entry(MaterialColor.TERRACOTTA_WHITE , "white_terracotta" ), - entry(MaterialColor.TERRACOTTA_ORANGE , "orange_terracotta" ), - entry(MaterialColor.TERRACOTTA_MAGENTA , "magenta_terracotta" ), - entry(MaterialColor.TERRACOTTA_LIGHT_BLUE, "light_blue_terracotta" ), - entry(MaterialColor.TERRACOTTA_YELLOW , "yellow_terracotta" ), - entry(MaterialColor.TERRACOTTA_LIGHT_GREEN , "lime_terracotta" ), - entry(MaterialColor.TERRACOTTA_PINK , "pink_terracotta" ), - entry(MaterialColor.TERRACOTTA_GRAY , "gray_terracotta" ), - entry(MaterialColor.TERRACOTTA_LIGHT_GRAY, "light_gray_terracotta" ), - entry(MaterialColor.TERRACOTTA_CYAN , "cyan_terracotta" ), - entry(MaterialColor.TERRACOTTA_PURPLE , "purple_terracotta" ), - entry(MaterialColor.TERRACOTTA_BLUE , "blue_terracotta" ), - entry(MaterialColor.TERRACOTTA_BROWN , "brown_terracotta" ), - entry(MaterialColor.TERRACOTTA_GREEN , "green_terracotta" ), - entry(MaterialColor.TERRACOTTA_RED , "red_terracotta" ), - entry(MaterialColor.TERRACOTTA_BLACK , "black_terracotta" ), - entry(MaterialColor.CRIMSON_NYLIUM , "crimson_nylium" ), - entry(MaterialColor.CRIMSON_STEM , "crimson_stem" ), - entry(MaterialColor.CRIMSON_HYPHAE , "crimson_hyphae" ), - entry(MaterialColor.WARPED_NYLIUM , "warped_nylium" ), - entry(MaterialColor.WARPED_STEM , "warped_stem" ), - entry(MaterialColor.WARPED_HYPHAE , "warped_hyphae" ), - entry(MaterialColor.WARPED_WART_BLOCK , "warped_wart" ), - entry(MaterialColor.DEEPSLATE , "deepslate" ), - entry(MaterialColor.RAW_IRON , "raw_iron" ), - entry(MaterialColor.GLOW_LICHEN , "glow_lichen" ) - ); - - public static final Map materialName = Map.ofEntries( - entry(Material.AIR , "air" ), - entry(Material.STRUCTURAL_AIR , "void" ), - entry(Material.PORTAL , "portal" ), - entry(Material.CLOTH_DECORATION , "carpet" ), - entry(Material.PLANT , "plant" ), - entry(Material.WATER_PLANT, "water_plant" ), - entry(Material.REPLACEABLE_PLANT, "vegetation" ), - entry(Material.REPLACEABLE_FIREPROOF_PLANT, "nether_shoots" ), - entry(Material.REPLACEABLE_WATER_PLANT, "sea_grass" ), - entry(Material.WATER , "water" ), - entry(Material.BUBBLE_COLUMN , "bubble_column"), - entry(Material.LAVA , "lava" ), - entry(Material.TOP_SNOW , "snow_layer" ), - entry(Material.FIRE , "fire" ), - entry(Material.DECORATION , "decoration" ), - entry(Material.WEB , "cobweb" ), - entry(Material.SCULK , "sculk" ), - entry(Material.BUILDABLE_GLASS , "redstone_lamp"), - entry(Material.CLAY, "clay" ), - entry(Material.DIRT , "dirt" ), - entry(Material.GRASS , "grass" ), - entry(Material.ICE_SOLID , "packed_ice" ), - entry(Material.SAND , "sand" ), - entry(Material.SPONGE , "sponge" ), - entry(Material.SHULKER_SHELL , "shulker" ), - entry(Material.WOOD , "wood" ), - entry(Material.NETHER_WOOD , "nether_wood" ), - entry(Material.BAMBOO_SAPLING , "shoots" ), - entry(Material.BAMBOO , "bamboo" ), - entry(Material.WOOL , "wool" ), - entry(Material.EXPLOSIVE , "tnt" ), - entry(Material.LEAVES , "leaves" ), - entry(Material.GLASS , "glass" ), - entry(Material.ICE , "ice" ), - entry(Material.CACTUS , "cactus" ), - entry(Material.STONE , "stone" ), - entry(Material.METAL , "metal" ), - entry(Material.SNOW , "snow" ), - entry(Material.HEAVY_METAL , "anvil" ), - entry(Material.BARRIER , "barrier" ), - entry(Material.PISTON , "piston" ), - entry(Material.MOSS , "moss" ), - entry(Material.VEGETABLE , "gourd" ), - entry(Material.EGG , "dragon_egg" ), - entry(Material.CAKE , "cake" ), - entry(Material.AMETHYST , "amethyst" ), - entry(Material.POWDER_SNOW , "powder_snow") - ); - public static List blockInfo(BlockPos pos, ServerLevel world) { BlockState state = world.getBlockState(pos); @@ -238,9 +39,9 @@ public static List blockInfo(BlockPos pos, ServerLevel world) lst.add(Messenger.s("")); lst.add(Messenger.s("=====================================")); lst.add(Messenger.s(String.format("Block info for %s%s (id %d%s):", blocks.getKey(block),metastring, blocks.getId(block), metastring ))); - lst.add(Messenger.s(String.format(" - Material: %s", materialName.get(material)))); - lst.add(Messenger.s(String.format(" - Map colour: %s", mapColourName.get(state.getMapColor(world, pos))))); - lst.add(Messenger.s(String.format(" - Sound type: %s", soundName.get(block.getSoundType(state))))); + lst.add(Messenger.s(String.format(" - Material: %s", Colors.materialName.get(material)))); + lst.add(Messenger.s(String.format(" - Map colour: %s", Colors.mapColourName.get(state.getMapColor(world, pos))))); + lst.add(Messenger.s(String.format(" - Sound type: %s", Colors.soundName.get(block.getSoundType(state))))); lst.add(Messenger.s("")); lst.add(Messenger.s(String.format(" - Full block: %s", state.isCollisionShapeFullBlock(world, pos)))); // isFullCube() ))); lst.add(Messenger.s(String.format(" - Normal cube: %s", state.isRedstoneConductor(world, pos)))); //isNormalCube()))); isSimpleFullBlock diff --git a/src/main/java/carpet/utils/SpawnChunks.java b/src/main/java/carpet/utils/SpawnChunks.java index 5c905d1718..9631d4689f 100644 --- a/src/main/java/carpet/utils/SpawnChunks.java +++ b/src/main/java/carpet/utils/SpawnChunks.java @@ -1,7 +1,6 @@ package carpet.utils; import carpet.fakes.ChunkTicketManagerInterface; -import carpet.fakes.ServerChunkManagerInterface; import net.minecraft.server.level.DistanceManager; import net.minecraft.server.level.ServerChunkCache; import net.minecraft.world.level.ChunkPos; @@ -10,7 +9,7 @@ public class SpawnChunks { public static void changeSpawnChunks(ServerChunkCache chunkManager, ChunkPos pos, int size) { - DistanceManager ticketManager = ((ServerChunkManagerInterface)chunkManager).getCMTicketManager(); + DistanceManager ticketManager = chunkManager.chunkMap.getDistanceManager(); ((ChunkTicketManagerInterface)ticketManager).changeSpawnChunks(pos, size); } } From 86a123d2f1ca4a2fe80bd0aad991a6162a020087 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 15 Feb 2023 12:57:53 +0100 Subject: [PATCH 055/233] store rate limit prevention --- .../java/carpet/script/ScriptCommand.java | 2 +- .../carpet/script/utils/AppStoreManager.java | 72 +++++++++++-------- 2 files changed, 44 insertions(+), 30 deletions(-) diff --git a/src/main/java/carpet/script/ScriptCommand.java b/src/main/java/carpet/script/ScriptCommand.java index b9bd17b1f2..3d1e3aed14 100644 --- a/src/main/java/carpet/script/ScriptCommand.java +++ b/src/main/java/carpet/script/ScriptCommand.java @@ -128,7 +128,7 @@ private static CompletableFuture suggestDownloadableApps( String previous = suggestionsBuilder.getRemaining(); try { - AppStoreManager.suggestionsFromPath(previous).forEach(suggestionsBuilder::suggest); + AppStoreManager.suggestionsFromPath(previous, context.getSource()).forEach(suggestionsBuilder::suggest); } catch (IOException e) { diff --git a/src/main/java/carpet/script/utils/AppStoreManager.java b/src/main/java/carpet/script/utils/AppStoreManager.java index e5ab6aecab..76ebccf86a 100644 --- a/src/main/java/carpet/script/utils/AppStoreManager.java +++ b/src/main/java/carpet/script/utils/AppStoreManager.java @@ -45,6 +45,7 @@ public class AppStoreManager * {@code /script download} command and getting the suggestions. */ private static StoreNode APP_STORE_ROOT = StoreNode.folder(null, ""); + private static long storeErrorTime = 0; /** * This is the base link to the scarpet app repo from the github api. @@ -116,7 +117,7 @@ private StoreNode(@Nullable StoreNode parent, String name) this.sealed = false; } - public synchronized void fillChildren() throws IOException + public synchronized void fillChildren(@Nullable CommandSourceStack source) throws IOException { if (sealed) { @@ -126,6 +127,14 @@ public synchronized void fillChildren() throws IOException { throw new IOException("Accessing scarpet app repo is disabled"); } + if (System.currentTimeMillis() - storeErrorTime < 30000) + { + if (source != null) + { + Carpet.Messenger_message(source, "di App store is not available yet"); + } + return; + } String queryPath = scarpetRepoLink + getPath(); String response; @@ -135,6 +144,11 @@ public synchronized void fillChildren() throws IOException } catch (IOException e) { + if (source != null) + { + Carpet.Messenger_message(source, "r Scarpet app store is not available at the moment, try in a minute"); + } + storeErrorTime = System.currentTimeMillis(); // Not sealing to allow retrying throw new IOException("Problems fetching " + queryPath, e); } @@ -160,36 +174,36 @@ public synchronized void fillChildren() throws IOException * Returns true if doing down the directory structure cannot continue since the matching element is either a leaf or * a string not matching of any node. */ - public boolean cannotContinueFor(String pathElement) throws IOException + public boolean cannotContinueFor(String pathElement, CommandSourceStack source) throws IOException { if (isLeaf()) { return true; } - fillChildren(); + fillChildren(source); return !children.containsKey(pathElement); } - public List createPathSuggestions() throws IOException + public List createPathSuggestions(CommandSourceStack source) throws IOException { if (isLeaf()) { return name.endsWith(".sc") ? Collections.singletonList(getPath()) : Collections.emptyList(); } - fillChildren(); + fillChildren(source); String prefix = getPath(); return children.values().stream(). filter(n -> (!n.isLeaf() || n.name.endsWith(".sc"))). map(s -> prefix + s.pathElement().replaceAll("/$", "")).toList(); } - public StoreNode drillDown(String pathElement) throws IOException + public StoreNode drillDown(String pathElement, CommandSourceStack source) throws IOException { if (isLeaf()) { throw new IOException(pathElement + " is not a folder"); } - fillChildren(); + fillChildren(source); if (!children.containsKey(pathElement)) { throw new IOException("Folder " + pathElement + " is not present"); @@ -197,9 +211,9 @@ public StoreNode drillDown(String pathElement) throws IOException return children.get(pathElement); } - public String getValue(String file) throws IOException + public String getValue(String file, CommandSourceStack source) throws IOException { - StoreNode leaf = drillDown(file); + StoreNode leaf = drillDown(file, source); if (!leaf.isLeaf()) { throw new IOException(file + " is not a file"); @@ -216,22 +230,22 @@ public String getValue(String file) throws IOException * @param currentPath The path down which we want to search for files * @return A pair of the current valid path, as well as the set of all the file/directory names at the end of that path */ - public static List suggestionsFromPath(String currentPath) throws IOException + public static List suggestionsFromPath(String currentPath, CommandSourceStack source) throws IOException { String[] path = currentPath.split("/"); StoreNode appKiosk = APP_STORE_ROOT; for (String pathElement : path) { - if (appKiosk.cannotContinueFor(pathElement)) + if (appKiosk.cannotContinueFor(pathElement, source)) { break; } appKiosk = appKiosk.children.get(pathElement); } - List filteredSuggestions = appKiosk.createPathSuggestions().stream().filter(s -> s.startsWith(currentPath)).toList(); + List filteredSuggestions = appKiosk.createPathSuggestions(source).stream().filter(s -> s.startsWith(currentPath)).toList(); if (filteredSuggestions.size() == 1 && !appKiosk.isLeaf()) { - return suggestionsFromPath(filteredSuggestions.get(0)); // Start suggesting directory contents + return suggestionsFromPath(filteredSuggestions.get(0), source); // Start suggesting directory contents } return filteredSuggestions; } @@ -246,7 +260,7 @@ public static List suggestionsFromPath(String currentPath) throws IOExce public static int downloadScript(CommandSourceStack source, String path) { - AppInfo nodeInfo = getFileNode(path); + AppInfo nodeInfo = getFileNode(path, source); return downloadScript(source, path, nodeInfo, false); } @@ -275,12 +289,12 @@ private static int downloadScript(CommandSourceStack source, String path, AppInf * @param appPath The user inputted path to the scarpet script * @return Pair of app file name and content */ - public static AppInfo getFileNode(String appPath) + public static AppInfo getFileNode(String appPath, CommandSourceStack source) { - return getFileNodeFrom(APP_STORE_ROOT, appPath); + return getFileNodeFrom(APP_STORE_ROOT, appPath, source); } - public static AppInfo getFileNodeFrom(StoreNode start, String appPath) + public static AppInfo getFileNodeFrom(StoreNode start, String appPath, CommandSourceStack source) { String[] path = appPath.split("/"); StoreNode appKiosk = start; @@ -288,11 +302,11 @@ public static AppInfo getFileNodeFrom(StoreNode start, String appPath) { for (String pathElement : Arrays.copyOfRange(path, 0, path.length - 1)) { - appKiosk = appKiosk.drillDown(pathElement); + appKiosk = appKiosk.drillDown(pathElement, source); } String appName = path[path.length - 1]; - appKiosk.getValue(appName); - return new AppInfo(appName, appKiosk.getValue(appName), appKiosk); + appKiosk.getValue(appName, source); + return new AppInfo(appName, appKiosk.getValue(appName, source), appKiosk); } catch (IOException e) { @@ -346,7 +360,7 @@ public static void writeUrlToFile(String url, Path destination) throws IOExcepti } } - private static String getFullContentUrl(String original, StoreNode storeSource) + private static String getFullContentUrl(String original, StoreNode storeSource, CommandSourceStack source) { if (original.matches("^https?://.*$")) // We've got a full url here: Just use it { @@ -354,9 +368,9 @@ private static String getFullContentUrl(String original, StoreNode storeSource) } if (original.charAt(0) == '/') // We've got an absolute path: Use app store root { - return getFileNode(original.substring(1)).url(); + return getFileNode(original.substring(1), source).url(); } - return getFileNodeFrom(storeSource, original).url(); // Relative path: Use download location + return getFileNodeFrom(storeSource, original, source).url(); // Relative path: Use download location } public static void addResource(CarpetScriptHost carpetScriptHost, StoreNode storeSource, Value resource) @@ -371,7 +385,7 @@ public static void addResource(CarpetScriptHost carpetScriptHost, StoreNode stor throw new InternalExpressionException("Missing 'source' field in resource descriptor: " + resource.getString()); } String source = resourceMap.get("source").getString(); - String contentUrl = getFullContentUrl(source, storeSource); + String contentUrl = getFullContentUrl(source, storeSource, carpetScriptHost.responsibleSource); String target = resourceMap.computeIfAbsent("target", k -> new StringValue(contentUrl.substring(contentUrl.lastIndexOf('/') + 1))).getString(); boolean shared = resourceMap.getOrDefault("shared", Value.FALSE).getBoolean(); @@ -396,11 +410,11 @@ public static void addResource(CarpetScriptHost carpetScriptHost, StoreNode stor * * @param originalSource The StoreNode from the container's app * @param sourceString The string the app specified as source - * @param contentUrl The full content URL, from {@link #getFullContentUrl(String, StoreNode)} + * @param contentUrl The full content URL, from {@link #getFullContentUrl(String, StoreNode, CommandSourceStack)} * @return A {@link StoreNode} that can be used in an app that came from the provided source */ @Nullable - private static StoreNode getNewStoreNode(StoreNode originalSource, String sourceString, String contentUrl) + private static StoreNode getNewStoreNode(CommandSourceStack commandSource, StoreNode originalSource, String sourceString, String contentUrl) { StoreNode next = originalSource; if (sourceString == contentUrl) // External URL (check getFullUrlContent) @@ -417,7 +431,7 @@ private static StoreNode getNewStoreNode(StoreNode originalSource, String source { for (int i = 0; i < dirs.length - 1; i++) { - next = next.drillDown(dirs[i]); + next = next.drillDown(dirs[i], commandSource); } } catch (IOException e) @@ -435,7 +449,7 @@ public static void addLibrary(CarpetScriptHost carpetScriptHost, StoreNode store } Map libraryMap = map.getMap().entrySet().stream().collect(Collectors.toMap(e -> e.getKey().getString(), e -> e.getValue().getString())); String source = libraryMap.get("source"); - String contentUrl = getFullContentUrl(source, storeSource); + String contentUrl = getFullContentUrl(source, storeSource, carpetScriptHost.responsibleSource); String target = libraryMap.computeIfAbsent("target", k -> contentUrl.substring(contentUrl.lastIndexOf('/') + 1)); if (!(contentUrl.endsWith(".sc") || contentUrl.endsWith(".scl"))) { @@ -447,7 +461,7 @@ public static void addLibrary(CarpetScriptHost carpetScriptHost, StoreNode store } try { - downloadScript(carpetScriptHost.responsibleSource, target, new AppInfo(target, contentUrl, getNewStoreNode(storeSource, source, contentUrl)), true); + downloadScript(carpetScriptHost.responsibleSource, target, new AppInfo(target, contentUrl, getNewStoreNode(carpetScriptHost.responsibleSource, storeSource, source, contentUrl)), true); } catch (CommandRuntimeException e) { From a295f81fa9fa9e1190b4dab4c30ffb77af02cc7e Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 15 Feb 2023 20:10:24 +0100 Subject: [PATCH 056/233] 23w07a --- gradle.properties | 4 ++-- .../java/carpet/mixins/MinecraftServer_tickspeedMixin.java | 2 +- src/main/java/carpet/mixins/ServerStatus_motdMixin.java | 2 +- src/main/java/carpet/script/utils/ShapesRenderer.java | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/gradle.properties b/gradle.properties index 21e3d6807e..6dce9405de 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,10 +4,10 @@ org.gradle.jvmargs=-Xmx1G # Fabric Properties # check these on https://fabricmc.net/use # or better: https://modmuss50.me/fabric.html - minecraft_version=23w06a + minecraft_version=23w07a loader_version=0.14.14 jsr305_version=3.0.2 - fabric_version=0.73.5+1.19.4 + fabric_version=0.74.0+1.19.4 # Mod Properties mod_version = 1.4.97 diff --git a/src/main/java/carpet/mixins/MinecraftServer_tickspeedMixin.java b/src/main/java/carpet/mixins/MinecraftServer_tickspeedMixin.java index cebe1ba176..c581492d9d 100644 --- a/src/main/java/carpet/mixins/MinecraftServer_tickspeedMixin.java +++ b/src/main/java/carpet/mixins/MinecraftServer_tickspeedMixin.java @@ -82,7 +82,7 @@ private boolean cancelRunLoop(MinecraftServer server) // could possibly just inject that mspt selection at the beginning of the loop, but then adding all mspt's to // replace 50L will be a hassle @Inject(method = "runServer", at = @At(value = "INVOKE", shift = At.Shift.AFTER, - target = "Lnet/minecraft/server/MinecraftServer;updateStatusIcon(Lnet/minecraft/network/protocol/status/ServerStatus;)V")) + target = "Lnet/minecraft/server/MinecraftServer;buildServerStatus()Lnet/minecraft/network/protocol/status/ServerStatus;")) private void modifiedRunLoop(CallbackInfo ci) { while (this.running) diff --git a/src/main/java/carpet/mixins/ServerStatus_motdMixin.java b/src/main/java/carpet/mixins/ServerStatus_motdMixin.java index 55ee6a3b26..adae60a0ff 100644 --- a/src/main/java/carpet/mixins/ServerStatus_motdMixin.java +++ b/src/main/java/carpet/mixins/ServerStatus_motdMixin.java @@ -11,7 +11,7 @@ @Mixin(ServerStatus.class) public class ServerStatus_motdMixin { - @Inject(method = "getDescription", at = @At("HEAD"), cancellable = true) + @Inject(method = "description", at = @At("HEAD"), cancellable = true) private void getDescriptionAlternative(CallbackInfoReturnable cir) { if (!CarpetSettings.customMOTD.equals("_")) diff --git a/src/main/java/carpet/script/utils/ShapesRenderer.java b/src/main/java/carpet/script/utils/ShapesRenderer.java index a83851a711..f3ae057c59 100644 --- a/src/main/java/carpet/script/utils/ShapesRenderer.java +++ b/src/main/java/carpet/script/utils/ShapesRenderer.java @@ -568,7 +568,7 @@ else if (shape.align == 1) text_x = (float) (-textRenderer.width(shape.value.getString())); } MultiBufferSource.BufferSource immediate = MultiBufferSource.immediate(builder); - textRenderer.drawInBatch(shape.value, text_x, 0.0F, shape.textcolor, false, matrices.last().pose(), immediate, false, shape.textbck, 15728880); + textRenderer.drawInBatch(shape.value, text_x, 0.0F, shape.textcolor, false, matrices.last().pose(), immediate, Font.DisplayMode.NORMAL, shape.textbck, 15728880); immediate.endBatch(); matrices.popPose(); RenderSystem.enableCull(); From bd0f47ff295569946fd1098843ba4a439b39c022 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 15 Feb 2023 20:11:26 +0100 Subject: [PATCH 057/233] 1.4.98 --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 6dce9405de..ec5d49ec7a 100644 --- a/gradle.properties +++ b/gradle.properties @@ -10,7 +10,7 @@ org.gradle.jvmargs=-Xmx1G fabric_version=0.74.0+1.19.4 # Mod Properties - mod_version = 1.4.97 + mod_version = 1.4.98 maven_group = carpet archives_base_name = fabric-carpet From 65de5492ac30b50fdf7e27c9fd6d1cbd4544a70a Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Sat, 18 Feb 2023 08:58:32 +0100 Subject: [PATCH 058/233] modernize camera.sc --- .../resources/assets/carpet/scripts/camera.sc | 380 +++++++++--------- 1 file changed, 186 insertions(+), 194 deletions(-) diff --git a/src/main/resources/assets/carpet/scripts/camera.sc b/src/main/resources/assets/carpet/scripts/camera.sc index 7bfd9feaa8..63cc6c46aa 100644 --- a/src/main/resources/assets/carpet/scripts/camera.sc +++ b/src/main/resources/assets/carpet/scripts/camera.sc @@ -1,75 +1,72 @@ -_command() -> -( - print('camera: scarpet app.'); - print('-------------------'); - print(' "/camera start" - Set the starting point, resetting the path'); - print(''); - print(' "/camera add " - Add a point to the end, secs later'); - print(' "/camera prepend " - Prepend the start secs before'); - print(' "/camera clear" - Remove entire path'); - print(' "/camera select" - .. a point or just punch it, to select it'); - print(' "/camera place_player - Move player to the selected point'); - print(' "/camera move" - Move the selected point to players location'); - print(' "/camera duration " - Set new selected path duration'); - print(' "/camera split_point" - Split selected path in half.'); - print(' "/camera delete_point" - Remove current key point'); - print(' "/camera trim_path" - Remove all key points from selected up'); - print(''); - print(' "/camera save_as "'); - print(' "/camera load "'); - print(' - Store and load paths from world saves /scripts folder'); - print(''); - print(' "/camera interpolation < linear | gauss | catmull_rom | gauss >"'); - print(' Select interpolation between points:'); - print(' - catmull_rom: Catmull-Rom interpolation (default).'); - print(' smooth path that goes through all points.'); - print(' - linear: straight paths between points.'); - print(' - gauss: automatic smooth transitions.'); - print(' - gauss : custom fixed variance '); - print(' (in seconds) for special effects.'); - print(' gauss makes the smoothest path,'); - print(' but treating points as suggestions only'); - print(''); - print(' "/camera repeat " - '); - print(' Repeat existing points configuration n-times'); - print(' using seconds to link path ends'); - print(''); - print(' "/camera stretch " - '); - print(' Change length of the entire path'); - print(' from 25 -> 4x faster, to 400 -> 4x slower,'); - print(''); - print(' "/camera transpose" - '); - print(' Move entire path with the start at players position.'); - print(''); - print(' "/camera play : Run the path with the player'); - print(' use "sneak" to stop it prematurely'); - print(' run /camera hide and F1 to clear the view'); - print(''); - print(' "/camera show": Show current path particles'); - print(' color of particles used is different for different players'); - print(' "/camera hide": Hide path display'); - print(' "/camera prefer_smooth_play": '); - print(' Eat CPU spikes and continue as usual'); - print(' "/camera prefer_synced_play": '); - print(' After CPU spikes jump to where you should be'); - - print(''); - null -); -__config() ->{ - 'commands'->{ - ''->'_command', - ''->'_call', - 'add '->'add', - 'prepend '->'prepend', +usage() -> 'camera: scarpet app. +------------------- + "/camera start" - Set the starting point, resetting the path + + + "/camera add " - Add a point to the end, secs later + "/camera prepend " - Prepend the start secs before + "/camera clear" - Remove entire path + "/camera select" - .. a point or just punch it, to select it + "/camera place_player - Move player to the selected point + "/camera move" - Move the selected point to players location + "/camera duration " - Set new selected path duration + "/camera split_point" - Split selected path in half. + "/camera delete_point" - Remove current key point + "/camera trim_path" - Remove all key points from selected up + + "/camera save_as " + "/camera load " + - Store and load paths from world saves /scripts folder + + "/camera interpolation < linear | gauss | catmull_rom | gauss >" + Select interpolation between points: + - catmull_rom: Catmull-Rom interpolation (default). + smooth path that goes through all points. + - linear: straight paths between points. + - gauss: automatic smooth transitions. + - gauss : custom fixed variance + (in seconds) for special effects. + gauss makes the smoothest path, + but treating points as suggestions only + + "/camera repeat " - + Repeat existing points configuration n-times + using seconds to link path ends + + "/camera stretch " - + Change length of the entire path + from 25 -> 4x faster, to 400 -> 4x slower, + + "/camera transpose" - + Move entire path with the start at players position. + + "/camera play : Run the path with the player + use "sneak" to stop it prematurely + run /camera hide and F1 to clear the view + + "/camera show": Show current path particles + color of particles used is different for different players + "/camera hide": Hide path display + "/camera prefer_smooth_play": + Eat CPU spikes and continue as usual + "/camera prefer_synced_play": + After CPU spikes jump to where you should be +'; + +__config() -> { + 'commands' -> { + '' -> _() -> print(usage()), + '' -> '_call', + 'add ' -> 'add', + 'prepend ' -> 'prepend', 'duration ' -> 'duration', - 'save_as '->'save_as', - 'load '->'load', - 'interpolation '->['__interpolation',true], - 'interpolation gauss'->['__interpolation','gauss',true], - 'interpolation gauss '->_(float)->(__interpolation('gauss_'+str(float),true)), - 'repeat '->'repeat', - 'stretch '->'stretch' + 'save_as ' -> 'save_as', + 'load ' -> 'load', + 'interpolation ' -> ['interpolation', null, true], + 'interpolation gauss' -> ['interpolation', 'gauss', null, true], + 'interpolation gauss ' -> _(float) -> interpolation('gauss', float, true), + 'repeat ' -> 'repeat', + 'stretch ' -> 'stretch' }, 'arguments'->{ 'seconds'->{'type'->'float', 'min' -> 0.01, 'suggest'->[]}, @@ -119,14 +116,14 @@ global_color_b = null; global_path_precalculated = null; // starts the path with current player location -start() -> __start_with( _() -> l(l(__camera_position(), 0,'sharp')) ); +start() -> _start_with( _() -> [ [_camera_position(), 0, 'sharp'] ] ); // start path with customized initial points selection -__start_with(points_supplier) -> +_start_with(points_supplier) -> ( p = player(); global_player = str(p); - global_player_eye_offset = l(0, p~'eye_height',0,0,0); + global_player_eye_offset = [0, p~'eye_height',0,0,0]; global_dimension = p~'dimension'; code = abs(hash_code(str(p))-123456); @@ -135,13 +132,13 @@ __start_with(points_supplier) -> global_points = call(points_supplier); global_selected_point = null; - __update(); + _update(); show(); print(str('Started path at %.1f %.1f %.1f', p~'x', p~'y', p~'z')); ); // gets current player controlling the path, or fails -__get_player() -> +_get_player() -> ( if (!global_player, exit('No player selected')); p = player(global_player); @@ -152,21 +149,21 @@ __get_player() -> // clears current path clear() -> ( - global_points = l(); + global_points = []; global_dimension = null; global_player = null; global_selected_point = null; global_showing_path = false; global_playing_path = false; - __update(); + _update(); print('Path cleared'); ); // camera position for the player sticks out of their eyes -__camera_position() -> (__get_player()~'location' + global_player_eye_offset); +_camera_position() -> (_get_player()~'location' + global_player_eye_offset); // path changed, now notify all processes that they need to update; -__update() -> +_update() -> ( global_path_precalculated = null; global_playing_path = false; @@ -174,90 +171,86 @@ __update() -> ); // ensures that the current execution context can modify the path -__assert_can_modify_path() -> +_assert_can_modify_path() -> ( if (!global_points, exit('Path is not setup for current player')); if (!global_showing_path, exit('Turn on path showing to edit key points')); - if(!global_player || !global_dimension || __get_player()~'dimension' != global_dimension, + if(!global_player || !global_dimension || _get_player()~'dimension' != global_dimension, exit('Player not in dimension')); ); // make sure selected point is correct -__assert_point_selected(validator) -> +_assert_point_selected(validator) -> ( - __assert_can_modify_path(); + _assert_can_modify_path(); if (!call(validator, global_selected_point), exit('No appropriate point selected')); ); //select a custom interpolation method -__interpolation(method, verbose) -> +interpolation(method, option, verbose) -> ( - __prepare_path_if_needed() -> __prepare_path_if_needed_generic(); - // each supported method needs to specify its __find_position_for_point to trace the path + _prepare_path_if_needed() -> _prepare_path_if_needed_generic(); + // each supported method needs to specify its _find_position_for_point to trace the path // accepting segment number, and position in the segment - // or optionally __prepare_path_if_needed, if path is inefficient to compute point by point + // or optionally _prepare_path_if_needed, if path is inefficient to compute point by point global_interpolator = if ( - method == 'linear', '__interpolator_linear', - method == 'catmull_rom', '__interpolator_cr', - method == 'gauss', _(s, p) -> __interpolator_gauB(s, p, 0), - method ~ '^gauss_', - ( - type = method - 'gauss_'; - type = replace(type,'_','.'); - variance = round(60*number(type)); - _(s, p, outer(variance)) -> __interpolator_gauB(s, p, variance); - ) + method == 'linear', '_interpolator_linear', + method == 'catmull_rom', '_interpolator_cr', + method == 'gauss' && option == null, _(s, p) -> _interpolator_gauB(s, p, 0), + method == 'gauss', + variance = round(60*option); + _(s, p, outer(variance)) -> _interpolator_gauB(s, p, variance); ); - __update(); - if(verbose, print('Interpolation changed to '+method)); + _update(); + if(verbose, print('Interpolation changed to '+method + if(option, ' '+option, ''))); ); -__interpolation('catmull_rom', false); +interpolation('catmull_rom', null, false); // adds a point to the end of the path with delay in seconds add(delay) -> ( - __assert_can_modify_path(); + _assert_can_modify_path(); //mode is currently unused, run_path does always sharp, gauss interpolator is always smooth // but this option could be used could be used at some point by more robust interpolators - __add_path_segment(__camera_position(), round(60*delay), 'smooth', true); - __update(); - print(__get_path_size_string()); + _add_path_segment(_camera_position(), round(60*delay), 'smooth', true); + _update(); + print(_get_path_size_string()); ); // prepends the path with a new starting point, with a segment of specified delay prepend(delay) -> ( - __assert_can_modify_path(); - __add_path_segment(__camera_position(), round(60*delay), 'smooth', false); - __update(); - print(__get_path_size_string()); + _assert_can_modify_path(); + _add_path_segment(_camera_position(), round(60*delay), 'smooth', false); + _update(); + print(_get_path_size_string()); ); // repeats existing points seveal times, using last section delay (seconds) to join points repeat(times, last_section_delay) -> ( - if (err = __is_not_valid_for_motion(), exit(err)); + if (err = _is_not_valid_for_motion(), exit(err)); positions = map(global_points, _:0); modes = map(global_points, _:(-1)); durations = map(global_points, global_points:(_i+1):1 - _:1 ); durations:(-1) = round(60*last_section_delay); loop(times, loop( length(positions), - __add_path_segment(copy(positions:_), durations:_, modes:_, true) + _add_path_segment(copy(positions:_), durations:_, modes:_, true) ) ); - __update(); - print(__get_path_size_string()); + _update(); + print(_get_path_size_string()); ); //stretches or shrinks current path to X percent of what it was before stretch(percentage) -> ( - if (err = __is_not_valid_for_motion(), exit(err)); + if (err = _is_not_valid_for_motion(), exit(err)); ratio = percentage/100; previous_path_length = global_points:(-1):1; for(global_points, _:1 = _:1*ratio ); - __update(); + _update(); print(str('path %s from %.2f to %.2f seconds', if(ratio<1,'shortened','extended'), previous_path_length/60, @@ -268,21 +261,20 @@ stretch(percentage) -> // moves current selected point to player location move() -> ( - __assert_point_selected(_(p) -> p != null); - new_position = __camera_position(); + _assert_point_selected(_(p) -> p != null); + new_position = _camera_position(); new_position:(-2) = __adjusted_rot( global_points:global_selected_point:0:(-2), new_position:(-2) ); global_points:global_selected_point:0 = new_position; - __update(); - null; + _update(); ); // chenges duration of the current selected segment to X seconds duration(amount) -> ( - __assert_point_selected(_(p) -> p); // skips nulls and 0 - starting point + _assert_point_selected(_(p) -> p); // skips nulls and 0 - starting point duration = number(amount); new_ticks = round(duration * 60); if (new_ticks < 10, return()); @@ -292,63 +284,63 @@ duration(amount) -> for (range(global_selected_point, length(global_points)), global_points:_:1 += delta; ); - __update(); - print(__get_path_size_string()); + _update(); + print(_get_path_size_string()); ); // deletes current keypoint without changing the path length delete_point() -> ( - __assert_point_selected(_(p) -> p != null); + _assert_point_selected(_(p) -> p != null); if (length(global_points) < 2, clear(); return()); if (global_selected_point == 0, global_points:1:1 = 0); global_points = filter(global_points, _i != global_selected_point); if (global_selected_point >= length(global_points), global_selected_point = null); - __update(); - print(__get_path_size_string()); + _update(); + print(_get_path_size_string()); ); // splits current selected segment in half by adding a keypoint in between split_point() -> ( - __assert_point_selected(_(p) -> p); // skips nulls and 0 - starting point + _assert_point_selected(_(p) -> p); // skips nulls and 0 - starting point current_time = global_points:global_selected_point:1; previous_time = global_points:(global_selected_point-1):1; segment_duration = current_time-previous_time; put( global_points, global_selected_point, - l( - __get_path_at(global_selected_point-1, previous_time, segment_duration/2), + [ + _get_path_at(global_selected_point-1, previous_time, segment_duration/2), previous_time+segment_duration/2, global_points:global_selected_point:2 - ), + ], 'insert' ); - __update(); - print(__get_path_size_string()); + _update(); + print(_get_path_size_string()); ); // removes all points in the path from the current point trim_path() -> ( - __assert_point_selected(_(p) -> p != null); + _assert_point_selected(_(p) -> p != null); global_points = slice(global_points, 0, global_selected_point); global_selected_point = null; - __update(); - print(__get_path_size_string()); + _update(); + print(_get_path_size_string()); ); // moves entire camera path keeping the angles to player position being in the starting point transpose() -> ( - __assert_can_modify_path(); - shift = pos(__get_player())-slice(global_points:0:0, 0, 3); + _assert_can_modify_path(); + shift = pos(_get_player())-slice(global_points:0:0, 0, 3); shift += 0; shift += 0; shift = shift + global_player_eye_offset; for(global_points, _:0 = _:0 + shift); - __update(); - print(__get_path_size_string()); + _update(); + print(_get_path_size_string()); ); // selects either a point of certain number (starting from 1), or closest point @@ -356,11 +348,11 @@ select(num) -> ( if (!global_points, return()); if (!global_showing_path, return()); - p = __get_player(); + p = _get_player(); num = (num+1000*(length(global_points)+1)) % (length(global_points)+1); selected_point = if (num, num-1, - __closest_point_to_center( - p~'pos'+l(0,p~'eye_height',0), + _closest_point_to_center( + p~'pos'+[0, p~'eye_height', 0], map(global_points, slice(_:0, 0, 3)) ) ); @@ -383,15 +375,15 @@ __on_player_attacks_entity(p, e) -> ); // adds new segment to the path -__add_path_segment(vector, duration, mode, append) -> +_add_path_segment(vector, duration, mode, append) -> ( - if ( (l('sharp','smooth') ~ mode) == null, exit('use smooth or sharp point')); - l(v, segment_time, m) = global_points:(if(append, -1, 0)); + if ( (['sharp','smooth'] ~ mode) == null, exit('use smooth or sharp point')); + [v, segment_time, m] = global_points:(if(append, -1, 0)); vector:(-2) = __adjusted_rot(v:(-2), vector:(-2)); if (append, - global_points += l(vector, segment_time+duration, mode); + global_points += [vector, segment_time+duration, mode]; , - new_points = l(l(vector, 0, mode)); + new_points = [[vector, 0, mode]]; for (global_points, _:1 += duration; new_points += _; @@ -411,9 +403,9 @@ __adjusted_rot(previous_rot, current_rot) -> ); // returns current path size blurb -__get_path_size_string() -> +_get_path_size_string() -> ( - if (!__is_not_valid_for_motion(), + if (!_is_not_valid_for_motion(), str('%d points, %.1f secs', length(global_points), global_points:(-1):1/60); , 'Path too small to run'; @@ -421,16 +413,16 @@ __get_path_size_string() -> ); // checks if the current path is valid for motion -__is_not_valid_for_motion() -> +_is_not_valid_for_motion() -> ( if(!global_points, return('Path not defined yet')); if(length(global_points)<2, return('Path not complete - add more points')); - if(!global_dimension || __get_player()~'dimension' != global_dimension, return('Wrong dimension')); + if(!global_dimension || _get_player()~'dimension' != global_dimension, return('Wrong dimension')); false ); // grabs position of a player for a given segment, which segment starts at start point, and offset by index points -__get_path_at(segment, start, index) -> +_get_path_at(segment, start, index) -> ( v = global_path_precalculated:(start+index); if(v == null, @@ -441,57 +433,57 @@ __get_path_at(segment, start, index) -> ); // squared euclidean distance between two points -__distsq(vec1, vec2) -> reduce(vec1 - vec2, _a + _*_, 0); +_distsq(vec1, vec2) -> reduce(vec1 - vec2, _a + _*_, 0); //finds index of the closest point from a list to the center point -__closest_point_to_center(center, points) -> +_closest_point_to_center(center, points) -> ( reduce(points, - d = __distsq(_, center); if( d ( - __get_path_size_string(); + _get_path_size_string(); if (global_showing_path, return ()); global_showing_path = true; global_needs_updating= false; - __create_markers() -> + _create_markers() -> ( - map(global_points || l(), + map(global_points || [], is_selected = global_selected_point != null && _i == global_selected_point; caption = if (_i == 0, '1: Start', str('%d: %.1fs', _i+1, global_points:_i:1/60); ); if (is_selected && _i > 0, caption += str(' (%.1fs current segment)', (global_points:_i:1 - global_points:(_i-1):1)/60); ); - m = create_marker(caption, _:0, 'observer'); + marker = create_marker(caption, _:0, 'observer'); if (is_selected, - modify(m,'effect','glowing',72000, 0, false, false); + modify(marker,'effect','glowing',72000, 0, false, false); ); - m + marker ); ); __show_path_tick() -> ( - if (__is_not_valid_for_motion(), return()); - __prepare_path_if_needed(); + if (_is_not_valid_for_motion(), return()); + _prepare_path_if_needed(); loop(global_particle_density, segment = floor(rand(length(global_points)-1)); particle_type = if ((segment+1) == global_selected_point, global_color_a, global_color_b); //'dust 0.1 0.9 0.1 1', 'dust 0.6 0.6 0.6 1'); start = global_points:segment:1; end = global_points:(segment+1):1; index = floor(rand(end-start)); - l(x, y, z) = slice(__get_path_at(segment, start, index), 0, 3); + [x, y, z] = slice(_get_path_at(segment, start, index), 0, 3); particle(particle_type, x, y, z, 1, 0, 0) ); null ); task( _() -> ( - global_markers = __create_markers(); + global_markers = _create_markers(); on_close = ( _() -> ( for(global_markers, modify(_,'remove')); global_markers = null; @@ -500,11 +492,11 @@ show() -> loop(7200, if(!global_showing_path, break()); - __get_player(); + _get_player(); if (global_needs_updating, global_needs_updating = false; for(global_markers, modify(_,'remove')); - global_markers = __create_markers(); + global_markers = _create_markers(); ); __show_path_tick(); sleep(100, call(on_close)); @@ -530,9 +522,9 @@ prefer_synced_play() -> (global_prefer_sync = true; 'Synchronized path play'); play() -> ( - if (err = __is_not_valid_for_motion(), exit(err)); - __prepare_path_if_needed(); - if (!__get_player() || __get_player()~'dimension' != global_dimension, exit('No player in dimension')); + if (err = _is_not_valid_for_motion(), exit(err)); + _prepare_path_if_needed(); + if (!_get_player() || _get_player()~'dimension' != global_dimension, exit('No player in dimension')); task( _() -> ( if (global_playing_path, // we don't want to join_task not to lock it just in case. No need to panic here global_playing_path = false; // cancel current path rendering @@ -541,14 +533,14 @@ play() -> showing_path = global_showing_path; hide(); sleep(1000); - sound('ui.button.click', pos(__get_player()), 8, 1); // to synchro with other clips + sound('ui.button.click', pos(_get_player()), 8, 1); // to synchro with other clips sleep(1000); // so particles can discipate global_playing_path = true; mspt = 1000 / 60; start_time = time(); very_start = start_time; point = 0; - p = __get_player(); + p = _get_player(); try ( loop( length(global_points)-1, segment = _; start = global_points:segment:1; @@ -556,7 +548,7 @@ play() -> loop(end-start, if (p~'sneaking', global_playing_path = false); if (!global_playing_path, throw()); - v = __get_path_at(segment, start, _)-global_player_eye_offset; + v = _get_path_at(segment, start, _)-global_player_eye_offset; modify(p, 'location', v); point += 1; end_time = time(); @@ -582,21 +574,21 @@ play() -> // moves player to a selected camera position place_player() -> ( - __assert_point_selected(_(p) -> p != null); - modify(__get_player(), 'location', global_points:global_selected_point:0 - global_player_eye_offset); + _assert_point_selected(_(p) -> p != null); + modify(_get_player(), 'location', global_points:global_selected_point:0 - global_player_eye_offset); ); // prepares empty path to fit new points -__prepare_path_if_needed_generic() -> +_prepare_path_if_needed_generic() -> ( if(!global_path_precalculated, global_path_precalculated = map(range(global_points:(-1):1), null)) ); // linear interpolator -__interpolator_linear(segment, point) -> +_interpolator_linear(segment, point) -> ( - l(va, start, mode_a) = global_points:segment; - l(vb, end, mode_b) = global_points:(segment+1); + [va, start, mode_a] = global_points:segment; + [vb, end, mode_b] = global_points:(segment+1); section = end-start; dt = point/section; dt*vb+(1-dt)*va @@ -605,49 +597,49 @@ __interpolator_linear(segment, point) -> // normal distribution should look like that //(1/sqrt(2*pi*d*d))*euler^(-((x-miu)^2)/(2*d*d)) // but we will be normalizing anyways, so who cares -__norm_prob(x, miu, d) -> euler^(-((x-miu)^2)/(2*d*d)); +_norm_prob(x, miu, d) -> euler^(-((x-miu)^2)/(2*d*d)); //gauB interpolator -__interpolator_gauB(from_index, point, deviation) -> +_interpolator_gauB(from_index, point, deviation) -> ( - components = l(); + components = []; path_point = global_points:from_index:1; try( for(range(from_index+1, length(global_points)), - l(v,ptime,mode) = global_points:_; + [v,ptime,mode] = global_points:_; dev = if (deviation > 0, deviation, - devs = l(); + devs = []; if (_+1 < length(global_points), devs += global_points:(_+1):1-ptime); if (_-1 >= 0, devs += ptime-global_points:(_-1):1); 0.6*reduce(devs, _a+_, 0)/length(devs) ); - impact = __norm_prob(path_point+point, ptime, dev); + impact = _norm_prob(path_point+point, ptime, dev); //if(rtotal && impact < 0.000001*rtotal, throw()); // can work badly on segments with vastly diff lengths - components += l(v, impact); + components += [v, impact]; rtotal += impact ) ); try( for(range(from_index, -1, -1), - l(v,ptime,mode) = global_points:_; + [v,ptime,mode] = global_points:_; dev = if (deviation > 0, deviation, - devs = l(); + devs = []; if (_+1 < length(global_points), devs += global_points:(_+1):1-ptime); if (_-1 >= 0, devs += ptime-global_points:(_-1):1); 0.6*reduce(devs, _a+_, 0)/length(devs) ); - impact = __norm_prob(path_point+point, ptime, dev); + impact = _norm_prob(path_point+point, ptime, dev); //if(ltotal && impact < 0.000001*ltotal, throw()); - components += l(v, impact); + components += [v, impact]; ltotal += impact ) ); total = rtotal+ltotal; - reduce(components, _a+_:0*(_:1/total), l(0,0,0,0,0)) + reduce(components, _a+_:0*(_:1/total), [0,0,0,0,0]) ); // Catmull-Rom spline -__interpolator_cr(from_index, point) -> +_interpolator_cr(from_index, point) -> ( total = global_points:(from_index+1):1 - global_points:from_index:1; p__1 = global_points:(if(from_index == 0, 0, from_index-1)):0; @@ -680,11 +672,11 @@ load(file) -> ( path_nbt = read_file(file, 'nbt'); if (!path_nbt, exit('No path to load: '+file)); - new_points = map(get(path_nbt, 'points[]'), l(_:'pos[]', _:'duration', _:'type')); + new_points = map(get(path_nbt, 'points[]'), [_:'pos[]', _:'duration', _:'type']); if (!new_points || first(new_points, length(_:0) != 5), exit('Incorrect data for :'+file); ); - __start_with(_(outer(new_points)) -> new_points); + _start_with(_(outer(new_points)) -> new_points); print('loaded '+file); ); From 2bf6d638d7585d41cc654489b03b1579c9c78716 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Sun, 19 Feb 2023 00:58:27 +0100 Subject: [PATCH 059/233] modernize chunk_display.sc --- .../assets/carpet/scripts/chunk_display.sc | 179 +++++++++--------- 1 file changed, 93 insertions(+), 86 deletions(-) diff --git a/src/main/resources/assets/carpet/scripts/chunk_display.sc b/src/main/resources/assets/carpet/scripts/chunk_display.sc index 1ec9875eff..062f4b81a8 100644 --- a/src/main/resources/assets/carpet/scripts/chunk_display.sc +++ b/src/main/resources/assets/carpet/scripts/chunk_display.sc @@ -1,100 +1,105 @@ global_update_interval = 100; -global_chunk_colors = m( +global_chunk_colors = { // loaded ticking - l(3, l(0xAAdd0000, 0x66990000)), // lime, green - l(2, l(0xFF000000, 0x88000000)), // red - l(1, l(0xFFcc0000, 0xbbaa0000)), // yellowish + 3 -> [0xAAdd0000, 0x66990000], // lime, green + 2 -> [0xFF000000, 0x88000000], // red + 1 -> [0xFFcc0000, 0xbbaa0000], // yellowish // 'unloaded' (in memory, so rather 'inaccessible') - l(0, l(0xcccccc00, 0x11111100)), // gray / hi constast + 0 -> [0xcccccc00, 0x11111100], // gray / hi constast // stable full generation (for '0's, all 1,2,3 are always 'full') - l('full', l(0xbbbbbb00, 0x88888800)), // gray + 'full' -> [0xbbbbbb00, 0x88888800], // gray // unstable final bits - l('heightmaps', l(0x33333300, 0x22222200)), // checker - l('spawn', l(0x00333300, 0x00222200)), // checker - l('light_gen', l(0x55550000, 0x44440000)), // checker + 'heightmaps' -> [0x33333300, 0x22222200], // checker + 'spawn' -> [0x00333300, 0x00222200], // checker + 'light_gen' -> [0x55550000, 0x44440000], // checker // stable features - l('features', l(0x88bb2200, 0x66882200)), // green muddled + 'features' -> [0x88bb2200, 0x66882200], // green muddled //stable terrain - l('liquid_carvers', l(0x65432100, 0x54321000)), // browns + 'liquid_carvers' -> [0x65432100, 0x54321000], // browns //unstable terrain - not generated yet - l('carvers', l(0x33003300, 0x22002200)), // checker - l('surface', l(0x33330000, 0x22220000)), // checker - l('noise', l(0x33000000, 0x22000000)), // checker - l('biomes', l(0x00330000, 0x00220000)), // checker - l('structure_references', l(0x00003300, 0x00002200)), // checker + 'carvers' -> [0x33003300, 0x22002200], // checker + 'surface' -> [0x33330000, 0x22220000], // checker + 'noise' -> [0x33000000, 0x22000000], // checker + 'biomes' -> [0x00330000, 0x00220000], // checker + 'structure_references' -> [0x00003300, 0x00002200], // checker // stable - l('structure_starts', l(0x66666600, 0x22222200)), // darkgrey + 'structure_starts' -> [0x66666600, 0x22222200], // darkgrey // not stated yet - l('empty', l(0xFF888800, 0xDD444400)), // pink + 'empty' -> [0xFF888800, 0xDD444400], // pink // proper not in memory - l(null , l(0xFFFFFF00, 0xFFFFFF00)), // hwite + null -> [0xFFFFFF00, 0xFFFFFF00], // hwite // ticket types - l('player', l(0x0000DD00, 0x00008800)), // blue - l('portal', l(0xAA00AA00, 0xAA00AA00)), // purple - l('dragon', l(0xAA008800, 0xAA008800)), // purple - l('forced', l(0xAABBFF00, 0x8899AA00)), // blue - l('light', l(0xFFFF0000, 0xBBBB0000)), // yellow - l('post_teleport', l(0xAA00AA00, 0xAA00AA00)), // purple - l('start', l(0xDDFF0000, 0xDDFF0000)), // lime, green + 'player' -> [0x0000DD00, 0x00008800], // blue + 'portal' -> [0xAA00AA00, 0xAA00AA00], // purple + 'dragon' -> [0xAA008800, 0xAA008800], // purple + 'forced' -> [0xAABBFF00, 0x8899AA00], // blue + 'light' -> [0xFFFF0000, 0xBBBB0000], // yellow + 'post_teleport' -> [0xAA00AA00, 0xAA00AA00], // purple + 'start' -> [0xDDFF0000, 0xDDFF0000], // lime, green // recent chunk requests - l('unknown', l(0xFF55FF00, 0xff99ff00)) // pink purple -); + 'unknown' -> [0xFF55FF00, 0xff99ff00] // pink purple +}; // map representing current displayed chunkloading setup global_current_setup = null; -// which blocks in the inventory represent which dimension -global_block_markers = m( - l('netherrack', 'the_nether'), - l('grass_block', 'overworld'), - l('end_stone', 'the_end') -); + +__config() -> { + 'commands' -> { + ' ' -> ['__setup_tracker', null], + '
    ' -> '__setup_tracker', + 'clear' -> '__remove_previous_setup' + }, + 'arguments' -> { + 'radius' -> { + 'type' -> 'int', + 'suggest' -> [16], + 'min' -> 8, + 'max' -> 64 + }, + 'center' -> { + 'type' -> 'columnpos' + }, + } +}; + +// for legacy support __on_player_uses_item(player, item_tuple, hand) -> ( + // which blocks in the inventory represent which dimension + global_block_markers = { + 'netherrack' -> 'the_nether', + 'grass_block' -> 'overworld', + 'end_stone' -> 'the_end' + }; if (hand != 'mainhand', return()); if (!has(global_block_markers, item_tuple:0), return()); if (item_tuple:1%16 != 0, return()); - new_setup = true; - if (global_current_setup, - new_setup = __remove_previous_setup(player) - ); - if (!new_setup, return()); - tag = nbt('{}'); - put(tag:'Enchantments','[]'); - put(tag:'Enchantments', '{lvl:1s,id:"minecraft:protection"}', 0); - inventory_set(player, player~'selected_slot', item_tuple:1, item_tuple:0, tag); - __setup_tracker(player, item_tuple); + print('setting chunkloading via item does not work anymore, use /chunk_display instead'); ); -__remove_previous_setup(new_player) -> +__remove_previous_setup() -> ( if (!global_current_setup, return()); global_running = false; - p = player(); - if (p && - global_block_markers:((item = inventory_get(p, global_current_setup:'inventory_slot')):0)==global_current_setup:'source_dimension' && - item:1 == global_current_setup:'radius' && - item:2, - inventory_set(p, global_current_setup:'inventory_slot', item:1, item:0, null); // disenchant - if( new_player == p && new_player~'selected_slot' == global_current_setup:'inventory_slot', - disabled = true - ); - ); global_current_setup = null; - !disabled + global_status_cache = {}; ); -__setup_tracker(player, item) -> +__setup_tracker(dimension, radius, columnpos) -> ( - setup = m(); - setup:'player_name' = str(player); - setup:'inventory_slot' = player ~ 'selected_slot'; - setup:'plot_dimension' = player ~ 'dimension'; - setup:'plot_center' = map(pos(player), floor(_))-l(0,1,0); - setup:'radius' = item:1; - setup:'source_dimension' = global_block_markers:(item:0); + //player = player(); + if (global_current_setup, + __remove_previous_setup() + ); + + setup = {}; + setup:'plot_dimension' = current_dimension();// player ~ 'dimension'; + setup:'plot_center' = map(pos(player()), floor(_))-[0,1,0]; + setup:'radius' = radius; + setup:'source_dimension' = dimension; multiplier = 1; if (setup:'source_dimension' != setup:'plot_dimension', multiplier = if ( @@ -102,48 +107,50 @@ __setup_tracker(player, item) -> setup:'source_dimension' == 'the_end', 0, 8); ); - setup:'source_center' = setup:'plot_center' * multiplier; + setup:'source_center' = if (columnpos, [columnpos:0, 0, columnpos:1], setup:'plot_center' * multiplier); print(setup:'source_dimension'+' around '+setup:'source_center'+' with '+setup:'radius'+' radius ('+ (2*setup:'radius'+1)^2 +' chunks)'); - l(sx, sy, sz) = setup:'source_center'; - global_status_cache = m(); + [sx, sy, sz] = setup:'source_center'; + global_status_cache = {}; loop( 2*setup:'radius'+1, dx = _ - setup:'radius'; loop( 2*setup:'radius'+1, dz = _ - setup:'radius'; - source_pos = l(sx+16*dx,sy,sz+16*dz); - global_status_cache:source_pos = l(null, 0); + source_pos = [sx+16*dx,sy,sz+16*dz]; + global_status_cache:source_pos = [null, 0]; ) ); global_current_setup = setup; global_running = true; - schedule(0, '__chunk_visualizer_tick', player); + schedule(0, '__chunk_visualizer_tick'); ); -global_status_cache = m(); +global_status_cache = {}; -__chunk_visualizer_tick(p) -> +__chunk_visualizer_tick() -> ( setup = global_current_setup; if(!setup, return()); if (!global_running, return()); - show_activity = (p~'holds':0 == 'redstone_torch'); + player = player(); + show_activity = (player~'holds':0 == 'redstone_torch'); yval = setup:'plot_center':1+16; base_update = global_update_interval; random_component = ceil(0.4*base_update); duration_max = ceil(1.5*base_update); + in_dimension( setup:'plot_dimension', - l(sx, sy, sz) = setup:'source_center'; - l(px, py, pz) = setup:'plot_center'; + [sx, sy, sz] = setup:'source_center'; + [px, py, pz] = setup:'plot_center'; source_center = setup:'source_center'; radius = setup:'radius'; source_dimension = setup:'source_dimension'; - shapes = l(); + shapes = []; now = tick_time(); loop( 2*radius+1, dx = _ - radius; loop( 2*radius+1, dz = _ - radius; changed = false; - source_pos = l(sx+16*dx,sy,sz+16*dz); + source_pos = [sx+16*dx,sy,sz+16*dz]; status = in_dimension( source_dimension, loaded_status = loaded_status(source_pos); if (loaded_status > 0, loaded_status, generation_status(source_pos)) @@ -155,29 +162,29 @@ __chunk_visualizer_tick(p) -> if (loaded_status > 0, tickets = in_dimension( source_dimension, chunk_tickets(source_pos)); for(tickets, - l(type, level) = _; + [type, level] = _; if (show_activity || type != 'unknown', status = type; ); ); ); - l(cached_status, expiry) = global_status_cache:source_pos; + [cached_status, expiry] = global_status_cache:source_pos; changed = (status != cached_status); if ( changed || (expiry < now), - global_status_cache:source_pos = l(status, now+base_update+floor(rand(random_component))); - bpos = l(dx/2, yval, dz/2); + global_status_cache:source_pos = [status, now+base_update+floor(rand(random_component))]; + bpos = [dx/2, yval, dz/2]; bcol = global_chunk_colors:status:((dx+dz)%2); - shapes += l('box', duration_max, 'from', bpos, 'to', bpos + l(0.5,0,0.5), - 'color', 0xffffff00, 'fill', bcol+128, 'follow', p, 'snap', 'xz'); + shapes += ['box', duration_max, 'from', bpos, 'to', bpos + [0.5,0,0.5], + 'color', 0xffffff00, 'fill', bcol+128, 'follow', player, 'snap', 'xz']; if (changed, pbcol = global_chunk_colors:cached_status:((dx+dz)%2); - shapes += l('box', 0, 'from', bpos, 'to', bpos + l(0.5,0,0.5), - 'color', 0xffffff00, 'fill', pbcol+128, 'follow', p, 'snap', 'xz'); + shapes += ['box', 0, 'from', bpos, 'to', bpos + [0.5,0,0.5], + 'color', 0xffffff00, 'fill', pbcol+128, 'follow', player, 'snap', 'xz']; ); ); ); ); draw_shape(shapes); ); - schedule(1, '__chunk_visualizer_tick', p) + schedule(1, '__chunk_visualizer_tick') ) \ No newline at end of file From 29afb8761ef9f100e9a859e5d38880892dbf8902 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Sun, 19 Feb 2023 01:15:42 +0100 Subject: [PATCH 060/233] cleanup overlay.sc --- .../assets/carpet/scripts/overlay.sc | 95 +++++++++---------- 1 file changed, 46 insertions(+), 49 deletions(-) diff --git a/src/main/resources/assets/carpet/scripts/overlay.sc b/src/main/resources/assets/carpet/scripts/overlay.sc index e64a32ef3c..f6933048b2 100644 --- a/src/main/resources/assets/carpet/scripts/overlay.sc +++ b/src/main/resources/assets/carpet/scripts/overlay.sc @@ -1,31 +1,31 @@ import('math', '_euclidean_sq', '_euclidean'); -global_renderers = m( - l('structures', m( - l('active', false), - l('handler', '__structure_renderer'), - l('tasks', m()), - l('range', 3), - l('max_pieces', 6) - )), - l('chunks', m( - l('active', false), - l('handler', '__chunk_renderer'), - l('tasks', m()), - l('range', 6) - )), - l('shapes', m( - l('active', false), - l('handler', '__shape_renderer'), - l('tasks', m()), - l('range', 8) - )), +global_renderers = { + 'structures' -> { + 'active' -> false, + 'handler' -> '__structure_renderer', + 'tasks' -> {}, + 'range' -> 3, + 'max_pieces' -> 6 + }, + 'chunks' -> { + 'active' -> false, + 'handler' -> '__chunk_renderer', + 'tasks' -> {}, + 'range' -> 6 + }, + 'shapes' -> { + 'active' -> false, + 'handler' -> '__shape_renderer', + 'tasks' -> {}, + 'range' -> 8 + }, 'portals' -> { 'active' -> false, 'handler' -> '__portal_renderer', 'tasks' -> {} } -); +}; global_shapes = {'sphere' -> [], 'box' -> []}; @@ -88,7 +88,7 @@ clear_shape(shape) -> clear() -> ( - for(global_renderers, global_renderers:_:'tasks' = m() ); + for(global_renderers, global_renderers:_:'tasks' = {} ); for(global_shapes, clear_shape(_)); ); @@ -109,36 +109,33 @@ __toggle(feature, renderer) -> __should_run(renderer, player_name) -> ( config = global_renderers:renderer; - if (length(config:'tasks')==0, config:'active' = false; return(l(null, null))); + if (length(config:'tasks')==0, config:'active' = false; return([null, null])); p = player(player_name); - if (!p, config:'active' = false; clear(); return(l(null, null))); + if (!p, config:'active' = false; clear(); return([null, null])); config:'active' = true; - l(p, config); + [p, config]; ); - - - __structure_renderer(player_name) -> ( - l(p, config) = __should_run('structures', player_name); + [p, config] = __should_run('structures', player_name); if (!p, return()); in_dimension(p, ppos = pos(p); - starts = m(); + starts = {}; r = config:'range'; for(range(-r,r), cx =_; for (range(-r,r), cz = _; - ref_pos = ppos + l(16*cx,0,16*cz); + ref_pos = ppos + [16*cx,0,16*cz]; for(filter(structure_references(ref_pos), has(config:'tasks':_)), name = _; for(structure_references(ref_pos, name), - starts += l(_, name); + starts += [_, name]; ) ) ) ); - for (starts, l(position, name) = _; + for (starts, [position, name] = _; structure_data = structures(position):name; if (!structure_data, continue()); // messed up references - shouldn't happen structure_pieces = structures(position, name):'pieces'; @@ -148,7 +145,7 @@ __structure_renderer(player_name) -> density = max(10, total_size/10); draw_shape('box', 15, 'from', from, 'to', to+1, 'color', 0x00FFFFFF, 'line', 3, 'fill', 0x00FFFF12); structure_pieces = slice(sort_key(structure_pieces, _euclidean_sq((_:2+_:3)/2,ppos)), 0, config:'max_pieces'); - for (structure_pieces, l(piece, direction, from, to) = _; + for (structure_pieces, [piece, direction, from, to] = _; r = 255 - floor(128 * _i/config:'max_pieces'); g = r; b = 255; @@ -164,7 +161,7 @@ __structure_renderer(player_name) -> __chunk_renderer(player_name) -> ( - l(p, config) = __should_run('chunks', player_name); + [p, config] = __should_run('chunks', player_name); if (!p, return()); in_dimension( p, // get lower corner of the chunk @@ -173,26 +170,26 @@ __chunk_renderer(player_name) -> rang = config:'range'; for(range(-rang,rang), cx =_; for (range(-rang,rang), cz = _; - ref_pos = ppos + l(16*cx,0,16*cz); + ref_pos = ppos + [16*cx,0,16*cz]; if(has(config:'tasks':'slime_chunks') && in_slime_chunk(ref_pos), player_distance = _euclidean(ppos, ref_pos); - top_00 = ref_pos + l(0, top('terrain', ref_pos)+10, 0); - top_11 = ref_pos + l(16, top('terrain', ref_pos+l(15,0,15))+10, 16); - top_10 = ref_pos + l(16, top('terrain', ref_pos+l(15, 0, 0))+10, 0); - top_01 = ref_pos + l(0, top('terrain', ref_pos+l(0, 0, 15))+10, 16); + top_00 = ref_pos + [0, top('terrain', ref_pos)+10, 0]; + top_11 = ref_pos + [16, top('terrain', ref_pos+l(15,0,15))+10, 16]; + top_10 = ref_pos + [16, top('terrain', ref_pos+l(15, 0, 0))+10, 0]; + top_01 = ref_pos + [0, top('terrain', ref_pos+l(0, 0, 15))+10, 16]; r = 30; g = 220; b = 30; a = max(0, 255-player_distance); color = a+256*(b+256*(g+256*r)); - draw_shape(l( - l('line', 15, 'from', top_00, 'to', top_10, 'color', color, 'line', 3), - l('line', 15, 'from', top_10, 'to', top_11, 'color', color, 'line', 3), - l('line', 15, 'from', top_11, 'to', top_01, 'color', color, 'line', 3), - l('line', 15, 'from', top_01, 'to', top_00, 'color', color, 'line', 3), - l('line', 15, 'from', top_00, 'to', top_11, 'color', color, 'line', 3), - l('line', 15, 'from', top_01, 'to', top_10, 'color', color, 'line', 3) - )); + draw_shape([ + ['line', 15, 'from', top_00, 'to', top_10, 'color', color, 'line', 3], + ['line', 15, 'from', top_10, 'to', top_11, 'color', color, 'line', 3], + ['line', 15, 'from', top_11, 'to', top_01, 'color', color, 'line', 3], + ['line', 15, 'from', top_01, 'to', top_00, 'color', color, 'line', 3], + ['line', 15, 'from', top_00, 'to', top_11, 'color', color, 'line', 3], + ['line', 15, 'from', top_01, 'to', top_10, 'color', color, 'line', 3] + ]); ) ) ) @@ -202,7 +199,7 @@ __chunk_renderer(player_name) -> __portal_renderer(player_name) -> ( - l(p, config) = __should_run('portals', player_name); + [p, config] = __should_run('portals', player_name); if (!p, return()); dim = p~'dimension'; shapes = []; From 23ed35a3983d1571ecdca03cc157b0d52b189071 Mon Sep 17 00:00:00 2001 From: silnarm Date: Sun, 19 Feb 2023 08:35:04 +1100 Subject: [PATCH 061/233] fake-players-falling-fix: * Fix fake players not accumulating fallDistance or ever 'hitting the ground' * Fixes #1586 (Fake player does not take fall damage) * Should Fix #1478 (fake players cannot use critical hits) * Should Fix Unreported/Unconfirmed (fake players can not engage Elytras) --- src/main/java/carpet/patches/EntityPlayerMPFake.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/main/java/carpet/patches/EntityPlayerMPFake.java b/src/main/java/carpet/patches/EntityPlayerMPFake.java index 2401d14786..4fcf391d3c 100644 --- a/src/main/java/carpet/patches/EntityPlayerMPFake.java +++ b/src/main/java/carpet/patches/EntityPlayerMPFake.java @@ -2,6 +2,7 @@ import carpet.CarpetSettings; import com.mojang.authlib.GameProfile; +import net.minecraft.core.BlockPos; import net.minecraft.core.UUIDUtil; import net.minecraft.network.chat.Component; import net.minecraft.network.protocol.PacketFlow; @@ -23,6 +24,7 @@ import net.minecraft.world.level.GameType; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.SkullBlockEntity; +import net.minecraft.world.level.block.state.BlockState; import carpet.fakes.ServerPlayerInterface; import carpet.utils.Messenger; @@ -175,4 +177,9 @@ public String getIpAddress() { return "127.0.0.1"; } + + @Override + protected void checkFallDamage(double y, boolean onGround, BlockState state, BlockPos pos) { + doCheckFallDamage(y, onGround); + } } From 146573803ce68e2fbe83555dde6e9cda16de9b47 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 22 Feb 2023 02:32:53 +0100 Subject: [PATCH 062/233] scarpet corountines idea --- .../java/carpet/script/CarpetScriptHost.java | 10 +- src/main/java/carpet/script/Context.java | 14 ++ src/main/java/carpet/script/ScriptHost.java | 5 + .../java/carpet/script/language/Loops.java | 18 ++ .../carpet/script/language/Threading.java | 59 +++++++ .../script/value/AbstractListValue.java | 10 +- .../carpet/script/value/FunctionValue.java | 12 +- .../carpet/script/value/LazyListValue.java | 7 +- .../java/carpet/script/value/ThreadValue.java | 162 +++++++++++++++++- .../java/carpet/script/value/UndefValue.java | 1 + src/main/java/carpet/script/value/Value.java | 1 + 11 files changed, 283 insertions(+), 16 deletions(-) diff --git a/src/main/java/carpet/script/CarpetScriptHost.java b/src/main/java/carpet/script/CarpetScriptHost.java index eba433779f..df94add237 100644 --- a/src/main/java/carpet/script/CarpetScriptHost.java +++ b/src/main/java/carpet/script/CarpetScriptHost.java @@ -866,7 +866,7 @@ public Value call(CommandSourceStack source, FunctionValue function, List assertAppIntegrity(function.getModule()); Context context = new CarpetContext(this, source); return function.getExpression().evalValue( - () -> function.execute(context, Context.VOID, function.getExpression(), function.getToken(), argv), + () -> function.execute(context, Context.VOID, function.getExpression(), function.getToken(), argv, null), context, Context.VOID ); @@ -903,7 +903,7 @@ public Value callUDF(BlockPos origin, CommandSourceStack source, FunctionValue f assertAppIntegrity(fun.getModule()); Context context = new CarpetContext(this, source, origin); return fun.getExpression().evalValue( - () -> fun.execute(context, Context.VOID, fun.getExpression(), fun.getToken(), argv), + () -> fun.execute(context, Context.VOID, fun.getExpression(), fun.getToken(), argv, null), context, Context.VOID); } @@ -1215,4 +1215,10 @@ public boolean issueDeprecation(String feature) } return false; } + + @Override + public boolean canSynchronouslyExecute() + { + return !scriptServer().server.isSameThread(); + } } diff --git a/src/main/java/carpet/script/Context.java b/src/main/java/carpet/script/Context.java index 35c46cd0db..01c761cab0 100644 --- a/src/main/java/carpet/script/Context.java +++ b/src/main/java/carpet/script/Context.java @@ -1,6 +1,7 @@ package carpet.script; import carpet.script.exception.InternalExpressionException; +import carpet.script.value.ThreadValue; import carpet.script.value.Value; import java.util.HashMap; @@ -30,6 +31,8 @@ public enum Type public final ScriptHost host; + private ThreadValue threadContext = null; + public Context(ScriptHost host) { this.host = host; @@ -69,10 +72,21 @@ public Set getAllVariableNames() public Context recreate() { Context ctx = duplicate(); + ctx.threadContext = threadContext; ctx.initialize(); return ctx; } + public void setThreadContext(ThreadValue callingThread) + { + this.threadContext = callingThread; + } + + public ThreadValue getThreadContext() + { + return threadContext; + } + protected void initialize() { //special variables for second order functions so we don't need to check them all the time diff --git a/src/main/java/carpet/script/ScriptHost.java b/src/main/java/carpet/script/ScriptHost.java index 3fbf31216a..91901953ce 100644 --- a/src/main/java/carpet/script/ScriptHost.java +++ b/src/main/java/carpet/script/ScriptHost.java @@ -58,6 +58,11 @@ public Path resolveScriptFile(String suffix) return scriptServer.resolveResource(suffix); } + public boolean canSynchronouslyExecute() + { + return true; + } + public static class ModuleData { Module parent; diff --git a/src/main/java/carpet/script/language/Loops.java b/src/main/java/carpet/script/language/Loops.java index ac42642b25..5d6ac58fb2 100644 --- a/src/main/java/carpet/script/language/Loops.java +++ b/src/main/java/carpet/script/language/Loops.java @@ -143,6 +143,9 @@ public static void apply(Expression expression) for (int i = 0; iterator.hasNext(); i++) { Value next = iterator.next(); + if(next == Value.EOL) { + continue; + } String variable = next.boundVariable; next.bindTo("_"); int doYouReally = i; @@ -197,6 +200,9 @@ public static void apply(Expression expression) for (int i = 0; iterator.hasNext(); i++) { Value next = iterator.next(); + if(next == Value.EOL) { + continue; + } String veriable = next.boundVariable; next.bindTo("_"); int seriously = i; @@ -254,6 +260,9 @@ public static void apply(Expression expression) for (int i = 0; iterator.hasNext(); i++) { Value next = iterator.next(); + if(next == Value.EOL) { + continue; + } String variable = next.boundVariable; next.bindTo("_"); int seriously = i; @@ -311,6 +320,9 @@ public static void apply(Expression expression) for (int i = 0; iterator.hasNext(); i++) { Value next = iterator.next(); + if(next == Value.EOL) { + continue; + } String variable = next.boundVariable; next.bindTo("_"); int seriously = i; @@ -381,6 +393,9 @@ public static void apply(Expression expression) for (int i = 0; iterator.hasNext(); i++) { Value next = iterator.next(); + if(next == Value.EOL) { + continue; + } String variable = next.boundVariable; next.bindTo("_"); int seriously = i; @@ -452,6 +467,9 @@ public static void apply(Expression expression) for (int i = 0; iterator.hasNext(); i++) { Value next = iterator.next(); + if(next == Value.EOL) { + continue; + } String variable = next.boundVariable; next.bindTo("_"); Value promiseWontChangeYou = acc; diff --git a/src/main/java/carpet/script/language/Threading.java b/src/main/java/carpet/script/language/Threading.java index a6f4a0a73d..a129d09717 100644 --- a/src/main/java/carpet/script/language/Threading.java +++ b/src/main/java/carpet/script/language/Threading.java @@ -1,5 +1,6 @@ package carpet.script.language; +import carpet.script.Context; import carpet.script.Expression; import carpet.script.argument.FunctionArgument; import carpet.script.exception.ExitStatement; @@ -128,5 +129,63 @@ public static void apply(Expression expression) } return (cc, tt) -> new NumericValue(time); // pass through for variables }); + + expression.addLazyFunction("yield", (c, t, lv) -> + { + if (c.getThreadContext() == null) + { + throw new InternalExpressionException("'yield' can only be used in a task"); + } + if (lv.isEmpty()) + { + throw new InternalExpressionException("'yield' requires at least one argument"); + } + boolean lock = lv.size() > 1 && lv.get(1).evalValue(c, Context.BOOLEAN).getBoolean(); + Value value = lv.get(0).evalValue(c); + Value ret = c.getThreadContext().ping(value, lock); + return (cc, tt) -> ret; + }); + + expression.addLazyFunction("task_send", 2, (c, t, lv) -> + { + Value threadValue = lv.get(0).evalValue(c); + if (!(threadValue instanceof ThreadValue thread)) + { + throw new InternalExpressionException("'task_next' requires a task value"); + } + if (!thread.isCoroutine) + { + throw new InternalExpressionException("'task_next' requires a coroutine task value"); + } + Value ret = lv.get(1).evalValue(c); + thread.send(ret); + return (cc, tt) -> Value.NULL; + }); + + expression.addLazyFunction("task_await", 1, (c, t, lv) -> + { + Value threadValue = lv.get(0).evalValue(c); + if (!(threadValue instanceof ThreadValue thread)) + { + throw new InternalExpressionException("'task_await' requires a task value"); + } + if (!thread.isCoroutine) + { + throw new InternalExpressionException("'task_await' requires a coroutine task value"); + } + Value ret = thread.next(); + return ret == Value.EOL ? ((cc, tt) -> Value.NULL) : ((cc, tt) -> ret); + }); + + expression.addLazyFunction("task_ready", 1, (c, t, lv) -> + { + Value threadValue = lv.get(0).evalValue(c); + if (!(threadValue instanceof ThreadValue thread)) + { + throw new InternalExpressionException("'task_ready' requires a task value"); + } + boolean ret = thread.isCoroutine && thread.hasNext(); + return (cc, tt) -> BooleanValue.of(ret); + }); } } diff --git a/src/main/java/carpet/script/value/AbstractListValue.java b/src/main/java/carpet/script/value/AbstractListValue.java index 511ccad01b..b9d917649c 100644 --- a/src/main/java/carpet/script/value/AbstractListValue.java +++ b/src/main/java/carpet/script/value/AbstractListValue.java @@ -3,13 +3,21 @@ import carpet.script.exception.InternalExpressionException; import com.google.common.collect.Lists; +import java.util.ArrayList; import java.util.List; public abstract class AbstractListValue extends Value implements Iterable { public List unpack() { - List retVal = Lists.newArrayList(iterator()); + ArrayList retVal = Lists.newArrayList(); + for (Value value : this) + { + if (value != Value.EOL) + { + retVal.add(value); + } + } fatality(); return retVal; } diff --git a/src/main/java/carpet/script/value/FunctionValue.java b/src/main/java/carpet/script/value/FunctionValue.java index 010dedecc4..1a44c42700 100644 --- a/src/main/java/carpet/script/value/FunctionValue.java +++ b/src/main/java/carpet/script/value/FunctionValue.java @@ -22,6 +22,8 @@ import net.minecraft.nbt.StringTag; import net.minecraft.nbt.Tag; +import javax.annotation.Nullable; + public class FunctionValue extends Value implements Fluff.ILazyFunction { private final Expression expression; @@ -158,7 +160,7 @@ public LazyValue callInContext(Context c, Context.Type type, List params) { try { - return execute(c, type, expression, token, params); + return execute(c, type, expression, token, params, null); } catch (ExpressionException exc) { @@ -214,10 +216,10 @@ public static List unpackArgs(List lazyParams, Context c) public LazyValue lazyEval(Context c, Context.Type type, Expression e, Tokenizer.Token t, List lazyParams) { List resolvedParams = unpackArgs(lazyParams, c); - return execute(c, type, e, t, resolvedParams); + return execute(c, type, e, t, resolvedParams, null); } - public LazyValue execute(Context c, Context.Type type, Expression e, Tokenizer.Token t, List params) + public LazyValue execute(Context c, Context.Type type, Expression e, Tokenizer.Token t, List params, @Nullable ThreadValue freshNewCallingThread) { assertArgsOk(params, fixedArgs -> { if (fixedArgs) // wrong number of args for fixed args @@ -237,6 +239,10 @@ public LazyValue execute(Context c, Context.Type type, Expression e, Tokenizer.T ); }); Context newFrame = c.recreate(); + if (freshNewCallingThread != null) + { + newFrame.setThreadContext(freshNewCallingThread); + } if (outerState != null) { diff --git a/src/main/java/carpet/script/value/LazyListValue.java b/src/main/java/carpet/script/value/LazyListValue.java index f3984ac094..5a2eba0ef8 100644 --- a/src/main/java/carpet/script/value/LazyListValue.java +++ b/src/main/java/carpet/script/value/LazyListValue.java @@ -137,7 +137,12 @@ public Iterator iterator() public List unroll() { List result = new ArrayList<>(); - this.forEachRemaining(result::add); + this.forEachRemaining(v -> { + if (v != Value.EOL) + { + result.add(v); + } + }); fatality(); return result; } diff --git a/src/main/java/carpet/script/value/ThreadValue.java b/src/main/java/carpet/script/value/ThreadValue.java index 4b1c856dfd..0922db9743 100644 --- a/src/main/java/carpet/script/value/ThreadValue.java +++ b/src/main/java/carpet/script/value/ThreadValue.java @@ -7,34 +7,39 @@ import carpet.script.exception.ExpressionException; import carpet.script.exception.InternalExpressionException; +import java.util.ArrayDeque; +import java.util.Deque; +import java.util.Iterator; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; +import java.util.concurrent.atomic.AtomicReference; import net.minecraft.nbt.Tag; -public class ThreadValue extends Value +public class ThreadValue extends LazyListValue { private final CompletableFuture taskFuture; private final long id; private static long sequence = 0L; + private final Deque coState = new ArrayDeque<>(); + private final AtomicReference coLock = new AtomicReference<>(Value.EOL); + public final boolean isCoroutine; - public ThreadValue(CompletableFuture taskFuture) + public ThreadValue(Value pool, FunctionValue function, Expression expr, Tokenizer.Token token, Context ctx, List args) { - this.taskFuture = taskFuture; this.id = sequence++; - } + this.isCoroutine = ctx.host.canSynchronouslyExecute(); + this.taskFuture = getCompletableFutureFromFunction(pool, function, expr, token, ctx, args); - public ThreadValue(Value pool, FunctionValue function, Expression expr, Tokenizer.Token token, Context ctx, List args) - { - this(getCompletableFutureFromFunction(pool, function, expr, token, ctx, args)); Thread.yield(); } - public static CompletableFuture getCompletableFutureFromFunction(Value pool, FunctionValue function, Expression expr, Tokenizer.Token token, Context ctx, List args) + public CompletableFuture getCompletableFutureFromFunction(Value pool, FunctionValue function, Expression expr, Tokenizer.Token token, Context ctx, List args) { ExecutorService executor = ctx.host.getExecutor(pool); + ThreadValue callingThread = isCoroutine ? this : null; if (executor == null) { // app is shutting down - no more threads can be spawned. @@ -45,7 +50,7 @@ public static CompletableFuture getCompletableFutureFromFunction(Value po return CompletableFuture.supplyAsync(() -> { try { - return function.execute(ctx, Context.NONE, expr, token, args).evalValue(ctx); + return function.execute(ctx, Context.NONE, expr, token, args, callingThread).evalValue(ctx); } catch (ExitStatement exit) { @@ -137,4 +142,143 @@ public String getTypeString() { return "task"; } + + @Override + public void fatality() + { + // we signal that won't be interested in the co-thread anymore + // but threads run client code, so we can't just kill them + } + + @Override + public void reset() + { + //throw new InternalExpressionException("Illegal operation on a task"); + } + + + @Override + public Iterator iterator() + { + if (!isCoroutine) + { + throw new InternalExpressionException("Cannot iterate over this task"); + } + return this; + } + + @Override + public boolean hasNext() + { + return !(coState.isEmpty() && taskFuture.isDone()); + } + + @Override + public Value next() + { + Value popped = null; + synchronized (coState) + { + while (true) + { + if (!coState.isEmpty()) + { + popped = coState.pop(); + } + else if (taskFuture.isDone()) + { + popped = Value.EOL; + } + if (popped != null) + { + break; + } + try + { + coState.wait(1); + } + catch (InterruptedException ignored) + { + } + } + coState.notifyAll(); + } + return popped; + } + + public void send(Value value) + { + synchronized (coLock) + { + coLock.set(value); + coLock.notifyAll(); + } + } + + public Value ping(Value value, boolean lock) + { + synchronized (coState) + { + try + { + if (!lock) + { + coState.add(value); + return Value.NULL; + } + while (true) + { + if (coState.isEmpty()) + { + coState.add(value); + break; + } + try + { + coState.wait(1); + } + + catch (InterruptedException ignored) + { + } + } + } + finally + { + coState.notifyAll(); + } + } + + // locked mode + + synchronized (coLock) + { + Value ret; + try + { + while (true) + { + Value current = coLock.get(); + if (current != Value.EOL) + { + ret = current; + coLock.set(Value.EOL); + break; + } + try + { + coLock.wait(1); + } + catch (InterruptedException ignored) + { + } + } + } + finally + { + coLock.notifyAll(); + } + return ret; + } + } } diff --git a/src/main/java/carpet/script/value/UndefValue.java b/src/main/java/carpet/script/value/UndefValue.java index 69c96b2727..9b6c8e79e3 100644 --- a/src/main/java/carpet/script/value/UndefValue.java +++ b/src/main/java/carpet/script/value/UndefValue.java @@ -7,6 +7,7 @@ public class UndefValue extends NullValue { public static final UndefValue UNDEF = new UndefValue(); + public static final UndefValue EOL = new UndefValue(); private RuntimeException getError() { diff --git a/src/main/java/carpet/script/value/Value.java b/src/main/java/carpet/script/value/Value.java index 2f1b89bfee..ba629111bd 100644 --- a/src/main/java/carpet/script/value/Value.java +++ b/src/main/java/carpet/script/value/Value.java @@ -25,6 +25,7 @@ public abstract class Value implements Comparable, Cloneable public static final NullValue NULL = NullValue.NULL; public static final UndefValue UNDEF = UndefValue.UNDEF; + public static final UndefValue EOL = UndefValue.EOL; public String boundVariable; From 4d842ae382a03d24a4614961e08413fddb1e21af Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 22 Feb 2023 11:24:41 +0100 Subject: [PATCH 063/233] not needed --- src/main/java/carpet/script/api/Auxiliary.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/main/java/carpet/script/api/Auxiliary.java b/src/main/java/carpet/script/api/Auxiliary.java index f08e5b0ee8..61dcd5dc94 100644 --- a/src/main/java/carpet/script/api/Auxiliary.java +++ b/src/main/java/carpet/script/api/Auxiliary.java @@ -876,10 +876,6 @@ else if (!interactable && targetBlock == null) { return; } - if (what.equalsIgnoreCase("forest_rock")) // there might be more of those - { - WorldTools.forceChunkUpdate(locator.block.getPos(), ((CarpetContext) c).level()); - } result[0] = BooleanValue.of(res); }); return result[0]; From 4c8e477f4b7d011a3eb316575ba41c0db62711d2 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 22 Feb 2023 20:22:02 +0100 Subject: [PATCH 064/233] 1.19.4-pre1 --- gradle.properties | 7 +++--- .../carpet/commands/PerimeterInfoCommand.java | 2 +- .../java/carpet/commands/PlayerCommand.java | 2 +- .../carpet/helpers/OptimizedExplosion.java | 4 ++-- src/main/java/carpet/mixins/EntityMixin.java | 3 ++- .../mixins/LivingEntity_creativeFlyMixin.java | 4 ++-- .../carpet/patches/EntityPlayerMPFake.java | 4 ++-- .../java/carpet/script/CarpetScriptHost.java | 2 +- .../java/carpet/script/ScriptCommand.java | 2 +- .../carpet/script/api/BlockIterators.java | 23 ++++++++++++------- .../java/carpet/script/api/WorldAccess.java | 2 +- .../java/carpet/script/utils/EntityTools.java | 2 +- .../carpet/script/utils/ShapesRenderer.java | 2 +- .../java/carpet/script/value/EntityValue.java | 4 ++-- .../script/value/NBTSerializableValue.java | 4 ++-- 15 files changed, 37 insertions(+), 30 deletions(-) diff --git a/gradle.properties b/gradle.properties index ec5d49ec7a..a66b7749be 100644 --- a/gradle.properties +++ b/gradle.properties @@ -2,12 +2,11 @@ org.gradle.jvmargs=-Xmx1G # Fabric Properties - # check these on https://fabricmc.net/use - # or better: https://modmuss50.me/fabric.html - minecraft_version=23w07a + # check https://fabricmc.net/develop/ + minecraft_version=1.19.4-pre1 loader_version=0.14.14 jsr305_version=3.0.2 - fabric_version=0.74.0+1.19.4 + fabric_version=0.74.1+1.19.4 # Mod Properties mod_version = 1.4.98 diff --git a/src/main/java/carpet/commands/PerimeterInfoCommand.java b/src/main/java/carpet/commands/PerimeterInfoCommand.java index 43942e7729..bc4780958b 100644 --- a/src/main/java/carpet/commands/PerimeterInfoCommand.java +++ b/src/main/java/carpet/commands/PerimeterInfoCommand.java @@ -30,7 +30,7 @@ public static void register(CommandDispatcher dispatcher, Co requires((player) -> CommandHelper.canUseCommand(player, CarpetSettings.commandPerimeterInfo)). executes( (c) -> perimeterDiagnose( c.getSource(), - new BlockPos(c.getSource().getPosition()), + BlockPos.containing(c.getSource().getPosition()), null)). then(argument("center position", BlockPosArgument.blockPos()). executes( (c) -> perimeterDiagnose( diff --git a/src/main/java/carpet/commands/PlayerCommand.java b/src/main/java/carpet/commands/PlayerCommand.java index da2c8dd7ae..d523de374f 100644 --- a/src/main/java/carpet/commands/PlayerCommand.java +++ b/src/main/java/carpet/commands/PlayerCommand.java @@ -311,7 +311,7 @@ private static int spawn(CommandContext context) throws Comm } MinecraftServer server = source.getServer(); - if (!Level.isInSpawnableBounds(new BlockPos(pos.x, pos.y, pos.z))) + if (!Level.isInSpawnableBounds(BlockPos.containing(pos.x, pos.y, pos.z))) { Messenger.m(context.getSource(), "rb Player "+playerName+" cannot be placed outside of the world"); return 0; diff --git a/src/main/java/carpet/helpers/OptimizedExplosion.java b/src/main/java/carpet/helpers/OptimizedExplosion.java index 4e5f8bfa26..d42a738f5a 100644 --- a/src/main/java/carpet/helpers/OptimizedExplosion.java +++ b/src/main/java/carpet/helpers/OptimizedExplosion.java @@ -342,7 +342,7 @@ private static void rayCalcs(Explosion e) { double d8 = eAccess.getZ(); for (float f1 = 0.3F; f > 0.0F; f -= 0.22500001F) { - BlockPos blockpos = new BlockPos(d4, d6, d8); + BlockPos blockpos = BlockPos.containing(d4, d6, d8); BlockState state = eAccess.getLevel().getBlockState(blockpos); FluidState fluidState = eAccess.getLevel().getFluidState(blockpos); @@ -534,7 +534,7 @@ private static void blastCalc(Explosion e){ boolean found = false; for (float f1 = 0.3F; f > 0.0F; f -= 0.22500001F) { - BlockPos blockpos = new BlockPos(d4, d6, d8); + BlockPos blockpos = BlockPos.containing(d4, d6, d8); BlockState state = eAccess.getLevel().getBlockState(blockpos); FluidState fluidState = eAccess.getLevel().getFluidState(blockpos); diff --git a/src/main/java/carpet/mixins/EntityMixin.java b/src/main/java/carpet/mixins/EntityMixin.java index 03cfd2c7df..6c2223adeb 100644 --- a/src/main/java/carpet/mixins/EntityMixin.java +++ b/src/main/java/carpet/mixins/EntityMixin.java @@ -4,6 +4,7 @@ import carpet.patches.EntityPlayerMPFake; import net.minecraft.util.Mth; import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.level.Level; import org.jetbrains.annotations.Nullable; import org.spongepowered.asm.mixin.Mixin; @@ -21,7 +22,7 @@ public abstract class EntityMixin implements EntityInterface @Shadow public float yRotO; - @Shadow public @Nullable abstract Entity getControllingPassenger(); + @Shadow public @Nullable abstract LivingEntity getControllingPassenger(); @Shadow public Level level; diff --git a/src/main/java/carpet/mixins/LivingEntity_creativeFlyMixin.java b/src/main/java/carpet/mixins/LivingEntity_creativeFlyMixin.java index b96c9eb19c..fea73417da 100644 --- a/src/main/java/carpet/mixins/LivingEntity_creativeFlyMixin.java +++ b/src/main/java/carpet/mixins/LivingEntity_creativeFlyMixin.java @@ -17,7 +17,7 @@ @Mixin(LivingEntity.class) public abstract class LivingEntity_creativeFlyMixin extends Entity { - @Shadow public float flyingSpeed; + @Shadow protected abstract float getFlyingSpeed(); public LivingEntity_creativeFlyMixin(EntityType type, Level world) { @@ -44,7 +44,7 @@ private void flyingAltSpeed(float slipperiness, CallbackInfoReturnable ci { Player self = (Player)(Object)(this); if (self.getAbilities().flying && !onGround) - cir.setReturnValue( flyingSpeed* (float)CarpetSettings.creativeFlySpeed); + cir.setReturnValue( getFlyingSpeed() * (float)CarpetSettings.creativeFlySpeed); } } } diff --git a/src/main/java/carpet/patches/EntityPlayerMPFake.java b/src/main/java/carpet/patches/EntityPlayerMPFake.java index 4fcf391d3c..10962c0412 100644 --- a/src/main/java/carpet/patches/EntityPlayerMPFake.java +++ b/src/main/java/carpet/patches/EntityPlayerMPFake.java @@ -69,7 +69,7 @@ public static EntityPlayerMPFake createFake(String username, MinecraftServer ser instance.teleportTo(worldIn, d0, d1, d2, (float)yaw, (float)pitch); instance.setHealth(20.0F); instance.unsetRemoved(); - instance.maxUpStep = 0.6F; + instance.setMaxUpStep(0.6F); instance.gameMode.changeGameModeForPlayer(gamemode); server.getPlayerList().broadcastAll(new ClientboundRotateHeadPacket(instance, (byte) (instance.yHeadRot * 256 / 360)), dimensionId);//instance.dimension); server.getPlayerList().broadcastAll(new ClientboundTeleportEntityPacket(instance), dimensionId);//instance.dimension); @@ -93,7 +93,7 @@ public static EntityPlayerMPFake createShadow(MinecraftServer server, ServerPlay playerShadow.connection.teleport(player.getX(), player.getY(), player.getZ(), player.getYRot(), player.getXRot()); playerShadow.gameMode.changeGameModeForPlayer(player.gameMode.getGameModeForPlayer()); ((ServerPlayerInterface) playerShadow).getActionPack().copyFrom(((ServerPlayerInterface) player).getActionPack()); - playerShadow.maxUpStep = 0.6F; + playerShadow.setMaxUpStep(0.6F); playerShadow.entityData.set(DATA_PLAYER_MODE_CUSTOMISATION, player.getEntityData().get(DATA_PLAYER_MODE_CUSTOMISATION)); diff --git a/src/main/java/carpet/script/CarpetScriptHost.java b/src/main/java/carpet/script/CarpetScriptHost.java index df94add237..e4f15faef3 100644 --- a/src/main/java/carpet/script/CarpetScriptHost.java +++ b/src/main/java/carpet/script/CarpetScriptHost.java @@ -110,7 +110,7 @@ public static CarpetScriptHost create(CarpetScriptServer scriptServer, Module mo CarpetExpression ex = new CarpetExpression(host.main, module.code(), source, new BlockPos(0, 0, 0)); ex.getExpr().asATextSource(); host.storeSource = storeSource; - ex.scriptRunCommand(host, new BlockPos(source.getPosition())); + ex.scriptRunCommand(host, BlockPos.containing(source.getPosition())); } catch (CarpetExpressionException e) { diff --git a/src/main/java/carpet/script/ScriptCommand.java b/src/main/java/carpet/script/ScriptCommand.java index 3d1e3aed14..7ea254405b 100644 --- a/src/main/java/carpet/script/ScriptCommand.java +++ b/src/main/java/carpet/script/ScriptCommand.java @@ -532,7 +532,7 @@ private static int compute(CommandContext context, String ex CarpetScriptHost host = getHost(context); return handleCall(source, host, () -> { CarpetExpression ex = new CarpetExpression(host.main, expr, source, new BlockPos(0, 0, 0)); - return ex.scriptRunCommand(host, new BlockPos(source.getPosition())); + return ex.scriptRunCommand(host, BlockPos.containing(source.getPosition())); }); } diff --git a/src/main/java/carpet/script/api/BlockIterators.java b/src/main/java/carpet/script/api/BlockIterators.java index e6061e02dc..d16c373394 100644 --- a/src/main/java/carpet/script/api/BlockIterators.java +++ b/src/main/java/carpet/script/api/BlockIterators.java @@ -50,14 +50,18 @@ public static void apply(Expression expression) if (rangeLocator.fromBlock) { range = new Vec3i( - abs(rangeLocator.vec.x - center.getX()), - abs(rangeLocator.vec.y - center.getY()), - abs(rangeLocator.vec.z - center.getZ()) + Mth.floor(abs(rangeLocator.vec.x - center.getX())), + Mth.floor(abs(rangeLocator.vec.y - center.getY())), + Mth.floor(abs(rangeLocator.vec.z - center.getZ())) ); } else { - range = new Vec3i(abs(rangeLocator.vec.x), abs(rangeLocator.vec.y), abs(rangeLocator.vec.z)); + range = new Vec3i( + Mth.floor(abs(rangeLocator.vec.x)), + Mth.floor(abs(rangeLocator.vec.y)), + Mth.floor(abs(rangeLocator.vec.z)) + ); } Vec3i upperRange = range; if (lv.size() > rangeLocator.offset + 1) // +1 cause we still need the expression @@ -66,14 +70,17 @@ public static void apply(Expression expression) if (rangeLocator.fromBlock) { upperRange = new Vec3i( - abs(rangeLocator.vec.x - center.getX()), - abs(rangeLocator.vec.y - center.getY()), - abs(rangeLocator.vec.z - center.getZ()) + Mth.floor(abs(rangeLocator.vec.x - center.getX())), + Mth.floor(abs(rangeLocator.vec.y - center.getY())), + Mth.floor(abs(rangeLocator.vec.z - center.getZ())) ); } else { - upperRange = new Vec3i(abs(rangeLocator.vec.x), abs(rangeLocator.vec.y), abs(rangeLocator.vec.z)); + upperRange = new Vec3i( + Mth.floor(abs(rangeLocator.vec.x)), + Mth.floor(abs(rangeLocator.vec.y)), + Mth.floor(abs(rangeLocator.vec.z))); } } if (llv.size() != rangeLocator.offset + 1) diff --git a/src/main/java/carpet/script/api/WorldAccess.java b/src/main/java/carpet/script/api/WorldAccess.java index 6139c2ae5a..17b23b402e 100644 --- a/src/main/java/carpet/script/api/WorldAccess.java +++ b/src/main/java/carpet/script/api/WorldAccess.java @@ -1101,7 +1101,7 @@ LivingEntity getIndirectSourceEntity() String itemString = lv.get(0).getString(); Vector3Argument locator = Vector3Argument.findIn(lv, 1); ItemInput stackArg = NBTSerializableValue.parseItem(itemString, cc.registryAccess()); - BlockPos where = new BlockPos(locator.vec); + BlockPos where = BlockPos.containing(locator.vec); // Paintings throw an exception if their direction is vertical, therefore we change the default here String facing = lv.size() > locator.offset ? lv.get(locator.offset).getString() diff --git a/src/main/java/carpet/script/utils/EntityTools.java b/src/main/java/carpet/script/utils/EntityTools.java index 232d2b2b52..2598fdbaac 100644 --- a/src/main/java/carpet/script/utils/EntityTools.java +++ b/src/main/java/carpet/script/utils/EntityTools.java @@ -17,7 +17,7 @@ public static void genericJump(Entity e) return; } float m = e.level.getBlockState(e.blockPosition()).getBlock().getJumpFactor(); - float g = e.level.getBlockState(new BlockPos(e.getX(), e.getBoundingBox().minY - 0.5000001D, e.getZ())).getBlock().getJumpFactor(); + float g = e.level.getBlockState(BlockPos.containing(e.getX(), e.getBoundingBox().minY - 0.5000001D, e.getZ())).getBlock().getJumpFactor(); float jumpVelocityMultiplier = m == 1.0D ? g : m; float jumpStrength = (0.42F * jumpVelocityMultiplier); Vec3 vec3d = e.getDeltaMovement(); diff --git a/src/main/java/carpet/script/utils/ShapesRenderer.java b/src/main/java/carpet/script/utils/ShapesRenderer.java index f3ae057c59..37738f87fa 100644 --- a/src/main/java/carpet/script/utils/ShapesRenderer.java +++ b/src/main/java/carpet/script/utils/ShapesRenderer.java @@ -381,7 +381,7 @@ public void renderLines(PoseStack matrices, Tesselator tessellator, BufferBuilde RenderSystem.enableCull(); RenderSystem.enableDepthTest(); - blockPos = new BlockPos(v1); + blockPos = BlockPos.containing(v1); int light = 0; if (client.level != null) { diff --git a/src/main/java/carpet/script/value/EntityValue.java b/src/main/java/carpet/script/value/EntityValue.java index 2acf6b82cb..2a4386ac82 100644 --- a/src/main/java/carpet/script/value/EntityValue.java +++ b/src/main/java/carpet/script/value/EntityValue.java @@ -1331,7 +1331,7 @@ else if (v instanceof final ListValue lv) { List list = lv.getItems(); Vector3Argument locator = Vector3Argument.findIn(list, 0, false, false); - pos = new BlockPos(locator.vec.x, locator.vec.y, locator.vec.z); + pos = BlockPos.containing(locator.vec.x, locator.vec.y, locator.vec.z); if (list.size() > locator.offset) { distance = (int) NumericValue.asNumber(list.get(locator.offset)).getLong(); @@ -1365,7 +1365,7 @@ else if (a instanceof final ListValue lv) { List params = lv.getItems(); Vector3Argument blockLocator = Vector3Argument.findIn(params, 0, false, false); - BlockPos pos = new BlockPos(blockLocator.vec); + BlockPos pos = BlockPos.containing(blockLocator.vec); ResourceKey world = spe.getCommandSenderWorld().dimension(); float angle = spe.getYHeadRot(); boolean forced = false; diff --git a/src/main/java/carpet/script/value/NBTSerializableValue.java b/src/main/java/carpet/script/value/NBTSerializableValue.java index 2befcd609d..2c367517ef 100644 --- a/src/main/java/carpet/script/value/NBTSerializableValue.java +++ b/src/main/java/carpet/script/value/NBTSerializableValue.java @@ -315,7 +315,7 @@ else if (e instanceof final LivingEntity le) if (v1 instanceof final ListValue lv) { List args = lv.getItems(); - BlockPos pos = new BlockPos( + BlockPos pos = BlockPos.containing( NumericValue.asNumber(args.get(0)).getDouble(), NumericValue.asNumber(args.get(1)).getDouble(), NumericValue.asNumber(args.get(2)).getDouble()); @@ -326,7 +326,7 @@ else if (e instanceof final LivingEntity le) { return !screenValue.isOpen() ? null : new InventoryLocator(screenValue.getPlayer(), screenValue.getPlayer().blockPosition(), screenValue.getInventory(), offset + 1); } - BlockPos pos = new BlockPos( + BlockPos pos = BlockPos.containing( NumericValue.asNumber(v1).getDouble(), NumericValue.asNumber(params.get(1 + offset)).getDouble(), NumericValue.asNumber(params.get(2 + offset)).getDouble()); From 78fa7d567471a0f93c2ddb034ed388790ac0c47a Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 22 Feb 2023 20:22:31 +0100 Subject: [PATCH 065/233] 1.4.99 --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index a66b7749be..c0eee5e095 100644 --- a/gradle.properties +++ b/gradle.properties @@ -9,7 +9,7 @@ org.gradle.jvmargs=-Xmx1G fabric_version=0.74.1+1.19.4 # Mod Properties - mod_version = 1.4.98 + mod_version = 1.4.99 maven_group = carpet archives_base_name = fabric-carpet From ac220a38d90717b59b4b4090608ea2d1bb7ea30e Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Mon, 27 Feb 2023 21:32:29 +0100 Subject: [PATCH 066/233] 1.19.4-pre2 --- gradle.properties | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gradle.properties b/gradle.properties index c0eee5e095..9b79baad75 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,10 +3,10 @@ org.gradle.jvmargs=-Xmx1G # Fabric Properties # check https://fabricmc.net/develop/ - minecraft_version=1.19.4-pre1 + minecraft_version=1.19.4-pre2 loader_version=0.14.14 jsr305_version=3.0.2 - fabric_version=0.74.1+1.19.4 + fabric_version=0.75.1+1.19.4 # Mod Properties mod_version = 1.4.99 From d787e0cc99104db937793b32bdd83c1697e349e0 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 1 Mar 2023 21:59:50 +0100 Subject: [PATCH 067/233] 1.19.4-pre3 --- gradle.properties | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gradle.properties b/gradle.properties index 9b79baad75..724239ab9c 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,10 +3,10 @@ org.gradle.jvmargs=-Xmx1G # Fabric Properties # check https://fabricmc.net/develop/ - minecraft_version=1.19.4-pre2 + minecraft_version=1.19.4-pre3 loader_version=0.14.14 jsr305_version=3.0.2 - fabric_version=0.75.1+1.19.4 + fabric_version=0.75.2+1.19.4 # Mod Properties mod_version = 1.4.99 From 3f19cce649a9ed2e412ee3a96b3364eeb82dd6fa Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Thu, 2 Mar 2023 22:24:29 +0100 Subject: [PATCH 068/233] fixed chest stickyness --- .../carpet/mixins/ChestBlock_customStickyMixin.java | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/src/main/java/carpet/mixins/ChestBlock_customStickyMixin.java b/src/main/java/carpet/mixins/ChestBlock_customStickyMixin.java index 23b369aeb3..6b98c1f84d 100644 --- a/src/main/java/carpet/mixins/ChestBlock_customStickyMixin.java +++ b/src/main/java/carpet/mixins/ChestBlock_customStickyMixin.java @@ -13,6 +13,8 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.ChestType; +import static net.minecraft.world.level.block.ChestBlock.getConnectedDirection; + @Mixin(ChestBlock.class) public class ChestBlock_customStickyMixin implements BlockBehaviourInterface { @@ -33,13 +35,6 @@ public boolean isStickyToNeighbor(Level level, BlockPos pos, BlockState state, B if (type == ChestType.SINGLE || neighborType == ChestType.SINGLE) { return false; } - if (type != neighborType.getOpposite()) { - return false; - } - - Direction facing = state.getValue(ChestBlock.FACING); - Direction neighborFacing = state.getValue(ChestBlock.FACING); - - return facing == neighborFacing; + return getConnectedDirection(state) == dir; } } From 93bec37dacdfcb49746f409744f62139b5447651 Mon Sep 17 00:00:00 2001 From: altrisi Date: Wed, 8 Mar 2023 13:24:37 +0100 Subject: [PATCH 069/233] Simplify and optimize bit roll operations Suggested in #1666, ran many testing to check it gives the same results --- src/main/java/carpet/script/Expression.java | 11 ++++++----- .../java/carpet/script/language/Operators.java | 16 ++-------------- 2 files changed, 8 insertions(+), 19 deletions(-) diff --git a/src/main/java/carpet/script/Expression.java b/src/main/java/carpet/script/Expression.java index a03f96cda7..7f427a40a8 100644 --- a/src/main/java/carpet/script/Expression.java +++ b/src/main/java/carpet/script/Expression.java @@ -45,10 +45,11 @@ import java.util.Map; import java.util.Set; import java.util.function.BiFunction; -import java.util.function.BinaryOperator; +import java.util.function.DoubleBinaryOperator; import java.util.function.DoubleToLongFunction; import java.util.function.DoubleUnaryOperator; import java.util.function.Function; +import java.util.function.LongBinaryOperator; import java.util.function.Supplier; import java.util.stream.Collectors; @@ -537,16 +538,16 @@ public void addMathematicalUnaryIntFunction(String name, DoubleToLongFunction fu addUnaryFunction(name, (v) -> new NumericValue(fun.applyAsLong(NumericValue.asNumber(v).getDouble()))); } - public void addMathematicalBinaryIntFunction(String name, BinaryOperator fun) + public void addMathematicalBinaryIntFunction(String name, LongBinaryOperator fun) { addBinaryFunction(name, (w, v) -> - new NumericValue(fun.apply(NumericValue.asNumber(w).getLong(), NumericValue.asNumber(v).getLong()))); + new NumericValue(fun.applyAsLong(NumericValue.asNumber(w).getLong(), NumericValue.asNumber(v).getLong()))); } - public void addMathematicalBinaryFunction(String name, BinaryOperator fun) + public void addMathematicalBinaryFunction(String name, DoubleBinaryOperator fun) { addBinaryFunction(name, (w, v) -> - new NumericValue(fun.apply(NumericValue.asNumber(w).getDouble(), NumericValue.asNumber(v).getDouble()))); + new NumericValue(fun.applyAsDouble(NumericValue.asNumber(w).getDouble(), NumericValue.asNumber(v).getDouble()))); } diff --git a/src/main/java/carpet/script/language/Operators.java b/src/main/java/carpet/script/language/Operators.java index 24a3ce2006..524aef0b28 100644 --- a/src/main/java/carpet/script/language/Operators.java +++ b/src/main/java/carpet/script/language/Operators.java @@ -315,20 +315,8 @@ public static void apply(Expression expression) expression.addFunctionalEquivalence("<=", "nondecreasing"); expression.addMathematicalBinaryIntFunction("bitwise_shift_left", (num, amount) -> num << amount); expression.addMathematicalBinaryIntFunction("bitwise_shift_right", (num, amount) -> num >> amount); - expression.addMathematicalBinaryIntFunction("bitwise_roll_left", (num, num2) -> { - long amount = num2 % 64; - long amountToRoll = 64 - amount; - long rolledBits = ((-1L) >> amountToRoll) << amountToRoll; - long rolledAmount = (num & rolledBits) >> amountToRoll; - return num << amount | rolledAmount; - }); - expression.addMathematicalBinaryIntFunction("bitwise_roll_right", (num, num2) -> { - long amount = num2 % 64; - long amountToRoll = 64 - amount; - long rolledBits = ((-1L) << amountToRoll) >> amountToRoll; - long rolledAmount = (num & rolledBits) << amountToRoll; - return num >> amount | rolledAmount; - }); + expression.addMathematicalBinaryIntFunction("bitwise_roll_left", (num, amount) -> Long.rotateLeft(num, (int)amount)); + expression.addMathematicalBinaryIntFunction("bitwise_roll_right", (num, amount) -> Long.rotateRight(num, (int)amount)); expression.addMathematicalUnaryIntFunction("bitwise_not", d -> { long num = (long) d; return ~num; From 883d887e110992b7f8a7718ec5aae2398b66a3b4 Mon Sep 17 00:00:00 2001 From: altrisi Date: Wed, 8 Mar 2023 14:07:50 +0100 Subject: [PATCH 070/233] Make `OutputConverter.convert` return `Value` This is a breaking change, but there's only one use of the function on all github The refactor also makes `register` take a function to `Value`, no one uses the one to `LazyValue` anyway. `registerToValue` is now deprecated --- .../script/annotation/AnnotationParser.java | 3 +- .../script/annotation/OutputConverter.java | 77 ++++++++----------- 2 files changed, 36 insertions(+), 44 deletions(-) diff --git a/src/main/java/carpet/script/annotation/AnnotationParser.java b/src/main/java/carpet/script/annotation/AnnotationParser.java index 2d64a0c0b3..9c5b6a66bc 100644 --- a/src/main/java/carpet/script/annotation/AnnotationParser.java +++ b/src/main/java/carpet/script/annotation/AnnotationParser.java @@ -260,7 +260,8 @@ public LazyValue apply(Context context, Context.Type t, List lazyValu Object[] params = getMethodParams(lv, context, t); try { - return outputConverter.convert(handle.invokeExact(params)); + Value result = outputConverter.convert(handle.invokeExact(params)); + return (cc, tt) -> result; } catch (Throwable e) { diff --git a/src/main/java/carpet/script/annotation/OutputConverter.java b/src/main/java/carpet/script/annotation/OutputConverter.java index 2c95b87e47..d24a3feca5 100644 --- a/src/main/java/carpet/script/annotation/OutputConverter.java +++ b/src/main/java/carpet/script/annotation/OutputConverter.java @@ -14,7 +14,7 @@ import net.minecraft.world.phys.Vec3; import org.apache.commons.lang3.ClassUtils; -import carpet.script.LazyValue; +import carpet.script.value.BooleanValue; import carpet.script.value.EntityValue; import carpet.script.value.FormattedTextValue; import carpet.script.value.NBTSerializableValue; @@ -26,40 +26,39 @@ import javax.annotation.Nullable; /** - *

    A converter from a given {@link Object} of type T into a {@link LazyValue}, used in order to convert the outputs of methods into usable Scarpet + *

    A converter from a given {@link Object} of type T into a {@link Value}, used in order to convert the outputs of methods into usable Scarpet * values.

    * * @see #register(Class, Function) - * @see #registerToValue(Class, Function) - * @param The type to convert from into a {@link LazyValue} + * @param The type to convert from into a {@link Value} */ public final class OutputConverter { private static final Map, OutputConverter> byResult = new HashMap<>(); - private static final OutputConverter VALUE = new OutputConverter<>(v -> (c, t) -> v); + private static final OutputConverter VALUE = new OutputConverter<>(Function.identity()); static { - register(LazyValue.class, Function.identity()); // Primitives are handled. Things are boxed in the process anyway, therefore - register(Boolean.class, v -> (v ? LazyValue.TRUE : LazyValue.FALSE)); // would recommend boxed outputs, so you can use null - register(Void.TYPE, v -> LazyValue.NULL); - registerToValue(Integer.class, NumericValue::of); - registerToValue(Double.class, NumericValue::of); - registerToValue(Float.class, NumericValue::of); - registerToValue(Long.class, NumericValue::of); - registerToValue(String.class, StringValue::new); - registerToValue(Entity.class, EntityValue::new); - registerToValue(Component.class, FormattedTextValue::new); - registerToValue(Tag.class, NBTSerializableValue::new); - registerToValue(BlockPos.class, ValueConversions::of); - registerToValue(Vec3.class, ValueConversions::of); - registerToValue(ItemStack.class, ValueConversions::of); - registerToValue(ResourceLocation.class, ValueConversions::of); - registerToValue(GlobalPos.class, ValueConversions::of); + // Primitives are handled. Things are boxed in the process anyway, therefore would recommend boxed outputs, so you can use null + register(Void.TYPE, v -> Value.NULL); + register(Boolean.class, BooleanValue::of); + register(Integer.class, NumericValue::new); + register(Double.class, NumericValue::of); + register(Float.class, NumericValue::of); + register(Long.class, NumericValue::new); + register(String.class, StringValue::new); + register(Entity.class, EntityValue::new); + register(Component.class, FormattedTextValue::new); + register(Tag.class, NBTSerializableValue::new); + register(BlockPos.class, ValueConversions::of); + register(Vec3.class, ValueConversions::of); + register(ItemStack.class, ValueConversions::of); + register(ResourceLocation.class, ValueConversions::of); + register(GlobalPos.class, ValueConversions::of); } - private final Function converter; + private final Function converter; - private OutputConverter(Function converter) + private OutputConverter(Function converter) { this.converter = converter; } @@ -85,27 +84,27 @@ public static OutputConverter get(Class returnType) } /** - *

    Converts the given input object into a {@link LazyValue}, to be used in return values of Scarpet functions

    + *

    Converts the given input object into a {@link Value}, to be used in return values of Scarpet functions

    * - *

    Returns {@link LazyValue#NULL} if passed a {@code null} input

    + *

    Returns {@link Value#NULL} if passed a {@code null} input

    * * @param input The value to convert * @return The converted value */ - public LazyValue convert(@Nullable T input) + public Value convert(@Nullable T input) { - return input == null ? LazyValue.NULL : converter.apply(input); + return input == null ? Value.NULL : converter.apply(input); } /** - *

    Registers a new type to be able to be used as the return value of methods, converting from inputType to a {@link LazyValue}.

    + *

    Registers a new type to be able to be used as the return value of methods, converting from inputType to a {@link Value} + * using the given function.

    * - * @see #registerToValue(Class, Function) * @param The type of the input type * @param inputType The class of T - * @param converter The function that converts the an instance of T to a {@link LazyValue} + * @param converter The function that converts the instance of T to a {@link Value} */ - public static void register(Class inputType, Function converter) + public static void register(Class inputType, Function converter) { OutputConverter instance = new OutputConverter<>(converter); if (byResult.containsKey(inputType)) @@ -116,21 +115,13 @@ public static void register(Class inputType, Function conve } /** - *

    Registers a new type to be able to be used as the return value of methods, converting from inputType to a {@link LazyValue}, with the - * converter returning a {@link Value} type.

    - * * @see #register(Class, Function) - * @param The type of the input type - * @param inputType The class of T - * @param converter The function that converts an instance of T to a {@link Value} + * + * @deprecated Just use {@link #register(Class, Function)}, it now does the same as this */ + @Deprecated public static void registerToValue(Class inputType, Function converter) { - OutputConverter instance = new OutputConverter<>(converter.andThen(v -> (c, t) -> v)); - if (byResult.containsKey(inputType)) - { - throw new IllegalArgumentException(inputType + " already has a registered OutputConverter"); - } - byResult.put(inputType, instance); + register(inputType, converter); } } From 13882146fc80f65582d75197570ee6f60b90eea2 Mon Sep 17 00:00:00 2001 From: altrisi Date: Wed, 8 Mar 2023 16:41:43 +0100 Subject: [PATCH 071/233] Simplify app store rule cleaning --- src/main/java/carpet/script/external/Carpet.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/carpet/script/external/Carpet.java b/src/main/java/carpet/script/external/Carpet.java index cc692d194b..264726772c 100644 --- a/src/main/java/carpet/script/external/Carpet.java +++ b/src/main/java/carpet/script/external/Carpet.java @@ -232,7 +232,7 @@ public String validate(@Nullable CommandSourceStack source, CarpetRule c } if (newValue.endsWith("/")) { - newValue = newValue.replaceAll("/$", ""); + newValue = newValue.substring(0, newValue.length() - 1); } AppStoreManager.setScarpetRepoLink("https://api.github.com/repos/" + newValue + "/"); return newValue; From 50470dd59af0ed9ffd73808ce3acd8c58290df74 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 8 Mar 2023 20:51:50 +0100 Subject: [PATCH 072/233] 1.19.4-pre4 --- gradle.properties | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/gradle.properties b/gradle.properties index 724239ab9c..7a4f9d1fba 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,10 +3,10 @@ org.gradle.jvmargs=-Xmx1G # Fabric Properties # check https://fabricmc.net/develop/ - minecraft_version=1.19.4-pre3 - loader_version=0.14.14 + minecraft_version=1.19.4-pre4 + loader_version=0.14.17 jsr305_version=3.0.2 - fabric_version=0.75.2+1.19.4 + fabric_version=0.75.3+1.19.4 # Mod Properties mod_version = 1.4.99 From 480153422914ee202248f84a51fc96ea99757fe3 Mon Sep 17 00:00:00 2001 From: altrisi Date: Wed, 8 Mar 2023 19:11:43 +0100 Subject: [PATCH 073/233] Sync `fillLimit` rule with the equivalent gamerule --- src/main/java/carpet/CarpetServer.java | 12 +++++ src/main/java/carpet/CarpetSettings.java | 44 ++++++++++++++++--- .../CloneCommands_fillUpdatesMixin.java | 12 ----- .../carpet/mixins/FillBiomeCommandMixin.java | 22 ---------- .../java/carpet/mixins/FillCommandMixin.java | 12 ----- src/main/resources/carpet.mixins.json | 1 - 6 files changed, 50 insertions(+), 53 deletions(-) delete mode 100644 src/main/java/carpet/mixins/FillBiomeCommandMixin.java diff --git a/src/main/java/carpet/CarpetServer.java b/src/main/java/carpet/CarpetServer.java index 27fa84e1f1..861ba61d10 100644 --- a/src/main/java/carpet/CarpetServer.java +++ b/src/main/java/carpet/CarpetServer.java @@ -23,6 +23,8 @@ import carpet.helpers.TickSpeed; import carpet.logging.LoggerRegistry; import carpet.script.CarpetScriptServer; +import carpet.api.settings.CarpetRule; +import carpet.api.settings.InvalidRuleValueException; import carpet.api.settings.SettingsManager; import carpet.logging.HUDController; import carpet.script.external.Carpet; @@ -104,6 +106,16 @@ public static void onServerLoadedWorlds(MinecraftServer minecraftServer) extensions.forEach(e -> e.onServerLoadedWorlds(minecraftServer)); // initialize scarpet rules after all extensions are loaded settingsManager.initializeScarpetRules(); + // run fillLimit rule migration now that gamerules are available + @SuppressWarnings("unchecked") + CarpetRule fillLimit = (CarpetRule) settingsManager.getCarpetRule("fillLimit"); + try + { + fillLimit.set(minecraftServer.createCommandSourceStack(), fillLimit.value()); + } catch (InvalidRuleValueException e) + { + throw new AssertionError(); + } extensions.forEach(e -> { if (e.extensionSettingsManager() != null) { diff --git a/src/main/java/carpet/CarpetSettings.java b/src/main/java/carpet/CarpetSettings.java index 97b144a06d..1fabb02e3d 100644 --- a/src/main/java/carpet/CarpetSettings.java +++ b/src/main/java/carpet/CarpetSettings.java @@ -22,6 +22,7 @@ import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.GameRules; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; @@ -626,29 +627,60 @@ private static class PushLimitLimits extends Validator { ) public static int railPowerLimit = 9; - private static class FillLimitLimits extends Validator { - @Override public Integer validate(CommandSourceStack source, CarpetRule currentRule, Integer newValue, String string) { - return (newValue>0 && newValue <= 20000000) ? newValue : null; + private static class FillLimitMigrator extends Validator + { + @Override + public Integer validate(CommandSourceStack source, CarpetRule changingRule, Integer newValue, String userInput) + { + if (source != null && source.getServer().overworld() != null) + { + GameRules.IntegerValue gamerule = source.getServer().getGameRules().getRule(GameRules.RULE_COMMAND_MODIFICATION_BLOCK_LIMIT); + if (gamerule.get() != newValue) + { + if (newValue == 32768 && changingRule.value() == newValue) // migration call, gamerule is different, update rule + { + Messenger.m(source, "g Syncing fillLimit rule with gamerule"); + newValue = gamerule.get(); + } else if (newValue != 32768 && gamerule.get() == 32768) + { + Messenger.m(source, "g Migrated value of fillLimit carpet rule to commandModificationBlockLimit gamerule"); + gamerule.set(newValue, source.getServer()); + } + } + } + return newValue; } @Override - public String description() { return "You must choose a value from 1 to 20M";} + public String description() { return "The value of this rule will be migrated to the gamerule";} } + @Rule( desc = "[Deprecated] Customizable fill/fillbiome/clone volume limit", extra = "Use vanilla gamerule instead. This setting will be removed in 1.20.0", options = {"32768", "250000", "1000000"}, category = CREATIVE, strict = false, - validate = FillLimitLimits.class + validate = FillLimitMigrator.class ) public static int fillLimit = 32768; + private static class ForceloadLimitValidator extends Validator + { + @Override + public Integer validate(CommandSourceStack source, CarpetRule currentRule, Integer newValue, String string) + { + return (newValue > 0 && newValue <= 20000000) ? newValue : null; + } + + @Override + public String description() { return "You must choose a value from 1 to 20M";} + } @Rule( desc = "Customizable forceload chunk limit", options = {"256"}, category = CREATIVE, strict = false, - validate = FillLimitLimits.class + validate = ForceloadLimitValidator.class ) public static int forceloadLimit = 256; diff --git a/src/main/java/carpet/mixins/CloneCommands_fillUpdatesMixin.java b/src/main/java/carpet/mixins/CloneCommands_fillUpdatesMixin.java index 3f9ba1dff5..7a172441e0 100644 --- a/src/main/java/carpet/mixins/CloneCommands_fillUpdatesMixin.java +++ b/src/main/java/carpet/mixins/CloneCommands_fillUpdatesMixin.java @@ -4,26 +4,14 @@ import net.minecraft.core.BlockPos; import net.minecraft.server.commands.CloneCommands; import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.level.GameRules; import net.minecraft.world.level.block.Block; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; - @Mixin(CloneCommands.class) public abstract class CloneCommands_fillUpdatesMixin { - @Redirect(method = "clone", at = @At( - value = "INVOKE", - target = "Lnet/minecraft/world/level/GameRules;getInt(Lnet/minecraft/world/level/GameRules$Key;)I" - )) - private static int redirectCloneGameRuleInt(GameRules instance, GameRules.Key key) - { - int vanilla = instance.getInt(key); - return Math.max(vanilla, CarpetSettings.fillLimit); - } - @Redirect(method = "clone", at = @At( value = "INVOKE", target = "Lnet/minecraft/server/level/ServerLevel;blockUpdated(Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/Block;)V" diff --git a/src/main/java/carpet/mixins/FillBiomeCommandMixin.java b/src/main/java/carpet/mixins/FillBiomeCommandMixin.java deleted file mode 100644 index cd4402a771..0000000000 --- a/src/main/java/carpet/mixins/FillBiomeCommandMixin.java +++ /dev/null @@ -1,22 +0,0 @@ -package carpet.mixins; - -import carpet.CarpetSettings; -import net.minecraft.server.commands.FillBiomeCommand; -import net.minecraft.world.level.GameRules; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Redirect; - -@Mixin(FillBiomeCommand.class) -public class FillBiomeCommandMixin -{ - @Redirect(method = "fill", at = @At( - value = "INVOKE", - target = "Lnet/minecraft/world/level/GameRules;getInt(Lnet/minecraft/world/level/GameRules$Key;)I" - )) - private static int redirectCloneGameRuleInt(GameRules instance, GameRules.Key key) - { - int vanilla = instance.getInt(key); - return Math.max(vanilla, CarpetSettings.fillLimit); - } -} diff --git a/src/main/java/carpet/mixins/FillCommandMixin.java b/src/main/java/carpet/mixins/FillCommandMixin.java index ab1e0a40e9..344f5ff372 100644 --- a/src/main/java/carpet/mixins/FillCommandMixin.java +++ b/src/main/java/carpet/mixins/FillCommandMixin.java @@ -4,7 +4,6 @@ import net.minecraft.core.BlockPos; import net.minecraft.server.commands.FillCommand; import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.level.GameRules; import net.minecraft.world.level.block.Block; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; @@ -13,17 +12,6 @@ @Mixin(FillCommand.class) public abstract class FillCommandMixin { - - @Redirect(method = "fillBlocks", at = @At( - value = "INVOKE", - target = "Lnet/minecraft/world/level/GameRules;getInt(Lnet/minecraft/world/level/GameRules$Key;)I" - )) - private static int redirectCloneGameRuleInt(GameRules instance, GameRules.Key key) - { - int vanilla = instance.getInt(key); - return Math.max(vanilla, CarpetSettings.fillLimit); - } - @Redirect(method = "fillBlocks", at = @At( value = "INVOKE", target = "Lnet/minecraft/server/level/ServerLevel;blockUpdated(Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/Block;)V" diff --git a/src/main/resources/carpet.mixins.json b/src/main/resources/carpet.mixins.json index 5b0bd9eb1f..79ef3e0c36 100644 --- a/src/main/resources/carpet.mixins.json +++ b/src/main/resources/carpet.mixins.json @@ -11,7 +11,6 @@ "PerfCommand_permissionMixin", "FillCommandMixin", - "FillBiomeCommandMixin", "CloneCommands_fillUpdatesMixin", "SetBlockCommand_fillUpdatesMixin", "ForceLoadCommand_forceLoadLimitMixin", From cc24f79d47ef260be12a4ca583186ea12907cfdc Mon Sep 17 00:00:00 2001 From: altrisi Date: Wed, 8 Mar 2023 20:26:43 +0100 Subject: [PATCH 074/233] Allow scarpet function name to be different to annotated method name --- .../java/carpet/script/annotation/AnnotationParser.java | 8 +++++--- .../java/carpet/script/annotation/ScarpetFunction.java | 9 +++++++++ 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/src/main/java/carpet/script/annotation/AnnotationParser.java b/src/main/java/carpet/script/annotation/AnnotationParser.java index 9c5b6a66bc..a5512d55e1 100644 --- a/src/main/java/carpet/script/annotation/AnnotationParser.java +++ b/src/main/java/carpet/script/annotation/AnnotationParser.java @@ -77,6 +77,7 @@ public final class AnnotationParser { static final int UNDEFINED_PARAMS = -2; + static final String USE_METHOD_NAME = "$METHOD_NAME_MARKER$"; private static final List functionList = new ArrayList<>(); /** @@ -172,7 +173,8 @@ private static class ParsedFunction implements TriFunction originClass, Supplier instance) { - this.name = method.getName(); + ScarpetFunction annotation = method.getAnnotation(ScarpetFunction.class); + this.name = annotation.functionName() == USE_METHOD_NAME ? method.getName() : annotation.functionName(); this.isMethodVarArgs = method.isVarArgs(); this.methodParamCount = method.getParameterCount(); @@ -199,7 +201,7 @@ private ParsedFunction(Method method, Class originClass, Supplier ins int setMaxParams = this.minParams; // Unlimited == Integer.MAX_VALUE if (this.isEffectivelyVarArgs) { - setMaxParams = method.getAnnotation(ScarpetFunction.class).maxParams(); + setMaxParams = annotation.maxParams(); if (setMaxParams == UNDEFINED_PARAMS) { throw new IllegalArgumentException("No maximum number of params specified for " + name + ", use ScarpetFunction.UNLIMITED_PARAMS for unlimited. " @@ -237,7 +239,7 @@ private ParsedFunction(Method method, Class originClass, Supplier ins } this.scarpetParamCount = this.isEffectivelyVarArgs ? -1 : this.minParams; - this.contextType = method.getAnnotation(ScarpetFunction.class).contextType(); + this.contextType = annotation.contextType(); } @Override diff --git a/src/main/java/carpet/script/annotation/ScarpetFunction.java b/src/main/java/carpet/script/annotation/ScarpetFunction.java index c4ad698f78..aada5f0b91 100644 --- a/src/main/java/carpet/script/annotation/ScarpetFunction.java +++ b/src/main/java/carpet/script/annotation/ScarpetFunction.java @@ -75,6 +75,15 @@ */ int maxParams() default AnnotationParser.UNDEFINED_PARAMS; + /** + *

    The name of the function in Scarpet, that by default will be the method name.

    + * + *

    The convention in Scarpet is to use names in snake case.

    + * + * @return The name for this function in Scarpet + */ + String functionName() default AnnotationParser.USE_METHOD_NAME; + /** *

    Defines the Context Type that will be used when evaluating arguments to annotated methods.

    * From c2ef75df6d653587565517335193dfb6a5a44a00 Mon Sep 17 00:00:00 2001 From: Ghoulboy Date: Wed, 2 Nov 2022 20:02:56 +0100 Subject: [PATCH 075/233] Removed if clauses It was functionally equivalent to the solution proposed in #1072 --- .../java/carpet/helpers/EntityPlayerActionPack.java | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/src/main/java/carpet/helpers/EntityPlayerActionPack.java b/src/main/java/carpet/helpers/EntityPlayerActionPack.java index 4e71cf1240..78c219064f 100644 --- a/src/main/java/carpet/helpers/EntityPlayerActionPack.java +++ b/src/main/java/carpet/helpers/EntityPlayerActionPack.java @@ -237,14 +237,9 @@ public void onUpdate() } } } - if (forward != 0.0F) - { - player.zza = forward*(sneaking?0.3F:1.0F); - } - if (strafing != 0.0F) - { - player.xxa = strafing*(sneaking?0.3F:1.0F); - } + float vel = sneaking?0.3F:1.0F; + player.zza = forward*vel; + player.xxa = strafing*vel; } static HitResult getTarget(ServerPlayer player) From 06bdbdaed2f012d28d2252bf0c7da8c846c3c95d Mon Sep 17 00:00:00 2001 From: altrisi Date: Wed, 8 Mar 2023 21:26:27 +0100 Subject: [PATCH 076/233] Add arithmetic shift, use logic shift in current right shift (#1670) * Add arithmetic shift, use logic shift in current * State that the MSBs will be cleared to zero in logic right shift --- docs/scarpet/language/Operators.md | 5 ++++- src/main/java/carpet/script/language/Operators.java | 3 ++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/scarpet/language/Operators.md b/docs/scarpet/language/Operators.md index ea18211bd1..605320fa85 100644 --- a/docs/scarpet/language/Operators.md +++ b/docs/scarpet/language/Operators.md @@ -308,7 +308,10 @@ only take integer values, so if the input has a decimal part, it will be discard tend to -1. - `bitwise_shift_left(num, amount)` -> Shifts all the bits of the first number `amount` spots to the left. Note that shifting more than 63 positions will result in a 0 (cos you shift out all the bits of the number) - - `bitwise_shift_right(num, amount)` -> Shifts all the bits of the first number `amount` spots to the right. Like with the above, + - `bitwise_shift_right(num, amount)` -> Shifts all the bits of the first number `amount` spots to the right logically. That is, the + `amount` most significant bits will always be set to 0. Like with the above, shifting more than 63 bits results in a 0. + - `bitwise_arithmetic_shift_right(num, amount)` -> Shifts all the bits of the first number `amount` spots to the right arithmetically. + That is, if the most significant (sign) bit is a 1, it'll propagate the one to the `amount` most significant bits. Like with the above, shifting more than 63 bits results in a 0. - `bitwise_roll_left(num, amount)` -> Rolls the bits of the first number `amount` bits to the left. This is basically where you shift out the first `amount` bits and then add them on at the back, essentially 'rolling' the number. Note that unlike with diff --git a/src/main/java/carpet/script/language/Operators.java b/src/main/java/carpet/script/language/Operators.java index 524aef0b28..a1c2d1a2d7 100644 --- a/src/main/java/carpet/script/language/Operators.java +++ b/src/main/java/carpet/script/language/Operators.java @@ -314,7 +314,8 @@ public static void apply(Expression expression) }); expression.addFunctionalEquivalence("<=", "nondecreasing"); expression.addMathematicalBinaryIntFunction("bitwise_shift_left", (num, amount) -> num << amount); - expression.addMathematicalBinaryIntFunction("bitwise_shift_right", (num, amount) -> num >> amount); + expression.addMathematicalBinaryIntFunction("bitwise_shift_right", (num, amount) -> num >>> amount); + expression.addMathematicalBinaryIntFunction("bitwise_arithmetic_shift_right", (num, amount) -> num >> amount); expression.addMathematicalBinaryIntFunction("bitwise_roll_left", (num, amount) -> Long.rotateLeft(num, (int)amount)); expression.addMathematicalBinaryIntFunction("bitwise_roll_right", (num, amount) -> Long.rotateRight(num, (int)amount)); expression.addMathematicalUnaryIntFunction("bitwise_not", d -> { From 0869cbb81cacf19a3dc4b156c90058dbdea48a00 Mon Sep 17 00:00:00 2001 From: altrisi Date: Wed, 8 Mar 2023 21:31:34 +0100 Subject: [PATCH 077/233] Move rule change event into a rule observer and outside the Java api * Move rule change event into a rule observer, without exposing it * Fix comment * Fix formatting changes added by my IDE Still trying to configure it to force correctly the new style Also remove some finals --- .../java/carpet/api/settings/CarpetRule.java | 13 ++++----- .../carpet/api/settings/SettingsManager.java | 29 ------------------- .../java/carpet/script/CarpetEventServer.java | 5 ++++ .../java/carpet/script/external/Carpet.java | 29 +++++++++++++++++++ 4 files changed, 40 insertions(+), 36 deletions(-) diff --git a/src/main/java/carpet/api/settings/CarpetRule.java b/src/main/java/carpet/api/settings/CarpetRule.java index 98fec623dd..70edf7abf6 100644 --- a/src/main/java/carpet/api/settings/CarpetRule.java +++ b/src/main/java/carpet/api/settings/CarpetRule.java @@ -100,15 +100,14 @@ default boolean strict() { /** *

    Sets this rule's value to the provided {@link String}, after first converting the {@link String} into a suitable type.

    * - *

    This methods run any required validation on the value first, and throws {@link InvalidRuleValueException} if the value is not suitable - * for this rule, regardless of whether it was impossible to convert the value to the required type, the rule doesn't accept the - * value, or the rule is immutable.

    + *

    This methods run any required validation on the value first, and throws {@link InvalidRuleValueException} if the value is not suitable for + * this rule, regardless of whether it was impossible to convert the value to the required type, the rule doesn't accept the value, or the rule is + * immutable.

    * *

    Implementations of this method must notify their {@link SettingsManager} by calling - * {@link SettingsManager#notifyRuleChanged(CommandSourceStack, CarpetRule, String)}, who is responsible for - * notifying the {@link ServerNetworkHandler} (if the rule isn't restricted from being synchronized with clients) - * and the {@link CarpetEventServer.Event#CARPET_RULE_CHANGES#onCarpetRuleChanges(CarpetRule, CommandSourceStack)} Scarpet event - * in case the value of the rule was changed because of the invocation.

    + * {@link SettingsManager#notifyRuleChanged(CommandSourceStack, CarpetRule, String)}, who is responsible for notifying the + * {@link ServerNetworkHandler} (if the rule isn't restricted from being synchronized with clients) and other rule observers like the Scarpet + * event, in case the value of the rule was changed because of the invocation.

    * *

    This method must not throw any exception other than the documented {@link InvalidRuleValueException}.

    * diff --git a/src/main/java/carpet/api/settings/SettingsManager.java b/src/main/java/carpet/api/settings/SettingsManager.java index 8dec18d6ed..b8a0430f72 100644 --- a/src/main/java/carpet/api/settings/SettingsManager.java +++ b/src/main/java/carpet/api/settings/SettingsManager.java @@ -25,8 +25,6 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -import carpet.script.CarpetEventServer; -import carpet.script.value.StringValue; import com.google.common.collect.Sets; import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.arguments.StringArgumentType; @@ -259,39 +257,12 @@ public void addCarpetRule(CarpetRule rule) { rules.put(rule.name(), rule); } - public static final CarpetEventServer.Event CARPET_RULE_CHANGES = new CarpetEventServer.Event("carpet_rule_changes", 2, true) - { - @Override - public void handleAny(final Object ... args) - { - final CarpetRule rule = (CarpetRule) args[0]; - final CommandSourceStack source = (CommandSourceStack) args[1]; - final String id = rule.settingsManager().identifier(); - final String namespace; - if (!id.equals("carpet")) - { - namespace = id + ":"; - } - else - { - namespace = ""; - } - handler.call( - () -> Arrays.asList( - new StringValue(namespace + rule.name()), - new StringValue(RuleHelper.toRuleString(rule.value())) - ), () -> source - ); - } - }; - public void notifyRuleChanged(CommandSourceStack source, CarpetRule rule, String userInput) { observers.forEach(observer -> observer.ruleChanged(source, rule, userInput)); staticObservers.forEach(observer -> observer.ruleChanged(source, rule, userInput)); ServerNetworkHandler.updateRuleWithConnectedClients(rule); switchScarpetRuleIfNeeded(source, rule); //TODO move into rule - if (CARPET_RULE_CHANGES.isNeeded()) CARPET_RULE_CHANGES.handleAny(rule, source); } /** diff --git a/src/main/java/carpet/script/CarpetEventServer.java b/src/main/java/carpet/script/CarpetEventServer.java index be9b154091..4a13a869e1 100644 --- a/src/main/java/carpet/script/CarpetEventServer.java +++ b/src/main/java/carpet/script/CarpetEventServer.java @@ -437,6 +437,11 @@ public static List publicEvents(CarpetScriptServer server) return events; } + static + { + Carpet.initCarpetEvents(); + } + public static final Event START = new Event("server_starts", 0, true) { @Override diff --git a/src/main/java/carpet/script/external/Carpet.java b/src/main/java/carpet/script/external/Carpet.java index 264726772c..700e7b97c4 100644 --- a/src/main/java/carpet/script/external/Carpet.java +++ b/src/main/java/carpet/script/external/Carpet.java @@ -11,6 +11,7 @@ import carpet.logging.HUDController; import carpet.network.ServerNetworkHandler; import carpet.patches.EntityPlayerMPFake; +import carpet.script.CarpetEventServer; import carpet.script.CarpetExpression; import carpet.script.CarpetScriptHost; import carpet.script.CarpetScriptServer; @@ -40,6 +41,7 @@ import java.nio.file.FileVisitOption; import java.nio.file.Files; import java.nio.file.Path; +import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; @@ -214,6 +216,33 @@ public static void assertRequirementMet(CarpetScriptHost host, String requiredMo throw new LoadException(String.format("%s requires a version of mod '%s' matching '%s', which is missing!", host.getName(), requiredModId, stringPredicate)); } + // to be ran once during CarpetEventServer.Event static init + public static void initCarpetEvents() { + CarpetEventServer.Event carpetRuleChanges = new CarpetEventServer.Event("carpet_rule_changes", 2, true) + { + @Override + public void handleAny(final Object... args) + { + CarpetRule rule = (CarpetRule) args[0]; + CommandSourceStack source = (CommandSourceStack) args[1]; + String id = rule.settingsManager().identifier(); + String namespace; + if (!id.equals("carpet")) + { + namespace = id + ":"; + } else + { + namespace = ""; + } + handler.call(() -> Arrays.asList( + new StringValue(namespace + rule.name()), + new StringValue(RuleHelper.toRuleString(rule.value())) + ), () -> source); + } + }; + SettingsManager.registerGlobalRuleObserver((source, changedRule, userInput) -> carpetRuleChanges.handleAny(changedRule, source)); + } + public static class ScarpetAppStoreValidator extends Validator { @Override From d5aea22d12bdc73484e2179edd1b24b6fe331431 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Thu, 9 Mar 2023 20:12:22 +0100 Subject: [PATCH 078/233] 1.19.4-rc1 --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 7a4f9d1fba..a006f2b1bd 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,7 +3,7 @@ org.gradle.jvmargs=-Xmx1G # Fabric Properties # check https://fabricmc.net/develop/ - minecraft_version=1.19.4-pre4 + minecraft_version=1.19.4-rc1 loader_version=0.14.17 jsr305_version=3.0.2 fabric_version=0.75.3+1.19.4 From 40c789b2f90961718f27ba7985b98c8fd21e67f7 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Fri, 10 Mar 2023 19:08:24 +0100 Subject: [PATCH 079/233] 1.19.4-rc2 --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index a006f2b1bd..138c820b98 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,7 +3,7 @@ org.gradle.jvmargs=-Xmx1G # Fabric Properties # check https://fabricmc.net/develop/ - minecraft_version=1.19.4-rc1 + minecraft_version=1.19.4-rc2 loader_version=0.14.17 jsr305_version=3.0.2 fabric_version=0.75.3+1.19.4 From 8c09946bef16b6eb2f038fd0c7dec59f7fe98e78 Mon Sep 17 00:00:00 2001 From: James McCulloch Date: Tue, 14 Mar 2023 12:02:41 -0400 Subject: [PATCH 080/233] Fix fake players not teleporting to unloaded chunks (#1665) * fake-players-teleporting-fix: * Fix fake players not being moved on the chunkmap when teleporting * Fixes #1190 (Player bots cannot be teleported to unloaded chunks) * fake-players-teleporting-fix: * add missing access widener * Revert "fake-players-teleporting-fix:" This reverts commit 617702fca14035913103140d2e04fa33065bf628. * fake-players-teleporting-fix: * access awaitingTeleport in a nicer way * fake-players-teleporting-fix: * access awaitingTeleport in a nicer way --- .../ServerGamePacketListenerImplAccessor.java | 11 ++++++++ .../patches/NetHandlerPlayServerFake.java | 25 +++++++++++++++++++ src/main/resources/carpet.mixins.json | 1 + 3 files changed, 37 insertions(+) create mode 100644 src/main/java/carpet/mixins/ServerGamePacketListenerImplAccessor.java diff --git a/src/main/java/carpet/mixins/ServerGamePacketListenerImplAccessor.java b/src/main/java/carpet/mixins/ServerGamePacketListenerImplAccessor.java new file mode 100644 index 0000000000..b199fe8ed1 --- /dev/null +++ b/src/main/java/carpet/mixins/ServerGamePacketListenerImplAccessor.java @@ -0,0 +1,11 @@ +package carpet.mixins; + +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Accessor; + +@Mixin(ServerGamePacketListenerImpl.class) +public interface ServerGamePacketListenerImplAccessor { + @Accessor("awaitingTeleport") + public int getAwaitingTeleport(); +} diff --git a/src/main/java/carpet/patches/NetHandlerPlayServerFake.java b/src/main/java/carpet/patches/NetHandlerPlayServerFake.java index d62dc27ee4..16f583c96e 100644 --- a/src/main/java/carpet/patches/NetHandlerPlayServerFake.java +++ b/src/main/java/carpet/patches/NetHandlerPlayServerFake.java @@ -1,11 +1,16 @@ package carpet.patches; +import carpet.mixins.ServerGamePacketListenerImplAccessor; import net.minecraft.network.Connection; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.contents.TranslatableContents; import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ServerboundAcceptTeleportationPacket; +import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; import net.minecraft.server.MinecraftServer; import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.world.entity.RelativeMovement; +import java.util.Set; public class NetHandlerPlayServerFake extends ServerGamePacketListenerImpl { @@ -27,6 +32,26 @@ public void disconnect(Component message) ((EntityPlayerMPFake) player).kill(message); } } + private boolean hasSpawned = false; + + @Override + public void teleport(double d, double e, double f, float g, float h, Set set) + { + super.teleport(d, e, f, g, h, set); + + handleAcceptTeleportPacket( + new ServerboundAcceptTeleportationPacket( ((ServerGamePacketListenerImplAccessor)this).getAwaitingTeleport() ) + ); + + if (!hasSpawned) { + hasSpawned = true; + } else { + handleMovePlayer( + new ServerboundMovePlayerPacket.PosRot(player.getX(), player.getY(), player.getZ(), player.getYRot(), player.getXRot(), false) + ); + } + } + } diff --git a/src/main/resources/carpet.mixins.json b/src/main/resources/carpet.mixins.json index 79ef3e0c36..fab1e6d264 100644 --- a/src/main/resources/carpet.mixins.json +++ b/src/main/resources/carpet.mixins.json @@ -8,6 +8,7 @@ "MobCategory_spawnMixin", "Commands_customCommandsMixin", "ServerGamePacketListenerImplMixin", + "ServerGamePacketListenerImplAccessor", "PerfCommand_permissionMixin", "FillCommandMixin", From 8307794f196d2521e9d9fac80e9e496a63fc98fb Mon Sep 17 00:00:00 2001 From: James McCulloch Date: Tue, 14 Mar 2023 12:07:27 -0400 Subject: [PATCH 081/233] Fix fake players not being able to respawn for exiting the end (#1664) * Allow fake players to respawn (to return from the end) * Fixes #1645 (Fake players get stuck in the end exit portal) * fix up some imports --- .../mixins/PlayerList_fakePlayersMixin.java | 13 +++++++++- .../carpet/patches/EntityPlayerMPFake.java | 24 ++++++++++++++++++- 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/src/main/java/carpet/mixins/PlayerList_fakePlayersMixin.java b/src/main/java/carpet/mixins/PlayerList_fakePlayersMixin.java index 9b9d6cc2b7..0792a72803 100644 --- a/src/main/java/carpet/mixins/PlayerList_fakePlayersMixin.java +++ b/src/main/java/carpet/mixins/PlayerList_fakePlayersMixin.java @@ -1,8 +1,10 @@ package carpet.mixins; +import com.mojang.authlib.GameProfile; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.Connection; import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.network.ServerGamePacketListenerImpl; import net.minecraft.server.players.PlayerList; @@ -44,4 +46,13 @@ private ServerGamePacketListenerImpl replaceNetworkHandler(MinecraftServer serve return new ServerGamePacketListenerImpl(this.server, clientConnection, playerIn); } } -} \ No newline at end of file + + @Redirect(method = "respawn", at = @At(value = "NEW", target = "net/minecraft/server/level/ServerPlayer")) + public ServerPlayer makePlayerForRespawn(MinecraftServer minecraftServer, ServerLevel serverLevel, GameProfile gameProfile, ServerPlayer serverPlayer, boolean bl) + { + if (serverPlayer instanceof EntityPlayerMPFake) { + return EntityPlayerMPFake.respawnFake(minecraftServer, serverLevel, gameProfile); + } + return new ServerPlayer(minecraftServer, serverLevel, gameProfile); + } +} diff --git a/src/main/java/carpet/patches/EntityPlayerMPFake.java b/src/main/java/carpet/patches/EntityPlayerMPFake.java index 10962c0412..f66d1b73e5 100644 --- a/src/main/java/carpet/patches/EntityPlayerMPFake.java +++ b/src/main/java/carpet/patches/EntityPlayerMPFake.java @@ -9,6 +9,7 @@ import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket; import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket; import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket; +import net.minecraft.network.protocol.game.ServerboundClientCommandPacket; import net.minecraft.resources.ResourceKey; import net.minecraft.server.MinecraftServer; import net.minecraft.server.TickTask; @@ -104,6 +105,11 @@ public static EntityPlayerMPFake createShadow(MinecraftServer server, ServerPlay return playerShadow; } + public static EntityPlayerMPFake respawnFake(MinecraftServer server, ServerLevel level, GameProfile profile) + { + return new EntityPlayerMPFake(server, level, profile, false); + } + private EntityPlayerMPFake(MinecraftServer server, ServerLevel worldIn, GameProfile profile, boolean shadow) { super(server, worldIn, profile); @@ -137,7 +143,6 @@ public void tick() { this.connection.resetPosition(); this.getLevel().getChunkSource().move(this); - hasChangedDimension(); //<- causes hard crash but would need to be done to enable portals // not as of 1.17 } try { @@ -182,4 +187,21 @@ public String getIpAddress() protected void checkFallDamage(double y, boolean onGround, BlockState state, BlockPos pos) { doCheckFallDamage(y, onGround); } + + @Override + public Entity changeDimension(ServerLevel serverLevel) + { + super.changeDimension(serverLevel); + if (wonGame) { + ServerboundClientCommandPacket p = new ServerboundClientCommandPacket(ServerboundClientCommandPacket.Action.PERFORM_RESPAWN); + connection.handleClientCommand(p); + } + + // If above branch was taken, *this* has been removed and replaced, the new instance has been set + // on 'our' connection (which is now theirs, but we still have a ref). + if (connection.player.isChangingDimension()) { + connection.player.hasChangedDimension(); + } + return connection.player; + } } From 9c82ca0ed4f712a19bfc5d56c6dfe57318a100e4 Mon Sep 17 00:00:00 2001 From: altrisi Date: Tue, 14 Mar 2023 17:16:29 +0100 Subject: [PATCH 082/233] Bump versions to 1.19.4 --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 138c820b98..418168ddb7 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,7 +3,7 @@ org.gradle.jvmargs=-Xmx1G # Fabric Properties # check https://fabricmc.net/develop/ - minecraft_version=1.19.4-rc2 + minecraft_version=1.19.4 loader_version=0.14.17 jsr305_version=3.0.2 fabric_version=0.75.3+1.19.4 From d9ec575205bd9143f036a865ee624de7451d4ca9 Mon Sep 17 00:00:00 2001 From: altrisi Date: Tue, 14 Mar 2023 17:42:25 +0100 Subject: [PATCH 083/233] Carpet 1.4.100 --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 418168ddb7..e221459a73 100644 --- a/gradle.properties +++ b/gradle.properties @@ -9,7 +9,7 @@ org.gradle.jvmargs=-Xmx1G fabric_version=0.75.3+1.19.4 # Mod Properties - mod_version = 1.4.99 + mod_version = 1.4.100 maven_group = carpet archives_base_name = fabric-carpet From 5a4f3ab877f32ef57db67a87fa5f943f2ea6f565 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Tue, 14 Mar 2023 17:38:12 +0000 Subject: [PATCH 084/233] Merge docs for 'Carpet Mod 1.4.100 for Minecraft 1.19.4' --- docs/scarpet/Full.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/scarpet/Full.md b/docs/scarpet/Full.md index c6de52acc9..9195f08b31 100644 --- a/docs/scarpet/Full.md +++ b/docs/scarpet/Full.md @@ -635,7 +635,10 @@ only take integer values, so if the input has a decimal part, it will be discard tend to -1. - `bitwise_shift_left(num, amount)` -> Shifts all the bits of the first number `amount` spots to the left. Note that shifting more than 63 positions will result in a 0 (cos you shift out all the bits of the number) - - `bitwise_shift_right(num, amount)` -> Shifts all the bits of the first number `amount` spots to the right. Like with the above, + - `bitwise_shift_right(num, amount)` -> Shifts all the bits of the first number `amount` spots to the right logically. That is, the + `amount` most significant bits will always be set to 0. Like with the above, shifting more than 63 bits results in a 0. + - `bitwise_arithmetic_shift_right(num, amount)` -> Shifts all the bits of the first number `amount` spots to the right arithmetically. + That is, if the most significant (sign) bit is a 1, it'll propagate the one to the `amount` most significant bits. Like with the above, shifting more than 63 bits results in a 0. - `bitwise_roll_left(num, amount)` -> Rolls the bits of the first number `amount` bits to the left. This is basically where you shift out the first `amount` bits and then add them on at the back, essentially 'rolling' the number. Note that unlike with From 8aae23c983474d9f2d2ab1ebe5821bb06e8f072a Mon Sep 17 00:00:00 2001 From: replaceitem <40722305+replaceitem@users.noreply.github.com> Date: Wed, 15 Mar 2023 14:46:31 +0100 Subject: [PATCH 085/233] Fixed AnnotationParser not detecting `USE_METHOD_NAME` (#1677) --- src/main/java/carpet/script/annotation/AnnotationParser.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/carpet/script/annotation/AnnotationParser.java b/src/main/java/carpet/script/annotation/AnnotationParser.java index a5512d55e1..19d1128de2 100644 --- a/src/main/java/carpet/script/annotation/AnnotationParser.java +++ b/src/main/java/carpet/script/annotation/AnnotationParser.java @@ -174,7 +174,7 @@ private static class ParsedFunction implements TriFunction originClass, Supplier instance) { ScarpetFunction annotation = method.getAnnotation(ScarpetFunction.class); - this.name = annotation.functionName() == USE_METHOD_NAME ? method.getName() : annotation.functionName(); + this.name = USE_METHOD_NAME.equals(annotation.functionName()) ? method.getName() : annotation.functionName(); this.isMethodVarArgs = method.isVarArgs(); this.methodParamCount = method.getParameterCount(); From f98c2409be42de6b0b02c2499244dfddd2e9a1e6 Mon Sep 17 00:00:00 2001 From: altrisi Date: Thu, 16 Mar 2023 17:36:44 +0100 Subject: [PATCH 086/233] Simplify enum options creation Slightly optimizes it --- src/main/java/carpet/settings/ParsedRule.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/carpet/settings/ParsedRule.java b/src/main/java/carpet/settings/ParsedRule.java index 5da52f34fe..66860f3d23 100644 --- a/src/main/java/carpet/settings/ParsedRule.java +++ b/src/main/java/carpet/settings/ParsedRule.java @@ -216,7 +216,7 @@ else if (this.type == String.class && categories.contains(RuleCategory.COMMAND)) } else if (this.type.isEnum()) { - this.options = Arrays.stream(this.type.getEnumConstants()).map(e -> ((Enum) e).name().toLowerCase(Locale.ROOT)).collect(Collectors.toUnmodifiableList()); + this.options = Arrays.stream(this.type.getEnumConstants()).map(e -> ((Enum) e).name().toLowerCase(Locale.ROOT)).toList(); converter0 = str -> { try { @SuppressWarnings({"unchecked", "rawtypes"}) // Raw necessary because of signature. Unchecked because compiler doesn't know T extends Enum From cde3ffced2edac8dd891c4caea1947b9a55db348 Mon Sep 17 00:00:00 2001 From: Ghoulboy Date: Sun, 19 Mar 2023 18:56:12 +0100 Subject: [PATCH 087/233] Fixing `/player botname stop` with relation to *fake* player movement (#1683) --- .../java/carpet/helpers/EntityPlayerActionPack.java | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/main/java/carpet/helpers/EntityPlayerActionPack.java b/src/main/java/carpet/helpers/EntityPlayerActionPack.java index 78c219064f..ca1fcb3757 100644 --- a/src/main/java/carpet/helpers/EntityPlayerActionPack.java +++ b/src/main/java/carpet/helpers/EntityPlayerActionPack.java @@ -6,6 +6,7 @@ import java.util.Map; import java.util.TreeMap; +import carpet.patches.EntityPlayerMPFake; import carpet.script.utils.Tracer; import net.minecraft.commands.arguments.EntityAnchorArgument; import net.minecraft.core.BlockPos; @@ -238,8 +239,13 @@ public void onUpdate() } } float vel = sneaking?0.3F:1.0F; - player.zza = forward*vel; - player.xxa = strafing*vel; + // The != 0.0F checks are needed given else real players can't control minecarts, however it works with fakes and else they don't stop immediately + if (forward != 0.0F || player instanceof EntityPlayerMPFake) { + player.zza = forward * vel; + } + if (strafing != 0.0F || player instanceof EntityPlayerMPFake) { + player.xxa = strafing * vel; + } } static HitResult getTarget(ServerPlayer player) From 1ad927da9dabe6e77b067fca6cac676695b67d20 Mon Sep 17 00:00:00 2001 From: altrisi Date: Sun, 19 Mar 2023 19:34:00 +0100 Subject: [PATCH 088/233] Up priority in `MinecraftServer_tickspeedMixin` --- src/main/java/carpet/mixins/MinecraftServer_tickspeedMixin.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/carpet/mixins/MinecraftServer_tickspeedMixin.java b/src/main/java/carpet/mixins/MinecraftServer_tickspeedMixin.java index c581492d9d..aaae5b0f40 100644 --- a/src/main/java/carpet/mixins/MinecraftServer_tickspeedMixin.java +++ b/src/main/java/carpet/mixins/MinecraftServer_tickspeedMixin.java @@ -24,7 +24,7 @@ import java.util.function.BooleanSupplier; -@Mixin(MinecraftServer.class) +@Mixin(value = MinecraftServer.class, priority = Integer.MAX_VALUE - 10) public abstract class MinecraftServer_tickspeedMixin extends ReentrantBlockableEventLoop { @Shadow private volatile boolean running; From d2d7d6f421e6d02c7789a530757de1b0e4d28ba1 Mon Sep 17 00:00:00 2001 From: altrisi Date: Sun, 19 Mar 2023 19:34:44 +0100 Subject: [PATCH 089/233] Carpet 1.4.101 --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index e221459a73..44c8687959 100644 --- a/gradle.properties +++ b/gradle.properties @@ -9,7 +9,7 @@ org.gradle.jvmargs=-Xmx1G fabric_version=0.75.3+1.19.4 # Mod Properties - mod_version = 1.4.100 + mod_version = 1.4.101 maven_group = carpet archives_base_name = fabric-carpet From 4e94d1bc15d2f2ee79f2c977201550ebd3a8a7d0 Mon Sep 17 00:00:00 2001 From: altrisi Date: Mon, 20 Mar 2023 18:51:20 +0100 Subject: [PATCH 090/233] Enforce 1.19.4 in dependency resolution --- src/main/resources/fabric.mod.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json index 3a32771aa2..99cf3df732 100644 --- a/src/main/resources/fabric.mod.json +++ b/src/main/resources/fabric.mod.json @@ -33,7 +33,7 @@ "accessWidener" : "carpet.accesswidener", "depends": { - "minecraft": "1.19.*", + "minecraft": "1.19.4", "fabricloader": ">=0.14.6", "java": ">=17" } From f1586b380948bf25699849418660c36d40343802 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 22 Mar 2023 18:27:44 +0100 Subject: [PATCH 091/233] 23w12a --- gradle.properties | 8 ++--- .../carpet/helpers/QuasiConnectivity.java | 4 +-- .../mixins/PistonBaseBlock_qcMixin.java | 4 +-- .../PistonBaseBlock_rotatorBlockMixin.java | 3 +- ...VibrationConfig_sculkSensorRangeMixin.java | 21 +++++++++++++ .../mixins/SculkSensorBlock_rangeMixin.java | 30 ------------------- .../java/carpet/script/value/ScreenValue.java | 2 -- src/main/resources/carpet.mixins.json | 2 +- src/main/resources/fabric.mod.json | 2 +- 9 files changed, 33 insertions(+), 43 deletions(-) create mode 100644 src/main/java/carpet/mixins/SculkSensorBlockEntityVibrationConfig_sculkSensorRangeMixin.java delete mode 100644 src/main/java/carpet/mixins/SculkSensorBlock_rangeMixin.java diff --git a/gradle.properties b/gradle.properties index 44c8687959..b80d507e06 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,10 +3,10 @@ org.gradle.jvmargs=-Xmx1G # Fabric Properties # check https://fabricmc.net/develop/ - minecraft_version=1.19.4 - loader_version=0.14.17 + minecraft_version=23w12a + loader_version=0.14.18 jsr305_version=3.0.2 - fabric_version=0.75.3+1.19.4 + fabric_version=0.76.0+1.19.4 # Mod Properties mod_version = 1.4.101 @@ -17,7 +17,7 @@ org.gradle.jvmargs=-Xmx1G # The Curseforge versions "names" or ids for the main branch (comma separated: 1.16.4,1.16.5) # This is needed because CF uses too vague names for prereleases and release candidates # Can also be the version ID directly coming from https://minecraft.curseforge.com/api/game/versions?token=[API_TOKEN] - release-curse-versions = Minecraft 1.19:1.19.4 + release-curse-versions = Minecraft 1.20:1.20-Snapshot # Whether or not to build another branch on release release-extra-branch = false # The name of the second branch to release diff --git a/src/main/java/carpet/helpers/QuasiConnectivity.java b/src/main/java/carpet/helpers/QuasiConnectivity.java index 0f8d221e34..5bc411acf3 100644 --- a/src/main/java/carpet/helpers/QuasiConnectivity.java +++ b/src/main/java/carpet/helpers/QuasiConnectivity.java @@ -3,11 +3,11 @@ import carpet.CarpetSettings; import net.minecraft.core.BlockPos; -import net.minecraft.world.level.Level; +import net.minecraft.world.level.SignalGetter; public class QuasiConnectivity { - public static boolean hasQuasiSignal(Level level, BlockPos pos) { + public static boolean hasQuasiSignal(SignalGetter level, BlockPos pos) { for (int i = 1; i <= CarpetSettings.quasiConnectivity; i++) { BlockPos above = pos.above(i); diff --git a/src/main/java/carpet/mixins/PistonBaseBlock_qcMixin.java b/src/main/java/carpet/mixins/PistonBaseBlock_qcMixin.java index 87ee3b4f1d..f0b3d1a8ff 100644 --- a/src/main/java/carpet/mixins/PistonBaseBlock_qcMixin.java +++ b/src/main/java/carpet/mixins/PistonBaseBlock_qcMixin.java @@ -1,5 +1,6 @@ package carpet.mixins; +import net.minecraft.world.level.SignalGetter; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -9,7 +10,6 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; -import net.minecraft.world.level.Level; import net.minecraft.world.level.block.piston.PistonBaseBlock; @Mixin(PistonBaseBlock.class) @@ -23,7 +23,7 @@ public class PistonBaseBlock_qcMixin { target = "Lnet/minecraft/core/BlockPos;above()Lnet/minecraft/core/BlockPos;" ) ) - private void carpet_checkQuasiSignal(Level level, BlockPos pos, Direction facing, CallbackInfoReturnable cir) { + private void carpet_checkQuasiSignal(SignalGetter level, BlockPos pos, Direction facing, CallbackInfoReturnable cir) { cir.setReturnValue(QuasiConnectivity.hasQuasiSignal(level, pos)); } } diff --git a/src/main/java/carpet/mixins/PistonBaseBlock_rotatorBlockMixin.java b/src/main/java/carpet/mixins/PistonBaseBlock_rotatorBlockMixin.java index d857d6b0fa..225a7eb44c 100644 --- a/src/main/java/carpet/mixins/PistonBaseBlock_rotatorBlockMixin.java +++ b/src/main/java/carpet/mixins/PistonBaseBlock_rotatorBlockMixin.java @@ -4,6 +4,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.level.Level; +import net.minecraft.world.level.SignalGetter; import net.minecraft.world.level.block.piston.PistonBaseBlock; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -11,7 +12,7 @@ @Mixin(PistonBaseBlock.class) public abstract class PistonBaseBlock_rotatorBlockMixin implements PistonBlockInterface { - @Shadow protected abstract boolean getNeighborSignal(Level world_1, BlockPos blockPos_1, Direction direction_1); + @Shadow protected abstract boolean getNeighborSignal(SignalGetter world_1, BlockPos blockPos_1, Direction direction_1); @Override public boolean publicShouldExtend(Level world_1, BlockPos blockPos_1, Direction direction_1) diff --git a/src/main/java/carpet/mixins/SculkSensorBlockEntityVibrationConfig_sculkSensorRangeMixin.java b/src/main/java/carpet/mixins/SculkSensorBlockEntityVibrationConfig_sculkSensorRangeMixin.java new file mode 100644 index 0000000000..8d3174544c --- /dev/null +++ b/src/main/java/carpet/mixins/SculkSensorBlockEntityVibrationConfig_sculkSensorRangeMixin.java @@ -0,0 +1,21 @@ +package carpet.mixins; + + +import carpet.CarpetSettings; +import net.minecraft.world.level.block.entity.SculkSensorBlockEntity; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(SculkSensorBlockEntity.VibrationConfig.class) +public class SculkSensorBlockEntityVibrationConfig_sculkSensorRangeMixin +{ + @Inject(method = "getListenerRadius", at = @At("HEAD"), cancellable = true) + private void sculkSensorRange(CallbackInfoReturnable cir) + { + if (CarpetSettings.sculkSensorRange != SculkSensorBlockEntity.VibrationConfig.LISTENER_RANGE) { + cir.setReturnValue(CarpetSettings.sculkSensorRange); + } + } +} diff --git a/src/main/java/carpet/mixins/SculkSensorBlock_rangeMixin.java b/src/main/java/carpet/mixins/SculkSensorBlock_rangeMixin.java deleted file mode 100644 index 3e0a20776f..0000000000 --- a/src/main/java/carpet/mixins/SculkSensorBlock_rangeMixin.java +++ /dev/null @@ -1,30 +0,0 @@ -package carpet.mixins; - -import carpet.CarpetSettings; -import net.minecraft.world.level.block.SculkSensorBlock; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -@Mixin(SculkSensorBlock.class) -public class SculkSensorBlock_rangeMixin { - - @Shadow - @Final - private int listenerRange; - - - @Inject( - method = "getListenerRange()I", - at = @At("HEAD"), - cancellable = true - ) - public void getListenerRange(CallbackInfoReturnable cir) { - if (CarpetSettings.sculkSensorRange != this.listenerRange) { - cir.setReturnValue(CarpetSettings.sculkSensorRange); - } - } -} diff --git a/src/main/java/carpet/script/value/ScreenValue.java b/src/main/java/carpet/script/value/ScreenValue.java index 9eb2702f9e..366738e787 100644 --- a/src/main/java/carpet/script/value/ScreenValue.java +++ b/src/main/java/carpet/script/value/ScreenValue.java @@ -45,7 +45,6 @@ import net.minecraft.world.inventory.GrindstoneMenu; import net.minecraft.world.inventory.HopperMenu; import net.minecraft.world.inventory.LecternMenu; -import net.minecraft.world.inventory.LegacySmithingMenu; import net.minecraft.world.inventory.LoomMenu; import net.minecraft.world.inventory.MerchantMenu; import net.minecraft.world.inventory.ShulkerBoxMenu; @@ -99,7 +98,6 @@ public class ScreenValue extends Value screenHandlerFactories.put("loom", LoomMenu::new); screenHandlerFactories.put("merchant", MerchantMenu::new); screenHandlerFactories.put("shulker_box", (syncId, playerInventory) -> new ShulkerBoxMenu(syncId, playerInventory, new SimpleContainer(9 * 3))); - screenHandlerFactories.put("smithing_legacy", LegacySmithingMenu::new); screenHandlerFactories.put("smithing", SmithingMenu::new); screenHandlerFactories.put("smoker", SmokerMenu::new); screenHandlerFactories.put("stonecutter", StonecutterMenu::new); diff --git a/src/main/resources/carpet.mixins.json b/src/main/resources/carpet.mixins.json index fab1e6d264..3d82268967 100644 --- a/src/main/resources/carpet.mixins.json +++ b/src/main/resources/carpet.mixins.json @@ -179,7 +179,7 @@ "TheEndGatewayBlockEntity_creativeNoClipMixin", "LivingEntity_creativeFlyMixin", "ChunkMap_creativePlayersLoadChunksMixin", - "SculkSensorBlock_rangeMixin", + "SculkSensorBlockEntityVibrationConfig_sculkSensorRangeMixin", "CollectingNeighborUpdaterAccessor", "BlockBehaviour_customStickyMixin", diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json index 99cf3df732..944cd5c868 100644 --- a/src/main/resources/fabric.mod.json +++ b/src/main/resources/fabric.mod.json @@ -33,7 +33,7 @@ "accessWidener" : "carpet.accesswidener", "depends": { - "minecraft": "1.19.4", + "minecraft": ">1.19.4", "fabricloader": ">=0.14.6", "java": ">=17" } From 972ed09d6b2d1035831e17561bc4515c7326caba Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 22 Mar 2023 18:51:32 +0100 Subject: [PATCH 092/233] 1.4.102 --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index b80d507e06..45982bc29e 100644 --- a/gradle.properties +++ b/gradle.properties @@ -9,7 +9,7 @@ org.gradle.jvmargs=-Xmx1G fabric_version=0.76.0+1.19.4 # Mod Properties - mod_version = 1.4.101 + mod_version = 1.4.102 maven_group = carpet archives_base_name = fabric-carpet From 23b7aa0945427c8898287d50fa95782f0dce6bfb Mon Sep 17 00:00:00 2001 From: altrisi Date: Thu, 23 Mar 2023 18:09:55 +0100 Subject: [PATCH 093/233] Require Loader 0.14.18 --- src/main/resources/fabric.mod.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json index 944cd5c868..0cc0168dfe 100644 --- a/src/main/resources/fabric.mod.json +++ b/src/main/resources/fabric.mod.json @@ -34,7 +34,7 @@ "depends": { "minecraft": ">1.19.4", - "fabricloader": ">=0.14.6", + "fabricloader": ">=0.14.18", "java": ">=17" } } From 4171f9b784e2d89395b6726c1ea5b10b0315e668 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 29 Mar 2023 18:44:12 +0200 Subject: [PATCH 094/233] 23w13a --- gradle.properties | 2 +- .../BlockBehaviourBlockStateBase_mixin.java | 27 +++++++++++++++++++ ...ingAmethystBlock_movableAmethystMixin.java | 5 ---- .../java/carpet/script/api/WorldAccess.java | 2 +- src/main/java/carpet/script/utils/Colors.java | 1 - src/main/java/carpet/utils/BlockInfo.java | 2 +- src/main/resources/carpet.mixins.json | 1 + 7 files changed, 31 insertions(+), 9 deletions(-) create mode 100644 src/main/java/carpet/mixins/BlockBehaviourBlockStateBase_mixin.java diff --git a/gradle.properties b/gradle.properties index 45982bc29e..8b851f25e2 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,7 +3,7 @@ org.gradle.jvmargs=-Xmx1G # Fabric Properties # check https://fabricmc.net/develop/ - minecraft_version=23w12a + minecraft_version=23w13a loader_version=0.14.18 jsr305_version=3.0.2 fabric_version=0.76.0+1.19.4 diff --git a/src/main/java/carpet/mixins/BlockBehaviourBlockStateBase_mixin.java b/src/main/java/carpet/mixins/BlockBehaviourBlockStateBase_mixin.java new file mode 100644 index 0000000000..3e512d97e9 --- /dev/null +++ b/src/main/java/carpet/mixins/BlockBehaviourBlockStateBase_mixin.java @@ -0,0 +1,27 @@ +package carpet.mixins; + +import carpet.CarpetSettings; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.BuddingAmethystBlock; +import net.minecraft.world.level.block.state.BlockBehaviour; +import net.minecraft.world.level.material.PushReaction; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(BlockBehaviour.BlockStateBase.class) +public abstract class BlockBehaviourBlockStateBase_mixin +{ + @Shadow public abstract Block getBlock(); + + @Inject(method = "getPistonPushReaction", at = @At("HEAD"), cancellable = true) + private void onGetPistonPushReaction(CallbackInfoReturnable cir) + { + if (CarpetSettings.movableAmethyst && getBlock() instanceof BuddingAmethystBlock) + { + cir.setReturnValue(PushReaction.NORMAL); + } + } +} diff --git a/src/main/java/carpet/mixins/BuddingAmethystBlock_movableAmethystMixin.java b/src/main/java/carpet/mixins/BuddingAmethystBlock_movableAmethystMixin.java index 6984a67376..b8f3d45f7c 100644 --- a/src/main/java/carpet/mixins/BuddingAmethystBlock_movableAmethystMixin.java +++ b/src/main/java/carpet/mixins/BuddingAmethystBlock_movableAmethystMixin.java @@ -26,11 +26,6 @@ public BuddingAmethystBlock_movableAmethystMixin(Properties settings) { super(settings); } - @Inject(at = @At("HEAD"), method = "getPistonPushReaction(Lnet/minecraft/world/level/block/state/BlockState;)Lnet/minecraft/world/level/material/PushReaction;", cancellable = true) - void getPistonBehavior(BlockState state, CallbackInfoReturnable cir) { - if (CarpetSettings.movableAmethyst) cir.setReturnValue(PushReaction.NORMAL); - } - @Override public void playerDestroy(Level world, Player player, BlockPos pos, BlockState state, @Nullable BlockEntity blockEntity, ItemStack stack) { super.playerDestroy(world, player, pos, state, blockEntity, stack); diff --git a/src/main/java/carpet/script/api/WorldAccess.java b/src/main/java/carpet/script/api/WorldAccess.java index 17b23b402e..43e55faaf1 100644 --- a/src/main/java/carpet/script/api/WorldAccess.java +++ b/src/main/java/carpet/script/api/WorldAccess.java @@ -524,7 +524,7 @@ else if (!("any".equals(statusString))) booleanStateTest(c, "liquid", lv, (s, p) -> !s.getFluidState().isEmpty())); expression.addContextFunction("flammable", -1, (c, t, lv) -> - booleanStateTest(c, "flammable", lv, (s, p) -> s.getMaterial().isFlammable())); + booleanStateTest(c, "flammable", lv, (s, p) -> s.ignitedByLava())); expression.addContextFunction("transparent", -1, (c, t, lv) -> booleanStateTest(c, "transparent", lv, (s, p) -> !s.getMaterial().isSolid())); diff --git a/src/main/java/carpet/script/utils/Colors.java b/src/main/java/carpet/script/utils/Colors.java index a746a7d7bc..d6c01eac92 100644 --- a/src/main/java/carpet/script/utils/Colors.java +++ b/src/main/java/carpet/script/utils/Colors.java @@ -182,7 +182,6 @@ public class Colors entry(Material.SPONGE , "sponge" ), entry(Material.SHULKER_SHELL , "shulker" ), entry(Material.WOOD , "wood" ), - entry(Material.NETHER_WOOD , "nether_wood" ), entry(Material.BAMBOO_SAPLING , "shoots" ), entry(Material.BAMBOO , "bamboo" ), entry(Material.WOOL , "wool" ), diff --git a/src/main/java/carpet/utils/BlockInfo.java b/src/main/java/carpet/utils/BlockInfo.java index c000acdc73..755e41034f 100644 --- a/src/main/java/carpet/utils/BlockInfo.java +++ b/src/main/java/carpet/utils/BlockInfo.java @@ -61,7 +61,7 @@ public static List blockInfo(BlockPos pos, ServerLevel world) lst.add(Messenger.s(String.format(" - Blocks movement on land: %s", !state.isPathfindable(world,pos, PathComputationType.LAND)))); lst.add(Messenger.s(String.format(" - Blocks movement in air: %s", !state.isPathfindable(world,pos, PathComputationType.AIR)))); lst.add(Messenger.s(String.format(" - Blocks movement in liquids: %s", !state.isPathfindable(world,pos, PathComputationType.WATER)))); - lst.add(Messenger.s(String.format(" - Can burn: %s", material.isFlammable()))); + lst.add(Messenger.s(String.format(" - Can burn: %s", state.ignitedByLava()))); lst.add(Messenger.s(String.format(" - Requires a tool: %s", !material.isReplaceable()))); //?maybe lst.add(Messenger.s(String.format(" - Hardness: %.2f", state.getDestroySpeed(world, pos)))); lst.add(Messenger.s(String.format(" - Blast resistance: %.2f", block.getExplosionResistance()))); diff --git a/src/main/resources/carpet.mixins.json b/src/main/resources/carpet.mixins.json index 3d82268967..537aed2a01 100644 --- a/src/main/resources/carpet.mixins.json +++ b/src/main/resources/carpet.mixins.json @@ -183,6 +183,7 @@ "CollectingNeighborUpdaterAccessor", "BlockBehaviour_customStickyMixin", + "BlockBehaviourBlockStateBase_mixin", "ChainBlock_customStickyMixin", "ChestBlock_customStickyMixin", "HoneyBlock_customStickyMixin", From ea693d0fb11eb5d39b89e33b0ae295ef6f137290 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 29 Mar 2023 19:42:18 +0200 Subject: [PATCH 095/233] 1.4.103 --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 8b851f25e2..796a39dfb1 100644 --- a/gradle.properties +++ b/gradle.properties @@ -9,7 +9,7 @@ org.gradle.jvmargs=-Xmx1G fabric_version=0.76.0+1.19.4 # Mod Properties - mod_version = 1.4.102 + mod_version = 1.4.103 maven_group = carpet archives_base_name = fabric-carpet From e7c02ea21a0fb8d12a3ede5af45e14395a549e6c Mon Sep 17 00:00:00 2001 From: James McCulloch Date: Sat, 1 Apr 2023 21:22:04 +1100 Subject: [PATCH 096/233] shadow-single-player-owner-fix: (#1687) * shadow-single-player-owner-fix: * Disallow shadowing a single player server owner. Fixes #1442 * shadow-single-player-owner-fix: * Remove some redundant calls --- src/main/java/carpet/commands/PlayerCommand.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/java/carpet/commands/PlayerCommand.java b/src/main/java/carpet/commands/PlayerCommand.java index d523de374f..61434b7774 100644 --- a/src/main/java/carpet/commands/PlayerCommand.java +++ b/src/main/java/carpet/commands/PlayerCommand.java @@ -365,6 +365,10 @@ private static int shadow(CommandContext context) Messenger.m(context.getSource(), "r Cannot shadow fake players"); return 0; } + if (player.getServer().isSingleplayerOwner(player.getGameProfile())) { + Messenger.m(context.getSource(), "r Cannot shadow single-player server owner"); + return 0; + } ServerPlayer sendingPlayer = null; try { From 591153458c24d60343851ee1ff0ee1d4d69743e9 Mon Sep 17 00:00:00 2001 From: altrisi Date: Sat, 1 Apr 2023 12:34:54 +0200 Subject: [PATCH 097/233] Fix `/player` `look` and `turn` commands reversing yaw and pitch (#1689) * Fix `/player` `look` and `turn` commands reversing yaw and pitch * Translate a comment to mojmap and update it a bit --- .../java/carpet/commands/PlayerCommand.java | 6 ++--- .../helpers/EntityPlayerActionPack.java | 27 +++++++++---------- 2 files changed, 16 insertions(+), 17 deletions(-) diff --git a/src/main/java/carpet/commands/PlayerCommand.java b/src/main/java/carpet/commands/PlayerCommand.java index 61434b7774..66c6e1a2db 100644 --- a/src/main/java/carpet/commands/PlayerCommand.java +++ b/src/main/java/carpet/commands/PlayerCommand.java @@ -87,9 +87,9 @@ public static void register(CommandDispatcher dispatcher, Co .then(argument("direction", RotationArgument.rotation()) .executes(c -> manipulate(c, ap -> ap.look(RotationArgument.getRotation(c, "direction").getRotation(c.getSource()))))) ).then(literal("turn") - .then(literal("left").executes(c -> manipulate(c, ap -> ap.turn(-90, 0)))) - .then(literal("right").executes(c -> manipulate(c, ap -> ap.turn(90, 0)))) - .then(literal("back").executes(c -> manipulate(c, ap -> ap.turn(180, 0)))) + .then(literal("left").executes(c -> manipulate(c, ap -> ap.turn(0, -90)))) + .then(literal("right").executes(c -> manipulate(c, ap -> ap.turn(0, 90)))) + .then(literal("back").executes(c -> manipulate(c, ap -> ap.turn(0, 180)))) .then(argument("rotation", RotationArgument.rotation()) .executes(c -> manipulate(c, ap -> ap.turn(RotationArgument.getRotation(c, "rotation").getRotation(c.getSource()))))) ).then(literal("move").executes(c -> manipulate(c, EntityPlayerActionPack::stopMovement)) diff --git a/src/main/java/carpet/helpers/EntityPlayerActionPack.java b/src/main/java/carpet/helpers/EntityPlayerActionPack.java index ca1fcb3757..6c1aec4674 100644 --- a/src/main/java/carpet/helpers/EntityPlayerActionPack.java +++ b/src/main/java/carpet/helpers/EntityPlayerActionPack.java @@ -112,27 +112,26 @@ public EntityPlayerActionPack setStrafing(float value) } public EntityPlayerActionPack look(Direction direction) { - switch (direction) + return switch (direction) { - case NORTH: return look(180, 0); - case SOUTH: return look(0, 0); - case EAST: return look(-90, 0); - case WEST: return look(90, 0); - case UP: return look(player.getYRot(), -90); - case DOWN: return look(player.getYRot(), 90); - } - return this; + case NORTH -> look(0, 180); + case SOUTH -> look(0, 0); + case EAST -> look(0, -90); + case WEST -> look(0, 90); + case UP -> look(-90, player.getYRot()); + case DOWN -> look(90, player.getYRot()); + }; } public EntityPlayerActionPack look(Vec2 rotation) { return look(rotation.x, rotation.y); } - public EntityPlayerActionPack look(float yaw, float pitch) + public EntityPlayerActionPack look(float pitch, float yaw) { - player.setYRot(yaw % 360); //setYaw player.setXRot(Mth.clamp(pitch, -90, 90)); // setPitch - // maybe player.setPositionAndAngles(player.x, player.y, player.z, yaw, MathHelper.clamp(pitch,-90.0F, 90.0F)); + player.setYRot(yaw % 360); //setYaw + // maybe player.moveTo(player.getX(), player.getY(), player.getZ(), yaw, Mth.clamp(pitch,-90.0F, 90.0F)); return this; } @@ -142,9 +141,9 @@ public EntityPlayerActionPack lookAt(Vec3 position) return this; } - public EntityPlayerActionPack turn(float yaw, float pitch) + public EntityPlayerActionPack turn(float pitch, float yaw) { - return look(player.getYRot() + yaw, player.getXRot() + pitch); + return look(player.getXRot() + pitch, player.getYRot() + yaw); } public EntityPlayerActionPack turn(Vec2 rotation) From b055b05263bd2564c5583848ab9b6e5e879f5b19 Mon Sep 17 00:00:00 2001 From: altrisi Date: Sun, 2 Apr 2023 12:51:22 +0200 Subject: [PATCH 098/233] Revert "Fix `/player` `look` and `turn` commands reversing yaw and pitch (#1689)" This reverts commit 591153458c24d60343851ee1ff0ee1d4d69743e9. --- .../java/carpet/commands/PlayerCommand.java | 6 ++--- .../helpers/EntityPlayerActionPack.java | 27 ++++++++++--------- 2 files changed, 17 insertions(+), 16 deletions(-) diff --git a/src/main/java/carpet/commands/PlayerCommand.java b/src/main/java/carpet/commands/PlayerCommand.java index 66c6e1a2db..61434b7774 100644 --- a/src/main/java/carpet/commands/PlayerCommand.java +++ b/src/main/java/carpet/commands/PlayerCommand.java @@ -87,9 +87,9 @@ public static void register(CommandDispatcher dispatcher, Co .then(argument("direction", RotationArgument.rotation()) .executes(c -> manipulate(c, ap -> ap.look(RotationArgument.getRotation(c, "direction").getRotation(c.getSource()))))) ).then(literal("turn") - .then(literal("left").executes(c -> manipulate(c, ap -> ap.turn(0, -90)))) - .then(literal("right").executes(c -> manipulate(c, ap -> ap.turn(0, 90)))) - .then(literal("back").executes(c -> manipulate(c, ap -> ap.turn(0, 180)))) + .then(literal("left").executes(c -> manipulate(c, ap -> ap.turn(-90, 0)))) + .then(literal("right").executes(c -> manipulate(c, ap -> ap.turn(90, 0)))) + .then(literal("back").executes(c -> manipulate(c, ap -> ap.turn(180, 0)))) .then(argument("rotation", RotationArgument.rotation()) .executes(c -> manipulate(c, ap -> ap.turn(RotationArgument.getRotation(c, "rotation").getRotation(c.getSource()))))) ).then(literal("move").executes(c -> manipulate(c, EntityPlayerActionPack::stopMovement)) diff --git a/src/main/java/carpet/helpers/EntityPlayerActionPack.java b/src/main/java/carpet/helpers/EntityPlayerActionPack.java index 6c1aec4674..ca1fcb3757 100644 --- a/src/main/java/carpet/helpers/EntityPlayerActionPack.java +++ b/src/main/java/carpet/helpers/EntityPlayerActionPack.java @@ -112,26 +112,27 @@ public EntityPlayerActionPack setStrafing(float value) } public EntityPlayerActionPack look(Direction direction) { - return switch (direction) + switch (direction) { - case NORTH -> look(0, 180); - case SOUTH -> look(0, 0); - case EAST -> look(0, -90); - case WEST -> look(0, 90); - case UP -> look(-90, player.getYRot()); - case DOWN -> look(90, player.getYRot()); - }; + case NORTH: return look(180, 0); + case SOUTH: return look(0, 0); + case EAST: return look(-90, 0); + case WEST: return look(90, 0); + case UP: return look(player.getYRot(), -90); + case DOWN: return look(player.getYRot(), 90); + } + return this; } public EntityPlayerActionPack look(Vec2 rotation) { return look(rotation.x, rotation.y); } - public EntityPlayerActionPack look(float pitch, float yaw) + public EntityPlayerActionPack look(float yaw, float pitch) { - player.setXRot(Mth.clamp(pitch, -90, 90)); // setPitch player.setYRot(yaw % 360); //setYaw - // maybe player.moveTo(player.getX(), player.getY(), player.getZ(), yaw, Mth.clamp(pitch,-90.0F, 90.0F)); + player.setXRot(Mth.clamp(pitch, -90, 90)); // setPitch + // maybe player.setPositionAndAngles(player.x, player.y, player.z, yaw, MathHelper.clamp(pitch,-90.0F, 90.0F)); return this; } @@ -141,9 +142,9 @@ public EntityPlayerActionPack lookAt(Vec3 position) return this; } - public EntityPlayerActionPack turn(float pitch, float yaw) + public EntityPlayerActionPack turn(float yaw, float pitch) { - return look(player.getXRot() + pitch, player.getYRot() + yaw); + return look(player.getYRot() + yaw, player.getXRot() + pitch); } public EntityPlayerActionPack turn(Vec2 rotation) From 2d0a8e11da96799ebe49ddbae934eb479260d12b Mon Sep 17 00:00:00 2001 From: altrisi Date: Sun, 2 Apr 2023 13:26:46 +0200 Subject: [PATCH 099/233] Keep the other improvements from #1689 --- .../helpers/EntityPlayerActionPack.java | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/src/main/java/carpet/helpers/EntityPlayerActionPack.java b/src/main/java/carpet/helpers/EntityPlayerActionPack.java index ca1fcb3757..c133aa6e90 100644 --- a/src/main/java/carpet/helpers/EntityPlayerActionPack.java +++ b/src/main/java/carpet/helpers/EntityPlayerActionPack.java @@ -112,16 +112,15 @@ public EntityPlayerActionPack setStrafing(float value) } public EntityPlayerActionPack look(Direction direction) { - switch (direction) + return switch (direction) { - case NORTH: return look(180, 0); - case SOUTH: return look(0, 0); - case EAST: return look(-90, 0); - case WEST: return look(90, 0); - case UP: return look(player.getYRot(), -90); - case DOWN: return look(player.getYRot(), 90); - } - return this; + case NORTH -> look(180, 0); + case SOUTH -> look(0, 0); + case EAST -> look(-90, 0); + case WEST -> look(90, 0); + case UP -> look(player.getYRot(), -90); + case DOWN -> look(player.getYRot(), 90); + }; } public EntityPlayerActionPack look(Vec2 rotation) { @@ -132,7 +131,7 @@ public EntityPlayerActionPack look(float yaw, float pitch) { player.setYRot(yaw % 360); //setYaw player.setXRot(Mth.clamp(pitch, -90, 90)); // setPitch - // maybe player.setPositionAndAngles(player.x, player.y, player.z, yaw, MathHelper.clamp(pitch,-90.0F, 90.0F)); + // maybe player.moveTo(player.getX(), player.getY(), player.getZ(), yaw, Mth.clamp(pitch,-90.0F, 90.0F)); return this; } From 73260a220c8a118227715b9b824ca5523af03b0a Mon Sep 17 00:00:00 2001 From: altrisi Date: Sun, 2 Apr 2023 21:23:42 +0200 Subject: [PATCH 100/233] Use `EnumMap` in the action pack --- src/main/java/carpet/helpers/EntityPlayerActionPack.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/carpet/helpers/EntityPlayerActionPack.java b/src/main/java/carpet/helpers/EntityPlayerActionPack.java index c133aa6e90..53916b95df 100644 --- a/src/main/java/carpet/helpers/EntityPlayerActionPack.java +++ b/src/main/java/carpet/helpers/EntityPlayerActionPack.java @@ -1,10 +1,10 @@ package carpet.helpers; import carpet.fakes.ServerPlayerInterface; +import java.util.EnumMap; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.TreeMap; import carpet.patches.EntityPlayerMPFake; import carpet.script.utils.Tracer; @@ -36,7 +36,7 @@ public class EntityPlayerActionPack { private final ServerPlayer player; - private final Map actions = new TreeMap<>(); + private final Map actions = new EnumMap<>(ActionType.class); private BlockPos currentBlock; private int blockHitDelay; From 5fcfc7aa8dfcfe69708e26ab34c2db5c589659d9 Mon Sep 17 00:00:00 2001 From: altrisi Date: Sun, 2 Apr 2023 21:54:44 +0200 Subject: [PATCH 101/233] Tiny drive-by cleanup of action pack's `onUpdate` --- src/main/java/carpet/helpers/EntityPlayerActionPack.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/java/carpet/helpers/EntityPlayerActionPack.java b/src/main/java/carpet/helpers/EntityPlayerActionPack.java index 53916b95df..2df403feb1 100644 --- a/src/main/java/carpet/helpers/EntityPlayerActionPack.java +++ b/src/main/java/carpet/helpers/EntityPlayerActionPack.java @@ -213,19 +213,20 @@ public EntityPlayerActionPack dismount() public void onUpdate() { Map actionAttempts = new HashMap<>(); - actions.entrySet().removeIf((e) -> e.getValue().done); + actions.values().removeIf(e -> e.done); for (Map.Entry e : actions.entrySet()) { + ActionType type = e.getKey(); Action action = e.getValue(); // skipping attack if use was successful - if (!(actionAttempts.getOrDefault(ActionType.USE, false) && e.getKey() == ActionType.ATTACK)) + if (!(actionAttempts.getOrDefault(ActionType.USE, false) && type == ActionType.ATTACK)) { Boolean actionStatus = action.tick(this, e.getKey()); if (actionStatus != null) - actionAttempts.put(e.getKey(), actionStatus); + actionAttempts.put(type, actionStatus); } // optionally retrying use after successful attack and unsuccessful use - if ( e.getKey() == ActionType.ATTACK + if (type == ActionType.ATTACK && actionAttempts.getOrDefault(ActionType.ATTACK, false) && !actionAttempts.getOrDefault(ActionType.USE, true) ) { From 431b0e68de9021a0afe6dc0d1d6916ed735382fa Mon Sep 17 00:00:00 2001 From: altrisi Date: Mon, 3 Apr 2023 18:41:09 +0200 Subject: [PATCH 102/233] Cleanup to the `/player` command (#1690) * Small cleanup to `/player` command There should be no changes to users * Use extracted `source` variable * Inline another single-use small function * Inline another trivial helper * Import inner classes of the ActionPack * Rename `literalargumentbuilder` variable * Compact unnecessary three lines into one * Inline `source.getServer` and pass `Vec3` to `createFake` This gets outside of "just" the command, but it's fine * Unpick name length constant * Pass `Vec3` directly to `BlockPos.containing` --- .../java/carpet/commands/PlayerCommand.java | 193 +++++++----------- .../carpet/patches/EntityPlayerMPFake.java | 7 +- 2 files changed, 80 insertions(+), 120 deletions(-) diff --git a/src/main/java/carpet/commands/PlayerCommand.java b/src/main/java/carpet/commands/PlayerCommand.java index 61434b7774..9cfbd1ec16 100644 --- a/src/main/java/carpet/commands/PlayerCommand.java +++ b/src/main/java/carpet/commands/PlayerCommand.java @@ -1,6 +1,8 @@ package carpet.commands; import carpet.helpers.EntityPlayerActionPack; +import carpet.helpers.EntityPlayerActionPack.Action; +import carpet.helpers.EntityPlayerActionPack.ActionType; import carpet.CarpetSettings; import carpet.fakes.ServerPlayerInterface; import carpet.patches.EntityPlayerMPFake; @@ -17,6 +19,7 @@ import net.minecraft.commands.CommandBuildContext; import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.arguments.DimensionArgument; +import net.minecraft.commands.arguments.GameModeArgument; import net.minecraft.commands.arguments.coordinates.RotationArgument; import net.minecraft.commands.arguments.coordinates.Vec3Argument; import net.minecraft.core.BlockPos; @@ -31,7 +34,6 @@ import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec2; import net.minecraft.world.phys.Vec3; -import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; @@ -44,26 +46,22 @@ public class PlayerCommand { - // TODO: allow any order like execute public static void register(CommandDispatcher dispatcher, CommandBuildContext commandBuildContext) { - final String[] gamemodeStrings = Arrays.stream(GameType.values()) - .map(GameType::getName) - .toArray(String[]::new); - LiteralArgumentBuilder literalargumentbuilder = literal("player") + LiteralArgumentBuilder command = literal("player") .requires((player) -> CommandHelper.canUseCommand(player, CarpetSettings.commandPlayer)) .then(argument("player", StringArgumentType.word()) - .suggests( (c, b) -> suggest(getPlayers(c.getSource()), b)) - .then(literal("stop").executes(PlayerCommand::stop)) - .then(makeActionCommand("use", EntityPlayerActionPack.ActionType.USE)) - .then(makeActionCommand("jump", EntityPlayerActionPack.ActionType.JUMP)) - .then(makeActionCommand("attack", EntityPlayerActionPack.ActionType.ATTACK)) - .then(makeActionCommand("drop", EntityPlayerActionPack.ActionType.DROP_ITEM)) + .suggests((c, b) -> suggest(getPlayerSuggestions(c.getSource()), b)) + .then(literal("stop").executes(manipulation(EntityPlayerActionPack::stopAll))) + .then(makeActionCommand("use", ActionType.USE)) + .then(makeActionCommand("jump", ActionType.JUMP)) + .then(makeActionCommand("attack", ActionType.ATTACK)) + .then(makeActionCommand("drop", ActionType.DROP_ITEM)) .then(makeDropCommand("drop", false)) - .then(makeActionCommand("dropStack", EntityPlayerActionPack.ActionType.DROP_STACK)) + .then(makeActionCommand("dropStack", ActionType.DROP_STACK)) .then(makeDropCommand("dropStack", true)) - .then(makeActionCommand("swapHands", EntityPlayerActionPack.ActionType.SWAP_HANDS)) + .then(makeActionCommand("swapHands", ActionType.SWAP_HANDS)) .then(literal("hotbar") .then(argument("slot", IntegerArgumentType.integer(1, 9)) .executes(c -> manipulate(c, ap -> ap.setSlot(IntegerArgumentType.getInteger(c, "slot")))))) @@ -83,63 +81,60 @@ public static void register(CommandDispatcher dispatcher, Co .then(literal("west").executes(manipulation(ap -> ap.look(Direction.WEST)))) .then(literal("up").executes(manipulation(ap -> ap.look(Direction.UP)))) .then(literal("down").executes(manipulation(ap -> ap.look(Direction.DOWN)))) - .then(literal("at").then(argument("position", Vec3Argument.vec3()).executes(PlayerCommand::lookAt))) + .then(literal("at").then(argument("position", Vec3Argument.vec3()) + .executes(c -> manipulate(c, ap -> ap.lookAt(Vec3Argument.getVec3(c, "position")))))) .then(argument("direction", RotationArgument.rotation()) .executes(c -> manipulate(c, ap -> ap.look(RotationArgument.getRotation(c, "direction").getRotation(c.getSource()))))) ).then(literal("turn") - .then(literal("left").executes(c -> manipulate(c, ap -> ap.turn(-90, 0)))) - .then(literal("right").executes(c -> manipulate(c, ap -> ap.turn(90, 0)))) - .then(literal("back").executes(c -> manipulate(c, ap -> ap.turn(180, 0)))) + .then(literal("left").executes(manipulation(ap -> ap.turn(-90, 0)))) + .then(literal("right").executes(manipulation(ap -> ap.turn(90, 0)))) + .then(literal("back").executes(manipulation(ap -> ap.turn(180, 0)))) .then(argument("rotation", RotationArgument.rotation()) .executes(c -> manipulate(c, ap -> ap.turn(RotationArgument.getRotation(c, "rotation").getRotation(c.getSource()))))) - ).then(literal("move").executes(c -> manipulate(c, EntityPlayerActionPack::stopMovement)) - .then(literal("forward").executes(c -> manipulate(c, ap -> ap.setForward(1)))) - .then(literal("backward").executes(c -> manipulate(c, ap -> ap.setForward(-1)))) - .then(literal("left").executes(c -> manipulate(c, ap -> ap.setStrafing(1)))) - .then(literal("right").executes(c -> manipulate(c, ap -> ap.setStrafing(-1)))) + ).then(literal("move").executes(manipulation(EntityPlayerActionPack::stopMovement)) + .then(literal("forward").executes(manipulation(ap -> ap.setForward(1)))) + .then(literal("backward").executes(manipulation(ap -> ap.setForward(-1)))) + .then(literal("left").executes(manipulation(ap -> ap.setStrafing(1)))) + .then(literal("right").executes(manipulation(ap -> ap.setStrafing(-1)))) ).then(literal("spawn").executes(PlayerCommand::spawn) .then(literal("in").requires((player) -> player.hasPermission(2)) - .then(argument("gamemode", StringArgumentType.word()) - .suggests( (c, b) -> suggest(gamemodeStrings, b)) + .then(argument("gamemode", GameModeArgument.gameMode()) .executes(PlayerCommand::spawn))) .then(literal("at").then(argument("position", Vec3Argument.vec3()).executes(PlayerCommand::spawn) .then(literal("facing").then(argument("direction", RotationArgument.rotation()).executes(PlayerCommand::spawn) .then(literal("in").then(argument("dimension", DimensionArgument.dimension()).executes(PlayerCommand::spawn) .then(literal("in").requires((player) -> player.hasPermission(2)) - .then(argument("gamemode", StringArgumentType.word()).suggests( (c, b) -> suggest(gamemodeStrings, b)) + .then(argument("gamemode", GameModeArgument.gameMode()) .executes(PlayerCommand::spawn) ))) ))) )) ) ); - dispatcher.register(literalargumentbuilder); + dispatcher.register(command); } - private static LiteralArgumentBuilder makeActionCommand(String actionName, EntityPlayerActionPack.ActionType type) + private static LiteralArgumentBuilder makeActionCommand(String actionName, ActionType type) { return literal(actionName) - .executes(c -> action(c, type, EntityPlayerActionPack.Action.once())) - .then(literal("once").executes(c -> action(c, type, EntityPlayerActionPack.Action.once()))) - .then(literal("continuous").executes(c -> action(c, type, EntityPlayerActionPack.Action.continuous()))) + .executes(manipulation(ap -> ap.start(type, Action.once()))) + .then(literal("once").executes(manipulation(ap -> ap.start(type, Action.once())))) + .then(literal("continuous").executes(manipulation(ap -> ap.start(type, Action.continuous())))) .then(literal("interval").then(argument("ticks", IntegerArgumentType.integer(1)) - .executes(c -> action(c, type, EntityPlayerActionPack.Action.interval(IntegerArgumentType.getInteger(c, "ticks")))))); + .executes(c -> manipulate(c, ap -> ap.start(type, Action.interval(IntegerArgumentType.getInteger(c, "ticks"))))))); } private static LiteralArgumentBuilder makeDropCommand(String actionName, boolean dropAll) { return literal(actionName) - .then(literal("all").executes(c ->manipulate(c, ap -> ap.drop(-2,dropAll)))) - .then(literal("mainhand").executes(c ->manipulate(c, ap -> ap.drop(-1,dropAll)))) - .then(literal("offhand").executes(c ->manipulate(c, ap -> ap.drop(40,dropAll)))) + .then(literal("all").executes(manipulation(ap -> ap.drop(-2, dropAll)))) + .then(literal("mainhand").executes(manipulation(ap -> ap.drop(-1, dropAll)))) + .then(literal("offhand").executes(manipulation(ap -> ap.drop(40, dropAll)))) .then(argument("slot", IntegerArgumentType.integer(0, 40)). - executes(c ->manipulate(c, ap -> ap.drop( - IntegerArgumentType.getInteger(c,"slot"), - dropAll - )))); + executes(c -> manipulate(c, ap -> ap.drop(IntegerArgumentType.getInteger(c, "slot"), dropAll)))); } - private static Collection getPlayers(CommandSourceStack source) + private static Collection getPlayerSuggestions(CommandSourceStack source) { Set players = new LinkedHashSet<>(List.of("Steve", "Alex")); players.addAll(source.getOnlinePlayerNames()); @@ -156,26 +151,23 @@ private static ServerPlayer getPlayer(CommandContext context private static boolean cantManipulate(CommandContext context) { Player player = getPlayer(context); + CommandSourceStack source = context.getSource(); if (player == null) { - Messenger.m(context.getSource(), "r Can only manipulate existing players"); + Messenger.m(source, "r Can only manipulate existing players"); return true; } - Player sendingPlayer; - try - { - sendingPlayer = context.getSource().getPlayerOrException(); - } - catch (CommandSyntaxException e) + Player sender = source.getPlayer(); + if (sender == null) { return false; } - if (!context.getSource().getServer().getPlayerList().isOp(sendingPlayer.getGameProfile())) + if (!source.getServer().getPlayerList().isOp(sender.getGameProfile())) { - if (sendingPlayer != player && !(player instanceof EntityPlayerMPFake)) + if (sender != player && !(player instanceof EntityPlayerMPFake)) { - Messenger.m(context.getSource(), "r Non OP players can't control other real players"); + Messenger.m(source, "r Non OP players can't control other real players"); return true; } } @@ -196,8 +188,8 @@ private static boolean cantSpawn(CommandContext context) String playerName = StringArgumentType.getString(context, "player"); MinecraftServer server = context.getSource().getServer(); PlayerList manager = server.getPlayerList(); - Player player = manager.getPlayerByName(playerName); - if (player != null) + + if (manager.getPlayerByName(playerName) != null) { Messenger.m(context.getSource(), "r Player ", "rb " + playerName, "r is already logged on"); return true; @@ -234,109 +226,86 @@ private static int kill(CommandContext context) return 1; } - private static int lookAt(CommandContext context) - { - return manipulate(context, ap -> { - //try { - ap.lookAt(Vec3Argument.getVec3(context, "position")); - //} catch (CommandSyntaxException ignored) {} - }); - } - @FunctionalInterface - interface SupplierWithCommandSyntaxException + interface SupplierWithCSE { T get() throws CommandSyntaxException; } - private static T tryGetArg(SupplierWithCommandSyntaxException a, SupplierWithCommandSyntaxException b) throws CommandSyntaxException + private static T getArgOrDefault(SupplierWithCSE getter, T defaultValue) throws CommandSyntaxException { try { - return a.get(); + return getter.get(); } catch (IllegalArgumentException e) { - return b.get(); + return defaultValue; } } private static int spawn(CommandContext context) throws CommandSyntaxException { if (cantSpawn(context)) return 0; + CommandSourceStack source = context.getSource(); - Vec3 pos = tryGetArg( + Vec3 pos = getArgOrDefault( () -> Vec3Argument.getVec3(context, "position"), - source::getPosition + source.getPosition() ); - Vec2 facing = tryGetArg( - () -> RotationArgument.getRotation(context, "direction").getRotation(context.getSource()), - source::getRotation + Vec2 facing = getArgOrDefault( + () -> RotationArgument.getRotation(context, "direction").getRotation(source), + source.getRotation() ); - ResourceKey dimType = tryGetArg( + ResourceKey dimType = getArgOrDefault( () -> DimensionArgument.getDimension(context, "dimension").dimension(), - () -> source.getLevel().dimension() // dimension.getType() + source.getLevel().dimension() ); GameType mode = GameType.CREATIVE; boolean flying = false; - try + if (source.getEntity() instanceof ServerPlayer sender) { - ServerPlayer player = context.getSource().getPlayerOrException(); - mode = player.gameMode.getGameModeForPlayer(); - flying = player.getAbilities().flying; + mode = sender.gameMode.getGameModeForPlayer(); + flying = sender.getAbilities().flying; } - catch (CommandSyntaxException ignored) {} try { - String opGameMode = StringArgumentType.getString(context, "gamemode"); - mode = GameType.byName(opGameMode, null); - if(mode == null) - { - Messenger.m(context.getSource(), "rb Invalid game mode: "+opGameMode+"."); - return 0; - } - } catch (IllegalArgumentException ignored) {} - if(mode == GameType.SPECTATOR) + mode = GameModeArgument.getGameMode(context, "gamemode"); + } catch (IllegalArgumentException notPresent) {} + + if (mode == GameType.SPECTATOR) { // Force override flying to true for spectator players, or they will fell out of the world. flying = true; - } else if(mode.isSurvival()){ + } else if (mode.isSurvival()) + { // Force override flying to false for survival-like players, or they will fly too flying = false; } String playerName = StringArgumentType.getString(context, "player"); - if (playerName.length()>maxPlayerLength(source.getServer())) + if (playerName.length() > maxNameLength(source.getServer())) { - Messenger.m(context.getSource(), "rb Player name: "+playerName+" is too long"); + Messenger.m(source, "rb Player name: " + playerName + " is too long"); return 0; } - MinecraftServer server = source.getServer(); - if (!Level.isInSpawnableBounds(BlockPos.containing(pos.x, pos.y, pos.z))) + if (!Level.isInSpawnableBounds(BlockPos.containing(pos))) { - Messenger.m(context.getSource(), "rb Player "+playerName+" cannot be placed outside of the world"); + Messenger.m(source, "rb Player " + playerName + " cannot be placed outside of the world"); return 0; } - Player player = EntityPlayerMPFake.createFake(playerName, server, pos.x, pos.y, pos.z, facing.y, facing.x, dimType, mode, flying); + Player player = EntityPlayerMPFake.createFake(playerName, source.getServer(), pos, facing.y, facing.x, dimType, mode, flying); if (player == null) { - Messenger.m(context.getSource(), "rb Player " + StringArgumentType.getString(context, "player") + " doesn't exist " + - "and cannot spawn in online mode. Turn the server offline to spawn non-existing players"); + Messenger.m(source, "rb Player " + playerName + " doesn't exist and cannot spawn in online mode. " + + "Turn the server offline to spawn non-existing players"); return 0; } return 1; } - private static int maxPlayerLength(MinecraftServer server) + private static int maxNameLength(MinecraftServer server) { - return server.getPort() >= 0 ? 16 : 40; - } - - private static int stop(CommandContext context) - { - if (cantManipulate(context)) return 0; - ServerPlayer player = getPlayer(context); - ((ServerPlayerInterface) player).getActionPack().stopAll(); - return 1; + return server.getPort() >= 0 ? Player.MAX_NAME_LENGTH : 40; } private static int manipulate(CommandContext context, Consumer action) @@ -352,13 +321,10 @@ private static Command manipulation(Consumer manipulate(c, action); } - private static int action(CommandContext context, EntityPlayerActionPack.ActionType type, EntityPlayerActionPack.Action action) - { - return manipulate(context, ap -> ap.start(type, action)); - } - private static int shadow(CommandContext context) { + if (cantManipulate(context)) return 0; + ServerPlayer player = getPlayer(context); if (player instanceof EntityPlayerMPFake) { @@ -369,14 +335,7 @@ private static int shadow(CommandContext context) Messenger.m(context.getSource(), "r Cannot shadow single-player server owner"); return 0; } - ServerPlayer sendingPlayer = null; - try - { - sendingPlayer = context.getSource().getPlayerOrException(); - } - catch (CommandSyntaxException ignored) { } - if (sendingPlayer!=player && cantManipulate(context)) return 0; EntityPlayerMPFake.createShadow(player.server, player); return 1; } diff --git a/src/main/java/carpet/patches/EntityPlayerMPFake.java b/src/main/java/carpet/patches/EntityPlayerMPFake.java index f66d1b73e5..7c3293d1ce 100644 --- a/src/main/java/carpet/patches/EntityPlayerMPFake.java +++ b/src/main/java/carpet/patches/EntityPlayerMPFake.java @@ -26,6 +26,7 @@ import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.SkullBlockEntity; import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.Vec3; import carpet.fakes.ServerPlayerInterface; import carpet.utils.Messenger; @@ -37,7 +38,7 @@ public class EntityPlayerMPFake extends ServerPlayer public Runnable fixStartingPosition = () -> {}; public boolean isAShadow; - public static EntityPlayerMPFake createFake(String username, MinecraftServer server, double d0, double d1, double d2, double yaw, double pitch, ResourceKey dimensionId, GameType gamemode, boolean flying) + public static EntityPlayerMPFake createFake(String username, MinecraftServer server, Vec3 pos, double yaw, double pitch, ResourceKey dimensionId, GameType gamemode, boolean flying) { //prolly half of that crap is not necessary, but it works ServerLevel worldIn = server.getLevel(dimensionId); @@ -65,9 +66,9 @@ public static EntityPlayerMPFake createFake(String username, MinecraftServer ser gameprofile = result.get(); } EntityPlayerMPFake instance = new EntityPlayerMPFake(server, worldIn, gameprofile, false); - instance.fixStartingPosition = () -> instance.moveTo(d0, d1, d2, (float) yaw, (float) pitch); + instance.fixStartingPosition = () -> instance.moveTo(pos.x, pos.y, pos.z, (float) yaw, (float) pitch); server.getPlayerList().placeNewPlayer(new FakeClientConnection(PacketFlow.SERVERBOUND), instance); - instance.teleportTo(worldIn, d0, d1, d2, (float)yaw, (float)pitch); + instance.teleportTo(worldIn, pos.x, pos.y, pos.z, (float) yaw, (float) pitch); instance.setHealth(20.0F); instance.unsetRemoved(); instance.setMaxUpStep(0.6F); From 83e88856aba6c9b6b2f4a96f38f9f150024c66cc Mon Sep 17 00:00:00 2001 From: altrisi Date: Mon, 3 Apr 2023 19:13:02 +0200 Subject: [PATCH 103/233] Rename fungus growth enum given the rule is no longer about a fix --- src/main/java/carpet/CarpetSettings.java | 4 ++-- src/main/java/carpet/mixins/HugeFungusFeatureMixin.java | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/carpet/CarpetSettings.java b/src/main/java/carpet/CarpetSettings.java index 1fabb02e3d..3e9bd5622e 100644 --- a/src/main/java/carpet/CarpetSettings.java +++ b/src/main/java/carpet/CarpetSettings.java @@ -1144,7 +1144,7 @@ public Boolean validate(CommandSourceStack source, CarpetRule changingR ) public static boolean tickSyncedWorldBorders = false; - public enum FungusFixMode { + public enum FungusGrowthMode { FALSE, RANDOM, ALL; } @@ -1154,5 +1154,5 @@ public enum FungusFixMode { extra = {"Setting to 'all' will make all nether fungi grow into 3x3 trees", "Setting to 'random' will make 6% of all nether fungi grow into 3x3 trees", "(this being consistent with worldgen)"}, category = {SURVIVAL, FEATURE} ) - public static FungusFixMode thickFungusGrowth = FungusFixMode.FALSE; + public static FungusGrowthMode thickFungusGrowth = FungusGrowthMode.FALSE; } diff --git a/src/main/java/carpet/mixins/HugeFungusFeatureMixin.java b/src/main/java/carpet/mixins/HugeFungusFeatureMixin.java index 99af900482..8084c184c0 100644 --- a/src/main/java/carpet/mixins/HugeFungusFeatureMixin.java +++ b/src/main/java/carpet/mixins/HugeFungusFeatureMixin.java @@ -9,7 +9,7 @@ import org.spongepowered.asm.mixin.injection.ModifyArgs; import org.spongepowered.asm.mixin.injection.invoke.arg.Args; -import static carpet.CarpetSettings.FungusFixMode.*; +import static carpet.CarpetSettings.FungusGrowthMode.*; @Mixin(HugeFungusFeature.class) public class HugeFungusFeatureMixin { @@ -17,8 +17,8 @@ public class HugeFungusFeatureMixin { private void mixin(Args args) { boolean natural = !((HugeFungusConfiguration) args.get(2)).planted; args.set(5, natural && ((boolean) args.get(5)) || - !natural && (CarpetSettings.thickFungusGrowth.equals(ALL) || - CarpetSettings.thickFungusGrowth.equals(RANDOM) && ((RandomSource) args.get(1)).nextFloat() < 0.06F) + !natural && (CarpetSettings.thickFungusGrowth == ALL || + CarpetSettings.thickFungusGrowth == RANDOM && ((RandomSource) args.get(1)).nextFloat() < 0.06F) ); } } From 56e25a780cedb2fae9d090d429e36423a0e364e9 Mon Sep 17 00:00:00 2001 From: altrisi Date: Mon, 3 Apr 2023 19:19:31 +0200 Subject: [PATCH 104/233] Missed call in 5fcfc7a --- src/main/java/carpet/helpers/EntityPlayerActionPack.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/carpet/helpers/EntityPlayerActionPack.java b/src/main/java/carpet/helpers/EntityPlayerActionPack.java index 2df403feb1..151094e7d8 100644 --- a/src/main/java/carpet/helpers/EntityPlayerActionPack.java +++ b/src/main/java/carpet/helpers/EntityPlayerActionPack.java @@ -221,7 +221,7 @@ public void onUpdate() // skipping attack if use was successful if (!(actionAttempts.getOrDefault(ActionType.USE, false) && type == ActionType.ATTACK)) { - Boolean actionStatus = action.tick(this, e.getKey()); + Boolean actionStatus = action.tick(this, type); if (actionStatus != null) actionAttempts.put(type, actionStatus); } From d85c23125f36505e2ff707b185f74085e739065a Mon Sep 17 00:00:00 2001 From: altrisi Date: Mon, 3 Apr 2023 19:40:33 +0200 Subject: [PATCH 105/233] Add explicit deprecation `SuppressWarnings` for Gradle --- src/main/java/carpet/settings/ParsedRule.java | 1 + src/main/java/carpet/settings/SettingsManager.java | 1 + src/main/java/carpet/settings/Validator.java | 1 + 3 files changed, 3 insertions(+) diff --git a/src/main/java/carpet/settings/ParsedRule.java b/src/main/java/carpet/settings/ParsedRule.java index 66860f3d23..28b3ddf874 100644 --- a/src/main/java/carpet/settings/ParsedRule.java +++ b/src/main/java/carpet/settings/ParsedRule.java @@ -38,6 +38,7 @@ * @deprecated Use the type {@link CarpetRule} instead */ @Deprecated(forRemoval = true) // to move to api.settings package and visibility to package private +@SuppressWarnings("removal") // Gradle needs the explicit suppression public final class ParsedRule implements CarpetRule, Comparable> { private static final Map, FromStringConverter> CONVERTER_MAP = Map.ofEntries( Map.entry(String.class, str -> str), diff --git a/src/main/java/carpet/settings/SettingsManager.java b/src/main/java/carpet/settings/SettingsManager.java index d7c9729eae..d2c0760d2f 100644 --- a/src/main/java/carpet/settings/SettingsManager.java +++ b/src/main/java/carpet/settings/SettingsManager.java @@ -19,6 +19,7 @@ * @deprecated Use {@link carpet.api.settings.SettingsManager} instead */ @Deprecated(forRemoval = true) +@SuppressWarnings("removal") // Gradle needs the explicit suppression public class SettingsManager extends carpet.api.settings.SettingsManager { /** diff --git a/src/main/java/carpet/settings/Validator.java b/src/main/java/carpet/settings/Validator.java index 4e191141bb..be4fc4034d 100644 --- a/src/main/java/carpet/settings/Validator.java +++ b/src/main/java/carpet/settings/Validator.java @@ -11,6 +11,7 @@ * @deprecated Use {@link carpet.api.settings.Validator} instead */ @Deprecated(forRemoval = true) +@SuppressWarnings("removal") // Gradle needs the explicit suppression public abstract class Validator extends carpet.api.settings.Validator { { From 3ae913c3e64cc19e5130793c45859d939019798f Mon Sep 17 00:00:00 2001 From: altrisi Date: Mon, 3 Apr 2023 21:42:44 +0200 Subject: [PATCH 106/233] Use enhanced switch in `CommandHelper` --- src/main/java/carpet/utils/CommandHelper.java | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/src/main/java/carpet/utils/CommandHelper.java b/src/main/java/carpet/utils/CommandHelper.java index 237ddf0898..9298d186bb 100644 --- a/src/main/java/carpet/utils/CommandHelper.java +++ b/src/main/java/carpet/utils/CommandHelper.java @@ -40,18 +40,13 @@ public static boolean canUseCommand(CommandSourceStack source, Object commandLev { if (commandLevel instanceof Boolean) return (Boolean) commandLevel; String commandLevelString = commandLevel.toString(); - switch (commandLevelString) + return switch (commandLevelString) { - case "true": return true; - case "false": return false; - case "ops": return source.hasPermission(2); // typical for other cheaty commands - case "0": - case "1": - case "2": - case "3": - case "4": - return source.hasPermission(Integer.parseInt(commandLevelString)); - } - return false; + case "true" -> true; + case "false" -> false; + case "ops" -> source.hasPermission(2); // typical for other cheaty commands + case "0", "1", "2", "3", "4" -> source.hasPermission(Integer.parseInt(commandLevelString)); + default -> false; + }; } } From 50c22b6fe2ab34de1d92a78d71c6c7262f09037c Mon Sep 17 00:00:00 2001 From: altrisi Date: Mon, 3 Apr 2023 21:47:30 +0200 Subject: [PATCH 107/233] Log exceptions in `notifyPlayersCommandsChanged` I want to remove this try-catch if possible, but don't know why it's triggered --- src/main/java/carpet/utils/CommandHelper.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/carpet/utils/CommandHelper.java b/src/main/java/carpet/utils/CommandHelper.java index 9298d186bb..d6825a914f 100644 --- a/src/main/java/carpet/utils/CommandHelper.java +++ b/src/main/java/carpet/utils/CommandHelper.java @@ -1,5 +1,6 @@ package carpet.utils; +import carpet.CarpetSettings; import net.minecraft.commands.CommandSourceStack; import net.minecraft.server.MinecraftServer; import net.minecraft.server.TickTask; @@ -29,7 +30,10 @@ public static void notifyPlayersCommandsChanged(MinecraftServer server) server.getCommands().sendCommands(player); } } - catch (NullPointerException ignored) {} + catch (NullPointerException e) + { + CarpetSettings.LOG.warn("Exception while refreshing commands, please report this to Carpet", e); + } })); } From cda7f791b7cf1f9959bc6bc7e408f629bead0331 Mon Sep 17 00:00:00 2001 From: altrisi Date: Mon, 3 Apr 2023 21:58:08 +0200 Subject: [PATCH 108/233] Prioritize new Rule annotation when parsing if both are present --- src/main/java/carpet/settings/ParsedRule.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/carpet/settings/ParsedRule.java b/src/main/java/carpet/settings/ParsedRule.java index 28b3ddf874..b02bfec5b1 100644 --- a/src/main/java/carpet/settings/ParsedRule.java +++ b/src/main/java/carpet/settings/ParsedRule.java @@ -149,12 +149,12 @@ record RuleAnnotation(boolean isLegacy, String name, String desc, String[] extra @Deprecated(forRemoval = true) public static ParsedRule of(Field field, SettingsManager settingsManager) { RuleAnnotation rule; - if (settingsManager instanceof carpet.settings.SettingsManager && field.isAnnotationPresent(Rule.class)) { // Legacy path - Rule a = field.getAnnotation(Rule.class); - rule = new RuleAnnotation(true, a.name(), a.desc(), a.extra(), a.category(), a.options(), a.strict(), a.appSource(), a.validate()); - } else if (field.isAnnotationPresent(carpet.api.settings.Rule.class)) { + if (field.isAnnotationPresent(carpet.api.settings.Rule.class)) { carpet.api.settings.Rule a = field.getAnnotation(carpet.api.settings.Rule.class); rule = new RuleAnnotation(false, null, null, null, a.categories(), a.options(), a.strict(), a.appSource(), a.validators()); + } else if (settingsManager instanceof carpet.settings.SettingsManager && field.isAnnotationPresent(Rule.class)) { // Legacy path + Rule a = field.getAnnotation(Rule.class); + rule = new RuleAnnotation(true, a.name(), a.desc(), a.extra(), a.category(), a.options(), a.strict(), a.appSource(), a.validate()); } else { // Don't allow to use old rule types in custom AND migrated settings manager throw new IllegalArgumentException("Old rule annotation is only supported in legacy SettngsManager!"); From fdb0936df723fe5a24e1822ee16b93f2117842ac Mon Sep 17 00:00:00 2001 From: altrisi Date: Tue, 4 Apr 2023 15:57:59 +0200 Subject: [PATCH 109/233] Remove deprecated log4j dependent methods in `c.s.SettingsManager` And another one that is normally a bug to use, and a field that is broken. Enables `runtimeOnlyLog4j` in loom --- build.gradle | 2 +- .../java/carpet/settings/SettingsManager.java | 92 ------------------- 2 files changed, 1 insertion(+), 93 deletions(-) diff --git a/build.gradle b/build.gradle index 3737e495a7..ea3f2e90c9 100644 --- a/build.gradle +++ b/build.gradle @@ -13,7 +13,7 @@ group = project.maven_group loom { accessWidenerPath = file("src/main/resources/carpet.accesswidener") - runtimeOnlyLog4j = false // Can be turned on after TriConsumer is no longer present in public API + runtimeOnlyLog4j = true } dependencies { diff --git a/src/main/java/carpet/settings/SettingsManager.java b/src/main/java/carpet/settings/SettingsManager.java index d2c0760d2f..ed2dbd9542 100644 --- a/src/main/java/carpet/settings/SettingsManager.java +++ b/src/main/java/carpet/settings/SettingsManager.java @@ -1,8 +1,6 @@ package carpet.settings; import carpet.CarpetServer; -import carpet.CarpetSettings; -import carpet.api.settings.CarpetRule; import carpet.utils.CommandHelper; import com.mojang.brigadier.CommandDispatcher; import net.minecraft.commands.CommandBuildContext; @@ -10,7 +8,6 @@ import net.minecraft.core.RegistryAccess; import net.minecraft.server.MinecraftServer; import net.minecraft.world.flag.FeatureFlags; -import org.apache.logging.log4j.util.TriConsumer; import java.util.Collection; import java.util.List; @@ -22,12 +19,6 @@ @SuppressWarnings("removal") // Gradle needs the explicit suppression public class SettingsManager extends carpet.api.settings.SettingsManager { - /** - * @deprecated Use {@link #locked()} instead - */ - @Deprecated(forRemoval = true) //to private (or protected?) - public boolean locked; - /** * Creates a new {@link SettingsManager} without a fancy name. * @see #SettingsManager(String, String, String) @@ -57,61 +48,6 @@ public SettingsManager(String version, String identifier, String fancyName) super(version, identifier, fancyName); } - /** - *

    Adds a custom rule observer to changes in rules from - * this specific {@link SettingsManager} instance.

    - * - *

    This outdated method may not be able to listen to all {@link CarpetRule} implementations

    - * - * @see SettingsManager#registerGlobalRuleObserver(RuleObserver) - * - * @param observer A {@link TriConsumer} that will be called with - * the used {@link CommandSourceStack}, the changed - * {@link ParsedRule} and a {@link String} being the - * value that the user typed. - * @deprecated Use {@link SettingsManager#registerRuleObserver(RuleObserver)} instead. - */ - @Deprecated(forRemoval = true) //to remove - public void addRuleObserver(TriConsumer, String> observer) - { - registerRuleObserver((source, rule, stringValue) -> { - if (rule instanceof ParsedRule pr) - observer.accept(source, pr, stringValue); - else - CarpetSettings.LOG.warn("Failed to notify observer '" + observer.getClass().getName() + "' about rule change"); - }); - CarpetSettings.LOG.warn(""" - Extension added outdated rule observer, this is deprecated and will crash in later carpet versions \ - (way before the rest of the old settings api because of relying on log4j)! - The observer class name is '%s'""".formatted(observer.getClass().getName())); - } - - /** - * Adds a custom rule observer to changes in rules from - * any registered {@link SettingsManager} instance. - * @see SettingsManager#addRuleObserver(TriConsumer) - * - * @param observer A {@link TriConsumer} that will be called with - * the used {@link CommandSourceStack}, the changed - * {@link ParsedRule} and a {@link String} being the - * value that the user typed. - * @deprecated Use {@link SettingsManager#registerRuleObserver(RuleObserver)} instead, given this one can't deal with {@link CarpetRule} - */ - @Deprecated(forRemoval = true) // to remove. This isn't really used anywhere - public static void addGlobalRuleObserver(TriConsumer, String> observer) - { - registerGlobalRuleObserver((source, rule, stringValue) -> { - if (rule instanceof ParsedRule pr) - observer.accept(source, pr, stringValue); - else - CarpetSettings.LOG.warn("Failed to notify observer '" + observer.getClass().getName() + "' about rule change"); - }); - CarpetSettings.LOG.warn(""" - Extension added outdated rule observer, this is deprecated and will crash in later carpet versions \ - (way before the rest of the old settings api because of relying on log4j)! - The observer class name is '%s'""".formatted(observer.getClass().getName())); - } - /** * @deprecated Use {@link #identifier()} instead */ @@ -178,34 +114,6 @@ public static boolean canUseCommand(CommandSourceStack source, Object commandLev return CommandHelper.canUseCommand(source, commandLevel); } - /** - * @param commandLevel A {@link String} being a permission level according to - * Carpet's standard for permissions (either 0-4, a {@link boolean}, - * or "ops". - * @return An {@link int} with the translated Vanilla permission level - * - * @deprecated While there's not an API replacement for this (at least yet), - * you can use the similar {@link CommandHelper#canUseCommand(CommandSourceStack, Object)} instead - * @apiNote Note that this method returns {@code 2} for {@code false} and {@code 0} for {@code true}. - * You probably want to use {@link #canUseCommand(CommandSourceStack, Object)}e - */ - @Deprecated(forRemoval = true) - public static int getCommandLevel(String commandLevel) - { - switch (commandLevel) - { - case "true": return 2; - case "false": return 0; - case "ops": return 2; // typical for other cheaty commands - case "0": - case "1": - case "2": - case "3": - case "4": - return Integer.parseInt(commandLevel); - } - return 0; - } @Deprecated(forRemoval = true) public void registerCommand(CommandDispatcher dispatcher) { From 9a5c2d5fc35894d8a5f454160583b4a511b75513 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 5 Apr 2023 20:08:29 +0200 Subject: [PATCH 110/233] deprecation of `material(...)`, fix `map_colour(...)` --- docs/scarpet/api/BlocksAndWorldAccess.md | 10 ++-------- src/main/java/carpet/script/api/WorldAccess.java | 11 ++++++----- 2 files changed, 8 insertions(+), 13 deletions(-) diff --git a/docs/scarpet/api/BlocksAndWorldAccess.md b/docs/scarpet/api/BlocksAndWorldAccess.md index e900466eaa..17684cf5d2 100644 --- a/docs/scarpet/api/BlocksAndWorldAccess.md +++ b/docs/scarpet/api/BlocksAndWorldAccess.md @@ -486,15 +486,9 @@ Returns the name of sound type made by the block at position. One of: `'candle'`', `'amethyst'`', `'amethyst_cluster'`', `'small_amethyst_bud'`', `'large_amethyst_bud'`', `'medium_amethyst_bud'`', `'tuff'`', `'calcite'`', `'copper'`' -### `material(pos)` +### `(Deprecated) material(pos)` -Returns the name of material of the block at position. very useful to target a group of blocks. One of: - -`'air'`, `'void'`, `'portal'`, `'carpet'`, `'plant'`, `'water_plant'`, `'vine'`, `'sea_grass'`, `'water'`, -`'bubble_column'`, `'lava'`, `'snow_layer'`, `'fire'`, `'redstone_bits'`, `'cobweb'`, `'redstone_lamp'`, `'clay'`, -`'dirt'`, `'grass'`, `'packed_ice'`, `'sand'`, `'sponge'`, `'wood'`, `'wool'`, `'tnt'`, `'leaves'`, `'glass'`, -`'ice'`, `'cactus'`, `'stone'`, `'iron'`, `'snow'`, `'anvil'`, `'barrier'`, `'piston'`, `'coral'`, `'gourd'`, -`'dragon_egg'`, `'cake'`, `'amethyst'` +Returns the name of material of the block at position. Very limited as the use of material for blocks is removed. ### `map_colour(pos)` diff --git a/src/main/java/carpet/script/api/WorldAccess.java b/src/main/java/carpet/script/api/WorldAccess.java index 43e55faaf1..51cef699a5 100644 --- a/src/main/java/carpet/script/api/WorldAccess.java +++ b/src/main/java/carpet/script/api/WorldAccess.java @@ -1160,14 +1160,15 @@ LivingEntity getIndirectSourceEntity() stateStringQuery(c, "block_sound", lv, (s, p) -> Colors.soundName.get(s.getSoundType()))); - expression.addContextFunction("material", -1, (c, t, lv) -> - stateStringQuery(c, "material", lv, (s, p) -> - Colors.materialName.get(s.getMaterial()))); + expression.addContextFunction("material", -1, (c, t, lv) -> { + c.host.issueDeprecation("material(...)"); // deprecated for block_state() + return stateStringQuery(c, "material", lv, (s, p) -> + Colors.materialName.getOrDefault(s.getMaterial(), "unknown")); + }); expression.addContextFunction("map_colour", -1, (c, t, lv) -> stateStringQuery(c, "map_colour", lv, (s, p) -> - Colors.materialName.get(s.getMapColor(((CarpetContext) c).level(), p)))); - + Colors.mapColourName.get(s.getMapColor(((CarpetContext) c).level(), p)))); // Deprecated for block_state() expression.addContextFunction("property", -1, (c, t, lv) -> From 1751f103f959a2c226340f7a9b9060b561da78f0 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 5 Apr 2023 20:12:21 +0200 Subject: [PATCH 111/233] 23w14a --- gradle.properties | 6 +-- .../carpet/helpers/OptimizedExplosion.java | 10 ++--- ...lowingFluid_liquidDamageDisabledMixin.java | 5 +-- .../script/command/CommandArgument.java | 5 ++- src/main/java/carpet/script/utils/Colors.java | 44 +------------------ src/main/java/carpet/utils/BlockInfo.java | 4 +- .../carpet/utils/PerimeterDiagnostics.java | 4 +- src/main/java/carpet/utils/WoolTool.java | 10 ++++- 8 files changed, 27 insertions(+), 61 deletions(-) diff --git a/gradle.properties b/gradle.properties index 796a39dfb1..206ee06677 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,10 +3,10 @@ org.gradle.jvmargs=-Xmx1G # Fabric Properties # check https://fabricmc.net/develop/ - minecraft_version=23w13a - loader_version=0.14.18 + minecraft_version=23w14a + loader_version=0.14.19 jsr305_version=3.0.2 - fabric_version=0.76.0+1.19.4 + fabric_version=0.77.0+1.19.4 # Mod Properties mod_version = 1.4.103 diff --git a/src/main/java/carpet/helpers/OptimizedExplosion.java b/src/main/java/carpet/helpers/OptimizedExplosion.java index d42a738f5a..cd869d509b 100644 --- a/src/main/java/carpet/helpers/OptimizedExplosion.java +++ b/src/main/java/carpet/helpers/OptimizedExplosion.java @@ -241,7 +241,7 @@ public static void doExplosionB(Explosion e, boolean spawnParticles) BlockState state = world.getBlockState(blockpos); Block block = state.getBlock(); - if (state.getMaterial() != Material.AIR) + if (!state.isAir()) { if (block.dropFromExplosion(e) && world instanceof ServerLevel serverLevel) { @@ -281,7 +281,7 @@ public static void doExplosionB(Explosion e, boolean spawnParticles) BlockPos down = blockpos1.below(1); if (eAccess.getRandom().nextInt(3) == 0 && - chunk.getBlockState(blockpos1).getMaterial() == Material.AIR && + chunk.getBlockState(blockpos1).isAir() && chunk.getBlockState(down).isSolidRender(world, down) ) { @@ -346,7 +346,7 @@ private static void rayCalcs(Explosion e) { BlockState state = eAccess.getLevel().getBlockState(blockpos); FluidState fluidState = eAccess.getLevel().getFluidState(blockpos); - if (state.getMaterial() != Material.AIR) { + if (!state.isAir()) { float f2 = Math.max(state.getBlock().getExplosionResistance(), fluidState.getExplosionResistance()); if (eAccess.getSource() != null) f2 = eAccess.getSource().getBlockExplosionResistance(e, eAccess.getLevel(), blockpos, state, fluidState, f2); @@ -475,7 +475,7 @@ private static boolean checkAffectedPosition(Explosion e, double xRel, double yR fluidCache.put(posImmutable, fluid); } - if (state.getMaterial() != Material.AIR) + if (!state.isAir()) { float resistance = Math.max(state.getBlock().getExplosionResistance(), fluid.getExplosionResistance()); @@ -538,7 +538,7 @@ private static void blastCalc(Explosion e){ BlockState state = eAccess.getLevel().getBlockState(blockpos); FluidState fluidState = eAccess.getLevel().getFluidState(blockpos); - if (state.getMaterial() != Material.AIR) { + if (!state.isAir()) { float f2 = Math.max(state.getBlock().getExplosionResistance(), fluidState.getExplosionResistance()); if (eAccess.getSource() != null) f2 = eAccess.getSource().getBlockExplosionResistance(e, eAccess.getLevel(), blockpos, state, fluidState, f2); diff --git a/src/main/java/carpet/mixins/FlowingFluid_liquidDamageDisabledMixin.java b/src/main/java/carpet/mixins/FlowingFluid_liquidDamageDisabledMixin.java index 0ce97ecc53..5d980f374f 100644 --- a/src/main/java/carpet/mixins/FlowingFluid_liquidDamageDisabledMixin.java +++ b/src/main/java/carpet/mixins/FlowingFluid_liquidDamageDisabledMixin.java @@ -3,10 +3,10 @@ import carpet.CarpetSettings; import net.minecraft.core.BlockPos; import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.FlowingFluid; import net.minecraft.world.level.material.Fluid; -import net.minecraft.world.level.material.Material; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -27,8 +27,7 @@ private void stopBreakingBlock(BlockGetter world, BlockPos pos, BlockState state { if (CarpetSettings.liquidDamageDisabled) { - Material material = state.getMaterial(); - cir.setReturnValue(material == Material.AIR || material.isLiquid()); + cir.setReturnValue(state.isAir() || state.is(Blocks.WATER) || state.is(Blocks.LAVA)); } } } diff --git a/src/main/java/carpet/script/command/CommandArgument.java b/src/main/java/carpet/script/command/CommandArgument.java index a0e43b500c..93276819fd 100644 --- a/src/main/java/carpet/script/command/CommandArgument.java +++ b/src/main/java/carpet/script/command/CommandArgument.java @@ -104,6 +104,7 @@ import net.minecraft.server.commands.BossBarCommands; import net.minecraft.world.entity.Entity; import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.storage.loot.LootDataType; import net.minecraft.world.phys.Vec2; import net.minecraft.world.scores.Scoreboard; @@ -210,10 +211,10 @@ public static CommandSyntaxException error(String text) (c, p) -> ValueConversions.of(ResourceLocationArgument.getAdvancement(c, p).getId()), (ctx, builder) -> SharedSuggestionProvider.suggestResource(ctx.getSource().getServer().getAdvancements().getAllAdvancements().stream().map(Advancement::getId), builder) ), new VanillaUnconfigurableArgument("lootcondition", ResourceLocationArgument::id, - (c, p) -> ValueConversions.of(c.getSource().registryAccess().registryOrThrow(Registries.LOOT_CONDITION_TYPE).getKey(ResourceLocationArgument.getPredicate(c, p).getType())), (ctx, builder) -> SharedSuggestionProvider.suggestResource(ctx.getSource().getServer().getPredicateManager().getKeys(), builder) + (c, p) -> ValueConversions.of(c.getSource().registryAccess().registryOrThrow(Registries.LOOT_CONDITION_TYPE).getKey(ResourceLocationArgument.getPredicate(c, p).getType())), (ctx, builder) -> SharedSuggestionProvider.suggestResource(ctx.getSource().getServer().getLootData().getKeys(LootDataType.PREDICATE), builder) ), new VanillaUnconfigurableArgument("loottable", ResourceLocationArgument::id, - (c, p) -> ValueConversions.of(ResourceLocationArgument.getId(c, p)), (ctx, builder) -> SharedSuggestionProvider.suggestResource(ctx.getSource().getServer().getLootTables().getIds(), builder) + (c, p) -> ValueConversions.of(ResourceLocationArgument.getId(c, p)), (ctx, builder) -> SharedSuggestionProvider.suggestResource(ctx.getSource().getServer().getLootData().getKeys(LootDataType.TABLE), builder) ), new VanillaUnconfigurableArgument("attribute", Registries.ATTRIBUTE), diff --git a/src/main/java/carpet/script/utils/Colors.java b/src/main/java/carpet/script/utils/Colors.java index d6c01eac92..7503cb9ff4 100644 --- a/src/main/java/carpet/script/utils/Colors.java +++ b/src/main/java/carpet/script/utils/Colors.java @@ -156,51 +156,11 @@ public class Colors ); public static final Map materialName = Map.ofEntries( - entry(Material.AIR , "air" ), - entry(Material.STRUCTURAL_AIR , "void" ), - entry(Material.PORTAL , "portal" ), - entry(Material.CLOTH_DECORATION , "carpet" ), entry(Material.PLANT , "plant" ), - entry(Material.WATER_PLANT, "water_plant" ), - entry(Material.REPLACEABLE_PLANT, "vegetation" ), - entry(Material.REPLACEABLE_FIREPROOF_PLANT, "nether_shoots" ), - entry(Material.REPLACEABLE_WATER_PLANT, "sea_grass" ), - entry(Material.WATER , "water" ), - entry(Material.BUBBLE_COLUMN , "bubble_column"), - entry(Material.LAVA , "lava" ), - entry(Material.TOP_SNOW , "snow_layer" ), - entry(Material.FIRE , "fire" ), - entry(Material.DECORATION , "decoration" ), - entry(Material.WEB , "cobweb" ), - entry(Material.SCULK , "sculk" ), - entry(Material.BUILDABLE_GLASS , "redstone_lamp"), - entry(Material.CLAY, "clay" ), - entry(Material.DIRT , "dirt" ), - entry(Material.GRASS , "grass" ), - entry(Material.ICE_SOLID , "packed_ice" ), + entry(Material.DEPRECATED_REPLACEABLE, "vegetation" ), entry(Material.SAND , "sand" ), - entry(Material.SPONGE , "sponge" ), - entry(Material.SHULKER_SHELL , "shulker" ), entry(Material.WOOD , "wood" ), - entry(Material.BAMBOO_SAPLING , "shoots" ), - entry(Material.BAMBOO , "bamboo" ), - entry(Material.WOOL , "wool" ), - entry(Material.EXPLOSIVE , "tnt" ), - entry(Material.LEAVES , "leaves" ), entry(Material.GLASS , "glass" ), - entry(Material.ICE , "ice" ), - entry(Material.CACTUS , "cactus" ), - entry(Material.STONE , "stone" ), - entry(Material.METAL , "metal" ), - entry(Material.SNOW , "snow" ), - entry(Material.HEAVY_METAL , "anvil" ), - entry(Material.BARRIER , "barrier" ), - entry(Material.PISTON , "piston" ), - entry(Material.MOSS , "moss" ), - entry(Material.VEGETABLE , "gourd" ), - entry(Material.EGG , "dragon_egg" ), - entry(Material.CAKE , "cake" ), - entry(Material.AMETHYST , "amethyst" ), - entry(Material.POWDER_SNOW , "powder_snow") + entry(Material.STONE , "stone" ) ); } diff --git a/src/main/java/carpet/utils/BlockInfo.java b/src/main/java/carpet/utils/BlockInfo.java index 755e41034f..70e417e911 100644 --- a/src/main/java/carpet/utils/BlockInfo.java +++ b/src/main/java/carpet/utils/BlockInfo.java @@ -17,6 +17,7 @@ import net.minecraft.world.entity.monster.ZombifiedPiglin; import net.minecraft.world.level.LightLayer; import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.Material; import net.minecraft.world.level.pathfinder.PathComputationType; @@ -39,13 +40,12 @@ public static List blockInfo(BlockPos pos, ServerLevel world) lst.add(Messenger.s("")); lst.add(Messenger.s("=====================================")); lst.add(Messenger.s(String.format("Block info for %s%s (id %d%s):", blocks.getKey(block),metastring, blocks.getId(block), metastring ))); - lst.add(Messenger.s(String.format(" - Material: %s", Colors.materialName.get(material)))); lst.add(Messenger.s(String.format(" - Map colour: %s", Colors.mapColourName.get(state.getMapColor(world, pos))))); lst.add(Messenger.s(String.format(" - Sound type: %s", Colors.soundName.get(block.getSoundType(state))))); lst.add(Messenger.s("")); lst.add(Messenger.s(String.format(" - Full block: %s", state.isCollisionShapeFullBlock(world, pos)))); // isFullCube() ))); lst.add(Messenger.s(String.format(" - Normal cube: %s", state.isRedstoneConductor(world, pos)))); //isNormalCube()))); isSimpleFullBlock - lst.add(Messenger.s(String.format(" - Is liquid: %s", material.isLiquid()))); + lst.add(Messenger.s(String.format(" - Is liquid: %s", state.is(Blocks.WATER) || state.is(Blocks.LAVA)))); lst.add(Messenger.s("")); lst.add(Messenger.s(String.format(" - Light in: %d, above: %d", Math.max(world.getBrightness(LightLayer.BLOCK, pos),world.getBrightness(LightLayer.SKY, pos)) , diff --git a/src/main/java/carpet/utils/PerimeterDiagnostics.java b/src/main/java/carpet/utils/PerimeterDiagnostics.java index c24dd384bc..0245419d9c 100644 --- a/src/main/java/carpet/utils/PerimeterDiagnostics.java +++ b/src/main/java/carpet/utils/PerimeterDiagnostics.java @@ -4,6 +4,7 @@ import java.util.List; import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerLevel; +import net.minecraft.tags.FluidTags; import net.minecraft.world.entity.AgeableMob; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.Mob; @@ -18,7 +19,6 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.material.Material; public class PerimeterDiagnostics { @@ -114,7 +114,7 @@ else if (el instanceof AmbientCreature) BlockState iblockstate_down = worldserver.getBlockState(pos.below()); BlockState iblockstate_up = worldserver.getBlockState(pos.above()); - if ( iblockstate.getMaterial() == Material.WATER && iblockstate_down.getMaterial() == Material.WATER && !iblockstate_up.isRedstoneConductor(worldserver, pos)) // isSimpleFUllBLock + if ( iblockstate.getFluidState().is(FluidTags.WATER) && !iblockstate_up.isRedstoneConductor(worldserver, pos)) // isSimpleFUllBLock { result.liquid++; if (add_water && diagnostic.check_entity_spawn(pos)) diff --git a/src/main/java/carpet/utils/WoolTool.java b/src/main/java/carpet/utils/WoolTool.java index b09a57a7a6..69e327ae99 100644 --- a/src/main/java/carpet/utils/WoolTool.java +++ b/src/main/java/carpet/utils/WoolTool.java @@ -13,14 +13,16 @@ import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerLevel; +import net.minecraft.tags.BlockTags; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.DyeColor; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.material.Material; import net.minecraft.world.level.material.MaterialColor; import net.minecraft.world.phys.Vec3; +import javax.annotation.Nullable; + import static java.util.Map.entry; /** @@ -129,11 +131,15 @@ public static void carpetPlacedAction(DyeColor color, Player placer, BlockPos po /** * Gets the colour of wool at the position, for hoppers to be able to decide whether to add their items to the global counter. */ + @Nullable public static DyeColor getWoolColorAtPosition(Level worldIn, BlockPos pos) { BlockState state = worldIn.getBlockState(pos); - if (state.getMaterial() != Material.WOOL || !state.isRedstoneConductor(worldIn, pos)) //isSimpleFullBlock + // wool and wool carpets + if (!state.is(BlockTags.WOOL)) + { return null; + } return Material2Dye.get(state.getMapColor(worldIn, pos)); } } From 8b7e6209c74b493cc826faee420dc58240716ad3 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 5 Apr 2023 20:12:43 +0200 Subject: [PATCH 112/233] 1.4.104 --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 206ee06677..0d256ecb04 100644 --- a/gradle.properties +++ b/gradle.properties @@ -9,7 +9,7 @@ org.gradle.jvmargs=-Xmx1G fabric_version=0.77.0+1.19.4 # Mod Properties - mod_version = 1.4.103 + mod_version = 1.4.104 maven_group = carpet archives_base_name = fabric-carpet From d5cd0331b3827fb6411dd5889259cb1ca79aa187 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Wed, 5 Apr 2023 18:33:35 +0000 Subject: [PATCH 113/233] Merge docs for 'Carpet Mod 1.4.104 for Minecraft 23w14a' --- docs/scarpet/Full.md | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/docs/scarpet/Full.md b/docs/scarpet/Full.md index 9195f08b31..8072b89e36 100644 --- a/docs/scarpet/Full.md +++ b/docs/scarpet/Full.md @@ -2814,15 +2814,9 @@ Returns the name of sound type made by the block at position. One of: `'candle'`', `'amethyst'`', `'amethyst_cluster'`', `'small_amethyst_bud'`', `'large_amethyst_bud'`', `'medium_amethyst_bud'`', `'tuff'`', `'calcite'`', `'copper'`' -### `material(pos)` +### `(Deprecated) material(pos)` -Returns the name of material of the block at position. very useful to target a group of blocks. One of: - -`'air'`, `'void'`, `'portal'`, `'carpet'`, `'plant'`, `'water_plant'`, `'vine'`, `'sea_grass'`, `'water'`, -`'bubble_column'`, `'lava'`, `'snow_layer'`, `'fire'`, `'redstone_bits'`, `'cobweb'`, `'redstone_lamp'`, `'clay'`, -`'dirt'`, `'grass'`, `'packed_ice'`, `'sand'`, `'sponge'`, `'wood'`, `'wool'`, `'tnt'`, `'leaves'`, `'glass'`, -`'ice'`, `'cactus'`, `'stone'`, `'iron'`, `'snow'`, `'anvil'`, `'barrier'`, `'piston'`, `'coral'`, `'gourd'`, -`'dragon_egg'`, `'cake'`, `'amethyst'` +Returns the name of material of the block at position. Very limited as the use of material for blocks is removed. ### `map_colour(pos)` From a3762584f376c9a704a0bbefc8aa9ac37fa85f0b Mon Sep 17 00:00:00 2001 From: altrisi Date: Sat, 8 Apr 2023 16:12:38 +0200 Subject: [PATCH 114/233] Use for loop for hopper counter info in `HUDController` --- src/main/java/carpet/logging/HUDController.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/java/carpet/logging/HUDController.java b/src/main/java/carpet/logging/HUDController.java index d941ab6404..9ac95b7b35 100644 --- a/src/main/java/carpet/logging/HUDController.java +++ b/src/main/java/carpet/logging/HUDController.java @@ -132,13 +132,14 @@ public static void update_hud(MinecraftServer server, List force) "g MSPT: ", String.format(Locale.US,"%s %.1f", color, MSPT))}; } - private static Component [] send_counter_info(MinecraftServer server, String color) + private static Component[] send_counter_info(MinecraftServer server, String colors) { List res = new ArrayList<>(); - Arrays.asList(color.split(",")).forEach(c ->{ - HopperCounter counter = HopperCounter.getCounter(c); + for (String color : colors.split(",")) + { + HopperCounter counter = HopperCounter.getCounter(color); if (counter != null) res.addAll(counter.format(server, false, true)); - }); + } return res.toArray(new Component[0]); } private static Component [] packetCounter() From 6b9e7aff3eedce591f7ff3a6f4698b5f5e5f5155 Mon Sep 17 00:00:00 2001 From: altrisi Date: Sat, 8 Apr 2023 16:14:47 +0200 Subject: [PATCH 115/233] Use `List.of` in `EquipmentInventory` `Arrays.asList` isn't immutable, and `List.of` can be optimized slightly better, is more readable and also removes an import --- src/main/java/carpet/script/utils/EquipmentInventory.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/carpet/script/utils/EquipmentInventory.java b/src/main/java/carpet/script/utils/EquipmentInventory.java index c6d6ca0559..1be44addd4 100644 --- a/src/main/java/carpet/script/utils/EquipmentInventory.java +++ b/src/main/java/carpet/script/utils/EquipmentInventory.java @@ -1,6 +1,5 @@ package carpet.script.utils; -import java.util.Arrays; import java.util.List; import net.minecraft.world.Container; @@ -11,7 +10,7 @@ public class EquipmentInventory implements Container { - private static final List slotToSlot = Arrays.asList( + private static final List slotToSlot = List.of( EquipmentSlot.MAINHAND, EquipmentSlot.FEET, EquipmentSlot.LEGS, EquipmentSlot.CHEST, EquipmentSlot.HEAD, EquipmentSlot.OFFHAND From 17c2d601d2486e2479288a7199e8f66b38c6487b Mon Sep 17 00:00:00 2001 From: altrisi Date: Sat, 8 Apr 2023 19:48:52 +0200 Subject: [PATCH 116/233] Remove global server reference from `Player_antiCheatDisabledMixin` --- .../java/carpet/mixins/Player_antiCheatDisabledMixin.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/carpet/mixins/Player_antiCheatDisabledMixin.java b/src/main/java/carpet/mixins/Player_antiCheatDisabledMixin.java index 621f7f4dc7..8a9625dc0a 100644 --- a/src/main/java/carpet/mixins/Player_antiCheatDisabledMixin.java +++ b/src/main/java/carpet/mixins/Player_antiCheatDisabledMixin.java @@ -1,7 +1,7 @@ package carpet.mixins; -import carpet.CarpetServer; import carpet.CarpetSettings; +import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ElytraItem; @@ -23,7 +23,7 @@ public abstract class Player_antiCheatDisabledMixin @Inject(method = "tryToStartFallFlying", at = @At("HEAD"), cancellable = true) private void allowDeploys(CallbackInfoReturnable cir) { - if (CarpetSettings.antiCheatDisabled && CarpetServer.minecraft_server != null && CarpetServer.minecraft_server.isDedicatedServer()) + if (CarpetSettings.antiCheatDisabled && (Object)this instanceof ServerPlayer sp && sp.getServer().isDedicatedServer()) { ItemStack itemStack_1 = getItemBySlot(EquipmentSlot.CHEST); if (itemStack_1.getItem() == Items.ELYTRA && ElytraItem.isFlyEnabled(itemStack_1)) { From 8cd60db5e443ee5a6235b274cef49a70be73c54d Mon Sep 17 00:00:00 2001 From: altrisi Date: Sat, 8 Apr 2023 20:01:30 +0200 Subject: [PATCH 117/233] Random cleanups to users of Level.OVERWORLD and reduce `minecraft_server` usage (#1697) - Use `overworld()` instead of `getLevel(Level.OVERWORLD)` when convenient - Remove now unnecessary `// OW` comments, from when it had no mappings - Make spawn chunk size and light batches not depend on global server instance - Merge all spawn chunk size logic into SpawnChunks instead of methods in the validator - Remove unneeded `withWorld(OVERWORLD)` with just-created server `CommandSource`s - Use enhanced for in light batch application --- src/main/java/carpet/CarpetSettings.java | 32 ++++--------------- .../mixins/MinecraftServer_coreMixin.java | 10 ++++-- .../ServerPlayer_scarpetEventMixin.java | 2 +- .../java/carpet/script/CarpetEventServer.java | 12 ++----- src/main/java/carpet/utils/Messenger.java | 6 ++-- src/main/java/carpet/utils/SpawnChunks.java | 14 +++++--- 6 files changed, 30 insertions(+), 46 deletions(-) diff --git a/src/main/java/carpet/CarpetSettings.java b/src/main/java/carpet/CarpetSettings.java index 3e9bd5622e..b837e1082a 100644 --- a/src/main/java/carpet/CarpetSettings.java +++ b/src/main/java/carpet/CarpetSettings.java @@ -12,7 +12,6 @@ import carpet.utils.SpawnChunks; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.commands.CommandSourceStack; -import net.minecraft.core.BlockPos; import net.minecraft.core.registries.Registries; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; @@ -21,7 +20,6 @@ import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; -import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.GameRules; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; @@ -34,7 +32,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Iterator; import java.util.Optional; import static carpet.api.settings.RuleCategory.BUGFIX; @@ -810,18 +807,6 @@ private static class SimulationDistanceValidator extends Validator public static int simulationDistance = 0; public static class ChangeSpawnChunksValidator extends Validator { - public static void changeSpawnSize(int size) - { - ServerLevel overworld = CarpetServer.minecraft_server.getLevel(Level.OVERWORLD); // OW - if (overworld != null) { - ChunkPos centerChunk = new ChunkPos(new BlockPos( - overworld.getLevelData().getXSpawn(), - overworld.getLevelData().getYSpawn(), - overworld.getLevelData().getZSpawn() - )); - SpawnChunks.changeSpawnChunks(overworld.getChunkSource(), centerChunk, size); - } - } @Override public Integer validate(CommandSourceStack source, CarpetRule currentRule, Integer newValue, String string) { if (source == null) return newValue; if (newValue < 0 || newValue > 32) @@ -834,11 +819,10 @@ public static void changeSpawnSize(int size) //must been some startup thing return newValue; } - if (CarpetServer.minecraft_server == null) return newValue; - ServerLevel currentOverworld = CarpetServer.minecraft_server.getLevel(Level.OVERWORLD); // OW + ServerLevel currentOverworld = source.getServer().overworld(); if (currentOverworld != null) { - changeSpawnSize(newValue); + SpawnChunks.changeSpawnSize(currentOverworld, newValue); } return newValue; } @@ -854,14 +838,11 @@ public static void changeSpawnSize(int size) public static int spawnChunksSize = MinecraftServer.START_CHUNK_RADIUS; public static class LightBatchValidator extends Validator { - public static void applyLightBatchSizes(int maxBatchSize) + public static void applyLightBatchSizes(MinecraftServer server, int maxBatchSize) { - Iterator iterator = CarpetServer.minecraft_server.getAllLevels().iterator(); - - while (iterator.hasNext()) + for (ServerLevel world : server.getAllLevels()) { - ServerLevel serverWorld = iterator.next(); - serverWorld.getChunkSource().getLightEngine().setTaskPerBatch(maxBatchSize); + world.getChunkSource().getLightEngine().setTaskPerBatch(maxBatchSize); } } @Override public Integer validate(CommandSourceStack source, CarpetRule currentRule, Integer newValue, String string) { @@ -876,9 +857,8 @@ public static void applyLightBatchSizes(int maxBatchSize) //must been some startup thing return newValue; } - if (CarpetServer.minecraft_server == null) return newValue; - applyLightBatchSizes(newValue); // Apply new settings + applyLightBatchSizes(source.getServer(), newValue); // Apply new settings return newValue; } diff --git a/src/main/java/carpet/mixins/MinecraftServer_coreMixin.java b/src/main/java/carpet/mixins/MinecraftServer_coreMixin.java index 6baa8f36b4..1d54415d4f 100644 --- a/src/main/java/carpet/mixins/MinecraftServer_coreMixin.java +++ b/src/main/java/carpet/mixins/MinecraftServer_coreMixin.java @@ -3,9 +3,12 @@ import carpet.CarpetServer; import carpet.CarpetSettings; import carpet.utils.CarpetProfiler; +import carpet.utils.SpawnChunks; import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.progress.ChunkProgressListener; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @@ -56,12 +59,15 @@ private void serverDoneClosed(CallbackInfo ci) CarpetServer.onServerDoneClosing((MinecraftServer) (Object) this); } + @Shadow + public abstract ServerLevel overworld(); + @Inject(method = "prepareLevels", at = @At("RETURN")) private void afterSpawnCreated(ChunkProgressListener worldGenerationProgressListener, CallbackInfo ci) { if (CarpetSettings.spawnChunksSize != 11) - CarpetSettings.ChangeSpawnChunksValidator.changeSpawnSize(CarpetSettings.spawnChunksSize); + SpawnChunks.changeSpawnSize(overworld(), CarpetSettings.spawnChunksSize); - CarpetSettings.LightBatchValidator.applyLightBatchSizes(CarpetSettings.lightEngineMaxBatchSize); + CarpetSettings.LightBatchValidator.applyLightBatchSizes((MinecraftServer) (Object) this, CarpetSettings.lightEngineMaxBatchSize); } } diff --git a/src/main/java/carpet/mixins/ServerPlayer_scarpetEventMixin.java b/src/main/java/carpet/mixins/ServerPlayer_scarpetEventMixin.java index 0a76eb7b82..506690539d 100644 --- a/src/main/java/carpet/mixins/ServerPlayer_scarpetEventMixin.java +++ b/src/main/java/carpet/mixins/ServerPlayer_scarpetEventMixin.java @@ -110,7 +110,7 @@ private void atChangeDimension(ServerLevel destination, CallbackInfoReturnable publicEvents(CarpetScriptServer server) @Override public void onTick(MinecraftServer server) { - handler.call(Collections::emptyList, () -> - server.createCommandSourceStack().withLevel(server.getLevel(Level.OVERWORLD)) - ); + handler.call(Collections::emptyList, server::createCommandSourceStack); } }; @@ -458,9 +456,7 @@ public void onTick(MinecraftServer server) @Override public void onTick(MinecraftServer server) { - handler.call(Collections::emptyList, () -> - server.createCommandSourceStack().withLevel(server.getLevel(Level.OVERWORLD)) - ); + handler.call(Collections::emptyList,server::createCommandSourceStack); } }; @@ -469,9 +465,7 @@ public void onTick(MinecraftServer server) @Override public void onTick(MinecraftServer server) { - handler.call(Collections::emptyList, () -> - server.createCommandSourceStack().withLevel(server.getLevel(Level.OVERWORLD)) - ); + handler.call(Collections::emptyList,server::createCommandSourceStack); } }; public static final Event NETHER_TICK = new Event("tick_nether", 0, true) diff --git a/src/main/java/carpet/utils/Messenger.java b/src/main/java/carpet/utils/Messenger.java index 36b9fce566..bc1ac9f9ad 100644 --- a/src/main/java/carpet/utils/Messenger.java +++ b/src/main/java/carpet/utils/Messenger.java @@ -1,7 +1,6 @@ package carpet.utils; import net.minecraft.ChatFormatting; -import net.minecraft.Util; import net.minecraft.commands.CommandSourceStack; import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; @@ -13,7 +12,6 @@ import net.minecraft.server.MinecraftServer; import net.minecraft.world.entity.MobCategory; import net.minecraft.world.entity.player.Player; -import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -162,7 +160,7 @@ public static Component tp(String desc, float x, float y, float z) } public static Component tp(String desc, int x, int y, int z) { - return getCoordsTextComponent(desc, (float)x, (float)y, (float)z, true); + return getCoordsTextComponent(desc, x, y, z, true); } /// to be continued @@ -233,7 +231,7 @@ private static Component getCoordsTextComponent(String style, float x, float y, public static void m(CommandSourceStack source, Object ... fields) { if (source != null) - source.sendSuccess(Messenger.c(fields),source.getServer() != null && source.getServer().getLevel(Level.OVERWORLD) != null); //OW + source.sendSuccess(Messenger.c(fields), source.getServer() != null && source.getServer().overworld() != null); } public static void m(Player player, Object ... fields) { diff --git a/src/main/java/carpet/utils/SpawnChunks.java b/src/main/java/carpet/utils/SpawnChunks.java index 9631d4689f..1d7042ca1a 100644 --- a/src/main/java/carpet/utils/SpawnChunks.java +++ b/src/main/java/carpet/utils/SpawnChunks.java @@ -1,15 +1,21 @@ package carpet.utils; import carpet.fakes.ChunkTicketManagerInterface; +import net.minecraft.core.BlockPos; import net.minecraft.server.level.DistanceManager; -import net.minecraft.server.level.ServerChunkCache; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.ChunkPos; public class SpawnChunks { - public static void changeSpawnChunks(ServerChunkCache chunkManager, ChunkPos pos, int size) + public static void changeSpawnSize(ServerLevel overworld, int size) { - DistanceManager ticketManager = chunkManager.chunkMap.getDistanceManager(); - ((ChunkTicketManagerInterface)ticketManager).changeSpawnChunks(pos, size); + ChunkPos centerChunk = new ChunkPos(new BlockPos( + overworld.getLevelData().getXSpawn(), + overworld.getLevelData().getYSpawn(), + overworld.getLevelData().getZSpawn() + )); + DistanceManager ticketManager = overworld.getChunkSource().chunkMap.getDistanceManager(); + ((ChunkTicketManagerInterface)ticketManager).changeSpawnChunks(centerChunk, size); } } From 51f213fa15cbbd70c5a73f4d5fecb280ac33f846 Mon Sep 17 00:00:00 2001 From: altrisi Date: Sat, 8 Apr 2023 20:14:26 +0200 Subject: [PATCH 118/233] Cleanup counter command (#1695) - Import `Commands.literal` - Use more readable syntax for Brigadier command - Use `DyeColor` directly instead of toString -> fromString everywhere - Also updates `WoolTool` to use the new `HopperCounter` getter that supports it - Split `resetCounter` in two, one for single and one for all Also: HopperCounter now uses `.overworld()` and its `//OW` comments are removed --- .../java/carpet/commands/CounterCommand.java | 68 ++++++++----------- .../java/carpet/helpers/HopperCounter.java | 15 ++-- src/main/java/carpet/utils/WoolTool.java | 8 +-- 3 files changed, 43 insertions(+), 48 deletions(-) diff --git a/src/main/java/carpet/commands/CounterCommand.java b/src/main/java/carpet/commands/CounterCommand.java index ebb004f5ce..5c3ace277f 100644 --- a/src/main/java/carpet/commands/CounterCommand.java +++ b/src/main/java/carpet/commands/CounterCommand.java @@ -6,16 +6,15 @@ import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.builder.LiteralArgumentBuilder; import net.minecraft.commands.CommandBuildContext; -import net.minecraft.commands.CommandRuntimeException; import net.minecraft.commands.CommandSourceStack; -import net.minecraft.commands.Commands; import net.minecraft.network.chat.Component; import net.minecraft.world.item.DyeColor; +import static net.minecraft.commands.Commands.literal; + /** * Class for the /counter command which allows to use hoppers pointing into wool */ - public class CounterCommand { /** @@ -23,26 +22,24 @@ public class CounterCommand */ public static void register(CommandDispatcher dispatcher, CommandBuildContext commandBuildContext) { - LiteralArgumentBuilder literalargumentbuilder = Commands.literal("counter").executes((context) - -> listAllCounters(context.getSource(), false)).requires((player) -> - CarpetSettings.hopperCounters); + LiteralArgumentBuilder commandBuilder = literal("counter") + .requires(c -> CarpetSettings.hopperCounters) + .executes(c -> listAllCounters(c.getSource(), false)) + .then(literal("reset") + .executes(c -> resetCounters(c.getSource()))); - literalargumentbuilder. - then((Commands.literal("reset").executes( (context)-> - resetCounter(context.getSource(), null)))); - for (DyeColor enumDyeColor: DyeColor.values()) + for (DyeColor dyeColor : DyeColor.values()) { - String color = enumDyeColor.toString(); - literalargumentbuilder. - then((Commands.literal(color).executes( (context)-> displayCounter(context.getSource(), color, false)))); - literalargumentbuilder.then(Commands.literal(color). - then(Commands.literal("reset").executes((context) -> - resetCounter(context.getSource(), color)))); - literalargumentbuilder.then(Commands.literal(color). - then(Commands.literal("realtime").executes((context) -> - displayCounter(context.getSource(), color, true)))); + commandBuilder.then( + literal(dyeColor.toString()) + .executes(c -> displayCounter(c.getSource(), dyeColor, false)) + .then(literal("reset") + .executes(c -> resetCounter(c.getSource(), dyeColor))) + .then(literal("realtime") + .executes(c -> displayCounter(c.getSource(), dyeColor, true))) + ); } - dispatcher.register(literalargumentbuilder); + dispatcher.register(commandBuilder); } /** @@ -52,10 +49,9 @@ public static void register(CommandDispatcher dispatcher, Co * would make it slower than IRL */ - private static int displayCounter(CommandSourceStack source, String color, boolean realtime) + private static int displayCounter(CommandSourceStack source, DyeColor color, boolean realtime) { HopperCounter counter = HopperCounter.getCounter(color); - if (counter == null) throw new CommandRuntimeException(Messenger.s("Unknown wool color: "+color)); for (Component message: counter.format(source.getServer(), realtime, false)) { @@ -64,25 +60,22 @@ private static int displayCounter(CommandSourceStack source, String color, boole return 1; } + private static int resetCounters(CommandSourceStack source) + { + HopperCounter.resetAll(source.getServer(), false); + Messenger.m(source, "w Restarted all counters"); + return 1; + } + /** - * A method to reset the counter's timer to 0 and empty its items. If the {@code color} parameter is {@code null}, - * it will reset all counters. + * A method to reset the counter's timer to 0 and empty its items + * * @param color The counter whose contents we want to reset */ - private static int resetCounter(CommandSourceStack source, String color) + private static int resetCounter(CommandSourceStack source, DyeColor color) { - if (color == null) - { - HopperCounter.resetAll(source.getServer(), false); - Messenger.m(source, "w Restarted all counters"); - } - else - { - HopperCounter counter = HopperCounter.getCounter(color); - if (counter == null) throw new CommandRuntimeException(Messenger.s("Unknown wool color")); - counter.reset(source.getServer()); - Messenger.m(source, "w Restarted "+color+" counter"); - } + HopperCounter.getCounter(color).reset(source.getServer()); + Messenger.m(source, "w Restarted " + color + " counter"); return 1; } @@ -99,5 +92,4 @@ private static int listAllCounters(CommandSourceStack source, boolean realtime) } return 1; } - } diff --git a/src/main/java/carpet/helpers/HopperCounter.java b/src/main/java/carpet/helpers/HopperCounter.java index f7f5159791..94c19e539f 100644 --- a/src/main/java/carpet/helpers/HopperCounter.java +++ b/src/main/java/carpet/helpers/HopperCounter.java @@ -10,7 +10,6 @@ import net.minecraft.ChatFormatting; import net.minecraft.core.Registry; import net.minecraft.core.RegistryAccess; -import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.Registries; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; @@ -27,7 +26,6 @@ import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.item.crafting.Recipe; import net.minecraft.world.item.crafting.RecipeType; -import net.minecraft.world.level.Level; import net.minecraft.world.level.block.AbstractBannerBlock; import net.minecraft.world.level.block.BeaconBeamBlock; import net.minecraft.world.level.block.Block; @@ -114,7 +112,7 @@ public void add(MinecraftServer server, ItemStack stack) { if (startTick < 0) { - startTick = server.getLevel(Level.OVERWORLD).getGameTime(); //OW + startTick = server.overworld().getGameTime(); startMillis = System.currentTimeMillis(); } Item item = stack.getItem(); @@ -128,7 +126,7 @@ public void add(MinecraftServer server, ItemStack stack) public void reset(MinecraftServer server) { counter.clear(); - startTick = server.getLevel(Level.OVERWORLD).getGameTime(); //OW + startTick = server.overworld().getGameTime(); startMillis = System.currentTimeMillis(); // pubSubProvider.publish(); } @@ -175,7 +173,7 @@ public static List formatAll(MinecraftServer server, boolean realtime */ public List format(MinecraftServer server, boolean realTime, boolean brief) { - long ticks = Math.max(realTime ? (System.currentTimeMillis() - startMillis) / 50 : server.getLevel(Level.OVERWORLD).getGameTime() - startTick, 1); //OW + long ticks = Math.max(realTime ? (System.currentTimeMillis() - startMillis) / 50 : server.overworld().getGameTime() - startTick, 1); if (startTick < 0 || ticks == 0) { if (brief) @@ -391,6 +389,13 @@ public static TextColor guessColor(Item item, RegistryAccess registryAccess) return null; } + /** + * Returns the hopper counter for the given color + */ + public static HopperCounter getCounter(DyeColor color) { + return COUNTERS.get(color); + } + /** * Returns the hopper counter from the colour name, if not null */ diff --git a/src/main/java/carpet/utils/WoolTool.java b/src/main/java/carpet/utils/WoolTool.java index 69e327ae99..fa1bc79e0d 100644 --- a/src/main/java/carpet/utils/WoolTool.java +++ b/src/main/java/carpet/utils/WoolTool.java @@ -107,9 +107,8 @@ public static void carpetPlacedAction(DyeColor color, Player placer, BlockPos po { DyeColor under = getWoolColorAtPosition(worldIn, pos.below()); if (under == null) return; - HopperCounter counter = HopperCounter.getCounter(under.toString()); - if (counter != null) - Messenger.send(placer, counter.format(worldIn.getServer(), false, false)); + HopperCounter counter = HopperCounter.getCounter(under); + Messenger.send(placer, counter.format(worldIn.getServer(), false, false)); } break; case RED: @@ -117,8 +116,7 @@ public static void carpetPlacedAction(DyeColor color, Player placer, BlockPos po { DyeColor under = getWoolColorAtPosition(worldIn, pos.below()); if (under == null) return; - HopperCounter counter = HopperCounter.getCounter(under.toString()); - if (counter == null) return; + HopperCounter counter = HopperCounter.getCounter(under); counter.reset(placer.getServer()); List res = new ArrayList<>(); res.add(Messenger.s(String.format("%s counter reset",under.toString()))); From 384bd371599cfaba5ee52380d84c9b63e2d2e957 Mon Sep 17 00:00:00 2001 From: altrisi Date: Thu, 13 Apr 2023 20:27:20 +0200 Subject: [PATCH 119/233] Remove unnecessary `getPlayerOrException` in `TickCommand` --- src/main/java/carpet/commands/TickCommand.java | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/src/main/java/carpet/commands/TickCommand.java b/src/main/java/carpet/commands/TickCommand.java index 415973b134..191672168b 100644 --- a/src/main/java/carpet/commands/TickCommand.java +++ b/src/main/java/carpet/commands/TickCommand.java @@ -8,7 +8,6 @@ import carpet.utils.Messenger; import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.builder.LiteralArgumentBuilder; -import com.mojang.brigadier.exceptions.CommandSyntaxException; import net.minecraft.commands.CommandBuildContext; import net.minecraft.commands.CommandSourceStack; import net.minecraft.network.chat.Component; @@ -86,14 +85,7 @@ private static int queryTps(CommandSourceStack source) private static int setWarp(CommandSourceStack source, int advance, String tail_command) { - ServerPlayer player = null; - try - { - player = source.getPlayerOrException(); - } - catch (CommandSyntaxException ignored) - { - } + ServerPlayer player = source.getPlayer(); // may be null Component message = TickSpeed.tickrate_advance(player, advance, tail_command, source); source.sendSuccess(message, false); return 1; From 598ec82d025cf255095478d22e461d8682bb0adb Mon Sep 17 00:00:00 2001 From: Ghoulboy Date: Sat, 15 Apr 2023 21:33:54 +0200 Subject: [PATCH 120/233] Replace deprecated `world_time()` with `system_info('world_time')` (#1702) --- src/main/resources/assets/carpet/scripts/ai_tracker.sc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/resources/assets/carpet/scripts/ai_tracker.sc b/src/main/resources/assets/carpet/scripts/ai_tracker.sc index 09148e909d..6bf87ab5ab 100644 --- a/src/main/resources/assets/carpet/scripts/ai_tracker.sc +++ b/src/main/resources/assets/carpet/scripts/ai_tracker.sc @@ -59,13 +59,13 @@ global_functions = { entry = query(e, 'brain', 'last_slept'); - slept = world_time()-entry; + slept = system_info('world_time')-entry; last_slept = format(if(entry == null, 'rb never', if(slept < 24000, 'e ', 'y ')+slept)); labels = [ ['golem timer', 'golem:', format(if(last_seen,'rb ','eb ')+last_seen )], ['sleep tracker', 'slept:', last_slept], - ['attempt', 'attempt in:', format(if( slept < 24000 && last_seen==0,'yb ','gi ')+ (100-(world_time()%100)))], + ['attempt', 'attempt in:', format(if( slept < 24000 && last_seen==0,'yb ','gi ')+ (100-(system_info('world_time')%100)))], ]; [visuals, abnoxious_visuals, labels]; ) From c9b93e598aafea9d44b9f73ee759e129c858b631 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Thu, 20 Apr 2023 14:26:40 +0200 Subject: [PATCH 121/233] added two argument while loop because duh? --- .../language/LoopsAndHigherOrderFunctions.md | 5 +-- .../java/carpet/script/language/Loops.java | 36 ++++++++++++++++++- 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/docs/scarpet/language/LoopsAndHigherOrderFunctions.md b/docs/scarpet/language/LoopsAndHigherOrderFunctions.md index 41a1c5aa2d..34409e6d2b 100644 --- a/docs/scarpet/language/LoopsAndHigherOrderFunctions.md +++ b/docs/scarpet/language/LoopsAndHigherOrderFunctions.md @@ -49,13 +49,14 @@ for(range(1000000,1100000),check_prime(_)) => 7216 From which we can learn that there is 7216 primes between 1M and 1.1M -### `while(cond, limit, expr)` +### `while(cond, expr)`, `while(cond, limit, expr)` -Evaluates expression `expr` repeatedly until condition `cond` becomes false, but not more than `limit` times. +Evaluates expression `expr` repeatedly until condition `cond` becomes false, but not more than `limit` times (if limit is specified). Returns the result of the last `expr` evaluation, or `null` if nothing was successful. Both `expr` and `cond` will received a bound variable `_` indicating current iteration, so its a number.
    +while(a<100,a=_*_) => 100 // loop stopped at condition
     while(a<100,10,a=_*_)  => 81 // loop exhausted via limit
     while(a<100,20,a=_*_)  => 100 // loop stopped at condition, but a has already been assigned
     while(_*_<100,20,a=_*_)  => 81 // loop stopped at condition, before a was assigned a value
    diff --git a/src/main/java/carpet/script/language/Loops.java b/src/main/java/carpet/script/language/Loops.java
    index 5d6ac58fb2..552325dfde 100644
    --- a/src/main/java/carpet/script/language/Loops.java
    +++ b/src/main/java/carpet/script/language/Loops.java
    @@ -49,8 +49,42 @@ public static void apply(Expression expression)
             });
     
             // lazy
    -        expression.addLazyFunction("while", 3, (c, t, lv) ->
    +        expression.addLazyFunction("while", -1, (c, t, lv) ->
             {
    +            if (lv.size() == 2) { // lets do nasty way so performance is not affected (might be super unnecessary, but hey)
    +                LazyValue condition = lv.get(0);
    +                LazyValue expr = lv.get(1);
    +                long i = 0;
    +                Value lastOne = Value.NULL;
    +                //scoping
    +                LazyValue defaultVal = c.getVariable("_");
    +                c.setVariable("_", (cc, tt) -> new NumericValue(0).bindTo("_"));
    +                while (condition.evalValue(c, Context.BOOLEAN).getBoolean())
    +                {
    +                    try
    +                    {
    +                        lastOne = expr.evalValue(c, t);
    +                    }
    +                    catch (BreakStatement | ContinueStatement stmt)
    +                    {
    +                        if (stmt.retval != null)
    +                        {
    +                            lastOne = stmt.retval;
    +                        }
    +                        if (stmt instanceof BreakStatement)
    +                        {
    +                            break;
    +                        }
    +                    }
    +                    i++;
    +                    long seriously = i;
    +                    c.setVariable("_", (cc, tt) -> new NumericValue(seriously).bindTo("_"));
    +                }
    +                //revering scope
    +                c.setVariable("_", defaultVal);
    +                Value lastValueNoKidding = lastOne;
    +                return (cc, tt) -> lastValueNoKidding;
    +            }
                 long limit = NumericValue.asNumber(lv.get(1).evalValue(c)).getLong();
                 LazyValue condition = lv.get(0);
                 LazyValue expr = lv.get(2);
    
    From 51fae27708824e01391fc638cf877579609425fb Mon Sep 17 00:00:00 2001
    From: gnembon <41132274+gnembon@users.noreply.github.com>
    Date: Thu, 20 Apr 2023 20:46:33 +0200
    Subject: [PATCH 122/233] single argument print(foo) in player scoped apps will
     always target the player instance for chat message output.
    
    ---
     docs/scarpet/api/Auxiliary.md                  |  1 +
     src/main/java/carpet/script/api/Auxiliary.java | 18 ++++++++++++------
     2 files changed, 13 insertions(+), 6 deletions(-)
    
    diff --git a/docs/scarpet/api/Auxiliary.md b/docs/scarpet/api/Auxiliary.md
    index 3fad58260b..544ed6c2de 100644
    --- a/docs/scarpet/api/Auxiliary.md
    +++ b/docs/scarpet/api/Auxiliary.md
    @@ -245,6 +245,7 @@ produce an exception.
     ### `print(expr)`, `print(player/player_list, expr)`
     
     Displays the result of the expression to the chat. Overrides default `scarpet` behaviour of sending everything to stderr.
    +For player scoped apps it always by default targets the player for whom the app runs on behalf. 
     Can optionally define player or list of players to send the message to.
     
     ### `format(components, ...)`, `format([components, ...])`
    diff --git a/src/main/java/carpet/script/api/Auxiliary.java b/src/main/java/carpet/script/api/Auxiliary.java
    index 61dcd5dc94..c9818c29c3 100644
    --- a/src/main/java/carpet/script/api/Auxiliary.java
    +++ b/src/main/java/carpet/script/api/Auxiliary.java
    @@ -505,25 +505,31 @@ else if (!interactable && targetBlock == null)
                 {
                     throw new InternalExpressionException("'print' takes one or two arguments");
                 }
    -            CommandSourceStack s = ((CarpetContext) c).source();
    +            CarpetContext cc = (CarpetContext) c;
    +            CommandSourceStack s = cc.source();
                 MinecraftServer server = s.getServer();
                 Value res = lv.get(0);
    -            List targets = null;
    +            List targets = null;
                 if (lv.size() == 2)
                 {
                     List playerValues = (res instanceof ListValue list) ? list.getItems() : Collections.singletonList(res);
    -                List playerTargets = new ArrayList<>();
    +                List playerTargets = new ArrayList<>();
                     playerValues.forEach(pv -> {
                         ServerPlayer player = EntityValue.getPlayerByValue(server, pv);
                         if (player == null)
                         {
                             throw new InternalExpressionException("Cannot target player " + pv.getString() + " in print");
                         }
    -                    playerTargets.add(player);
    +                    playerTargets.add(player.createCommandSourceStack());
                     });
                     targets = playerTargets;
                     res = lv.get(1);
    -            }
    +            } else if (c.host.user != null) {
    +                ServerPlayer player = cc.server().getPlayerList().getPlayerByName(cc.host.user);
    +                if (player != null) {
    +                    targets = Collections.singletonList(player.createCommandSourceStack());
    +                }
    +            } // optionally retrieve from CC.host.responsibleSource to print?
                 Component message = FormattedTextValue.getTextByValue(res);
                 if (targets == null)
                 {
    @@ -531,7 +537,7 @@ else if (!interactable && targetBlock == null)
                 }
                 else
                 {
    -                targets.forEach(p -> p.createCommandSourceStack().sendSuccess(message, false));
    +                targets.forEach(p -> p.sendSuccess(message, false));
                 }
                 return res; // pass through for variables
             });
    
    From 97ab52a917d1a4758fa330dc0a1e25f24b712e83 Mon Sep 17 00:00:00 2001
    From: gnembon <41132274+gnembon@users.noreply.github.com>
    Date: Thu, 20 Apr 2023 22:02:33 +0200
    Subject: [PATCH 123/233] removal of `material()`
    
    ---
     docs/scarpet/api/BlocksAndWorldAccess.md | 3 ++-
     1 file changed, 2 insertions(+), 1 deletion(-)
    
    diff --git a/docs/scarpet/api/BlocksAndWorldAccess.md b/docs/scarpet/api/BlocksAndWorldAccess.md
    index 17684cf5d2..86d11329ad 100644
    --- a/docs/scarpet/api/BlocksAndWorldAccess.md
    +++ b/docs/scarpet/api/BlocksAndWorldAccess.md
    @@ -488,7 +488,8 @@ Returns the name of sound type made by the block at position. One of:
     
     ### `(Deprecated) material(pos)`
     
    -Returns the name of material of the block at position. Very limited as the use of material for blocks is removed.
    +Returns `'unknown'`. The concept of material for blocks is removed. On previous versions it returned the name of the material the block
    +was made of.
     
     ### `map_colour(pos)`
     
    
    From d68c252180110cdd77d670cbdda422908f1d5f10 Mon Sep 17 00:00:00 2001
    From: gnembon <41132274+gnembon@users.noreply.github.com>
    Date: Thu, 20 Apr 2023 22:13:32 +0200
    Subject: [PATCH 124/233] 23w16a
    
    ---
     gradle.properties                                    |  4 ++--
     src/main/java/carpet/helpers/OptimizedExplosion.java |  1 -
     .../mixins/ChunkMap_scarpetChunkCreationMixin.java   | 12 +++++++-----
     .../FlowingFluid_liquidDamageDisabledMixin.java      |  2 +-
     .../carpet/mixins/PickaxeItem_missingToolsMixin.java |  9 +++++----
     ...kEntityVibrationConfig_sculkSensorRangeMixin.java |  4 ++--
     src/main/java/carpet/script/api/WorldAccess.java     |  5 ++---
     src/main/java/carpet/script/utils/Colors.java        | 10 ----------
     .../carpet/script/utils/SnoopyCommandSource.java     |  4 ++--
     src/main/java/carpet/utils/BlockInfo.java            |  6 +-----
     src/main/resources/carpet.accesswidener              |  1 +
     11 files changed, 23 insertions(+), 35 deletions(-)
    
    diff --git a/gradle.properties b/gradle.properties
    index 0d256ecb04..4873ce8c55 100644
    --- a/gradle.properties
    +++ b/gradle.properties
    @@ -3,10 +3,10 @@ org.gradle.jvmargs=-Xmx1G
     
     # Fabric Properties
     	# check https://fabricmc.net/develop/
    -	minecraft_version=23w14a
    +	minecraft_version=23w16a
     	loader_version=0.14.19
     	jsr305_version=3.0.2
    -	fabric_version=0.77.0+1.19.4
    +	fabric_version=0.78.0+1.20
     
     # Mod Properties
     	mod_version = 1.4.104
    diff --git a/src/main/java/carpet/helpers/OptimizedExplosion.java b/src/main/java/carpet/helpers/OptimizedExplosion.java
    index cd869d509b..9345f7146d 100644
    --- a/src/main/java/carpet/helpers/OptimizedExplosion.java
    +++ b/src/main/java/carpet/helpers/OptimizedExplosion.java
    @@ -29,7 +29,6 @@
     import net.minecraft.world.level.block.state.BlockState;
     import net.minecraft.world.level.chunk.ChunkAccess;
     import net.minecraft.world.level.material.FluidState;
    -import net.minecraft.world.level.material.Material;
     import net.minecraft.world.level.storage.loot.LootContext;
     import net.minecraft.world.level.storage.loot.parameters.LootContextParams;
     import net.minecraft.world.phys.AABB;
    diff --git a/src/main/java/carpet/mixins/ChunkMap_scarpetChunkCreationMixin.java b/src/main/java/carpet/mixins/ChunkMap_scarpetChunkCreationMixin.java
    index 98e2743208..5087666d98 100644
    --- a/src/main/java/carpet/mixins/ChunkMap_scarpetChunkCreationMixin.java
    +++ b/src/main/java/carpet/mixins/ChunkMap_scarpetChunkCreationMixin.java
    @@ -99,13 +99,14 @@ public abstract class ChunkMap_scarpetChunkCreationMixin implements ThreadedAnvi
         @Shadow
         protected abstract boolean promoteChunkMap();
     
    -    @Shadow
    -    protected abstract CompletableFuture, ChunkLoadingFailure>> getChunkRangeFuture (final ChunkPos centerChunk, final int margin, final IntFunction distanceToStatus);
    -
         @Shadow
         protected abstract Iterable getChunks();
     
     
    +    @Shadow protected abstract CompletableFuture, ChunkLoadingFailure>> getChunkRangeFuture(final ChunkHolder chunkHolder, final int i, final IntFunction intFunction);
    +
    +    //@Shadow protected abstract void postLoadProtoChunk(final ServerLevel serverLevel, final List list);
    +
         ThreadLocal generated = ThreadLocal.withInitial(() -> null);
     
         // in protoChunkToFullChunk
    @@ -289,7 +290,8 @@ public void relightChunk(ChunkPos pos)
             if (!(chunk.getStatus().isOrAfter(ChunkStatus.LIGHT.getParent()))) return;
             ((ServerLightingProviderInterface) this.lightEngine).removeLightData(chunk);
             this.addRelightTicket(pos);
    -        final CompletableFuture lightFuture = this.getChunkRangeFuture (pos, 1, (pos_) -> ChunkStatus.LIGHT)
    +        ChunkHolder chunkHolder = this.updatingChunkMap.get(pos.toLong());
    +        final CompletableFuture lightFuture = this.getChunkRangeFuture(chunkHolder, 1, (pos_) -> ChunkStatus.LIGHT)
                     .thenCompose(
                         either -> either.map(
                                 list -> ((ServerLightingProviderInterface) this.lightEngine).relight(chunk),
    @@ -414,7 +416,7 @@ public Map regenerateChunkRegion(final List requested
             {
                 final ChunkPos pos = chunk.getPos();
     
    -            lightFutures.add(this.getChunkRangeFuture (pos, 1, (pos_) -> ChunkStatus.LIGHT).thenCompose(
    +            lightFutures.add(this.getChunkRangeFuture (this.updatingChunkMap.get(pos.toLong()), 1, (pos_) -> ChunkStatus.LIGHT).thenCompose(
                     either -> either.map(
                         list -> ((ServerLightingProviderInterface) this.lightEngine).relight(chunk),
                         unloaded -> {
    diff --git a/src/main/java/carpet/mixins/FlowingFluid_liquidDamageDisabledMixin.java b/src/main/java/carpet/mixins/FlowingFluid_liquidDamageDisabledMixin.java
    index 5d980f374f..933e0980f7 100644
    --- a/src/main/java/carpet/mixins/FlowingFluid_liquidDamageDisabledMixin.java
    +++ b/src/main/java/carpet/mixins/FlowingFluid_liquidDamageDisabledMixin.java
    @@ -19,7 +19,7 @@ public class FlowingFluid_liquidDamageDisabledMixin
                 method = "canHoldFluid",
                 at = @At(
                         value = "INVOKE",
    -                    target = "Lnet/minecraft/world/level/material/Material;blocksMotion()Z"
    +                    target = "Lnet/minecraft/world/level/block/state/BlockState;blocksMotion()Z"
                 ),
                 cancellable = true
         )
    diff --git a/src/main/java/carpet/mixins/PickaxeItem_missingToolsMixin.java b/src/main/java/carpet/mixins/PickaxeItem_missingToolsMixin.java
    index 750107c750..890dcdfbd6 100644
    --- a/src/main/java/carpet/mixins/PickaxeItem_missingToolsMixin.java
    +++ b/src/main/java/carpet/mixins/PickaxeItem_missingToolsMixin.java
    @@ -7,8 +7,8 @@
     import net.minecraft.world.item.PickaxeItem;
     import net.minecraft.world.item.Tier;
     import net.minecraft.world.level.block.Block;
    +import net.minecraft.world.level.block.SoundType;
     import net.minecraft.world.level.block.state.BlockState;
    -import net.minecraft.world.level.material.Material;
     import org.spongepowered.asm.mixin.Mixin;
     
     @Mixin(PickaxeItem.class)
    @@ -21,9 +21,10 @@ protected PickaxeItem_missingToolsMixin(float attackDamage, float attackSpeed, T
     
         @Override
         public float getDestroySpeed(ItemStack stack, BlockState state) {
    -        Material material = state.getMaterial();
    -        if (CarpetSettings.missingTools && material == Material.GLASS)
    -             return speed;
    +        if (CarpetSettings.missingTools && state.getBlock().getSoundType(state) == SoundType.GLASS)
    +        {
    +            return speed;
    +        }
             return super.getDestroySpeed(stack, state);
         }
     }
    diff --git a/src/main/java/carpet/mixins/SculkSensorBlockEntityVibrationConfig_sculkSensorRangeMixin.java b/src/main/java/carpet/mixins/SculkSensorBlockEntityVibrationConfig_sculkSensorRangeMixin.java
    index 8d3174544c..149f52b205 100644
    --- a/src/main/java/carpet/mixins/SculkSensorBlockEntityVibrationConfig_sculkSensorRangeMixin.java
    +++ b/src/main/java/carpet/mixins/SculkSensorBlockEntityVibrationConfig_sculkSensorRangeMixin.java
    @@ -8,13 +8,13 @@
     import org.spongepowered.asm.mixin.injection.Inject;
     import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
     
    -@Mixin(SculkSensorBlockEntity.VibrationConfig.class)
    +@Mixin(SculkSensorBlockEntity.VibrationUser.class)
     public class SculkSensorBlockEntityVibrationConfig_sculkSensorRangeMixin
     {
         @Inject(method = "getListenerRadius", at = @At("HEAD"), cancellable = true)
         private void sculkSensorRange(CallbackInfoReturnable cir)
         {
    -        if (CarpetSettings.sculkSensorRange != SculkSensorBlockEntity.VibrationConfig.LISTENER_RANGE) {
    +        if (CarpetSettings.sculkSensorRange != SculkSensorBlockEntity.VibrationUser.LISTENER_RANGE) {
                 cir.setReturnValue(CarpetSettings.sculkSensorRange);
             }
         }
    diff --git a/src/main/java/carpet/script/api/WorldAccess.java b/src/main/java/carpet/script/api/WorldAccess.java
    index 51cef699a5..eb757a9b8f 100644
    --- a/src/main/java/carpet/script/api/WorldAccess.java
    +++ b/src/main/java/carpet/script/api/WorldAccess.java
    @@ -527,7 +527,7 @@ else if (!("any".equals(statusString)))
                     booleanStateTest(c, "flammable", lv, (s, p) -> s.ignitedByLava()));
     
             expression.addContextFunction("transparent", -1, (c, t, lv) ->
    -                booleanStateTest(c, "transparent", lv, (s, p) -> !s.getMaterial().isSolid()));
    +                booleanStateTest(c, "transparent", lv, (s, p) -> !s.isSolid()));
     
             /*this.expr.addContextFunction("opacity", -1, (c, t, lv) ->
                     genericStateTest(c, "opacity", lv, (s, p, w) -> new NumericValue(s.getOpacity(w, p))));
    @@ -1162,8 +1162,7 @@ LivingEntity getIndirectSourceEntity()
     
             expression.addContextFunction("material", -1, (c, t, lv) -> {
                 c.host.issueDeprecation("material(...)"); // deprecated for block_state()
    -            return stateStringQuery(c, "material", lv, (s, p) ->
    -                    Colors.materialName.getOrDefault(s.getMaterial(), "unknown"));
    +            return StringValue.of("unknown");
             });
     
             expression.addContextFunction("map_colour", -1, (c, t, lv) ->
    diff --git a/src/main/java/carpet/script/utils/Colors.java b/src/main/java/carpet/script/utils/Colors.java
    index 7503cb9ff4..5f8b1196a3 100644
    --- a/src/main/java/carpet/script/utils/Colors.java
    +++ b/src/main/java/carpet/script/utils/Colors.java
    @@ -1,7 +1,6 @@
     package carpet.script.utils;
     
     import net.minecraft.world.level.block.SoundType;
    -import net.minecraft.world.level.material.Material;
     import net.minecraft.world.level.material.MaterialColor;
     
     import java.util.Map;
    @@ -154,13 +153,4 @@ public class Colors
                 entry(MaterialColor.RAW_IRON           , "raw_iron"           ),
                 entry(MaterialColor.GLOW_LICHEN           , "glow_lichen"           )
         );
    -
    -    public static final Map materialName = Map.ofEntries(
    -            entry(Material.PLANT          , "plant"        ),
    -            entry(Material.DEPRECATED_REPLACEABLE, "vegetation"       ),
    -            entry(Material.SAND      , "sand"         ),
    -            entry(Material.WOOD           , "wood"         ),
    -            entry(Material.GLASS          , "glass"        ),
    -            entry(Material.STONE          , "stone"        )
    -    );
     }
    diff --git a/src/main/java/carpet/script/utils/SnoopyCommandSource.java b/src/main/java/carpet/script/utils/SnoopyCommandSource.java
    index b656a9970f..a22121d7d6 100644
    --- a/src/main/java/carpet/script/utils/SnoopyCommandSource.java
    +++ b/src/main/java/carpet/script/utils/SnoopyCommandSource.java
    @@ -45,7 +45,7 @@ public SnoopyCommandSource(CommandSourceStack original, Component[] error, List<
             super(CommandSource.NULL, original.getPosition(), original.getRotation(), original.getLevel(), Vanilla.MinecraftServer_getRunPermissionLevel(original.getServer()),
                     original.getTextName(), original.getDisplayName(), original.getServer(), original.getEntity(), false,
                     (ctx, succ, res) -> {
    -                }, EntityAnchorArgument.Anchor.FEET, CommandSigningContext.ANONYMOUS, TaskChainer.immediate(original.getServer()));
    +                }, EntityAnchorArgument.Anchor.FEET, CommandSigningContext.ANONYMOUS, TaskChainer.immediate(original.getServer()), i -> {});
             this.output = CommandSource.NULL;
             this.position = original.getPosition();
             this.world = original.getLevel();
    @@ -92,7 +92,7 @@ private SnoopyCommandSource(CommandSource output, Vec3 pos, Vec2 rot, ServerLeve
         {
             super(output, pos, rot, world, level,
                     simpleName, name, server, entity, false,
    -                consumer, entityAnchor, context, TaskChainer.immediate(server));
    +                consumer, entityAnchor, context, TaskChainer.immediate(server), i -> {});
             this.output = output;
             this.position = pos;
             this.rotation = rot;
    diff --git a/src/main/java/carpet/utils/BlockInfo.java b/src/main/java/carpet/utils/BlockInfo.java
    index 70e417e911..1ca6d0c9f8 100644
    --- a/src/main/java/carpet/utils/BlockInfo.java
    +++ b/src/main/java/carpet/utils/BlockInfo.java
    @@ -19,7 +19,6 @@
     import net.minecraft.world.level.block.Block;
     import net.minecraft.world.level.block.Blocks;
     import net.minecraft.world.level.block.state.BlockState;
    -import net.minecraft.world.level.material.Material;
     import net.minecraft.world.level.pathfinder.PathComputationType;
     import net.minecraft.world.phys.Vec3;
     
    @@ -28,7 +27,6 @@ public class BlockInfo
         public static List blockInfo(BlockPos pos, ServerLevel world)
         {
             BlockState state = world.getBlockState(pos);
    -        Material material = state.getMaterial();
             Block block = state.getBlock();
             String metastring = "";
             final Registry blocks = world.registryAccess().registryOrThrow(Registries.BLOCK);
    @@ -51,9 +49,8 @@ public static List blockInfo(BlockPos pos, ServerLevel world)
                     Math.max(world.getBrightness(LightLayer.BLOCK, pos),world.getBrightness(LightLayer.SKY, pos)) ,
                     Math.max(world.getBrightness(LightLayer.BLOCK, pos.above()),world.getBrightness(LightLayer.SKY, pos.above())))));
             lst.add(Messenger.s(String.format(" - Brightness in: %.2f, above: %.2f", world.getLightLevelDependentMagicValue(pos), world.getLightLevelDependentMagicValue(pos.above()))));
    -        lst.add(Messenger.s(String.format(" - Is opaque: %s", material.isSolid() )));
    +        lst.add(Messenger.s(String.format(" - Is opaque: %s", state.isSolid() )));
             //lst.add(Messenger.s(String.format(" - Light opacity: %d", state.getOpacity(world,pos))));
    -        lst.add(Messenger.s(String.format(" - Blocks light: %s", state.getMaterial().isSolidBlocking())));
             //lst.add(Messenger.s(String.format(" - Emitted light: %d", state.getLightValue())));
             //lst.add(Messenger.s(String.format(" - Picks neighbour light value: %s", state.useNeighborBrightness(world, pos))));
             lst.add(Messenger.s(""));
    @@ -62,7 +59,6 @@ public static List blockInfo(BlockPos pos, ServerLevel world)
             lst.add(Messenger.s(String.format(" - Blocks movement in air: %s", !state.isPathfindable(world,pos, PathComputationType.AIR))));
             lst.add(Messenger.s(String.format(" - Blocks movement in liquids: %s", !state.isPathfindable(world,pos, PathComputationType.WATER))));
             lst.add(Messenger.s(String.format(" - Can burn: %s", state.ignitedByLava())));
    -        lst.add(Messenger.s(String.format(" - Requires a tool: %s", !material.isReplaceable()))); //?maybe
             lst.add(Messenger.s(String.format(" - Hardness: %.2f", state.getDestroySpeed(world, pos))));
             lst.add(Messenger.s(String.format(" - Blast resistance: %.2f", block.getExplosionResistance())));
             lst.add(Messenger.s(String.format(" - Ticks randomly: %s", block.isRandomlyTicking(state))));
    diff --git a/src/main/resources/carpet.accesswidener b/src/main/resources/carpet.accesswidener
    index e33690214a..6ab29864b2 100644
    --- a/src/main/resources/carpet.accesswidener
    +++ b/src/main/resources/carpet.accesswidener
    @@ -8,6 +8,7 @@ accessible class net/minecraft/world/level/border/WorldBorder$BorderExtent
     accessible class net/minecraft/world/level/border/WorldBorder$StaticBorderExtent
     accessible class net/minecraft/server/MinecraftServer$ReloadableResources
     accessible class net/minecraft/world/level/biome/Biome$ClimateSettings
    +accessible class net/minecraft/world/level/block/entity/SculkSensorBlockEntity$VibrationUser
     
     accessible method net/minecraft/world/level/border/WorldBorder getListeners ()Ljava/util/List;
     
    
    From ebd6db42c8ec464ff5189cdf6d84354c35950d20 Mon Sep 17 00:00:00 2001
    From: gnembon <41132274+gnembon@users.noreply.github.com>
    Date: Thu, 20 Apr 2023 22:14:17 +0200
    Subject: [PATCH 125/233] 1.4.105
    
    ---
     gradle.properties | 2 +-
     1 file changed, 1 insertion(+), 1 deletion(-)
    
    diff --git a/gradle.properties b/gradle.properties
    index 4873ce8c55..9bc38d1a20 100644
    --- a/gradle.properties
    +++ b/gradle.properties
    @@ -9,7 +9,7 @@ org.gradle.jvmargs=-Xmx1G
     	fabric_version=0.78.0+1.20
     
     # Mod Properties
    -	mod_version = 1.4.104
    +	mod_version = 1.4.105
     	maven_group = carpet
     	archives_base_name = fabric-carpet
     
    
    From 66d906b8aea2ec4bd3b9d5626ff6abdb8c2656eb Mon Sep 17 00:00:00 2001
    From: "github-actions[bot]" 
    Date: Thu, 20 Apr 2023 20:35:42 +0000
    Subject: [PATCH 126/233] Merge docs for 'Carpet Mod 1.4.105 for Minecraft
     23w16a'
    
    ---
     docs/scarpet/Full.md | 9 ++++++---
     1 file changed, 6 insertions(+), 3 deletions(-)
    
    diff --git a/docs/scarpet/Full.md b/docs/scarpet/Full.md
    index 8072b89e36..77dc35af73 100644
    --- a/docs/scarpet/Full.md
    +++ b/docs/scarpet/Full.md
    @@ -1253,13 +1253,14 @@ for(range(1000000,1100000),check_prime(_))  => 7216
     
     From which we can learn that there is 7216 primes between 1M and 1.1M
     
    -### `while(cond, limit, expr)`
    +### `while(cond, expr)`, `while(cond, limit, expr)`
     
    -Evaluates expression `expr` repeatedly until condition `cond` becomes false, but not more than `limit` times. 
    +Evaluates expression `expr` repeatedly until condition `cond` becomes false, but not more than `limit` times (if limit is specified). 
     Returns the result of the last `expr` evaluation, or `null` if nothing was successful. Both `expr` and `cond` will 
     received a bound variable `_` indicating current iteration, so its a number.
     
     
    +while(a<100,a=_*_) => 100 // loop stopped at condition
     while(a<100,10,a=_*_)  => 81 // loop exhausted via limit
     while(a<100,20,a=_*_)  => 100 // loop stopped at condition, but a has already been assigned
     while(_*_<100,20,a=_*_)  => 81 // loop stopped at condition, before a was assigned a value
    @@ -2816,7 +2817,8 @@ Returns the name of sound type made by the block at position. One of:
     
     ### `(Deprecated) material(pos)`
     
    -Returns the name of material of the block at position. Very limited as the use of material for blocks is removed.
    +Returns `'unknown'`. The concept of material for blocks is removed. On previous versions it returned the name of the material the block
    +was made of.
     
     ### `map_colour(pos)`
     
    @@ -5534,6 +5536,7 @@ produce an exception.
     ### `print(expr)`, `print(player/player_list, expr)`
     
     Displays the result of the expression to the chat. Overrides default `scarpet` behaviour of sending everything to stderr.
    +For player scoped apps it always by default targets the player for whom the app runs on behalf. 
     Can optionally define player or list of players to send the message to.
     
     ### `format(components, ...)`, `format([components, ...])`
    
    From f1205a4251c4779b96b569707988478f00094fef Mon Sep 17 00:00:00 2001
    From: altrisi 
    Date: Sat, 22 Apr 2023 20:41:12 +0200
    Subject: [PATCH 127/233] Make hoppers use the getter for `HopperCounter` in
     their mixin
    
    And very minor cleanup in it
    ---
     .../carpet/mixins/HopperBlockEntity_counterMixin.java     | 8 ++++----
     1 file changed, 4 insertions(+), 4 deletions(-)
    
    diff --git a/src/main/java/carpet/mixins/HopperBlockEntity_counterMixin.java b/src/main/java/carpet/mixins/HopperBlockEntity_counterMixin.java
    index 1c05b4634a..7f09d7de40 100644
    --- a/src/main/java/carpet/mixins/HopperBlockEntity_counterMixin.java
    +++ b/src/main/java/carpet/mixins/HopperBlockEntity_counterMixin.java
    @@ -40,17 +40,17 @@ protected HopperBlockEntity_counterMixin(BlockEntityType blockEntityType, Blo
         private static void onInsert(Level world, BlockPos blockPos, BlockState blockState, Container inventory, CallbackInfoReturnable cir)
         {
             if (CarpetSettings.hopperCounters) {
    -            DyeColor wool_color = WoolTool.getWoolColorAtPosition(
    +            DyeColor woolColor = WoolTool.getWoolColorAtPosition(
                         world,
    -                    blockPos.relative(blockState.getValue(HopperBlock.FACING))); // offset
    -            if (wool_color != null)
    +                    blockPos.relative(blockState.getValue(HopperBlock.FACING)));
    +            if (woolColor != null)
                 {
                     for (int i = 0; i < inventory.getContainerSize(); ++i)
                     {
                         if (!inventory.getItem(i).isEmpty())
                         {
                             ItemStack itemstack = inventory.getItem(i);//.copy();
    -                        HopperCounter.COUNTERS.get(wool_color).add(world.getServer(), itemstack);
    +                        HopperCounter.getCounter(woolColor).add(world.getServer(), itemstack);
                             inventory.setItem(i, ItemStack.EMPTY);
                         }
                     }
    
    From 15b120f729ad20cdb713005db7572d637866d606 Mon Sep 17 00:00:00 2001
    From: altrisi 
    Date: Sat, 22 Apr 2023 20:45:29 +0200
    Subject: [PATCH 128/233] Encapsulate `COUNTERS` field in `HopperCounter`
    
    ---
     src/main/java/carpet/helpers/HopperCounter.java | 2 +-
     1 file changed, 1 insertion(+), 1 deletion(-)
    
    diff --git a/src/main/java/carpet/helpers/HopperCounter.java b/src/main/java/carpet/helpers/HopperCounter.java
    index 94c19e539f..7fb99718a4 100644
    --- a/src/main/java/carpet/helpers/HopperCounter.java
    +++ b/src/main/java/carpet/helpers/HopperCounter.java
    @@ -52,7 +52,7 @@ public class HopperCounter
         /**
          * A map of all the {@link HopperCounter} counters.
          */
    -    public static final Map COUNTERS;
    +    private static final Map COUNTERS;
     
         /**
          * The default display colour of each item, which makes them look nicer when printing the counter contents to the chat
    
    From 07033af7dd95efffffbe3af53e0fe61561704fc9 Mon Sep 17 00:00:00 2001
    From: gnembon <41132274+gnembon@users.noreply.github.com>
    Date: Wed, 26 Apr 2023 22:58:59 +0200
    Subject: [PATCH 129/233] 23w17a
    
    ---
     gradle.properties                             |   4 +-
     src/main/java/carpet/CarpetSettings.java      |   2 +-
     .../carpet/fakes/LightStorageInterface.java   |   6 +-
     ...ighting_scarpetChunkCreationInterface.java |   2 +
     .../helpers/EntityPlayerActionPack.java       |  38 +++---
     .../carpet/helpers/FertilizableCoral.java     |   4 +-
     .../java/carpet/helpers/HopperCounter.java    |  19 +--
     .../java/carpet/helpers/ParticleDisplay.java  |   8 +-
     .../java/carpet/logging/HUDController.java    |   2 +-
     .../mixins/ArmorStand_scarpetMarkerMixin.java |   2 +-
     ...tionStorage_scarpetChunkCreationMixin.java |  10 +-
     .../ExperienceOrb_xpNoCooldownMixin.java      |   2 +-
     .../Guardian_renewableSpongesMixin.java       |   8 +-
     .../carpet/mixins/HugeFungusFeatureMixin.java |   2 +-
     ...LightEngine_scarpetChunkCreationMixin.java |  19 ++-
     ...tionStorage_scarpetChunkCreationMixin.java |  18 +--
     ...LightEngine_scarpetChunkCreationMixin.java |   6 +-
     .../mixins/LivingEntity_cleanLogsMixin.java   |   2 +-
     .../mixins/LivingEntity_creativeFlyMixin.java |   4 +-
     .../LivingEntity_maxCollisionsMixin.java      |   8 +-
     .../MerchantResultSlot_scarpetEventMixin.java |   2 +-
     .../carpet/mixins/Player_parrotMixin.java     |   2 +-
     .../mixins/Player_scarpetEventsMixin.java     |   6 +-
     .../java/carpet/mixins/PrimedTntMixin.java    |  10 +-
     .../ServerGamePacketListenerImplMixin.java    |   2 +-
     .../ServerPlayer_scarpetEventMixin.java       |   2 +-
     ...tionStorage_scarpetChunkCreationMixin.java |  19 ++-
     ...LightEngine_scarpetChunkCreationMixin.java |  16 ++-
     ...ThreadedLevelLightEngine_scarpetMixin.java |  19 ++-
     .../java/carpet/mixins/Villager_aiMixin.java  |   4 +-
     .../carpet/patches/EntityPlayerMPFake.java    |   6 +-
     .../java/carpet/script/CarpetEventServer.java |  36 ++---
     .../java/carpet/script/api/Inventories.java   |   2 +-
     src/main/java/carpet/script/utils/Colors.java | 128 +++++++++---------
     .../java/carpet/script/utils/EntityTools.java |   6 +-
     .../carpet/script/utils/ShapeDispatcher.java  |  66 ++++-----
     .../script/utils/SnoopyCommandSource.java     |   8 +-
     src/main/java/carpet/script/utils/Tracer.java |   4 +-
     .../java/carpet/script/utils/WorldTools.java  |   2 +-
     .../java/carpet/script/value/EntityValue.java |  18 +--
     .../java/carpet/script/value/ScreenValue.java |   2 +-
     .../carpet/script/value/ValueConversions.java |   4 +-
     src/main/java/carpet/utils/SpawnReporter.java |   2 +-
     src/main/java/carpet/utils/WoolTool.java      |  42 +++---
     44 files changed, 309 insertions(+), 265 deletions(-)
    
    diff --git a/gradle.properties b/gradle.properties
    index 9bc38d1a20..144aafbf3c 100644
    --- a/gradle.properties
    +++ b/gradle.properties
    @@ -3,10 +3,10 @@ org.gradle.jvmargs=-Xmx1G
     
     # Fabric Properties
     	# check https://fabricmc.net/develop/
    -	minecraft_version=23w16a
    +	minecraft_version=23w17a
     	loader_version=0.14.19
     	jsr305_version=3.0.2
    -	fabric_version=0.78.0+1.20
    +	fabric_version=0.79.1+1.20
     
     # Mod Properties
     	mod_version = 1.4.105
    diff --git a/src/main/java/carpet/CarpetSettings.java b/src/main/java/carpet/CarpetSettings.java
    index b837e1082a..481b3401bc 100644
    --- a/src/main/java/carpet/CarpetSettings.java
    +++ b/src/main/java/carpet/CarpetSettings.java
    @@ -842,7 +842,7 @@ public static void applyLightBatchSizes(MinecraftServer server, int maxBatchSize
             {
                 for (ServerLevel world : server.getAllLevels())
                 {
    -                world.getChunkSource().getLightEngine().setTaskPerBatch(maxBatchSize);
    +                //world.getChunkSource().getLightEngine().setTaskPerBatch(maxBatchSize);
                 }
             }
             @Override public Integer validate(CommandSourceStack source, CarpetRule currentRule, Integer newValue, String string) {
    diff --git a/src/main/java/carpet/fakes/LightStorageInterface.java b/src/main/java/carpet/fakes/LightStorageInterface.java
    index f233a2ac29..9c91f2afc8 100644
    --- a/src/main/java/carpet/fakes/LightStorageInterface.java
    +++ b/src/main/java/carpet/fakes/LightStorageInterface.java
    @@ -1,10 +1,12 @@
     package carpet.fakes;
     
    -import net.minecraft.world.level.lighting.LayerLightEngine;
    +import net.minecraft.world.level.lighting.LightEngine;
     
     public interface LightStorageInterface extends Lighting_scarpetChunkCreationInterface
     {
         void processRemoveLightData(long pos);
     
    -    void processRelight(LayerLightEngine lightProvider, long pos);
    +    void processRelight(LightEngine lightProvider, long pos);
    +
    +    int getLightLevelByLong(long blockPos);
     }
    diff --git a/src/main/java/carpet/fakes/Lighting_scarpetChunkCreationInterface.java b/src/main/java/carpet/fakes/Lighting_scarpetChunkCreationInterface.java
    index 5c72fc5987..8dc0ab68e9 100644
    --- a/src/main/java/carpet/fakes/Lighting_scarpetChunkCreationInterface.java
    +++ b/src/main/java/carpet/fakes/Lighting_scarpetChunkCreationInterface.java
    @@ -5,4 +5,6 @@ public interface Lighting_scarpetChunkCreationInterface
         void removeLightData(long pos);
     
         void relight(long pos);
    +
    +    default void clearQueuedSectionBlocksPublicAccess(long sectionPos) {};
     }
    diff --git a/src/main/java/carpet/helpers/EntityPlayerActionPack.java b/src/main/java/carpet/helpers/EntityPlayerActionPack.java
    index 151094e7d8..e0601ea28c 100644
    --- a/src/main/java/carpet/helpers/EntityPlayerActionPack.java
    +++ b/src/main/java/carpet/helpers/EntityPlayerActionPack.java
    @@ -174,12 +174,12 @@ public EntityPlayerActionPack mount(boolean onlyRideables)
             List entities;
             if (onlyRideables)
             {
    -            entities = player.level.getEntities(player, player.getBoundingBox().inflate(3.0D, 1.0D, 3.0D),
    +            entities = player.level().getEntities(player, player.getBoundingBox().inflate(3.0D, 1.0D, 3.0D),
                         e -> e instanceof Minecart || e instanceof Boat || e instanceof AbstractHorse);
             }
                 else
             {
    -            entities = player.level.getEntities(player, player.getBoundingBox().inflate(3.0D, 1.0D, 3.0D));
    +            entities = player.level().getEntities(player, player.getBoundingBox().inflate(3.0D, 1.0D, 3.0D));
             }
             if (entities.size()==0)
                 return this;
    @@ -310,11 +310,11 @@ boolean execute(ServerPlayer player, Action action)
                             case BLOCK:
                             {
                                 player.resetLastActionTime();
    -                            ServerLevel world = player.getLevel();
    +                            ServerLevel world = player.serverLevel();
                                 BlockHitResult blockHit = (BlockHitResult) hit;
                                 BlockPos pos = blockHit.getBlockPos();
                                 Direction side = blockHit.getDirection();
    -                            if (pos.getY() < player.getLevel().getMaxBuildHeight() - (side == Direction.UP ? 1 : 0) && world.mayInteract(player, pos))
    +                            if (pos.getY() < player.level().getMaxBuildHeight() - (side == Direction.UP ? 1 : 0) && world.mayInteract(player, pos))
                                 {
                                     InteractionResult result = player.gameMode.useItemOn(player, world, player.getItemInHand(hand), hand, blockHit);
                                     if (result.consumesAction())
    @@ -349,7 +349,7 @@ boolean execute(ServerPlayer player, Action action)
                             }
                         }
                         ItemStack handItem = player.getItemInHand(hand);
    -                    if (player.gameMode.useItem(player, player.getLevel(), handItem, hand).consumesAction())
    +                    if (player.gameMode.useItem(player, player.level(), handItem, hand).consumesAction())
                         {
                             ap.itemUseCooldown = 3;
                             return true;
    @@ -392,17 +392,17 @@ boolean execute(ServerPlayer player, Action action) {
                             BlockHitResult blockHit = (BlockHitResult) hit;
                             BlockPos pos = blockHit.getBlockPos();
                             Direction side = blockHit.getDirection();
    -                        if (player.blockActionRestricted(player.level, pos, player.gameMode.getGameModeForPlayer())) return false;
    -                        if (ap.currentBlock != null && player.level.getBlockState(ap.currentBlock).isAir())
    +                        if (player.blockActionRestricted(player.level(), pos, player.gameMode.getGameModeForPlayer())) return false;
    +                        if (ap.currentBlock != null && player.level().getBlockState(ap.currentBlock).isAir())
                             {
                                 ap.currentBlock = null;
                                 return false;
                             }
    -                        BlockState state = player.level.getBlockState(pos);
    +                        BlockState state = player.level().getBlockState(pos);
                             boolean blockBroken = false;
                             if (player.gameMode.getGameModeForPlayer().isCreative())
                             {
    -                            player.gameMode.handleBlockBreakAction(pos, ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK, side, player.getLevel().getMaxBuildHeight(), -1);
    +                            player.gameMode.handleBlockBreakAction(pos, ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK, side, player.level().getMaxBuildHeight(), -1);
                                 ap.blockHitDelay = 5;
                                 blockBroken = true;
                             }
    @@ -410,15 +410,15 @@ else  if (ap.currentBlock == null || !ap.currentBlock.equals(pos))
                             {
                                 if (ap.currentBlock != null)
                                 {
    -                                player.gameMode.handleBlockBreakAction(ap.currentBlock, ServerboundPlayerActionPacket.Action.ABORT_DESTROY_BLOCK, side, player.getLevel().getMaxBuildHeight(), -1);
    +                                player.gameMode.handleBlockBreakAction(ap.currentBlock, ServerboundPlayerActionPacket.Action.ABORT_DESTROY_BLOCK, side, player.level().getMaxBuildHeight(), -1);
                                 }
    -                            player.gameMode.handleBlockBreakAction(pos, ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK, side, player.getLevel().getMaxBuildHeight(), -1);
    +                            player.gameMode.handleBlockBreakAction(pos, ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK, side, player.level().getMaxBuildHeight(), -1);
                                 boolean notAir = !state.isAir();
                                 if (notAir && ap.curBlockDamageMP == 0)
                                 {
    -                                state.attack(player.level, pos, player);
    +                                state.attack(player.level(), pos, player);
                                 }
    -                            if (notAir && state.getDestroyProgress(player, player.level, pos) >= 1)
    +                            if (notAir && state.getDestroyProgress(player, player.level(), pos) >= 1)
                                 {
                                     ap.currentBlock = null;
                                     //instamine??
    @@ -432,15 +432,15 @@ else  if (ap.currentBlock == null || !ap.currentBlock.equals(pos))
                             }
                             else
                             {
    -                            ap.curBlockDamageMP += state.getDestroyProgress(player, player.level, pos);
    +                            ap.curBlockDamageMP += state.getDestroyProgress(player, player.level(), pos);
                                 if (ap.curBlockDamageMP >= 1)
                                 {
    -                                player.gameMode.handleBlockBreakAction(pos, ServerboundPlayerActionPacket.Action.STOP_DESTROY_BLOCK, side, player.getLevel().getMaxBuildHeight(), -1);
    +                                player.gameMode.handleBlockBreakAction(pos, ServerboundPlayerActionPacket.Action.STOP_DESTROY_BLOCK, side, player.level().getMaxBuildHeight(), -1);
                                     ap.currentBlock = null;
                                     ap.blockHitDelay = 5;
                                     blockBroken = true;
                                 }
    -                            player.level.destroyBlockProgress(-1, pos, (int) (ap.curBlockDamageMP * 10));
    +                            player.level().destroyBlockProgress(-1, pos, (int) (ap.curBlockDamageMP * 10));
     
                             }
                             player.resetLastActionTime();
    @@ -456,8 +456,8 @@ void inactiveTick(ServerPlayer player, Action action)
                 {
                     EntityPlayerActionPack ap = ((ServerPlayerInterface) player).getActionPack();
                     if (ap.currentBlock == null) return;
    -                player.level.destroyBlockProgress(-1, ap.currentBlock, -1);
    -                player.gameMode.handleBlockBreakAction(ap.currentBlock, ServerboundPlayerActionPacket.Action.ABORT_DESTROY_BLOCK, Direction.DOWN, player.getLevel().getMaxBuildHeight(), -1);
    +                player.level().destroyBlockProgress(-1, ap.currentBlock, -1);
    +                player.gameMode.handleBlockBreakAction(ap.currentBlock, ServerboundPlayerActionPacket.Action.ABORT_DESTROY_BLOCK, Direction.DOWN, player.level().getMaxBuildHeight(), -1);
                     ap.currentBlock = null;
                 }
             },
    @@ -468,7 +468,7 @@ boolean execute(ServerPlayer player, Action action)
                 {
                     if (action.limit == 1)
                     {
    -                    if (player.isOnGround()) player.jumpFromGround(); // onGround
    +                    if (player.onGround()) player.jumpFromGround(); // onGround
                     }
                     else
                     {
    diff --git a/src/main/java/carpet/helpers/FertilizableCoral.java b/src/main/java/carpet/helpers/FertilizableCoral.java
    index 567818d922..c1116af662 100644
    --- a/src/main/java/carpet/helpers/FertilizableCoral.java
    +++ b/src/main/java/carpet/helpers/FertilizableCoral.java
    @@ -21,7 +21,7 @@
     import net.minecraft.world.level.levelgen.feature.CoralMushroomFeature;
     import net.minecraft.world.level.levelgen.feature.CoralTreeFeature;
     import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration;
    -import net.minecraft.world.level.material.MaterialColor;
    +import net.minecraft.world.level.material.MapColor;
     
     /**
      * Deduplicates logic for the different behaviors of the {@code renewableCoral} rule
    @@ -56,7 +56,7 @@ public default void performBonemeal(ServerLevel worldIn, RandomSource random, Bl
                 default -> new CoralMushroomFeature(NoneFeatureConfiguration.CODEC);
             };
     
    -        MaterialColor color = blockUnder.getMapColor(worldIn, pos);
    +        MapColor color = blockUnder.getMapColor(worldIn, pos);
             BlockState properBlock = blockUnder;
             HolderSet.Named coralBlocks = worldIn.registryAccess().registryOrThrow(Registries.BLOCK).getTag(BlockTags.CORAL_BLOCKS).orElseThrow();
             for (Holder block: coralBlocks)
    diff --git a/src/main/java/carpet/helpers/HopperCounter.java b/src/main/java/carpet/helpers/HopperCounter.java
    index 7fb99718a4..fb5dd3b03b 100644
    --- a/src/main/java/carpet/helpers/HopperCounter.java
    +++ b/src/main/java/carpet/helpers/HopperCounter.java
    @@ -30,7 +30,8 @@
     import net.minecraft.world.level.block.BeaconBeamBlock;
     import net.minecraft.world.level.block.Block;
     import net.minecraft.world.level.block.Blocks;
    -import net.minecraft.world.level.material.MaterialColor;
    +import net.minecraft.world.level.material.MapColor;
    +
     import java.util.ArrayList;
     import java.util.Collection;
     import java.util.Collections;
    @@ -100,7 +101,7 @@ private HopperCounter(DyeColor color)
         {
             startTick = -1;
             this.color = color;
    -        this.prettyColour = WoolTool.Material2DyeName.getOrDefault(color.getMaterialColor(),"w ") + color.getName();
    +        this.prettyColour = WoolTool.Material2DyeName.getOrDefault(color.getMapColor(),"w ") + color.getName();
         }
     
         /**
    @@ -229,7 +230,7 @@ public List format(MinecraftServer server, boolean realTime, boolean
          */
         public static int appropriateColor(int color)
         {
    -        if (color == 0) return MaterialColor.SNOW.col;
    +        if (color == 0) return MapColor.SNOW.col;
             int r = (color >> 16 & 255);
             int g = (color >> 8 & 255);
             int b = (color & 255);
    @@ -241,7 +242,7 @@ public static int appropriateColor(int color)
     
         /**
          * Maps items that don't get a good block to reference for colour, or those that colour is wrong to a number of blocks, so we can get their colours easily with the
    -     * {@link Block#defaultMaterialColor()} method as these items have those same colours.
    +     * {@link Block#defaultMapColor()} method as these items have those same colours.
          */
         private static final Map DEFAULTS = Map.ofEntries(
                 entry(Items.DANDELION, Blocks.YELLOW_WOOL),
    @@ -334,8 +335,8 @@ public static int appropriateColor(int color)
          */
         public static TextColor fromItem(Item item, RegistryAccess registryAccess)
         {
    -        if (DEFAULTS.containsKey(item)) return TextColor.fromRgb(appropriateColor(DEFAULTS.get(item).defaultMaterialColor().col));
    -        if (item instanceof DyeItem dye) return TextColor.fromRgb(appropriateColor(dye.getDyeColor().getMaterialColor().col));
    +        if (DEFAULTS.containsKey(item)) return TextColor.fromRgb(appropriateColor(DEFAULTS.get(item).defaultMapColor().col));
    +        if (item instanceof DyeItem dye) return TextColor.fromRgb(appropriateColor(dye.getDyeColor().getMapColor().col));
             Block block = null;
             final Registry itemRegistry = registryAccess.registryOrThrow(Registries.ITEM);
             final Registry blockRegistry = registryAccess.registryOrThrow(Registries.BLOCK);
    @@ -350,9 +351,9 @@ else if (blockRegistry.getOptional(id).isPresent())
             }
             if (block != null)
             {
    -            if (block instanceof AbstractBannerBlock) return TextColor.fromRgb(appropriateColor(((AbstractBannerBlock) block).getColor().getMaterialColor().col));
    -            if (block instanceof BeaconBeamBlock) return TextColor.fromRgb(appropriateColor( ((BeaconBeamBlock) block).getColor().getMaterialColor().col));
    -            return TextColor.fromRgb(appropriateColor( block.defaultMaterialColor().col));
    +            if (block instanceof AbstractBannerBlock) return TextColor.fromRgb(appropriateColor(((AbstractBannerBlock) block).getColor().getMapColor().col));
    +            if (block instanceof BeaconBeamBlock) return TextColor.fromRgb(appropriateColor( ((BeaconBeamBlock) block).getColor().getMapColor().col));
    +            return TextColor.fromRgb(appropriateColor( block.defaultMapColor().col));
             }
             return null;
         }
    diff --git a/src/main/java/carpet/helpers/ParticleDisplay.java b/src/main/java/carpet/helpers/ParticleDisplay.java
    index 5335f0b240..35b693a8f5 100644
    --- a/src/main/java/carpet/helpers/ParticleDisplay.java
    +++ b/src/main/java/carpet/helpers/ParticleDisplay.java
    @@ -12,11 +12,11 @@ public class ParticleDisplay
     {
         public static void drawParticleLine(ServerPlayer player, Vec3 from, Vec3 to, String main, String accent, int count, double spread)
         {
    -        HolderLookup> lookup = player.getLevel().holderLookup(Registries.PARTICLE_TYPE);
    +        HolderLookup> lookup = player.level().holderLookup(Registries.PARTICLE_TYPE);
             ParticleOptions accentParticle = ParticleParser.getEffect(accent, lookup);
             ParticleOptions mainParticle = ParticleParser.getEffect(main, lookup);
     
    -        if (accentParticle != null) player.getLevel().sendParticles(
    +        if (accentParticle != null) player.serverLevel().sendParticles(
                     player,
                     accentParticle,
                     true,
    @@ -29,9 +29,9 @@ public static void drawParticleLine(ServerPlayer player, Vec3 from, Vec3 to, Str
             Vec3 incvec = to.subtract(from).normalize();//    multiply(50/sqrt(lineLengthSq));
             for (Vec3 delta = new Vec3(0.0,0.0,0.0);
                  delta.lengthSqr() < lineLengthSq;
    -             delta = delta.add(incvec.scale(player.level.random.nextFloat())))
    +             delta = delta.add(incvec.scale(player.level().random.nextFloat())))
             {
    -            player.getLevel().sendParticles(
    +            player.serverLevel().sendParticles(
                         player,
                         mainParticle,
                         true,
    diff --git a/src/main/java/carpet/logging/HUDController.java b/src/main/java/carpet/logging/HUDController.java
    index 9ac95b7b35..31e3735d42 100644
    --- a/src/main/java/carpet/logging/HUDController.java
    +++ b/src/main/java/carpet/logging/HUDController.java
    @@ -89,7 +89,7 @@ public static void update_hud(MinecraftServer server, List force)
                         case "overworld" -> Level.OVERWORLD;
                         case "nether" -> Level.NETHER;
                         case "end" -> Level.END;
    -                    default -> player.level.dimension();
    +                    default -> player.level().dimension();
                     };
                     return new Component[]{SpawnReporter.printMobcapsForDimension(server.getLevel(dim), false).get(0)};
                 });
    diff --git a/src/main/java/carpet/mixins/ArmorStand_scarpetMarkerMixin.java b/src/main/java/carpet/mixins/ArmorStand_scarpetMarkerMixin.java
    index 79359b9b95..1a944301d5 100644
    --- a/src/main/java/carpet/mixins/ArmorStand_scarpetMarkerMixin.java
    +++ b/src/main/java/carpet/mixins/ArmorStand_scarpetMarkerMixin.java
    @@ -29,7 +29,7 @@ protected ArmorStand_scarpetMarkerMixin(EntityType entit
         @Inject(method = "readAdditionalSaveData", at = @At("HEAD"))
         private void checkScarpetMarkerUnloaded(CallbackInfo ci)
         {
    -        if (!level.isClientSide)
    +        if (!level().isClientSide)
             {
                 if (getTags().contains(Auxiliary.MARKER_STRING))
                 {
    diff --git a/src/main/java/carpet/mixins/BlockLightSectionStorage_scarpetChunkCreationMixin.java b/src/main/java/carpet/mixins/BlockLightSectionStorage_scarpetChunkCreationMixin.java
    index 63d868ce7b..238f5fde13 100644
    --- a/src/main/java/carpet/mixins/BlockLightSectionStorage_scarpetChunkCreationMixin.java
    +++ b/src/main/java/carpet/mixins/BlockLightSectionStorage_scarpetChunkCreationMixin.java
    @@ -12,7 +12,7 @@
     import net.minecraft.world.level.chunk.LightChunkGetter;
     import net.minecraft.world.level.lighting.BlockLightSectionStorage;
     import net.minecraft.world.level.lighting.BlockLightSectionStorage.BlockDataLayerStorageMap;
    -import net.minecraft.world.level.lighting.LayerLightEngine;
    +import net.minecraft.world.level.lighting.LightEngine;
     import net.minecraft.world.level.lighting.LayerLightSectionStorage;
     
     @Mixin(BlockLightSectionStorage.class)
    @@ -24,7 +24,7 @@ private BlockLightSectionStorage_scarpetChunkCreationMixin(final LightLayer ligh
         }
     
         @Override
    -    public void processRelight(final LayerLightEngine lightProvider, final long cPos)
    +    public void processRelight(final LightEngine lightProvider, final long cPos)
         {
             final DynamicGraphMinFixedPoint_resetChunkInterface levelPropagator = (DynamicGraphMinFixedPoint_resetChunkInterface) lightProvider;
     
    @@ -62,4 +62,10 @@ public void processRelight(final LayerLightEngine lightProvider, final lon
                 }
             }
         }
    +
    +    @Override
    +    public int getLightLevelByLong(long blockPos)
    +    {
    +        return getLightValue(blockPos);
    +    }
     }
    diff --git a/src/main/java/carpet/mixins/ExperienceOrb_xpNoCooldownMixin.java b/src/main/java/carpet/mixins/ExperienceOrb_xpNoCooldownMixin.java
    index e11c8f3ba9..3c90497ae1 100644
    --- a/src/main/java/carpet/mixins/ExperienceOrb_xpNoCooldownMixin.java
    +++ b/src/main/java/carpet/mixins/ExperienceOrb_xpNoCooldownMixin.java
    @@ -31,7 +31,7 @@ public ExperienceOrb_xpNoCooldownMixin(EntityType type, Level world)
     
         @Inject(method = "playerTouch", at = @At("HEAD"))
         private void addXP(Player player, CallbackInfo ci) {
    -        if (CarpetSettings.xpNoCooldown && !level.isClientSide) {
    +        if (CarpetSettings.xpNoCooldown && !level().isClientSide) {
                 player.takeXpDelay = 0;
                 // reducing the count to 1 and leaving vanilla to deal with it
                 while (this.count > 1) {
    diff --git a/src/main/java/carpet/mixins/Guardian_renewableSpongesMixin.java b/src/main/java/carpet/mixins/Guardian_renewableSpongesMixin.java
    index 4675f6f83b..69f9a9c007 100644
    --- a/src/main/java/carpet/mixins/Guardian_renewableSpongesMixin.java
    +++ b/src/main/java/carpet/mixins/Guardian_renewableSpongesMixin.java
    @@ -24,11 +24,11 @@ protected Guardian_renewableSpongesMixin(EntityType entityTyp
         @Override
         public void thunderHit(ServerLevel serverWorld, LightningBolt lightningEntity)
         {                                // isRemoved()
    -        if (!this.level.isClientSide && !this.isRemoved() && CarpetSettings.renewableSponges && !((Object)this instanceof ElderGuardian))
    +        if (!this.level().isClientSide && !this.isRemoved() && CarpetSettings.renewableSponges && !((Object)this instanceof ElderGuardian))
             {
    -            ElderGuardian elderGuardian = new ElderGuardian(EntityType.ELDER_GUARDIAN ,this.level);
    +            ElderGuardian elderGuardian = new ElderGuardian(EntityType.ELDER_GUARDIAN ,this.level());
                 elderGuardian.moveTo(this.getX(), this.getY(), this.getZ(), this.getYRot(), this.getXRot());
    -            elderGuardian.finalizeSpawn(serverWorld ,this.level.getCurrentDifficultyAt(elderGuardian.blockPosition()), MobSpawnType.CONVERSION, (SpawnGroupData)null, (CompoundTag)null);
    +            elderGuardian.finalizeSpawn(serverWorld ,this.level().getCurrentDifficultyAt(elderGuardian.blockPosition()), MobSpawnType.CONVERSION, (SpawnGroupData)null, (CompoundTag)null);
                 elderGuardian.setNoAi(this.isNoAi());
                 
                 if (this.hasCustomName())
    @@ -37,7 +37,7 @@ public void thunderHit(ServerLevel serverWorld, LightningBolt lightningEntity)
                     elderGuardian.setCustomNameVisible(this.isCustomNameVisible());
                 }
                 
    -            this.level.addFreshEntity(elderGuardian);
    +            this.level().addFreshEntity(elderGuardian);
                 this.discard(); // discard remove();
             }
             else
    diff --git a/src/main/java/carpet/mixins/HugeFungusFeatureMixin.java b/src/main/java/carpet/mixins/HugeFungusFeatureMixin.java
    index 8084c184c0..e07921bf1c 100644
    --- a/src/main/java/carpet/mixins/HugeFungusFeatureMixin.java
    +++ b/src/main/java/carpet/mixins/HugeFungusFeatureMixin.java
    @@ -13,7 +13,7 @@
     
     @Mixin(HugeFungusFeature.class)
     public class HugeFungusFeatureMixin {
    -    @ModifyArgs(method = "place", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/levelgen/feature/HugeFungusFeature;placeStem(Lnet/minecraft/world/level/LevelAccessor;Lnet/minecraft/util/RandomSource;Lnet/minecraft/world/level/levelgen/feature/HugeFungusConfiguration;Lnet/minecraft/core/BlockPos;IZ)V"))
    +    @ModifyArgs(method = "place", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/levelgen/feature/HugeFungusFeature;placeStem(Lnet/minecraft/world/level/WorldGenLevel;Lnet/minecraft/util/RandomSource;Lnet/minecraft/world/level/levelgen/feature/HugeFungusConfiguration;Lnet/minecraft/core/BlockPos;IZ)V"))
         private void mixin(Args args) {
             boolean natural = !((HugeFungusConfiguration) args.get(2)).planted;
             args.set(5, natural && ((boolean) args.get(5)) ||
    diff --git a/src/main/java/carpet/mixins/LayerLightEngine_scarpetChunkCreationMixin.java b/src/main/java/carpet/mixins/LayerLightEngine_scarpetChunkCreationMixin.java
    index d2f826476a..9093cc3f66 100644
    --- a/src/main/java/carpet/mixins/LayerLightEngine_scarpetChunkCreationMixin.java
    +++ b/src/main/java/carpet/mixins/LayerLightEngine_scarpetChunkCreationMixin.java
    @@ -1,23 +1,25 @@
     package carpet.mixins;
     
    +import carpet.fakes.LightStorageInterface;
     import org.spongepowered.asm.mixin.Final;
     import org.spongepowered.asm.mixin.Mixin;
     import org.spongepowered.asm.mixin.Shadow;
    -import org.spongepowered.asm.mixin.gen.Invoker;
     
     import carpet.fakes.ChunkLightProviderInterface;
     import carpet.fakes.Lighting_scarpetChunkCreationInterface;
     import net.minecraft.world.level.chunk.DataLayer;
    -import net.minecraft.world.level.lighting.LayerLightEngine;
    +import net.minecraft.world.level.lighting.LightEngine;
     import net.minecraft.world.level.lighting.LayerLightSectionStorage;
     
    -@Mixin(LayerLightEngine.class)
    +@Mixin(LightEngine.class)
     public abstract class LayerLightEngine_scarpetChunkCreationMixin implements Lighting_scarpetChunkCreationInterface, ChunkLightProviderInterface
     {
         @Shadow
         @Final
         protected LayerLightSectionStorage storage;
     
    +    @Shadow protected abstract void clearQueuedSectionBlocks(final long l);
    +
         @Override
         public void removeLightData(final long pos)
         {
    @@ -31,6 +33,13 @@ public void relight(final long pos)
         }
     
         @Override
    -    @Invoker("getLevel")
    -    public abstract int callGetCurrentLevelFromSection(DataLayer array, long blockPos);
    +    public int callGetCurrentLevelFromSection(DataLayer array, long blockPos) {
    +        return ((LightStorageInterface)storage).getLightLevelByLong(blockPos);
    +    };
    +
    +    @Override
    +    public void clearQueuedSectionBlocksPublicAccess(long sectionPos)
    +    {
    +        clearQueuedSectionBlocks(sectionPos);
    +    }
     }
    diff --git a/src/main/java/carpet/mixins/LayerLightSectionStorage_scarpetChunkCreationMixin.java b/src/main/java/carpet/mixins/LayerLightSectionStorage_scarpetChunkCreationMixin.java
    index 5dea17c045..cc65e2bb3f 100644
    --- a/src/main/java/carpet/mixins/LayerLightSectionStorage_scarpetChunkCreationMixin.java
    +++ b/src/main/java/carpet/mixins/LayerLightSectionStorage_scarpetChunkCreationMixin.java
    @@ -1,10 +1,12 @@
     package carpet.mixins;
     
     import java.util.Arrays;
    +
    +import carpet.fakes.Lighting_scarpetChunkCreationInterface;
     import net.minecraft.core.SectionPos;
     import net.minecraft.world.level.chunk.DataLayer;
     import net.minecraft.world.level.lighting.DataLayerStorageMap;
    -import net.minecraft.world.level.lighting.LayerLightEngine;
    +import net.minecraft.world.level.lighting.LightEngine;
     import net.minecraft.world.level.lighting.LayerLightSectionStorage;
     import org.spongepowered.asm.mixin.Final;
     import org.spongepowered.asm.mixin.Mixin;
    @@ -25,8 +27,8 @@ public abstract class LayerLightSectionStorage_scarpetChunkCreationMixin impleme
         @Shadow
         protected abstract DataLayer getDataLayer(final long sectionPos, final boolean cached);
     
    -    @Shadow
    -    protected abstract void clearQueuedSectionBlocks(final LayerLightEngine storage, final long blockChunkPos);
    +    //@Shadow
    +    //protected abstract void clearQueuedSectionBlocks(final LightEngine storage, final long blockChunkPos);
     
         @Shadow
         @Final
    @@ -42,7 +44,7 @@ public abstract class LayerLightSectionStorage_scarpetChunkCreationMixin impleme
         @Final
         protected Long2ObjectMap queuedSections;
     
    -    @Shadow protected abstract void enableLightSources(final long l, final boolean bl);
    +    //@Shadow protected abstract void enableLightSources(final long l, final boolean bl);
     
         @Unique
         private final LongSet removedChunks = new LongOpenHashSet();
    @@ -63,10 +65,10 @@ public void relight(final long pos)
         }
     
         @Inject(
    -        method = "markNewInconsistencies(Lnet/minecraft/world/level/lighting/LayerLightEngine;ZZ)V",
    +        method = "markNewInconsistencies",
             at = @At("HEAD")
         )
    -    private void processData(final LayerLightEngine lightProvider, final boolean doSkylight, final boolean skipEdgeLightPropagation, final CallbackInfo ci)
    +    private void processData(final LightEngine lightProvider, final CallbackInfo ci)
         {
             // Process light removal
     
    @@ -80,7 +82,7 @@ private void processData(final LayerLightEngine lightProvider, final boole
     
                     if (this.storingLightForSection(sectionPos))
                     {
    -                    this.clearQueuedSectionBlocks(lightProvider, sectionPos);
    +                    ((Lighting_scarpetChunkCreationInterface)lightProvider).clearQueuedSectionBlocksPublicAccess(sectionPos);
     
                         if (this.changedSections.add(sectionPos))
                             this.updatingSectionData.copyDataLayer(sectionPos);
    @@ -108,7 +110,7 @@ public void processRemoveLightData(final long pos)
         }
     
         @Override
    -    public void processRelight(final LayerLightEngine lightProvider, final long pos)
    +    public void processRelight(final LightEngine lightProvider, final long pos)
         {
         }
     }
    diff --git a/src/main/java/carpet/mixins/LevelLightEngine_scarpetChunkCreationMixin.java b/src/main/java/carpet/mixins/LevelLightEngine_scarpetChunkCreationMixin.java
    index f61c23a97c..cfcbd2bad7 100644
    --- a/src/main/java/carpet/mixins/LevelLightEngine_scarpetChunkCreationMixin.java
    +++ b/src/main/java/carpet/mixins/LevelLightEngine_scarpetChunkCreationMixin.java
    @@ -5,7 +5,7 @@
     import org.spongepowered.asm.mixin.Shadow;
     
     import carpet.fakes.Lighting_scarpetChunkCreationInterface;
    -import net.minecraft.world.level.lighting.LayerLightEngine;
    +import net.minecraft.world.level.lighting.LightEngine;
     import net.minecraft.world.level.lighting.LevelLightEngine;
     
     @Mixin(LevelLightEngine.class)
    @@ -13,11 +13,11 @@ public abstract class LevelLightEngine_scarpetChunkCreationMixin implements Ligh
     {
         @Shadow
         @Final
    -    private LayerLightEngine blockEngine;
    +    private LightEngine blockEngine;
     
         @Shadow
         @Final
    -    private LayerLightEngine skyEngine;
    +    private LightEngine skyEngine;
     
         @Override
         public void removeLightData(final long pos)
    diff --git a/src/main/java/carpet/mixins/LivingEntity_cleanLogsMixin.java b/src/main/java/carpet/mixins/LivingEntity_cleanLogsMixin.java
    index 16cf02dd29..525d918f25 100644
    --- a/src/main/java/carpet/mixins/LivingEntity_cleanLogsMixin.java
    +++ b/src/main/java/carpet/mixins/LivingEntity_cleanLogsMixin.java
    @@ -22,6 +22,6 @@ public LivingEntity_cleanLogsMixin(EntityType type, Level world)
         @Redirect(method = "die", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/LivingEntity;hasCustomName()Z"))
         private boolean shouldLogDeaths(LivingEntity livingEntity)
         {
    -        return livingEntity.hasCustomName() && CarpetSettings.cleanLogs && level.getGameRules().getBoolean(GameRules.RULE_SHOWDEATHMESSAGES);
    +        return livingEntity.hasCustomName() && CarpetSettings.cleanLogs && level().getGameRules().getBoolean(GameRules.RULE_SHOWDEATHMESSAGES);
         }
     }
    diff --git a/src/main/java/carpet/mixins/LivingEntity_creativeFlyMixin.java b/src/main/java/carpet/mixins/LivingEntity_creativeFlyMixin.java
    index fea73417da..e34908382c 100644
    --- a/src/main/java/carpet/mixins/LivingEntity_creativeFlyMixin.java
    +++ b/src/main/java/carpet/mixins/LivingEntity_creativeFlyMixin.java
    @@ -30,7 +30,7 @@ private float drag(float original)
             if (CarpetSettings.creativeFlyDrag != 0.09 && (Object)this instanceof Player)
             {
                 Player self = (Player)(Object)(this);
    -            if (self.getAbilities().flying && ! onGround )
    +            if (self.getAbilities().flying && ! onGround() )
                     return (float)(1.0-CarpetSettings.creativeFlyDrag);
             }
             return original;
    @@ -43,7 +43,7 @@ private void flyingAltSpeed(float slipperiness, CallbackInfoReturnable ci
             if (CarpetSettings.creativeFlySpeed != 1.0D && (Object)this instanceof Player)
             {
                 Player self = (Player)(Object)(this);
    -            if (self.getAbilities().flying && !onGround)
    +            if (self.getAbilities().flying && !onGround())
                     cir.setReturnValue( getFlyingSpeed() * (float)CarpetSettings.creativeFlySpeed);
             }
         }
    diff --git a/src/main/java/carpet/mixins/LivingEntity_maxCollisionsMixin.java b/src/main/java/carpet/mixins/LivingEntity_maxCollisionsMixin.java
    index e237b3aa5c..f7168f9a93 100644
    --- a/src/main/java/carpet/mixins/LivingEntity_maxCollisionsMixin.java
    +++ b/src/main/java/carpet/mixins/LivingEntity_maxCollisionsMixin.java
    @@ -37,8 +37,8 @@ private void tickPushingReplacement(CallbackInfo ci) {
             int maxEntityCramming =-1;
             if (CarpetSettings.maxEntityCollisions > 0)
             {
    -            maxEntityCramming = this.level.getGameRules().getInt(GameRules.RULE_MAX_ENTITY_CRAMMING);
    -            entities = ((LevelInterface) this.level).getOtherEntitiesLimited(
    +            maxEntityCramming = this.level().getGameRules().getInt(GameRules.RULE_MAX_ENTITY_CRAMMING);
    +            entities = ((LevelInterface) this.level()).getOtherEntitiesLimited(
                         this,
                         this.getBoundingBox(),
                         EntitySelector.pushableBy(this),
    @@ -46,11 +46,11 @@ private void tickPushingReplacement(CallbackInfo ci) {
             }
             else
             {
    -            entities = this.level.getEntities(this, this.getBoundingBox(), EntitySelector.pushableBy(this));
    +            entities = this.level().getEntities(this, this.getBoundingBox(), EntitySelector.pushableBy(this));
             }
     
             if (!entities.isEmpty()) {
    -            if (maxEntityCramming < 0) maxEntityCramming = this.level.getGameRules().getInt(GameRules.RULE_MAX_ENTITY_CRAMMING);
    +            if (maxEntityCramming < 0) maxEntityCramming = this.level().getGameRules().getInt(GameRules.RULE_MAX_ENTITY_CRAMMING);
                 if (maxEntityCramming > 0 && entities.size() > maxEntityCramming - 1 && this.random.nextInt(4) == 0) {
                     int candidates = 0;
     
    diff --git a/src/main/java/carpet/mixins/MerchantResultSlot_scarpetEventMixin.java b/src/main/java/carpet/mixins/MerchantResultSlot_scarpetEventMixin.java
    index bd7d73891e..0ebb016888 100644
    --- a/src/main/java/carpet/mixins/MerchantResultSlot_scarpetEventMixin.java
    +++ b/src/main/java/carpet/mixins/MerchantResultSlot_scarpetEventMixin.java
    @@ -26,7 +26,7 @@ public abstract class MerchantResultSlot_scarpetEventMixin {
                 target = "Lnet/minecraft/world/item/trading/Merchant;notifyTrade(Lnet/minecraft/world/item/trading/MerchantOffer;)V")
         )
         private void onTrade(Player player, ItemStack stack, CallbackInfo ci) {
    -        if(PLAYER_TRADES.isNeeded() && !player.level.isClientSide())
    +        if(PLAYER_TRADES.isNeeded() && !player.level().isClientSide())
             {
                 PLAYER_TRADES.onTrade((ServerPlayer) player, merchant, slots.getActiveOffer());
             }
    diff --git a/src/main/java/carpet/mixins/Player_parrotMixin.java b/src/main/java/carpet/mixins/Player_parrotMixin.java
    index 691230ef16..bc29fc66cd 100644
    --- a/src/main/java/carpet/mixins/Player_parrotMixin.java
    +++ b/src/main/java/carpet/mixins/Player_parrotMixin.java
    @@ -51,7 +51,7 @@ private void cancelDropShoulderEntities1(Player playerEntity)
         private void onTickMovement(CallbackInfo ci)
         {
             boolean parrots_will_drop = !CarpetSettings.persistentParrots || this.abilities.invulnerable;
    -        if (!this.level.isClientSide && ((parrots_will_drop && this.fallDistance > 0.5F) || this.isInWater() || this.abilities.flying || isSleeping()))
    +        if (!this.level().isClientSide && ((parrots_will_drop && this.fallDistance > 0.5F) || this.isInWater() || this.abilities.flying || isSleeping()))
             {
                 this.removeEntitiesOnShoulder();
             }
    diff --git a/src/main/java/carpet/mixins/Player_scarpetEventsMixin.java b/src/main/java/carpet/mixins/Player_scarpetEventsMixin.java
    index 6f41f62086..31720265f6 100644
    --- a/src/main/java/carpet/mixins/Player_scarpetEventsMixin.java
    +++ b/src/main/java/carpet/mixins/Player_scarpetEventsMixin.java
    @@ -57,7 +57,7 @@ private void playerTakingDamage(DamageSource source, float amount, CallbackInfo
         @Inject(method = "touch", at = @At("HEAD"))
         private void onEntityCollision(Entity entity, CallbackInfo ci)
         {
    -        if (PLAYER_COLLIDES_WITH_ENTITY.isNeeded() && !level.isClientSide)
    +        if (PLAYER_COLLIDES_WITH_ENTITY.isNeeded() && !level().isClientSide)
             {
                 PLAYER_COLLIDES_WITH_ENTITY.onEntityHandAction((ServerPlayer)(Object)this, entity, null);
             }
    @@ -66,7 +66,7 @@ private void onEntityCollision(Entity entity, CallbackInfo ci)
         @Inject(method = "interactOn", cancellable = true, at = @At("HEAD"))
         private void doInteract(Entity entity, InteractionHand hand, CallbackInfoReturnable cir)
         {
    -        if (!level.isClientSide && PLAYER_INTERACTS_WITH_ENTITY.isNeeded())
    +        if (!level().isClientSide && PLAYER_INTERACTS_WITH_ENTITY.isNeeded())
             {
                 if(PLAYER_INTERACTS_WITH_ENTITY.onEntityHandAction((ServerPlayer) (Object)this, entity, hand)) {
                     cir.setReturnValue(InteractionResult.PASS);
    @@ -78,7 +78,7 @@ private void doInteract(Entity entity, InteractionHand hand, CallbackInfoReturna
         @Inject(method = "attack", at = @At("HEAD"), cancellable = true)
         private void onAttack(Entity target, CallbackInfo ci)
         {
    -        if (!level.isClientSide && PLAYER_ATTACKS_ENTITY.isNeeded() && target.isAttackable())
    +        if (!level().isClientSide && PLAYER_ATTACKS_ENTITY.isNeeded() && target.isAttackable())
             {
                 if(PLAYER_ATTACKS_ENTITY.onEntityHandAction((ServerPlayer) (Object)this, target, null)) {
                     ci.cancel();
    diff --git a/src/main/java/carpet/mixins/PrimedTntMixin.java b/src/main/java/carpet/mixins/PrimedTntMixin.java
    index b3c29a5f21..82c085745c 100644
    --- a/src/main/java/carpet/mixins/PrimedTntMixin.java
    +++ b/src/main/java/carpet/mixins/PrimedTntMixin.java
    @@ -72,11 +72,11 @@ private void initTNTLogger(Level world_1, double double_1, double double_2, doub
         private void onExplode(CallbackInfo ci)
         {
             if (LoggerRegistry.__tnt && logHelper != null)
    -            logHelper.onExploded(getX(), getY(), getZ(), this.level.getGameTime());
    +            logHelper.onExploded(getX(), getY(), getZ(), this.level().getGameTime());
     
             if (mergedTNT > 1)
                 for (int i = 0; i < mergedTNT - 1; i++)
    -                this.level.explode(this, this.getX(), this.getY() + (double)(this.getBbHeight() / 16.0F),
    +                this.level().explode(this, this.getX(), this.getY() + (double)(this.getBbHeight() / 16.0F),
                             this.getZ(),
                             4.0F,
                             Level.ExplosionInteraction.TNT);
    @@ -90,9 +90,9 @@ private void tryMergeTnt(CallbackInfo ci)
             // Merge code for combining tnt into a single entity if they happen to exist in the same spot, same fuse, no motion CARPET-XCOM
             if(CarpetSettings.mergeTNT){
                 Vec3 velocity = getDeltaMovement();
    -            if(!level.isClientSide && mergeBool && velocity.x == 0 && velocity.y == 0 && velocity.z == 0){
    +            if(!level().isClientSide && mergeBool && velocity.x == 0 && velocity.y == 0 && velocity.z == 0){
                     mergeBool = false;
    -                for(Entity entity : level.getEntities(this, this.getBoundingBox())){
    +                for(Entity entity : level().getEntities(this, this.getBoundingBox())){
                         if(entity instanceof PrimedTnt && !entity.isRemoved()){
                             PrimedTnt entityTNTPrimed = (PrimedTnt)entity;
                             Vec3 tntVelocity = entityTNTPrimed.getDeltaMovement();
    @@ -113,7 +113,7 @@ private void setMergeable(CallbackInfo ci)
         {
             // Merge code, merge only tnt that have had a chance to move CARPET-XCOM
             Vec3 velocity = getDeltaMovement();
    -        if(!level.isClientSide && (velocity.y != 0 || velocity.x != 0 || velocity.z != 0)){
    +        if(!level().isClientSide && (velocity.y != 0 || velocity.x != 0 || velocity.z != 0)){
                 mergeBool = true;
             }
         }
    diff --git a/src/main/java/carpet/mixins/ServerGamePacketListenerImplMixin.java b/src/main/java/carpet/mixins/ServerGamePacketListenerImplMixin.java
    index 714d8a75d2..53788619b0 100644
    --- a/src/main/java/carpet/mixins/ServerGamePacketListenerImplMixin.java
    +++ b/src/main/java/carpet/mixins/ServerGamePacketListenerImplMixin.java
    @@ -28,7 +28,7 @@ private void onCustomCarpetPayload(ServerboundCustomPayloadPacket packet, Callba
                 // We should force onto the main thread here
                 // ServerNetworkHandler.handleData can possibly mutate data that isn't
                 // thread safe, and also allows for client commands to be executed
    -            PacketUtils.ensureRunningOnSameThread(packet, (ServerGamePacketListener) this, player.getLevel());
    +            PacketUtils.ensureRunningOnSameThread(packet, (ServerGamePacketListener) this, player.serverLevel());
                 ServerNetworkHandler.handleData(packet.getData(), player);
                 ci.cancel();
             }
    diff --git a/src/main/java/carpet/mixins/ServerPlayer_scarpetEventMixin.java b/src/main/java/carpet/mixins/ServerPlayer_scarpetEventMixin.java
    index 506690539d..4f41fc067f 100644
    --- a/src/main/java/carpet/mixins/ServerPlayer_scarpetEventMixin.java
    +++ b/src/main/java/carpet/mixins/ServerPlayer_scarpetEventMixin.java
    @@ -100,7 +100,7 @@ private void setSneakingConditionally(ServerPlayer serverPlayerEntity, boolean s
         private void logPreviousCoordinates(ServerLevel serverWorld, CallbackInfoReturnable cir)
         {
             previousLocation = position();
    -        previousDimension = level.dimension();  //dimension type
    +        previousDimension = level().dimension();  //dimension type
         }
     
         @Inject(method = "changeDimension", at = @At("RETURN"))
    diff --git a/src/main/java/carpet/mixins/SkyLightSectionStorage_scarpetChunkCreationMixin.java b/src/main/java/carpet/mixins/SkyLightSectionStorage_scarpetChunkCreationMixin.java
    index 35d9ba7f7d..83daf4150c 100644
    --- a/src/main/java/carpet/mixins/SkyLightSectionStorage_scarpetChunkCreationMixin.java
    +++ b/src/main/java/carpet/mixins/SkyLightSectionStorage_scarpetChunkCreationMixin.java
    @@ -14,7 +14,7 @@
     import net.minecraft.world.level.chunk.DataLayer;
     import net.minecraft.world.level.chunk.LightChunkGetter;
     import net.minecraft.world.level.lighting.BlockLightSectionStorage.BlockDataLayerStorageMap;
    -import net.minecraft.world.level.lighting.LayerLightEngine;
    +import net.minecraft.world.level.lighting.LightEngine;
     import net.minecraft.world.level.lighting.LayerLightSectionStorage;
     import net.minecraft.world.level.lighting.SkyLightSectionStorage;
     
    @@ -26,7 +26,7 @@ protected SkyLightSectionStorage_scarpetChunkCreationMixin(final LightLayer ligh
             super(lightType, chunkProvider, lightData);
         }
     
    -    @Shadow
    +    /*@Shadow
         @Final
         private LongSet sectionsToAddSourcesTo;
     
    @@ -37,10 +37,11 @@ protected SkyLightSectionStorage_scarpetChunkCreationMixin(final LightLayer ligh
         @Shadow
         @Final
         private LongSet sectionsWithSources;
    +     */
     
         @Shadow protected abstract boolean isAboveData(final long pos);
     
    -    @Shadow protected abstract boolean lightOnInSection(final long sectionPos);
    +    //@Shadow protected abstract boolean lightOnInSection(final long sectionPos);
     
         @Override
         public void processRemoveLightData(final long cPos)
    @@ -48,16 +49,18 @@ public void processRemoveLightData(final long cPos)
             for (int y = -1; y < 17; ++y)
             {
                 final long sectionPos = SectionPos.asLong(SectionPos.x(cPos), y, SectionPos.z(cPos));
    -
    +/* do something with this later
                 this.sectionsToAddSourcesTo.remove(sectionPos);
                 this.sectionsToRemoveSourcesFrom.remove(sectionPos);
     
                 this.sectionsWithSources.remove(sectionPos);
    +
    + */
             }
         }
     
         @Override
    -    public void processRelight(final LayerLightEngine lightProvider, final long cPos)
    +    public void processRelight(final LightEngine lightProvider, final long cPos)
         {
             final DynamicGraphMinFixedPoint_resetChunkInterface levelPropagator = (DynamicGraphMinFixedPoint_resetChunkInterface) lightProvider;
     
    @@ -114,4 +117,10 @@ public void processRelight(final LayerLightEngine lightProvider, final lon
                 }
             }
         }
    +
    +    @Override
    +    public int getLightLevelByLong(long blockPos)
    +    {
    +        return getLightValue(blockPos);
    +    }
     }
    diff --git a/src/main/java/carpet/mixins/ThreadedLevelLightEngine_scarpetChunkCreationMixin.java b/src/main/java/carpet/mixins/ThreadedLevelLightEngine_scarpetChunkCreationMixin.java
    index 5f67c20bd9..16fd2da860 100644
    --- a/src/main/java/carpet/mixins/ThreadedLevelLightEngine_scarpetChunkCreationMixin.java
    +++ b/src/main/java/carpet/mixins/ThreadedLevelLightEngine_scarpetChunkCreationMixin.java
    @@ -35,6 +35,8 @@ private ThreadedLevelLightEngine_scarpetChunkCreationMixin(final LightChunkGette
         @Final
         private ChunkMap chunkMap;
     
    +    //@Shadow public abstract void propagateLightSources(final ChunkPos chunkPos);
    +
         @Override
         @Invoker("updateChunkStatus")
         public abstract void invokeUpdateChunkStatus(ChunkPos pos);
    @@ -46,7 +48,7 @@ public void removeLightData(final ChunkAccess chunk)
             chunk.setLightCorrect(false);
     
             this.addTask(pos.x, pos.z, () -> 0, ThreadedLevelLightEngine.TaskType.PRE_UPDATE, Util.name(() -> {
    -                super.enableLightSources(pos, false);
    +                super.setLightEnabled(pos, false);
                     ((Lighting_scarpetChunkCreationInterface) this).removeLightData(SectionPos.getZeroNode(SectionPos.asLong(pos.x, 0, pos.z)));
                 },
                 () -> "Remove light data " + pos
    @@ -58,8 +60,14 @@ public CompletableFuture relight(final ChunkAccess chunk)
         {
             final ChunkPos pos = chunk.getPos();
     
    -        this.addTask(pos.x, pos.z, () -> 0, ThreadedLevelLightEngine.TaskType.PRE_UPDATE, Util.name(() -> {
    -                super.enableLightSources(pos, true);
    +        propagateLightSources(pos);
    +        /*this.addTask(pos.x, pos.z, () -> 0, ThreadedLevelLightEngine.TaskType.PRE_UPDATE, Util.name(() -> {
    +                super.setLightEnabled(pos, true);
    +
    +                chunk.findBlockLightSources((lightPos, state) -> {
    +                        final int lightEmission = state.getLightEmission();
    +                        enqueueIncrease(lightPos.asLong(), LightEngine.QueueEntry.increaseLightFromEmission(lightEmission, isEmptyShape(state)));
    +                    });
     
                     chunk.getLights().forEach(
                         blockPos -> super.onBlockEmissionIncrease(blockPos, chunk.getLightEmission(blockPos))
    @@ -68,7 +76,7 @@ public CompletableFuture relight(final ChunkAccess chunk)
                     ((Lighting_scarpetChunkCreationInterface) this).relight(SectionPos.getZeroNode(SectionPos.asLong(pos.x, 0, pos.z)));
                 },
                 () -> "Relight chunk " + pos
    -        ));
    +        ));*/
     
             return CompletableFuture.runAsync(
                 Util.name(() -> {
    diff --git a/src/main/java/carpet/mixins/ThreadedLevelLightEngine_scarpetMixin.java b/src/main/java/carpet/mixins/ThreadedLevelLightEngine_scarpetMixin.java
    index bc87dd5179..901654e2eb 100644
    --- a/src/main/java/carpet/mixins/ThreadedLevelLightEngine_scarpetMixin.java
    +++ b/src/main/java/carpet/mixins/ThreadedLevelLightEngine_scarpetMixin.java
    @@ -16,7 +16,11 @@
     @Mixin(ThreadedLevelLightEngine.class)
     public abstract class ThreadedLevelLightEngine_scarpetMixin extends LevelLightEngine implements ServerLightingProviderInterface
     {
    -    @Shadow public abstract void checkBlock(BlockPos pos);
    +    //@Shadow public abstract void checkBlock(BlockPos pos);
    +
    +    //@Shadow public abstract void setLightEnabled(final ChunkPos chunkPos, final boolean bl);
    +
    +    //@Shadow public abstract void propagateLightSources(final ChunkPos chunkPos);
     
         public ThreadedLevelLightEngine_scarpetMixin(LightChunkGetter chunkProvider, boolean hasBlockLight, boolean hasSkyLight)
         {
    @@ -34,18 +38,19 @@ public void resetLight(ChunkAccess chunk, ChunkPos pos)
                     //ChunkPos pos = new ChunkPos(x, z);
                     int j;
                     for(j = -1; j < 17; ++j) {                                                                 // skip some recomp
    -                    super.queueSectionData(LightLayer.BLOCK, SectionPos.of(pos, j), new DataLayer(), false);
    -                    super.queueSectionData(LightLayer.SKY, SectionPos.of(pos, j), new DataLayer(), false);
    +                    super.queueSectionData(LightLayer.BLOCK, SectionPos.of(pos, j), new DataLayer());
    +                    super.queueSectionData(LightLayer.SKY, SectionPos.of(pos, j), new DataLayer());
                     }
                     for(j = 0; j < 16; ++j) {
                         super.updateSectionStatus(SectionPos.of(pos, j), true);
                     }
     
    -                super.enableLightSources(pos, true);
    +                setLightEnabled(pos, true);
     
    -                    chunk.getLights().forEach((blockPos) -> {
    -                        super.onBlockEmissionIncrease(blockPos, chunk.getLightEmission(blockPos));
    -                    });
    +                propagateLightSources(pos);
    +                //    chunk.getLights().forEach((blockPos) -> {
    +                //        super.onBlockEmissionIncrease(blockPos, chunk.getLightEmission(blockPos));
    +                //    });
     
                 }
     
    diff --git a/src/main/java/carpet/mixins/Villager_aiMixin.java b/src/main/java/carpet/mixins/Villager_aiMixin.java
    index ce82c03470..359fbcf6f0 100644
    --- a/src/main/java/carpet/mixins/Villager_aiMixin.java
    +++ b/src/main/java/carpet/mixins/Villager_aiMixin.java
    @@ -79,7 +79,7 @@ private void ontick(CallbackInfo ci)
                 //boolean work = false;
                 boolean sleep = false;
                 boolean panic = this.brain.isActive(Activity.PANIC);
    -            long currentTime = this.level.getGameTime();
    +            long currentTime = this.level().getGameTime();
                 if (optional_11.isPresent()) {
                     sleep = (currentTime - optional_11.get()) < 24000L;
                 }
    @@ -123,7 +123,7 @@ private void onInteract(Player playerEntity_1, InteractionHand hand_1, CallbackI
                 if (itemStack_1.getItem() == Items.EMERALD)
                 {
                     GlobalPos bedPos = this.brain.getMemory(MemoryModuleType.HOME).orElse(null);
    -                if (bedPos == null || bedPos.dimension() != level.dimension()) // get Dimension
    +                if (bedPos == null || bedPos.dimension() != level().dimension()) // get Dimension
                     {
                         setUnhappy();
                         ((ServerLevel) getCommandSenderWorld()).sendParticles(new BlockParticleOption(ParticleTypes.BLOCK_MARKER, Blocks.BARRIER.defaultBlockState()), getX(), getY() + getEyeHeight() + 1, getZ(), 1, 0.1, 0.1, 0.1, 0.0);
    diff --git a/src/main/java/carpet/patches/EntityPlayerMPFake.java b/src/main/java/carpet/patches/EntityPlayerMPFake.java
    index 7c3293d1ce..2c4b8fc023 100644
    --- a/src/main/java/carpet/patches/EntityPlayerMPFake.java
    +++ b/src/main/java/carpet/patches/EntityPlayerMPFake.java
    @@ -85,7 +85,7 @@ public static EntityPlayerMPFake createShadow(MinecraftServer server, ServerPlay
         {
             player.getServer().getPlayerList().remove(player);
             player.connection.disconnect(Component.translatable("multiplayer.disconnect.duplicate_login"));
    -        ServerLevel worldIn = player.getLevel();//.getWorld(player.dimension);
    +        ServerLevel worldIn = player.serverLevel();//.getWorld(player.dimension);
             GameProfile gameprofile = player.getGameProfile();
             EntityPlayerMPFake playerShadow = new EntityPlayerMPFake(server, worldIn, gameprofile, true);
             playerShadow.setChatSession(player.getChatSession());
    @@ -99,7 +99,7 @@ public static EntityPlayerMPFake createShadow(MinecraftServer server, ServerPlay
             playerShadow.entityData.set(DATA_PLAYER_MODE_CUSTOMISATION, player.getEntityData().get(DATA_PLAYER_MODE_CUSTOMISATION));
     
     
    -        server.getPlayerList().broadcastAll(new ClientboundRotateHeadPacket(playerShadow, (byte) (player.yHeadRot * 256 / 360)), playerShadow.level.dimension());
    +        server.getPlayerList().broadcastAll(new ClientboundRotateHeadPacket(playerShadow, (byte) (player.yHeadRot * 256 / 360)), playerShadow.level().dimension());
             server.getPlayerList().broadcastAll(new ClientboundPlayerInfoUpdatePacket(ClientboundPlayerInfoUpdatePacket.Action.ADD_PLAYER, playerShadow));
             //player.world.getChunkManager().updatePosition(playerShadow);
             playerShadow.getAbilities().flying = player.getAbilities().flying;
    @@ -143,7 +143,7 @@ public void tick()
             if (this.getServer().getTickCount() % 10 == 0)
             {
                 this.connection.resetPosition();
    -            this.getLevel().getChunkSource().move(this);
    +            this.serverLevel().getChunkSource().move(this);
             }
             try
             {
    diff --git a/src/main/java/carpet/script/CarpetEventServer.java b/src/main/java/carpet/script/CarpetEventServer.java
    index af9bc5c9b6..b03e9217c6 100644
    --- a/src/main/java/carpet/script/CarpetEventServer.java
    +++ b/src/main/java/carpet/script/CarpetEventServer.java
    @@ -591,7 +591,7 @@ public boolean onItemAction(ServerPlayer player, InteractionHand enumhand, ItemS
                     return handler.call(() ->
                             Arrays.asList(
                                     new EntityValue(player),
    -                                ValueConversions.of(itemstack, player.getLevel().registryAccess()),
    +                                ValueConversions.of(itemstack, player.level().registryAccess()),
                                     StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand")
                             ), player::createCommandSourceStack);
                 }
    @@ -604,7 +604,7 @@ public boolean onBlockAction(ServerPlayer player, BlockPos blockpos, Direction f
                     return handler.call(() ->
                             Arrays.asList(
                                     new EntityValue(player),
    -                                new BlockValue(null, player.getLevel(), blockpos),
    +                                new BlockValue(null, player.serverLevel(), blockpos),
                                     StringValue.of(facing.getName())
                             ), player::createCommandSourceStack);
                 }
    @@ -622,9 +622,9 @@ public boolean onBlockHit(ServerPlayer player, InteractionHand enumhand, BlockHi
                         Vec3 vec3d = hitRes.getLocation().subtract(blockpos.getX(), blockpos.getY(), blockpos.getZ());
                         return Arrays.asList(
                                 new EntityValue(player),
    -                            ValueConversions.of(itemstack, player.getLevel().registryAccess()),
    +                            ValueConversions.of(itemstack, player.level().registryAccess()),
                                 StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand"),
    -                            new BlockValue(null, player.getLevel(), blockpos),
    +                            new BlockValue(null, player.serverLevel(), blockpos),
                                 StringValue.of(enumfacing.getName()),
                                 ListValue.of(
                                         new NumericValue(vec3d.x),
    @@ -648,7 +648,7 @@ public boolean onBlockHit(ServerPlayer player, InteractionHand enumhand, BlockHi
                         return Arrays.asList(
                                 new EntityValue(player),
                                 StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand"),
    -                            new BlockValue(null, player.getLevel(), blockpos),
    +                            new BlockValue(null, player.serverLevel(), blockpos),
                                 StringValue.of(enumfacing.getName()),
                                 ListValue.of(
                                         new NumericValue(vec3d.x),
    @@ -667,9 +667,9 @@ public boolean onBlockPlaced(ServerPlayer player, BlockPos pos, InteractionHand
                 {
                     return handler.call(() -> Arrays.asList(
                             new EntityValue(player),
    -                        ValueConversions.of(itemstack, player.getLevel().registryAccess()),
    +                        ValueConversions.of(itemstack, player.level().registryAccess()),
                             StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand"),
    -                        new BlockValue(null, player.getLevel(), pos)
    +                        new BlockValue(null, player.serverLevel(), pos)
                     ), player::createCommandSourceStack);
                 }
             };
    @@ -680,9 +680,9 @@ public boolean onBlockPlaced(ServerPlayer player, BlockPos pos, InteractionHand
                 {
                     handler.call(() -> Arrays.asList(
                             new EntityValue(player),
    -                        ValueConversions.of(itemstack, player.getLevel().registryAccess()),
    +                        ValueConversions.of(itemstack, player.level().registryAccess()),
                             StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand"),
    -                        new BlockValue(null, player.getLevel(), pos)
    +                        new BlockValue(null, player.serverLevel(), pos)
                     ), player::createCommandSourceStack);
                     return false;
                 }
    @@ -693,7 +693,7 @@ public boolean onBlockPlaced(ServerPlayer player, BlockPos pos, InteractionHand
                 public boolean onBlockBroken(ServerPlayer player, BlockPos pos, BlockState previousBS)
                 {
                     return handler.call(
    -                        () -> Arrays.asList(new EntityValue(player), new BlockValue(previousBS, player.getLevel(), pos)),
    +                        () -> Arrays.asList(new EntityValue(player), new BlockValue(previousBS, player.serverLevel(), pos)),
                             player::createCommandSourceStack
                     );
                 }
    @@ -713,7 +713,7 @@ public boolean onEntityHandAction(ServerPlayer player, Entity entity, Interactio
                 @Override
                 public void onTrade(ServerPlayer player, Merchant merchant, MerchantOffer tradeOffer)
                 {
    -                RegistryAccess regs = player.getLevel().registryAccess();
    +                RegistryAccess regs = player.level().registryAccess();
                     handler.call(() -> Arrays.asList(
                             new EntityValue(player),
                             merchant instanceof final AbstractVillager villager ? new EntityValue(villager) : Value.NULL,
    @@ -728,7 +728,7 @@ public void onTrade(ServerPlayer player, Merchant merchant, MerchantOffer tradeO
                 @Override
                 public boolean onItemAction(ServerPlayer player, InteractionHand enumhand, ItemStack itemstack)
                 {
    -                handler.call(() -> Arrays.asList(new EntityValue(player), ValueConversions.of(itemstack, player.getLevel().registryAccess())), player::createCommandSourceStack);
    +                handler.call(() -> Arrays.asList(new EntityValue(player), ValueConversions.of(itemstack, player.level().registryAccess())), player::createCommandSourceStack);
                     return false;
                 }
             };
    @@ -787,7 +787,7 @@ public boolean onItemAction(ServerPlayer player, InteractionHand enumhand, ItemS
                     handler.call(() ->
                             Arrays.asList(
                                     new EntityValue(player),
    -                                ValueConversions.of(itemstack, player.getLevel().registryAccess()),
    +                                ValueConversions.of(itemstack, player.level().registryAccess()),
                                     StringValue.of(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand")
                             ), player::createCommandSourceStack);
                     return false;
    @@ -802,7 +802,7 @@ public boolean onItemAction(ServerPlayer player, InteractionHand enumhand, ItemS
                     return handler.call(() ->
                             Arrays.asList(
                                     new EntityValue(player),
    -                                ValueConversions.of(itemstack, player.getLevel().registryAccess()),
    +                                ValueConversions.of(itemstack, player.level().registryAccess()),
                                     new StringValue(enumhand == InteractionHand.MAIN_HAND ? "mainhand" : "offhand")
                             ), player::createCommandSourceStack);
                 }
    @@ -999,7 +999,7 @@ public void onPlayerStatistic(ServerPlayer player, Stat stat, int amount)
                     {
                         return;
                     }
    -                Registry> registry = player.getLevel().registryAccess().registryOrThrow(Registries.STAT_TYPE);
    +                Registry> registry = player.level().registryAccess().registryOrThrow(Registries.STAT_TYPE);
                     handler.call(() -> Arrays.asList(
                             new EntityValue(player),
                             NBTSerializableValue.nameFromRegistryId(registry.getKey(stat.getType())),
    @@ -1105,7 +1105,7 @@ public void onEntityAction(Entity entity, boolean created)
                         {
                             handler.call(
                                     () -> Collections.singletonList(new EntityValue(entity)),
    -                                () -> entity.getServer().createCommandSourceStack().withLevel((ServerLevel) entity.level).withPermission(Vanilla.MinecraftServer_getRunPermissionLevel(entity.getServer()))
    +                                () -> entity.getServer().createCommandSourceStack().withLevel((ServerLevel) entity.level()).withPermission(Vanilla.MinecraftServer_getRunPermissionLevel(entity.getServer()))
                             );
                         }
                     })).collect(Collectors.toUnmodifiableMap(Map.Entry::getKey, Map.Entry::getValue));
    @@ -1124,7 +1124,7 @@ public void onEntityAction(Entity entity, boolean created)
                         {
                             handler.call(
                                     () -> Arrays.asList(new EntityValue(entity), BooleanValue.of(created)),
    -                                () -> entity.getServer().createCommandSourceStack().withLevel((ServerLevel) entity.level).withPermission(Vanilla.MinecraftServer_getRunPermissionLevel(entity.getServer()))
    +                                () -> entity.getServer().createCommandSourceStack().withLevel((ServerLevel) entity.level()).withPermission(Vanilla.MinecraftServer_getRunPermissionLevel(entity.getServer()))
                             );
                         }
                     }))
    @@ -1334,7 +1334,7 @@ public void onCustomPlayerEvent(ServerPlayer player, Object... args)
                             valArgs.add(EntityValue.of(player));
                             for (Object o : args)
                             {
    -                            valArgs.add(ValueConversions.guess(player.getLevel(), o));
    +                            valArgs.add(ValueConversions.guess(player.serverLevel(), o));
                             }
                             return valArgs;
                         }, player::createCommandSourceStack
    diff --git a/src/main/java/carpet/script/api/Inventories.java b/src/main/java/carpet/script/api/Inventories.java
    index 2347f7ca8e..327ea5fcf0 100644
    --- a/src/main/java/carpet/script/api/Inventories.java
    +++ b/src/main/java/carpet/script/api/Inventories.java
    @@ -437,7 +437,7 @@ else if (owner instanceof LivingEntity livingEntity)
                 {
                     // stolen from LookTargetUtil.give((VillagerEntity)owner, droppedStack, (LivingEntity) owner);
                     double dropY = livingEntity.getY() - 0.30000001192092896D + livingEntity.getEyeHeight();
    -                item = new ItemEntity(livingEntity.level, livingEntity.getX(), dropY, livingEntity.getZ(), droppedStack);
    +                item = new ItemEntity(livingEntity.level(), livingEntity.getX(), dropY, livingEntity.getZ(), droppedStack);
                     Vec3 vec3d = livingEntity.getViewVector(1.0F).normalize().scale(0.3);//  new Vec3d(0, 0.3, 0);
                     item.setDeltaMovement(vec3d);
                     item.setDefaultPickUpDelay();
    diff --git a/src/main/java/carpet/script/utils/Colors.java b/src/main/java/carpet/script/utils/Colors.java
    index 5f8b1196a3..8b5a10cdbb 100644
    --- a/src/main/java/carpet/script/utils/Colors.java
    +++ b/src/main/java/carpet/script/utils/Colors.java
    @@ -1,7 +1,7 @@
     package carpet.script.utils;
     
     import net.minecraft.world.level.block.SoundType;
    -import net.minecraft.world.level.material.MaterialColor;
    +import net.minecraft.world.level.material.MapColor;
     
     import java.util.Map;
     
    @@ -89,68 +89,68 @@ public class Colors
                 entry(SoundType.POLISHED_DEEPSLATE, "polished_deepslate")
         );
     
    -    public static final Map mapColourName = Map.ofEntries(
    -            entry(MaterialColor.NONE     , "air"       ),
    -            entry(MaterialColor.GRASS     , "grass"     ),
    -            entry(MaterialColor.SAND       , "sand"      ),
    -            entry(MaterialColor.WOOL        , "wool"      ),
    -            entry(MaterialColor.FIRE       , "tnt"       ),
    -            entry(MaterialColor.ICE        , "ice"       ),
    -            entry(MaterialColor.METAL      , "iron"      ),
    -            entry(MaterialColor.PLANT    , "foliage"   ),
    -            entry(MaterialColor.SNOW     , "snow"      ),
    -            entry(MaterialColor.CLAY       , "clay"      ),
    -            entry(MaterialColor.DIRT       , "dirt"      ),
    -            entry(MaterialColor.STONE      , "stone"     ),
    -            entry(MaterialColor.WATER      , "water"     ),
    -            entry(MaterialColor.WOOD       , "wood"      ),
    -            entry(MaterialColor.QUARTZ     , "quartz"    ),
    -            entry(MaterialColor.COLOR_ORANGE    , "adobe"     ),
    -            entry(MaterialColor.COLOR_MAGENTA   , "magenta"   ),
    -            entry(MaterialColor.COLOR_LIGHT_BLUE, "light_blue"),
    -            entry(MaterialColor.COLOR_YELLOW    , "yellow"    ),
    -            entry(MaterialColor.COLOR_LIGHT_GREEN      , "lime"      ),
    -            entry(MaterialColor.COLOR_PINK      , "pink"      ),
    -            entry(MaterialColor.COLOR_GRAY      , "gray"      ),
    -            entry(MaterialColor.COLOR_LIGHT_GRAY, "light_gray"),
    -            entry(MaterialColor.COLOR_CYAN      , "cyan"      ),
    -            entry(MaterialColor.COLOR_PURPLE    , "purple"    ),
    -            entry(MaterialColor.COLOR_BLUE      , "blue"      ),
    -            entry(MaterialColor.COLOR_BROWN     , "brown"     ),
    -            entry(MaterialColor.COLOR_GREEN     , "green"     ),
    -            entry(MaterialColor.COLOR_RED       , "red"       ),
    -            entry(MaterialColor.COLOR_BLACK     , "black"     ),
    -            entry(MaterialColor.GOLD      , "gold"      ),
    -            entry(MaterialColor.DIAMOND    , "diamond"   ),
    -            entry(MaterialColor.LAPIS      , "lapis"     ),
    -            entry(MaterialColor.EMERALD    , "emerald"   ),
    -            entry(MaterialColor.PODZOL     , "obsidian"  ),
    -            entry(MaterialColor.NETHER     , "netherrack"), //TODO fix these
    -            entry(MaterialColor.TERRACOTTA_WHITE      , "white_terracotta"      ),
    -            entry(MaterialColor.TERRACOTTA_ORANGE    , "orange_terracotta"     ),
    -            entry(MaterialColor.TERRACOTTA_MAGENTA   , "magenta_terracotta"    ),
    -            entry(MaterialColor.TERRACOTTA_LIGHT_BLUE, "light_blue_terracotta" ),
    -            entry(MaterialColor.TERRACOTTA_YELLOW    , "yellow_terracotta"     ),
    -            entry(MaterialColor.TERRACOTTA_LIGHT_GREEN      , "lime_terracotta"       ),
    -            entry(MaterialColor.TERRACOTTA_PINK      , "pink_terracotta"       ),
    -            entry(MaterialColor.TERRACOTTA_GRAY      , "gray_terracotta"       ),
    -            entry(MaterialColor.TERRACOTTA_LIGHT_GRAY, "light_gray_terracotta" ),
    -            entry(MaterialColor.TERRACOTTA_CYAN      , "cyan_terracotta"       ),
    -            entry(MaterialColor.TERRACOTTA_PURPLE    , "purple_terracotta"     ),
    -            entry(MaterialColor.TERRACOTTA_BLUE      , "blue_terracotta"       ),
    -            entry(MaterialColor.TERRACOTTA_BROWN     , "brown_terracotta"      ),
    -            entry(MaterialColor.TERRACOTTA_GREEN     , "green_terracotta"      ),
    -            entry(MaterialColor.TERRACOTTA_RED       , "red_terracotta"        ),
    -            entry(MaterialColor.TERRACOTTA_BLACK     , "black_terracotta"      ),
    -            entry(MaterialColor.CRIMSON_NYLIUM        , "crimson_nylium"        ),
    -            entry(MaterialColor.CRIMSON_STEM         , "crimson_stem"          ),
    -            entry(MaterialColor.CRIMSON_HYPHAE        , "crimson_hyphae"        ),
    -            entry(MaterialColor.WARPED_NYLIUM         , "warped_nylium"         ),
    -            entry(MaterialColor.WARPED_STEM           , "warped_stem"           ),
    -            entry(MaterialColor.WARPED_HYPHAE         , "warped_hyphae"         ),
    -            entry(MaterialColor.WARPED_WART_BLOCK           , "warped_wart"           ),
    -            entry(MaterialColor.DEEPSLATE           , "deepslate"           ),
    -            entry(MaterialColor.RAW_IRON           , "raw_iron"           ),
    -            entry(MaterialColor.GLOW_LICHEN           , "glow_lichen"           )
    +    public static final Map mapColourName = Map.ofEntries(
    +            entry(MapColor.NONE     , "air"       ),
    +            entry(MapColor.GRASS     , "grass"     ),
    +            entry(MapColor.SAND       , "sand"      ),
    +            entry(MapColor.WOOL        , "wool"      ),
    +            entry(MapColor.FIRE       , "tnt"       ),
    +            entry(MapColor.ICE        , "ice"       ),
    +            entry(MapColor.METAL      , "iron"      ),
    +            entry(MapColor.PLANT    , "foliage"   ),
    +            entry(MapColor.SNOW     , "snow"      ),
    +            entry(MapColor.CLAY       , "clay"      ),
    +            entry(MapColor.DIRT       , "dirt"      ),
    +            entry(MapColor.STONE      , "stone"     ),
    +            entry(MapColor.WATER      , "water"     ),
    +            entry(MapColor.WOOD       , "wood"      ),
    +            entry(MapColor.QUARTZ     , "quartz"    ),
    +            entry(MapColor.COLOR_ORANGE    , "adobe"     ),
    +            entry(MapColor.COLOR_MAGENTA   , "magenta"   ),
    +            entry(MapColor.COLOR_LIGHT_BLUE, "light_blue"),
    +            entry(MapColor.COLOR_YELLOW    , "yellow"    ),
    +            entry(MapColor.COLOR_LIGHT_GREEN      , "lime"      ),
    +            entry(MapColor.COLOR_PINK      , "pink"      ),
    +            entry(MapColor.COLOR_GRAY      , "gray"      ),
    +            entry(MapColor.COLOR_LIGHT_GRAY, "light_gray"),
    +            entry(MapColor.COLOR_CYAN      , "cyan"      ),
    +            entry(MapColor.COLOR_PURPLE    , "purple"    ),
    +            entry(MapColor.COLOR_BLUE      , "blue"      ),
    +            entry(MapColor.COLOR_BROWN     , "brown"     ),
    +            entry(MapColor.COLOR_GREEN     , "green"     ),
    +            entry(MapColor.COLOR_RED       , "red"       ),
    +            entry(MapColor.COLOR_BLACK     , "black"     ),
    +            entry(MapColor.GOLD      , "gold"      ),
    +            entry(MapColor.DIAMOND    , "diamond"   ),
    +            entry(MapColor.LAPIS      , "lapis"     ),
    +            entry(MapColor.EMERALD    , "emerald"   ),
    +            entry(MapColor.PODZOL     , "obsidian"  ),
    +            entry(MapColor.NETHER     , "netherrack"), //TODO fix these
    +            entry(MapColor.TERRACOTTA_WHITE      , "white_terracotta"      ),
    +            entry(MapColor.TERRACOTTA_ORANGE    , "orange_terracotta"     ),
    +            entry(MapColor.TERRACOTTA_MAGENTA   , "magenta_terracotta"    ),
    +            entry(MapColor.TERRACOTTA_LIGHT_BLUE, "light_blue_terracotta" ),
    +            entry(MapColor.TERRACOTTA_YELLOW    , "yellow_terracotta"     ),
    +            entry(MapColor.TERRACOTTA_LIGHT_GREEN      , "lime_terracotta"       ),
    +            entry(MapColor.TERRACOTTA_PINK      , "pink_terracotta"       ),
    +            entry(MapColor.TERRACOTTA_GRAY      , "gray_terracotta"       ),
    +            entry(MapColor.TERRACOTTA_LIGHT_GRAY, "light_gray_terracotta" ),
    +            entry(MapColor.TERRACOTTA_CYAN      , "cyan_terracotta"       ),
    +            entry(MapColor.TERRACOTTA_PURPLE    , "purple_terracotta"     ),
    +            entry(MapColor.TERRACOTTA_BLUE      , "blue_terracotta"       ),
    +            entry(MapColor.TERRACOTTA_BROWN     , "brown_terracotta"      ),
    +            entry(MapColor.TERRACOTTA_GREEN     , "green_terracotta"      ),
    +            entry(MapColor.TERRACOTTA_RED       , "red_terracotta"        ),
    +            entry(MapColor.TERRACOTTA_BLACK     , "black_terracotta"      ),
    +            entry(MapColor.CRIMSON_NYLIUM        , "crimson_nylium"        ),
    +            entry(MapColor.CRIMSON_STEM         , "crimson_stem"          ),
    +            entry(MapColor.CRIMSON_HYPHAE        , "crimson_hyphae"        ),
    +            entry(MapColor.WARPED_NYLIUM         , "warped_nylium"         ),
    +            entry(MapColor.WARPED_STEM           , "warped_stem"           ),
    +            entry(MapColor.WARPED_HYPHAE         , "warped_hyphae"         ),
    +            entry(MapColor.WARPED_WART_BLOCK           , "warped_wart"           ),
    +            entry(MapColor.DEEPSLATE           , "deepslate"           ),
    +            entry(MapColor.RAW_IRON           , "raw_iron"           ),
    +            entry(MapColor.GLOW_LICHEN           , "glow_lichen"           )
         );
     }
    diff --git a/src/main/java/carpet/script/utils/EntityTools.java b/src/main/java/carpet/script/utils/EntityTools.java
    index 2598fdbaac..5849e50a8b 100644
    --- a/src/main/java/carpet/script/utils/EntityTools.java
    +++ b/src/main/java/carpet/script/utils/EntityTools.java
    @@ -12,12 +12,12 @@ public class EntityTools
          */
         public static void genericJump(Entity e)
         {
    -        if (!e.isOnGround() && !e.isInWaterOrBubble() && !e.isInLava())
    +        if (!e.onGround() && !e.isInWaterOrBubble() && !e.isInLava())
             {
                 return;
             }
    -        float m = e.level.getBlockState(e.blockPosition()).getBlock().getJumpFactor();
    -        float g = e.level.getBlockState(BlockPos.containing(e.getX(), e.getBoundingBox().minY - 0.5000001D, e.getZ())).getBlock().getJumpFactor();
    +        float m = e.level().getBlockState(e.blockPosition()).getBlock().getJumpFactor();
    +        float g = e.level().getBlockState(BlockPos.containing(e.getX(), e.getBoundingBox().minY - 0.5000001D, e.getZ())).getBlock().getJumpFactor();
             float jumpVelocityMultiplier = m == 1.0D ? g : m;
             float jumpStrength = (0.42F * jumpVelocityMultiplier);
             Vec3 vec3d = e.getDeltaMovement();
    diff --git a/src/main/java/carpet/script/utils/ShapeDispatcher.java b/src/main/java/carpet/script/utils/ShapeDispatcher.java
    index ce25aaac86..e2b02644d3 100644
    --- a/src/main/java/carpet/script/utils/ShapeDispatcher.java
    +++ b/src/main/java/carpet/script/utils/ShapeDispatcher.java
    @@ -767,15 +767,15 @@ public Consumer alternative()
                         {
                             return;
                         }
    -                    particle = getParticleData("block_marker " + blocks.getKey(Block.byItem(this.item.getItem())), p.level.registryAccess());
    +                    particle = getParticleData("block_marker " + blocks.getKey(Block.byItem(this.item.getItem())), p.level().registryAccess());
                     }
                     else
                     {
    -                    particle = getParticleData("block_marker " + blocks.getKey(this.blockState.getBlock()), p.level.registryAccess());
    +                    particle = getParticleData("block_marker " + blocks.getKey(this.blockState.getBlock()), p.level().registryAccess());
                     }
     
    -                Vec3 v = relativiseRender(p.level, this.pos, 0);
    -                p.getLevel().sendParticles(p, particle, true, v.x, v.y, v.z, 1, 0.0, 0.0, 0.0, 0.0);
    +                Vec3 v = relativiseRender(p.level(), this.pos, 0);
    +                p.serverLevel().sendParticles(p, particle, true, v.x, v.y, v.z, 1, 0.0, 0.0, 0.0, 0.0);
                 };
             }
     
    @@ -868,14 +868,14 @@ public Consumer alternative()
                 double density = Math.max(2.0, from.distanceTo(to) / 50 / (a + 0.1));
                 return p ->
                 {
    -                if (p.level.dimension() == shapeDimension)
    +                if (p.level().dimension() == shapeDimension)
                     {
                         particleMesh(
                                 Collections.singletonList(p),
    -                            replacementParticle(p.level.registryAccess()),
    +                            replacementParticle(p.level().registryAccess()),
                                 density,
    -                            relativiseRender(p.level, from, 0),
    -                            relativiseRender(p.level, to, 0)
    +                            relativiseRender(p.level(), from, 0),
    +                            relativiseRender(p.level(), to, 0)
                         );
                     }
                 };
    @@ -966,19 +966,19 @@ ArrayList getAlterPoint(ServerPlayer p)
                             Vec3 vecA = vertexList.get(i);
                             if (relative.get(i))
                             {
    -                            vecA = relativiseRender(p.level, vecA, 0);
    +                            vecA = relativiseRender(p.level(), vecA, 0);
                             }
                             i++;
                             Vec3 vecB = vertexList.get(i);
                             if (relative.get(i))
                             {
    -                            vecB = relativiseRender(p.level, vecB, 0);
    +                            vecB = relativiseRender(p.level(), vecB, 0);
                             }
                             i++;
                             Vec3 vecC = vertexList.get(i);
                             if (relative.get(i))
                             {
    -                            vecC = relativiseRender(p.level, vecC, 0);
    +                            vecC = relativiseRender(p.level(), vecC, 0);
                             }
                             alterDrawTriangles(vecA, vecB, vecC);
                         }
    @@ -987,19 +987,19 @@ ArrayList getAlterPoint(ServerPlayer p)
                         Vec3 vec0 = vertexList.get(0);
                         if (relative.get(0))
                         {
    -                        vec0 = relativiseRender(p.level, vec0, 0);
    +                        vec0 = relativiseRender(p.level(), vec0, 0);
                         }
                         Vec3 vec1 = vertexList.get(1);
                         if (relative.get(1))
                         {
    -                        vec1 = relativiseRender(p.level, vec1, 0);
    +                        vec1 = relativiseRender(p.level(), vec1, 0);
                         }
                         for (int i = 2; i < vertexList.size(); i++)
                         {
                             Vec3 vec = vertexList.get(i);
                             if (relative.get(i))
                             {
    -                            vec = relativiseRender(p.level, vec, 0);
    +                            vec = relativiseRender(p.level(), vec, 0);
                             }
                             alterDrawTriangles(vec0, vec1, vec);
                             vec1 = vec;
    @@ -1009,19 +1009,19 @@ ArrayList getAlterPoint(ServerPlayer p)
                         Vec3 vecA = vertexList.get(0);
                         if (relative.get(0))
                         {
    -                        vecA = relativiseRender(p.level, vecA, 0);
    +                        vecA = relativiseRender(p.level(), vecA, 0);
                         }
                         Vec3 vecB = vertexList.get(1);
                         if (relative.get(1))
                         {
    -                        vecB = relativiseRender(p.level, vecB, 0);
    +                        vecB = relativiseRender(p.level(), vecB, 0);
                         }
                         for (int i = 2; i < vertexList.size(); i++)
                         {
                             Vec3 vec = vertexList.get(i);
                             if (relative.get(i))
                             {
    -                            vec = relativiseRender(p.level, vec, 0);
    +                            vec = relativiseRender(p.level(), vec, 0);
                             }
                             alterDrawTriangles(vecA, vecB, vec);
                             vecA = vecB;
    @@ -1061,16 +1061,16 @@ void alterDrawTriangles(Vec3 a, Vec3 b, Vec3 c)
             public Consumer alternative()
             {
                 return p -> {
    -                if (p.level.dimension() != this.shapeDimension)
    +                if (p.level().dimension() != this.shapeDimension)
                     {
                         return;
                     }
                     if (fa > 0.0f)
                     {
    -                    ParticleOptions locparticledata = getParticleData(String.format(Locale.ROOT, "dust %.1f %.1f %.1f %.1f", fr, fg, fb, fa), p.level.registryAccess());
    +                    ParticleOptions locparticledata = getParticleData(String.format(Locale.ROOT, "dust %.1f %.1f %.1f %.1f", fr, fg, fb, fa), p.level().registryAccess());
                         for (Vec3 v : getAlterPoint(p))
                         {
    -                        p.getLevel().sendParticles(p, locparticledata, true,
    +                        p.serverLevel().sendParticles(p, locparticledata, true,
                                     v.x, v.y, v.z, 1,
                                     0.0, 0.0, 0.0, 0.0);
                         }
    @@ -1205,13 +1205,13 @@ public Consumer alternative()
                 double density = Math.max(2.0, from.distanceTo(to) / 50) / (a + 0.1);
                 return p ->
                 {
    -                if (p.level.dimension() == shapeDimension)
    +                if (p.level().dimension() == shapeDimension)
                     {
                         drawParticleLine(
                                 Collections.singletonList(p),
    -                            replacementParticle(p.level.registryAccess()),
    -                            relativiseRender(p.level, from, 0),
    -                            relativiseRender(p.level, to, 0),
    +                            replacementParticle(p.level().registryAccess()),
    +                            relativiseRender(p.level(), from, 0),
    +                            relativiseRender(p.level(), to, 0),
                                 density
                         );
                     }
    @@ -1279,8 +1279,8 @@ public Consumer alternative()
                 return p ->
                 {
                     int partno = Math.min(1000, 20 * subdivisions);
    -                RandomSource rand = p.level.getRandom();
    -                ServerLevel world = p.getLevel();
    +                RandomSource rand = p.level().getRandom();
    +                ServerLevel world = p.serverLevel();
                     ParticleOptions particle = replacementParticle(world.registryAccess());
     
                     Vec3 ccenter = relativiseRender(world, center, 0);
    @@ -1376,8 +1376,8 @@ public Consumer alternative()
                 return p ->
                 {
                     int partno = (int) Math.min(1000, Math.sqrt(20 * subdivisions * (1 + height)));
    -                RandomSource rand = p.level.getRandom();
    -                ServerLevel world = p.getLevel();
    +                RandomSource rand = p.level().getRandom();
    +                ServerLevel world = p.serverLevel();
                     ParticleOptions particle = replacementParticle(world.registryAccess());
     
                     Vec3 ccenter = relativiseRender(world, center, 0);
    @@ -2183,7 +2183,7 @@ private static int drawOptimizedParticleLine(List playerList, Part
             int parts = 0;
             for (ServerPlayer player : playerList)
             {
    -            ServerLevel world = player.getLevel();
    +            ServerLevel world = player.serverLevel();
                 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);
    @@ -2200,7 +2200,7 @@ private static int drawOptimizedParticleLine(List playerList, Part
                 int dev = 2 * divider;
                 for (ServerPlayer player : playerList)
                 {
    -                ServerLevel world = player.getLevel();
    +                ServerLevel world = player.serverLevel();
                     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);
    @@ -2224,7 +2224,7 @@ public static int drawParticleLine(List players, ParticleOptions p
             int pcount = 0;
             if (distance < 100)
             {
    -            RandomSource rand = players.get(0).level.random;
    +            RandomSource rand = players.get(0).level().random;
                 int particles = (int) (distance / density) + 1;
                 Vec3 towards = to.subtract(from);
                 for (int i = 0; i < particles; i++)
    @@ -2232,7 +2232,7 @@ public static int drawParticleLine(List players, ParticleOptions p
                     Vec3 at = from.add(towards.scale(rand.nextDouble()));
                     for (ServerPlayer player : players)
                     {
    -                    player.getLevel().sendParticles(player, particle, true,
    +                    player.serverLevel().sendParticles(player, particle, true,
                                 at.x, at.y, at.z, 1,
                                 0.0, 0.0, 0.0, 0.0);
                         pcount++;
    @@ -2253,7 +2253,7 @@ public static int drawParticleLine(List players, ParticleOptions p
             {
                 for (ServerPlayer player : players)
                 {
    -                player.getLevel().sendParticles(player, particle, true,
    +                player.serverLevel().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++;
    diff --git a/src/main/java/carpet/script/utils/SnoopyCommandSource.java b/src/main/java/carpet/script/utils/SnoopyCommandSource.java
    index a22121d7d6..75e8cdedec 100644
    --- a/src/main/java/carpet/script/utils/SnoopyCommandSource.java
    +++ b/src/main/java/carpet/script/utils/SnoopyCommandSource.java
    @@ -66,16 +66,16 @@ public SnoopyCommandSource(CommandSourceStack original, Component[] error, List<
         public SnoopyCommandSource(ServerPlayer player, Component[] error, List output)
         {
             super(player, player.position(), player.getRotationVector(),
    -                player.level instanceof final ServerLevel serverLevel ? serverLevel : null,
    +                player.level() instanceof final ServerLevel serverLevel ? serverLevel : null,
                     player.server.getProfilePermissions(player.getGameProfile()), player.getName().getString(), player.getDisplayName(),
    -                player.level.getServer(), player);
    +                player.level().getServer(), player);
             this.output = player;
             this.position = player.position();
    -        this.world = player.level instanceof final ServerLevel serverLevel ? serverLevel : null;
    +        this.world = player.level() instanceof final ServerLevel serverLevel ? serverLevel : null;
             this.level = player.server.getProfilePermissions(player.getGameProfile());
             this.simpleName = player.getName().getString();
             this.name = player.getDisplayName();
    -        this.server = player.level.getServer();
    +        this.server = player.level().getServer();
             this.entity = player;
             this.resultConsumer = (ctx, succ, res) -> {
             };
    diff --git a/src/main/java/carpet/script/utils/Tracer.java b/src/main/java/carpet/script/utils/Tracer.java
    index e4f4998a33..a1e17d132d 100644
    --- a/src/main/java/carpet/script/utils/Tracer.java
    +++ b/src/main/java/carpet/script/utils/Tracer.java
    @@ -31,7 +31,7 @@ public static BlockHitResult rayTraceBlocks(Entity source, float partialTicks, d
             Vec3 pos = source.getEyePosition(partialTicks);
             Vec3 rotation = source.getViewVector(partialTicks);
             Vec3 reachEnd = pos.add(rotation.x * reach, rotation.y * reach, rotation.z * reach);
    -        return source.level.clip(new ClipContext(pos, reachEnd, ClipContext.Block.OUTLINE, fluids ?
    +        return source.level().clip(new ClipContext(pos, reachEnd, ClipContext.Block.OUTLINE, fluids ?
                     ClipContext.Fluid.ANY : ClipContext.Fluid.NONE, source));
         }
     
    @@ -45,7 +45,7 @@ public static EntityHitResult rayTraceEntities(Entity source, float partialTicks
     
         public static EntityHitResult rayTraceEntities(Entity source, Vec3 start, Vec3 end, AABB box, Predicate predicate, double maxSqDistance)
         {
    -        Level world = source.level;
    +        Level world = source.level();
             double targetDistance = maxSqDistance;
             Entity target = null;
             Vec3 targetHitPos = null;
    diff --git a/src/main/java/carpet/script/utils/WorldTools.java b/src/main/java/carpet/script/utils/WorldTools.java
    index ce5ff43700..548b760457 100644
    --- a/src/main/java/carpet/script/utils/WorldTools.java
    +++ b/src/main/java/carpet/script/utils/WorldTools.java
    @@ -165,7 +165,7 @@ public static void forceChunkUpdate(BlockPos pos, ServerLevel world)
                 List players = world.getChunkSource().chunkMap.getPlayers(chunkPos, false);
                 if (!players.isEmpty())
                 {
    -                ClientboundLevelChunkWithLightPacket packet = new ClientboundLevelChunkWithLightPacket(worldChunk, world.getLightEngine(), null, null, false); // false seems to update neighbours as well.
    +                ClientboundLevelChunkWithLightPacket packet = new ClientboundLevelChunkWithLightPacket(worldChunk, world.getLightEngine(), null, null); // false seems to update neighbours as well.
                     players.forEach(p -> p.connection.send(packet));
                 }
             }
    diff --git a/src/main/java/carpet/script/value/EntityValue.java b/src/main/java/carpet/script/value/EntityValue.java
    index 2a4386ac82..24565a1dd7 100644
    --- a/src/main/java/carpet/script/value/EntityValue.java
    +++ b/src/main/java/carpet/script/value/EntityValue.java
    @@ -434,12 +434,12 @@ public Value get(String what, @Nullable Value arg)
             put("motion_x", (e, a) -> new NumericValue(e.getDeltaMovement().x));
             put("motion_y", (e, a) -> new NumericValue(e.getDeltaMovement().y));
             put("motion_z", (e, a) -> new NumericValue(e.getDeltaMovement().z));
    -        put("on_ground", (e, a) -> BooleanValue.of(e.isOnGround()));
    +        put("on_ground", (e, a) -> BooleanValue.of(e.onGround()));
             put("name", (e, a) -> new StringValue(e.getName().getString()));
             put("display_name", (e, a) -> new FormattedTextValue(e.getDisplayName()));
             put("command_name", (e, a) -> new StringValue(e.getScoreboardName()));
             put("custom_name", (e, a) -> e.hasCustomName() ? new StringValue(e.getCustomName().getString()) : Value.NULL);
    -        put("type", (e, a) -> nameFromRegistryId(e.getLevel().registryAccess().registryOrThrow(Registries.ENTITY_TYPE).getKey(e.getType())));
    +        put("type", (e, a) -> nameFromRegistryId(e.level().registryAccess().registryOrThrow(Registries.ENTITY_TYPE).getKey(e.getType())));
             put("is_riding", (e, a) -> BooleanValue.of(e.isPassenger()));
             put("is_ridden", (e, a) -> BooleanValue.of(e.isVehicle()));
             put("passengers", (e, a) -> ListValue.wrap(e.getPassengers().stream().map(EntityValue::new)));
    @@ -489,7 +489,7 @@ public Value get(String what, @Nullable Value arg)
             put("immune_to_frost", (e, a) -> BooleanValue.of(!e.canFreeze()));
     
             put("invulnerable", (e, a) -> BooleanValue.of(e.isInvulnerable()));
    -        put("dimension", (e, a) -> nameFromRegistryId(e.level.dimension().location())); // getDimId
    +        put("dimension", (e, a) -> nameFromRegistryId(e.level().dimension().location())); // getDimId
             put("height", (e, a) -> new NumericValue(e.getDimensions(Pose.STANDING).height));
             put("width", (e, a) -> new NumericValue(e.getDimensions(Pose.STANDING).width));
             put("eye_height", (e, a) -> new NumericValue(e.getEyeHeight()));
    @@ -516,7 +516,7 @@ public Value get(String what, @Nullable Value arg)
                 }
                 return Value.NULL;
             });
    -        put("home", (e, a) -> e instanceof final Mob mob ? (mob.getRestrictRadius() > 0) ? new BlockValue(null, (ServerLevel) e.getLevel(), mob.getRestrictCenter()) : Value.FALSE : Value.NULL);
    +        put("home", (e, a) -> e instanceof final Mob mob ? (mob.getRestrictRadius() > 0) ? new BlockValue(null, (ServerLevel) e.level(), mob.getRestrictCenter()) : Value.FALSE : Value.NULL);
             put("spawn_point", (e, a) -> {
                 if (e instanceof final ServerPlayer spe)
                 {
    @@ -566,7 +566,7 @@ public Value get(String what, @Nullable Value arg)
     
             put("brain", (e, a) -> {
                 String module = a.getString();
    -            MemoryModuleType moduleType = e.getLevel().registryAccess().registryOrThrow(Registries.MEMORY_MODULE_TYPE).get(InputValidator.identifierOf(module));
    +            MemoryModuleType moduleType = e.level().registryAccess().registryOrThrow(Registries.MEMORY_MODULE_TYPE).get(InputValidator.identifierOf(module));
                 if (moduleType == MemoryModuleType.DUMMY)
                 {
                     return Value.NULL;
    @@ -704,7 +704,7 @@ public Value get(String what, @Nullable Value arg)
                     {
                         return Value.NULL;
                     }
    -                return new BlockValue(null, sp.getLevel(), pos);
    +                return new BlockValue(null, sp.serverLevel(), pos);
                 }
                 return Value.NULL;
             });
    @@ -831,7 +831,7 @@ else if (entities)
                 {
                     return Value.NULL;
                 }
    -            Registry attributes = e.getLevel().registryAccess().registryOrThrow(Registries.ATTRIBUTE);
    +            Registry attributes = e.level().registryAccess().registryOrThrow(Registries.ATTRIBUTE);
                 if (a == null)
                 {
                     AttributeMap container = el.getAttributes();
    @@ -1711,7 +1711,7 @@ else if (v instanceof final ListValue lv)
     
             });
             put("item", (e, v) -> {
    -            ItemStack item = ValueConversions.getItemStackFromValue(v, true, e.level.registryAccess());
    +            ItemStack item = ValueConversions.getItemStackFromValue(v, true, e.level().registryAccess());
                 if (e instanceof final ItemEntity itementity)
                 {
                     itementity.setItem(item);
    @@ -1745,7 +1745,7 @@ public net.minecraft.nbt.Tag toTag(boolean force)
             }
             CompoundTag tag = new CompoundTag();
             tag.put("Data", getEntity().saveWithoutId(new CompoundTag()));
    -        Registry> reg = getEntity().level.registryAccess().registryOrThrow(Registries.ENTITY_TYPE);
    +        Registry> reg = getEntity().level().registryAccess().registryOrThrow(Registries.ENTITY_TYPE);
             tag.put("Name", StringTag.valueOf(reg.getKey(getEntity().getType()).toString()));
             return tag;
         }
    diff --git a/src/main/java/carpet/script/value/ScreenValue.java b/src/main/java/carpet/script/value/ScreenValue.java
    index 366738e787..faa177b798 100644
    --- a/src/main/java/carpet/script/value/ScreenValue.java
    +++ b/src/main/java/carpet/script/value/ScreenValue.java
    @@ -265,7 +265,7 @@ public void slotChanged(AbstractContainerMenu handler, int slotId, ItemStack sta
                 {
                     Map data = new HashMap<>();
                     data.put(StringValue.of("slot"), NumericValue.of(slotId));
    -                data.put(StringValue.of("stack"), ValueConversions.of(stack, player.level.registryAccess()));
    +                data.put(StringValue.of("stack"), ValueConversions.of(stack, player.level().registryAccess()));
                     ScreenValue.this.callListener(ScreenValue.this.player, "slot_update", data);
                 }
     
    diff --git a/src/main/java/carpet/script/value/ValueConversions.java b/src/main/java/carpet/script/value/ValueConversions.java
    index d93bcb160b..1c595fca52 100644
    --- a/src/main/java/carpet/script/value/ValueConversions.java
    +++ b/src/main/java/carpet/script/value/ValueConversions.java
    @@ -40,7 +40,7 @@
     import net.minecraft.world.level.levelgen.structure.BoundingBox;
     import net.minecraft.world.level.levelgen.structure.StructurePiece;
     import net.minecraft.world.level.levelgen.structure.StructureStart;
    -import net.minecraft.world.level.material.MaterialColor;
    +import net.minecraft.world.level.material.MapColor;
     import net.minecraft.world.level.pathfinder.Node;
     import net.minecraft.world.level.pathfinder.Path;
     import net.minecraft.world.phys.AABB;
    @@ -84,7 +84,7 @@ public static Value of(ServerLevel world)
             return of(world.dimension().location());
         }
     
    -    public static Value of(MaterialColor color)
    +    public static Value of(MapColor color)
         {
             return ListValue.of(StringValue.of(Colors.mapColourName.get(color)), ofRGB(color.col));
         }
    diff --git a/src/main/java/carpet/utils/SpawnReporter.java b/src/main/java/carpet/utils/SpawnReporter.java
    index f7b6a5e1e9..7db763a5c0 100644
    --- a/src/main/java/carpet/utils/SpawnReporter.java
    +++ b/src/main/java/carpet/utils/SpawnReporter.java
    @@ -85,7 +85,7 @@ public static void registerSpawn(Mob mob, MobCategory cat, BlockPos pos)
                     return;
                 }
             }
    -        Pair, MobCategory> key = Pair.of(mob.level.dimension(), cat);
    +        Pair, MobCategory> key = Pair.of(mob.level().dimension(), cat);
             long count = spawn_stats.get(key).getOrDefault(mob.getType(), 0L);
             spawn_stats.get(key).put(mob.getType(), count + 1);
             spawned_mobs.get(key).put(Pair.of(mob.getType(), pos));
    diff --git a/src/main/java/carpet/utils/WoolTool.java b/src/main/java/carpet/utils/WoolTool.java
    index fa1bc79e0d..4f0da908b3 100644
    --- a/src/main/java/carpet/utils/WoolTool.java
    +++ b/src/main/java/carpet/utils/WoolTool.java
    @@ -18,7 +18,7 @@
     import net.minecraft.world.item.DyeColor;
     import net.minecraft.world.level.Level;
     import net.minecraft.world.level.block.state.BlockState;
    -import net.minecraft.world.level.material.MaterialColor;
    +import net.minecraft.world.level.material.MapColor;
     import net.minecraft.world.phys.Vec3;
     
     import javax.annotation.Nullable;
    @@ -32,34 +32,34 @@
     public class WoolTool
     {
         /**
    -     * A map of the {@link MaterialColor} to the {@link DyeColor} which is used in {@link WoolTool#getWoolColorAtPosition}
    +     * A map of the {@link net.minecraft.world.level.material.MapColor} to the {@link DyeColor} which is used in {@link WoolTool#getWoolColorAtPosition}
          * to get the colour of wool at a position.
          */
    -    private static final Map Material2Dye = Arrays.stream(DyeColor.values())
    -            .collect(Collectors.toUnmodifiableMap(DyeColor::getMaterialColor, Function.identity()));
    +    private static final Map Material2Dye = Arrays.stream(DyeColor.values())
    +            .collect(Collectors.toUnmodifiableMap(DyeColor::getMapColor, Function.identity()));
     
         /**
          * A map of all the wool colours to their respective colours in the {@link Messenger#m} format so the name of the counter
          * gets printed in colour.
          */
     
    -    public static final Map Material2DyeName = Map.ofEntries(
    -        entry(MaterialColor.SNOW, "w "),
    -        entry(MaterialColor.COLOR_ORANGE, "#F9801D "),
    -        entry(MaterialColor.COLOR_MAGENTA, "m "),
    -        entry(MaterialColor.COLOR_LIGHT_BLUE, "t "),
    -        entry(MaterialColor.COLOR_YELLOW, "y "),
    -        entry(MaterialColor.COLOR_LIGHT_GREEN, "l "),
    -        entry(MaterialColor.COLOR_PINK, "#FFACCB "),
    -        entry(MaterialColor.COLOR_GRAY, "f "),
    -        entry(MaterialColor.COLOR_LIGHT_GRAY, "g "),
    -        entry(MaterialColor.COLOR_CYAN, "c "),
    -        entry(MaterialColor.COLOR_PURPLE, "p "),
    -        entry(MaterialColor.COLOR_BLUE, "v "),
    -        entry(MaterialColor.COLOR_BROWN, "#835432 "),
    -        entry(MaterialColor.COLOR_GREEN, "e "),
    -        entry(MaterialColor.COLOR_RED, "r "),
    -        entry(MaterialColor.COLOR_BLACK, "k ")
    +    public static final Map Material2DyeName = Map.ofEntries(
    +        entry(MapColor.SNOW, "w "),
    +        entry(MapColor.COLOR_ORANGE, "#F9801D "),
    +        entry(MapColor.COLOR_MAGENTA, "m "),
    +        entry(MapColor.COLOR_LIGHT_BLUE, "t "),
    +        entry(MapColor.COLOR_YELLOW, "y "),
    +        entry(MapColor.COLOR_LIGHT_GREEN, "l "),
    +        entry(MapColor.COLOR_PINK, "#FFACCB "),
    +        entry(MapColor.COLOR_GRAY, "f "),
    +        entry(MapColor.COLOR_LIGHT_GRAY, "g "),
    +        entry(MapColor.COLOR_CYAN, "c "),
    +        entry(MapColor.COLOR_PURPLE, "p "),
    +        entry(MapColor.COLOR_BLUE, "v "),
    +        entry(MapColor.COLOR_BROWN, "#835432 "),
    +        entry(MapColor.COLOR_GREEN, "e "),
    +        entry(MapColor.COLOR_RED, "r "),
    +        entry(MapColor.COLOR_BLACK, "k ")
         );
     
         /**
    
    From 00ee45d59bb9f42969dace5ed7b0d7cc29a7173c Mon Sep 17 00:00:00 2001
    From: gnembon <41132274+gnembon@users.noreply.github.com>
    Date: Wed, 26 Apr 2023 22:59:34 +0200
    Subject: [PATCH 130/233] 1.4.106
    
    ---
     gradle.properties | 2 +-
     1 file changed, 1 insertion(+), 1 deletion(-)
    
    diff --git a/gradle.properties b/gradle.properties
    index 144aafbf3c..ef25f0aa6f 100644
    --- a/gradle.properties
    +++ b/gradle.properties
    @@ -9,7 +9,7 @@ org.gradle.jvmargs=-Xmx1G
     	fabric_version=0.79.1+1.20
     
     # Mod Properties
    -	mod_version = 1.4.105
    +	mod_version = 1.4.106
     	maven_group = carpet
     	archives_base_name = fabric-carpet
     
    
    From 1c4bcd682d01706f860640bb816979d6ed5661e1 Mon Sep 17 00:00:00 2001
    From: altrisi 
    Date: Thu, 27 Apr 2023 18:06:57 +0200
    Subject: [PATCH 131/233] Use `DyeColor`'s `textColor` for hopper counters
     (#1709)
    
    * Use `DyeColor`'s `textColor` for hopper counters
    
    * Remove now unused `Material2DyeName` map in `WoolTool`
    ---
     .../java/carpet/helpers/HopperCounter.java    | 20 +++++++++-------
     src/main/java/carpet/utils/WoolTool.java      | 24 -------------------
     2 files changed, 11 insertions(+), 33 deletions(-)
    
    diff --git a/src/main/java/carpet/helpers/HopperCounter.java b/src/main/java/carpet/helpers/HopperCounter.java
    index fb5dd3b03b..2138541e16 100644
    --- a/src/main/java/carpet/helpers/HopperCounter.java
    +++ b/src/main/java/carpet/helpers/HopperCounter.java
    @@ -3,7 +3,6 @@
     import carpet.CarpetServer;
     import carpet.fakes.IngredientInterface;
     import carpet.fakes.RecipeManagerInterface;
    -import carpet.utils.WoolTool;
     import carpet.utils.Messenger;
     import it.unimi.dsi.fastutil.objects.Object2LongLinkedOpenHashMap;
     import it.unimi.dsi.fastutil.objects.Object2LongMap;
    @@ -79,7 +78,7 @@ public class HopperCounter
          * The string which is passed into {@link Messenger#m} which makes each counter name be displayed in the colour of
          * that counter.
          */
    -    private final String prettyColour;
    +    private final String coloredName;
         /**
          * All the items stored within the counter, as a map of {@link Item} mapped to a {@code long} of the amount of items
          * stored thus far of that item type.
    @@ -101,7 +100,10 @@ private HopperCounter(DyeColor color)
         {
             startTick = -1;
             this.color = color;
    -        this.prettyColour = WoolTool.Material2DyeName.getOrDefault(color.getMapColor(),"w ") + color.getName();
    +        String hexColor = Integer.toHexString(color.getTextColor());
    +        if (hexColor.length() < 6)
    +            hexColor = "0".repeat(hexColor.length() - 4) + hexColor;
    +        this.coloredName = '#' + hexColor + ' ' + color.getName();
         }
     
         /**
    @@ -179,31 +181,31 @@ public List format(MinecraftServer server, boolean realTime, boolean
             {
                 if (brief)
                 {
    -                return Collections.singletonList(Messenger.c("b"+prettyColour,"w : ","gi -, -/h, - min "));
    +                return Collections.singletonList(Messenger.c("b"+coloredName,"w : ","gi -, -/h, - min "));
                 }
    -            return Collections.singletonList(Messenger.c(prettyColour, "w  hasn't started counting yet"));
    +            return Collections.singletonList(Messenger.c(coloredName, "w  hasn't started counting yet"));
             }
             long total = getTotalItems();
             if (total == 0)
             {
                 if (brief)
                 {
    -                return Collections.singletonList(Messenger.c("b"+prettyColour,"w : ","wb 0","w , ","wb 0","w /h, ", String.format("wb %.1f ", ticks / (20.0 * 60.0)), "w min"));
    +                return Collections.singletonList(Messenger.c("b"+coloredName,"w : ","wb 0","w , ","wb 0","w /h, ", String.format("wb %.1f ", ticks / (20.0 * 60.0)), "w min"));
                 }
    -            return Collections.singletonList(Messenger.c("w No items for ", prettyColour, String.format("w  yet (%.2f min.%s)",
    +            return Collections.singletonList(Messenger.c("w No items for ", coloredName, String.format("w  yet (%.2f min.%s)",
                         ticks / (20.0 * 60.0), (realTime ? " - real time" : "")),
                         "nb  [X]", "^g reset", "!/counter " + color.getName() +" reset"));
             }
             if (brief)
             {
    -            return Collections.singletonList(Messenger.c("b"+prettyColour,"w : ",
    +            return Collections.singletonList(Messenger.c("b"+coloredName,"w : ",
                         "wb "+total,"w , ",
                         "wb "+(total * (20 * 60 * 60) / ticks),"w /h, ",
                         String.format("wb %.1f ", ticks / (20.0 * 60.0)), "w min"
                 ));
             }
             List items = new ArrayList<>();
    -        items.add(Messenger.c("w Items for ", prettyColour,
    +        items.add(Messenger.c("w Items for ", coloredName,
                     "w  (",String.format("wb %.2f", ticks*1.0/(20*60)), "w  min"+(realTime?" - real time":"")+"), ",
                     "w total: ", "wb "+total, "w , (",String.format("wb %.1f",total*1.0*(20*60*60)/ticks),"w /h):",
                     "nb [X]", "^g reset", "!/counter "+color+" reset"
    diff --git a/src/main/java/carpet/utils/WoolTool.java b/src/main/java/carpet/utils/WoolTool.java
    index 4f0da908b3..93a682f3c8 100644
    --- a/src/main/java/carpet/utils/WoolTool.java
    +++ b/src/main/java/carpet/utils/WoolTool.java
    @@ -38,30 +38,6 @@ public class WoolTool
         private static final Map Material2Dye = Arrays.stream(DyeColor.values())
                 .collect(Collectors.toUnmodifiableMap(DyeColor::getMapColor, Function.identity()));
     
    -    /**
    -     * A map of all the wool colours to their respective colours in the {@link Messenger#m} format so the name of the counter
    -     * gets printed in colour.
    -     */
    -
    -    public static final Map Material2DyeName = Map.ofEntries(
    -        entry(MapColor.SNOW, "w "),
    -        entry(MapColor.COLOR_ORANGE, "#F9801D "),
    -        entry(MapColor.COLOR_MAGENTA, "m "),
    -        entry(MapColor.COLOR_LIGHT_BLUE, "t "),
    -        entry(MapColor.COLOR_YELLOW, "y "),
    -        entry(MapColor.COLOR_LIGHT_GREEN, "l "),
    -        entry(MapColor.COLOR_PINK, "#FFACCB "),
    -        entry(MapColor.COLOR_GRAY, "f "),
    -        entry(MapColor.COLOR_LIGHT_GRAY, "g "),
    -        entry(MapColor.COLOR_CYAN, "c "),
    -        entry(MapColor.COLOR_PURPLE, "p "),
    -        entry(MapColor.COLOR_BLUE, "v "),
    -        entry(MapColor.COLOR_BROWN, "#835432 "),
    -        entry(MapColor.COLOR_GREEN, "e "),
    -        entry(MapColor.COLOR_RED, "r "),
    -        entry(MapColor.COLOR_BLACK, "k ")
    -    );
    -
         /**
          * The method which gets triggered when a player places a carpet, and decides what to do based on the carpet's colour:
          * 
      From 68a447daf9e033e8223f85a9d1ba16bb742753cb Mon Sep 17 00:00:00 2001 From: altrisi Date: Thu, 27 Apr 2023 18:07:23 +0200 Subject: [PATCH 132/233] Don't use map color to check for wool color (#1708) --- src/main/java/carpet/utils/WoolTool.java | 34 +++++++++++++++--------- 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/src/main/java/carpet/utils/WoolTool.java b/src/main/java/carpet/utils/WoolTool.java index 93a682f3c8..23f16c5687 100644 --- a/src/main/java/carpet/utils/WoolTool.java +++ b/src/main/java/carpet/utils/WoolTool.java @@ -3,11 +3,8 @@ import carpet.CarpetSettings; import carpet.helpers.HopperCounter; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.Map; -import java.util.function.Function; -import java.util.stream.Collectors; import net.minecraft.commands.CommandSourceStack; import net.minecraft.core.BlockPos; @@ -17,6 +14,8 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.DyeColor; import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.MapColor; import net.minecraft.world.phys.Vec3; @@ -32,11 +31,27 @@ public class WoolTool { /** - * A map of the {@link net.minecraft.world.level.material.MapColor} to the {@link DyeColor} which is used in {@link WoolTool#getWoolColorAtPosition} + * A map from a wool {@link Block} to its {@link DyeColor} which is used in {@link WoolTool#getWoolColorAtPosition} * to get the colour of wool at a position. */ - private static final Map Material2Dye = Arrays.stream(DyeColor.values()) - .collect(Collectors.toUnmodifiableMap(DyeColor::getMapColor, Function.identity())); + private static final Map WOOL_BLOCK_TO_DYE = Map.ofEntries( + entry(Blocks.WHITE_WOOL, DyeColor.WHITE), + entry(Blocks.ORANGE_WOOL, DyeColor.ORANGE), + entry(Blocks.MAGENTA_WOOL, DyeColor.MAGENTA), + entry(Blocks.LIGHT_BLUE_WOOL, DyeColor.LIGHT_BLUE), + entry(Blocks.YELLOW_WOOL, DyeColor.YELLOW), + entry(Blocks.LIME_WOOL, DyeColor.LIME), + entry(Blocks.PINK_WOOL, DyeColor.PINK), + entry(Blocks.GRAY_WOOL, DyeColor.GRAY), + entry(Blocks.LIGHT_GRAY_WOOL, DyeColor.LIGHT_GRAY), + entry(Blocks.CYAN_WOOL, DyeColor.CYAN), + entry(Blocks.PURPLE_WOOL, DyeColor.PURPLE), + entry(Blocks.BLUE_WOOL, DyeColor.BLUE), + entry(Blocks.BROWN_WOOL, DyeColor.BROWN), + entry(Blocks.GREEN_WOOL, DyeColor.GREEN), + entry(Blocks.RED_WOOL, DyeColor.RED), + entry(Blocks.BLACK_WOOL, DyeColor.BLACK) + ); /** * The method which gets triggered when a player places a carpet, and decides what to do based on the carpet's colour: @@ -109,11 +124,6 @@ public static void carpetPlacedAction(DyeColor color, Player placer, BlockPos po public static DyeColor getWoolColorAtPosition(Level worldIn, BlockPos pos) { BlockState state = worldIn.getBlockState(pos); - // wool and wool carpets - if (!state.is(BlockTags.WOOL)) - { - return null; - } - return Material2Dye.get(state.getMapColor(worldIn, pos)); + return WOOL_BLOCK_TO_DYE.get(state.getBlock()); } } From 773e8722ca6960a0b727cde0c6d342aec2beccdc Mon Sep 17 00:00:00 2001 From: altrisi Date: Mon, 1 May 2023 13:56:07 +0200 Subject: [PATCH 133/233] Reuse Mojang's `floor` function in noise samplers --- .../script/utils/PerlinNoiseSampler.java | 23 ++++++++----------- .../script/utils/SimplexNoiseSampler.java | 11 +++++---- 2 files changed, 15 insertions(+), 19 deletions(-) diff --git a/src/main/java/carpet/script/utils/PerlinNoiseSampler.java b/src/main/java/carpet/script/utils/PerlinNoiseSampler.java index 56903050e4..3c3daa79e8 100644 --- a/src/main/java/carpet/script/utils/PerlinNoiseSampler.java +++ b/src/main/java/carpet/script/utils/PerlinNoiseSampler.java @@ -1,6 +1,7 @@ package carpet.script.utils; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; +import net.minecraft.util.Mth; import java.util.Map; import java.util.Random; @@ -59,9 +60,9 @@ public double sample3d(double x, double y, double z) double f = x + this.originX; double g = y + this.originY; double h = z + this.originZ; - int i = floor(f); - int j = floor(g); - int k = floor(h); + int i = Mth.floor(f); + int j = Mth.floor(g); + int k = Mth.floor(h); double l = f - (double) i; double m = g - (double) j; double n = h - (double) k; @@ -72,7 +73,7 @@ public double sample3d(double x, double y, double z) /* if (d != 0.0D) { double r = Math.min(e, m); - t = (double)floor(r / d) * d; + t = (double)Mth.floor(r / d) * d; } else { t = 0.0D; }*/ @@ -120,8 +121,8 @@ public double sample2d(double x, double y) { double f = x + this.originX; double g = y + this.originY; - int i = floor(f); - int j = floor(g); + int i = Mth.floor(f); + int j = Mth.floor(g); double l = f - (double) i; double m = g - (double) j; double o = perlinFade(l); @@ -161,7 +162,7 @@ public static double lerp2(double deltaX, double deltaY, double d, double e, dou public double sample1d(double x) { double f = x + this.originX; - int i = floor(f); + int i = Mth.floor(f); double l = f - i; double o = perlinFade(l); return this.sample1d(i, l, o) + 0.5; @@ -194,10 +195,4 @@ public static double perlinFade(double d) { return d * d * d * (d * (d * 6.0D - 15.0D) + 10.0D); } - - public static int floor(double d) - { - int i = (int) d; - return d < i ? i - 1 : i; - } -} \ No newline at end of file +} diff --git a/src/main/java/carpet/script/utils/SimplexNoiseSampler.java b/src/main/java/carpet/script/utils/SimplexNoiseSampler.java index 5b16882ec0..0237e5a34a 100644 --- a/src/main/java/carpet/script/utils/SimplexNoiseSampler.java +++ b/src/main/java/carpet/script/utils/SimplexNoiseSampler.java @@ -1,6 +1,7 @@ package carpet.script.utils; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; +import net.minecraft.util.Mth; import java.util.Map; import java.util.Random; @@ -52,8 +53,8 @@ public double sample2d(double x, double y) x = x / 2; y = y / 2; double d = (x + y) * SKEW_FACTOR_2D; - int i = PerlinNoiseSampler.floor(x + d); - int j = PerlinNoiseSampler.floor(y + d); + int i = Mth.floor(x + d); + int j = Mth.floor(y + d); double e = (i + j) * UNSKEW_FACTOR_2D; double f = i - e; double g = j - e; @@ -96,9 +97,9 @@ public double sample3d(double d, double e, double f) f = f / 2; //final double g = 0.3333333333333333D; double h = (d + e + f) * 0.3333333333333333D; - int i = floor(d + h); - int j = floor(e + h); - int k = floor(f + h); + int i = Mth.floor(d + h); + int j = Mth.floor(e + h); + int k = Mth.floor(f + h); //final double l = 0.16666666666666666D; double m = (i + j + k) * 0.16666666666666666D; double n = i - m; From 334f1060a535b5d3d467c014d71e05422c3681a2 Mon Sep 17 00:00:00 2001 From: altrisi Date: Mon, 1 May 2023 14:45:12 +0200 Subject: [PATCH 134/233] Fix wrong zero padding of hex color in #1709 Found by manyrandomthings on #1715 Co-authored-by: manyrandomthings <42223559+manyrandomthings@users.noreply.github.com> --- src/main/java/carpet/helpers/HopperCounter.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/carpet/helpers/HopperCounter.java b/src/main/java/carpet/helpers/HopperCounter.java index 2138541e16..5bcedeca45 100644 --- a/src/main/java/carpet/helpers/HopperCounter.java +++ b/src/main/java/carpet/helpers/HopperCounter.java @@ -102,7 +102,7 @@ private HopperCounter(DyeColor color) this.color = color; String hexColor = Integer.toHexString(color.getTextColor()); if (hexColor.length() < 6) - hexColor = "0".repeat(hexColor.length() - 4) + hexColor; + hexColor = "0".repeat(6 - hexColor.length()) + hexColor; this.coloredName = '#' + hexColor + ' ' + color.getName(); } From 9cae675ede91e571cbf74da42775cc95f806751b Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 3 May 2023 21:50:37 +0200 Subject: [PATCH 135/233] attempt to make the game no crash when resetting chunks. Lighting gonna get fixed later I presume --- ...tionStorage_scarpetChunkCreationMixin.java | 9 +++++---- ...tionStorage_scarpetChunkCreationMixin.java | 19 ++++++++++--------- ...LightEngine_scarpetChunkCreationMixin.java | 15 ++------------- 3 files changed, 17 insertions(+), 26 deletions(-) diff --git a/src/main/java/carpet/mixins/BlockLightSectionStorage_scarpetChunkCreationMixin.java b/src/main/java/carpet/mixins/BlockLightSectionStorage_scarpetChunkCreationMixin.java index 238f5fde13..5111b614f5 100644 --- a/src/main/java/carpet/mixins/BlockLightSectionStorage_scarpetChunkCreationMixin.java +++ b/src/main/java/carpet/mixins/BlockLightSectionStorage_scarpetChunkCreationMixin.java @@ -26,7 +26,7 @@ private BlockLightSectionStorage_scarpetChunkCreationMixin(final LightLayer ligh @Override public void processRelight(final LightEngine lightProvider, final long cPos) { - final DynamicGraphMinFixedPoint_resetChunkInterface levelPropagator = (DynamicGraphMinFixedPoint_resetChunkInterface) lightProvider; + //final DynamicGraphMinFixedPoint_resetChunkInterface levelPropagator = (DynamicGraphMinFixedPoint_resetChunkInterface) lightProvider.; for (int y = -1; y < 17; ++y) { @@ -53,11 +53,12 @@ public void processRelight(final LightEngine lightProvider, final long cPo for (int dy = 0; dy < 16; ++dy) { final long dst = BlockPos.offset(pos, ox + t * dx, dy, oz + t * dz); - final long src = BlockPos.offset(dst, dir); + lightProvider.checkBlock(BlockPos.of(dst)); + //final long src = BlockPos.offset(dst, dir); - final int srcLevel = ((ChunkLightProviderInterface) lightProvider).callGetCurrentLevelFromSection(neighborLightArray, src); + //final int srcLevel = ((ChunkLightProviderInterface) lightProvider).callGetCurrentLevelFromSection(neighborLightArray, src); - levelPropagator.cmInvokeUpdateLevel(src, dst, levelPropagator.cmCallGetPropagatedLevel(src, dst, srcLevel), true); + //levelPropagator.cmInvokeUpdateLevel(src, dst, levelPropagator.cmCallGetPropagatedLevel(src, dst, srcLevel), true); } } } diff --git a/src/main/java/carpet/mixins/SkyLightSectionStorage_scarpetChunkCreationMixin.java b/src/main/java/carpet/mixins/SkyLightSectionStorage_scarpetChunkCreationMixin.java index 83daf4150c..579a1cd402 100644 --- a/src/main/java/carpet/mixins/SkyLightSectionStorage_scarpetChunkCreationMixin.java +++ b/src/main/java/carpet/mixins/SkyLightSectionStorage_scarpetChunkCreationMixin.java @@ -62,7 +62,7 @@ public void processRemoveLightData(final long cPos) @Override public void processRelight(final LightEngine lightProvider, final long cPos) { - final DynamicGraphMinFixedPoint_resetChunkInterface levelPropagator = (DynamicGraphMinFixedPoint_resetChunkInterface) lightProvider; + //final DynamicGraphMinFixedPoint_resetChunkInterface levelPropagator = (DynamicGraphMinFixedPoint_resetChunkInterface) lightProvider; for (int y = -1; y < 17; ++y) { @@ -102,17 +102,18 @@ public void processRelight(final LightEngine lightProvider, final long cPo for (int dy = 0; dy < 16; ++dy) { final long dst = BlockPos.offset(pos, ox + t * dx, dy, oz + t * dz); - long src = BlockPos.offset(dst, dir); + //long src = BlockPos.offset(dst, dir); - long adj_src = (neighborLightArray != null) - ? src - : BlockPos.asLong(BlockPos.getX(src), neighbourY, BlockPos.getZ(src)); + //long adj_src = (neighborLightArray != null) + // ? src + // : BlockPos.asLong(BlockPos.getX(src), neighbourY, BlockPos.getZ(src)); - final int srcLevel = neighborCeilingLightArray != null - ? ((ChunkLightProviderInterface) lightProvider).callGetCurrentLevelFromSection(neighborCeilingLightArray, adj_src) - : emptyLightLevel; + //final int srcLevel = neighborCeilingLightArray != null + // ? ((ChunkLightProviderInterface) lightProvider).callGetCurrentLevelFromSection(neighborCeilingLightArray, adj_src) + // : emptyLightLevel; - levelPropagator.cmInvokeUpdateLevel(src, dst, levelPropagator.cmCallGetPropagatedLevel(src, dst, srcLevel), true); + lightProvider.checkBlock(BlockPos.of(dst)); + //levelPropagator.cmInvokeUpdateLevel(src, dst, levelPropagator.cmCallGetPropagatedLevel(src, dst, srcLevel), true); } } } diff --git a/src/main/java/carpet/mixins/ThreadedLevelLightEngine_scarpetChunkCreationMixin.java b/src/main/java/carpet/mixins/ThreadedLevelLightEngine_scarpetChunkCreationMixin.java index 16fd2da860..71eeec3c84 100644 --- a/src/main/java/carpet/mixins/ThreadedLevelLightEngine_scarpetChunkCreationMixin.java +++ b/src/main/java/carpet/mixins/ThreadedLevelLightEngine_scarpetChunkCreationMixin.java @@ -35,8 +35,6 @@ private ThreadedLevelLightEngine_scarpetChunkCreationMixin(final LightChunkGette @Final private ChunkMap chunkMap; - //@Shadow public abstract void propagateLightSources(final ChunkPos chunkPos); - @Override @Invoker("updateChunkStatus") public abstract void invokeUpdateChunkStatus(ChunkPos pos); @@ -61,22 +59,13 @@ public CompletableFuture relight(final ChunkAccess chunk) final ChunkPos pos = chunk.getPos(); propagateLightSources(pos); - /*this.addTask(pos.x, pos.z, () -> 0, ThreadedLevelLightEngine.TaskType.PRE_UPDATE, Util.name(() -> { - super.setLightEnabled(pos, true); - - chunk.findBlockLightSources((lightPos, state) -> { - final int lightEmission = state.getLightEmission(); - enqueueIncrease(lightPos.asLong(), LightEngine.QueueEntry.increaseLightFromEmission(lightEmission, isEmptyShape(state))); - }); + this.addTask(pos.x, pos.z, () -> 0, ThreadedLevelLightEngine.TaskType.PRE_UPDATE, Util.name(() -> { - chunk.getLights().forEach( - blockPos -> super.onBlockEmissionIncrease(blockPos, chunk.getLightEmission(blockPos)) - ); ((Lighting_scarpetChunkCreationInterface) this).relight(SectionPos.getZeroNode(SectionPos.asLong(pos.x, 0, pos.z))); }, () -> "Relight chunk " + pos - ));*/ + )); return CompletableFuture.runAsync( Util.name(() -> { From cac97b5127fcfb25f030034c18df33f47a493b26 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 3 May 2023 22:09:14 +0200 Subject: [PATCH 136/233] 23w18a --- gradle.properties | 4 ++-- .../mixins/LayerLightEngine_scarpetChunkCreationMixin.java | 4 ++-- .../LayerLightSectionStorage_scarpetChunkCreationMixin.java | 2 +- .../mixins/ServerPlayerGameMode_scarpetEventsMixin.java | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/gradle.properties b/gradle.properties index ef25f0aa6f..cce20ec66c 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,10 +3,10 @@ org.gradle.jvmargs=-Xmx1G # Fabric Properties # check https://fabricmc.net/develop/ - minecraft_version=23w17a + minecraft_version=23w18a loader_version=0.14.19 jsr305_version=3.0.2 - fabric_version=0.79.1+1.20 + fabric_version=0.80.1+1.20 # Mod Properties mod_version = 1.4.106 diff --git a/src/main/java/carpet/mixins/LayerLightEngine_scarpetChunkCreationMixin.java b/src/main/java/carpet/mixins/LayerLightEngine_scarpetChunkCreationMixin.java index 9093cc3f66..7b86b7b776 100644 --- a/src/main/java/carpet/mixins/LayerLightEngine_scarpetChunkCreationMixin.java +++ b/src/main/java/carpet/mixins/LayerLightEngine_scarpetChunkCreationMixin.java @@ -18,7 +18,7 @@ public abstract class LayerLightEngine_scarpetChunkCreationMixin implements Ligh @Final protected LayerLightSectionStorage storage; - @Shadow protected abstract void clearQueuedSectionBlocks(final long l); + //@Shadow protected abstract void clearQueuedSectionBlocks(final long l); @Override public void removeLightData(final long pos) @@ -40,6 +40,6 @@ public int callGetCurrentLevelFromSection(DataLayer array, long blockPos) { @Override public void clearQueuedSectionBlocksPublicAccess(long sectionPos) { - clearQueuedSectionBlocks(sectionPos); + //clearQueuedSectionBlocks(sectionPos); } } diff --git a/src/main/java/carpet/mixins/LayerLightSectionStorage_scarpetChunkCreationMixin.java b/src/main/java/carpet/mixins/LayerLightSectionStorage_scarpetChunkCreationMixin.java index cc65e2bb3f..72d793cd4e 100644 --- a/src/main/java/carpet/mixins/LayerLightSectionStorage_scarpetChunkCreationMixin.java +++ b/src/main/java/carpet/mixins/LayerLightSectionStorage_scarpetChunkCreationMixin.java @@ -82,7 +82,7 @@ private void processData(final LightEngine lightProvider, final CallbackIn if (this.storingLightForSection(sectionPos)) { - ((Lighting_scarpetChunkCreationInterface)lightProvider).clearQueuedSectionBlocksPublicAccess(sectionPos); + //((Lighting_scarpetChunkCreationInterface)lightProvider).clearQueuedSectionBlocksPublicAccess(sectionPos); if (this.changedSections.add(sectionPos)) this.updatingSectionData.copyDataLayer(sectionPos); diff --git a/src/main/java/carpet/mixins/ServerPlayerGameMode_scarpetEventsMixin.java b/src/main/java/carpet/mixins/ServerPlayerGameMode_scarpetEventsMixin.java index 91eb674f66..163d34cedb 100644 --- a/src/main/java/carpet/mixins/ServerPlayerGameMode_scarpetEventsMixin.java +++ b/src/main/java/carpet/mixins/ServerPlayerGameMode_scarpetEventsMixin.java @@ -54,7 +54,7 @@ private void onBlockBroken(BlockPos blockPos_1, CallbackInfoReturnable @Inject(method = "useItemOn", at = @At( value = "INVOKE", - target = "Lnet/minecraft/advancements/critereon/ItemInteractWithBlockTrigger;trigger(Lnet/minecraft/server/level/ServerPlayer;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/item/ItemStack;)V", + target = "Lnet/minecraft/advancements/critereon/ItemUsedOnLocationTrigger;trigger(Lnet/minecraft/server/level/ServerPlayer;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/item/ItemStack;)V", shift = At.Shift.BEFORE )) private void onBlockActivated(ServerPlayer serverPlayerEntity, Level world, ItemStack stack, InteractionHand hand, BlockHitResult hitResult, CallbackInfoReturnable cir) From a8ead7ff24752d50b4286f39291a9d84e4700500 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 3 May 2023 22:12:01 +0200 Subject: [PATCH 137/233] 1.4.107 --- .gitignore | 1 + gradle.properties | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 3e26bc92e8..db0d4ae688 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ .gradle/ build/ out/ +lout/ classes/ publish/ diff --git a/gradle.properties b/gradle.properties index cce20ec66c..5c1b923c59 100644 --- a/gradle.properties +++ b/gradle.properties @@ -9,7 +9,7 @@ org.gradle.jvmargs=-Xmx1G fabric_version=0.80.1+1.20 # Mod Properties - mod_version = 1.4.106 + mod_version = 1.4.107 maven_group = carpet archives_base_name = fabric-carpet From 5759e237944c518a80193f5920d2ab952657d00b Mon Sep 17 00:00:00 2001 From: altrisi Date: Mon, 1 May 2023 14:46:49 +0200 Subject: [PATCH 138/233] Fix integers operation results being downcasted to floating point Co-authored-by: manyrandomthings <42223559+manyrandomthings@users.noreply.github.com> --- src/main/java/carpet/script/language/Sys.java | 2 +- src/main/java/carpet/script/value/NumericValue.java | 11 +++++------ 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/src/main/java/carpet/script/language/Sys.java b/src/main/java/carpet/script/language/Sys.java index 01f455288d..31d13c7d5a 100644 --- a/src/main/java/carpet/script/language/Sys.java +++ b/src/main/java/carpet/script/language/Sys.java @@ -55,7 +55,7 @@ public static void apply(Expression expression) { if (v instanceof final NumericValue num) { - return new NumericValue(num.isInteger() ? num.getLong() : num.getDouble()); + return num.clone(); } if (v instanceof ListValue || v instanceof MapValue) { diff --git a/src/main/java/carpet/script/value/NumericValue.java b/src/main/java/carpet/script/value/NumericValue.java index 3cbd99a85c..7b15e09bf3 100644 --- a/src/main/java/carpet/script/value/NumericValue.java +++ b/src/main/java/carpet/script/value/NumericValue.java @@ -131,7 +131,7 @@ public Value add(Value v) { // TODO test if definintn add(NumericVlaue) woud solve the casting if (v instanceof final NumericValue nv) { - return new NumericValue(longValue != null && nv.longValue != null ? (longValue + nv.longValue) : (value + nv.value)); + return longValue != null && nv.longValue != null ? new NumericValue(longValue + nv.longValue) : new NumericValue(value + nv.value); } return super.add(v); } @@ -141,7 +141,7 @@ public Value subtract(Value v) { // TODO test if definintn add(NumericVlaue) woud solve the casting if (v instanceof final NumericValue nv) { - return new NumericValue(longValue != null && nv.longValue != null ? (longValue - nv.longValue) : (value - nv.value)); + return longValue != null && nv.longValue != null ? new NumericValue(longValue - nv.longValue) : new NumericValue(value - nv.value); } return super.subtract(v); } @@ -151,7 +151,7 @@ public Value multiply(Value v) { if (v instanceof final NumericValue nv) { - return new NumericValue(longValue != null && nv.longValue != null ? (longValue * nv.longValue) : (value * nv.value)); + return longValue != null && nv.longValue != null ? new NumericValue(longValue * nv.longValue) : new NumericValue(value * nv.value); } return v instanceof ListValue ? v.multiply(this) : new StringValue(StringUtils.repeat(v.getString(), (int) getLong())); } @@ -303,13 +303,12 @@ public JsonElement toJson() { return new JsonPrimitive(longValue); } - long lv = getLong(); - return new JsonPrimitive(value == lv ? getLong() : value); + return isInteger() ? new JsonPrimitive(getLong()) : new JsonPrimitive(getDouble()); } public NumericValue opposite() { - return new NumericValue(longValue != null ? -longValue : -value); + return longValue != null ? new NumericValue(-longValue) : new NumericValue(-value); } public boolean isInteger() From 240c8a8fc552314ce62fa8aec6f3f96226992749 Mon Sep 17 00:00:00 2001 From: altrisi Date: Sun, 7 May 2023 21:54:56 +0200 Subject: [PATCH 139/233] Fix ci badge --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b60fd0aad0..23da28c1e4 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ # Fabric Carpet -[![Development Builds](https://github.com/gnembon/fabric-carpet/workflows/Development%20Builds/badge.svg)](https://github.com/gnembon/fabric-carpet/actions?query=workflow%3A%22Development+Builds%22) +[![Development Builds](https://github.com/gnembon/fabric-carpet/actions/workflows/devbuild.yml/badge.svg)](https://github.com/gnembon/fabric-carpet/actions/workflows/devbuild.yml) [![CurseForge downloads](http://cf.way2muchnoise.eu/full_349239_downloads.svg)](https://www.curseforge.com/minecraft/mc-mods/carpet) [![Modrinth downloads](https://img.shields.io/modrinth/dt/carpet?label=Modrinth%20downloads&logo=data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbDpzcGFjZT0icHJlc2VydmUiIGZpbGwtcnVsZT0iZXZlbm9kZCIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIgc3Ryb2tlLW1pdGVybGltaXQ9IjEuNSIgY2xpcC1ydWxlPSJldmVub2RkIiB2aWV3Qm94PSIwIDAgMTAwIDEwMCI+PHBhdGggZmlsbD0ibm9uZSIgZD0iTTAgMGgxMDB2MTAwSDB6Ii8+PGNsaXBQYXRoIGlkPSJhIj48cGF0aCBkPSJNMTAwIDBIMHYxMDBoMTAwVjBaTTQ2LjAwMiA0OS4yOTVsLjA3NiAxLjc1NyA4LjgzIDMyLjk2MyA3Ljg0My0yLjEwMi04LjU5Ni0zMi4wOTQgNS44MDQtMzIuOTMyLTcuOTk3LTEuNDEtNS45NiAzMy44MThaIi8+PC9jbGlwUGF0aD48ZyBjbGlwLXBhdGg9InVybCgjYSkiPjxwYXRoIGZpbGw9IiMwMGQ4NDUiIGQ9Ik01MCAxN2MxOC4yMDcgMCAzMi45ODggMTQuNzg3IDMyLjk4OCAzM1M2OC4yMDcgODMgNTAgODMgMTcuMDEyIDY4LjIxMyAxNy4wMTIgNTAgMzEuNzkzIDE3IDUwIDE3Wm0wIDljMTMuMjQgMCAyMy45ODggMTAuNzU1IDIzLjk4OCAyNFM2My4yNCA3NCA1MCA3NCAyNi4wMTIgNjMuMjQ1IDI2LjAxMiA1MCAzNi43NiAyNiA1MCAyNloiLz48L2c+PGNsaXBQYXRoIGlkPSJiIj48cGF0aCBkPSJNMCAwdjQ2aDUwbDEuMzY4LjI0MUw5OSA2My41NzhsLTIuNzM2IDcuNTE3TDQ5LjI5NSA1NEgwdjQ2aDEwMFYwSDBaIi8+PC9jbGlwUGF0aD48ZyBjbGlwLXBhdGg9InVybCgjYikiPjxwYXRoIGZpbGw9IiMwMGQ4NDUiIGQ9Ik01MCAwYzI3LjU5NiAwIDUwIDIyLjQwNCA1MCA1MHMtMjIuNDA0IDUwLTUwIDUwUzAgNzcuNTk2IDAgNTAgMjIuNDA0IDAgNTAgMFptMCA5YzIyLjYyOSAwIDQxIDE4LjM3MSA0MSA0MVM3Mi42MjkgOTEgNTAgOTEgOSA3Mi42MjkgOSA1MCAyNy4zNzEgOSA1MCA5WiIvPjwvZz48Y2xpcFBhdGggaWQ9ImMiPjxwYXRoIGQ9Ik01MCAwYzI3LjU5NiAwIDUwIDIyLjQwNCA1MCA1MHMtMjIuNDA0IDUwLTUwIDUwUzAgNzcuNTk2IDAgNTAgMjIuNDA0IDAgNTAgMFptMCAzOS41NDljNS43NjggMCAxMC40NTEgNC42ODMgMTAuNDUxIDEwLjQ1MSAwIDUuNzY4LTQuNjgzIDEwLjQ1MS0xMC40NTEgMTAuNDUxLTUuNzY4IDAtMTAuNDUxLTQuNjgzLTEwLjQ1MS0xMC40NTEgMC01Ljc2OCA0LjY4My0xMC40NTEgMTAuNDUxLTEwLjQ1MVoiLz48L2NsaXBQYXRoPjxnIGNsaXAtcGF0aD0idXJsKCNjKSI+PHBhdGggZmlsbD0ibm9uZSIgc3Ryb2tlPSIjMDBkODQ1IiBzdHJva2Utd2lkdGg9IjkiIGQ9Ik01MCA1MCA1LjE3MSA3NS44ODIiLz48L2c+PGNsaXBQYXRoIGlkPSJkIj48cGF0aCBkPSJNNTAgMGMyNy41OTYgMCA1MCAyMi40MDQgNTAgNTBzLTIyLjQwNCA1MC01MCA1MFMwIDc3LjU5NiAwIDUwIDIyLjQwNCAwIDUwIDBabTAgMjUuMzZjMTMuNTk5IDAgMjQuNjQgMTEuMDQxIDI0LjY0IDI0LjY0UzYzLjU5OSA3NC42NCA1MCA3NC42NCAyNS4zNiA2My41OTkgMjUuMzYgNTAgMzYuNDAxIDI1LjM2IDUwIDI1LjM2WiIvPjwvY2xpcFBhdGg+PGcgY2xpcC1wYXRoPSJ1cmwoI2QpIj48cGF0aCBmaWxsPSJub25lIiBzdHJva2U9IiMwMGQ4NDUiIHN0cm9rZS13aWR0aD0iOSIgZD0ibTUwIDUwIDUwLTEzLjM5NyIvPjwvZz48cGF0aCBmaWxsPSIjMDBkODQ1IiBkPSJNMzcuMjQzIDUyLjc0NiAzNSA0NWw4LTkgMTEtMyA0IDQtNiA2LTQgMS0zIDQgMS4xMiA0LjI0IDMuMTEyIDMuMDkgNC45NjQtLjU5OCAyLjg2Ni0yLjk2NCA4LjE5Ni0yLjE5NiAxLjQ2NCA1LjQ2NC04LjA5OCA4LjAyNkw0Ni44MyA2NS40OWwtNS41ODctNS44MTUtNC02LjkyOVoiLz48L3N2Zz4=)](https://modrinth.com/mod/carpet) [![GitHub downloads](https://img.shields.io/github/downloads/gnembon/fabric-carpet/total?label=Github%20downloads&logo=github)](https://github.com/gnembon/fabric-carpet/releases) From fa0200c1376cbed94b38bc9b5f41f5b815d7f0b5 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 10 May 2023 21:12:15 +0200 Subject: [PATCH 140/233] 1.20-pre1 --- gradle.properties | 4 ++-- src/main/java/carpet/helpers/OptimizedExplosion.java | 5 ++--- src/main/java/carpet/mixins/Level_movableBEMixin.java | 4 ++-- 3 files changed, 6 insertions(+), 7 deletions(-) diff --git a/gradle.properties b/gradle.properties index 5c1b923c59..70734ee29a 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,10 +3,10 @@ org.gradle.jvmargs=-Xmx1G # Fabric Properties # check https://fabricmc.net/develop/ - minecraft_version=23w18a + minecraft_version=1.20-pre1 loader_version=0.14.19 jsr305_version=3.0.2 - fabric_version=0.80.1+1.20 + fabric_version=0.80.2+1.20 # Mod Properties mod_version = 1.4.107 diff --git a/src/main/java/carpet/helpers/OptimizedExplosion.java b/src/main/java/carpet/helpers/OptimizedExplosion.java index 9345f7146d..aec3620c2d 100644 --- a/src/main/java/carpet/helpers/OptimizedExplosion.java +++ b/src/main/java/carpet/helpers/OptimizedExplosion.java @@ -29,7 +29,7 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.chunk.ChunkAccess; import net.minecraft.world.level.material.FluidState; -import net.minecraft.world.level.storage.loot.LootContext; +import net.minecraft.world.level.storage.loot.LootParams; import net.minecraft.world.level.storage.loot.parameters.LootContextParams; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.Vec3; @@ -246,8 +246,7 @@ public static void doExplosionB(Explosion e, boolean spawnParticles) { BlockEntity blockEntity = state.hasBlockEntity() ? world.getBlockEntity(blockpos) : null; //hasBlockEntity() - LootContext.Builder lootBuilder = (new LootContext.Builder((ServerLevel)eAccess.getLevel())) - .withRandom(eAccess.getLevel().random) + LootParams.Builder lootBuilder = (new LootParams.Builder((ServerLevel)eAccess.getLevel())) .withParameter(LootContextParams.ORIGIN, Vec3.atCenterOf(blockpos)) .withParameter(LootContextParams.TOOL, ItemStack.EMPTY) .withOptionalParameter(LootContextParams.BLOCK_ENTITY, blockEntity) diff --git a/src/main/java/carpet/mixins/Level_movableBEMixin.java b/src/main/java/carpet/mixins/Level_movableBEMixin.java index 151f215f39..24d97c96f9 100644 --- a/src/main/java/carpet/mixins/Level_movableBEMixin.java +++ b/src/main/java/carpet/mixins/Level_movableBEMixin.java @@ -3,7 +3,7 @@ import carpet.fakes.WorldChunkInterface; import carpet.fakes.LevelInterface; import net.minecraft.core.BlockPos; -import net.minecraft.server.level.ChunkHolder; +import net.minecraft.server.level.FullChunkStatus; import net.minecraft.util.profiling.ProfilerFiller; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; @@ -100,7 +100,7 @@ public boolean setBlockStateWithBlockEntity(BlockPos blockPos_1, BlockState bloc this.setBlocksDirty(blockPos_1, blockState_2, blockState_3); } - if ((int_1 & 2) != 0 && (!this.isClientSide || (int_1 & 4) == 0) && (this.isClientSide || worldChunk_1.getFullStatus() != null && worldChunk_1.getFullStatus().isOrAfter(ChunkHolder.FullChunkStatus.TICKING))) + if ((int_1 & 2) != 0 && (!this.isClientSide || (int_1 & 4) == 0) && (this.isClientSide || worldChunk_1.getFullStatus() != null && worldChunk_1.getFullStatus().isOrAfter(FullChunkStatus.BLOCK_TICKING))) { this.sendBlockUpdated(blockPos_1, blockState_2, blockState_1, int_1); } From 2cfedc733ea60695f6896b3a1497737054afe4c1 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 10 May 2023 21:12:57 +0200 Subject: [PATCH 141/233] 1.4.108 --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 70734ee29a..baed9206e8 100644 --- a/gradle.properties +++ b/gradle.properties @@ -9,7 +9,7 @@ org.gradle.jvmargs=-Xmx1G fabric_version=0.80.2+1.20 # Mod Properties - mod_version = 1.4.107 + mod_version = 1.4.108 maven_group = carpet archives_base_name = fabric-carpet From 755ec1daa8ae76ceee3bcd547bda3622bd04566d Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Fri, 12 May 2023 22:04:19 +0200 Subject: [PATCH 142/233] relight cleanup - think it works now. Little higher level, but that's what's needed. --- .../fakes/ChunkLightProviderInterface.java | 8 -- .../carpet/fakes/LightStorageInterface.java | 12 -- ...ighting_scarpetChunkCreationInterface.java | 4 - ...tionStorage_scarpetChunkCreationMixin.java | 72 ---------- .../ChunkMap_scarpetChunkCreationMixin.java | 63 +++++---- ...LightEngine_scarpetChunkCreationMixin.java | 24 +--- ...tionStorage_scarpetChunkCreationMixin.java | 84 ++---------- ...LightEngine_scarpetChunkCreationMixin.java | 10 -- ...tionStorage_scarpetChunkCreationMixin.java | 127 ------------------ ...LightEngine_scarpetChunkCreationMixin.java | 32 ++++- src/main/resources/carpet.mixins.json | 2 - 11 files changed, 74 insertions(+), 364 deletions(-) delete mode 100644 src/main/java/carpet/fakes/ChunkLightProviderInterface.java delete mode 100644 src/main/java/carpet/fakes/LightStorageInterface.java delete mode 100644 src/main/java/carpet/mixins/BlockLightSectionStorage_scarpetChunkCreationMixin.java delete mode 100644 src/main/java/carpet/mixins/SkyLightSectionStorage_scarpetChunkCreationMixin.java diff --git a/src/main/java/carpet/fakes/ChunkLightProviderInterface.java b/src/main/java/carpet/fakes/ChunkLightProviderInterface.java deleted file mode 100644 index 6da216c49c..0000000000 --- a/src/main/java/carpet/fakes/ChunkLightProviderInterface.java +++ /dev/null @@ -1,8 +0,0 @@ -package carpet.fakes; - -import net.minecraft.world.level.chunk.DataLayer; - -public interface ChunkLightProviderInterface -{ - int callGetCurrentLevelFromSection(DataLayer array, long blockPos); -} diff --git a/src/main/java/carpet/fakes/LightStorageInterface.java b/src/main/java/carpet/fakes/LightStorageInterface.java deleted file mode 100644 index 9c91f2afc8..0000000000 --- a/src/main/java/carpet/fakes/LightStorageInterface.java +++ /dev/null @@ -1,12 +0,0 @@ -package carpet.fakes; - -import net.minecraft.world.level.lighting.LightEngine; - -public interface LightStorageInterface extends Lighting_scarpetChunkCreationInterface -{ - void processRemoveLightData(long pos); - - void processRelight(LightEngine lightProvider, long pos); - - int getLightLevelByLong(long blockPos); -} diff --git a/src/main/java/carpet/fakes/Lighting_scarpetChunkCreationInterface.java b/src/main/java/carpet/fakes/Lighting_scarpetChunkCreationInterface.java index 8dc0ab68e9..7cfdb5fde5 100644 --- a/src/main/java/carpet/fakes/Lighting_scarpetChunkCreationInterface.java +++ b/src/main/java/carpet/fakes/Lighting_scarpetChunkCreationInterface.java @@ -3,8 +3,4 @@ public interface Lighting_scarpetChunkCreationInterface { void removeLightData(long pos); - - void relight(long pos); - - default void clearQueuedSectionBlocksPublicAccess(long sectionPos) {}; } diff --git a/src/main/java/carpet/mixins/BlockLightSectionStorage_scarpetChunkCreationMixin.java b/src/main/java/carpet/mixins/BlockLightSectionStorage_scarpetChunkCreationMixin.java deleted file mode 100644 index 5111b614f5..0000000000 --- a/src/main/java/carpet/mixins/BlockLightSectionStorage_scarpetChunkCreationMixin.java +++ /dev/null @@ -1,72 +0,0 @@ -package carpet.mixins; - -import org.spongepowered.asm.mixin.Mixin; - -import carpet.fakes.ChunkLightProviderInterface; -import carpet.fakes.LightStorageInterface; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.core.SectionPos; -import net.minecraft.world.level.LightLayer; -import net.minecraft.world.level.chunk.DataLayer; -import net.minecraft.world.level.chunk.LightChunkGetter; -import net.minecraft.world.level.lighting.BlockLightSectionStorage; -import net.minecraft.world.level.lighting.BlockLightSectionStorage.BlockDataLayerStorageMap; -import net.minecraft.world.level.lighting.LightEngine; -import net.minecraft.world.level.lighting.LayerLightSectionStorage; - -@Mixin(BlockLightSectionStorage.class) -public abstract class BlockLightSectionStorage_scarpetChunkCreationMixin extends LayerLightSectionStorage implements LightStorageInterface -{ - private BlockLightSectionStorage_scarpetChunkCreationMixin(final LightLayer lightType, final LightChunkGetter chunkProvider, final BlockDataLayerStorageMap lightData) - { - super(lightType, chunkProvider, lightData); - } - - @Override - public void processRelight(final LightEngine lightProvider, final long cPos) - { - //final DynamicGraphMinFixedPoint_resetChunkInterface levelPropagator = (DynamicGraphMinFixedPoint_resetChunkInterface) lightProvider.; - - for (int y = -1; y < 17; ++y) - { - final long sectionPos = SectionPos.asLong(SectionPos.x(cPos), y, SectionPos.z(cPos)); - final long pos = BlockPos.asLong(SectionPos.sectionToBlockCoord(SectionPos.x(sectionPos)), SectionPos.sectionToBlockCoord(y), SectionPos.sectionToBlockCoord(SectionPos.z(sectionPos))); - - if (!this.storingLightForSection(sectionPos)) - continue; - - for (final Direction dir : Direction.Plane.HORIZONTAL) - { - final DataLayer neighborLightArray = this.getDataLayerData(SectionPos.offset(sectionPos, dir)); - - if (neighborLightArray == null) - continue; - - final int ox = 15 * Math.max(dir.getStepX(), 0); - final int oz = 15 * Math.max(dir.getStepZ(), 0); - - final int dx = Math.abs(dir.getStepZ()); - final int dz = Math.abs(dir.getStepX()); - - for (int t = 0; t < 16; ++t) - for (int dy = 0; dy < 16; ++dy) - { - final long dst = BlockPos.offset(pos, ox + t * dx, dy, oz + t * dz); - lightProvider.checkBlock(BlockPos.of(dst)); - //final long src = BlockPos.offset(dst, dir); - - //final int srcLevel = ((ChunkLightProviderInterface) lightProvider).callGetCurrentLevelFromSection(neighborLightArray, src); - - //levelPropagator.cmInvokeUpdateLevel(src, dst, levelPropagator.cmCallGetPropagatedLevel(src, dst, srcLevel), true); - } - } - } - } - - @Override - public int getLightLevelByLong(long blockPos) - { - return getLightValue(blockPos); - } -} diff --git a/src/main/java/carpet/mixins/ChunkMap_scarpetChunkCreationMixin.java b/src/main/java/carpet/mixins/ChunkMap_scarpetChunkCreationMixin.java index 5087666d98..8345096652 100644 --- a/src/main/java/carpet/mixins/ChunkMap_scarpetChunkCreationMixin.java +++ b/src/main/java/carpet/mixins/ChunkMap_scarpetChunkCreationMixin.java @@ -398,34 +398,8 @@ public Map regenerateChunkRegion(final List requested this.modified = true; this.promoteChunkMap(); - // Remove light for affected neighbors - - for (final ChunkAccess chunk : affectedNeighbors) - ((ServerLightingProviderInterface) this.lightEngine).removeLightData(chunk); - - // Schedule relighting of neighbors - - for (final ChunkAccess chunk : affectedNeighbors) - this.addRelightTicket(chunk.getPos()); - - this.tickTicketManager(); - final List> lightFutures = new ArrayList<>(); - - for (final ChunkAccess chunk : affectedNeighbors) - { - final ChunkPos pos = chunk.getPos(); - lightFutures.add(this.getChunkRangeFuture (this.updatingChunkMap.get(pos.toLong()), 1, (pos_) -> ChunkStatus.LIGHT).thenCompose( - either -> either.map( - list -> ((ServerLightingProviderInterface) this.lightEngine).relight(chunk), - unloaded -> { - this.releaseRelightTicket(pos); - return CompletableFuture.completedFuture(null); - } - ) - )); - } // Force generation to previous states // This ensures that the world is in a consistent state after this method @@ -473,7 +447,42 @@ public Map regenerateChunkRegion(final List requested report.put("layer_time_" + status.getName(), (int) (System.currentTimeMillis() - start)); } - report.put("relight_count", lightFutures.size()); + + + + + report.put("relight_count", affectedNeighbors.size()); + + // Remove light for affected neighbors + + for (final ChunkAccess chunk : affectedNeighbors) + ((ServerLightingProviderInterface) this.lightEngine).removeLightData(chunk); + + // Schedule relighting of neighbors + + for (final ChunkAccess chunk : affectedNeighbors) + this.addRelightTicket(chunk.getPos()); + + this.tickTicketManager(); + + final List> lightFutures = new ArrayList<>(); + + for (final ChunkAccess chunk : affectedNeighbors) + { + final ChunkPos pos = chunk.getPos(); + + lightFutures.add(this.getChunkRangeFuture (this.updatingChunkMap.get(pos.toLong()), 1, (pos_) -> ChunkStatus.LIGHT).thenCompose( + either -> either.map( + list -> ((ServerLightingProviderInterface) this.lightEngine).relight(chunk), + unloaded -> { + this.releaseRelightTicket(pos); + return CompletableFuture.completedFuture(null); + } + ) + )); + } + + final long relightStart = System.currentTimeMillis(); this.waitFor(lightFutures); diff --git a/src/main/java/carpet/mixins/LayerLightEngine_scarpetChunkCreationMixin.java b/src/main/java/carpet/mixins/LayerLightEngine_scarpetChunkCreationMixin.java index 7b86b7b776..a4e7c6a7b3 100644 --- a/src/main/java/carpet/mixins/LayerLightEngine_scarpetChunkCreationMixin.java +++ b/src/main/java/carpet/mixins/LayerLightEngine_scarpetChunkCreationMixin.java @@ -1,45 +1,23 @@ package carpet.mixins; -import carpet.fakes.LightStorageInterface; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; -import carpet.fakes.ChunkLightProviderInterface; import carpet.fakes.Lighting_scarpetChunkCreationInterface; -import net.minecraft.world.level.chunk.DataLayer; import net.minecraft.world.level.lighting.LightEngine; import net.minecraft.world.level.lighting.LayerLightSectionStorage; @Mixin(LightEngine.class) -public abstract class LayerLightEngine_scarpetChunkCreationMixin implements Lighting_scarpetChunkCreationInterface, ChunkLightProviderInterface +public abstract class LayerLightEngine_scarpetChunkCreationMixin implements Lighting_scarpetChunkCreationInterface { @Shadow @Final protected LayerLightSectionStorage storage; - //@Shadow protected abstract void clearQueuedSectionBlocks(final long l); - @Override public void removeLightData(final long pos) { ((Lighting_scarpetChunkCreationInterface) this.storage).removeLightData(pos); } - - @Override - public void relight(final long pos) - { - ((Lighting_scarpetChunkCreationInterface) this.storage).relight(pos); - } - - @Override - public int callGetCurrentLevelFromSection(DataLayer array, long blockPos) { - return ((LightStorageInterface)storage).getLightLevelByLong(blockPos); - }; - - @Override - public void clearQueuedSectionBlocksPublicAccess(long sectionPos) - { - //clearQueuedSectionBlocks(sectionPos); - } } diff --git a/src/main/java/carpet/mixins/LayerLightSectionStorage_scarpetChunkCreationMixin.java b/src/main/java/carpet/mixins/LayerLightSectionStorage_scarpetChunkCreationMixin.java index 72d793cd4e..7f41c737cd 100644 --- a/src/main/java/carpet/mixins/LayerLightSectionStorage_scarpetChunkCreationMixin.java +++ b/src/main/java/carpet/mixins/LayerLightSectionStorage_scarpetChunkCreationMixin.java @@ -6,29 +6,19 @@ import net.minecraft.core.SectionPos; import net.minecraft.world.level.chunk.DataLayer; import net.minecraft.world.level.lighting.DataLayerStorageMap; -import net.minecraft.world.level.lighting.LightEngine; import net.minecraft.world.level.lighting.LayerLightSectionStorage; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.Unique; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import carpet.fakes.LightStorageInterface; import it.unimi.dsi.fastutil.longs.Long2ObjectMap; -import it.unimi.dsi.fastutil.longs.LongOpenHashSet; import it.unimi.dsi.fastutil.longs.LongSet; @Mixin(LayerLightSectionStorage.class) -public abstract class LayerLightSectionStorage_scarpetChunkCreationMixin implements LightStorageInterface +public abstract class LayerLightSectionStorage_scarpetChunkCreationMixin implements Lighting_scarpetChunkCreationInterface { @Shadow - protected abstract DataLayer getDataLayer(final long sectionPos, final boolean cached); - - //@Shadow - //protected abstract void clearQueuedSectionBlocks(final LightEngine storage, final long blockChunkPos); + protected abstract DataLayer getDataLayer(long sectionPos, boolean cached); @Shadow @Final @@ -38,79 +28,29 @@ public abstract class LayerLightSectionStorage_scarpetChunkCreationMixin impleme @Final protected DataLayerStorageMap updatingSectionData; - @Shadow protected abstract boolean storingLightForSection(final long sectionPos); + @Shadow protected abstract boolean storingLightForSection(long sectionPos); @Shadow @Final protected Long2ObjectMap queuedSections; - //@Shadow protected abstract void enableLightSources(final long l, final boolean bl); - - @Unique - private final LongSet removedChunks = new LongOpenHashSet(); - - @Unique - private final LongSet relightChunks = new LongOpenHashSet(); - - @Override - public void removeLightData(final long pos) - { - this.removedChunks.add(pos); - } - @Override - public void relight(final long pos) - { - this.relightChunks.add(pos); - } - - @Inject( - method = "markNewInconsistencies", - at = @At("HEAD") - ) - private void processData(final LightEngine lightProvider, final CallbackInfo ci) + public void removeLightData(long cPos) { - // Process light removal - for (final long cPos : this.removedChunks) + for (int y = -1; y < 17; ++y) { - for (int y = -1; y < 17; ++y) - { - final long sectionPos = SectionPos.asLong(SectionPos.x(cPos), y, SectionPos.z(cPos)); - - this.queuedSections.remove(sectionPos); + long sectionPos = SectionPos.asLong(SectionPos.x(cPos), y, SectionPos.z(cPos)); - if (this.storingLightForSection(sectionPos)) - { - //((Lighting_scarpetChunkCreationInterface)lightProvider).clearQueuedSectionBlocksPublicAccess(sectionPos); + this.queuedSections.remove(sectionPos); - if (this.changedSections.add(sectionPos)) - this.updatingSectionData.copyDataLayer(sectionPos); + if (this.storingLightForSection(sectionPos)) + { + if (this.changedSections.add(sectionPos)) + this.updatingSectionData.copyDataLayer(sectionPos); - Arrays.fill(this.getDataLayer(sectionPos, true).getData(), (byte) 0); - } + Arrays.fill(this.getDataLayer(sectionPos, true).getData(), (byte) 0); } - - this.processRemoveLightData(cPos); } - - this.removedChunks.clear(); - - // Process relighting - - for (final long cPos : this.relightChunks) - this.processRelight(lightProvider, cPos); - - this.relightChunks.clear(); - } - - @Override - public void processRemoveLightData(final long pos) - { - } - - @Override - public void processRelight(final LightEngine lightProvider, final long pos) - { } } diff --git a/src/main/java/carpet/mixins/LevelLightEngine_scarpetChunkCreationMixin.java b/src/main/java/carpet/mixins/LevelLightEngine_scarpetChunkCreationMixin.java index cfcbd2bad7..55bb324cc4 100644 --- a/src/main/java/carpet/mixins/LevelLightEngine_scarpetChunkCreationMixin.java +++ b/src/main/java/carpet/mixins/LevelLightEngine_scarpetChunkCreationMixin.java @@ -28,14 +28,4 @@ public void removeLightData(final long pos) if (this.skyEngine != null) ((Lighting_scarpetChunkCreationInterface) this.skyEngine).removeLightData(pos); } - - @Override - public void relight(final long pos) - { - if (this.blockEngine != null) - ((Lighting_scarpetChunkCreationInterface) this.blockEngine).relight(pos); - - if (this.skyEngine != null) - ((Lighting_scarpetChunkCreationInterface) this.skyEngine).relight(pos); - } } diff --git a/src/main/java/carpet/mixins/SkyLightSectionStorage_scarpetChunkCreationMixin.java b/src/main/java/carpet/mixins/SkyLightSectionStorage_scarpetChunkCreationMixin.java deleted file mode 100644 index 579a1cd402..0000000000 --- a/src/main/java/carpet/mixins/SkyLightSectionStorage_scarpetChunkCreationMixin.java +++ /dev/null @@ -1,127 +0,0 @@ -package carpet.mixins; - -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; - -import carpet.fakes.ChunkLightProviderInterface; -import carpet.fakes.LightStorageInterface; -import it.unimi.dsi.fastutil.longs.LongSet; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.core.SectionPos; -import net.minecraft.world.level.LightLayer; -import net.minecraft.world.level.chunk.DataLayer; -import net.minecraft.world.level.chunk.LightChunkGetter; -import net.minecraft.world.level.lighting.BlockLightSectionStorage.BlockDataLayerStorageMap; -import net.minecraft.world.level.lighting.LightEngine; -import net.minecraft.world.level.lighting.LayerLightSectionStorage; -import net.minecraft.world.level.lighting.SkyLightSectionStorage; - -@Mixin(SkyLightSectionStorage.class) -public abstract class SkyLightSectionStorage_scarpetChunkCreationMixin extends LayerLightSectionStorage implements LightStorageInterface -{ - protected SkyLightSectionStorage_scarpetChunkCreationMixin(final LightLayer lightType, final LightChunkGetter chunkProvider, final BlockDataLayerStorageMap lightData) - { - super(lightType, chunkProvider, lightData); - } - - /*@Shadow - @Final - private LongSet sectionsToAddSourcesTo; - - @Shadow - @Final - private LongSet sectionsToRemoveSourcesFrom; - - @Shadow - @Final - private LongSet sectionsWithSources; - */ - - @Shadow protected abstract boolean isAboveData(final long pos); - - //@Shadow protected abstract boolean lightOnInSection(final long sectionPos); - - @Override - public void processRemoveLightData(final long cPos) - { - for (int y = -1; y < 17; ++y) - { - final long sectionPos = SectionPos.asLong(SectionPos.x(cPos), y, SectionPos.z(cPos)); -/* do something with this later - this.sectionsToAddSourcesTo.remove(sectionPos); - this.sectionsToRemoveSourcesFrom.remove(sectionPos); - - this.sectionsWithSources.remove(sectionPos); - - */ - } - } - - @Override - public void processRelight(final LightEngine lightProvider, final long cPos) - { - //final DynamicGraphMinFixedPoint_resetChunkInterface levelPropagator = (DynamicGraphMinFixedPoint_resetChunkInterface) lightProvider; - - for (int y = -1; y < 17; ++y) - { - final long sectionPos = SectionPos.asLong(SectionPos.x(cPos), y, SectionPos.z(cPos)); - final long pos = BlockPos.asLong(SectionPos.sectionToBlockCoord(SectionPos.x(sectionPos)), SectionPos.sectionToBlockCoord(y), SectionPos.sectionToBlockCoord(SectionPos.z(sectionPos))); - - if (!this.storingLightForSection(sectionPos)) - continue; - - for (final Direction dir : Direction.Plane.HORIZONTAL) - { - long neighborCeilingSectionPos = SectionPos.offset(sectionPos, dir); - final DataLayer neighborLightArray = this.getDataLayerData(neighborCeilingSectionPos); - - DataLayer neighborCeilingLightArray = neighborLightArray; - - while (neighborCeilingLightArray == null && !this.isAboveData(neighborCeilingSectionPos)) - { - neighborCeilingSectionPos = SectionPos.offset(neighborCeilingSectionPos, Direction.UP); - neighborCeilingLightArray = this.getDataLayerData(neighborCeilingSectionPos); - } - - final int ox = 15 * Math.max(dir.getStepX(), 0); - final int oz = 15 * Math.max(dir.getStepZ(), 0); - - final int dx = Math.abs(dir.getStepZ()); - final int dz = Math.abs(dir.getStepX()); - - int emptyLightLevel = (neighborCeilingLightArray == null) - ? (this.lightOnInSection(SectionPos.getZeroNode(neighborCeilingSectionPos)) ? 0 : 15) - : 0; - int neighbourY = (neighborLightArray == null) - ? SectionPos.sectionToBlockCoord(SectionPos.y(neighborCeilingSectionPos)) - : 0; - - for (int t = 0; t < 16; ++t) - for (int dy = 0; dy < 16; ++dy) - { - final long dst = BlockPos.offset(pos, ox + t * dx, dy, oz + t * dz); - //long src = BlockPos.offset(dst, dir); - - //long adj_src = (neighborLightArray != null) - // ? src - // : BlockPos.asLong(BlockPos.getX(src), neighbourY, BlockPos.getZ(src)); - - //final int srcLevel = neighborCeilingLightArray != null - // ? ((ChunkLightProviderInterface) lightProvider).callGetCurrentLevelFromSection(neighborCeilingLightArray, adj_src) - // : emptyLightLevel; - - lightProvider.checkBlock(BlockPos.of(dst)); - //levelPropagator.cmInvokeUpdateLevel(src, dst, levelPropagator.cmCallGetPropagatedLevel(src, dst, srcLevel), true); - } - } - } - } - - @Override - public int getLightLevelByLong(long blockPos) - { - return getLightValue(blockPos); - } -} diff --git a/src/main/java/carpet/mixins/ThreadedLevelLightEngine_scarpetChunkCreationMixin.java b/src/main/java/carpet/mixins/ThreadedLevelLightEngine_scarpetChunkCreationMixin.java index 71eeec3c84..964fa8edac 100644 --- a/src/main/java/carpet/mixins/ThreadedLevelLightEngine_scarpetChunkCreationMixin.java +++ b/src/main/java/carpet/mixins/ThreadedLevelLightEngine_scarpetChunkCreationMixin.java @@ -3,6 +3,7 @@ import java.util.concurrent.CompletableFuture; import java.util.function.IntSupplier; import net.minecraft.Util; +import net.minecraft.core.BlockPos; import net.minecraft.core.SectionPos; import net.minecraft.server.level.ChunkMap; import net.minecraft.server.level.ThreadedLevelLightEngine; @@ -42,7 +43,7 @@ private ThreadedLevelLightEngine_scarpetChunkCreationMixin(final LightChunkGette @Override public void removeLightData(final ChunkAccess chunk) { - final ChunkPos pos = chunk.getPos(); + ChunkPos pos = chunk.getPos(); chunk.setLightCorrect(false); this.addTask(pos.x, pos.z, () -> 0, ThreadedLevelLightEngine.TaskType.PRE_UPDATE, Util.name(() -> { @@ -54,15 +55,32 @@ public void removeLightData(final ChunkAccess chunk) } @Override - public CompletableFuture relight(final ChunkAccess chunk) + public CompletableFuture relight(ChunkAccess chunk) { - final ChunkPos pos = chunk.getPos(); + ChunkPos pos = chunk.getPos(); - propagateLightSources(pos); this.addTask(pos.x, pos.z, () -> 0, ThreadedLevelLightEngine.TaskType.PRE_UPDATE, Util.name(() -> { - - - ((Lighting_scarpetChunkCreationInterface) this).relight(SectionPos.getZeroNode(SectionPos.asLong(pos.x, 0, pos.z))); + super.propagateLightSources(pos); + int minY = chunk.getMinBuildHeight(); + int maxY = chunk.getMaxBuildHeight(); + int minX = pos.getMinBlockX(); + int minZ = pos.getMinBlockZ(); + BlockPos.MutableBlockPos poss = new BlockPos.MutableBlockPos(); + for (int x = -1; x < 17; ++x) + { + for (int z = -1; z < 17; ++z) + { + if (x > 0 && x < 16 && z > 0 && z < 16) + {// not really efficient way to do it, but hey, we have bigger problems with this + continue; + } + for (int y = minY; y < maxY; ++y) + { + poss.set(x + minX, y, z + minZ); + super.checkBlock(poss); + } + } + } }, () -> "Relight chunk " + pos )); diff --git a/src/main/resources/carpet.mixins.json b/src/main/resources/carpet.mixins.json index 537aed2a01..82bc4b9348 100644 --- a/src/main/resources/carpet.mixins.json +++ b/src/main/resources/carpet.mixins.json @@ -48,8 +48,6 @@ "LevelLightEngine_scarpetChunkCreationMixin", "LayerLightEngine_scarpetChunkCreationMixin", "LayerLightSectionStorage_scarpetChunkCreationMixin", - "BlockLightSectionStorage_scarpetChunkCreationMixin", - "SkyLightSectionStorage_scarpetChunkCreationMixin", "DistanceManager_spawnChunksMixin", "ServerLevel_spawnChunksMixin", "ThreadedLevelLightEngine_scarpetChunkCreationMixin", From e0a3060339ba53ecbacdc41e6fc49b2d57a46d9e Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Sun, 14 May 2023 23:36:55 +0200 Subject: [PATCH 143/233] tickspeed server - client separation. --- .../java/carpet/commands/TickCommand.java | 10 +- .../fakes/MinecraftServerInterface.java | 3 + .../java/carpet/helpers/TickRateManager.java | 305 ++++++++++++++++++ src/main/java/carpet/helpers/TickSpeed.java | 282 ++++++---------- .../java/carpet/logging/HUDController.java | 7 +- .../BoundTickingBlockEntity_tickMixin.java | 2 +- .../mixins/DistanceManager_tickMixin.java | 2 +- .../LevelRenderer_pausedShakeMixin.java | 2 +- .../java/carpet/mixins/Level_tickMixin.java | 14 +- .../java/carpet/mixins/MinecraftMixin.java | 12 +- .../mixins/MinecraftServer_scarpetMixin.java | 2 +- .../MinecraftServer_tickspeedMixin.java | 39 ++- .../carpet/mixins/PlayerTabOverlayMixin.java | 1 + .../mixins/ServerChunkCache_tickMixin.java | 2 +- .../ServerFunctionManager_tickMixin.java | 2 +- .../carpet/mixins/ServerLevel_tickMixin.java | 12 +- .../carpet/mixins/Timer_tickSpeedMixin.java | 4 +- .../carpet/network/ClientNetworkHandler.java | 8 +- .../carpet/network/ServerNetworkHandler.java | 23 +- .../patches/TickSyncedBorderExtent.java | 4 +- .../java/carpet/script/external/Carpet.java | 2 +- 21 files changed, 503 insertions(+), 235 deletions(-) create mode 100644 src/main/java/carpet/helpers/TickRateManager.java diff --git a/src/main/java/carpet/commands/TickCommand.java b/src/main/java/carpet/commands/TickCommand.java index 191672168b..491b6c6a28 100644 --- a/src/main/java/carpet/commands/TickCommand.java +++ b/src/main/java/carpet/commands/TickCommand.java @@ -79,8 +79,8 @@ private static int setTps(CommandSourceStack source, float tps) private static int queryTps(CommandSourceStack source) { - Messenger.m(source, "w Current tps is: ",String.format("wb %.1f", TickSpeed.tickrate)); - return (int)TickSpeed.tickrate; + Messenger.m(source, "w Current tps is: ",String.format("wb %.1f", TickSpeed.gTRM().map(trm -> trm.tickrate).orElse(20.0f))); + return (int)(float)TickSpeed.gTRM().map(trm -> trm.tickrate).orElse(20.0f); } private static int setWarp(CommandSourceStack source, int advance, String tail_command) @@ -132,9 +132,9 @@ private static int step(CommandSourceStack source, int advance) private static int toggleSuperHot(CommandSourceStack source) { - TickSpeed.is_superHot = !TickSpeed.is_superHot; - ServerNetworkHandler.updateSuperHotStateToConnectedPlayers(); - if (TickSpeed.is_superHot) + TickSpeed.gTRM().ifPresent(trm -> trm.is_superHot = !trm.is_superHot); + ServerNetworkHandler.updateSuperHotStateToConnectedPlayers(source.getServer()); + if (TickSpeed.gTRM().map(trm -> trm.is_superHot).orElse(false)) { Messenger.m(source, "gi Superhot enabled"); } diff --git a/src/main/java/carpet/fakes/MinecraftServerInterface.java b/src/main/java/carpet/fakes/MinecraftServerInterface.java index 8b0454361c..ce2466d1b8 100644 --- a/src/main/java/carpet/fakes/MinecraftServerInterface.java +++ b/src/main/java/carpet/fakes/MinecraftServerInterface.java @@ -3,6 +3,7 @@ import java.util.Map; import java.util.function.BooleanSupplier; +import carpet.helpers.TickRateManager; import carpet.script.CarpetScriptServer; import net.minecraft.core.RegistryAccess; import net.minecraft.resources.ResourceKey; @@ -23,4 +24,6 @@ public interface MinecraftServerInterface void addScriptServer(CarpetScriptServer scriptServer); CarpetScriptServer getScriptServer(); + + TickRateManager getTickRateManager(); } diff --git a/src/main/java/carpet/helpers/TickRateManager.java b/src/main/java/carpet/helpers/TickRateManager.java new file mode 100644 index 0000000000..2666f35106 --- /dev/null +++ b/src/main/java/carpet/helpers/TickRateManager.java @@ -0,0 +1,305 @@ +package carpet.helpers; + +import carpet.CarpetServer; +import carpet.network.ServerNetworkHandler; +import carpet.utils.Messenger; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.Commands; +import net.minecraft.network.chat.Component; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerPlayer; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.BiConsumer; + +public class TickRateManager +{ + public static final int PLAYER_GRACE = 2; + public float tickrate = 20.0f; + public float mspt = 50.0f; + public long time_bias = 0; + public long time_warp_start_time = 0; + public long time_warp_scheduled_ticks = 0; + public ServerPlayer time_advancerer = null; + public String tick_warp_callback = null; + public CommandSourceStack tick_warp_sender = null; + public int player_active_timeout = 0; + public boolean process_entities = true; + private boolean deepFreeze = false; + private boolean is_paused = false; + public boolean is_superHot = false; + + private MinecraftServer server; + + public TickRateManager(MinecraftServer server) { + this.server = server; + } + + + /** + * @return Whether or not the game is in a frozen state. + * You should normally use {@link #process_entities} instead, + * since that one accounts for tick steps and superhot + */ + public boolean isPaused() + { + return is_paused; + } + + /** + * Whether or not the game is deeply frozen. + * This can be used for things that you may not normally want + * to freeze, but may need to in some situations. + * This should be checked with {@link #process_entities} to make sure the + * current tick is actually frozen, not only the game + * + * @return Whether or not the game is deeply frozen. + */ + public boolean deeplyFrozen() + { + return deepFreeze; + } + + /** + * Used to update the frozen state of the game. + * Handles connected clients as well. + * + * @param isPaused Whether or not the game is paused + * @param isDeepFreeze Whether or not the game is deeply frozen + */ + public void setFrozenState(boolean isPaused, boolean isDeepFreeze) + { + is_paused = isPaused; + deepFreeze = isPaused ? isDeepFreeze : false; + ServerNetworkHandler.updateFrozenStateToConnectedPlayers(server); + } + + + public void reset_player_active_timeout() + { + if (player_active_timeout < PLAYER_GRACE) + { + player_active_timeout = PLAYER_GRACE; + ServerNetworkHandler.updateTickPlayerActiveTimeoutToConnectedPlayers(server); + } + } + + public void reset() // do we need reset? + { + tickrate = 20.0f; + mspt = 50.0f; + time_bias = 0; + time_warp_start_time = 0; + time_warp_scheduled_ticks = 0; + time_advancerer = null; + tick_warp_callback = null; + tick_warp_sender = null; + player_active_timeout = 0; + process_entities = true; + deepFreeze = false; + is_paused = false; + is_superHot = false; + notifyTickrateListeners("carpet"); + } + + public void add_ticks_to_run_in_pause(int ticks) + { + player_active_timeout = PLAYER_GRACE + ticks; + ServerNetworkHandler.updateTickPlayerActiveTimeoutToConnectedPlayers(server); + } + + public Component tickrate_advance(ServerPlayer player, int advance, String callback, CommandSourceStack source) + { + if (0 == advance) + { + tick_warp_callback = null; + if (source != tick_warp_sender) + { + tick_warp_sender = null; + } + if (time_bias > 0) + { + finish_time_warp(); + tick_warp_sender = null; + return Messenger.c("gi Warp interrupted"); + } + return Messenger.c("ri No warp in progress"); + } + if (time_bias > 0) + { + String who = "Another player"; + if (time_advancerer != null) + { + who = time_advancerer.getScoreboardName(); + } + return Messenger.c("l " + who + " is already advancing time at the moment. Try later or ask them"); + } + time_advancerer = player; + time_warp_start_time = System.nanoTime(); + time_warp_scheduled_ticks = advance; + time_bias = advance; + tick_warp_callback = callback; + tick_warp_sender = source; + return Messenger.c("gi Warp speed ...."); + } + + public void finish_time_warp() + { + + long completed_ticks = time_warp_scheduled_ticks - time_bias; + double milis_to_complete = System.nanoTime() - time_warp_start_time; + if (milis_to_complete == 0.0) + { + milis_to_complete = 1.0; + } + milis_to_complete /= 1000000.0; + int tps = (int) (1000.0D * completed_ticks / milis_to_complete); + double mspt = (1.0 * milis_to_complete) / completed_ticks; + time_warp_scheduled_ticks = 0; + time_warp_start_time = 0; + if (tick_warp_callback != null) + { + Commands icommandmanager = tick_warp_sender.getServer().getCommands(); + try + { + icommandmanager.performPrefixedCommand(tick_warp_sender, tick_warp_callback); + } + catch (Throwable var23) + { + if (time_advancerer != null) + { + Messenger.m(time_advancerer, "r Command Callback failed - unknown error: ", "rb /" + tick_warp_callback, "/" + tick_warp_callback); + } + } + tick_warp_callback = null; + tick_warp_sender = null; + } + if (time_advancerer != null) + { + Messenger.m(time_advancerer, String.format("gi ... Time warp completed with %d tps, or %.2f mspt", tps, mspt)); + time_advancerer = null; + } + else + { + Messenger.print_server_message(CarpetServer.minecraft_server, String.format("... Time warp completed with %d tps, or %.2f mspt", tps, mspt)); + } + time_bias = 0; + + } + + public boolean continueWarp() + { + if (!process_entities) + // Returning false so we don't have to run at max speed when doing nothing + { + return false; + } + if (time_bias > 0) + { + if (time_bias == time_warp_scheduled_ticks) //first call after previous tick, adjust start time + { + time_warp_start_time = System.nanoTime(); + } + time_bias -= 1; + return true; + } + else + { + finish_time_warp(); + return false; + } + } + + public void tick() + { + if (player_active_timeout > 0) + { + player_active_timeout--; + } + if (is_paused) + { + process_entities = player_active_timeout >= PLAYER_GRACE; + } + else if (is_superHot) + { + process_entities = player_active_timeout > 0; + } + else + { + process_entities = true; + } + } + + /** + * Functional interface that listens for tickrate changes. This is + * implemented to allow tickrate compatibility with other mods etc. + */ + private final Map> tickrateListeners = new HashMap<>(); + private static final float MIN_TICKRATE = 0.01f; + + //unused - mod compat reasons + public void tickrate(float rate) + { + tickrate(rate, true); + } + + public void tickrate(float rate, boolean update) + { + tickrate = rate; + long msptt = (long) (1000.0 / tickrate); + if (msptt <= 0L) + { + msptt = 1L; + tickrate = 1000.0f; + } + + this.mspt = msptt; + + if (update) + { + notifyTickrateListeners("carpet"); + } + } + + private void tickrateChanged(String modId, float rate) + { + // Other mods might change the tickrate in a slightly + // different way. Also allow for tickrates that don't + // divide into 1000 here. + + if (rate < MIN_TICKRATE) + { + rate = MIN_TICKRATE; + } + + tickrate = rate; + mspt = 1000.0f / tickrate; + + notifyTickrateListeners(modId); + } + + private void notifyTickrateListeners(String originModId) + { + synchronized (tickrateListeners) + { + for (Map.Entry> listenerEntry : tickrateListeners.entrySet()) + { + if (originModId == null || !originModId.equals(listenerEntry.getKey())) + { + listenerEntry.getValue().accept(originModId, Float.valueOf(tickrate)); + } + } + } + ServerNetworkHandler.updateTickSpeedToConnectedPlayers(server); + } + + public BiConsumer addTickrateListener(String modId, BiConsumer tickrateListener) + { + synchronized (tickrateListeners) + { + tickrateListeners.put(modId, tickrateListener); + } + return this::tickrateChanged; + } +} diff --git a/src/main/java/carpet/helpers/TickSpeed.java b/src/main/java/carpet/helpers/TickSpeed.java index 04bf36ff0c..6392b8a506 100644 --- a/src/main/java/carpet/helpers/TickSpeed.java +++ b/src/main/java/carpet/helpers/TickSpeed.java @@ -2,7 +2,10 @@ import java.util.HashMap; import java.util.Map; +import java.util.Optional; import java.util.function.BiConsumer; + +import carpet.fakes.MinecraftServerInterface; import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.Commands; import net.minecraft.network.chat.Component; @@ -13,40 +16,38 @@ public class TickSpeed { - public static final int PLAYER_GRACE = 2; - public static float tickrate = 20.0f; - public static float mspt = 50.0f; - public static long time_bias = 0; - public static long time_warp_start_time = 0; - public static long time_warp_scheduled_ticks = 0; - public static ServerPlayer time_advancerer = null; - public static String tick_warp_callback = null; - public static CommandSourceStack tick_warp_sender = null; - public static int player_active_timeout = 0; - public static boolean process_entities = true; - private static boolean deepFreeze = false; - private static boolean is_paused = false; - public static boolean is_superHot = false; + public static Optional gTRM() { + if (CarpetServer.minecraft_server == null) return Optional.empty(); + return Optional.of(((MinecraftServerInterface)CarpetServer.minecraft_server).getTickRateManager()); + } + + public static boolean process_entities() { + return gTRM().map(trm -> trm.process_entities).orElse(true); + } + + public static float mspt() { + return gTRM().map(trm -> trm.mspt).orElse(50.0f); + } /** * @return Whether or not the game is in a frozen state. - * You should normally use {@link #process_entities} instead, + * You should normally use {@link #process_entities()} instead, * since that one accounts for tick steps and superhot */ public static boolean isPaused() { - return is_paused; + return gTRM().map(TickRateManager::isPaused).orElse(false); } /** * Whether or not the game is deeply frozen. * This can be used for things that you may not normally want * to freeze, but may need to in some situations. - * This should be checked with {@link #process_entities} to make sure the + * This should be checked with {@link #process_entities()} to make sure the * current tick is actually frozen, not only the game * @return Whether or not the game is deeply frozen. */ public static boolean deeplyFrozen() { - return deepFreeze; + return gTRM().map(TickRateManager::deeplyFrozen).orElse(false); } /** @@ -56,9 +57,7 @@ public static boolean deeplyFrozen() { * @param isDeepFreeze Whether or not the game is deeply frozen */ public static void setFrozenState(boolean isPaused, boolean isDeepFreeze) { - is_paused = isPaused; - deepFreeze = isPaused ? isDeepFreeze : false; - ServerNetworkHandler.updateFrozenStateToConnectedPlayers(); + gTRM().ifPresent(trm -> trm.setFrozenState(isPaused, isDeepFreeze)); } /** @@ -70,206 +69,129 @@ public static void setFrozenState(boolean isPaused, boolean isDeepFreeze) { public static void reset_player_active_timeout() { - if (player_active_timeout < PLAYER_GRACE) - { - player_active_timeout = PLAYER_GRACE; - ServerNetworkHandler.updateTickPlayerActiveTimeoutToConnectedPlayers(); - } + gTRM().ifPresent(TickRateManager::reset_player_active_timeout); } public static void reset() { - tickrate = 20.0f; - mspt = 50.0f; - time_bias = 0; - time_warp_start_time = 0; - time_warp_scheduled_ticks = 0; - time_advancerer = null; - tick_warp_callback = null; - tick_warp_sender = null; - player_active_timeout = 0; - process_entities = true; - deepFreeze = false; - is_paused = false; - is_superHot = false; - notifyTickrateListeners("carpet"); + gTRM().ifPresent(TickRateManager::reset); } public static void add_ticks_to_run_in_pause(int ticks) { - player_active_timeout = PLAYER_GRACE+ticks; - ServerNetworkHandler.updateTickPlayerActiveTimeoutToConnectedPlayers(); + gTRM().ifPresent(trm -> trm.add_ticks_to_run_in_pause(ticks)); } public static Component tickrate_advance(ServerPlayer player, int advance, String callback, CommandSourceStack source) { - if (0 == advance) - { - tick_warp_callback = null; - if (source != tick_warp_sender) tick_warp_sender = null; - if (time_bias > 0) - { - finish_time_warp(); - tick_warp_sender = null; - return Messenger.c("gi Warp interrupted"); - } - return Messenger.c("ri No warp in progress"); - } - if (time_bias > 0) - { - String who = "Another player"; - if (time_advancerer != null) who = time_advancerer.getScoreboardName(); - return Messenger.c("l "+who+" is already advancing time at the moment. Try later or ask them"); - } - time_advancerer = player; - time_warp_start_time = System.nanoTime(); - time_warp_scheduled_ticks = advance; - time_bias = advance; - tick_warp_callback = callback; - tick_warp_sender = source; - return Messenger.c("gi Warp speed ...."); + return gTRM().map(trm -> trm.tickrate_advance(player, advance, callback, source)).orElse(Messenger.c("ri Tickrate management not enabled")); } public static void finish_time_warp() { - - long completed_ticks = time_warp_scheduled_ticks - time_bias; - double milis_to_complete = System.nanoTime()-time_warp_start_time; - if (milis_to_complete == 0.0) - { - milis_to_complete = 1.0; - } - milis_to_complete /= 1000000.0; - int tps = (int) (1000.0D*completed_ticks/milis_to_complete); - double mspt = (1.0*milis_to_complete)/completed_ticks; - time_warp_scheduled_ticks = 0; - time_warp_start_time = 0; - if (tick_warp_callback != null) - { - Commands icommandmanager = tick_warp_sender.getServer().getCommands(); - try - { - icommandmanager.performPrefixedCommand(tick_warp_sender, tick_warp_callback); - } - catch (Throwable var23) - { - if (time_advancerer != null) - { - Messenger.m(time_advancerer, "r Command Callback failed - unknown error: ", "rb /"+tick_warp_callback,"/"+tick_warp_callback); - } - } - tick_warp_callback = null; - tick_warp_sender = null; - } - if (time_advancerer != null) - { - Messenger.m(time_advancerer, String.format("gi ... Time warp completed with %d tps, or %.2f mspt",tps, mspt )); - time_advancerer = null; - } - else - { - Messenger.print_server_message(CarpetServer.minecraft_server, String.format("... Time warp completed with %d tps, or %.2f mspt",tps, mspt )); - } - time_bias = 0; - + gTRM().ifPresent(TickRateManager::finish_time_warp); } public static boolean continueWarp() { - if (!process_entities) - // Returning false so we don't have to run at max speed when doing nothing - return false; - if (time_bias > 0) - { - if (time_bias == time_warp_scheduled_ticks) //first call after previous tick, adjust start time - { - time_warp_start_time = System.nanoTime(); - } - time_bias -= 1; - return true; - } - else - { - finish_time_warp(); - return false; - } + return gTRM().map(TickRateManager::continueWarp).orElse(false); } public static void tick() { - if (player_active_timeout > 0) - { - player_active_timeout--; - } - if (is_paused) - { - process_entities = player_active_timeout >= PLAYER_GRACE; - } - else if (is_superHot) - { - process_entities = player_active_timeout > 0; - } - else - { - process_entities = true; - } + gTRM().ifPresent(TickRateManager::tick); } //unused - mod compat reasons public static void tickrate(float rate) {tickrate(rate, true);} public static void tickrate(float rate, boolean update) + { + gTRM().ifPresent(trm -> trm.tickrate(rate, update)); + } + + + + + public static BiConsumer addTickrateListener(String modId, BiConsumer tickrateListener) + { + return gTRM().map(trm -> trm.addTickrateListener(modId, tickrateListener)).orElse(null); + } + + + + + // client only + + private static float tickrate = 20.0f; + private static float mspt = 50.0f; + private static int player_active_timeout = 0; + private static boolean process_entities = true; + private static boolean deepFreeze = false; + private static boolean is_paused = false; + private static boolean is_superHot = false; + + public static void tickrateClient(float rate) { tickrate = rate; - long mspt = (long)(1000.0 / tickrate); - if (mspt <= 0L) + long msptt = (long) (1000.0 / tickrate); + if (msptt <= 0L) { - mspt = 1L; + msptt = 1L; tickrate = 1000.0f; } - - TickSpeed.mspt = mspt; - - if (update) notifyTickrateListeners("carpet"); + + mspt = msptt; } - - private static void tickrateChanged(String modId, float rate) + + public static float msptClient() { + return mspt; + } + + public static boolean process_entitiesClient() { - // Other mods might change the tickrate in a slightly - // different way. Also allow for tickrates that don't - // divide into 1000 here. - - if (rate < MIN_TICKRATE) - { - rate = MIN_TICKRATE; - } - - tickrate = rate; - mspt = 1000.0f / tickrate; - - notifyTickrateListeners(modId); + return process_entities; } - - private static void notifyTickrateListeners(String originModId) + + public static boolean isIs_superHotClient() { - synchronized (tickrateListeners) - { - for (Map.Entry> listenerEntry : tickrateListeners.entrySet()) - { - if (originModId == null || !originModId.equals(listenerEntry.getKey())) - { - listenerEntry.getValue().accept(originModId, Float.valueOf(tickrate)); - } - } - } - ServerNetworkHandler.updateTickSpeedToConnectedPlayers(); + return is_superHot; } - - public static BiConsumer addTickrateListener(String modId, BiConsumer tickrateListener) + + public static void setPlayer_active_timeoutClient(int timeout) { - synchronized (tickrateListeners) + player_active_timeout = timeout; + } + + + public static void setFrozenStateClient(boolean isPaused, boolean isDeepFreeze) + { + is_paused = isPaused; + deepFreeze = isPaused ? isDeepFreeze : false; + } + + public static void setSuperHotClient(boolean isSuperHot) + { + is_superHot = isSuperHot; + } + + public static void tickClient() + { + if (player_active_timeout > 0) { - tickrateListeners.put(modId, tickrateListener); + player_active_timeout--; + } + if (is_paused) + { + process_entities = player_active_timeout >= TickRateManager.PLAYER_GRACE; + } + else if (is_superHot) + { + process_entities = player_active_timeout > 0; + } + else + { + process_entities = true; } - return TickSpeed::tickrateChanged; } + } diff --git a/src/main/java/carpet/logging/HUDController.java b/src/main/java/carpet/logging/HUDController.java index 31e3735d42..1a6bf09f58 100644 --- a/src/main/java/carpet/logging/HUDController.java +++ b/src/main/java/carpet/logging/HUDController.java @@ -1,7 +1,9 @@ package carpet.logging; import carpet.CarpetServer; +import carpet.fakes.MinecraftServerInterface; import carpet.helpers.HopperCounter; +import carpet.helpers.TickRateManager; import carpet.helpers.TickSpeed; import carpet.logging.logHelpers.PacketCounter; import carpet.utils.Messenger; @@ -117,16 +119,17 @@ public static void update_hud(MinecraftServer server, List force) private static Component [] send_tps_display(MinecraftServer server) { final OptionalDouble averageTPS = Arrays.stream(server.tickTimes).average(); + TickRateManager trm = ((MinecraftServerInterface)server).getTickRateManager(); if (averageTPS.isEmpty()) { return new Component[]{Component.literal("No TPS data available")}; } double MSPT = Arrays.stream(server.tickTimes).average().getAsDouble() * 1.0E-6D; - double TPS = 1000.0D / Math.max((TickSpeed.time_warp_start_time != 0)?0.0:TickSpeed.mspt, MSPT); + double TPS = 1000.0D / Math.max((trm.time_warp_start_time != 0)?0.0:trm.mspt, MSPT); if (TickSpeed.isPaused()) { TPS = 0; } - String color = Messenger.heatmap_color(MSPT,TickSpeed.mspt); + String color = Messenger.heatmap_color(MSPT,trm.mspt); return new Component[]{Messenger.c( "g TPS: ", String.format(Locale.US, "%s %.1f",color, TPS), "g MSPT: ", String.format(Locale.US,"%s %.1f", color, MSPT))}; diff --git a/src/main/java/carpet/mixins/BoundTickingBlockEntity_tickMixin.java b/src/main/java/carpet/mixins/BoundTickingBlockEntity_tickMixin.java index 7e0383d2a8..834c4c3e63 100644 --- a/src/main/java/carpet/mixins/BoundTickingBlockEntity_tickMixin.java +++ b/src/main/java/carpet/mixins/BoundTickingBlockEntity_tickMixin.java @@ -34,7 +34,7 @@ private void startTileEntitySection(CallbackInfo ci) )) private void checkProcessBEs(BlockEntityTicker blockEntityTicker, Level world, BlockPos pos, BlockState state, T blockEntity) { - if (TickSpeed.process_entities) blockEntityTicker.tick(world, pos, state, blockEntity); + if (TickSpeed.process_entities()) blockEntityTicker.tick(world, pos, state, blockEntity); } @Inject(method = "tick()V", at = @At("RETURN")) diff --git a/src/main/java/carpet/mixins/DistanceManager_tickMixin.java b/src/main/java/carpet/mixins/DistanceManager_tickMixin.java index ff5ca448bc..19fc1ec3ec 100644 --- a/src/main/java/carpet/mixins/DistanceManager_tickMixin.java +++ b/src/main/java/carpet/mixins/DistanceManager_tickMixin.java @@ -18,6 +18,6 @@ private void pauseTicketSystem(CallbackInfo ci) { // pausing expiry of tickets // that will prevent also chunks from unloading, so require a deep frozen state - if (!TickSpeed.process_entities && TickSpeed.deeplyFrozen()) ticketTickCounter--; + if (!TickSpeed.process_entities() && TickSpeed.deeplyFrozen()) ticketTickCounter--; } } diff --git a/src/main/java/carpet/mixins/LevelRenderer_pausedShakeMixin.java b/src/main/java/carpet/mixins/LevelRenderer_pausedShakeMixin.java index 40eb19333b..44b99aaacc 100644 --- a/src/main/java/carpet/mixins/LevelRenderer_pausedShakeMixin.java +++ b/src/main/java/carpet/mixins/LevelRenderer_pausedShakeMixin.java @@ -25,7 +25,7 @@ public class LevelRenderer_pausedShakeMixin private float changeTickPhase(float previous) { initial = previous; - if (!TickSpeed.process_entities) + if (!TickSpeed.process_entitiesClient()) return ((MinecraftClientInferface)minecraft).getPausedTickDelta(); return previous; } diff --git a/src/main/java/carpet/mixins/Level_tickMixin.java b/src/main/java/carpet/mixins/Level_tickMixin.java index cde0cdc192..18e4447b6b 100644 --- a/src/main/java/carpet/mixins/Level_tickMixin.java +++ b/src/main/java/carpet/mixins/Level_tickMixin.java @@ -86,8 +86,18 @@ private void endTileEntitySection(CallbackInfo ci) @Inject(method = "guardEntityTick", at = @At("HEAD"), cancellable = true) private void startEntity(Consumer consumer_1, Entity e, CallbackInfo ci) { - if (!(TickSpeed.process_entities || (e instanceof Player) || (TickSpeed.is_superHot && isClientSide && e.getControllingPassenger() instanceof Player))) - ci.cancel(); + // this shows that probably tick speed controller needs to be accessible through level referring to servers on server and client on clientLevel + if (isClientSide) { + if (!(TickSpeed.process_entitiesClient() || (e instanceof Player) || TickSpeed.isIs_superHotClient() && e.getControllingPassenger() instanceof Player)) + { + ci.cancel(); + } + } else { + if (!(TickSpeed.gTRM().map(trm -> trm.process_entities).orElse(true) || (e instanceof Player))) + { + ci.cancel(); + } + } entitySection = CarpetProfiler.start_entity_section((Level) (Object) this, e, CarpetProfiler.TYPE.ENTITY); } diff --git a/src/main/java/carpet/mixins/MinecraftMixin.java b/src/main/java/carpet/mixins/MinecraftMixin.java index 03c086e70c..6a871aea52 100644 --- a/src/main/java/carpet/mixins/MinecraftMixin.java +++ b/src/main/java/carpet/mixins/MinecraftMixin.java @@ -26,9 +26,15 @@ private void onCloseGame(Screen screen, CallbackInfo ci) @Inject(at = @At("HEAD"), method = "tick") private void onClientTick(CallbackInfo info) { if (this.level != null) { - if (CarpetServer.minecraft_server == null) - TickSpeed.tick(); - if (!TickSpeed.process_entities) + TickSpeed.tickClient(); + if (CarpetServer.minecraft_server == null) // remote client only ? no - now any client + { + + } else { + // hmm, server should tick, rgiht? + //TickSpeed.tick(); + } + if (!TickSpeed.process_entitiesClient()) CarpetClient.shapes.renewShapes(); } } diff --git a/src/main/java/carpet/mixins/MinecraftServer_scarpetMixin.java b/src/main/java/carpet/mixins/MinecraftServer_scarpetMixin.java index 27591cbb45..baaae69253 100644 --- a/src/main/java/carpet/mixins/MinecraftServer_scarpetMixin.java +++ b/src/main/java/carpet/mixins/MinecraftServer_scarpetMixin.java @@ -89,7 +89,7 @@ public Map, ServerLevel> getCMWorlds() )) public void tickTasks(BooleanSupplier booleanSupplier_1, CallbackInfo ci) { - if (!TickSpeed.process_entities) + if (!TickSpeed.process_entities()) return; TICK.onTick((MinecraftServer) (Object) this); NETHER_TICK.onTick((MinecraftServer) (Object) this); diff --git a/src/main/java/carpet/mixins/MinecraftServer_tickspeedMixin.java b/src/main/java/carpet/mixins/MinecraftServer_tickspeedMixin.java index aaae5b0f40..7ae968b373 100644 --- a/src/main/java/carpet/mixins/MinecraftServer_tickspeedMixin.java +++ b/src/main/java/carpet/mixins/MinecraftServer_tickspeedMixin.java @@ -1,5 +1,7 @@ package carpet.mixins; +import carpet.fakes.MinecraftServerInterface; +import carpet.helpers.TickRateManager; import carpet.helpers.TickSpeed; import carpet.patches.CopyProfilerResult; import carpet.utils.CarpetProfiler; @@ -25,7 +27,7 @@ import java.util.function.BooleanSupplier; @Mixin(value = MinecraftServer.class, priority = Integer.MAX_VALUE - 10) -public abstract class MinecraftServer_tickspeedMixin extends ReentrantBlockableEventLoop +public abstract class MinecraftServer_tickspeedMixin extends ReentrantBlockableEventLoop implements MinecraftServerInterface { @Shadow private volatile boolean running; @@ -67,6 +69,20 @@ public MinecraftServer_tickspeedMixin(String name) private float carpetMsptAccum = 0.0f; + private TickRateManager tickRateManager; + + @Inject(method = "", at = @At("RETURN")) + private void onInit(CallbackInfo ci) + { + tickRateManager = new TickRateManager((MinecraftServer)(Object)this); + } + + @Override + public TickRateManager getTickRateManager() + { + return tickRateManager; + } + /** * To ensure compatibility with other mods we should allow milliseconds */ @@ -95,32 +111,33 @@ private void modifiedRunLoop(CallbackInfo ci) } long msThisTick = 0L; long long_1 = 0L; - if (TickSpeed.time_warp_start_time != 0 && TickSpeed.continueWarp()) + float mspt = tickRateManager.mspt; + if (tickRateManager.time_warp_start_time != 0 && TickSpeed.continueWarp()) { //making sure server won't flop after the warp or if the warp is interrupted this.nextTickTime = this.lastOverloadWarning = Util.getMillis(); - carpetMsptAccum = TickSpeed.mspt; + carpetMsptAccum = mspt; } else { - if (Math.abs(carpetMsptAccum - TickSpeed.mspt) > 1.0f) + if (Math.abs(carpetMsptAccum - mspt) > 1.0f) { // Tickrate changed. Ensure that we use the correct value. - carpetMsptAccum = TickSpeed.mspt; + carpetMsptAccum = mspt; } msThisTick = (long)carpetMsptAccum; // regular tick - carpetMsptAccum += TickSpeed.mspt - msThisTick; + carpetMsptAccum += mspt - msThisTick; long_1 = Util.getMillis() - this.nextTickTime; } //end tick deciding //smoothed out delay to include mcpt component. With 50L gives defaults. - if (long_1 > /*2000L*/1000L+20*TickSpeed.mspt && this.nextTickTime - this.lastOverloadWarning >= /*15000L*/10000L+100*TickSpeed.mspt) + if (long_1 > /*2000L*/1000L+20*mspt && this.nextTickTime - this.lastOverloadWarning >= /*15000L*/10000L+100*mspt) { - long long_2 = (long)(long_1 / TickSpeed.mspt);//50L; + long long_2 = (long)(long_1 / mspt);//50L; LOGGER.warn("Can't keep up! Is the server overloaded? Running {}ms or {} ticks behind", long_1, long_2); - this.nextTickTime += (long)(long_2 * TickSpeed.mspt);//50L; + this.nextTickTime += (long)(long_2 * mspt);//50L; this.lastOverloadWarning = this.nextTickTime; } @@ -134,9 +151,9 @@ private void modifiedRunLoop(CallbackInfo ci) //this.startMonitor(tickDurationMonitor); this.startMetricsRecordingTick(); this.profiler.push("tick"); - this.tickServer(TickSpeed.time_warp_start_time != 0 ? ()->true : this::haveTime); + this.tickServer(TickSpeed.gTRM().map(trm -> trm.time_warp_start_time).orElse(0L) != 0 ? ()->true : this::haveTime); this.profiler.popPush("nextTickWait"); - if (TickSpeed.time_warp_start_time != 0) // clearing all hanging tasks no matter what when warping + if (TickSpeed.gTRM().map(trm -> trm.time_warp_start_time).orElse(0L) != 0) // clearing all hanging tasks no matter what when warping { while(this.runEveryTask()) {Thread.yield();} } diff --git a/src/main/java/carpet/mixins/PlayerTabOverlayMixin.java b/src/main/java/carpet/mixins/PlayerTabOverlayMixin.java index a8fa51db8d..7fe502033a 100644 --- a/src/main/java/carpet/mixins/PlayerTabOverlayMixin.java +++ b/src/main/java/carpet/mixins/PlayerTabOverlayMixin.java @@ -12,6 +12,7 @@ public abstract class PlayerTabOverlayMixin implements PlayerListHudInterface @Shadow private Component header; + @Override public boolean hasFooterOrHeader() { return footer != null || header != null; diff --git a/src/main/java/carpet/mixins/ServerChunkCache_tickMixin.java b/src/main/java/carpet/mixins/ServerChunkCache_tickMixin.java index b82bf3dd31..dfbe7e6664 100644 --- a/src/main/java/carpet/mixins/ServerChunkCache_tickMixin.java +++ b/src/main/java/carpet/mixins/ServerChunkCache_tickMixin.java @@ -78,7 +78,7 @@ private void stopSpawningSection(CallbackInfo ci) private boolean skipChunkTicking(ServerLevel serverWorld) { boolean debug = serverWorld.isDebug(); - if (!TickSpeed.process_entities) + if (!TickSpeed.process_entities()) { // simplified chunk tick iteration assuming world is frozen otherwise as suggested by Hadron67 // to be kept in sync with the original injection source diff --git a/src/main/java/carpet/mixins/ServerFunctionManager_tickMixin.java b/src/main/java/carpet/mixins/ServerFunctionManager_tickMixin.java index a1b4611277..b4aab97496 100644 --- a/src/main/java/carpet/mixins/ServerFunctionManager_tickMixin.java +++ b/src/main/java/carpet/mixins/ServerFunctionManager_tickMixin.java @@ -16,7 +16,7 @@ public class ServerFunctionManager_tickMixin @Inject(method = "tick", at = @At("HEAD"), cancellable = true) private void beforeDatapacks(CallbackInfo ci) { - if (!TickSpeed.process_entities) ci.cancel(); + if (!TickSpeed.process_entities()) ci.cancel(); else currentSection = CarpetProfiler.start_section(null, "Datapacks", CarpetProfiler.TYPE.GENERAL); } diff --git a/src/main/java/carpet/mixins/ServerLevel_tickMixin.java b/src/main/java/carpet/mixins/ServerLevel_tickMixin.java index fd6a874827..23a60e5cb8 100644 --- a/src/main/java/carpet/mixins/ServerLevel_tickMixin.java +++ b/src/main/java/carpet/mixins/ServerLevel_tickMixin.java @@ -159,13 +159,13 @@ private void endRandomTicks(CallbackInfo ci) { )) private void tickWorldBorder(WorldBorder worldBorder) { - if (TickSpeed.process_entities) worldBorder.tick(); + if (TickSpeed.process_entities()) worldBorder.tick(); } @Inject(method = "advanceWeatherCycle", cancellable = true, at = @At("HEAD")) private void tickWeather(CallbackInfo ci) { - if (!TickSpeed.process_entities) ci.cancel(); + if (!TickSpeed.process_entities()) ci.cancel(); } @Redirect(method = "tick", at = @At( @@ -174,7 +174,7 @@ private void tickWeather(CallbackInfo ci) )) private void tickTimeConditionally(ServerLevel serverWorld) { - if (TickSpeed.process_entities) tickTime(); + if (TickSpeed.process_entities()) tickTime(); } @Redirect(method = "tick", at = @At( @@ -183,7 +183,7 @@ private void tickTimeConditionally(ServerLevel serverWorld) )) private boolean tickPendingBlocks(ServerLevel serverWorld) { - if (!TickSpeed.process_entities) return true; + if (!TickSpeed.process_entities()) return true; return serverWorld.isDebug(); // isDebug() } @@ -193,7 +193,7 @@ private boolean tickPendingBlocks(ServerLevel serverWorld) )) private void tickConditionally(Raids raidManager) { - if (TickSpeed.process_entities) raidManager.tick(); + if (TickSpeed.process_entities()) raidManager.tick(); } @Redirect(method = "tick", at = @At( @@ -202,6 +202,6 @@ private void tickConditionally(Raids raidManager) )) private void tickConditionally(ServerLevel serverWorld) { - if (TickSpeed.process_entities) runBlockEvents(); + if (TickSpeed.process_entities()) runBlockEvents(); } } diff --git a/src/main/java/carpet/mixins/Timer_tickSpeedMixin.java b/src/main/java/carpet/mixins/Timer_tickSpeedMixin.java index 57994cac7b..c8e4f1fe75 100644 --- a/src/main/java/carpet/mixins/Timer_tickSpeedMixin.java +++ b/src/main/java/carpet/mixins/Timer_tickSpeedMixin.java @@ -14,9 +14,9 @@ public class Timer_tickSpeedMixin { target = "Lnet/minecraft/client/Timer;msPerTick:F" )) private float adjustTickSpeed(Timer counter) { - if (CarpetSettings.smoothClientAnimations && TickSpeed.process_entities) + if (CarpetSettings.smoothClientAnimations && TickSpeed.process_entitiesClient()) { - return Math.max(50.0f, TickSpeed.mspt); + return Math.max(50.0f, TickSpeed.msptClient()); } return 50f; } diff --git a/src/main/java/carpet/network/ClientNetworkHandler.java b/src/main/java/carpet/network/ClientNetworkHandler.java index 698d8cff51..292774022a 100644 --- a/src/main/java/carpet/network/ClientNetworkHandler.java +++ b/src/main/java/carpet/network/ClientNetworkHandler.java @@ -65,15 +65,15 @@ public class ClientNetworkHandler } } }); - dataHandlers.put("TickRate", (p, t) -> TickSpeed.tickrate(((NumericTag)t).getAsFloat(), false)); + dataHandlers.put("TickRate", (p, t) -> TickSpeed.tickrateClient(((NumericTag)t).getAsFloat())); dataHandlers.put("TickingState", (p, t) -> { CompoundTag tickingState = (CompoundTag)t; - TickSpeed.setFrozenState(tickingState.getBoolean("is_paused"), tickingState.getBoolean("deepFreeze")); + TickSpeed.setFrozenStateClient(tickingState.getBoolean("is_paused"), tickingState.getBoolean("deepFreeze")); }); dataHandlers.put("SuperHotState", (p, t) -> { - TickSpeed.is_superHot = ((ByteTag) t).equals(ByteTag.ONE); + TickSpeed.setSuperHotClient(((ByteTag) t).equals(ByteTag.ONE)); }); - dataHandlers.put("TickPlayerActiveTimeout", (p, t) -> TickSpeed.player_active_timeout = ((NumericTag)t).getAsInt()); + dataHandlers.put("TickPlayerActiveTimeout", (p, t) -> TickSpeed.setPlayer_active_timeoutClient(((NumericTag)t).getAsInt())); dataHandlers.put("scShape", (p, t) -> { // deprecated // and unused // should remove for 1.17 if (CarpetClient.shapes != null) CarpetClient.shapes.addShape((CompoundTag)t); diff --git a/src/main/java/carpet/network/ServerNetworkHandler.java b/src/main/java/carpet/network/ServerNetworkHandler.java index 7d0fd0f65a..7a80ae6031 100644 --- a/src/main/java/carpet/network/ServerNetworkHandler.java +++ b/src/main/java/carpet/network/ServerNetworkHandler.java @@ -23,6 +23,7 @@ import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.chat.Component; import net.minecraft.network.protocol.game.ClientboundCustomPayloadPacket; +import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerPlayer; public class ServerNetworkHandler @@ -144,10 +145,10 @@ public static void updateRuleWithConnectedClients(CarpetRule rule) } } - public static void updateTickSpeedToConnectedPlayers() + public static void updateTickSpeedToConnectedPlayers(MinecraftServer server) { if (CarpetSettings.superSecretSetting) return; - for (ServerPlayer player : remoteCarpetPlayers.keySet()) + for (ServerPlayer player : validCarpetPlayers) { player.connection.send(new ClientboundCustomPayloadPacket( CarpetClient.CARPET_CHANNEL, @@ -156,10 +157,10 @@ public static void updateTickSpeedToConnectedPlayers() } } - public static void updateFrozenStateToConnectedPlayers() + public static void updateFrozenStateToConnectedPlayers(MinecraftServer server) { if (CarpetSettings.superSecretSetting) return; - for (ServerPlayer player : remoteCarpetPlayers.keySet()) + for (ServerPlayer player : validCarpetPlayers) { player.connection.send(new ClientboundCustomPayloadPacket( CarpetClient.CARPET_CHANNEL, @@ -168,10 +169,10 @@ public static void updateFrozenStateToConnectedPlayers() } } - public static void updateSuperHotStateToConnectedPlayers() + public static void updateSuperHotStateToConnectedPlayers(MinecraftServer server) { if(CarpetSettings.superSecretSetting) return; - for (ServerPlayer player : remoteCarpetPlayers.keySet()) + for (ServerPlayer player : validCarpetPlayers) { player.connection.send(new ClientboundCustomPayloadPacket( CarpetClient.CARPET_CHANNEL, @@ -180,10 +181,10 @@ public static void updateSuperHotStateToConnectedPlayers() } } - public static void updateTickPlayerActiveTimeoutToConnectedPlayers() + public static void updateTickPlayerActiveTimeoutToConnectedPlayers(MinecraftServer server) { if (CarpetSettings.superSecretSetting) return; - for (ServerPlayer player : remoteCarpetPlayers.keySet()) + for (ServerPlayer player : validCarpetPlayers) { player.connection.send(new ClientboundCustomPayloadPacket( CarpetClient.CARPET_CHANNEL, @@ -256,7 +257,7 @@ private DataBuilder() } private DataBuilder withTickRate() { - tag.putFloat("TickRate", TickSpeed.tickrate); + tag.putFloat("TickRate", TickSpeed.gTRM().map(trm -> trm.tickrate).orElse(20.0f)); return this; } private DataBuilder withFrozenState() @@ -269,12 +270,12 @@ private DataBuilder withFrozenState() } private DataBuilder withSuperHotState() { - tag.putBoolean("SuperHotState", TickSpeed.is_superHot); + tag.putBoolean("SuperHotState", TickSpeed.gTRM().map(trm -> trm.is_superHot).orElse(false)); return this; } private DataBuilder withTickPlayerActiveTimeout() { - tag.putInt("TickPlayerActiveTimeout", TickSpeed.player_active_timeout); + tag.putInt("TickPlayerActiveTimeout", TickSpeed.gTRM().map(trm -> trm.player_active_timeout).orElse(0)); return this; } private DataBuilder withRule(CarpetRule rule) diff --git a/src/main/java/carpet/patches/TickSyncedBorderExtent.java b/src/main/java/carpet/patches/TickSyncedBorderExtent.java index f0c87319f3..4051dceac8 100644 --- a/src/main/java/carpet/patches/TickSyncedBorderExtent.java +++ b/src/main/java/carpet/patches/TickSyncedBorderExtent.java @@ -89,13 +89,13 @@ public long getLerpRemainingTime() double ms; if (server == null) { - ms = TickSpeed.mspt; + ms = TickSpeed.mspt(); } else { ms = Arrays.stream(server.tickTimes).average().orElseThrow(IllegalStateException::new) * 1.0E-6D; } - double tps = 1_000.0D / Math.max((TickSpeed.time_warp_start_time != 0) ? 0.0 : TickSpeed.mspt, ms); + double tps = 1_000.0D / Math.max((TickSpeed.gTRM().map(trm -> trm.time_warp_start_time).orElse(0L) != 0) ? 0.0 : TickSpeed.mspt(), ms); return (long) ((this.tickDuration - this.ticks) / tps * 1_000); } diff --git a/src/main/java/carpet/script/external/Carpet.java b/src/main/java/carpet/script/external/Carpet.java index 700e7b97c4..2d3660ea48 100644 --- a/src/main/java/carpet/script/external/Carpet.java +++ b/src/main/java/carpet/script/external/Carpet.java @@ -136,7 +136,7 @@ public static String isModdedPlayer(Player p) public static boolean isTickProcessingPaused() { - return !TickSpeed.process_entities; + return !TickSpeed.process_entities(); } public static void handleExtensionsAPI(CarpetExpression expression) From df786605c2b160e1d18353e47f4ddd929526de8b Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Tue, 16 May 2023 10:35:40 +0200 Subject: [PATCH 144/233] moar client-server tick speed separation --- gradle.properties | 2 +- src/main/java/carpet/CarpetServer.java | 7 ++- .../java/carpet/commands/SpawnCommand.java | 8 +-- .../java/carpet/commands/TickCommand.java | 36 +++++++++----- .../java/carpet/helpers/TickRateManager.java | 23 ++------- src/main/java/carpet/helpers/TickSpeed.java | 49 +++++-------------- .../java/carpet/logging/HUDController.java | 2 +- .../BoundTickingBlockEntity_tickMixin.java | 13 ++++- ...ientPacketListener_customPacketsMixin.java | 3 ++ .../mixins/DistanceManager_tickMixin.java | 23 --------- .../java/carpet/mixins/Level_tickMixin.java | 16 ++++-- .../mixins/MinecraftServer_scarpetMixin.java | 5 +- .../MinecraftServer_tickspeedMixin.java | 6 +-- .../mixins/ServerChunkCache_tickMixin.java | 19 ++++++- .../ServerFunctionManager_tickMixin.java | 17 +++++-- ...erverGamePacketListenerImpl_tickMixin.java | 6 +-- .../carpet/mixins/ServerLevel_tickMixin.java | 14 +++--- .../carpet/network/ServerNetworkHandler.java | 43 +++++++++------- .../patches/TickSyncedBorderExtent.java | 13 +++-- .../java/carpet/script/CarpetEventServer.java | 2 +- .../java/carpet/script/external/Carpet.java | 4 +- src/main/resources/carpet.accesswidener | 2 + src/main/resources/carpet.mixins.json | 1 - 23 files changed, 166 insertions(+), 148 deletions(-) delete mode 100644 src/main/java/carpet/mixins/DistanceManager_tickMixin.java diff --git a/gradle.properties b/gradle.properties index baed9206e8..3c146851ff 100644 --- a/gradle.properties +++ b/gradle.properties @@ -6,7 +6,7 @@ org.gradle.jvmargs=-Xmx1G minecraft_version=1.20-pre1 loader_version=0.14.19 jsr305_version=3.0.2 - fabric_version=0.80.2+1.20 + fabric_version=0.81.1+1.20 # Mod Properties mod_version = 1.4.108 diff --git a/src/main/java/carpet/CarpetServer.java b/src/main/java/carpet/CarpetServer.java index 861ba61d10..623769e5d2 100644 --- a/src/main/java/carpet/CarpetServer.java +++ b/src/main/java/carpet/CarpetServer.java @@ -14,6 +14,8 @@ import carpet.commands.PerimeterInfoCommand; import carpet.commands.PlayerCommand; import carpet.commands.ProfileCommand; +import carpet.fakes.MinecraftServerInterface; +import carpet.helpers.TickRateManager; import carpet.script.ScriptCommand; import carpet.commands.SpawnCommand; import carpet.commands.TestCommand; @@ -127,7 +129,8 @@ public static void onServerLoadedWorlds(MinecraftServer minecraftServer) public static void tick(MinecraftServer server) { - TickSpeed.tick(); + TickRateManager trm = ((MinecraftServerInterface)server).getTickRateManager(); + trm.tick(); HUDController.update_hud(server, null); if (scriptServer != null) scriptServer.tick(); @@ -228,7 +231,7 @@ public static void onServerClosed(MinecraftServer server) } // this for whatever reason gets called multiple times even when joining; - TickSpeed.reset(); + TickSpeed.resetClient(); } public static void onServerDoneClosing(MinecraftServer server) { diff --git a/src/main/java/carpet/commands/SpawnCommand.java b/src/main/java/carpet/commands/SpawnCommand.java index 07cd3b5c44..62bbb16a02 100644 --- a/src/main/java/carpet/commands/SpawnCommand.java +++ b/src/main/java/carpet/commands/SpawnCommand.java @@ -1,9 +1,10 @@ package carpet.commands; import carpet.CarpetSettings; +import carpet.fakes.MinecraftServerInterface; import carpet.fakes.SpawnGroupInterface; import carpet.helpers.HopperCounter; -import carpet.helpers.TickSpeed; +import carpet.helpers.TickRateManager; import carpet.utils.CommandHelper; import carpet.utils.Messenger; import carpet.utils.SpawnReporter; @@ -198,7 +199,8 @@ private static int runTest(CommandSourceStack source, int ticks, String counter) // tick warp 0 - TickSpeed.tickrate_advance(null, 0, null, null); + TickRateManager trm = ((MinecraftServerInterface)source.getServer()).getTickRateManager(); + trm.tickrate_advance(null, 0, null, null); // tick warp given player CommandSourceStack csource = null; ServerPlayer player = null; @@ -210,7 +212,7 @@ private static int runTest(CommandSourceStack source, int ticks, String counter) catch (CommandSyntaxException ignored) { } - TickSpeed.tickrate_advance(player, ticks, null, csource); + trm.tickrate_advance(player, ticks, null, csource); Messenger.m(source, String.format("gi Started spawn test for %d ticks", ticks)); return 1; } diff --git a/src/main/java/carpet/commands/TickCommand.java b/src/main/java/carpet/commands/TickCommand.java index 491b6c6a28..5ed82a5b0a 100644 --- a/src/main/java/carpet/commands/TickCommand.java +++ b/src/main/java/carpet/commands/TickCommand.java @@ -1,7 +1,8 @@ package carpet.commands; import carpet.CarpetSettings; -import carpet.helpers.TickSpeed; +import carpet.fakes.MinecraftServerInterface; +import carpet.helpers.TickRateManager; import carpet.network.ServerNetworkHandler; import carpet.utils.CarpetProfiler; import carpet.utils.CommandHelper; @@ -72,30 +73,35 @@ public static void register(CommandDispatcher dispatcher, Co private static int setTps(CommandSourceStack source, float tps) { - TickSpeed.tickrate(tps, true); + TickRateManager trm = ((MinecraftServerInterface)source.getServer()).getTickRateManager(); + trm.tickrate(tps, true); queryTps(source); return (int)tps; } private static int queryTps(CommandSourceStack source) { - Messenger.m(source, "w Current tps is: ",String.format("wb %.1f", TickSpeed.gTRM().map(trm -> trm.tickrate).orElse(20.0f))); - return (int)(float)TickSpeed.gTRM().map(trm -> trm.tickrate).orElse(20.0f); + TickRateManager trm = ((MinecraftServerInterface)source.getServer()).getTickRateManager(); + + Messenger.m(source, "w Current tps is: ",String.format("wb %.1f", trm.tickrate)); + return (int) trm.tickrate; } private static int setWarp(CommandSourceStack source, int advance, String tail_command) { ServerPlayer player = source.getPlayer(); // may be null - Component message = TickSpeed.tickrate_advance(player, advance, tail_command, source); + TickRateManager trm = ((MinecraftServerInterface)source.getServer()).getTickRateManager(); + Component message = trm.tickrate_advance(player, advance, tail_command, source); source.sendSuccess(message, false); return 1; } private static int freezeStatus(CommandSourceStack source) { - if(TickSpeed.isPaused()) + TickRateManager trm = ((MinecraftServerInterface)source.getServer()).getTickRateManager(); + if(trm.isPaused()) { - Messenger.m(source, "gi Freeze Status: Game is "+(TickSpeed.deeplyFrozen()?"deeply ":"")+"frozen"); + Messenger.m(source, "gi Freeze Status: Game is "+(trm.deeplyFrozen()?"deeply ":"")+"frozen"); } else { @@ -106,8 +112,9 @@ private static int freezeStatus(CommandSourceStack source) private static int setFreeze(CommandSourceStack source, boolean isDeep, boolean freeze) { - TickSpeed.setFrozenState(freeze, isDeep); - if (TickSpeed.isPaused()) + TickRateManager trm = ((MinecraftServerInterface)source.getServer()).getTickRateManager(); + trm.setFrozenState(freeze, isDeep); + if (trm.isPaused()) { Messenger.m(source, "gi Game is "+(isDeep?"deeply ":"")+"frozen"); } @@ -120,21 +127,24 @@ private static int setFreeze(CommandSourceStack source, boolean isDeep, boolean private static int toggleFreeze(CommandSourceStack source, boolean isDeep) { - return setFreeze(source, isDeep, !TickSpeed.isPaused()); + TickRateManager trm = ((MinecraftServerInterface)source.getServer()).getTickRateManager(); + return setFreeze(source, isDeep, !trm.isPaused()); } private static int step(CommandSourceStack source, int advance) { - TickSpeed.add_ticks_to_run_in_pause(advance); + TickRateManager trm = ((MinecraftServerInterface)source.getServer()).getTickRateManager(); + trm.add_ticks_to_run_in_pause(advance); Messenger.m(source, "gi Stepping " + advance + " tick" + (advance != 1 ? "s" : "")); return 1; } private static int toggleSuperHot(CommandSourceStack source) { - TickSpeed.gTRM().ifPresent(trm -> trm.is_superHot = !trm.is_superHot); + TickRateManager trm = ((MinecraftServerInterface)source.getServer()).getTickRateManager(); + trm.is_superHot = !trm.is_superHot; ServerNetworkHandler.updateSuperHotStateToConnectedPlayers(source.getServer()); - if (TickSpeed.gTRM().map(trm -> trm.is_superHot).orElse(false)) + if (trm.is_superHot) { Messenger.m(source, "gi Superhot enabled"); } diff --git a/src/main/java/carpet/helpers/TickRateManager.java b/src/main/java/carpet/helpers/TickRateManager.java index 2666f35106..0534792776 100644 --- a/src/main/java/carpet/helpers/TickRateManager.java +++ b/src/main/java/carpet/helpers/TickRateManager.java @@ -47,6 +47,11 @@ public boolean isPaused() return is_paused; } + public boolean process_entities() + { + return process_entities; + } + /** * Whether or not the game is deeply frozen. * This can be used for things that you may not normally want @@ -85,24 +90,6 @@ public void reset_player_active_timeout() } } - public void reset() // do we need reset? - { - tickrate = 20.0f; - mspt = 50.0f; - time_bias = 0; - time_warp_start_time = 0; - time_warp_scheduled_ticks = 0; - time_advancerer = null; - tick_warp_callback = null; - tick_warp_sender = null; - player_active_timeout = 0; - process_entities = true; - deepFreeze = false; - is_paused = false; - is_superHot = false; - notifyTickrateListeners("carpet"); - } - public void add_ticks_to_run_in_pause(int ticks) { player_active_timeout = PLAYER_GRACE + ticks; diff --git a/src/main/java/carpet/helpers/TickSpeed.java b/src/main/java/carpet/helpers/TickSpeed.java index 6392b8a506..a30f437e51 100644 --- a/src/main/java/carpet/helpers/TickSpeed.java +++ b/src/main/java/carpet/helpers/TickSpeed.java @@ -1,22 +1,18 @@ package carpet.helpers; -import java.util.HashMap; -import java.util.Map; import java.util.Optional; import java.util.function.BiConsumer; import carpet.fakes.MinecraftServerInterface; import net.minecraft.commands.CommandSourceStack; -import net.minecraft.commands.Commands; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerPlayer; import carpet.CarpetServer; -import carpet.network.ServerNetworkHandler; import carpet.utils.Messenger; public class TickSpeed { - public static Optional gTRM() { + private static Optional gTRM() { if (CarpetServer.minecraft_server == null) return Optional.empty(); return Optional.of(((MinecraftServerInterface)CarpetServer.minecraft_server).getTickRateManager()); } @@ -29,43 +25,17 @@ public static float mspt() { return gTRM().map(trm -> trm.mspt).orElse(50.0f); } - /** - * @return Whether or not the game is in a frozen state. - * You should normally use {@link #process_entities()} instead, - * since that one accounts for tick steps and superhot - */ public static boolean isPaused() { return gTRM().map(TickRateManager::isPaused).orElse(false); } - /** - * Whether or not the game is deeply frozen. - * This can be used for things that you may not normally want - * to freeze, but may need to in some situations. - * This should be checked with {@link #process_entities()} to make sure the - * current tick is actually frozen, not only the game - * @return Whether or not the game is deeply frozen. - */ public static boolean deeplyFrozen() { return gTRM().map(TickRateManager::deeplyFrozen).orElse(false); } - /** - * Used to update the frozen state of the game. - * Handles connected clients as well. - * @param isPaused Whether or not the game is paused - * @param isDeepFreeze Whether or not the game is deeply frozen - */ public static void setFrozenState(boolean isPaused, boolean isDeepFreeze) { gTRM().ifPresent(trm -> trm.setFrozenState(isPaused, isDeepFreeze)); } - - /** - * Functional interface that listens for tickrate changes. This is - * implemented to allow tickrate compatibility with other mods etc. - */ - private static final Map> tickrateListeners = new HashMap<>(); - private static final float MIN_TICKRATE = 0.01f; public static void reset_player_active_timeout() { @@ -74,7 +44,7 @@ public static void reset_player_active_timeout() public static void reset() { - gTRM().ifPresent(TickRateManager::reset); + // noop - called on server to reset client } public static void add_ticks_to_run_in_pause(int ticks) @@ -109,16 +79,12 @@ public static void tickrate(float rate, boolean update) } - - public static BiConsumer addTickrateListener(String modId, BiConsumer tickrateListener) { return gTRM().map(trm -> trm.addTickrateListener(modId, tickrateListener)).orElse(null); } - - // client only private static float tickrate = 20.0f; @@ -193,5 +159,16 @@ else if (is_superHot) } } + public static void resetClient() + { + tickrate = 20.0f; + mspt = 50.0f; + player_active_timeout = 0; + process_entities = true; + deepFreeze = false; + is_paused = false; + is_superHot = false; + } + } diff --git a/src/main/java/carpet/logging/HUDController.java b/src/main/java/carpet/logging/HUDController.java index 1a6bf09f58..6b29a6fa69 100644 --- a/src/main/java/carpet/logging/HUDController.java +++ b/src/main/java/carpet/logging/HUDController.java @@ -126,7 +126,7 @@ public static void update_hud(MinecraftServer server, List force) } double MSPT = Arrays.stream(server.tickTimes).average().getAsDouble() * 1.0E-6D; double TPS = 1000.0D / Math.max((trm.time_warp_start_time != 0)?0.0:trm.mspt, MSPT); - if (TickSpeed.isPaused()) { + if (trm.isPaused()) { TPS = 0; } String color = Messenger.heatmap_color(MSPT,trm.mspt); diff --git a/src/main/java/carpet/mixins/BoundTickingBlockEntity_tickMixin.java b/src/main/java/carpet/mixins/BoundTickingBlockEntity_tickMixin.java index 834c4c3e63..b36a5c4080 100644 --- a/src/main/java/carpet/mixins/BoundTickingBlockEntity_tickMixin.java +++ b/src/main/java/carpet/mixins/BoundTickingBlockEntity_tickMixin.java @@ -1,8 +1,11 @@ package carpet.mixins; +import carpet.fakes.MinecraftServerInterface; +import carpet.helpers.TickRateManager; import carpet.helpers.TickSpeed; import carpet.utils.CarpetProfiler; import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; @@ -34,7 +37,15 @@ private void startTileEntitySection(CallbackInfo ci) )) private void checkProcessBEs(BlockEntityTicker blockEntityTicker, Level world, BlockPos pos, BlockState state, T blockEntity) { - if (TickSpeed.process_entities()) blockEntityTicker.tick(world, pos, state, blockEntity); + if (world.isClientSide()) { + // client + if (TickSpeed.process_entitiesClient()) blockEntityTicker.tick(world, pos, state, blockEntity); + } else { + // server + ServerLevel serverWorld = (ServerLevel) world; + TickRateManager tickRateManager = ((MinecraftServerInterface)serverWorld.getServer()).getTickRateManager(); + if (tickRateManager.process_entities()) blockEntityTicker.tick(world, pos, state, blockEntity); + } } @Inject(method = "tick()V", at = @At("RETURN")) diff --git a/src/main/java/carpet/mixins/ClientPacketListener_customPacketsMixin.java b/src/main/java/carpet/mixins/ClientPacketListener_customPacketsMixin.java index ce0736453c..64f0735ce4 100644 --- a/src/main/java/carpet/mixins/ClientPacketListener_customPacketsMixin.java +++ b/src/main/java/carpet/mixins/ClientPacketListener_customPacketsMixin.java @@ -1,5 +1,6 @@ package carpet.mixins; +import carpet.helpers.TickSpeed; import carpet.network.CarpetClient; import carpet.network.ClientNetworkHandler; import net.minecraft.client.Minecraft; @@ -33,11 +34,13 @@ private void onOnCustomPayload(ClientboundCustomPayloadPacket packet, CallbackIn private void onGameJoined(ClientboundLoginPacket packet, CallbackInfo info) { CarpetClient.gameJoined(minecraft.player); + TickSpeed.resetClient(); } @Inject(method = "onDisconnect", at = @At("HEAD")) private void onCMDisconnected(Component reason, CallbackInfo ci) { CarpetClient.disconnect(); + TickSpeed.resetClient(); } } diff --git a/src/main/java/carpet/mixins/DistanceManager_tickMixin.java b/src/main/java/carpet/mixins/DistanceManager_tickMixin.java deleted file mode 100644 index 19fc1ec3ec..0000000000 --- a/src/main/java/carpet/mixins/DistanceManager_tickMixin.java +++ /dev/null @@ -1,23 +0,0 @@ -package carpet.mixins; - -import carpet.helpers.TickSpeed; -import net.minecraft.server.level.DistanceManager; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(DistanceManager.class) -public class DistanceManager_tickMixin -{ - @Shadow private long ticketTickCounter; - - @Inject(method = "purgeStaleTickets", at = @At("HEAD")) - private void pauseTicketSystem(CallbackInfo ci) - { - // pausing expiry of tickets - // that will prevent also chunks from unloading, so require a deep frozen state - if (!TickSpeed.process_entities() && TickSpeed.deeplyFrozen()) ticketTickCounter--; - } -} diff --git a/src/main/java/carpet/mixins/Level_tickMixin.java b/src/main/java/carpet/mixins/Level_tickMixin.java index 18e4447b6b..898db3d7cd 100644 --- a/src/main/java/carpet/mixins/Level_tickMixin.java +++ b/src/main/java/carpet/mixins/Level_tickMixin.java @@ -1,8 +1,11 @@ package carpet.mixins; import carpet.fakes.LevelInterface; +import carpet.fakes.MinecraftServerInterface; +import carpet.helpers.TickRateManager; import carpet.helpers.TickSpeed; import carpet.utils.CarpetProfiler; +import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.redstone.NeighborUpdater; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -87,13 +90,18 @@ private void endTileEntitySection(CallbackInfo ci) private void startEntity(Consumer consumer_1, Entity e, CallbackInfo ci) { // this shows that probably tick speed controller needs to be accessible through level referring to servers on server and client on clientLevel - if (isClientSide) { - if (!(TickSpeed.process_entitiesClient() || (e instanceof Player) || TickSpeed.isIs_superHotClient() && e.getControllingPassenger() instanceof Player)) + if (!isClientSide) + { + ServerLevel serverLevel = (ServerLevel) (Object) this; + TickRateManager trm = ((MinecraftServerInterface)serverLevel.getServer()).getTickRateManager(); + if (!(trm.process_entities() || (e instanceof Player))) { ci.cancel(); } - } else { - if (!(TickSpeed.gTRM().map(trm -> trm.process_entities).orElse(true) || (e instanceof Player))) + } + else + { + if (!(TickSpeed.process_entitiesClient() || (e instanceof Player) || TickSpeed.isIs_superHotClient() && e.getControllingPassenger() instanceof Player)) { ci.cancel(); } diff --git a/src/main/java/carpet/mixins/MinecraftServer_scarpetMixin.java b/src/main/java/carpet/mixins/MinecraftServer_scarpetMixin.java index baaae69253..b260416432 100644 --- a/src/main/java/carpet/mixins/MinecraftServer_scarpetMixin.java +++ b/src/main/java/carpet/mixins/MinecraftServer_scarpetMixin.java @@ -1,7 +1,6 @@ package carpet.mixins; import carpet.fakes.MinecraftServerInterface; -import carpet.helpers.TickSpeed; import carpet.script.CarpetScriptServer; import net.minecraft.Util; import net.minecraft.core.RegistryAccess; @@ -89,8 +88,10 @@ public Map, ServerLevel> getCMWorlds() )) public void tickTasks(BooleanSupplier booleanSupplier_1, CallbackInfo ci) { - if (!TickSpeed.process_entities()) + if (!getTickRateManager().process_entities()) + { return; + } TICK.onTick((MinecraftServer) (Object) this); NETHER_TICK.onTick((MinecraftServer) (Object) this); ENDER_TICK.onTick((MinecraftServer) (Object) this); diff --git a/src/main/java/carpet/mixins/MinecraftServer_tickspeedMixin.java b/src/main/java/carpet/mixins/MinecraftServer_tickspeedMixin.java index 7ae968b373..7962bb0f51 100644 --- a/src/main/java/carpet/mixins/MinecraftServer_tickspeedMixin.java +++ b/src/main/java/carpet/mixins/MinecraftServer_tickspeedMixin.java @@ -112,7 +112,7 @@ private void modifiedRunLoop(CallbackInfo ci) long msThisTick = 0L; long long_1 = 0L; float mspt = tickRateManager.mspt; - if (tickRateManager.time_warp_start_time != 0 && TickSpeed.continueWarp()) + if (tickRateManager.time_warp_start_time != 0 && tickRateManager.continueWarp()) { //making sure server won't flop after the warp or if the warp is interrupted this.nextTickTime = this.lastOverloadWarning = Util.getMillis(); @@ -151,9 +151,9 @@ private void modifiedRunLoop(CallbackInfo ci) //this.startMonitor(tickDurationMonitor); this.startMetricsRecordingTick(); this.profiler.push("tick"); - this.tickServer(TickSpeed.gTRM().map(trm -> trm.time_warp_start_time).orElse(0L) != 0 ? ()->true : this::haveTime); + this.tickServer(tickRateManager.time_warp_start_time != 0 ? ()->true : this::haveTime); this.profiler.popPush("nextTickWait"); - if (TickSpeed.gTRM().map(trm -> trm.time_warp_start_time).orElse(0L) != 0) // clearing all hanging tasks no matter what when warping + if (tickRateManager.time_warp_start_time != 0) // clearing all hanging tasks no matter what when warping { while(this.runEveryTask()) {Thread.yield();} } diff --git a/src/main/java/carpet/mixins/ServerChunkCache_tickMixin.java b/src/main/java/carpet/mixins/ServerChunkCache_tickMixin.java index dfbe7e6664..51b7c41391 100644 --- a/src/main/java/carpet/mixins/ServerChunkCache_tickMixin.java +++ b/src/main/java/carpet/mixins/ServerChunkCache_tickMixin.java @@ -1,8 +1,10 @@ package carpet.mixins; +import carpet.fakes.MinecraftServerInterface; import carpet.fakes.ThreadedAnvilChunkStorageInterface; -import carpet.helpers.TickSpeed; +import carpet.helpers.TickRateManager; import carpet.utils.CarpetProfiler; +import net.minecraft.server.level.DistanceManager; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -78,7 +80,7 @@ private void stopSpawningSection(CallbackInfo ci) private boolean skipChunkTicking(ServerLevel serverWorld) { boolean debug = serverWorld.isDebug(); - if (!TickSpeed.process_entities()) + if (!((MinecraftServerInterface)serverWorld.getServer()).getTickRateManager().process_entities()) { // simplified chunk tick iteration assuming world is frozen otherwise as suggested by Hadron67 // to be kept in sync with the original injection source @@ -97,4 +99,17 @@ private boolean skipChunkTicking(ServerLevel serverWorld) return debug; } + @Redirect(method = "tick", at = @At( + value = "INVOKE", + target = "Lnet/minecraft/server/level/DistanceManager;purgeStaleTickets()V" + )) + private void pauseTicketSystem(DistanceManager distanceManager) + { + // pausing expiry of tickets + // that will prevent also chunks from unloading, so require a deep frozen state + TickRateManager trm = ((MinecraftServerInterface) level.getServer()).getTickRateManager(); + if (!trm.process_entities() && trm.deeplyFrozen()) return; + distanceManager.purgeStaleTickets(); + } + } diff --git a/src/main/java/carpet/mixins/ServerFunctionManager_tickMixin.java b/src/main/java/carpet/mixins/ServerFunctionManager_tickMixin.java index b4aab97496..f428c41d74 100644 --- a/src/main/java/carpet/mixins/ServerFunctionManager_tickMixin.java +++ b/src/main/java/carpet/mixins/ServerFunctionManager_tickMixin.java @@ -1,9 +1,12 @@ package carpet.mixins; -import carpet.helpers.TickSpeed; +import carpet.fakes.MinecraftServerInterface; import carpet.utils.CarpetProfiler; +import net.minecraft.server.MinecraftServer; import net.minecraft.server.ServerFunctionManager; +import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @@ -11,14 +14,20 @@ @Mixin(ServerFunctionManager.class) public class ServerFunctionManager_tickMixin { + @Shadow @Final MinecraftServer server; CarpetProfiler.ProfilerToken currentSection; @Inject(method = "tick", at = @At("HEAD"), cancellable = true) private void beforeDatapacks(CallbackInfo ci) { - if (!TickSpeed.process_entities()) ci.cancel(); - else - currentSection = CarpetProfiler.start_section(null, "Datapacks", CarpetProfiler.TYPE.GENERAL); + if (! ((MinecraftServerInterface)server).getTickRateManager().process_entities()) + { + ci.cancel(); + } + else + { + currentSection = CarpetProfiler.start_section(null, "Datapacks", CarpetProfiler.TYPE.GENERAL); + } } @Inject(method = "tick", at = @At("RETURN")) diff --git a/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_tickMixin.java b/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_tickMixin.java index b1b7e6d09c..de670f1249 100644 --- a/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_tickMixin.java +++ b/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_tickMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.helpers.TickSpeed; +import carpet.fakes.MinecraftServerInterface; import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; import net.minecraft.network.protocol.game.ServerboundPlayerInputPacket; import net.minecraft.server.level.ServerPlayer; @@ -27,7 +27,7 @@ private void checkMoves(ServerboundPlayerInputPacket p, CallbackInfo ci) { if (p.getXxa() != 0.0F || p.getZza() != 0.0F || p.isJumping() || p.isShiftKeyDown()) { - TickSpeed.reset_player_active_timeout(); + ((MinecraftServerInterface)player.getServer()).getTickRateManager().reset_player_active_timeout(); } } @@ -53,7 +53,7 @@ private void checkMove(ServerboundMovePlayerPacket p, CallbackInfo ci) { lastMoved = movedBy; lastMovedTick = player.getServer().getTickCount(); - TickSpeed.reset_player_active_timeout(); + ((MinecraftServerInterface)player.getServer()).getTickRateManager().reset_player_active_timeout(); } } } diff --git a/src/main/java/carpet/mixins/ServerLevel_tickMixin.java b/src/main/java/carpet/mixins/ServerLevel_tickMixin.java index 23a60e5cb8..3784958f64 100644 --- a/src/main/java/carpet/mixins/ServerLevel_tickMixin.java +++ b/src/main/java/carpet/mixins/ServerLevel_tickMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.helpers.TickSpeed; +import carpet.fakes.MinecraftServerInterface; import carpet.utils.CarpetProfiler; import net.minecraft.core.Holder; import net.minecraft.core.RegistryAccess; @@ -159,13 +159,13 @@ private void endRandomTicks(CallbackInfo ci) { )) private void tickWorldBorder(WorldBorder worldBorder) { - if (TickSpeed.process_entities()) worldBorder.tick(); + if (((MinecraftServerInterface)getServer()).getTickRateManager().process_entities()) worldBorder.tick(); } @Inject(method = "advanceWeatherCycle", cancellable = true, at = @At("HEAD")) private void tickWeather(CallbackInfo ci) { - if (!TickSpeed.process_entities()) ci.cancel(); + if (!((MinecraftServerInterface)getServer()).getTickRateManager().process_entities()) ci.cancel(); } @Redirect(method = "tick", at = @At( @@ -174,7 +174,7 @@ private void tickWeather(CallbackInfo ci) )) private void tickTimeConditionally(ServerLevel serverWorld) { - if (TickSpeed.process_entities()) tickTime(); + if (((MinecraftServerInterface)getServer()).getTickRateManager().process_entities()) tickTime(); } @Redirect(method = "tick", at = @At( @@ -183,7 +183,7 @@ private void tickTimeConditionally(ServerLevel serverWorld) )) private boolean tickPendingBlocks(ServerLevel serverWorld) { - if (!TickSpeed.process_entities()) return true; + if (!((MinecraftServerInterface)getServer()).getTickRateManager().process_entities()) return true; return serverWorld.isDebug(); // isDebug() } @@ -193,7 +193,7 @@ private boolean tickPendingBlocks(ServerLevel serverWorld) )) private void tickConditionally(Raids raidManager) { - if (TickSpeed.process_entities()) raidManager.tick(); + if (((MinecraftServerInterface)getServer()).getTickRateManager().process_entities()) raidManager.tick(); } @Redirect(method = "tick", at = @At( @@ -202,6 +202,6 @@ private void tickConditionally(Raids raidManager) )) private void tickConditionally(ServerLevel serverWorld) { - if (TickSpeed.process_entities()) runBlockEvents(); + if (((MinecraftServerInterface)getServer()).getTickRateManager().process_entities()) runBlockEvents(); } } diff --git a/src/main/java/carpet/network/ServerNetworkHandler.java b/src/main/java/carpet/network/ServerNetworkHandler.java index 7a80ae6031..4d5882863f 100644 --- a/src/main/java/carpet/network/ServerNetworkHandler.java +++ b/src/main/java/carpet/network/ServerNetworkHandler.java @@ -4,8 +4,9 @@ import carpet.CarpetSettings; import carpet.api.settings.CarpetRule; import carpet.api.settings.RuleHelper; +import carpet.fakes.MinecraftServerInterface; import carpet.fakes.ServerGamePacketListenerImplInterface; -import carpet.helpers.TickSpeed; +import carpet.helpers.TickRateManager; import carpet.script.utils.SnoopyCommandSource; import carpet.api.settings.SettingsManager; import io.netty.buffer.Unpooled; @@ -77,7 +78,7 @@ public static void onHello(ServerPlayer playerEntity, FriendlyByteBuf packetData CarpetSettings.LOG.info("Player "+playerEntity.getName().getString()+" joined with a matching carpet client"); else CarpetSettings.LOG.warn("Player "+playerEntity.getName().getString()+" joined with another carpet version: "+clientVersion); - DataBuilder data = DataBuilder.create().withTickRate().withFrozenState().withTickPlayerActiveTimeout(); // .withSuperHotState() + DataBuilder data = DataBuilder.create(playerEntity.server).withTickRate().withFrozenState().withTickPlayerActiveTimeout(); // .withSuperHotState() CarpetServer.settingsManager.getCarpetRules().forEach(data::withRule); CarpetServer.extensions.forEach(e -> { SettingsManager eManager = e.extensionSettingsManager(); @@ -114,7 +115,7 @@ private static void handleClientCommand(ServerPlayer player, CompoundTag command if (!output.isEmpty()) result.put("output", outputResult); player.connection.send(new ClientboundCustomPayloadPacket( CarpetClient.CARPET_CHANNEL, - DataBuilder.create().withCustomNbt("clientCommand", result).build() + DataBuilder.create(player.server).withCustomNbt("clientCommand", result).build() )); // run command plug to command output, } @@ -140,7 +141,7 @@ public static void updateRuleWithConnectedClients(CarpetRule rule) { player.connection.send(new ClientboundCustomPayloadPacket( CarpetClient.CARPET_CHANNEL, - DataBuilder.create().withRule(rule).build() + DataBuilder.create(player.server).withRule(rule).build() )); } } @@ -152,7 +153,7 @@ public static void updateTickSpeedToConnectedPlayers(MinecraftServer server) { player.connection.send(new ClientboundCustomPayloadPacket( CarpetClient.CARPET_CHANNEL, - DataBuilder.create().withTickRate().build() + DataBuilder.create(player.server).withTickRate().build() )); } } @@ -164,7 +165,7 @@ public static void updateFrozenStateToConnectedPlayers(MinecraftServer server) { player.connection.send(new ClientboundCustomPayloadPacket( CarpetClient.CARPET_CHANNEL, - DataBuilder.create().withFrozenState().build() + DataBuilder.create(player.server).withFrozenState().build() )); } } @@ -176,7 +177,7 @@ public static void updateSuperHotStateToConnectedPlayers(MinecraftServer server) { player.connection.send(new ClientboundCustomPayloadPacket( CarpetClient.CARPET_CHANNEL, - DataBuilder.create().withSuperHotState().build() + DataBuilder.create(player.server).withSuperHotState().build() )); } } @@ -188,7 +189,7 @@ public static void updateTickPlayerActiveTimeoutToConnectedPlayers(MinecraftServ { player.connection.send(new ClientboundCustomPayloadPacket( CarpetClient.CARPET_CHANNEL, - DataBuilder.create().withTickPlayerActiveTimeout().build() + DataBuilder.create(player.server).withTickPlayerActiveTimeout().build() )); } } @@ -200,7 +201,7 @@ public static void broadcastCustomCommand(String command, Tag data) { player.connection.send(new ClientboundCustomPayloadPacket( CarpetClient.CARPET_CHANNEL, - DataBuilder.create().withCustomNbt(command, data).build() + DataBuilder.create(player.server).withCustomNbt(command, data).build() )); } } @@ -211,7 +212,7 @@ public static void sendCustomCommand(ServerPlayer player, String command, Tag da { player.connection.send(new ClientboundCustomPayloadPacket( CarpetClient.CARPET_CHANNEL, - DataBuilder.create().withCustomNbt(command, data).build() + DataBuilder.create(player.server).withCustomNbt(command, data).build() )); } } @@ -247,35 +248,41 @@ public static String getPlayerStatus(ServerPlayer player) private static class DataBuilder { private CompoundTag tag; - private static DataBuilder create() + private MinecraftServer server; + private static DataBuilder create(final MinecraftServer server) { - return new DataBuilder(); + return new DataBuilder(server); } - private DataBuilder() + private DataBuilder(MinecraftServer server) { tag = new CompoundTag(); + this.server = server; } private DataBuilder withTickRate() { - tag.putFloat("TickRate", TickSpeed.gTRM().map(trm -> trm.tickrate).orElse(20.0f)); + TickRateManager trm = ((MinecraftServerInterface)server).getTickRateManager(); + tag.putFloat("TickRate", trm.tickrate); return this; } private DataBuilder withFrozenState() { + TickRateManager trm = ((MinecraftServerInterface)server).getTickRateManager(); CompoundTag tickingState = new CompoundTag(); - tickingState.putBoolean("is_paused", TickSpeed.isPaused()); - tickingState.putBoolean("deepFreeze", TickSpeed.deeplyFrozen()); + tickingState.putBoolean("is_paused", trm.isPaused()); + tickingState.putBoolean("deepFreeze", trm.deeplyFrozen()); tag.put("TickingState", tickingState); return this; } private DataBuilder withSuperHotState() { - tag.putBoolean("SuperHotState", TickSpeed.gTRM().map(trm -> trm.is_superHot).orElse(false)); + TickRateManager trm = ((MinecraftServerInterface)server).getTickRateManager(); + tag.putBoolean("SuperHotState", trm.is_superHot); return this; } private DataBuilder withTickPlayerActiveTimeout() { - tag.putInt("TickPlayerActiveTimeout", TickSpeed.gTRM().map(trm -> trm.player_active_timeout).orElse(0)); + TickRateManager trm = ((MinecraftServerInterface)server).getTickRateManager(); + tag.putInt("TickPlayerActiveTimeout", trm.player_active_timeout); return this; } private DataBuilder withRule(CarpetRule rule) diff --git a/src/main/java/carpet/patches/TickSyncedBorderExtent.java b/src/main/java/carpet/patches/TickSyncedBorderExtent.java index 4051dceac8..a1aa428084 100644 --- a/src/main/java/carpet/patches/TickSyncedBorderExtent.java +++ b/src/main/java/carpet/patches/TickSyncedBorderExtent.java @@ -1,7 +1,8 @@ package carpet.patches; import carpet.CarpetServer; -import carpet.helpers.TickSpeed; +import carpet.fakes.MinecraftServerInterface; +import carpet.helpers.TickRateManager; import net.minecraft.server.MinecraftServer; import net.minecraft.util.Mth; import net.minecraft.world.level.border.BorderChangeListener; @@ -89,13 +90,19 @@ public long getLerpRemainingTime() double ms; if (server == null) { - ms = TickSpeed.mspt(); + // can this even happen? + ms = 50.0; } else { ms = Arrays.stream(server.tickTimes).average().orElseThrow(IllegalStateException::new) * 1.0E-6D; + TickRateManager trm = ((MinecraftServerInterface)server).getTickRateManager(); + if (trm.time_warp_start_time == 0) // not in time warp + { + ms = Math.max(ms, trm.mspt); + } } - double tps = 1_000.0D / Math.max((TickSpeed.gTRM().map(trm -> trm.time_warp_start_time).orElse(0L) != 0) ? 0.0 : TickSpeed.mspt(), ms); + double tps = 1_000.0D / ms; return (long) ((this.tickDuration - this.ticks) / tps * 1_000); } diff --git a/src/main/java/carpet/script/CarpetEventServer.java b/src/main/java/carpet/script/CarpetEventServer.java index b03e9217c6..c749b47be1 100644 --- a/src/main/java/carpet/script/CarpetEventServer.java +++ b/src/main/java/carpet/script/CarpetEventServer.java @@ -1369,7 +1369,7 @@ public CarpetEventServer(CarpetScriptServer scriptServer) public void tick() { - if (Carpet.isTickProcessingPaused()) + if (Carpet.isTickProcessingPaused(scriptServer.server)) { return; } diff --git a/src/main/java/carpet/script/external/Carpet.java b/src/main/java/carpet/script/external/Carpet.java index 2d3660ea48..1f6218310c 100644 --- a/src/main/java/carpet/script/external/Carpet.java +++ b/src/main/java/carpet/script/external/Carpet.java @@ -134,9 +134,9 @@ public static String isModdedPlayer(Player p) return null; } - public static boolean isTickProcessingPaused() + public static boolean isTickProcessingPaused(MinecraftServer server) { - return !TickSpeed.process_entities(); + return !((MinecraftServerInterface)server).getTickRateManager().process_entities(); } public static void handleExtensionsAPI(CarpetExpression expression) diff --git a/src/main/resources/carpet.accesswidener b/src/main/resources/carpet.accesswidener index 6ab29864b2..ebfed8ee50 100644 --- a/src/main/resources/carpet.accesswidener +++ b/src/main/resources/carpet.accesswidener @@ -12,4 +12,6 @@ accessible class net/minecraft/world/level/block/entity/SculkSensorBlockEntity$V accessible method net/minecraft/world/level/border/WorldBorder getListeners ()Ljava/util/List; +accessible method net/minecraft/server/level/DistanceManager purgeStaleTickets ()V + accessible field net/minecraft/world/level/block/state/BlockBehaviour UPDATE_SHAPE_ORDER [Lnet/minecraft/core/Direction; diff --git a/src/main/resources/carpet.mixins.json b/src/main/resources/carpet.mixins.json index 82bc4b9348..26a4d5c49b 100644 --- a/src/main/resources/carpet.mixins.json +++ b/src/main/resources/carpet.mixins.json @@ -36,7 +36,6 @@ "BoundTickingBlockEntity_tickMixin", "ServerChunkCache_tickMixin", "ChunkMap_tickMixin", - "DistanceManager_tickMixin", "ServerFunctionManager_tickMixin", "WorldBorder_tickMixin", "ChunkMap_scarpetChunkCreationMixin", From 344b0a5b7cbf00d09e26b65959a4064fbdef4832 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Tue, 16 May 2023 21:03:59 +0200 Subject: [PATCH 145/233] /info command now requires gamemasters permissions to request info from unloaded chunks. --- src/main/java/carpet/commands/InfoCommand.java | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/main/java/carpet/commands/InfoCommand.java b/src/main/java/carpet/commands/InfoCommand.java index c3ab1c20d5..4e36964c7e 100644 --- a/src/main/java/carpet/commands/InfoCommand.java +++ b/src/main/java/carpet/commands/InfoCommand.java @@ -12,6 +12,7 @@ import net.minecraft.commands.CommandBuildContext; import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.Commands; import net.minecraft.commands.arguments.coordinates.BlockPosArgument; import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; @@ -67,6 +68,18 @@ public static void printBlock(List messages, CommandSourceStack sourc private static int infoBlock(CommandSourceStack source, BlockPos pos, String grep) { + if (!source.hasPermission(Commands.LEVEL_GAMEMASTERS)) { + //check id pos is loaded + if (!source.getLevel().hasChunkAt(pos)) { + Messenger.m(source, "r Chunk is not loaded"); + return 0; + } + // verify it is in world bounds + if (!source.getLevel().isInWorldBounds(pos)) { + Messenger.m(source, "r Position is outside of world bounds"); + return 0; + } + } printBlock(BlockInfo.blockInfo(pos, source.getLevel()),source, grep); return 1; } From 044c66388afccd2b76d147da48e8aff61dc55ac9 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Tue, 16 May 2023 21:16:09 +0200 Subject: [PATCH 146/233] 1.20-pre2 --- gradle.properties | 4 ++-- src/main/java/carpet/commands/CounterCommand.java | 4 ++-- src/main/java/carpet/commands/TickCommand.java | 2 +- src/main/java/carpet/script/api/Auxiliary.java | 4 ++-- src/main/java/carpet/script/utils/SnoopyCommandSource.java | 5 +++-- src/main/java/carpet/utils/Messenger.java | 4 ++-- 6 files changed, 12 insertions(+), 11 deletions(-) diff --git a/gradle.properties b/gradle.properties index 3c146851ff..d1ed9ed6d9 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,10 +3,10 @@ org.gradle.jvmargs=-Xmx1G # Fabric Properties # check https://fabricmc.net/develop/ - minecraft_version=1.20-pre1 + minecraft_version=1.20-pre2 loader_version=0.14.19 jsr305_version=3.0.2 - fabric_version=0.81.1+1.20 + fabric_version=0.81.2+1.20 # Mod Properties mod_version = 1.4.108 diff --git a/src/main/java/carpet/commands/CounterCommand.java b/src/main/java/carpet/commands/CounterCommand.java index 5c3ace277f..2868381485 100644 --- a/src/main/java/carpet/commands/CounterCommand.java +++ b/src/main/java/carpet/commands/CounterCommand.java @@ -55,7 +55,7 @@ private static int displayCounter(CommandSourceStack source, DyeColor color, boo for (Component message: counter.format(source.getServer(), realtime, false)) { - source.sendSuccess(message, false); + source.sendSuccess(() -> message, false); } return 1; } @@ -88,7 +88,7 @@ private static int listAllCounters(CommandSourceStack source, boolean realtime) { for (Component message: HopperCounter.formatAll(source.getServer(), realtime)) { - source.sendSuccess(message, false); + source.sendSuccess(() -> message, false); } return 1; } diff --git a/src/main/java/carpet/commands/TickCommand.java b/src/main/java/carpet/commands/TickCommand.java index 5ed82a5b0a..8f0130ef7c 100644 --- a/src/main/java/carpet/commands/TickCommand.java +++ b/src/main/java/carpet/commands/TickCommand.java @@ -92,7 +92,7 @@ private static int setWarp(CommandSourceStack source, int advance, String tail_c ServerPlayer player = source.getPlayer(); // may be null TickRateManager trm = ((MinecraftServerInterface)source.getServer()).getTickRateManager(); Component message = trm.tickrate_advance(player, advance, tail_command, source); - source.sendSuccess(message, false); + source.sendSuccess(() -> message, false); return 1; } diff --git a/src/main/java/carpet/script/api/Auxiliary.java b/src/main/java/carpet/script/api/Auxiliary.java index c9818c29c3..3ad9f989ec 100644 --- a/src/main/java/carpet/script/api/Auxiliary.java +++ b/src/main/java/carpet/script/api/Auxiliary.java @@ -533,11 +533,11 @@ else if (!interactable && targetBlock == null) Component message = FormattedTextValue.getTextByValue(res); if (targets == null) { - s.sendSuccess(message, false); + s.sendSuccess(() -> message, false); } else { - targets.forEach(p -> p.sendSuccess(message, false)); + targets.forEach(p -> p.sendSuccess(() -> message, false)); } return res; // pass through for variables }); diff --git a/src/main/java/carpet/script/utils/SnoopyCommandSource.java b/src/main/java/carpet/script/utils/SnoopyCommandSource.java index 75e8cdedec..4fe3d8d575 100644 --- a/src/main/java/carpet/script/utils/SnoopyCommandSource.java +++ b/src/main/java/carpet/script/utils/SnoopyCommandSource.java @@ -20,6 +20,7 @@ import java.util.List; import java.util.function.BinaryOperator; +import java.util.function.Supplier; public class SnoopyCommandSource extends CommandSourceStack { @@ -196,9 +197,9 @@ public void sendFailure(Component message) } @Override - public void sendSuccess(Component message, boolean broadcastToOps) + public void sendSuccess(Supplier message, boolean broadcastToOps) { - chatOutput.add(message); + chatOutput.add(message.get()); } } diff --git a/src/main/java/carpet/utils/Messenger.java b/src/main/java/carpet/utils/Messenger.java index bc1ac9f9ad..067fadda56 100644 --- a/src/main/java/carpet/utils/Messenger.java +++ b/src/main/java/carpet/utils/Messenger.java @@ -231,7 +231,7 @@ private static Component getCoordsTextComponent(String style, float x, float y, public static void m(CommandSourceStack source, Object ... fields) { if (source != null) - source.sendSuccess(Messenger.c(fields), source.getServer() != null && source.getServer().overworld() != null); + source.sendSuccess(() -> Messenger.c(fields), source.getServer() != null && source.getServer().overworld() != null); } public static void m(Player player, Object ... fields) { @@ -283,7 +283,7 @@ public static void send(Player player, Collection lines) } public static void send(CommandSourceStack source, Collection lines) { - lines.stream().forEachOrdered((s) -> source.sendSuccess(s, false)); + lines.stream().forEachOrdered((s) -> source.sendSuccess(() -> s, false)); } From d0a796721830ef7c621a7cb4950ba9b2dbcc6462 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Tue, 16 May 2023 21:16:22 +0200 Subject: [PATCH 147/233] 1.4.109 --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index d1ed9ed6d9..beb22442ac 100644 --- a/gradle.properties +++ b/gradle.properties @@ -9,7 +9,7 @@ org.gradle.jvmargs=-Xmx1G fabric_version=0.81.2+1.20 # Mod Properties - mod_version = 1.4.108 + mod_version = 1.4.109 maven_group = carpet archives_base_name = fabric-carpet From c6f52b3293bbc6d0e8735a16599e569eae528f11 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 17 May 2023 21:20:00 +0200 Subject: [PATCH 148/233] retire static TickSpeed. Use Server and Client synchronization agents. --- src/main/java/carpet/CarpetServer.java | 8 +- .../java/carpet/commands/SpawnCommand.java | 8 +- .../java/carpet/commands/TickCommand.java | 38 +-- .../carpet/fakes/ClientLevelInterface.java | 8 + .../java/carpet/fakes/MinecraftInterface.java | 10 + .../fakes/MinecraftServerInterface.java | 4 +- .../carpet/helpers/ServerTickRateManager.java | 246 +++++++++++++++ .../java/carpet/helpers/TickRateManager.java | 292 +++--------------- src/main/java/carpet/helpers/TickSpeed.java | 27 +- .../java/carpet/logging/HUDController.java | 13 +- .../BoundTickingBlockEntity_tickMixin.java | 11 +- .../mixins/ClientLevel_tickSpeedMixin.java | 28 ++ ...ientPacketListener_customPacketsMixin.java | 3 - .../LevelRenderer_pausedShakeMixin.java | 8 +- .../java/carpet/mixins/Level_tickMixin.java | 45 +-- .../java/carpet/mixins/MinecraftMixin.java | 29 +- .../mixins/MinecraftServer_scarpetMixin.java | 2 +- .../MinecraftServer_tickspeedMixin.java | 19 +- .../mixins/ServerChunkCache_tickMixin.java | 8 +- .../ServerFunctionManager_tickMixin.java | 2 +- ...erverGamePacketListenerImpl_tickMixin.java | 4 +- .../carpet/mixins/ServerLevel_tickMixin.java | 12 +- .../carpet/mixins/Timer_tickSpeedMixin.java | 14 +- .../carpet/network/ClientNetworkHandler.java | 19 +- .../carpet/network/ServerNetworkHandler.java | 18 +- .../patches/TickSyncedBorderExtent.java | 8 +- .../java/carpet/script/external/Carpet.java | 3 +- src/main/resources/carpet.mixins.json | 1 + 28 files changed, 490 insertions(+), 398 deletions(-) create mode 100644 src/main/java/carpet/fakes/ClientLevelInterface.java create mode 100644 src/main/java/carpet/fakes/MinecraftInterface.java create mode 100644 src/main/java/carpet/helpers/ServerTickRateManager.java create mode 100644 src/main/java/carpet/mixins/ClientLevel_tickSpeedMixin.java diff --git a/src/main/java/carpet/CarpetServer.java b/src/main/java/carpet/CarpetServer.java index 623769e5d2..94fb270498 100644 --- a/src/main/java/carpet/CarpetServer.java +++ b/src/main/java/carpet/CarpetServer.java @@ -15,14 +15,13 @@ import carpet.commands.PlayerCommand; import carpet.commands.ProfileCommand; import carpet.fakes.MinecraftServerInterface; -import carpet.helpers.TickRateManager; +import carpet.helpers.ServerTickRateManager; import carpet.script.ScriptCommand; import carpet.commands.SpawnCommand; import carpet.commands.TestCommand; import carpet.commands.TickCommand; import carpet.network.ServerNetworkHandler; import carpet.helpers.HopperCounter; -import carpet.helpers.TickSpeed; import carpet.logging.LoggerRegistry; import carpet.script.CarpetScriptServer; import carpet.api.settings.CarpetRule; @@ -129,7 +128,7 @@ public static void onServerLoadedWorlds(MinecraftServer minecraftServer) public static void tick(MinecraftServer server) { - TickRateManager trm = ((MinecraftServerInterface)server).getTickRateManager(); + ServerTickRateManager trm = ((MinecraftServerInterface)server).getTickRateManager(); trm.tick(); HUDController.update_hud(server, null); if (scriptServer != null) scriptServer.tick(); @@ -229,9 +228,6 @@ public static void onServerClosed(MinecraftServer server) extensions.forEach(e -> e.onServerClosed(server)); minecraft_server = null; } - - // this for whatever reason gets called multiple times even when joining; - TickSpeed.resetClient(); } public static void onServerDoneClosing(MinecraftServer server) { diff --git a/src/main/java/carpet/commands/SpawnCommand.java b/src/main/java/carpet/commands/SpawnCommand.java index 62bbb16a02..b3edf1c56a 100644 --- a/src/main/java/carpet/commands/SpawnCommand.java +++ b/src/main/java/carpet/commands/SpawnCommand.java @@ -4,7 +4,7 @@ import carpet.fakes.MinecraftServerInterface; import carpet.fakes.SpawnGroupInterface; import carpet.helpers.HopperCounter; -import carpet.helpers.TickRateManager; +import carpet.helpers.ServerTickRateManager; import carpet.utils.CommandHelper; import carpet.utils.Messenger; import carpet.utils.SpawnReporter; @@ -199,8 +199,8 @@ private static int runTest(CommandSourceStack source, int ticks, String counter) // tick warp 0 - TickRateManager trm = ((MinecraftServerInterface)source.getServer()).getTickRateManager(); - trm.tickrate_advance(null, 0, null, null); + ServerTickRateManager trm = ((MinecraftServerInterface)source.getServer()).getTickRateManager(); + trm.requestGameToWarpSpeed(null, 0, null, null); // tick warp given player CommandSourceStack csource = null; ServerPlayer player = null; @@ -212,7 +212,7 @@ private static int runTest(CommandSourceStack source, int ticks, String counter) catch (CommandSyntaxException ignored) { } - trm.tickrate_advance(player, ticks, null, csource); + trm.requestGameToWarpSpeed(player, ticks, null, csource); Messenger.m(source, String.format("gi Started spawn test for %d ticks", ticks)); return 1; } diff --git a/src/main/java/carpet/commands/TickCommand.java b/src/main/java/carpet/commands/TickCommand.java index 8f0130ef7c..5b3bcda459 100644 --- a/src/main/java/carpet/commands/TickCommand.java +++ b/src/main/java/carpet/commands/TickCommand.java @@ -2,7 +2,7 @@ import carpet.CarpetSettings; import carpet.fakes.MinecraftServerInterface; -import carpet.helpers.TickRateManager; +import carpet.helpers.ServerTickRateManager; import carpet.network.ServerNetworkHandler; import carpet.utils.CarpetProfiler; import carpet.utils.CommandHelper; @@ -73,33 +73,33 @@ public static void register(CommandDispatcher dispatcher, Co private static int setTps(CommandSourceStack source, float tps) { - TickRateManager trm = ((MinecraftServerInterface)source.getServer()).getTickRateManager(); - trm.tickrate(tps, true); + ServerTickRateManager trm = ((MinecraftServerInterface)source.getServer()).getTickRateManager(); + trm.setTickRate(tps, true); queryTps(source); return (int)tps; } private static int queryTps(CommandSourceStack source) { - TickRateManager trm = ((MinecraftServerInterface)source.getServer()).getTickRateManager(); + ServerTickRateManager trm = ((MinecraftServerInterface)source.getServer()).getTickRateManager(); - Messenger.m(source, "w Current tps is: ",String.format("wb %.1f", trm.tickrate)); - return (int) trm.tickrate; + Messenger.m(source, "w Current tps is: ",String.format("wb %.1f", trm.tickrate())); + return (int) trm.tickrate(); } private static int setWarp(CommandSourceStack source, int advance, String tail_command) { ServerPlayer player = source.getPlayer(); // may be null - TickRateManager trm = ((MinecraftServerInterface)source.getServer()).getTickRateManager(); - Component message = trm.tickrate_advance(player, advance, tail_command, source); + ServerTickRateManager trm = ((MinecraftServerInterface)source.getServer()).getTickRateManager(); + Component message = trm.requestGameToWarpSpeed(player, advance, tail_command, source); source.sendSuccess(() -> message, false); return 1; } private static int freezeStatus(CommandSourceStack source) { - TickRateManager trm = ((MinecraftServerInterface)source.getServer()).getTickRateManager(); - if(trm.isPaused()) + ServerTickRateManager trm = ((MinecraftServerInterface)source.getServer()).getTickRateManager(); + if(trm.gameIsPaused()) { Messenger.m(source, "gi Freeze Status: Game is "+(trm.deeplyFrozen()?"deeply ":"")+"frozen"); } @@ -112,9 +112,9 @@ private static int freezeStatus(CommandSourceStack source) private static int setFreeze(CommandSourceStack source, boolean isDeep, boolean freeze) { - TickRateManager trm = ((MinecraftServerInterface)source.getServer()).getTickRateManager(); + ServerTickRateManager trm = ((MinecraftServerInterface)source.getServer()).getTickRateManager(); trm.setFrozenState(freeze, isDeep); - if (trm.isPaused()) + if (trm.gameIsPaused()) { Messenger.m(source, "gi Game is "+(isDeep?"deeply ":"")+"frozen"); } @@ -127,24 +127,24 @@ private static int setFreeze(CommandSourceStack source, boolean isDeep, boolean private static int toggleFreeze(CommandSourceStack source, boolean isDeep) { - TickRateManager trm = ((MinecraftServerInterface)source.getServer()).getTickRateManager(); - return setFreeze(source, isDeep, !trm.isPaused()); + ServerTickRateManager trm = ((MinecraftServerInterface)source.getServer()).getTickRateManager(); + return setFreeze(source, isDeep, !trm.gameIsPaused()); } private static int step(CommandSourceStack source, int advance) { - TickRateManager trm = ((MinecraftServerInterface)source.getServer()).getTickRateManager(); - trm.add_ticks_to_run_in_pause(advance); + ServerTickRateManager trm = ((MinecraftServerInterface)source.getServer()).getTickRateManager(); + trm.stepGameIfPaused(advance); Messenger.m(source, "gi Stepping " + advance + " tick" + (advance != 1 ? "s" : "")); return 1; } private static int toggleSuperHot(CommandSourceStack source) { - TickRateManager trm = ((MinecraftServerInterface)source.getServer()).getTickRateManager(); - trm.is_superHot = !trm.is_superHot; + ServerTickRateManager trm = ((MinecraftServerInterface)source.getServer()).getTickRateManager(); + trm.setSuperHot(!trm.isSuperHot()); ServerNetworkHandler.updateSuperHotStateToConnectedPlayers(source.getServer()); - if (trm.is_superHot) + if (trm.isSuperHot()) { Messenger.m(source, "gi Superhot enabled"); } diff --git a/src/main/java/carpet/fakes/ClientLevelInterface.java b/src/main/java/carpet/fakes/ClientLevelInterface.java new file mode 100644 index 0000000000..6ecdf58a1e --- /dev/null +++ b/src/main/java/carpet/fakes/ClientLevelInterface.java @@ -0,0 +1,8 @@ +package carpet.fakes; + +import carpet.helpers.TickRateManager; + +public interface ClientLevelInterface +{ + TickRateManager getTickRateManager(); +} diff --git a/src/main/java/carpet/fakes/MinecraftInterface.java b/src/main/java/carpet/fakes/MinecraftInterface.java new file mode 100644 index 0000000000..63553267b3 --- /dev/null +++ b/src/main/java/carpet/fakes/MinecraftInterface.java @@ -0,0 +1,10 @@ +package carpet.fakes; + +import carpet.helpers.TickRateManager; + +import java.util.Optional; + +public interface MinecraftInterface +{ + Optional getTickRateManager(); +} diff --git a/src/main/java/carpet/fakes/MinecraftServerInterface.java b/src/main/java/carpet/fakes/MinecraftServerInterface.java index ce2466d1b8..cf3fd479b7 100644 --- a/src/main/java/carpet/fakes/MinecraftServerInterface.java +++ b/src/main/java/carpet/fakes/MinecraftServerInterface.java @@ -3,7 +3,7 @@ import java.util.Map; import java.util.function.BooleanSupplier; -import carpet.helpers.TickRateManager; +import carpet.helpers.ServerTickRateManager; import carpet.script.CarpetScriptServer; import net.minecraft.core.RegistryAccess; import net.minecraft.resources.ResourceKey; @@ -25,5 +25,5 @@ public interface MinecraftServerInterface void addScriptServer(CarpetScriptServer scriptServer); CarpetScriptServer getScriptServer(); - TickRateManager getTickRateManager(); + ServerTickRateManager getTickRateManager(); } diff --git a/src/main/java/carpet/helpers/ServerTickRateManager.java b/src/main/java/carpet/helpers/ServerTickRateManager.java new file mode 100644 index 0000000000..775acf0b3d --- /dev/null +++ b/src/main/java/carpet/helpers/ServerTickRateManager.java @@ -0,0 +1,246 @@ +package carpet.helpers; + +import carpet.CarpetServer; +import carpet.network.ServerNetworkHandler; +import carpet.utils.Messenger; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.Commands; +import net.minecraft.network.chat.Component; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerPlayer; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.BiConsumer; + +public class ServerTickRateManager extends TickRateManager +{ + private long remainingWarpTicks = 0; + private long tickWarpStartTime = 0; + private long scheduledCurrentWarpTicks = 0; + private ServerPlayer warpResponsiblePlayer = null; + private String tickWarpCallback = null; + private CommandSourceStack warpResponsibleSource = null; + + private MinecraftServer server; + + public ServerTickRateManager(MinecraftServer server) { + this.server = server; + } + + public boolean isInWarpSpeed() + { + return tickWarpStartTime != 0; + } + + /** + * Whether or not the game is deeply frozen. + * This can be used for things that you may not normally want + * to freeze, but may need to in some situations. + * This should be checked with {@link #runGameElements} to make sure the + * current tick is actually frozen, not only the game + * + * @return Whether or not the game is deeply frozen. + */ + public boolean deeplyFrozen() + { + return deepFreeze; + } + + /** + * Used to update the frozen state of the game. + * Handles connected clients as well. + * + * @param isPaused Whether or not the game is paused + * @param isDeepFreeze Whether or not the game is deeply frozen + */ + @Override + public void setFrozenState(boolean isPaused, boolean isDeepFreeze) + { + super.setFrozenState(isPaused, isDeepFreeze); + ServerNetworkHandler.updateFrozenStateToConnectedPlayers(server); + } + + + public void resetPlayerActivity() + { + if (playerActivityTimeout < PLAYER_GRACE) + { + playerActivityTimeout = PLAYER_GRACE; + ServerNetworkHandler.updateTickPlayerActiveTimeoutToConnectedPlayers(server); + } + } + + public void stepGameIfPaused(int ticks) + { + playerActivityTimeout = PLAYER_GRACE + ticks; + ServerNetworkHandler.updateTickPlayerActiveTimeoutToConnectedPlayers(server); + } + + public Component requestGameToWarpSpeed(ServerPlayer player, int advance, String callback, CommandSourceStack source) + { + if (0 == advance) + { + tickWarpCallback = null; + if (source != warpResponsibleSource) + { + warpResponsibleSource = null; + } + if (remainingWarpTicks > 0) + { + finishTickWarp(); + warpResponsibleSource = null; + return Messenger.c("gi Warp interrupted"); + } + return Messenger.c("ri No warp in progress"); + } + if (remainingWarpTicks > 0) + { + String who = "Another player"; + if (warpResponsiblePlayer != null) + { + who = warpResponsiblePlayer.getScoreboardName(); + } + return Messenger.c("l " + who + " is already advancing time at the moment. Try later or ask them"); + } + warpResponsiblePlayer = player; + tickWarpStartTime = System.nanoTime(); + scheduledCurrentWarpTicks = advance; + remainingWarpTicks = advance; + tickWarpCallback = callback; + warpResponsibleSource = source; + return Messenger.c("gi Warp speed ...."); + } + + // should be private + public void finishTickWarp() + { + + long completed_ticks = scheduledCurrentWarpTicks - remainingWarpTicks; + double milis_to_complete = System.nanoTime() - tickWarpStartTime; + if (milis_to_complete == 0.0) + { + milis_to_complete = 1.0; + } + milis_to_complete /= 1000000.0; + int tps = (int) (1000.0D * completed_ticks / milis_to_complete); + double mspt = (1.0 * milis_to_complete) / completed_ticks; + scheduledCurrentWarpTicks = 0; + tickWarpStartTime = 0; + if (tickWarpCallback != null) + { + Commands icommandmanager = warpResponsibleSource.getServer().getCommands(); + try + { + icommandmanager.performPrefixedCommand(warpResponsibleSource, tickWarpCallback); + } + catch (Throwable var23) + { + if (warpResponsiblePlayer != null) + { + Messenger.m(warpResponsiblePlayer, "r Command Callback failed - unknown error: ", "rb /" + tickWarpCallback, "/" + tickWarpCallback); + } + } + tickWarpCallback = null; + warpResponsibleSource = null; + } + if (warpResponsiblePlayer != null) + { + Messenger.m(warpResponsiblePlayer, String.format("gi ... Time warp completed with %d tps, or %.2f mspt", tps, mspt)); + warpResponsiblePlayer = null; + } + else + { + Messenger.print_server_message(CarpetServer.minecraft_server, String.format("... Time warp completed with %d tps, or %.2f mspt", tps, mspt)); + } + remainingWarpTicks = 0; + + } + + public boolean continueWarp() + { + if (!runGameElements) + // Returning false so we don't have to run at max speed when doing nothing + { + return false; + } + if (remainingWarpTicks > 0) + { + if (remainingWarpTicks == scheduledCurrentWarpTicks) //first call after previous tick, adjust start time + { + tickWarpStartTime = System.nanoTime(); + } + remainingWarpTicks -= 1; + return true; + } + else + { + finishTickWarp(); + return false; + } + } + + /** + * Functional interface that listens for tickrate changes. This is + * implemented to allow tickrate compatibility with other mods etc. + */ + private final Map> tickrateListeners = new HashMap<>(); + private static final float MIN_TICKRATE = 0.01f; + + //unused - mod compat reasons + @Override + public void setTickRate(float rate) + { + setTickRate(rate, true); + } + + public void setTickRate(float rate, boolean update) + { + super.setTickRate(rate); + if (update) + { + notifyTickrateListeners("carpet"); + } + } + + private void tickrateChanged(String modId, float rate) + { + // Other mods might change the tickrate in a slightly + // different way. Also allow for tickrates that don't + // divide into 1000 here. + + if (rate < MIN_TICKRATE) + { + rate = MIN_TICKRATE; + } + + tickrate = rate; + mspt = 1000.0f / tickrate; + + notifyTickrateListeners(modId); + } + + private void notifyTickrateListeners(String originModId) + { + synchronized (tickrateListeners) + { + for (Map.Entry> listenerEntry : tickrateListeners.entrySet()) + { + if (originModId == null || !originModId.equals(listenerEntry.getKey())) + { + listenerEntry.getValue().accept(originModId, tickrate); + } + } + } + ServerNetworkHandler.updateTickSpeedToConnectedPlayers(server); + } + + public BiConsumer addTickrateListener(String modId, BiConsumer tickrateListener) + { + synchronized (tickrateListeners) + { + tickrateListeners.put(modId, tickrateListener); + } + return this::tickrateChanged; + } +} diff --git a/src/main/java/carpet/helpers/TickRateManager.java b/src/main/java/carpet/helpers/TickRateManager.java index 0534792776..dca76a3933 100644 --- a/src/main/java/carpet/helpers/TickRateManager.java +++ b/src/main/java/carpet/helpers/TickRateManager.java @@ -1,292 +1,96 @@ package carpet.helpers; -import carpet.CarpetServer; -import carpet.network.ServerNetworkHandler; -import carpet.utils.Messenger; -import net.minecraft.commands.CommandSourceStack; -import net.minecraft.commands.Commands; -import net.minecraft.network.chat.Component; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.level.ServerPlayer; - -import java.util.HashMap; -import java.util.Map; -import java.util.function.BiConsumer; - public class TickRateManager { public static final int PLAYER_GRACE = 2; - public float tickrate = 20.0f; - public float mspt = 50.0f; - public long time_bias = 0; - public long time_warp_start_time = 0; - public long time_warp_scheduled_ticks = 0; - public ServerPlayer time_advancerer = null; - public String tick_warp_callback = null; - public CommandSourceStack tick_warp_sender = null; - public int player_active_timeout = 0; - public boolean process_entities = true; - private boolean deepFreeze = false; - private boolean is_paused = false; - public boolean is_superHot = false; - - private MinecraftServer server; - - public TickRateManager(MinecraftServer server) { - this.server = server; + protected float tickrate = 20.0f; + protected float mspt = 50.0f; + protected int playerActivityTimeout = 0; + protected boolean runGameElements = true; + // deep freeze is onlyu used serverside + protected boolean deepFreeze = false; + protected boolean isGamePaused = false; + protected boolean isSuperHot = false; + + public void setTickRate(float rate) + { + tickrate = rate; + long msptt = (long) (1000.0 / tickrate); + if (msptt <= 0L) + { + msptt = 1L; + tickrate = 1000.0f; + } + mspt = msptt; } + public float tickrate() + { + return tickrate; + } /** * @return Whether or not the game is in a frozen state. - * You should normally use {@link #process_entities} instead, + * You should normally use {@link #runGameElements} instead, * since that one accounts for tick steps and superhot */ - public boolean isPaused() + public boolean gameIsPaused() { - return is_paused; + return isGamePaused; } - public boolean process_entities() - { - return process_entities; + public float mspt() { + return mspt; } - /** - * Whether or not the game is deeply frozen. - * This can be used for things that you may not normally want - * to freeze, but may need to in some situations. - * This should be checked with {@link #process_entities} to make sure the - * current tick is actually frozen, not only the game - * - * @return Whether or not the game is deeply frozen. - */ - public boolean deeplyFrozen() - { - return deepFreeze; - } - - /** - * Used to update the frozen state of the game. - * Handles connected clients as well. - * - * @param isPaused Whether or not the game is paused - * @param isDeepFreeze Whether or not the game is deeply frozen - */ - public void setFrozenState(boolean isPaused, boolean isDeepFreeze) + public boolean runsNormally() { - is_paused = isPaused; - deepFreeze = isPaused ? isDeepFreeze : false; - ServerNetworkHandler.updateFrozenStateToConnectedPlayers(server); + return runGameElements; } - - public void reset_player_active_timeout() + public boolean isSuperHot() { - if (player_active_timeout < PLAYER_GRACE) - { - player_active_timeout = PLAYER_GRACE; - ServerNetworkHandler.updateTickPlayerActiveTimeoutToConnectedPlayers(server); - } + return isSuperHot; } - public void add_ticks_to_run_in_pause(int ticks) + public void setPlayerActiveTimeout(int timeout) { - player_active_timeout = PLAYER_GRACE + ticks; - ServerNetworkHandler.updateTickPlayerActiveTimeoutToConnectedPlayers(server); + playerActivityTimeout = timeout; } - public Component tickrate_advance(ServerPlayer player, int advance, String callback, CommandSourceStack source) + public int getPlayerActiveTimeout() { - if (0 == advance) - { - tick_warp_callback = null; - if (source != tick_warp_sender) - { - tick_warp_sender = null; - } - if (time_bias > 0) - { - finish_time_warp(); - tick_warp_sender = null; - return Messenger.c("gi Warp interrupted"); - } - return Messenger.c("ri No warp in progress"); - } - if (time_bias > 0) - { - String who = "Another player"; - if (time_advancerer != null) - { - who = time_advancerer.getScoreboardName(); - } - return Messenger.c("l " + who + " is already advancing time at the moment. Try later or ask them"); - } - time_advancerer = player; - time_warp_start_time = System.nanoTime(); - time_warp_scheduled_ticks = advance; - time_bias = advance; - tick_warp_callback = callback; - tick_warp_sender = source; - return Messenger.c("gi Warp speed ...."); + return playerActivityTimeout; } - public void finish_time_warp() + public void setFrozenState(boolean isPaused, boolean isDeepFreeze) { - - long completed_ticks = time_warp_scheduled_ticks - time_bias; - double milis_to_complete = System.nanoTime() - time_warp_start_time; - if (milis_to_complete == 0.0) - { - milis_to_complete = 1.0; - } - milis_to_complete /= 1000000.0; - int tps = (int) (1000.0D * completed_ticks / milis_to_complete); - double mspt = (1.0 * milis_to_complete) / completed_ticks; - time_warp_scheduled_ticks = 0; - time_warp_start_time = 0; - if (tick_warp_callback != null) - { - Commands icommandmanager = tick_warp_sender.getServer().getCommands(); - try - { - icommandmanager.performPrefixedCommand(tick_warp_sender, tick_warp_callback); - } - catch (Throwable var23) - { - if (time_advancerer != null) - { - Messenger.m(time_advancerer, "r Command Callback failed - unknown error: ", "rb /" + tick_warp_callback, "/" + tick_warp_callback); - } - } - tick_warp_callback = null; - tick_warp_sender = null; - } - if (time_advancerer != null) - { - Messenger.m(time_advancerer, String.format("gi ... Time warp completed with %d tps, or %.2f mspt", tps, mspt)); - time_advancerer = null; - } - else - { - Messenger.print_server_message(CarpetServer.minecraft_server, String.format("... Time warp completed with %d tps, or %.2f mspt", tps, mspt)); - } - time_bias = 0; - + isGamePaused = isPaused; + deepFreeze = isPaused && isDeepFreeze; } - public boolean continueWarp() + public void setSuperHot(boolean isSuperHot) { - if (!process_entities) - // Returning false so we don't have to run at max speed when doing nothing - { - return false; - } - if (time_bias > 0) - { - if (time_bias == time_warp_scheduled_ticks) //first call after previous tick, adjust start time - { - time_warp_start_time = System.nanoTime(); - } - time_bias -= 1; - return true; - } - else - { - finish_time_warp(); - return false; - } + this.isSuperHot = isSuperHot; } public void tick() { - if (player_active_timeout > 0) + if (playerActivityTimeout > 0) { - player_active_timeout--; + playerActivityTimeout--; } - if (is_paused) + if (isGamePaused) { - process_entities = player_active_timeout >= PLAYER_GRACE; + runGameElements = playerActivityTimeout >= PLAYER_GRACE; } - else if (is_superHot) + else if (isSuperHot) { - process_entities = player_active_timeout > 0; + runGameElements = playerActivityTimeout > 0; } else { - process_entities = true; - } - } - - /** - * Functional interface that listens for tickrate changes. This is - * implemented to allow tickrate compatibility with other mods etc. - */ - private final Map> tickrateListeners = new HashMap<>(); - private static final float MIN_TICKRATE = 0.01f; - - //unused - mod compat reasons - public void tickrate(float rate) - { - tickrate(rate, true); - } - - public void tickrate(float rate, boolean update) - { - tickrate = rate; - long msptt = (long) (1000.0 / tickrate); - if (msptt <= 0L) - { - msptt = 1L; - tickrate = 1000.0f; - } - - this.mspt = msptt; - - if (update) - { - notifyTickrateListeners("carpet"); - } - } - - private void tickrateChanged(String modId, float rate) - { - // Other mods might change the tickrate in a slightly - // different way. Also allow for tickrates that don't - // divide into 1000 here. - - if (rate < MIN_TICKRATE) - { - rate = MIN_TICKRATE; - } - - tickrate = rate; - mspt = 1000.0f / tickrate; - - notifyTickrateListeners(modId); - } - - private void notifyTickrateListeners(String originModId) - { - synchronized (tickrateListeners) - { - for (Map.Entry> listenerEntry : tickrateListeners.entrySet()) - { - if (originModId == null || !originModId.equals(listenerEntry.getKey())) - { - listenerEntry.getValue().accept(originModId, Float.valueOf(tickrate)); - } - } - } - ServerNetworkHandler.updateTickSpeedToConnectedPlayers(server); - } - - public BiConsumer addTickrateListener(String modId, BiConsumer tickrateListener) - { - synchronized (tickrateListeners) - { - tickrateListeners.put(modId, tickrateListener); + runGameElements = true; } - return this::tickrateChanged; } } diff --git a/src/main/java/carpet/helpers/TickSpeed.java b/src/main/java/carpet/helpers/TickSpeed.java index a30f437e51..e74be60eb3 100644 --- a/src/main/java/carpet/helpers/TickSpeed.java +++ b/src/main/java/carpet/helpers/TickSpeed.java @@ -10,27 +10,28 @@ import carpet.CarpetServer; import carpet.utils.Messenger; +@Deprecated(forRemoval = true, since = "now") public class TickSpeed { - private static Optional gTRM() { + private static Optional gTRM() { if (CarpetServer.minecraft_server == null) return Optional.empty(); return Optional.of(((MinecraftServerInterface)CarpetServer.minecraft_server).getTickRateManager()); } public static boolean process_entities() { - return gTRM().map(trm -> trm.process_entities).orElse(true); + return gTRM().map(ServerTickRateManager::runsNormally).orElse(true); } public static float mspt() { - return gTRM().map(trm -> trm.mspt).orElse(50.0f); + return gTRM().map(ServerTickRateManager::mspt).orElse(50.0f); } public static boolean isPaused() { - return gTRM().map(TickRateManager::isPaused).orElse(false); + return gTRM().map(ServerTickRateManager::gameIsPaused).orElse(false); } public static boolean deeplyFrozen() { - return gTRM().map(TickRateManager::deeplyFrozen).orElse(false); + return gTRM().map(ServerTickRateManager::deeplyFrozen).orElse(false); } public static void setFrozenState(boolean isPaused, boolean isDeepFreeze) { @@ -39,7 +40,7 @@ public static void setFrozenState(boolean isPaused, boolean isDeepFreeze) { public static void reset_player_active_timeout() { - gTRM().ifPresent(TickRateManager::reset_player_active_timeout); + gTRM().ifPresent(ServerTickRateManager::resetPlayerActivity); } public static void reset() @@ -49,33 +50,33 @@ public static void reset() public static void add_ticks_to_run_in_pause(int ticks) { - gTRM().ifPresent(trm -> trm.add_ticks_to_run_in_pause(ticks)); + gTRM().ifPresent(trm -> trm.stepGameIfPaused(ticks)); } public static Component tickrate_advance(ServerPlayer player, int advance, String callback, CommandSourceStack source) { - return gTRM().map(trm -> trm.tickrate_advance(player, advance, callback, source)).orElse(Messenger.c("ri Tickrate management not enabled")); + return gTRM().map(trm -> trm.requestGameToWarpSpeed(player, advance, callback, source)).orElse(Messenger.c("ri Tickrate management not enabled")); } public static void finish_time_warp() { - gTRM().ifPresent(TickRateManager::finish_time_warp); + gTRM().ifPresent(ServerTickRateManager::finishTickWarp); } public static boolean continueWarp() { - return gTRM().map(TickRateManager::continueWarp).orElse(false); + return gTRM().map(ServerTickRateManager::continueWarp).orElse(false); } public static void tick() { - gTRM().ifPresent(TickRateManager::tick); + gTRM().ifPresent(ServerTickRateManager::tick); } //unused - mod compat reasons public static void tickrate(float rate) {tickrate(rate, true);} public static void tickrate(float rate, boolean update) { - gTRM().ifPresent(trm -> trm.tickrate(rate, update)); + gTRM().ifPresent(trm -> trm.setTickRate(rate, update)); } @@ -147,7 +148,7 @@ public static void tickClient() } if (is_paused) { - process_entities = player_active_timeout >= TickRateManager.PLAYER_GRACE; + process_entities = player_active_timeout >= ServerTickRateManager.PLAYER_GRACE; } else if (is_superHot) { diff --git a/src/main/java/carpet/logging/HUDController.java b/src/main/java/carpet/logging/HUDController.java index 6b29a6fa69..6167883945 100644 --- a/src/main/java/carpet/logging/HUDController.java +++ b/src/main/java/carpet/logging/HUDController.java @@ -3,8 +3,7 @@ import carpet.CarpetServer; import carpet.fakes.MinecraftServerInterface; import carpet.helpers.HopperCounter; -import carpet.helpers.TickRateManager; -import carpet.helpers.TickSpeed; +import carpet.helpers.ServerTickRateManager; import carpet.logging.logHelpers.PacketCounter; import carpet.utils.Messenger; import carpet.utils.SpawnReporter; @@ -118,18 +117,18 @@ public static void update_hud(MinecraftServer server, List force) } private static Component [] send_tps_display(MinecraftServer server) { - final OptionalDouble averageTPS = Arrays.stream(server.tickTimes).average(); - TickRateManager trm = ((MinecraftServerInterface)server).getTickRateManager(); + OptionalDouble averageTPS = Arrays.stream(server.tickTimes).average(); + ServerTickRateManager trm = ((MinecraftServerInterface)server).getTickRateManager(); if (averageTPS.isEmpty()) { return new Component[]{Component.literal("No TPS data available")}; } double MSPT = Arrays.stream(server.tickTimes).average().getAsDouble() * 1.0E-6D; - double TPS = 1000.0D / Math.max((trm.time_warp_start_time != 0)?0.0:trm.mspt, MSPT); - if (trm.isPaused()) { + double TPS = 1000.0D / Math.max(trm.isInWarpSpeed()?0.0:trm.mspt(), MSPT); + if (trm.gameIsPaused()) { TPS = 0; } - String color = Messenger.heatmap_color(MSPT,trm.mspt); + String color = Messenger.heatmap_color(MSPT,trm.mspt()); return new Component[]{Messenger.c( "g TPS: ", String.format(Locale.US, "%s %.1f",color, TPS), "g MSPT: ", String.format(Locale.US,"%s %.1f", color, MSPT))}; diff --git a/src/main/java/carpet/mixins/BoundTickingBlockEntity_tickMixin.java b/src/main/java/carpet/mixins/BoundTickingBlockEntity_tickMixin.java index b36a5c4080..370fd25cb8 100644 --- a/src/main/java/carpet/mixins/BoundTickingBlockEntity_tickMixin.java +++ b/src/main/java/carpet/mixins/BoundTickingBlockEntity_tickMixin.java @@ -1,8 +1,9 @@ package carpet.mixins; +import carpet.fakes.ClientLevelInterface; import carpet.fakes.MinecraftServerInterface; import carpet.helpers.TickRateManager; -import carpet.helpers.TickSpeed; +import carpet.helpers.ServerTickRateManager; import carpet.utils.CarpetProfiler; import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerLevel; @@ -37,14 +38,16 @@ private void startTileEntitySection(CallbackInfo ci) )) private void checkProcessBEs(BlockEntityTicker blockEntityTicker, Level world, BlockPos pos, BlockState state, T blockEntity) { + // these two branches are identical, but we need to check the world type and inferfaces if (world.isClientSide()) { // client - if (TickSpeed.process_entitiesClient()) blockEntityTicker.tick(world, pos, state, blockEntity); + TickRateManager tickRateManager = ((ClientLevelInterface)world).getTickRateManager(); + if (tickRateManager.runsNormally()) blockEntityTicker.tick(world, pos, state, blockEntity); } else { // server ServerLevel serverWorld = (ServerLevel) world; - TickRateManager tickRateManager = ((MinecraftServerInterface)serverWorld.getServer()).getTickRateManager(); - if (tickRateManager.process_entities()) blockEntityTicker.tick(world, pos, state, blockEntity); + ServerTickRateManager serverTickRateManager = ((MinecraftServerInterface)serverWorld.getServer()).getTickRateManager(); + if (serverTickRateManager.runsNormally()) blockEntityTicker.tick(world, pos, state, blockEntity); } } diff --git a/src/main/java/carpet/mixins/ClientLevel_tickSpeedMixin.java b/src/main/java/carpet/mixins/ClientLevel_tickSpeedMixin.java new file mode 100644 index 0000000000..50d0de5e04 --- /dev/null +++ b/src/main/java/carpet/mixins/ClientLevel_tickSpeedMixin.java @@ -0,0 +1,28 @@ +package carpet.mixins; + +import carpet.fakes.ClientLevelInterface; +import carpet.helpers.TickRateManager; +import net.minecraft.client.multiplayer.ClientLevel; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(ClientLevel.class) +public class ClientLevel_tickSpeedMixin implements ClientLevelInterface +{ + + private TickRateManager tickRateManager; + + @Inject(method = "", at = @At("RETURN")) + private void onInit(CallbackInfo ci) + { + this.tickRateManager = new TickRateManager(); + } + + @Override + public TickRateManager getTickRateManager() + { + return tickRateManager; + } +} diff --git a/src/main/java/carpet/mixins/ClientPacketListener_customPacketsMixin.java b/src/main/java/carpet/mixins/ClientPacketListener_customPacketsMixin.java index 64f0735ce4..ce0736453c 100644 --- a/src/main/java/carpet/mixins/ClientPacketListener_customPacketsMixin.java +++ b/src/main/java/carpet/mixins/ClientPacketListener_customPacketsMixin.java @@ -1,6 +1,5 @@ package carpet.mixins; -import carpet.helpers.TickSpeed; import carpet.network.CarpetClient; import carpet.network.ClientNetworkHandler; import net.minecraft.client.Minecraft; @@ -34,13 +33,11 @@ private void onOnCustomPayload(ClientboundCustomPayloadPacket packet, CallbackIn private void onGameJoined(ClientboundLoginPacket packet, CallbackInfo info) { CarpetClient.gameJoined(minecraft.player); - TickSpeed.resetClient(); } @Inject(method = "onDisconnect", at = @At("HEAD")) private void onCMDisconnected(Component reason, CallbackInfo ci) { CarpetClient.disconnect(); - TickSpeed.resetClient(); } } diff --git a/src/main/java/carpet/mixins/LevelRenderer_pausedShakeMixin.java b/src/main/java/carpet/mixins/LevelRenderer_pausedShakeMixin.java index 44b99aaacc..941f61ac32 100644 --- a/src/main/java/carpet/mixins/LevelRenderer_pausedShakeMixin.java +++ b/src/main/java/carpet/mixins/LevelRenderer_pausedShakeMixin.java @@ -1,8 +1,10 @@ package carpet.mixins; +import carpet.fakes.ClientLevelInterface; import carpet.fakes.MinecraftClientInferface; -import carpet.helpers.TickSpeed; +import carpet.helpers.TickRateManager; import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.renderer.LevelRenderer; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -15,6 +17,7 @@ public class LevelRenderer_pausedShakeMixin { @Shadow @Final private Minecraft minecraft; + @Shadow private ClientLevel level; float initial = -1234.0f; // require 0 is for optifine being a bitch as it usually is. @@ -25,7 +28,8 @@ public class LevelRenderer_pausedShakeMixin private float changeTickPhase(float previous) { initial = previous; - if (!TickSpeed.process_entitiesClient()) + TickRateManager trm = ((ClientLevelInterface)level).getTickRateManager(); + if (!trm.runsNormally()) return ((MinecraftClientInferface)minecraft).getPausedTickDelta(); return previous; } diff --git a/src/main/java/carpet/mixins/Level_tickMixin.java b/src/main/java/carpet/mixins/Level_tickMixin.java index 898db3d7cd..d562dbfb7b 100644 --- a/src/main/java/carpet/mixins/Level_tickMixin.java +++ b/src/main/java/carpet/mixins/Level_tickMixin.java @@ -1,10 +1,12 @@ package carpet.mixins; +import carpet.fakes.ClientLevelInterface; import carpet.fakes.LevelInterface; import carpet.fakes.MinecraftServerInterface; import carpet.helpers.TickRateManager; -import carpet.helpers.TickSpeed; +import carpet.helpers.ServerTickRateManager; import carpet.utils.CarpetProfiler; +import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.redstone.NeighborUpdater; import org.spongepowered.asm.mixin.Final; @@ -53,55 +55,26 @@ private void startBlockEntities(CallbackInfo ci) { private void endBlockEntities(CallbackInfo ci) { CarpetProfiler.end_current_section(currentSection); } -/* - @Inject(method = "tickBlockEntities", locals = LocalCapture.CAPTURE_FAILHARD, at = @At( - value = "INVOKE", - target = "Lnet/minecraft/class_5562;method_31704()Z", - shift = At.Shift.BEFORE, - ordinal = 0 - )) - private void startTileEntitySection(CallbackInfo ci, Profiler profiler_1, Iterator i, class_5562 lv) - { - entitySection = CarpetProfiler.start_block_entity_section((World)(Object)this, (BlockEntity) lv, CarpetProfiler.TYPE.TILEENTITY); - } - @Redirect(method = "tickBlockEntities", at = @At( - value = "INVOKE", - target = "Lnet/minecraft/class_5562;method_31704()Z", - ordinal = 0 - )) // isRemoved() - private boolean checkProcessTEs(class_5562 class_5562) - { - return class_5562.method_31704() || !TickSpeed.process_entities; // blockEntity can be NULL? happened once with fake player - } - - @Inject(method = "tickBlockEntities", at = @At( - value = "INVOKE", - target = "Lnet/minecraft/class_5562;method_31703()V", - shift = At.Shift.AFTER, - ordinal = 0 - )) - private void endTileEntitySection(CallbackInfo ci) - { - CarpetProfiler.end_current_entity_section(entitySection); - } -*/ @Inject(method = "guardEntityTick", at = @At("HEAD"), cancellable = true) private void startEntity(Consumer consumer_1, Entity e, CallbackInfo ci) { // this shows that probably tick speed controller needs to be accessible through level referring to servers on server and client on clientLevel + // these two branches could also be merged into one generic for cloent and server if (!isClientSide) { ServerLevel serverLevel = (ServerLevel) (Object) this; - TickRateManager trm = ((MinecraftServerInterface)serverLevel.getServer()).getTickRateManager(); - if (!(trm.process_entities() || (e instanceof Player))) + ServerTickRateManager trm = ((MinecraftServerInterface)serverLevel.getServer()).getTickRateManager(); + if (!(trm.runsNormally() || (e instanceof Player))) { ci.cancel(); } } else { - if (!(TickSpeed.process_entitiesClient() || (e instanceof Player) || TickSpeed.isIs_superHotClient() && e.getControllingPassenger() instanceof Player)) + ClientLevel clientLevel = (ClientLevel) (Object) this; + TickRateManager trm = ((ClientLevelInterface)clientLevel).getTickRateManager(); + if (!(trm.runsNormally() || (e instanceof Player) || trm.isSuperHot() && e.getControllingPassenger() instanceof Player)) { ci.cancel(); } diff --git a/src/main/java/carpet/mixins/MinecraftMixin.java b/src/main/java/carpet/mixins/MinecraftMixin.java index 6a871aea52..525d05371f 100644 --- a/src/main/java/carpet/mixins/MinecraftMixin.java +++ b/src/main/java/carpet/mixins/MinecraftMixin.java @@ -1,7 +1,9 @@ package carpet.mixins; import carpet.CarpetServer; -import carpet.helpers.TickSpeed; +import carpet.fakes.ClientLevelInterface; +import carpet.helpers.TickRateManager; +import carpet.fakes.MinecraftInterface; import carpet.network.CarpetClient; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screens.Screen; @@ -12,8 +14,10 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import java.util.Optional; + @Mixin(Minecraft.class) -public class MinecraftMixin +public class MinecraftMixin implements MinecraftInterface { @Shadow public ClientLevel level; @@ -26,16 +30,19 @@ private void onCloseGame(Screen screen, CallbackInfo ci) @Inject(at = @At("HEAD"), method = "tick") private void onClientTick(CallbackInfo info) { if (this.level != null) { - TickSpeed.tickClient(); - if (CarpetServer.minecraft_server == null) // remote client only ? no - now any client - { - - } else { - // hmm, server should tick, rgiht? - //TickSpeed.tick(); - } - if (!TickSpeed.process_entitiesClient()) + getTickRateManager().ifPresent(TickRateManager::tick); + // hope server doesn't need to tick - should be handled by the server on its own + if (!getTickRateManager().map(TickRateManager::runsNormally).orElse(true)) CarpetClient.shapes.renewShapes(); } } + + @Override + public Optional getTickRateManager() + { + if (this.level != null) { + return Optional.of(((ClientLevelInterface)this.level).getTickRateManager()); + } + return Optional.empty(); + } } diff --git a/src/main/java/carpet/mixins/MinecraftServer_scarpetMixin.java b/src/main/java/carpet/mixins/MinecraftServer_scarpetMixin.java index b260416432..1dcbfffd75 100644 --- a/src/main/java/carpet/mixins/MinecraftServer_scarpetMixin.java +++ b/src/main/java/carpet/mixins/MinecraftServer_scarpetMixin.java @@ -88,7 +88,7 @@ public Map, ServerLevel> getCMWorlds() )) public void tickTasks(BooleanSupplier booleanSupplier_1, CallbackInfo ci) { - if (!getTickRateManager().process_entities()) + if (!getTickRateManager().runsNormally()) { return; } diff --git a/src/main/java/carpet/mixins/MinecraftServer_tickspeedMixin.java b/src/main/java/carpet/mixins/MinecraftServer_tickspeedMixin.java index 7962bb0f51..6daa46bb98 100644 --- a/src/main/java/carpet/mixins/MinecraftServer_tickspeedMixin.java +++ b/src/main/java/carpet/mixins/MinecraftServer_tickspeedMixin.java @@ -1,8 +1,7 @@ package carpet.mixins; import carpet.fakes.MinecraftServerInterface; -import carpet.helpers.TickRateManager; -import carpet.helpers.TickSpeed; +import carpet.helpers.ServerTickRateManager; import carpet.patches.CopyProfilerResult; import carpet.utils.CarpetProfiler; import net.minecraft.Util; @@ -69,18 +68,18 @@ public MinecraftServer_tickspeedMixin(String name) private float carpetMsptAccum = 0.0f; - private TickRateManager tickRateManager; + private ServerTickRateManager serverTickRateManager; @Inject(method = "", at = @At("RETURN")) private void onInit(CallbackInfo ci) { - tickRateManager = new TickRateManager((MinecraftServer)(Object)this); + serverTickRateManager = new ServerTickRateManager((MinecraftServer)(Object)this); } @Override - public TickRateManager getTickRateManager() + public ServerTickRateManager getTickRateManager() { - return tickRateManager; + return serverTickRateManager; } /** @@ -111,8 +110,8 @@ private void modifiedRunLoop(CallbackInfo ci) } long msThisTick = 0L; long long_1 = 0L; - float mspt = tickRateManager.mspt; - if (tickRateManager.time_warp_start_time != 0 && tickRateManager.continueWarp()) + float mspt = serverTickRateManager.mspt(); + if (serverTickRateManager.isInWarpSpeed() && serverTickRateManager.continueWarp()) { //making sure server won't flop after the warp or if the warp is interrupted this.nextTickTime = this.lastOverloadWarning = Util.getMillis(); @@ -151,9 +150,9 @@ private void modifiedRunLoop(CallbackInfo ci) //this.startMonitor(tickDurationMonitor); this.startMetricsRecordingTick(); this.profiler.push("tick"); - this.tickServer(tickRateManager.time_warp_start_time != 0 ? ()->true : this::haveTime); + this.tickServer(serverTickRateManager.isInWarpSpeed() ? ()->true : this::haveTime); this.profiler.popPush("nextTickWait"); - if (tickRateManager.time_warp_start_time != 0) // clearing all hanging tasks no matter what when warping + if (serverTickRateManager.isInWarpSpeed()) // clearing all hanging tasks no matter what when warping { while(this.runEveryTask()) {Thread.yield();} } diff --git a/src/main/java/carpet/mixins/ServerChunkCache_tickMixin.java b/src/main/java/carpet/mixins/ServerChunkCache_tickMixin.java index 51b7c41391..34d69c3eb6 100644 --- a/src/main/java/carpet/mixins/ServerChunkCache_tickMixin.java +++ b/src/main/java/carpet/mixins/ServerChunkCache_tickMixin.java @@ -2,7 +2,7 @@ import carpet.fakes.MinecraftServerInterface; import carpet.fakes.ThreadedAnvilChunkStorageInterface; -import carpet.helpers.TickRateManager; +import carpet.helpers.ServerTickRateManager; import carpet.utils.CarpetProfiler; import net.minecraft.server.level.DistanceManager; import org.spongepowered.asm.mixin.Final; @@ -80,7 +80,7 @@ private void stopSpawningSection(CallbackInfo ci) private boolean skipChunkTicking(ServerLevel serverWorld) { boolean debug = serverWorld.isDebug(); - if (!((MinecraftServerInterface)serverWorld.getServer()).getTickRateManager().process_entities()) + if (!((MinecraftServerInterface)serverWorld.getServer()).getTickRateManager().runsNormally()) { // simplified chunk tick iteration assuming world is frozen otherwise as suggested by Hadron67 // to be kept in sync with the original injection source @@ -107,8 +107,8 @@ private void pauseTicketSystem(DistanceManager distanceManager) { // pausing expiry of tickets // that will prevent also chunks from unloading, so require a deep frozen state - TickRateManager trm = ((MinecraftServerInterface) level.getServer()).getTickRateManager(); - if (!trm.process_entities() && trm.deeplyFrozen()) return; + ServerTickRateManager trm = ((MinecraftServerInterface) level.getServer()).getTickRateManager(); + if (!trm.runsNormally() && trm.deeplyFrozen()) return; distanceManager.purgeStaleTickets(); } diff --git a/src/main/java/carpet/mixins/ServerFunctionManager_tickMixin.java b/src/main/java/carpet/mixins/ServerFunctionManager_tickMixin.java index f428c41d74..471525435b 100644 --- a/src/main/java/carpet/mixins/ServerFunctionManager_tickMixin.java +++ b/src/main/java/carpet/mixins/ServerFunctionManager_tickMixin.java @@ -20,7 +20,7 @@ public class ServerFunctionManager_tickMixin @Inject(method = "tick", at = @At("HEAD"), cancellable = true) private void beforeDatapacks(CallbackInfo ci) { - if (! ((MinecraftServerInterface)server).getTickRateManager().process_entities()) + if (! ((MinecraftServerInterface)server).getTickRateManager().runsNormally()) { ci.cancel(); } diff --git a/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_tickMixin.java b/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_tickMixin.java index de670f1249..7c8e131503 100644 --- a/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_tickMixin.java +++ b/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_tickMixin.java @@ -27,7 +27,7 @@ private void checkMoves(ServerboundPlayerInputPacket p, CallbackInfo ci) { if (p.getXxa() != 0.0F || p.getZza() != 0.0F || p.isJumping() || p.isShiftKeyDown()) { - ((MinecraftServerInterface)player.getServer()).getTickRateManager().reset_player_active_timeout(); + ((MinecraftServerInterface)player.getServer()).getTickRateManager().resetPlayerActivity(); } } @@ -53,7 +53,7 @@ private void checkMove(ServerboundMovePlayerPacket p, CallbackInfo ci) { lastMoved = movedBy; lastMovedTick = player.getServer().getTickCount(); - ((MinecraftServerInterface)player.getServer()).getTickRateManager().reset_player_active_timeout(); + ((MinecraftServerInterface)player.getServer()).getTickRateManager().resetPlayerActivity(); } } } diff --git a/src/main/java/carpet/mixins/ServerLevel_tickMixin.java b/src/main/java/carpet/mixins/ServerLevel_tickMixin.java index 3784958f64..f68add3867 100644 --- a/src/main/java/carpet/mixins/ServerLevel_tickMixin.java +++ b/src/main/java/carpet/mixins/ServerLevel_tickMixin.java @@ -159,13 +159,13 @@ private void endRandomTicks(CallbackInfo ci) { )) private void tickWorldBorder(WorldBorder worldBorder) { - if (((MinecraftServerInterface)getServer()).getTickRateManager().process_entities()) worldBorder.tick(); + if (((MinecraftServerInterface)getServer()).getTickRateManager().runsNormally()) worldBorder.tick(); } @Inject(method = "advanceWeatherCycle", cancellable = true, at = @At("HEAD")) private void tickWeather(CallbackInfo ci) { - if (!((MinecraftServerInterface)getServer()).getTickRateManager().process_entities()) ci.cancel(); + if (!((MinecraftServerInterface)getServer()).getTickRateManager().runsNormally()) ci.cancel(); } @Redirect(method = "tick", at = @At( @@ -174,7 +174,7 @@ private void tickWeather(CallbackInfo ci) )) private void tickTimeConditionally(ServerLevel serverWorld) { - if (((MinecraftServerInterface)getServer()).getTickRateManager().process_entities()) tickTime(); + if (((MinecraftServerInterface)getServer()).getTickRateManager().runsNormally()) tickTime(); } @Redirect(method = "tick", at = @At( @@ -183,7 +183,7 @@ private void tickTimeConditionally(ServerLevel serverWorld) )) private boolean tickPendingBlocks(ServerLevel serverWorld) { - if (!((MinecraftServerInterface)getServer()).getTickRateManager().process_entities()) return true; + if (!((MinecraftServerInterface)getServer()).getTickRateManager().runsNormally()) return true; return serverWorld.isDebug(); // isDebug() } @@ -193,7 +193,7 @@ private boolean tickPendingBlocks(ServerLevel serverWorld) )) private void tickConditionally(Raids raidManager) { - if (((MinecraftServerInterface)getServer()).getTickRateManager().process_entities()) raidManager.tick(); + if (((MinecraftServerInterface)getServer()).getTickRateManager().runsNormally()) raidManager.tick(); } @Redirect(method = "tick", at = @At( @@ -202,6 +202,6 @@ private void tickConditionally(Raids raidManager) )) private void tickConditionally(ServerLevel serverWorld) { - if (((MinecraftServerInterface)getServer()).getTickRateManager().process_entities()) runBlockEvents(); + if (((MinecraftServerInterface)getServer()).getTickRateManager().runsNormally()) runBlockEvents(); } } diff --git a/src/main/java/carpet/mixins/Timer_tickSpeedMixin.java b/src/main/java/carpet/mixins/Timer_tickSpeedMixin.java index c8e4f1fe75..fdf61ef18e 100644 --- a/src/main/java/carpet/mixins/Timer_tickSpeedMixin.java +++ b/src/main/java/carpet/mixins/Timer_tickSpeedMixin.java @@ -1,12 +1,16 @@ package carpet.mixins; -import carpet.helpers.TickSpeed; +import carpet.fakes.MinecraftInterface; +import carpet.helpers.TickRateManager; +import net.minecraft.client.Minecraft; import net.minecraft.client.Timer; import carpet.CarpetSettings; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; +import java.util.Optional; + @Mixin(Timer.class) public class Timer_tickSpeedMixin { @Redirect(method = "advanceTime", at = @At( @@ -14,9 +18,13 @@ public class Timer_tickSpeedMixin { target = "Lnet/minecraft/client/Timer;msPerTick:F" )) private float adjustTickSpeed(Timer counter) { - if (CarpetSettings.smoothClientAnimations && TickSpeed.process_entitiesClient()) + if (CarpetSettings.smoothClientAnimations) { - return Math.max(50.0f, TickSpeed.msptClient()); + Optional trm = ((MinecraftInterface)Minecraft.getInstance()).getTickRateManager(); + if (trm.isPresent() && trm.get().runsNormally()) + { + return Math.max(50.0f, trm.get().mspt()); + } } return 50f; } diff --git a/src/main/java/carpet/network/ClientNetworkHandler.java b/src/main/java/carpet/network/ClientNetworkHandler.java index 292774022a..ab7950f542 100644 --- a/src/main/java/carpet/network/ClientNetworkHandler.java +++ b/src/main/java/carpet/network/ClientNetworkHandler.java @@ -5,7 +5,8 @@ import carpet.CarpetSettings; import carpet.api.settings.CarpetRule; import carpet.api.settings.InvalidRuleValueException; -import carpet.helpers.TickSpeed; +import carpet.fakes.ClientLevelInterface; +import carpet.helpers.TickRateManager; import carpet.api.settings.SettingsManager; import io.netty.buffer.Unpooled; import java.util.HashMap; @@ -65,15 +66,23 @@ public class ClientNetworkHandler } } }); - dataHandlers.put("TickRate", (p, t) -> TickSpeed.tickrateClient(((NumericTag)t).getAsFloat())); + dataHandlers.put("TickRate", (p, t) -> { + TickRateManager tickRateManager = ((ClientLevelInterface)p.clientLevel).getTickRateManager(); + tickRateManager.setTickRate(((NumericTag) t).getAsFloat()); + }); dataHandlers.put("TickingState", (p, t) -> { CompoundTag tickingState = (CompoundTag)t; - TickSpeed.setFrozenStateClient(tickingState.getBoolean("is_paused"), tickingState.getBoolean("deepFreeze")); + TickRateManager tickRateManager = ((ClientLevelInterface)p.clientLevel).getTickRateManager(); + tickRateManager.setFrozenState(tickingState.getBoolean("is_paused"), tickingState.getBoolean("deepFreeze")); }); dataHandlers.put("SuperHotState", (p, t) -> { - TickSpeed.setSuperHotClient(((ByteTag) t).equals(ByteTag.ONE)); + TickRateManager tickRateManager = ((ClientLevelInterface)p.clientLevel).getTickRateManager(); + tickRateManager.setSuperHot(((ByteTag) t).equals(ByteTag.ONE)); + }); + dataHandlers.put("TickPlayerActiveTimeout", (p, t) -> { + TickRateManager tickRateManager = ((ClientLevelInterface)p.clientLevel).getTickRateManager(); + tickRateManager.setPlayerActiveTimeout(((NumericTag) t).getAsInt()); }); - dataHandlers.put("TickPlayerActiveTimeout", (p, t) -> TickSpeed.setPlayer_active_timeoutClient(((NumericTag)t).getAsInt())); dataHandlers.put("scShape", (p, t) -> { // deprecated // and unused // should remove for 1.17 if (CarpetClient.shapes != null) CarpetClient.shapes.addShape((CompoundTag)t); diff --git a/src/main/java/carpet/network/ServerNetworkHandler.java b/src/main/java/carpet/network/ServerNetworkHandler.java index 4d5882863f..3a0a0ee80f 100644 --- a/src/main/java/carpet/network/ServerNetworkHandler.java +++ b/src/main/java/carpet/network/ServerNetworkHandler.java @@ -6,7 +6,7 @@ import carpet.api.settings.RuleHelper; import carpet.fakes.MinecraftServerInterface; import carpet.fakes.ServerGamePacketListenerImplInterface; -import carpet.helpers.TickRateManager; +import carpet.helpers.ServerTickRateManager; import carpet.script.utils.SnoopyCommandSource; import carpet.api.settings.SettingsManager; import io.netty.buffer.Unpooled; @@ -260,29 +260,29 @@ private DataBuilder(MinecraftServer server) } private DataBuilder withTickRate() { - TickRateManager trm = ((MinecraftServerInterface)server).getTickRateManager(); - tag.putFloat("TickRate", trm.tickrate); + ServerTickRateManager trm = ((MinecraftServerInterface)server).getTickRateManager(); + tag.putFloat("TickRate", trm.tickrate()); return this; } private DataBuilder withFrozenState() { - TickRateManager trm = ((MinecraftServerInterface)server).getTickRateManager(); + ServerTickRateManager trm = ((MinecraftServerInterface)server).getTickRateManager(); CompoundTag tickingState = new CompoundTag(); - tickingState.putBoolean("is_paused", trm.isPaused()); + tickingState.putBoolean("is_paused", trm.gameIsPaused()); tickingState.putBoolean("deepFreeze", trm.deeplyFrozen()); tag.put("TickingState", tickingState); return this; } private DataBuilder withSuperHotState() { - TickRateManager trm = ((MinecraftServerInterface)server).getTickRateManager(); - tag.putBoolean("SuperHotState", trm.is_superHot); + ServerTickRateManager trm = ((MinecraftServerInterface)server).getTickRateManager(); + tag.putBoolean("SuperHotState", trm.isSuperHot()); return this; } private DataBuilder withTickPlayerActiveTimeout() { - TickRateManager trm = ((MinecraftServerInterface)server).getTickRateManager(); - tag.putInt("TickPlayerActiveTimeout", trm.player_active_timeout); + ServerTickRateManager trm = ((MinecraftServerInterface)server).getTickRateManager(); + tag.putInt("TickPlayerActiveTimeout", trm.getPlayerActiveTimeout()); return this; } private DataBuilder withRule(CarpetRule rule) diff --git a/src/main/java/carpet/patches/TickSyncedBorderExtent.java b/src/main/java/carpet/patches/TickSyncedBorderExtent.java index a1aa428084..a9e8917a10 100644 --- a/src/main/java/carpet/patches/TickSyncedBorderExtent.java +++ b/src/main/java/carpet/patches/TickSyncedBorderExtent.java @@ -2,7 +2,7 @@ import carpet.CarpetServer; import carpet.fakes.MinecraftServerInterface; -import carpet.helpers.TickRateManager; +import carpet.helpers.ServerTickRateManager; import net.minecraft.server.MinecraftServer; import net.minecraft.util.Mth; import net.minecraft.world.level.border.BorderChangeListener; @@ -96,10 +96,10 @@ public long getLerpRemainingTime() else { ms = Arrays.stream(server.tickTimes).average().orElseThrow(IllegalStateException::new) * 1.0E-6D; - TickRateManager trm = ((MinecraftServerInterface)server).getTickRateManager(); - if (trm.time_warp_start_time == 0) // not in time warp + ServerTickRateManager trm = ((MinecraftServerInterface)server).getTickRateManager(); + if (!trm.isInWarpSpeed()) { - ms = Math.max(ms, trm.mspt); + ms = Math.max(ms, trm.mspt()); } } double tps = 1_000.0D / ms; diff --git a/src/main/java/carpet/script/external/Carpet.java b/src/main/java/carpet/script/external/Carpet.java index 1f6218310c..21182959dc 100644 --- a/src/main/java/carpet/script/external/Carpet.java +++ b/src/main/java/carpet/script/external/Carpet.java @@ -7,7 +7,6 @@ import carpet.api.settings.SettingsManager; import carpet.api.settings.Validator; import carpet.fakes.MinecraftServerInterface; -import carpet.helpers.TickSpeed; import carpet.logging.HUDController; import carpet.network.ServerNetworkHandler; import carpet.patches.EntityPlayerMPFake; @@ -136,7 +135,7 @@ public static String isModdedPlayer(Player p) public static boolean isTickProcessingPaused(MinecraftServer server) { - return !((MinecraftServerInterface)server).getTickRateManager().process_entities(); + return !((MinecraftServerInterface)server).getTickRateManager().runsNormally(); } public static void handleExtensionsAPI(CarpetExpression expression) diff --git a/src/main/resources/carpet.mixins.json b/src/main/resources/carpet.mixins.json index 26a4d5c49b..936e8c0afa 100644 --- a/src/main/resources/carpet.mixins.json +++ b/src/main/resources/carpet.mixins.json @@ -188,6 +188,7 @@ "SlimeBlock_customStickyMixin" ], "client": [ + "ClientLevel_tickSpeedMixin", "ShulkerBoxAccessMixin", "Timer_tickSpeedMixin", "MinecraftMixin", From b74495677718e1558b105dab8f7a8a0ffa20f4e3 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Thu, 18 May 2023 14:19:26 +0200 Subject: [PATCH 149/233] fixed server only issues, properly separated client / server logic in common class. --- .../carpet/fakes/ClientLevelInterface.java | 8 ----- .../java/carpet/fakes/LevelInterface.java | 3 ++ .../carpet/helpers/ServerTickRateManager.java | 9 ++++++ .../java/carpet/helpers/TickRateManager.java | 9 ++++++ .../BoundTickingBlockEntity_tickMixin.java | 19 ++++-------- .../mixins/ClientLevel_tickSpeedMixin.java | 6 ++-- .../LevelRenderer_pausedShakeMixin.java | 4 +-- .../carpet/mixins/Level_movableBEMixin.java | 1 + .../java/carpet/mixins/Level_tickMixin.java | 29 ++++--------------- .../java/carpet/mixins/MinecraftMixin.java | 5 ++-- .../carpet/mixins/ServerLevel_tickMixin.java | 22 +++++++++----- .../carpet/network/ClientNetworkHandler.java | 10 +++---- 12 files changed, 59 insertions(+), 66 deletions(-) delete mode 100644 src/main/java/carpet/fakes/ClientLevelInterface.java diff --git a/src/main/java/carpet/fakes/ClientLevelInterface.java b/src/main/java/carpet/fakes/ClientLevelInterface.java deleted file mode 100644 index 6ecdf58a1e..0000000000 --- a/src/main/java/carpet/fakes/ClientLevelInterface.java +++ /dev/null @@ -1,8 +0,0 @@ -package carpet.fakes; - -import carpet.helpers.TickRateManager; - -public interface ClientLevelInterface -{ - TickRateManager getTickRateManager(); -} diff --git a/src/main/java/carpet/fakes/LevelInterface.java b/src/main/java/carpet/fakes/LevelInterface.java index 583da75774..05da80b4f4 100644 --- a/src/main/java/carpet/fakes/LevelInterface.java +++ b/src/main/java/carpet/fakes/LevelInterface.java @@ -1,5 +1,6 @@ package carpet.fakes; +import carpet.helpers.TickRateManager; import net.minecraft.world.level.redstone.NeighborUpdater; import org.jetbrains.annotations.Nullable; @@ -22,4 +23,6 @@ public interface LevelInterface List getOtherEntitiesLimited(@Nullable Entity except, AABB box, Predicate predicate, int limit); NeighborUpdater getNeighborUpdater(); + + TickRateManager tickRateManager(); } diff --git a/src/main/java/carpet/helpers/ServerTickRateManager.java b/src/main/java/carpet/helpers/ServerTickRateManager.java index 775acf0b3d..64b70882be 100644 --- a/src/main/java/carpet/helpers/ServerTickRateManager.java +++ b/src/main/java/carpet/helpers/ServerTickRateManager.java @@ -8,6 +8,8 @@ import net.minecraft.network.chat.Component; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.player.Player; import java.util.HashMap; import java.util.Map; @@ -33,6 +35,13 @@ public boolean isInWarpSpeed() return tickWarpStartTime != 0; } + + @Override + public boolean shouldEntityTick(Entity e) + { + return (runsNormally() || (e instanceof Player)); + } + /** * Whether or not the game is deeply frozen. * This can be used for things that you may not normally want diff --git a/src/main/java/carpet/helpers/TickRateManager.java b/src/main/java/carpet/helpers/TickRateManager.java index dca76a3933..6c2ccca460 100644 --- a/src/main/java/carpet/helpers/TickRateManager.java +++ b/src/main/java/carpet/helpers/TickRateManager.java @@ -1,5 +1,8 @@ package carpet.helpers; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.player.Player; + public class TickRateManager { public static final int PLAYER_GRACE = 2; @@ -93,4 +96,10 @@ else if (isSuperHot) runGameElements = true; } } + + public boolean shouldEntityTick(Entity e) + { + // client + return (runsNormally() || (e instanceof Player) || isSuperHot() && e.getControllingPassenger() instanceof Player); + } } diff --git a/src/main/java/carpet/mixins/BoundTickingBlockEntity_tickMixin.java b/src/main/java/carpet/mixins/BoundTickingBlockEntity_tickMixin.java index 370fd25cb8..bc8a76917f 100644 --- a/src/main/java/carpet/mixins/BoundTickingBlockEntity_tickMixin.java +++ b/src/main/java/carpet/mixins/BoundTickingBlockEntity_tickMixin.java @@ -1,12 +1,9 @@ package carpet.mixins; -import carpet.fakes.ClientLevelInterface; -import carpet.fakes.MinecraftServerInterface; +import carpet.fakes.LevelInterface; import carpet.helpers.TickRateManager; -import carpet.helpers.ServerTickRateManager; import carpet.utils.CarpetProfiler; import net.minecraft.core.BlockPos; -import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; @@ -38,16 +35,10 @@ private void startTileEntitySection(CallbackInfo ci) )) private void checkProcessBEs(BlockEntityTicker blockEntityTicker, Level world, BlockPos pos, BlockState state, T blockEntity) { - // these two branches are identical, but we need to check the world type and inferfaces - if (world.isClientSide()) { - // client - TickRateManager tickRateManager = ((ClientLevelInterface)world).getTickRateManager(); - if (tickRateManager.runsNormally()) blockEntityTicker.tick(world, pos, state, blockEntity); - } else { - // server - ServerLevel serverWorld = (ServerLevel) world; - ServerTickRateManager serverTickRateManager = ((MinecraftServerInterface)serverWorld.getServer()).getTickRateManager(); - if (serverTickRateManager.runsNormally()) blockEntityTicker.tick(world, pos, state, blockEntity); + TickRateManager tickRateManager = ((LevelInterface)world).tickRateManager(); + if (tickRateManager.runsNormally()) + { + blockEntityTicker.tick(world, pos, state, blockEntity); } } diff --git a/src/main/java/carpet/mixins/ClientLevel_tickSpeedMixin.java b/src/main/java/carpet/mixins/ClientLevel_tickSpeedMixin.java index 50d0de5e04..12a5b6cf33 100644 --- a/src/main/java/carpet/mixins/ClientLevel_tickSpeedMixin.java +++ b/src/main/java/carpet/mixins/ClientLevel_tickSpeedMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.fakes.ClientLevelInterface; +import carpet.fakes.LevelInterface; import carpet.helpers.TickRateManager; import net.minecraft.client.multiplayer.ClientLevel; import org.spongepowered.asm.mixin.Mixin; @@ -9,7 +9,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(ClientLevel.class) -public class ClientLevel_tickSpeedMixin implements ClientLevelInterface +public abstract class ClientLevel_tickSpeedMixin implements LevelInterface { private TickRateManager tickRateManager; @@ -21,7 +21,7 @@ private void onInit(CallbackInfo ci) } @Override - public TickRateManager getTickRateManager() + public TickRateManager tickRateManager() { return tickRateManager; } diff --git a/src/main/java/carpet/mixins/LevelRenderer_pausedShakeMixin.java b/src/main/java/carpet/mixins/LevelRenderer_pausedShakeMixin.java index 941f61ac32..2c38ffb871 100644 --- a/src/main/java/carpet/mixins/LevelRenderer_pausedShakeMixin.java +++ b/src/main/java/carpet/mixins/LevelRenderer_pausedShakeMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.fakes.ClientLevelInterface; +import carpet.fakes.LevelInterface; import carpet.fakes.MinecraftClientInferface; import carpet.helpers.TickRateManager; import net.minecraft.client.Minecraft; @@ -28,7 +28,7 @@ public class LevelRenderer_pausedShakeMixin private float changeTickPhase(float previous) { initial = previous; - TickRateManager trm = ((ClientLevelInterface)level).getTickRateManager(); + TickRateManager trm = ((LevelInterface)level).tickRateManager(); if (!trm.runsNormally()) return ((MinecraftClientInferface)minecraft).getPausedTickDelta(); return previous; diff --git a/src/main/java/carpet/mixins/Level_movableBEMixin.java b/src/main/java/carpet/mixins/Level_movableBEMixin.java index 24d97c96f9..d5820368ae 100644 --- a/src/main/java/carpet/mixins/Level_movableBEMixin.java +++ b/src/main/java/carpet/mixins/Level_movableBEMixin.java @@ -57,6 +57,7 @@ public abstract class Level_movableBEMixin implements LevelInterface, LevelAcces /** * @author 2No2Name */ + @Override public boolean setBlockStateWithBlockEntity(BlockPos blockPos_1, BlockState blockState_1, BlockEntity newBlockEntity, int int_1) { if (isOutsideBuildHeight(blockPos_1) || !this.isClientSide && isDebug()) return false; diff --git a/src/main/java/carpet/mixins/Level_tickMixin.java b/src/main/java/carpet/mixins/Level_tickMixin.java index d562dbfb7b..146c00cec5 100644 --- a/src/main/java/carpet/mixins/Level_tickMixin.java +++ b/src/main/java/carpet/mixins/Level_tickMixin.java @@ -1,13 +1,8 @@ package carpet.mixins; -import carpet.fakes.ClientLevelInterface; import carpet.fakes.LevelInterface; -import carpet.fakes.MinecraftServerInterface; import carpet.helpers.TickRateManager; -import carpet.helpers.ServerTickRateManager; import carpet.utils.CarpetProfiler; -import net.minecraft.client.multiplayer.ClientLevel; -import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.redstone.NeighborUpdater; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -22,7 +17,6 @@ import java.util.function.Consumer; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; -import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.Level; @Mixin(Level.class) @@ -41,6 +35,7 @@ public NeighborUpdater getNeighborUpdater() { return this.neighborUpdater; } + @Override public Map, Entity> getPrecookedMobs() { return precookedMobs; @@ -59,26 +54,12 @@ private void endBlockEntities(CallbackInfo ci) { @Inject(method = "guardEntityTick", at = @At("HEAD"), cancellable = true) private void startEntity(Consumer consumer_1, Entity e, CallbackInfo ci) { - // this shows that probably tick speed controller needs to be accessible through level referring to servers on server and client on clientLevel - // these two branches could also be merged into one generic for cloent and server - if (!isClientSide) - { - ServerLevel serverLevel = (ServerLevel) (Object) this; - ServerTickRateManager trm = ((MinecraftServerInterface)serverLevel.getServer()).getTickRateManager(); - if (!(trm.runsNormally() || (e instanceof Player))) - { - ci.cancel(); - } - } - else + TickRateManager trm = tickRateManager(); + if (!trm.shouldEntityTick(e)) { - ClientLevel clientLevel = (ClientLevel) (Object) this; - TickRateManager trm = ((ClientLevelInterface)clientLevel).getTickRateManager(); - if (!(trm.runsNormally() || (e instanceof Player) || trm.isSuperHot() && e.getControllingPassenger() instanceof Player)) - { - ci.cancel(); - } + ci.cancel(); } + entitySection = CarpetProfiler.start_entity_section((Level) (Object) this, e, CarpetProfiler.TYPE.ENTITY); } diff --git a/src/main/java/carpet/mixins/MinecraftMixin.java b/src/main/java/carpet/mixins/MinecraftMixin.java index 525d05371f..7941cc25b1 100644 --- a/src/main/java/carpet/mixins/MinecraftMixin.java +++ b/src/main/java/carpet/mixins/MinecraftMixin.java @@ -1,7 +1,6 @@ package carpet.mixins; -import carpet.CarpetServer; -import carpet.fakes.ClientLevelInterface; +import carpet.fakes.LevelInterface; import carpet.helpers.TickRateManager; import carpet.fakes.MinecraftInterface; import carpet.network.CarpetClient; @@ -41,7 +40,7 @@ private void onClientTick(CallbackInfo info) { public Optional getTickRateManager() { if (this.level != null) { - return Optional.of(((ClientLevelInterface)this.level).getTickRateManager()); + return Optional.of(((LevelInterface)this.level).tickRateManager()); } return Optional.empty(); } diff --git a/src/main/java/carpet/mixins/ServerLevel_tickMixin.java b/src/main/java/carpet/mixins/ServerLevel_tickMixin.java index f68add3867..3150311a83 100644 --- a/src/main/java/carpet/mixins/ServerLevel_tickMixin.java +++ b/src/main/java/carpet/mixins/ServerLevel_tickMixin.java @@ -1,6 +1,8 @@ package carpet.mixins; +import carpet.fakes.LevelInterface; import carpet.fakes.MinecraftServerInterface; +import carpet.helpers.TickRateManager; import carpet.utils.CarpetProfiler; import net.minecraft.core.Holder; import net.minecraft.core.RegistryAccess; @@ -23,13 +25,19 @@ import net.minecraft.world.level.storage.WritableLevelData; @Mixin(ServerLevel.class) -public abstract class ServerLevel_tickMixin extends Level +public abstract class ServerLevel_tickMixin extends Level implements LevelInterface { protected ServerLevel_tickMixin(final WritableLevelData writableLevelData, final ResourceKey resourceKey, final RegistryAccess registryAccess, final Holder holder, final Supplier supplier, final boolean bl, final boolean bl2, final long l, final int i) { super(writableLevelData, resourceKey, registryAccess, holder, supplier, bl, bl2, l, i); } + @Override + public TickRateManager tickRateManager() + { + return ((MinecraftServerInterface)getServer()).getTickRateManager(); + } + @Shadow protected abstract void runBlockEvents(); @Shadow protected abstract void tickTime(); @@ -159,13 +167,13 @@ private void endRandomTicks(CallbackInfo ci) { )) private void tickWorldBorder(WorldBorder worldBorder) { - if (((MinecraftServerInterface)getServer()).getTickRateManager().runsNormally()) worldBorder.tick(); + if (tickRateManager().runsNormally()) worldBorder.tick(); } @Inject(method = "advanceWeatherCycle", cancellable = true, at = @At("HEAD")) private void tickWeather(CallbackInfo ci) { - if (!((MinecraftServerInterface)getServer()).getTickRateManager().runsNormally()) ci.cancel(); + if (!tickRateManager().runsNormally()) ci.cancel(); } @Redirect(method = "tick", at = @At( @@ -174,7 +182,7 @@ private void tickWeather(CallbackInfo ci) )) private void tickTimeConditionally(ServerLevel serverWorld) { - if (((MinecraftServerInterface)getServer()).getTickRateManager().runsNormally()) tickTime(); + if (tickRateManager().runsNormally()) tickTime(); } @Redirect(method = "tick", at = @At( @@ -183,7 +191,7 @@ private void tickTimeConditionally(ServerLevel serverWorld) )) private boolean tickPendingBlocks(ServerLevel serverWorld) { - if (!((MinecraftServerInterface)getServer()).getTickRateManager().runsNormally()) return true; + if (!tickRateManager().runsNormally()) return true; return serverWorld.isDebug(); // isDebug() } @@ -193,7 +201,7 @@ private boolean tickPendingBlocks(ServerLevel serverWorld) )) private void tickConditionally(Raids raidManager) { - if (((MinecraftServerInterface)getServer()).getTickRateManager().runsNormally()) raidManager.tick(); + if (tickRateManager().runsNormally()) raidManager.tick(); } @Redirect(method = "tick", at = @At( @@ -202,6 +210,6 @@ private void tickConditionally(Raids raidManager) )) private void tickConditionally(ServerLevel serverWorld) { - if (((MinecraftServerInterface)getServer()).getTickRateManager().runsNormally()) runBlockEvents(); + if (tickRateManager().runsNormally()) runBlockEvents(); } } diff --git a/src/main/java/carpet/network/ClientNetworkHandler.java b/src/main/java/carpet/network/ClientNetworkHandler.java index ab7950f542..0973b7e834 100644 --- a/src/main/java/carpet/network/ClientNetworkHandler.java +++ b/src/main/java/carpet/network/ClientNetworkHandler.java @@ -5,7 +5,7 @@ import carpet.CarpetSettings; import carpet.api.settings.CarpetRule; import carpet.api.settings.InvalidRuleValueException; -import carpet.fakes.ClientLevelInterface; +import carpet.fakes.LevelInterface; import carpet.helpers.TickRateManager; import carpet.api.settings.SettingsManager; import io.netty.buffer.Unpooled; @@ -67,20 +67,20 @@ public class ClientNetworkHandler } }); dataHandlers.put("TickRate", (p, t) -> { - TickRateManager tickRateManager = ((ClientLevelInterface)p.clientLevel).getTickRateManager(); + TickRateManager tickRateManager = ((LevelInterface)p.clientLevel).tickRateManager(); tickRateManager.setTickRate(((NumericTag) t).getAsFloat()); }); dataHandlers.put("TickingState", (p, t) -> { CompoundTag tickingState = (CompoundTag)t; - TickRateManager tickRateManager = ((ClientLevelInterface)p.clientLevel).getTickRateManager(); + TickRateManager tickRateManager = ((LevelInterface)p.clientLevel).tickRateManager(); tickRateManager.setFrozenState(tickingState.getBoolean("is_paused"), tickingState.getBoolean("deepFreeze")); }); dataHandlers.put("SuperHotState", (p, t) -> { - TickRateManager tickRateManager = ((ClientLevelInterface)p.clientLevel).getTickRateManager(); + TickRateManager tickRateManager = ((LevelInterface)p.clientLevel).tickRateManager(); tickRateManager.setSuperHot(((ByteTag) t).equals(ByteTag.ONE)); }); dataHandlers.put("TickPlayerActiveTimeout", (p, t) -> { - TickRateManager tickRateManager = ((ClientLevelInterface)p.clientLevel).getTickRateManager(); + TickRateManager tickRateManager = ((LevelInterface)p.clientLevel).tickRateManager(); tickRateManager.setPlayerActiveTimeout(((NumericTag) t).getAsInt()); }); dataHandlers.put("scShape", (p, t) -> { // deprecated // and unused // should remove for 1.17 From e140a5ddb02da864d77bbba6eb284ef0a7e7238e Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Fri, 19 May 2023 00:45:27 +0200 Subject: [PATCH 150/233] send tick info with client level data --- .../java/carpet/mixins/PlayerList_coreMixin.java | 8 ++++++++ .../java/carpet/network/ServerNetworkHandler.java | 13 ++++++++++--- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/src/main/java/carpet/mixins/PlayerList_coreMixin.java b/src/main/java/carpet/mixins/PlayerList_coreMixin.java index e547f6b6f7..e689d1535a 100644 --- a/src/main/java/carpet/mixins/PlayerList_coreMixin.java +++ b/src/main/java/carpet/mixins/PlayerList_coreMixin.java @@ -1,7 +1,9 @@ package carpet.mixins; import carpet.CarpetServer; +import carpet.network.ServerNetworkHandler; import net.minecraft.network.Connection; +import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.players.PlayerList; import org.spongepowered.asm.mixin.Mixin; @@ -18,4 +20,10 @@ private void onPlayerConnected(Connection connection, ServerPlayer player, Callb { CarpetServer.onPlayerLoggedIn(player); } + + @Inject(method = "sendLevelInfo", at = @At("RETURN")) + private void onLevelChanged(final ServerPlayer serverPlayer, final ServerLevel serverLevel, final CallbackInfo ci) + { + ServerNetworkHandler.sendPlayerLevelData(serverPlayer, serverLevel); + } } diff --git a/src/main/java/carpet/network/ServerNetworkHandler.java b/src/main/java/carpet/network/ServerNetworkHandler.java index 3a0a0ee80f..c216f003f8 100644 --- a/src/main/java/carpet/network/ServerNetworkHandler.java +++ b/src/main/java/carpet/network/ServerNetworkHandler.java @@ -25,6 +25,7 @@ import net.minecraft.network.chat.Component; import net.minecraft.network.protocol.game.ClientboundCustomPayloadPacket; import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; public class ServerNetworkHandler @@ -70,7 +71,6 @@ public static void onPlayerJoin(ServerPlayer playerEntity) public static void onHello(ServerPlayer playerEntity, FriendlyByteBuf packetData) { - validCarpetPlayers.add(playerEntity); String clientVersion = packetData.readUtf(64); remoteCarpetPlayers.put(playerEntity, clientVersion); @@ -78,7 +78,8 @@ public static void onHello(ServerPlayer playerEntity, FriendlyByteBuf packetData CarpetSettings.LOG.info("Player "+playerEntity.getName().getString()+" joined with a matching carpet client"); else CarpetSettings.LOG.warn("Player "+playerEntity.getName().getString()+" joined with another carpet version: "+clientVersion); - DataBuilder data = DataBuilder.create(playerEntity.server).withTickRate().withFrozenState().withTickPlayerActiveTimeout(); // .withSuperHotState() + + DataBuilder data = DataBuilder.create(playerEntity.server);//;.withTickRate().withFrozenState().withTickPlayerActiveTimeout(); // .withSuperHotState() CarpetServer.settingsManager.getCarpetRules().forEach(data::withRule); CarpetServer.extensions.forEach(e -> { SettingsManager eManager = e.extensionSettingsManager(); @@ -86,7 +87,13 @@ public static void onHello(ServerPlayer playerEntity, FriendlyByteBuf packetData eManager.getCarpetRules().forEach(data::withRule); } }); - playerEntity.connection.send(new ClientboundCustomPayloadPacket(CarpetClient.CARPET_CHANNEL, data.build() )); + playerEntity.connection.send(new ClientboundCustomPayloadPacket(CarpetClient.CARPET_CHANNEL, data.build())); + } + + public static void sendPlayerLevelData(ServerPlayer player, ServerLevel level) { + DataBuilder data = DataBuilder.create(player.server).withTickRate().withFrozenState().withTickPlayerActiveTimeout(); // .withSuperHotState() + player.connection.send(new ClientboundCustomPayloadPacket(CarpetClient.CARPET_CHANNEL, data.build() )); + } private static void handleClientCommand(ServerPlayer player, CompoundTag commandData) From f15a0eabf7edb5d1a9fbbe351c098d7efce7ee8c Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Fri, 19 May 2023 08:01:07 +0200 Subject: [PATCH 151/233] null level fixes #1703 --- src/main/java/carpet/script/api/WorldAccess.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/carpet/script/api/WorldAccess.java b/src/main/java/carpet/script/api/WorldAccess.java index eb757a9b8f..eaab2eb5fb 100644 --- a/src/main/java/carpet/script/api/WorldAccess.java +++ b/src/main/java/carpet/script/api/WorldAccess.java @@ -932,7 +932,7 @@ else if (item instanceof TridentItem || item instanceof SwordItem) } if (DUMMY_ENTITY == null) { - DUMMY_ENTITY = new FallingBlockEntity(EntityType.FALLING_BLOCK, cc.server().overworld()); + DUMMY_ENTITY = new FallingBlockEntity(EntityType.FALLING_BLOCK, null); } Block.dropResources(state, world, where, be, DUMMY_ENTITY, tool); } From e28f52171fa5427bb3cf4538baa99eb154cd9a60 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Tue, 23 May 2023 18:25:09 +0200 Subject: [PATCH 152/233] 1.20-pre5 --- gradle.properties | 2 +- .../carpet/mixins/ChunkMap_scarpetChunkCreationMixin.java | 7 +++++-- src/main/java/carpet/patches/EntityPlayerMPFake.java | 2 +- src/main/java/carpet/script/api/WorldAccess.java | 3 ++- 4 files changed, 9 insertions(+), 5 deletions(-) diff --git a/gradle.properties b/gradle.properties index beb22442ac..8a95201ae3 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,7 +3,7 @@ org.gradle.jvmargs=-Xmx1G # Fabric Properties # check https://fabricmc.net/develop/ - minecraft_version=1.20-pre2 + minecraft_version=1.20-pre5 loader_version=0.14.19 jsr305_version=3.0.2 fabric_version=0.81.2+1.20 diff --git a/src/main/java/carpet/mixins/ChunkMap_scarpetChunkCreationMixin.java b/src/main/java/carpet/mixins/ChunkMap_scarpetChunkCreationMixin.java index 8345096652..913c9bca1d 100644 --- a/src/main/java/carpet/mixins/ChunkMap_scarpetChunkCreationMixin.java +++ b/src/main/java/carpet/mixins/ChunkMap_scarpetChunkCreationMixin.java @@ -15,6 +15,7 @@ import carpet.fakes.SimpleEntityLookupInterface; import carpet.fakes.ServerWorldInterface; import net.minecraft.Util; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.server.MinecraftServer; import net.minecraft.server.TickTask; import net.minecraft.server.level.ChunkHolder; @@ -439,12 +440,14 @@ public Map regenerateChunkRegion(final List requested if (futures == null) continue; - report.put("layer_count_" + status.getName(), futures.size()); + String statusName = BuiltInRegistries.CHUNK_STATUS.getKey(status).getPath(); + + report.put("layer_count_" + statusName, futures.size()); final long start = System.currentTimeMillis(); this.waitFor(futures); - report.put("layer_time_" + status.getName(), (int) (System.currentTimeMillis() - start)); + report.put("layer_time_" + statusName, (int) (System.currentTimeMillis() - start)); } diff --git a/src/main/java/carpet/patches/EntityPlayerMPFake.java b/src/main/java/carpet/patches/EntityPlayerMPFake.java index 2c4b8fc023..3ac3f4e871 100644 --- a/src/main/java/carpet/patches/EntityPlayerMPFake.java +++ b/src/main/java/carpet/patches/EntityPlayerMPFake.java @@ -186,7 +186,7 @@ public String getIpAddress() @Override protected void checkFallDamage(double y, boolean onGround, BlockState state, BlockPos pos) { - doCheckFallDamage(y, onGround); + doCheckFallDamage(0.0, y, 0.0, onGround); } @Override diff --git a/src/main/java/carpet/script/api/WorldAccess.java b/src/main/java/carpet/script/api/WorldAccess.java index eaab2eb5fb..012d931fb8 100644 --- a/src/main/java/carpet/script/api/WorldAccess.java +++ b/src/main/java/carpet/script/api/WorldAccess.java @@ -38,6 +38,7 @@ import net.minecraft.core.HolderSet; import net.minecraft.core.QuartPos; import net.minecraft.core.Registry; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.Registries; import net.minecraft.resources.ResourceKey; import net.minecraft.server.level.DistanceManager; @@ -632,7 +633,7 @@ else if (!("any".equals(statusString))) forceLoad = lv.get(blockArgument.offset).getBoolean(); } ChunkAccess chunk = ((CarpetContext) c).level().getChunk(pos.getX() >> 4, pos.getZ() >> 4, ChunkStatus.EMPTY, forceLoad); - return chunk == null ? Value.NULL : new StringValue(chunk.getStatus().getName()); + return chunk == null ? Value.NULL : ValueConversions.of(BuiltInRegistries.CHUNK_STATUS.getKey(chunk.getStatus())); }); expression.addContextFunction("chunk_tickets", -1, (c, t, lv) -> From 046d84af424c3034fd83b77c412566eab20a95e2 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Tue, 23 May 2023 18:26:37 +0200 Subject: [PATCH 153/233] 1.4.110 --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 8a95201ae3..7e8633413b 100644 --- a/gradle.properties +++ b/gradle.properties @@ -9,7 +9,7 @@ org.gradle.jvmargs=-Xmx1G fabric_version=0.81.2+1.20 # Mod Properties - mod_version = 1.4.109 + mod_version = 1.4.110 maven_group = carpet archives_base_name = fabric-carpet From f75e3d77a21783e35e464cf9d58fbba0012e6ae3 Mon Sep 17 00:00:00 2001 From: triphora Date: Wed, 24 May 2023 06:36:15 -0400 Subject: [PATCH 154/233] Improve Modrinth download badge (#1722) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 23da28c1e4..bb67e0936f 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ [![Development Builds](https://github.com/gnembon/fabric-carpet/actions/workflows/devbuild.yml/badge.svg)](https://github.com/gnembon/fabric-carpet/actions/workflows/devbuild.yml) [![CurseForge downloads](http://cf.way2muchnoise.eu/full_349239_downloads.svg)](https://www.curseforge.com/minecraft/mc-mods/carpet) -[![Modrinth downloads](https://img.shields.io/modrinth/dt/carpet?label=Modrinth%20downloads&logo=data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbDpzcGFjZT0icHJlc2VydmUiIGZpbGwtcnVsZT0iZXZlbm9kZCIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIgc3Ryb2tlLW1pdGVybGltaXQ9IjEuNSIgY2xpcC1ydWxlPSJldmVub2RkIiB2aWV3Qm94PSIwIDAgMTAwIDEwMCI+PHBhdGggZmlsbD0ibm9uZSIgZD0iTTAgMGgxMDB2MTAwSDB6Ii8+PGNsaXBQYXRoIGlkPSJhIj48cGF0aCBkPSJNMTAwIDBIMHYxMDBoMTAwVjBaTTQ2LjAwMiA0OS4yOTVsLjA3NiAxLjc1NyA4LjgzIDMyLjk2MyA3Ljg0My0yLjEwMi04LjU5Ni0zMi4wOTQgNS44MDQtMzIuOTMyLTcuOTk3LTEuNDEtNS45NiAzMy44MThaIi8+PC9jbGlwUGF0aD48ZyBjbGlwLXBhdGg9InVybCgjYSkiPjxwYXRoIGZpbGw9IiMwMGQ4NDUiIGQ9Ik01MCAxN2MxOC4yMDcgMCAzMi45ODggMTQuNzg3IDMyLjk4OCAzM1M2OC4yMDcgODMgNTAgODMgMTcuMDEyIDY4LjIxMyAxNy4wMTIgNTAgMzEuNzkzIDE3IDUwIDE3Wm0wIDljMTMuMjQgMCAyMy45ODggMTAuNzU1IDIzLjk4OCAyNFM2My4yNCA3NCA1MCA3NCAyNi4wMTIgNjMuMjQ1IDI2LjAxMiA1MCAzNi43NiAyNiA1MCAyNloiLz48L2c+PGNsaXBQYXRoIGlkPSJiIj48cGF0aCBkPSJNMCAwdjQ2aDUwbDEuMzY4LjI0MUw5OSA2My41NzhsLTIuNzM2IDcuNTE3TDQ5LjI5NSA1NEgwdjQ2aDEwMFYwSDBaIi8+PC9jbGlwUGF0aD48ZyBjbGlwLXBhdGg9InVybCgjYikiPjxwYXRoIGZpbGw9IiMwMGQ4NDUiIGQ9Ik01MCAwYzI3LjU5NiAwIDUwIDIyLjQwNCA1MCA1MHMtMjIuNDA0IDUwLTUwIDUwUzAgNzcuNTk2IDAgNTAgMjIuNDA0IDAgNTAgMFptMCA5YzIyLjYyOSAwIDQxIDE4LjM3MSA0MSA0MVM3Mi42MjkgOTEgNTAgOTEgOSA3Mi42MjkgOSA1MCAyNy4zNzEgOSA1MCA5WiIvPjwvZz48Y2xpcFBhdGggaWQ9ImMiPjxwYXRoIGQ9Ik01MCAwYzI3LjU5NiAwIDUwIDIyLjQwNCA1MCA1MHMtMjIuNDA0IDUwLTUwIDUwUzAgNzcuNTk2IDAgNTAgMjIuNDA0IDAgNTAgMFptMCAzOS41NDljNS43NjggMCAxMC40NTEgNC42ODMgMTAuNDUxIDEwLjQ1MSAwIDUuNzY4LTQuNjgzIDEwLjQ1MS0xMC40NTEgMTAuNDUxLTUuNzY4IDAtMTAuNDUxLTQuNjgzLTEwLjQ1MS0xMC40NTEgMC01Ljc2OCA0LjY4My0xMC40NTEgMTAuNDUxLTEwLjQ1MVoiLz48L2NsaXBQYXRoPjxnIGNsaXAtcGF0aD0idXJsKCNjKSI+PHBhdGggZmlsbD0ibm9uZSIgc3Ryb2tlPSIjMDBkODQ1IiBzdHJva2Utd2lkdGg9IjkiIGQ9Ik01MCA1MCA1LjE3MSA3NS44ODIiLz48L2c+PGNsaXBQYXRoIGlkPSJkIj48cGF0aCBkPSJNNTAgMGMyNy41OTYgMCA1MCAyMi40MDQgNTAgNTBzLTIyLjQwNCA1MC01MCA1MFMwIDc3LjU5NiAwIDUwIDIyLjQwNCAwIDUwIDBabTAgMjUuMzZjMTMuNTk5IDAgMjQuNjQgMTEuMDQxIDI0LjY0IDI0LjY0UzYzLjU5OSA3NC42NCA1MCA3NC42NCAyNS4zNiA2My41OTkgMjUuMzYgNTAgMzYuNDAxIDI1LjM2IDUwIDI1LjM2WiIvPjwvY2xpcFBhdGg+PGcgY2xpcC1wYXRoPSJ1cmwoI2QpIj48cGF0aCBmaWxsPSJub25lIiBzdHJva2U9IiMwMGQ4NDUiIHN0cm9rZS13aWR0aD0iOSIgZD0ibTUwIDUwIDUwLTEzLjM5NyIvPjwvZz48cGF0aCBmaWxsPSIjMDBkODQ1IiBkPSJNMzcuMjQzIDUyLjc0NiAzNSA0NWw4LTkgMTEtMyA0IDQtNiA2LTQgMS0zIDQgMS4xMiA0LjI0IDMuMTEyIDMuMDkgNC45NjQtLjU5OCAyLjg2Ni0yLjk2NCA4LjE5Ni0yLjE5NiAxLjQ2NCA1LjQ2NC04LjA5OCA4LjAyNkw0Ni44MyA2NS40OWwtNS41ODctNS44MTUtNC02LjkyOVoiLz48L3N2Zz4=)](https://modrinth.com/mod/carpet) +[![Modrinth downloads](https://img.shields.io/modrinth/dt/carpet?label=Modrinth%20downloads&logo=modrinth)](https://modrinth.com/mod/carpet) [![GitHub downloads](https://img.shields.io/github/downloads/gnembon/fabric-carpet/total?label=Github%20downloads&logo=github)](https://github.com/gnembon/fabric-carpet/releases) [![GitHub contributors](https://img.shields.io/github/contributors/gnembon/fabric-carpet?label=Contributors&logo=github)](https://github.com/gnembon/fabric-carpet/graphs/contributors) [![Discord](https://badgen.net/discord/online-members/gn99m4QRY4?icon=discord&label=Discord&list=what)](https://discord.gg/gn99m4QRY4) From aeb68e9ba0a31693c084fead28c2c47ce29013e6 Mon Sep 17 00:00:00 2001 From: James McCulloch Date: Wed, 24 May 2023 22:24:03 +1000 Subject: [PATCH 155/233] Fake player portal fix (#1724) * fake-player-portal-fix: * Fix the teleport fix, so it doesn't crash when bots go through nether portals (Fixes #1712) * fake-player-portal-fix: * Re-implement fix for #1190 * Without causing #1712 * Just move the bot on the chunkmap directly. --- .../ServerGamePacketListenerImplAccessor.java | 11 ----------- .../patches/NetHandlerPlayServerFake.java | 18 +++--------------- src/main/resources/carpet.mixins.json | 1 - 3 files changed, 3 insertions(+), 27 deletions(-) delete mode 100644 src/main/java/carpet/mixins/ServerGamePacketListenerImplAccessor.java diff --git a/src/main/java/carpet/mixins/ServerGamePacketListenerImplAccessor.java b/src/main/java/carpet/mixins/ServerGamePacketListenerImplAccessor.java deleted file mode 100644 index b199fe8ed1..0000000000 --- a/src/main/java/carpet/mixins/ServerGamePacketListenerImplAccessor.java +++ /dev/null @@ -1,11 +0,0 @@ -package carpet.mixins; - -import net.minecraft.server.network.ServerGamePacketListenerImpl; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Accessor; - -@Mixin(ServerGamePacketListenerImpl.class) -public interface ServerGamePacketListenerImplAccessor { - @Accessor("awaitingTeleport") - public int getAwaitingTeleport(); -} diff --git a/src/main/java/carpet/patches/NetHandlerPlayServerFake.java b/src/main/java/carpet/patches/NetHandlerPlayServerFake.java index 16f583c96e..a8e5b852e7 100644 --- a/src/main/java/carpet/patches/NetHandlerPlayServerFake.java +++ b/src/main/java/carpet/patches/NetHandlerPlayServerFake.java @@ -1,12 +1,9 @@ package carpet.patches; -import carpet.mixins.ServerGamePacketListenerImplAccessor; import net.minecraft.network.Connection; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.contents.TranslatableContents; import net.minecraft.network.protocol.Packet; -import net.minecraft.network.protocol.game.ServerboundAcceptTeleportationPacket; -import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; import net.minecraft.server.MinecraftServer; import net.minecraft.server.network.ServerGamePacketListenerImpl; import net.minecraft.world.entity.RelativeMovement; @@ -32,23 +29,14 @@ public void disconnect(Component message) ((EntityPlayerMPFake) player).kill(message); } } - private boolean hasSpawned = false; @Override public void teleport(double d, double e, double f, float g, float h, Set set) { super.teleport(d, e, f, g, h, set); - - handleAcceptTeleportPacket( - new ServerboundAcceptTeleportationPacket( ((ServerGamePacketListenerImplAccessor)this).getAwaitingTeleport() ) - ); - - if (!hasSpawned) { - hasSpawned = true; - } else { - handleMovePlayer( - new ServerboundMovePlayerPacket.PosRot(player.getX(), player.getY(), player.getZ(), player.getYRot(), player.getXRot(), false) - ); + if (player.serverLevel().getPlayerByUUID(player.getUUID()) != null) { + resetPosition(); + player.serverLevel().getChunkSource().move(player); } } diff --git a/src/main/resources/carpet.mixins.json b/src/main/resources/carpet.mixins.json index 936e8c0afa..c6af4fd698 100644 --- a/src/main/resources/carpet.mixins.json +++ b/src/main/resources/carpet.mixins.json @@ -8,7 +8,6 @@ "MobCategory_spawnMixin", "Commands_customCommandsMixin", "ServerGamePacketListenerImplMixin", - "ServerGamePacketListenerImplAccessor", "PerfCommand_permissionMixin", "FillCommandMixin", From 9ca4e9538f59d0d57173fa75b64501b932b457ef Mon Sep 17 00:00:00 2001 From: James McCulloch Date: Wed, 24 May 2023 22:38:48 +1000 Subject: [PATCH 156/233] shadow-player-reconnect-fix (#1686) * if a bot is kill()ed for a duplicate login, handle the disconnect immediately, Fixes #1468 --- src/main/java/carpet/patches/EntityPlayerMPFake.java | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/main/java/carpet/patches/EntityPlayerMPFake.java b/src/main/java/carpet/patches/EntityPlayerMPFake.java index 3ac3f4e871..7ef72d9f73 100644 --- a/src/main/java/carpet/patches/EntityPlayerMPFake.java +++ b/src/main/java/carpet/patches/EntityPlayerMPFake.java @@ -5,6 +5,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.UUIDUtil; import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.contents.TranslatableContents; import net.minecraft.network.protocol.PacketFlow; import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket; import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket; @@ -132,9 +133,14 @@ public void kill() public void kill(Component reason) { shakeOff(); - this.server.tell(new TickTask(this.server.getTickCount(), () -> { + + if (reason.getContents() instanceof TranslatableContents text && text.getKey().equals("multiplayer.disconnect.duplicate_login")) { this.connection.onDisconnect(reason); - })); + } else { + this.server.tell(new TickTask(this.server.getTickCount(), () -> { + this.connection.onDisconnect(reason); + })); + } } @Override From 41aecaafe4ec7df7302f0c5cf04f142c36f68d51 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Thu, 25 May 2023 21:14:02 +0200 Subject: [PATCH 157/233] 1.20-pre6 --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 7e8633413b..0ac13bbaaa 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,7 +3,7 @@ org.gradle.jvmargs=-Xmx1G # Fabric Properties # check https://fabricmc.net/develop/ - minecraft_version=1.20-pre5 + minecraft_version=1.20-pre6 loader_version=0.14.19 jsr305_version=3.0.2 fabric_version=0.81.2+1.20 From b8069c46a0ddd3f4288dcaa5e9b9adc8b791cbef Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Thu, 25 May 2023 21:14:13 +0200 Subject: [PATCH 158/233] 1.4.111 --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 0ac13bbaaa..72d08c48a6 100644 --- a/gradle.properties +++ b/gradle.properties @@ -9,7 +9,7 @@ org.gradle.jvmargs=-Xmx1G fabric_version=0.81.2+1.20 # Mod Properties - mod_version = 1.4.110 + mod_version = 1.4.111 maven_group = carpet archives_base_name = fabric-carpet From ad4a41e4973cfb98723870d2b9801c5be18e454f Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Mon, 29 May 2023 23:11:57 +0200 Subject: [PATCH 159/233] 1.20-pre7 --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 72d08c48a6..a45a76895b 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,7 +3,7 @@ org.gradle.jvmargs=-Xmx1G # Fabric Properties # check https://fabricmc.net/develop/ - minecraft_version=1.20-pre6 + minecraft_version=1.20-pre7 loader_version=0.14.19 jsr305_version=3.0.2 fabric_version=0.81.2+1.20 From fb6ecb90062414a7e11e34667029ce629bd02866 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Thu, 8 Jun 2023 10:49:07 +0200 Subject: [PATCH 160/233] 1.20 --- gradle.properties | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gradle.properties b/gradle.properties index a45a76895b..ec053525e0 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,7 +3,7 @@ org.gradle.jvmargs=-Xmx1G # Fabric Properties # check https://fabricmc.net/develop/ - minecraft_version=1.20-pre7 + minecraft_version=1.20 loader_version=0.14.19 jsr305_version=3.0.2 fabric_version=0.81.2+1.20 @@ -17,7 +17,7 @@ org.gradle.jvmargs=-Xmx1G # The Curseforge versions "names" or ids for the main branch (comma separated: 1.16.4,1.16.5) # This is needed because CF uses too vague names for prereleases and release candidates # Can also be the version ID directly coming from https://minecraft.curseforge.com/api/game/versions?token=[API_TOKEN] - release-curse-versions = Minecraft 1.20:1.20-Snapshot + release-curse-versions = Minecraft 1.20:1.20 # Whether or not to build another branch on release release-extra-branch = false # The name of the second branch to release From d73ec4a371f102586daee128cc5a307ff75c4869 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Thu, 8 Jun 2023 10:49:34 +0200 Subject: [PATCH 161/233] 1.4.112 --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index ec053525e0..8a800f0f97 100644 --- a/gradle.properties +++ b/gradle.properties @@ -9,7 +9,7 @@ org.gradle.jvmargs=-Xmx1G fabric_version=0.81.2+1.20 # Mod Properties - mod_version = 1.4.111 + mod_version = 1.4.112 maven_group = carpet archives_base_name = fabric-carpet From 3145614fc552a6d95f75676d2610af7302345cff Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Mon, 12 Jun 2023 22:56:04 +0200 Subject: [PATCH 162/233] 1.20.1 --- gradle.properties | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/gradle.properties b/gradle.properties index 8a800f0f97..8946439342 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,10 +3,10 @@ org.gradle.jvmargs=-Xmx1G # Fabric Properties # check https://fabricmc.net/develop/ - minecraft_version=1.20 - loader_version=0.14.19 + minecraft_version=1.20.1 + loader_version=0.14.21 jsr305_version=3.0.2 - fabric_version=0.81.2+1.20 + fabric_version=0.83.0+1.20.1 # Mod Properties mod_version = 1.4.112 @@ -17,7 +17,7 @@ org.gradle.jvmargs=-Xmx1G # The Curseforge versions "names" or ids for the main branch (comma separated: 1.16.4,1.16.5) # This is needed because CF uses too vague names for prereleases and release candidates # Can also be the version ID directly coming from https://minecraft.curseforge.com/api/game/versions?token=[API_TOKEN] - release-curse-versions = Minecraft 1.20:1.20 + release-curse-versions = Minecraft 1.20:1.20.1 # Whether or not to build another branch on release release-extra-branch = false # The name of the second branch to release From 7f6f92d0ee5937ceae44466d1ea35b58c52789fe Mon Sep 17 00:00:00 2001 From: altrisi Date: Mon, 19 Jun 2023 20:41:27 +0200 Subject: [PATCH 163/233] Add note about non-api field being used in Carpet Extra --- src/main/java/carpet/CarpetSettings.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/carpet/CarpetSettings.java b/src/main/java/carpet/CarpetSettings.java index 481b3401bc..270bae34a6 100644 --- a/src/main/java/carpet/CarpetSettings.java +++ b/src/main/java/carpet/CarpetSettings.java @@ -242,7 +242,7 @@ public String description() category = {SURVIVAL, FEATURE} ) public static String stackableShulkerBoxes = "false"; - public static int shulkerBoxStackSize = 1; + public static int shulkerBoxStackSize = 1; // Referenced from Carpet extra @Rule( desc = "Explosions won't destroy blocks", category = {CREATIVE, TNT} ) public static boolean explosionNoBlockDamage = false; From 01bec472eaa991858605ea9261487ce39a597707 Mon Sep 17 00:00:00 2001 From: altrisi Date: Thu, 22 Jun 2023 16:12:59 +0200 Subject: [PATCH 164/233] Fix syntax error in `pt_br` language file --- src/main/resources/assets/carpet/lang/pt_br.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/resources/assets/carpet/lang/pt_br.json b/src/main/resources/assets/carpet/lang/pt_br.json index c5f53d6bff..f47e5b4baa 100644 --- a/src/main/resources/assets/carpet/lang/pt_br.json +++ b/src/main/resources/assets/carpet/lang/pt_br.json @@ -15,7 +15,7 @@ "carpet.settings.command.change_permanently_tooltip": "clique para manter as configurações em %s para salvar nas reinicializações", "carpet.settings.command.default_set": "A regra %s agora será padronizada para %s", "carpet.settings.command.default_removed": "A regra %s não será mais definida na reinicialização", - "carpet.settings.command.current_value": "valor atual" + "carpet.settings.command.current_value": "valor atual", // Categories @@ -421,4 +421,4 @@ // xpNoCooldown "carpet.rule.xpNoCooldown.desc": "Os jogadores absorvem XP instantaneamente, sem demora" -} \ No newline at end of file +} From 22f31a7b51eec55332b49d07dc27ab8ad08fecba Mon Sep 17 00:00:00 2001 From: altrisi Date: Thu, 22 Jun 2023 16:20:43 +0200 Subject: [PATCH 165/233] Clean up translation file loading --- src/main/java/carpet/utils/Translations.java | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/src/main/java/carpet/utils/Translations.java b/src/main/java/carpet/utils/Translations.java index 5b854bfc74..d69e857efa 100644 --- a/src/main/java/carpet/utils/Translations.java +++ b/src/main/java/carpet/utils/Translations.java @@ -6,14 +6,13 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; -import org.apache.commons.io.IOUtils; -import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.HashMap; import java.util.Map; -import java.util.Objects; public class Translations { @@ -46,17 +45,14 @@ public static boolean hasTranslation(String key) public static Map getTranslationFromResourcePath(String path) { - String dataJSON; - try - { - dataJSON = IOUtils.toString( - Objects.requireNonNull(Translations.class.getClassLoader().getResourceAsStream(path)), - StandardCharsets.UTF_8); - } catch (NullPointerException | IOException e) { - return Map.of(); + InputStream langFile = Translations.class.getClassLoader().getResourceAsStream(path); + if (langFile == null) { + // we don't have that language + return Collections.emptyMap(); } Gson gson = new GsonBuilder().setLenient().create(); - return gson.fromJson(dataJSON, new TypeToken>() {}.getType()); + return gson.fromJson(new InputStreamReader(langFile, StandardCharsets.UTF_8), + new TypeToken>() {}); } public static void updateLanguage() From cce52f3ed163d8ac7aa77e531119d3601079a52c Mon Sep 17 00:00:00 2001 From: altrisi Date: Mon, 26 Jun 2023 17:59:57 +0200 Subject: [PATCH 166/233] Include app name in deprecation warnings (#1750) --- src/main/java/carpet/script/CarpetScriptHost.java | 2 +- src/main/java/carpet/script/ScriptHost.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/carpet/script/CarpetScriptHost.java b/src/main/java/carpet/script/CarpetScriptHost.java index e4f15faef3..6cee11d716 100644 --- a/src/main/java/carpet/script/CarpetScriptHost.java +++ b/src/main/java/carpet/script/CarpetScriptHost.java @@ -1210,7 +1210,7 @@ public boolean issueDeprecation(String feature) { if (super.issueDeprecation(feature)) { - Carpet.Messenger_message(responsibleSource, "rb '" + feature + "' is deprecated and soon will be removed. Please consult the docs for their replacement"); + Carpet.Messenger_message(responsibleSource, "rb App '" +getName() + "' uses '" + feature + "', which is deprecated for removal. Check the docs for a replacement"); return true; } return false; diff --git a/src/main/java/carpet/script/ScriptHost.java b/src/main/java/carpet/script/ScriptHost.java index 91901953ce..e20e79c397 100644 --- a/src/main/java/carpet/script/ScriptHost.java +++ b/src/main/java/carpet/script/ScriptHost.java @@ -551,7 +551,7 @@ public boolean issueDeprecation(String feature) return false; } deprecations.add(feature); - DEPRECATION_LOG.warn("'" + feature + "' is deprecated and soon will be removed. Please consult the docs for their replacement"); + DEPRECATION_LOG.warn("App '" + getName() + "' uses '" + feature + "', which is deprecated for removal. Check the docs for a replacement"); return true; } From a8fedc37e4dcfa803262e1a57502e13f917fa915 Mon Sep 17 00:00:00 2001 From: altrisi Date: Mon, 26 Jun 2023 18:19:43 +0200 Subject: [PATCH 167/233] Refactor unnecessary Stream->List in `/track` suggestions --- src/main/java/carpet/utils/MobAI.java | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/main/java/carpet/utils/MobAI.java b/src/main/java/carpet/utils/MobAI.java index 80208dd2b2..454d234b65 100644 --- a/src/main/java/carpet/utils/MobAI.java +++ b/src/main/java/carpet/utils/MobAI.java @@ -4,10 +4,9 @@ import com.google.common.collect.Sets; import java.util.HashMap; import java.util.HashSet; -import java.util.List; import java.util.Map; import java.util.Set; -import java.util.stream.Collectors; +import java.util.stream.Stream; import net.minecraft.commands.CommandSourceStack; import net.minecraft.core.BlockPos; @@ -58,23 +57,23 @@ public static void startTracking(EntityType e, TrackingType type) aiTrackers.get(e).add(type); } - public static List availbleTypes(CommandSourceStack source) + public static Stream availbleTypes(CommandSourceStack source) { Set> types = new HashSet<>(); for (TrackingType type: TrackingType.values()) { types.addAll(type.types); } - return types.stream().map(t -> source.registryAccess().registryOrThrow(Registries.ENTITY_TYPE).getKey(t).getPath()).collect(Collectors.toList()); + return types.stream().map(t -> source.registryAccess().registryOrThrow(Registries.ENTITY_TYPE).getKey(t).getPath()); } - public static List availableFor(EntityType entityType) + public static Stream availableFor(EntityType entityType) { Set availableOptions = new HashSet<>(); for (TrackingType type: TrackingType.values()) if (type.types.contains(entityType)) availableOptions.add(type); - return availableOptions.stream().map(t -> t.name().toLowerCase()).collect(Collectors.toList()); + return availableOptions.stream().map(t -> t.name().toLowerCase()); } public enum TrackingType From 177179b70ab222a51eaebba705c67e86171ae8a6 Mon Sep 17 00:00:00 2001 From: altrisi Date: Mon, 26 Jun 2023 18:33:20 +0200 Subject: [PATCH 168/233] Don't use `getPlayerOrException` in `CarpetScriptHost` --- src/main/java/carpet/script/CarpetScriptHost.java | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/src/main/java/carpet/script/CarpetScriptHost.java b/src/main/java/carpet/script/CarpetScriptHost.java index 6cee11d716..9c775c60b3 100644 --- a/src/main/java/carpet/script/CarpetScriptHost.java +++ b/src/main/java/carpet/script/CarpetScriptHost.java @@ -675,12 +675,8 @@ public CarpetScriptHost retrieveOwnForExecution(CommandSourceStack source) throw return this; } // user based - ServerPlayer player; - try - { - player = source.getPlayerOrException(); - } - catch (CommandSyntaxException ignored) + ServerPlayer player = source.getPlayer(); + if (player == null) { throw new SimpleCommandExceptionType(Component.literal("Cannot run player based apps without the player context")).create(); } @@ -1057,11 +1053,7 @@ public void setChatErrorSnooper(CommandSourceStack source) responsibleSource = source; errorSnooper = (expr, /*Nullable*/ token, ctx, message) -> { - try - { - source.getPlayerOrException(); - } - catch (CommandSyntaxException e) + if (!source.isPlayer()) { return null; } From db2023f5b9a44c04db56f8cdfc670c769a196e01 Mon Sep 17 00:00:00 2001 From: altrisi Date: Mon, 26 Jun 2023 18:41:24 +0200 Subject: [PATCH 169/233] Move app store validator to `CarpetSettings` --- src/main/java/carpet/CarpetSettings.java | 30 +++++++++++++++-- .../java/carpet/script/external/Carpet.java | 33 ------------------- .../carpet/script/utils/AppStoreManager.java | 6 +++- 3 files changed, 33 insertions(+), 36 deletions(-) diff --git a/src/main/java/carpet/CarpetSettings.java b/src/main/java/carpet/CarpetSettings.java index 270bae34a6..4caf08bf26 100644 --- a/src/main/java/carpet/CarpetSettings.java +++ b/src/main/java/carpet/CarpetSettings.java @@ -4,7 +4,7 @@ import carpet.api.settings.RuleCategory; import carpet.api.settings.Validators; import carpet.api.settings.Validator; -import carpet.script.external.Carpet; +import carpet.script.utils.AppStoreManager; import carpet.settings.Rule; import carpet.utils.Translations; import carpet.utils.CommandHelper; @@ -551,6 +551,32 @@ private static class ModulePermissionLevel extends Validator { ) public static boolean scriptsOptimization = true; + private static class ScarpetAppStore extends Validator { + @Override + public String validate(CommandSourceStack source, CarpetRule currentRule, String newValue, String stringInput) { + if (newValue.equals(currentRule.value())) { + // Don't refresh the local repo if it's the same (world change), helps preventing hitting rate limits from github when + // getting suggestions. Pending is a way to invalidate the cache when it gets old, and investigating api usage further + return newValue; + } + if (newValue.equals("none")) { + AppStoreManager.setScarpetRepoLink(null); + } else { + if (newValue.endsWith("/")) + newValue = newValue.substring(0, newValue.length() - 1); + AppStoreManager.setScarpetRepoLink("https://api.github.com/repos/" + newValue + "/"); + } + if (source != null) + CommandHelper.notifyPlayersCommandsChanged(source.getServer()); + return newValue; + } + + @Override + public String description() { + return "Appstore link should point to a valid github repository"; + } + } + @Rule( desc = "Location of the online repository of scarpet apps", extra = { @@ -560,7 +586,7 @@ private static class ModulePermissionLevel extends Validator { }, category = SCARPET, strict = false, - validate= Carpet.ScarpetAppStoreValidator.class + validate = ScarpetAppStore.class ) public static String scriptsAppStore = "gnembon/scarpet/contents/programs"; diff --git a/src/main/java/carpet/script/external/Carpet.java b/src/main/java/carpet/script/external/Carpet.java index 21182959dc..d4f92f2dd3 100644 --- a/src/main/java/carpet/script/external/Carpet.java +++ b/src/main/java/carpet/script/external/Carpet.java @@ -5,7 +5,6 @@ import carpet.api.settings.CarpetRule; import carpet.api.settings.RuleHelper; import carpet.api.settings.SettingsManager; -import carpet.api.settings.Validator; import carpet.fakes.MinecraftServerInterface; import carpet.logging.HUDController; import carpet.network.ServerNetworkHandler; @@ -17,7 +16,6 @@ import carpet.script.Module; import carpet.script.exception.InternalExpressionException; import carpet.script.exception.LoadException; -import carpet.script.utils.AppStoreManager; import carpet.script.value.MapValue; import carpet.script.value.StringValue; import carpet.utils.CarpetProfiler; @@ -241,35 +239,4 @@ public void handleAny(final Object... args) }; SettingsManager.registerGlobalRuleObserver((source, changedRule, userInput) -> carpetRuleChanges.handleAny(changedRule, source)); } - - public static class ScarpetAppStoreValidator extends Validator - { - @Override - public String validate(@Nullable CommandSourceStack source, CarpetRule currentRule, String newValue, String stringInput) - { - if (newValue.equals(currentRule.value())) - { - // Don't refresh the local repo if it's the same (world change), helps preventing hitting rate limits from github when - // getting suggestions. Pending is a way to invalidate the cache when it gets old, and investigating api usage further - return newValue; - } - if (newValue.equalsIgnoreCase("none")) - { - AppStoreManager.setScarpetRepoLink(null); - return newValue; - } - if (newValue.endsWith("/")) - { - newValue = newValue.substring(0, newValue.length() - 1); - } - AppStoreManager.setScarpetRepoLink("https://api.github.com/repos/" + newValue + "/"); - return newValue; - } - - @Override - public String description() - { - return "Appstore link should point to a valid github repository"; - } - } } diff --git a/src/main/java/carpet/script/utils/AppStoreManager.java b/src/main/java/carpet/script/utils/AppStoreManager.java index 76ebccf86a..505e73bc27 100644 --- a/src/main/java/carpet/script/utils/AppStoreManager.java +++ b/src/main/java/carpet/script/utils/AppStoreManager.java @@ -58,6 +58,10 @@ public static void setScarpetRepoLink(@Nullable String link) scarpetRepoLink = link; } + public static boolean enabled() + { + return scarpetRepoLink != null; + } private record AppInfo(String name, String url, StoreNode source) { @@ -123,7 +127,7 @@ public synchronized void fillChildren(@Nullable CommandSourceStack source) throw { return; } - if (scarpetRepoLink == null) + if (!enabled()) { throw new IOException("Accessing scarpet app repo is disabled"); } From 5b1a02997e5e4dde03ba00a558732e67ebf202f5 Mon Sep 17 00:00:00 2001 From: altrisi Date: Thu, 29 Jun 2023 15:55:11 +0200 Subject: [PATCH 170/233] Fix bitwise shift docs not mentioning mask to amount Resolves #1675 --- docs/scarpet/language/Operators.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/scarpet/language/Operators.md b/docs/scarpet/language/Operators.md index 605320fa85..c13921f9fb 100644 --- a/docs/scarpet/language/Operators.md +++ b/docs/scarpet/language/Operators.md @@ -306,13 +306,13 @@ only take integer values, so if the input has a decimal part, it will be discard - `bitwise_xor(...)` -> Does the bitwise XOR operation on each number in order. - `bitwise_or(...)` -> Does the bitwise AND operation on each number in order. Note that with larger ranges of numbers this will tend to -1. - - `bitwise_shift_left(num, amount)` -> Shifts all the bits of the first number `amount` spots to the left. Note that shifting more - than 63 positions will result in a 0 (cos you shift out all the bits of the number) + - `bitwise_shift_left(num, amount)` -> Shifts all the bits of the first number `amount` spots to the left. Note that only the 6 + lowest-order bits of the amount are considered. - `bitwise_shift_right(num, amount)` -> Shifts all the bits of the first number `amount` spots to the right logically. That is, the - `amount` most significant bits will always be set to 0. Like with the above, shifting more than 63 bits results in a 0. + `amount` most significant bits will always be set to 0. Like with the above, only the 6 lowest-order bits of the amount are considered. - `bitwise_arithmetic_shift_right(num, amount)` -> Shifts all the bits of the first number `amount` spots to the right arithmetically. That is, if the most significant (sign) bit is a 1, it'll propagate the one to the `amount` most significant bits. Like with the above, - shifting more than 63 bits results in a 0. + only the 6 lowest-order bits of the amount are considered. - `bitwise_roll_left(num, amount)` -> Rolls the bits of the first number `amount` bits to the left. This is basically where you shift out the first `amount` bits and then add them on at the back, essentially 'rolling' the number. Note that unlike with shifting, you can roll more than 63 bits at a time, as it just makes the number roll over more times, which isn't an issue From 4c134cc88a7fc9acab1ca471869bad995fedb6b4 Mon Sep 17 00:00:00 2001 From: Calvineries Date: Fri, 7 Jul 2023 12:10:02 +0200 Subject: [PATCH 171/233] Create fr_fr.json (#1741) --- src/main/java/carpet/CarpetSettings.java | 2 +- .../resources/assets/carpet/lang/fr_fr.json | 432 ++++++++++++++++++ 2 files changed, 433 insertions(+), 1 deletion(-) create mode 100644 src/main/resources/assets/carpet/lang/fr_fr.json diff --git a/src/main/java/carpet/CarpetSettings.java b/src/main/java/carpet/CarpetSettings.java index 4caf08bf26..8180db5c15 100644 --- a/src/main/java/carpet/CarpetSettings.java +++ b/src/main/java/carpet/CarpetSettings.java @@ -71,7 +71,7 @@ private static class LanguageValidator extends Validator { @Rule( desc = "Sets the language for Carpet", category = FEATURE, - options = {"en_us", "pt_br", "zh_cn", "zh_tw"}, + options = {"en_us", "fr_fr", "pt_br", "zh_cn", "zh_tw"}, strict = true, // the current system doesn't handle fallbacks and other, not defined languages would make unreadable mess. Change later validate = LanguageValidator.class ) diff --git a/src/main/resources/assets/carpet/lang/fr_fr.json b/src/main/resources/assets/carpet/lang/fr_fr.json new file mode 100644 index 0000000000..047415349b --- /dev/null +++ b/src/main/resources/assets/carpet/lang/fr_fr.json @@ -0,0 +1,432 @@ +{ + // Settings command UI elements + + "carpet.settings.command.browse_categories": "Parcourir les catégories", + "carpet.settings.command.version": "version", + "carpet.settings.command.list_all_category": "liste toutes les options de la catégorie %s", + "carpet.settings.command.current_settings_header": "Options actuelles de %s", + "carpet.settings.command.switch_to": "Passer à %s", + "carpet.settings.command.unknown_rule": "Règle inconnue", + "carpet.settings.command.current_from_file_header": "Options de démarrage actuelles de %s depuis %s", + "carpet.settings.command.mod_settings_matching": "Options de %s correspondant à \"%s\" ", + "carpet.settings.command.all_mod_settings": "Toutes les options de %s", + "carpet.settings.command.tags": "Balises", + "carpet.settings.command.change_permanently": "Changer définitivement", + "carpet.settings.command.change_permanently_tooltip": "cliquez pour conserver les options dans %s et les enregistrer entre les redémarrages", + "carpet.settings.command.default_set": "La règle %s sera désormais définie par défaut sur %s", + "carpet.settings.command.default_removed": "La règle %s ne sera plus définie au redémarrage", + "carpet.settings.command.current_value": "valeur actuelle", + + // Categories: + + "carpet.category.bugfix": "correction de bugs", + "carpet.category.survival": "survie", + "carpet.category.creative": "créatif", + "carpet.category.experimental": "expérimental", + "carpet.category.optimization": "optimisation", + "carpet.category.feature": "fonctionnalité", + "carpet.category.command": "commande", + "carpet.category.tnt": "TNT", + "carpet.category.dispenser": "distributeur", + "carpet.category.scarpet": "scarpet", + "carpet.category.client": "client", + + // Rules + + // allowSpawningOfflinePlayers + "carpet.rule.allowSpawningOfflinePlayers.desc": "Fait apparaître les joueurs hors ligne en mode en ligne si le joueur en online-mode avec le nom spécifié n'existe pas", + + // antiCheatDisabled + "carpet.rule.antiCheatDisabled.desc": "Empêche les joueurs de se téléporter en arrière lorsqu'ils se déplacent trop rapidement", + + "carpet.rule.antiCheatDisabled.extra.0": "... ou d'être expulsé pour 'vol'", + "carpet.rule.antiCheatDisabled.extra.1": "Fait davantage confiance au positionnement des clients", + "carpet.rule.antiCheatDisabled.extra.2": "Augmente la distance de minage autorisée du joueur à 32 blocs", + + // carpetCommandPermissionLevel + "carpet.rule.carpetCommandPermissionLevel.desc": "Niveau de permission pour les commandes Carpet. Peut être défini uniquement via le fichier .conf", + + // carpets + "carpet.rule.carpets.desc": "Placer des tapis peut entraîner l'exécution de commandes Carpet pour les joueurs non-opérateurs", + + // chainStone + "carpet.rule.chainStone.desc": "Les chaînes se colleront les unes aux autres sur les extrémités longues", + + "carpet.rule.chainStone.extra.0": "et se colleront aux autres blocs qui y sont directement connectés.", + "carpet.rule.chainStone.extra.1": "Avec stick_to_all : elles colleront même si elles ne sont pas connectées visuellement", + + // cleanLogs + "carpet.rule.cleanLogs.desc": "Supprime les messages indésirables des journaux", + + "carpet.rule.cleanLogs.extra.0": "N'affiche pas 'Maximum sound pool size 247 reached'", + "carpet.rule.cleanLogs.extra.1": "Ce qui est normal avec de bonnes fermes et mécanismes", + + // commandDistance + "carpet.rule.commandDistance.desc": "Active la commande /distance pour mesurer la distance en jeu entre deux points", + + "carpet.rule.commandDistance.extra.0": "Active également l'action de pose de tapis marron si la règle 'carpets' est également activée", + + // commandDraw + "carpet.rule.commandDraw.desc": "Active les commandes /draw", + + "carpet.rule.commandDraw.extra.0": "... permet de dessiner des formes simples ou", + "carpet.rule.commandDraw.extra.1": "d'autres formes qui sont un peu difficiles à réaliser normalement", + + // commandInfo + "carpet.rule.commandInfo.desc": "Active la commande /info pour les blocs", + + "carpet.rule.commandInfo.extra.0": "Active également l'action de pose de tapis gris", + "carpet.rule.commandInfo.extra.1": "si la règle 'carpets' est également activée", + + // commandLog + "carpet.rule.commandLog.desc": "Active la commande /log pour surveiller les événements via le chat et les superpositions", + + // commandPerimeterInfo + "carpet.rule.commandPerimeterInfo.desc": "Active la commande /perimeterinfo", + + "carpet.rule.commandPerimeterInfo.extra.0": "... qui analyse la zone autour du bloc pour trouver des emplacements potentiellement exploitables", + + // commandPlayer + "carpet.rule.commandPlayer.desc": "Active la commande /player pour contrôler/faire apparaître des joueurs", + + // commandProfile + "carpet.rule.commandProfile.desc": "Active la commande /profile pour surveiller les performances du jeu", + + "carpet.rule.commandProfile.extra.0": "sous-ensemble des capacités de la commande /tick", + + // commandScript + "carpet.rule.commandScript.desc": "Active la commande /script", + + "carpet.rule.commandScript.extra.0": "Une API de scripting en jeu pour le langage de programmation Scarpet", + + // commandScriptACE + "carpet.rule.commandScriptACE.desc": "Active les restrictions pour l'exécution de code arbitraire avec Scarpet", + + "carpet.rule.commandScriptACE.extra.0": "Les utilisateurs qui n'ont pas ce niveau de permission", + "carpet.rule.commandScriptACE.extra.1": "ne pourront pas charger d'applications ou exécuter /script run.", + "carpet.rule.commandScriptACE.extra.2": "C'est également le niveau de permission que les applications", + "carpet.rule.commandScriptACE.extra.3": "auront lors de l'exécution de commandes avec run()", + + // commandSpawn + "carpet.rule.commandSpawn.desc": "Active la commande /spawn pour le suivi des points d'apparition", + + // commandTick + "carpet.rule.commandTick.desc": "Active la commande /tick pour contrôler les horloges du jeu", + + // commandTrackAI + "carpet.rule.commandTrackAI.desc": "Permet de suivre l'IA des mobs via la commande /track", + + // creativeFlyDrag + "carpet.rule.creativeFlyDrag.desc": "Résistance de l'air en mode créatif", + + "carpet.rule.creativeFlyDrag.extra.0": "Une résistance accrue ralentira votre vol", + "carpet.rule.creativeFlyDrag.extra.1": "Vous devrez donc ajuster votre vitesse en conséquence", + "carpet.rule.creativeFlyDrag.extra.2": "Avec une résistance de 1.0, une vitesse de 11 semble correspondre aux vitesses normales de base.", + "carpet.rule.creativeFlyDrag.extra.3": "Paramètre purement côté client, ce qui signifie que", + "carpet.rule.creativeFlyDrag.extra.4": "le configurer sur le serveur dédié n'a aucun effet", + "carpet.rule.creativeFlyDrag.extra.5": "mais cela signifie également que cela fonctionnera également sur les serveurs vanilla", + + // creativeFlySpeed + "carpet.rule.creativeFlySpeed.desc": "Multiplicateur de vitesse de vol en mode créatif", + + "carpet.rule.creativeFlySpeed.extra.0": "Paramètre purement côté client, ce qui signifie que", + "carpet.rule.creativeFlySpeed.extra.1": "le configurer sur le serveur dédié n'a aucun effet", + "carpet.rule.creativeFlySpeed.extra.2": "mais cela signifie également que cela fonctionnera également sur les serveurs vanilla", + + // creativeNoClip + "carpet.rule.creativeNoClip.desc": "Mode créatif sans collision", + + "carpet.rule.creativeNoClip.extra.0": "Sur les serveurs, cela doit être configuré à la fois", + "carpet.rule.creativeNoClip.extra.1": "sur le client et sur le serveur pour fonctionner correctement.", + "carpet.rule.creativeNoClip.extra.2": "Aucun effet lorsqu'il est configuré uniquement sur le serveur", + "carpet.rule.creativeNoClip.extra.3": "Peut permettre de traverser les murs", + "carpet.rule.creativeNoClip.extra.4": "s'il est uniquement configuré côté client Carpet", + "carpet.rule.creativeNoClip.extra.5": "mais nécessite un peu de magie avec des trappes", + "carpet.rule.creativeNoClip.extra.6": "pour permettre au joueur d'entrer dans les blocs", + + // creativePlayersLoadChunks + "carpet.rule.creativePlayersLoadChunks.desc": "Les joueurs en mode créatif chargent les chunks, ou non ! Tout comme les spectateurs !", + + "carpet.rule.creativePlayersLoadChunks.extra.0": "La bascule se comporte exactement comme si le joueur était en mode spectateur et basculait le gamerule spectatorsGenerateChunks.", + + // ctrlQCraftingFix + "carpet.rule.ctrlQCraftingFix.desc": "Jeter des piles entières fonctionne également depuis l'interface de fabrication", + + // customMOTD + "carpet.rule.customMOTD.desc": "Définit un message MOTD différent lorsqu'un client essaie de se connecter au serveur", + + "carpet.rule.customMOTD.extra.0": "utilisez '_' pour utiliser le paramètre de démarrage de server.properties", + + // defaultLoggers + "carpet.rule.defaultLoggers.desc": "Définit ces loggers avec leurs configurations par défaut pour tous les nouveaux joueurs", + + "carpet.rule.defaultLoggers.extra.0": "utilisez une liste séparée par des virgules, comme 'tps,mobcaps' pour plusieurs loggers, aucun pour rien", + + // desertShrubs + "carpet.rule.desertShrubs.desc": "Les pousses se transforment en buissons morts dans les climats chauds et sans accès à l'eau", + + // explosionNoBlockDamage + "carpet.rule.explosionNoBlockDamage.desc": "Les explosions ne détruisent pas les blocs", + + // fastRedstoneDust + "carpet.rule.fastRedstoneDust.desc": "Optimisations de performances pour la poussière de redstone", + + "carpet.rule.fastRedstoneDust.extra.0": "par Theosib", + "carpet.rule.fastRedstoneDust.extra.1": ".. corrige également certains comportements de localisation de la redstone vanille MC-11193", + "carpet.rule.fastRedstoneDust.extra.2": "donc le comportement des dispositifs de localisation vanille n'est pas garanti", + + // fillLimit + "carpet.rule.fillLimit.desc": "[Obsolète] Limite personnalisable du volume de remplissage/clone/biomereplace", + + "carpet.rule.fillLimit.extra.0": "Utilisez la règle de jeu vanilla à la place. Ce paramètre sera supprimé dans la version 1.20.0", + + // fillUpdates + "carpet.rule.fillUpdates.desc": "Les commandes fill/clone/setblock et les blocs de structure provoquent des mises à jour de blocs", + + // flippinCactus + "carpet.rule.flippinCactus.desc": "Les joueurs peuvent retourner et faire pivoter les blocs lorsqu'ils tiennent un cactus", + + "carpet.rule.flippinCactus.extra.0": "Ne provoque pas de mises à jour de blocs lorsqu'il est retourné/faire pivoter", + "carpet.rule.flippinCactus.extra.1": "S'applique aux pistons, observateurs, distributeurs, répéteurs, escaliers, terracotta émaillée, etc.", + + // fogOff + "carpet.rule.fogOff.desc": "Supprime le brouillard du client dans le Nether et l'End", + + "carpet.rule.fogOff.extra.0": "Améliore la visibilité, mais l'apparence est étrange", + + // forceloadLimit + "carpet.rule.forceloadLimit.desc": "Limite personnalisable des chunks de chargement forcé", + + // hardcodeTNTangle + "carpet.rule.hardcodeTNTangle.desc": "Définit l'angle aléatoire horizontal de la TNT pour le débogage des dispositifs TNT", + + "carpet.rule.hardcodeTNTangle.extra.0": "Définir sur -1 pour un comportement par défaut", + + // hopperCounters + "carpet.rule.hopperCounters.desc": "Les entonnoirs pointant vers de la laine comptent les objets qui passent à travers eux", + + "carpet.rule.hopperCounters.extra.0": "Active la commande /counter et les actions lors de la pose de tapis rouge et vert sur des blocs de laine", + "carpet.rule.hopperCounters.extra.1": "Utilisez /counter reset pour réinitialiser le compteur et /counter pour interroger", + "carpet.rule.hopperCounters.extra.2": "En mode survie, placez un tapis vert sur de la laine de même couleur pour interroger, rouge pour réinitialiser les compteurs", + "carpet.rule.hopperCounters.extra.3": "Les compteurs sont globaux et partagés entre les joueurs, 16 canaux disponibles", + "carpet.rule.hopperCounters.extra.4": "Les objets comptés sont détruits, comptez jusqu'à une pile par tick par entonnoir", + + // huskSpawningInTemples + "carpet.rule.huskSpawningInTemples.desc": "Seuls les Husks apparaissent dans les temples du désert", + + // interactionUpdates + "carpet.rule.interactionUpdates.desc": "La pose de blocs provoque des mises à jour de blocs", + + // lagFreeSpawning + "carpet.rule.lagFreeSpawning.desc": "L'apparition nécessite beaucoup moins de CPU et de mémoire", + + // language + "carpet.rule.language.desc": "Définit la langue pour Carpet", + + // lightEngineMaxBatchSize + "carpet.rule.lightEngineMaxBatchSize.desc": "Modifie la taille maximale du lot de tâches d'éclairage", + + "carpet.rule.lightEngineMaxBatchSize.extra.0": "Permet une tolérance supérieure à l'extinction de la lumière", + "carpet.rule.lightEngineMaxBatchSize.extra.1": "en le réglant sur 5 - Limite par défaut définie par le jeu", + + // lightningKillsDropsFix + "carpet.rule.lightningKillsDropsFix.desc": "La foudre détruit les objets qui tombent lorsque la foudre tue une entité", + + "carpet.rule.lightningKillsDropsFix.extra.0": "En le réglant sur true, la foudre ne détruira pas les objets", + "carpet.rule.lightningKillsDropsFix.extra.1": "Corrige MC-206922.", + + // liquidDamageDisabled + "carpet.rule.liquidDamageDisabled.desc": "Désactive la destruction de blocs causée par les liquides en mouvement", + + // maxEntityCollisions + "carpet.rule.maxEntityCollisions.desc": "Limites personnalisables de collisions d'entités maximales, 0 pour aucune limite", + + // mergeTNT + "carpet.rule.mergeTNT.desc": "Fusionne les entités TNT amorcées immobiles", + + // missingTools + "carpet.rule.missingTools.desc": "Le verre peut être cassé plus rapidement avec des pioches", + + // moreBlueSkulls + "carpet.rule.moreBlueSkulls.desc": "Augmente à des fins de test le nombre de têtes bleues tirées par l'Wither", + + // movableAmethyst + "carpet.rule.movableAmethyst.desc": "Permet aux blocs d'améthystes en bourgeonnement d'être déplacés", + + "carpet.rule.movableAmethyst.extra.0": "Permet de les déplacer avec des pistons", + "carpet.rule.movableAmethyst.extra.1": "et ajoute un drop supplémentaire lors de l'extraction avec une pioche enchantée avec Soie Toucher", + + // movableBlockEntities + "carpet.rule.movableBlockEntities.desc": "Les pistons peuvent pousser des blocs entités, comme des entonnoirs, des coffres, etc.", + + // optimizedTNT + "carpet.rule.optimizedTNT.desc": "Le TNT provoque moins de lag lorsqu'il explose au même endroit et dans des liquides", + + // perfPermissionLevel + "carpet.rule.perfPermissionLevel.desc": "Niveau de permission requis pour la commande /perf", + + // persistentParrots + "carpet.rule.persistentParrots.desc": "Les perroquets ne quittent pas vos épaules tant que vous ne subissez pas de dégâts appropriés", + + // piglinsSpawningInBastions + "carpet.rule.piglinsSpawningInBastions.desc": "Les Piglins réapparaissent dans les vestiges des bastions", + + "carpet.rule.piglinsSpawningInBastions.extra.0": "Comprend les piglins, les brutes et quelques hoglins", + + // pingPlayerListLimit + "carpet.rule.pingPlayerListLimit.desc": "Limite d'échantillonnage de la liste des joueurs pour la liste de serveurs ping (menu multijoueur)", + + // placementRotationFix + "carpet.rule.placementRotationFix.desc": "Corrige le problème de rotation de placement de bloc lorsqu'un joueur fait rapidement tourner les blocs en les plaçant", + + // portalCreativeDelay + "carpet.rule.portalCreativeDelay.desc": "Nombre de ticks de délai pour utiliser un portail du Nether en mode Créatif", + + // portalSurvivalDelay + "carpet.rule.portalSurvivalDelay.desc": "Nombre de ticks de délai pour utiliser un portail du Nether en mode Survie", + + // pushLimit + "carpet.rule.pushLimit.desc": "Limite de poussée personnalisable des pistons", + + // quasiConnectivity + "carpet.rule.quasiConnectivity.desc": "Les pistons, les droppers et les distributeurs vérifient la puissance du ou des blocs situés au-dessus d'eux.", + + "carpet.rule.quasiConnectivity.extra.0": "Définit la portée à laquelle les pistons, les droppers et les distributeurs vérifient la 'quasi puissance'.", + + // railPowerLimit + "carpet.rule.railPowerLimit.desc": "Portée personnalisable de puissance des rails alimentés", + + // renewableBlackstone + "carpet.rule.renewableBlackstone.desc": "Générateur de basalte du Nether sans sable des âmes en dessous", + + "carpet.rule.renewableBlackstone.extra.0": ".. se transformera en blackstone à la place", + + // renewableCoral + "carpet.rule.renewableCoral.desc": "Les structures de corail poussent avec de l'engrais à partir de plantes de corail", + + "carpet.rule.renewableCoral.extra.0": "L'extension permet également de faire pousser à partir de ventilateurs de corail pour une culture durable en dehors des océans chauds", + + // renewableDeepslate + "carpet.rule.renewableDeepslate.desc": "La lave et l'eau génèrent de la pierre profonde et de la pierre profonde ciselée en dessous de Y0", + + // renewableSponges + "carpet.rule.renewableSponges.desc": "Les gardiens se transforment en gardiens anciens lorsqu'ils sont frappés par la foudre", + + // rotatorBlock + "carpet.rule.rotatorBlock.desc": "Les cactus dans les distributeurs font tourner les blocs.", + + "carpet.rule.rotatorBlock.extra.0": "Tourne les blocs dans le sens antihoraire si possible", + + // scriptsAppStore + "carpet.rule.scriptsAppStore.desc": "Emplacement du dépôt en ligne des applications scarpet", + + "carpet.rule.scriptsAppStore.extra.0": "Définissez sur 'none' pour désactiver.", + "carpet.rule.scriptsAppStore.extra.1": "Indiquez n'importe quel référentiel github avec des applications scarpet", + "carpet.rule.scriptsAppStore.extra.2": "en utilisant //contents/", + + // scriptsAutoload + "carpet.rule.scriptsAutoload.desc": "Les scripts scarpet des fichiers du monde se chargeront automatiquement au démarrage du serveur/monde", + + "carpet.rule.scriptsAutoload.extra.0": "si /script est activé", + + // scriptsDebugging + "carpet.rule.scriptsDebugging.desc": "Active les messages de débogage des scripts dans le journal système", + + // scriptsOptimization + "carpet.rule.scriptsOptimization.desc": "Active l'optimisation des scripts", + + // sculkSensorRange + "carpet.rule.sculkSensorRange.desc": "Portée personnalisable du capteur sculk", + + // shulkerSpawningInEndCities + "carpet.rule.shulkerSpawningInEndCities.desc": "Les Shulkers réapparaissent dans les cités de l'End", + + // silverFishDropGravel + "carpet.rule.silverFishDropGravel.desc": "Les poissons d'argent laissent tomber un objet gravier lorsqu'ils sortent d'un bloc", + + // simulationDistance + "carpet.rule.simulationDistance.desc": "Modifie la distance de simulation du serveur.", + + "carpet.rule.simulationDistance.extra.0": "Définir sur 0 pour ne pas remplacer la valeur dans les paramètres du serveur.", + + // smoothClientAnimations + "carpet.rule.smoothClientAnimations.desc": "Animation fluide du client avec des paramètres faibles de TPS", + + "carpet.rule.smoothClientAnimations.extra.0": "Fonctionne uniquement en mode un joueur et ralentit les joueurs", + + // spawnChunksSize + "carpet.rule.spawnChunksSize.desc": "Modifie la taille des tronçons de génération", + + "carpet.rule.spawnChunksSize.extra.0": "Définit le nouveau rayon", + "carpet.rule.spawnChunksSize.extra.1": "Définir sur 0 - désactive les tronçons de génération", + + // stackableShulkerBoxes + "carpet.rule.stackableShulkerBoxes.desc": "Les boîtes de shulker vides peuvent s'empiler lorsqu'elles sont jetées au sol.", + + "carpet.rule.stackableShulkerBoxes.extra.0": ".. ou lorsqu'elles sont manipulées à l'intérieur des inventaires", + + // structureBlockIgnored + "carpet.rule.structureBlockIgnored.desc": "Modifie le bloc ignoré par le bloc de structure", + + // structureBlockLimit + "carpet.rule.structureBlockLimit.desc": "Limite personnalisable du bloc de structure sur chaque axe", + + "carpet.rule.structureBlockLimit.extra.0": "AVERTISSEMENT : doit être permanent pour un chargement correct.", + "carpet.rule.structureBlockLimit.extra.1": "Il est recommandé de définir 'structureBlockIgnored' sur 'air'", + "carpet.rule.structureBlockLimit.extra.2": "lors de l'enregistrement de structures massives.", + "carpet.rule.structureBlockLimit.extra.3": "Nécessaire sur le client du joueur qui édite le bloc de structure.", + "carpet.rule.structureBlockLimit.extra.4": "'structureBlockOutlineDistance' peut être nécessaire pour", + "carpet.rule.structureBlockLimit.extra.5": "un rendu correct des structures longues.", + + // structureBlockOutlineDistance + "carpet.rule.structureBlockOutlineDistance.desc": "Distance de rendu personnalisable de l'aperçu du bloc de structure", + + "carpet.rule.structureBlockOutlineDistance.extra.0": "Nécessaire sur le client pour fonctionner correctement", + + // summonNaturalLightning + "carpet.rule.summonNaturalLightning.desc": "L'invocation d'un éclair a tous les effets secondaires d'un éclair naturel", + + // superSecretSetting + "carpet.rule.superSecretSetting.desc": "Gbhs sgnf sadsgras fhskdpri !!!", + + // thickFungusGrowth + "carpet.rule.thickFungusGrowth.desc": "Permet de faire pousser des champignons du Nether avec une base de 3x3 avec de l'engrais", + + "carpet.rule.thickFungusGrowth.extra.0": "Le réglage sur 'all' fera pousser tous les champignons du Nether en arbres de 3x3", + "carpet.rule.thickFungusGrowth.extra.1": "Le réglage sur 'random' fera pousser 6% de tous les champignons du Nether en arbres de 3x3", + "carpet.rule.thickFungusGrowth.extra.2": "(ceci est cohérent avec la génération du monde)", + + // tickSyncedWorldBorders + "carpet.rule.tickSyncedWorldBorders.desc": "Déplace les limites du monde en fonction du temps de jeu plutôt que du temps réel", + + "carpet.rule.tickSyncedWorldBorders.extra.0": "Cela a pour effet que lorsque le taux de ticks change, la vitesse des limites du monde change également proportionnellement", + + // tntDoNotUpdate + "carpet.rule.tntDoNotUpdate.desc": "La TNT ne se met pas à jour lorsqu'elle est placée contre une source de courant", + + // tntPrimerMomentumRemoved + "carpet.rule.tntPrimerMomentumRemoved.desc": "Supprime l'élan aléatoire de la TNT lorsqu'elle est amorcée", + + // tntRandomRange + "carpet.rule.tntRandomRange.desc": "Définit la plage d'explosion aléatoire de la TNT sur une valeur fixe", + + "carpet.rule.tntRandomRange.extra.0": "Définir sur -1 pour le comportement par défaut", + + // updateSuppressionBlock + "carpet.rule.updateSuppressionBlock.desc": "Placer un rail d'activation sur le dessus d'un bloc de barrière remplira la pile de mise à jour des voisins lorsque le rail s'éteint.", + + "carpet.rule.updateSuppressionBlock.extra.0": "L'entier saisi correspond au nombre de mises à jour qui doivent rester dans la pile", + "carpet.rule.updateSuppressionBlock.extra.1": "-1 pour le désactiver", + + // viewDistance + "carpet.rule.viewDistance.desc": "Modifie la distance de vue du serveur.", + + "carpet.rule.viewDistance.extra.0": "Définir sur 0 pour ne pas remplacer la valeur dans les paramètres du serveur.", + + // xpFromExplosions + "carpet.rule.xpFromExplosions.desc": "L'expérience tombera de tous les blocs qui produisent de l'expérience lors d'une explosion de tout type", + + // xpNoCooldown + "carpet.rule.xpNoCooldown.desc": "Les joueurs absorbent instantanément l'expérience, sans délai" + +} From 5e5c434e8145b028da6b547e4c5e85f49700b207 Mon Sep 17 00:00:00 2001 From: Ghoulboy Date: Fri, 7 Jul 2023 14:54:21 +0200 Subject: [PATCH 172/233] Updating Scarpet docs for BlockIterations.md (#1757) --- docs/scarpet/api/BlocksAndWorldAccess.md | 26 ++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/docs/scarpet/api/BlocksAndWorldAccess.md b/docs/scarpet/api/BlocksAndWorldAccess.md index 86d11329ad..70c266a92f 100644 --- a/docs/scarpet/api/BlocksAndWorldAccess.md +++ b/docs/scarpet/api/BlocksAndWorldAccess.md @@ -241,9 +241,10 @@ If called with no args, returns `'clear'`, `'rain` or `'thunder'` based on the c always return `'thunder'`, if not will return `'rain'` or `'clear'` based on the current weather. With one arg, (either `'clear'`, `'rain` or `'thunder'`), returns the number of remaining ticks for that weather type. -NB: It can thunder without there being a thunderstorm, there has to be both rain and thunder to form a storm. +NB: It can thunder without there being a thunderstorm; there has to be both rain and thunder to form a storm. So if +running `weather()` returns `'thunder'`, you can use `weather('rain')>0` to see if there's a storm going on. -With two args, sets the weather to `type` for `ticks` ticks. +With two args, sets the weather to the given `type` for `ticks` ticks. ## Block and World querying @@ -292,6 +293,7 @@ back in state definition in various applications where block properties are requ Throws `unknown_block` if the provided input is not valid.
      +set(x,y,z,'iron_block'); block_state(x,y,z)  => {}
       set(x,y,z,'iron_trapdoor','half','top'); block_state(x,y,z)  => {waterlogged: false, half: top, open: false, ...}
       set(x,y,z,'iron_trapdoor','half','top'); block_state(x,y,z,'half')  => top
       block_state('iron_trapdoor','half')  => top
      @@ -303,7 +305,14 @@ bool(block_state(block('iron_trapdoor[half=top]'),'powered'))  => 0
       
       ### `block_list()`, `block_list(tag)`
       
      -Returns list of all blocks. If tag is provided, returns list of blocks that belong to this block tag.
      +Returns list of all blocks in the game. If `tag` is provided, returns list of all blocks that belong to this block tag.
      +
      +block_list() => [dark_oak_button, wall_torch, structure_block, polished_blackstone_brick_slab, cherry_sapling... ]
      +block_list('impermeable') => [glass, white_stained_glass, orange_stained_glass, magenta_stained_glass... ] //All da glass
      +block_list('rails') => [rail, powered_rail, detector_rail, activator_rail]
      +block_list('not_a_valid_block_tag') => null //Not a valid block tag
      +
      + ### `block_tags()`, `block_tags(block)`, `block_tags(block, tag)` @@ -313,12 +322,21 @@ to this tag, and `true` if the block belongs to the tag. Throws `unknown_block` if `block` doesn't exist +
      +block_tags() => [geode_invalid_blocks, wall_post_override, ice, wooden_stairs, bamboo_blocks, stone_bricks... ]
      +block_tags('iron_block') => [mineable/pickaxe, needs_stone_tool, beacon_base_blocks]
      +block_tags('glass') => [impermeable]
      +block_tags('glass', 'impermeable') => true
      +block_tags('glass', 'beacon_base_blocks') => false
      +
      + ### `block_data(pos)` Return NBT string associated with specific location, or null if the block does not carry block data. Can be currently used to match specific information from it, or use it to copy to another block -
          block_data(x,y,z) => '{TransferCooldown:0,x:450,y:68, ... }'
      +
      +block_data(x,y,z) => '{TransferCooldown:0,x:450,y:68, ... }'
       
      ### `poi(pos), poi(pos, radius?, type?, status?, column_search?)` From e5c395485b12dc788f2e3489821675163c4e54be Mon Sep 17 00:00:00 2001 From: Ghoulboy Date: Fri, 7 Jul 2023 14:55:08 +0200 Subject: [PATCH 173/233] Updating Scarpet docs for BlockIterations.md (#1754) --- docs/scarpet/api/BlockIterations.md | 31 +++++++++++++++++++---------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/docs/scarpet/api/BlockIterations.md b/docs/scarpet/api/BlockIterations.md index 1a5e609160..fccce48e26 100644 --- a/docs/scarpet/api/BlockIterations.md +++ b/docs/scarpet/api/BlockIterations.md @@ -6,13 +6,15 @@ These functions help scan larger areas of blocks without using generic loop func Evaluates expression over area of blocks defined by its center `center = (cx, cy, cz)`, expanded in all directions by `range = (dx, dy, dz)` blocks, or optionally in negative with `range` coords, and `upper_range` coords in -positive values, so you can use that if you know the lower coord, and dimension by calling `'scan(center, 0, 0, 0, w, h, d, ...)`. +positive values. That means that if you want a box starting at the northwest coord with given base, width and height +dimensions, you can do `'scan(center, 0, 0, 0, w, h, d, ...)`. `center` can be defined either as three coordinates, a single tuple of three coords, or a block value. -`range` and `upper_range` can have the same representations, just if they are block values, it computes the distance to the center -as range instead of taking the values as is. +`range` and `upper_range` can have the same representations, just if they are block values, it computes the distance to +the center as range instead of taking the values as is. That way you can iterate from the center to a box whose surface +area constains the `range` and/or `upper_range` blocks. -`expr` receives `_x, _y, _z` as coords of current analyzed block and `_`, which represents the block itself. +`expr` receives `_x, _y, _z` variables as coords of current analyzed block and `_`, which represents the block itself. Returns number of successful evaluations of `expr` (with `true` boolean result) unless called in void context, which would cause the expression not be evaluated for their boolean value. @@ -36,19 +38,26 @@ Returns the list of 6 neighbouring blocks to the argument. Commonly used with ot for(neighbours(x,y,z),air(_)) => 4 // number of air blocks around a block
      -### `rect(centre, range?, upper_range?)` +### `rect(center, range?, upper_range?)` Returns an iterator, just like `range` function that iterates over a rectangular area of blocks. If only center -point is specified, it iterates over 27 blocks. If `range` arguments are specified, expands selection by the respective -number of blocks in each direction. If `positive_range` arguments are specified, - it uses `range` for negative offset, and `positive_range` for positive. +point is specified, it iterates over 27 blocks (range of 1). If `range` arguments are specified, expands selection by +the respective number of blocks in each direction. If `upper_range` arguments are specified, it uses `range` for +negative offset, and `upper_range` for positive, similar to `scan`. + +Basically the arguments are the same as the first three arguments of `scan`, except this function returns the list of +blocks that `scan` would evaluate over. If you are going to iterate over these blocks, like `for(rect(args), do_something())`, +then `scan(args, do_something())` is an equivalent, yet more compute-friendly alternative, especially for very large areas. -`centre` can be defined either as three coordinates, a list of three coords, or a block value. -`range` and `positive_range` can have the same representations, just if they are block values, it computes the distance to the center +`center` can be defined either as three coordinates, a list of three coords, or a block value. +`range` and `upper_range` can have the same representations, just if they are block values, it computes the distance to the center as range instead of taking the values as is.` -### `diamond(centre_pos, radius?, height?)` +### `diamond(center_pos, radius?, height?)` Iterates over a diamond like area of blocks. With no radius and height, its 7 blocks centered around the middle (block + neighbours). With a radius specified, it expands shape on x and z coords, and with a custom height, on y. Any of these can be zero as well. radius of 0 makes a stick, height of 0 makes a diamond shape pad. + +If radius and height are the same, creats a 3D diamond, of all the blocks which are a manhattan distance of `radius` away +from the center. From 5374d5b5ab826f2e82148ba0f52421bb558403cf Mon Sep 17 00:00:00 2001 From: altrisi Date: Tue, 25 Jul 2023 21:17:05 +0200 Subject: [PATCH 174/233] Don't check writable in `CarpetRulePrinter` Turns out that means the file has to exist, and messes with Carpet Extra's printer --- src/main/java/carpet/utils/CarpetRulePrinter.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/carpet/utils/CarpetRulePrinter.java b/src/main/java/carpet/utils/CarpetRulePrinter.java index 62d14d4fb8..34be3ca3cb 100644 --- a/src/main/java/carpet/utils/CarpetRulePrinter.java +++ b/src/main/java/carpet/utils/CarpetRulePrinter.java @@ -35,7 +35,7 @@ public void onInitializeServer() { // Prepare an OptionParser for our parameters OptionParser parser = new OptionParser(); OptionSpec shouldDump = parser.accepts("carpetDumpRules"); - OptionSpec pathSpec = parser.accepts("dumpPath").withRequiredArg().withValuesConvertedBy(new PathConverter(PathProperties.WRITABLE)); + OptionSpec pathSpec = parser.accepts("dumpPath").withRequiredArg().withValuesConvertedBy(new PathConverter()); OptionSpec filterSpec = parser.accepts("dumpFilter").withRequiredArg(); parser.allowsUnrecognizedOptions(); // minecraft may need more stuff later that we don't want to special-case OptionSet options = parser.parse(args); From f60ea8f84cb3a6af31f3eeb32c10f7f9e69e0269 Mon Sep 17 00:00:00 2001 From: James McCulloch Date: Wed, 26 Jul 2023 21:25:27 +1000 Subject: [PATCH 175/233] Fix golem spawning range box in ai-tracker (#1761) --- src/main/resources/assets/carpet/scripts/ai_tracker.sc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/resources/assets/carpet/scripts/ai_tracker.sc b/src/main/resources/assets/carpet/scripts/ai_tracker.sc index 6bf87ab5ab..bcf80eac3f 100644 --- a/src/main/resources/assets/carpet/scripts/ai_tracker.sc +++ b/src/main/resources/assets/carpet/scripts/ai_tracker.sc @@ -35,7 +35,7 @@ global_functions = { villager_height = e~'height'; __create_box(abnoxious_visuals, e, [-8,-6,-8], - [8,7,8], + [9,7,9], 0x00dd0000, 'golem spawning', true ); __create_box(abnoxious_visuals, e, From 5516b41a76ede76d60226db977df904aaededfb0 Mon Sep 17 00:00:00 2001 From: altrisi Date: Wed, 26 Jul 2023 13:27:53 +0200 Subject: [PATCH 176/233] Fix root command in `ai_tracker` --- src/main/resources/assets/carpet/scripts/ai_tracker.sc | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/resources/assets/carpet/scripts/ai_tracker.sc b/src/main/resources/assets/carpet/scripts/ai_tracker.sc index bcf80eac3f..d3ccd7cba8 100644 --- a/src/main/resources/assets/carpet/scripts/ai_tracker.sc +++ b/src/main/resources/assets/carpet/scripts/ai_tracker.sc @@ -1,4 +1,4 @@ -_command() -> ' +print_info() -> print(' ai_tracker allows to display some extra information about various entities AI activity @@ -22,7 +22,7 @@ Settings you may want to change - update_frequency: changes update speed - clear: removes all options - transparency: default opacity of shapes, 8 for start -'; +'); global_functions = { @@ -373,7 +373,7 @@ global_hostile_to_villager = { __config() ->{ 'commands'->{ - ''->'_command', + ''->'print_info', 'clear'->'clear', 'toggle_boxes'->_()->global_display_boxes = !global_display_boxes, ''->['__toggle',null], From dd902fd77cf12c51441ef475eebc11c4d684cac4 Mon Sep 17 00:00:00 2001 From: AngelBottomless Date: Wed, 26 Jul 2023 22:40:00 +0900 Subject: [PATCH 177/233] Fix piglin brutes spawning in air (#1769) --- .../PiglinBrute_getPlacementTypeMixin.java | 33 +++++++++++++++++++ src/main/resources/carpet.mixins.json | 2 +- 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 src/main/java/carpet/mixins/PiglinBrute_getPlacementTypeMixin.java diff --git a/src/main/java/carpet/mixins/PiglinBrute_getPlacementTypeMixin.java b/src/main/java/carpet/mixins/PiglinBrute_getPlacementTypeMixin.java new file mode 100644 index 0000000000..0a0376de0b --- /dev/null +++ b/src/main/java/carpet/mixins/PiglinBrute_getPlacementTypeMixin.java @@ -0,0 +1,33 @@ +package carpet.mixins; + +import carpet.CarpetSettings; +import net.minecraft.core.BlockPos; +import net.minecraft.util.RandomSource; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.MobSpawnType; +import net.minecraft.world.entity.SpawnPlacements; +import net.minecraft.world.entity.monster.Monster; +import net.minecraft.world.entity.monster.piglin.Piglin; +import net.minecraft.world.entity.monster.piglin.PiglinBrute; +import net.minecraft.world.level.LevelAccessor; +import net.minecraft.world.level.ServerLevelAccessor; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.levelgen.Heightmap; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(SpawnPlacements.class) +public class PiglinBrute_getPlacementTypeMixin { + @Inject(method = "getPlacementType", at = @At("HEAD"), cancellable = true) + private static void getPlacementType(EntityType entityType, CallbackInfoReturnable cir) { + if (CarpetSettings.piglinsSpawningInBastions && entityType == EntityType.PIGLIN_BRUTE) { + cir.setReturnValue(SpawnPlacements.Type.ON_GROUND); + } + } +} diff --git a/src/main/resources/carpet.mixins.json b/src/main/resources/carpet.mixins.json index c6af4fd698..2594ed2111 100644 --- a/src/main/resources/carpet.mixins.json +++ b/src/main/resources/carpet.mixins.json @@ -26,7 +26,7 @@ "ServerStatus_motdMixin", "MinecraftServer_pingPlayerSampleLimit", "HugeFungusFeatureMixin", - + "PiglinBrute_getPlacementTypeMixin", "MinecraftServer_coreMixin", "MinecraftServer_tickspeedMixin", From 36908d6578e4c69f119a497eb78f4f7178c3e7b2 Mon Sep 17 00:00:00 2001 From: altrisi Date: Wed, 26 Jul 2023 16:39:31 +0200 Subject: [PATCH 178/233] Fix sending Carpet tickrate to players without Carpet installed Fixes #1772 --- src/main/java/carpet/network/ServerNetworkHandler.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/carpet/network/ServerNetworkHandler.java b/src/main/java/carpet/network/ServerNetworkHandler.java index c216f003f8..0c525f0331 100644 --- a/src/main/java/carpet/network/ServerNetworkHandler.java +++ b/src/main/java/carpet/network/ServerNetworkHandler.java @@ -79,7 +79,7 @@ public static void onHello(ServerPlayer playerEntity, FriendlyByteBuf packetData else CarpetSettings.LOG.warn("Player "+playerEntity.getName().getString()+" joined with another carpet version: "+clientVersion); - DataBuilder data = DataBuilder.create(playerEntity.server);//;.withTickRate().withFrozenState().withTickPlayerActiveTimeout(); // .withSuperHotState() + DataBuilder data = DataBuilder.create(playerEntity.server); // tickrate related settings are sent on world change CarpetServer.settingsManager.getCarpetRules().forEach(data::withRule); CarpetServer.extensions.forEach(e -> { SettingsManager eManager = e.extensionSettingsManager(); @@ -91,6 +91,7 @@ public static void onHello(ServerPlayer playerEntity, FriendlyByteBuf packetData } public static void sendPlayerLevelData(ServerPlayer player, ServerLevel level) { + if (CarpetSettings.superSecretSetting || !validCarpetPlayers.contains(player)) return; DataBuilder data = DataBuilder.create(player.server).withTickRate().withFrozenState().withTickPlayerActiveTimeout(); // .withSuperHotState() player.connection.send(new ClientboundCustomPayloadPacket(CarpetClient.CARPET_CHANNEL, data.build() )); From ac588c3e55984d0cf195103a4bf0cf6081588a74 Mon Sep 17 00:00:00 2001 From: altrisi Date: Wed, 26 Jul 2023 19:01:03 +0200 Subject: [PATCH 179/233] Add utility method to easily run code on all `SettingsManager`s (#1696) --- src/main/java/carpet/CarpetServer.java | 45 +++++++++---------- ...ientPacketListener_clientCommandMixin.java | 7 +-- .../carpet/network/ServerNetworkHandler.java | 12 +---- 3 files changed, 25 insertions(+), 39 deletions(-) diff --git a/src/main/java/carpet/CarpetServer.java b/src/main/java/carpet/CarpetServer.java index 94fb270498..b2e5248770 100644 --- a/src/main/java/carpet/CarpetServer.java +++ b/src/main/java/carpet/CarpetServer.java @@ -4,6 +4,7 @@ import java.util.HashSet; import java.util.List; import java.util.Set; +import java.util.function.Consumer; import carpet.commands.CounterCommand; import carpet.commands.DistanceCommand; @@ -88,12 +89,8 @@ public static void onServerLoaded(MinecraftServer server) // shoudl not be needed - that bit needs refactoring, but not now. SpawnReporter.reset_spawn_stats(server, true); - settingsManager.attachServer(server); - extensions.forEach(e -> { - SettingsManager sm = e.extensionSettingsManager(); - if (sm != null) sm.attachServer(server); - e.onServerLoaded(server); - }); + forEachManager(sm -> sm.attachServer(server)); + extensions.forEach(e -> e.onServerLoaded(server)); scriptServer = new CarpetScriptServer(server); Carpet.MinecraftServer_addScriptServer(server, scriptServer); MobAI.resetTrackers(); @@ -106,7 +103,7 @@ public static void onServerLoadedWorlds(MinecraftServer minecraftServer) HopperCounter.resetAll(minecraftServer, true); extensions.forEach(e -> e.onServerLoadedWorlds(minecraftServer)); // initialize scarpet rules after all extensions are loaded - settingsManager.initializeScarpetRules(); + forEachManager(SettingsManager::initializeScarpetRules); // run fillLimit rule migration now that gamerules are available @SuppressWarnings("unchecked") CarpetRule fillLimit = (CarpetRule) settingsManager.getCarpetRule("fillLimit"); @@ -117,12 +114,6 @@ public static void onServerLoadedWorlds(MinecraftServer minecraftServer) { throw new AssertionError(); } - extensions.forEach(e -> { - if (e.extensionSettingsManager() != null) - { - e.extensionSettingsManager().initializeScarpetRules(); - } - }); scriptServer.initializeForWorld(); } @@ -145,11 +136,8 @@ public static void registerCarpetCommands(CommandDispatcher { return; } - settingsManager.registerCommand(dispatcher, commandBuildContext); - extensions.forEach(e -> { - SettingsManager sm = e.extensionSettingsManager(); - if (sm != null) sm.registerCommand(dispatcher, commandBuildContext); - }); + forEachManager(sm -> sm.registerCommand(dispatcher, commandBuildContext)); + TickCommand.register(dispatcher, commandBuildContext); ProfileCommand.register(dispatcher, commandBuildContext); CounterCommand.register(dispatcher, commandBuildContext); @@ -231,11 +219,22 @@ public static void onServerClosed(MinecraftServer server) } public static void onServerDoneClosing(MinecraftServer server) { - settingsManager.detachServer(); - extensions.forEach(e -> { - SettingsManager manager = e.extensionSettingsManager(); - if (manager != null) manager.detachServer(); - }); + forEachManager(SettingsManager::detachServer); + } + + // not API + // carpet's included + public static void forEachManager(Consumer consumer) + { + consumer.accept(settingsManager); + for (CarpetExtension e : extensions) + { + SettingsManager manager = e.extensionSettingsManager(); + if (manager != null) + { + consumer.accept(manager); + } + } } public static void registerExtensionLoggers() diff --git a/src/main/java/carpet/mixins/ClientPacketListener_clientCommandMixin.java b/src/main/java/carpet/mixins/ClientPacketListener_clientCommandMixin.java index 2b98456b46..61ba0dd6d0 100644 --- a/src/main/java/carpet/mixins/ClientPacketListener_clientCommandMixin.java +++ b/src/main/java/carpet/mixins/ClientPacketListener_clientCommandMixin.java @@ -2,7 +2,6 @@ import carpet.CarpetServer; import carpet.network.CarpetClient; -import carpet.api.settings.SettingsManager; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientPacketListener; import net.minecraft.client.player.LocalPlayer; @@ -29,11 +28,7 @@ private void inspectMessage(String string, CallbackInfo ci) if (CarpetServer.minecraft_server == null && !CarpetClient.isCarpet() && minecraft.player != null) { LocalPlayer playerSource = minecraft.player; - CarpetServer.settingsManager.inspectClientsideCommand(playerSource.createCommandSourceStack(), "/"+string); - CarpetServer.extensions.forEach(e -> { - SettingsManager sm = e.extensionSettingsManager(); - if (sm != null) sm.inspectClientsideCommand(playerSource.createCommandSourceStack(), "/"+string); - }); + CarpetServer.forEachManager(sm -> sm.inspectClientsideCommand(playerSource.createCommandSourceStack(), "/" + string)); } } } diff --git a/src/main/java/carpet/network/ServerNetworkHandler.java b/src/main/java/carpet/network/ServerNetworkHandler.java index 0c525f0331..c2cf113d19 100644 --- a/src/main/java/carpet/network/ServerNetworkHandler.java +++ b/src/main/java/carpet/network/ServerNetworkHandler.java @@ -8,7 +8,6 @@ import carpet.fakes.ServerGamePacketListenerImplInterface; import carpet.helpers.ServerTickRateManager; import carpet.script.utils.SnoopyCommandSource; -import carpet.api.settings.SettingsManager; import io.netty.buffer.Unpooled; import java.util.ArrayList; import java.util.HashMap; @@ -78,16 +77,9 @@ public static void onHello(ServerPlayer playerEntity, FriendlyByteBuf packetData CarpetSettings.LOG.info("Player "+playerEntity.getName().getString()+" joined with a matching carpet client"); else CarpetSettings.LOG.warn("Player "+playerEntity.getName().getString()+" joined with another carpet version: "+clientVersion); - DataBuilder data = DataBuilder.create(playerEntity.server); // tickrate related settings are sent on world change - CarpetServer.settingsManager.getCarpetRules().forEach(data::withRule); - CarpetServer.extensions.forEach(e -> { - SettingsManager eManager = e.extensionSettingsManager(); - if (eManager != null) { - eManager.getCarpetRules().forEach(data::withRule); - } - }); - playerEntity.connection.send(new ClientboundCustomPayloadPacket(CarpetClient.CARPET_CHANNEL, data.build())); + CarpetServer.forEachManager(sm -> sm.getCarpetRules().forEach(data::withRule)); + playerEntity.connection.send(new ClientboundCustomPayloadPacket(CarpetClient.CARPET_CHANNEL, data.build() )); } public static void sendPlayerLevelData(ServerPlayer player, ServerLevel level) { From a05776a576878191356dbee2c1d01ddabf22b4b1 Mon Sep 17 00:00:00 2001 From: altrisi Date: Wed, 26 Jul 2023 19:59:29 +0200 Subject: [PATCH 180/233] Create identifier with separate components Quite useless change, though may help by interning --- src/main/java/carpet/network/CarpetClient.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/carpet/network/CarpetClient.java b/src/main/java/carpet/network/CarpetClient.java index 3367ee0174..2bb3f0c845 100644 --- a/src/main/java/carpet/network/CarpetClient.java +++ b/src/main/java/carpet/network/CarpetClient.java @@ -20,7 +20,7 @@ public class CarpetClient private static LocalPlayer clientPlayer = null; private static boolean isServerCarpet = false; public static String serverCarpetVersion; - public static final ResourceLocation CARPET_CHANNEL = new ResourceLocation("carpet:hello"); + public static final ResourceLocation CARPET_CHANNEL = new ResourceLocation("carpet", "hello"); public static void gameJoined(LocalPlayer player) { From b1cc289a4945c6c246d4aab4e47483395bb56c94 Mon Sep 17 00:00:00 2001 From: manyrandomthings <42223559+manyrandomthings@users.noreply.github.com> Date: Fri, 28 Jul 2023 08:23:59 -0400 Subject: [PATCH 181/233] Fix registry lists being randomized (#1774) --- src/main/java/carpet/script/api/Auxiliary.java | 4 ++-- src/main/java/carpet/script/api/Inventories.java | 4 +++- src/main/java/carpet/script/api/WorldAccess.java | 4 ++-- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/main/java/carpet/script/api/Auxiliary.java b/src/main/java/carpet/script/api/Auxiliary.java index 3ad9f989ec..fe2de59978 100644 --- a/src/main/java/carpet/script/api/Auxiliary.java +++ b/src/main/java/carpet/script/api/Auxiliary.java @@ -133,7 +133,7 @@ public static void apply(Expression expression) CarpetContext cc = (CarpetContext) c; if (lv.isEmpty()) { - return ListValue.wrap(cc.registry(Registries.SOUND_EVENT).keySet().stream().map(ValueConversions::of)); + return ListValue.wrap(cc.registry(Registries.SOUND_EVENT).holders().map(soundEventReference -> ValueConversions.of(soundEventReference.key().location()))); } String rawString = lv.get(0).getString(); ResourceLocation soundName = InputValidator.identifierOf(rawString); @@ -181,7 +181,7 @@ public static void apply(Expression expression) CarpetContext cc = (CarpetContext) c; if (lv.isEmpty()) { - return ListValue.wrap(cc.registry(Registries.PARTICLE_TYPE).keySet().stream().map(ValueConversions::of)); + return ListValue.wrap(cc.registry(Registries.PARTICLE_TYPE).holders().map(particleTypeReference -> ValueConversions.of(particleTypeReference.key().location()))); } MinecraftServer ms = cc.server(); ServerLevel world = cc.level(); diff --git a/src/main/java/carpet/script/api/Inventories.java b/src/main/java/carpet/script/api/Inventories.java index 327ea5fcf0..755369d1c9 100644 --- a/src/main/java/carpet/script/api/Inventories.java +++ b/src/main/java/carpet/script/api/Inventories.java @@ -29,6 +29,7 @@ import java.util.Set; import net.minecraft.commands.arguments.item.ItemInput; +import net.minecraft.core.Holder; import net.minecraft.core.HolderSet; import net.minecraft.core.Registry; import net.minecraft.core.RegistryAccess; @@ -36,6 +37,7 @@ import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.network.protocol.game.ClientboundContainerSetSlotPacket; +import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; import net.minecraft.tags.TagKey; @@ -71,7 +73,7 @@ public static void apply(Expression expression) Registry items = cc.registry(Registries.ITEM); if (lv.isEmpty()) { - return ListValue.wrap(items.keySet().stream().map(ValueConversions::of)); + return ListValue.wrap(items.holders().map(itemReference -> ValueConversions.of(itemReference.key().location()))); } String tag = lv.get(0).getString(); Optional> itemTag = items.getTag(TagKey.create(Registries.ITEM, InputValidator.identifierOf(tag))); diff --git a/src/main/java/carpet/script/api/WorldAccess.java b/src/main/java/carpet/script/api/WorldAccess.java index 012d931fb8..6ac0586117 100644 --- a/src/main/java/carpet/script/api/WorldAccess.java +++ b/src/main/java/carpet/script/api/WorldAccess.java @@ -1225,7 +1225,7 @@ LivingEntity getIndirectSourceEntity() Registry blocks = cc.registry(Registries.BLOCK); if (lv.isEmpty()) { - return ListValue.wrap(blocks.keySet().stream().map(ValueConversions::of)); + return ListValue.wrap(blocks.holders().map(blockReference -> ValueConversions.of(blockReference.key().location()))); } ResourceLocation tag = InputValidator.identifierOf(lv.get(0).getString()); Optional> tagset = blocks.getTag(TagKey.create(Registries.BLOCK, tag)); @@ -1256,7 +1256,7 @@ LivingEntity getIndirectSourceEntity() ServerLevel world = cc.level(); if (lv.isEmpty()) { - return ListValue.wrap(world.registryAccess().registryOrThrow(Registries.BIOME).keySet().stream().map(ValueConversions::of)); + return ListValue.wrap(cc.registry(Registries.BIOME).holders().map(biomeReference -> ValueConversions.of(biomeReference.key().location()))); } Biome biome; From efddb904a0093c4d921e8f572172bd4098176db8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Filip=20=C5=A0?= Date: Fri, 28 Jul 2023 15:27:03 +0200 Subject: [PATCH 182/233] Add option to configure listing fake players on the multiplayer screen (#1756) --- src/main/java/carpet/CarpetSettings.java | 3 +++ src/main/java/carpet/patches/EntityPlayerMPFake.java | 5 +++++ 2 files changed, 8 insertions(+) diff --git a/src/main/java/carpet/CarpetSettings.java b/src/main/java/carpet/CarpetSettings.java index 8180db5c15..871cb9d8c0 100644 --- a/src/main/java/carpet/CarpetSettings.java +++ b/src/main/java/carpet/CarpetSettings.java @@ -597,6 +597,9 @@ public String description() { @Rule(desc = "Spawn offline players in online mode if online-mode player with specified name does not exist", category = COMMAND) public static boolean allowSpawningOfflinePlayers = true; + @Rule(desc = "Allows listing fake players on the multiplayer screen", category = COMMAND) + public static boolean allowListingFakePlayers = false; + @Rule(desc = "Allows to track mobs AI via /track command", category = COMMAND) public static String commandTrackAI = "ops"; diff --git a/src/main/java/carpet/patches/EntityPlayerMPFake.java b/src/main/java/carpet/patches/EntityPlayerMPFake.java index 7ef72d9f73..617e718b2f 100644 --- a/src/main/java/carpet/patches/EntityPlayerMPFake.java +++ b/src/main/java/carpet/patches/EntityPlayerMPFake.java @@ -190,6 +190,11 @@ public String getIpAddress() return "127.0.0.1"; } + @Override + public boolean allowsListing() { + return CarpetSettings.allowListingFakePlayers; + } + @Override protected void checkFallDamage(double y, boolean onGround, BlockState state, BlockPos pos) { doCheckFallDamage(0.0, y, 0.0, onGround); From fbe37017c59f9c5b8e088ad657ca7c4a13a2f2c5 Mon Sep 17 00:00:00 2001 From: altrisi Date: Fri, 28 Jul 2023 20:57:48 +0200 Subject: [PATCH 183/233] Refactor spawn reporting (#1519) Not all that could be done for now --- src/main/java/carpet/CarpetServer.java | 2 +- .../java/carpet/commands/SpawnCommand.java | 65 ++-- .../carpet/mixins/NaturalSpawnerMixin.java | 19 +- .../carpet/mixins/ServerChunkCacheMixin.java | 35 +- .../mixins/ServerLevel_scarpetMixin.java | 4 +- src/main/java/carpet/utils/SpawnReporter.java | 309 +++++++++--------- src/main/java/carpet/utils/WoolTool.java | 2 +- 7 files changed, 202 insertions(+), 234 deletions(-) diff --git a/src/main/java/carpet/CarpetServer.java b/src/main/java/carpet/CarpetServer.java index b2e5248770..90897bbdf7 100644 --- a/src/main/java/carpet/CarpetServer.java +++ b/src/main/java/carpet/CarpetServer.java @@ -87,7 +87,7 @@ public static void onServerLoaded(MinecraftServer server) { CarpetServer.minecraft_server = server; // shoudl not be needed - that bit needs refactoring, but not now. - SpawnReporter.reset_spawn_stats(server, true); + SpawnReporter.resetSpawnStats(server, true); forEachManager(sm -> sm.attachServer(server)); extensions.forEach(e -> e.onServerLoaded(server)); diff --git a/src/main/java/carpet/commands/SpawnCommand.java b/src/main/java/carpet/commands/SpawnCommand.java index b3edf1c56a..be13686d87 100644 --- a/src/main/java/carpet/commands/SpawnCommand.java +++ b/src/main/java/carpet/commands/SpawnCommand.java @@ -28,6 +28,7 @@ import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.MobCategory; import net.minecraft.world.item.DyeColor; +import net.minecraft.world.level.levelgen.structure.BoundingBox; import static com.mojang.brigadier.arguments.IntegerArgumentType.getInteger; import static com.mojang.brigadier.arguments.IntegerArgumentType.integer; @@ -52,17 +53,18 @@ public static void register(CommandDispatcher dispatcher, Co then(literal("tracking"). executes( (c) -> printTrackingReport(c.getSource())). then(literal("start"). - executes( (c) -> startTracking(c.getSource(), null, null)). + executes( (c) -> startTracking(c.getSource(), null)). then(argument("from", BlockPosArgument.blockPos()). then(argument("to", BlockPosArgument.blockPos()). executes( (c) -> startTracking( c.getSource(), - BlockPosArgument.getSpawnablePos(c, "from"), - BlockPosArgument.getSpawnablePos(c, "to")))))). + BoundingBox.fromCorners( + BlockPosArgument.getSpawnablePos(c, "from"), + BlockPosArgument.getSpawnablePos(c, "to"))))))). then(literal("stop"). executes( (c) -> stopTracking(c.getSource()))). then(argument("type", word()). - suggests( (c, b) -> suggest(Arrays.stream(MobCategory.values()).map(MobCategory::getName),b)). + suggests( (c, b) -> suggest(Arrays.stream(SpawnReporter.cachedMobCategories()).map(MobCategory::getName),b)). executes( (c) -> recentSpawnsForType(c.getSource(), getString(c, "type"))))). then(literal("test"). executes( (c)-> runTest(c.getSource(), 72000, null)). @@ -85,7 +87,7 @@ public static void register(CommandDispatcher dispatcher, Co then(literal("reset"). executes( (c) -> resetSpawnRates(c.getSource()))). then(argument("type", word()). - suggests( (c, b) -> suggest(Arrays.stream(MobCategory.values()).map(MobCategory::getName),b)). + suggests( (c, b) -> suggest(Arrays.stream(SpawnReporter.cachedMobCategories()).map(MobCategory::getName),b)). then(argument("rounds", integer(0)). suggests( (c, b) -> suggest(new String[]{"1"},b)). executes( (c) -> setSpawnRates( @@ -102,20 +104,20 @@ public static void register(CommandDispatcher dispatcher, Co then(literal("entities"). executes( (c) -> generalMobcaps(c.getSource()) ). then(argument("type", string()). - suggests( (c, b)->suggest(Arrays.stream(MobCategory.values()).map(MobCategory::getName), b)). + suggests( (c, b)->suggest(Arrays.stream(SpawnReporter.cachedMobCategories()).map(MobCategory::getName), b)). executes( (c) -> listEntitiesOfType(c.getSource(), getString(c, "type"), false)). then(literal("all").executes( (c) -> listEntitiesOfType(c.getSource(), getString(c, "type"), true))))); dispatcher.register(literalargumentbuilder); } - private static final Map MOB_CATEGORY_MAP = Arrays.stream(MobCategory.values()).collect(Collectors.toMap(MobCategory::getName, Function.identity())); + private static final Map MOB_CATEGORY_MAP = Arrays.stream(SpawnReporter.cachedMobCategories()).collect(Collectors.toMap(MobCategory::getName, Function.identity())); private static MobCategory getCategory(String string) throws CommandSyntaxException { - if (!Arrays.stream(MobCategory.values()).map(MobCategory::getName).collect(Collectors.toSet()).contains(string)) + if (!Arrays.stream(SpawnReporter.cachedMobCategories()).map(MobCategory::getName).collect(Collectors.toSet()).contains(string)) { - throw new SimpleCommandExceptionType(Messenger.c("r Wrong mob type: "+string+" should be "+ Arrays.stream(MobCategory.values()).map(MobCategory::getName).collect(Collectors.joining(", ")))).create(); + throw new SimpleCommandExceptionType(Messenger.c("r Wrong mob type: "+string+" should be "+ Arrays.stream(SpawnReporter.cachedMobCategories()).map(MobCategory::getName).collect(Collectors.joining(", ")))).create(); } return MOB_CATEGORY_MAP.get(string.toLowerCase(Locale.ROOT)); } @@ -129,45 +131,26 @@ private static int listSpawns(CommandSourceStack source, BlockPos pos) private static int printTrackingReport(CommandSourceStack source) { - Messenger.send(source, SpawnReporter.tracking_report(source.getLevel())); + Messenger.send(source, SpawnReporter.makeTrackingReport(source.getLevel())); return 1; } - private static int startTracking(CommandSourceStack source, BlockPos a, BlockPos b) + private static int startTracking(CommandSourceStack source, BoundingBox filter) { - if (SpawnReporter.track_spawns != 0L) + if (SpawnReporter.trackingSpawns()) { Messenger.m(source, "r You are already tracking spawning."); return 0; } - BlockPos lsl = null; - BlockPos usl = null; - if (a != null && b != null) - { - lsl = new BlockPos( - Math.min(a.getX(), b.getX()), - Math.min(a.getY(), b.getY()), - Math.min(a.getZ(), b.getZ()) ); - usl = new BlockPos( - Math.max(a.getX(), b.getX()), - Math.max(a.getY(), b.getY()), - Math.max(a.getZ(), b.getZ()) ); - } - SpawnReporter.reset_spawn_stats(source.getServer(), false); - SpawnReporter.track_spawns = (long) source.getServer().getTickCount(); - SpawnReporter.lower_spawning_limit = lsl; - SpawnReporter.upper_spawning_limit = usl; + SpawnReporter.startTracking(source.getServer(), filter); Messenger.m(source, "gi Spawning tracking started."); return 1; } private static int stopTracking(CommandSourceStack source) { - Messenger.send(source, SpawnReporter.tracking_report(source.getLevel())); - SpawnReporter.reset_spawn_stats(source.getServer(),false); - SpawnReporter.track_spawns = 0L; - SpawnReporter.lower_spawning_limit = null; - SpawnReporter.upper_spawning_limit = null; + Messenger.send(source, SpawnReporter.makeTrackingReport(source.getLevel())); + SpawnReporter.stopTracking(source.getServer()); Messenger.m(source, "gi Spawning tracking stopped."); return 1; } @@ -175,17 +158,15 @@ private static int stopTracking(CommandSourceStack source) private static int recentSpawnsForType(CommandSourceStack source, String mob_type) throws CommandSyntaxException { MobCategory cat = getCategory(mob_type); - Messenger.send(source, SpawnReporter.recent_spawns(source.getLevel(), cat)); + Messenger.send(source, SpawnReporter.getRecentSpawns(source.getLevel(), cat)); return 1; } private static int runTest(CommandSourceStack source, int ticks, String counter) { - //stop tracking - SpawnReporter.reset_spawn_stats(source.getServer(),false); - //start tracking - SpawnReporter.track_spawns = (long) source.getServer().getTickCount(); - //counter reset + // Start tracking + SpawnReporter.startTracking(source.getServer(), null); + // Reset counter if (counter == null) { HopperCounter.resetAll(source.getServer(), false); @@ -221,12 +202,12 @@ private static int toggleMocking(CommandSourceStack source, boolean domock) { if (domock) { - SpawnReporter.initialize_mocking(); + SpawnReporter.initializeMocking(); Messenger.m(source, "gi Mob spawns will now be mocked."); } else { - SpawnReporter.stop_mocking(); + SpawnReporter.stopMocking(); Messenger.m(source, "gi Normal mob spawning."); } return 1; diff --git a/src/main/java/carpet/mixins/NaturalSpawnerMixin.java b/src/main/java/carpet/mixins/NaturalSpawnerMixin.java index 4f9eb3dd49..fc470860dc 100644 --- a/src/main/java/carpet/mixins/NaturalSpawnerMixin.java +++ b/src/main/java/carpet/mixins/NaturalSpawnerMixin.java @@ -161,7 +161,7 @@ private static void spawnEntity(ServerLevel world, Entity entity_1, // we used the mob - next time we will create a new one when needed ((LevelInterface) world).getPrecookedMobs().remove(entity_1.getType()); - if (SpawnReporter.track_spawns > 0L && SpawnReporter.local_spawns != null) + if (SpawnReporter.trackingSpawns() && SpawnReporter.local_spawns != null) { SpawnReporter.registerSpawn( //world.method_27983(), // getDimensionType //dimension.getType(), // getDimensionType @@ -169,7 +169,7 @@ private static void spawnEntity(ServerLevel world, Entity entity_1, group, //entity_1.getType().getSpawnGroup(), entity_1.blockPosition()); } - if (!SpawnReporter.mock_spawns) + if (!SpawnReporter.mockSpawns) world.addFreshEntityWithPassengers(entity_1); //world.spawnEntity(entity_1); } @@ -180,7 +180,7 @@ private static void spawnEntity(ServerLevel world, Entity entity_1, )) private static SpawnGroupData spawnEntity(Mob mobEntity, ServerLevelAccessor serverWorldAccess, DifficultyInstance difficulty, MobSpawnType spawnReason, SpawnGroupData entityData, CompoundTag entityTag) { - if (!SpawnReporter.mock_spawns) // WorldAccess + if (!SpawnReporter.mockSpawns) // WorldAccess return mobEntity.finalizeSpawn(serverWorldAccess, difficulty, spawnReason, entityData, entityTag); return null; } @@ -273,7 +273,7 @@ private static boolean changeMobcaps( private static void checkSpawns(ServerLevel world, LevelChunk chunk, NaturalSpawner.SpawnState info, boolean spawnAnimals, boolean spawnMonsters, boolean shouldSpawnAnimals, CallbackInfo ci) { - if (SpawnReporter.track_spawns > 0L) + if (SpawnReporter.trackingSpawns()) { MobCategory[] var6 = SPAWNING_CATEGORIES; int var7 = var6.length; @@ -288,23 +288,20 @@ private static void checkSpawns(ServerLevel world, LevelChunk chunk, NaturalSpaw int int_3 = newCap * int_2 / MAGIC_NUMBER; //current spawning limits int mobCount = info.getMobCategoryCounts().getInt(entityCategory); - if (SpawnReporter.track_spawns > 0L && !SpawnReporter.first_chunk_marker.contains(entityCategory)) + if (SpawnReporter.trackingSpawns() && !SpawnReporter.first_chunk_marker.contains(entityCategory)) { SpawnReporter.first_chunk_marker.add(entityCategory); //first chunk with spawn eligibility for that category Pair, MobCategory> key = Pair.of(dim, entityCategory); - int spawnTries = SpawnReporter.spawn_tries.get(entityCategory); - SpawnReporter.spawn_attempts.put(key, - SpawnReporter.spawn_attempts.get(key) + spawnTries); + SpawnReporter.spawn_attempts.addTo(key, spawnTries); - SpawnReporter.spawn_cap_count.put(key, - SpawnReporter.spawn_cap_count.get(key) + mobCount); + SpawnReporter.spawn_cap_count.addTo(key, mobCount); } - if (mobCount <= int_3 || SpawnReporter.mock_spawns) //TODO this will not float with player based mobcaps + if (mobCount <= int_3 || SpawnReporter.mockSpawns) //TODO this will not float with player based mobcaps { //place 0 to indicate there were spawn attempts for a category //if (entityCategory != EntityCategory.CREATURE || world.getServer().getTicks() % 400 == 0) diff --git a/src/main/java/carpet/mixins/ServerChunkCacheMixin.java b/src/main/java/carpet/mixins/ServerChunkCacheMixin.java index 2724b6508f..815ed55183 100644 --- a/src/main/java/carpet/mixins/ServerChunkCacheMixin.java +++ b/src/main/java/carpet/mixins/ServerChunkCacheMixin.java @@ -1,6 +1,7 @@ package carpet.mixins; import carpet.utils.SpawnReporter; +import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; import org.apache.commons.lang3.tuple.Pair; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -10,7 +11,6 @@ import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import java.util.HashMap; import java.util.HashSet; import net.minecraft.resources.ResourceKey; import net.minecraft.server.level.DistanceManager; @@ -39,17 +39,15 @@ private int setupTracking(DistanceManager chunkTicketManager) //((WorldInterface)world).getPrecookedMobs().clear(); not needed because mobs are compared with predefined BBs SpawnReporter.chunkCounts.put(dim, j); - if (SpawnReporter.track_spawns > 0L) + if (SpawnReporter.trackingSpawns()) { //local spawns now need to be tracked globally cause each calll is just for chunk - SpawnReporter.local_spawns = new HashMap<>(); + SpawnReporter.local_spawns = new Object2LongOpenHashMap<>(); SpawnReporter.first_chunk_marker = new HashSet<>(); - for (MobCategory cat : MobCategory.values()) + for (MobCategory cat : SpawnReporter.cachedMobCategories()) { Pair, MobCategory> key = Pair.of(dim, cat); - SpawnReporter.overall_spawn_ticks.put(key, - SpawnReporter.overall_spawn_ticks.get(key)+ - SpawnReporter.spawn_tries.get(cat)); + SpawnReporter.overall_spawn_ticks.addTo(key, SpawnReporter.spawn_tries.get(cat)); } } return j; @@ -59,11 +57,11 @@ private int setupTracking(DistanceManager chunkTicketManager) @Inject(method = "tickChunks", at = @At("RETURN")) private void onFinishSpawnWorldCycle(CallbackInfo ci) { - LevelData levelProperties_1 = this.level.getLevelData(); // levelProperies class - boolean boolean_3 = levelProperties_1.getGameTime() % 400L == 0L; - if (SpawnReporter.track_spawns > 0L && SpawnReporter.local_spawns != null) + LevelData levelData = this.level.getLevelData(); // levelProperies class + boolean boolean_3 = levelData.getGameTime() % 400L == 0L; + if (SpawnReporter.trackingSpawns() && SpawnReporter.local_spawns != null) { - for (MobCategory cat: MobCategory.values()) + for (MobCategory cat: SpawnReporter.cachedMobCategories()) { ResourceKey dim = level.dimension(); // getDimensionType; Pair, MobCategory> key = Pair.of(dim, cat); @@ -73,19 +71,15 @@ private void onFinishSpawnWorldCycle(CallbackInfo ci) if (!cat.isPersistent() || boolean_3) // isAnimal { // fill mobcaps for that category so spawn got cancelled - SpawnReporter.spawn_ticks_full.put(key, - SpawnReporter.spawn_ticks_full.get(key)+ spawnTries); + SpawnReporter.spawn_ticks_full.addTo(key, spawnTries); } } - else if (SpawnReporter.local_spawns.get(cat) > 0) + else if (SpawnReporter.local_spawns.getLong(cat) > 0) { // tick spawned mobs for that type - SpawnReporter.spawn_ticks_succ.put(key, - SpawnReporter.spawn_ticks_succ.get(key)+spawnTries); - SpawnReporter.spawn_ticks_spawns.put(key, - SpawnReporter.spawn_ticks_spawns.get(key)+ - SpawnReporter.local_spawns.get(cat)); + SpawnReporter.spawn_ticks_succ.addTo(key, spawnTries); + SpawnReporter.spawn_ticks_spawns.addTo(key, SpawnReporter.local_spawns.getLong(cat)); // this will be off comparing to 1.13 as that would succeed if // ANY tries in that round were successful. // there will be much more difficult to mix in @@ -95,8 +89,7 @@ else if (SpawnReporter.local_spawns.get(cat) > 0) else // spawn no mobs despite trying { //tick didn's spawn mobs of that type - SpawnReporter.spawn_ticks_fail.put(key, - SpawnReporter.spawn_ticks_fail.get(key)+spawnTries); + SpawnReporter.spawn_ticks_fail.addTo(key, spawnTries); } } } diff --git a/src/main/java/carpet/mixins/ServerLevel_scarpetMixin.java b/src/main/java/carpet/mixins/ServerLevel_scarpetMixin.java index 927f3a2fea..4fb5295d44 100644 --- a/src/main/java/carpet/mixins/ServerLevel_scarpetMixin.java +++ b/src/main/java/carpet/mixins/ServerLevel_scarpetMixin.java @@ -25,6 +25,7 @@ import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @@ -37,7 +38,6 @@ import static carpet.script.CarpetEventServer.Event.LIGHTNING; import static carpet.script.CarpetEventServer.Event.CHUNK_UNLOADED; - @Mixin(ServerLevel.class) public abstract class ServerLevel_scarpetMixin extends Level implements ServerWorldInterface { @@ -94,11 +94,13 @@ private void handleChunkUnload(LevelChunk levelChunk, CallbackInfo ci) private ServerLevelData serverLevelData; @Shadow @Final private PersistentEntitySectionManager entityManager; + @Unique @Override public ServerLevelData getWorldPropertiesCM(){ return serverLevelData; } + @Unique @Override public LevelEntityGetter getEntityLookupCMPublic() { return entityManager.getEntityGetter(); diff --git a/src/main/java/carpet/utils/SpawnReporter.java b/src/main/java/carpet/utils/SpawnReporter.java index 7db763a5c0..0dc7c8199a 100644 --- a/src/main/java/carpet/utils/SpawnReporter.java +++ b/src/main/java/carpet/utils/SpawnReporter.java @@ -32,6 +32,7 @@ import net.minecraft.world.level.chunk.ChunkGenerator; import net.minecraft.world.level.entity.EntityTypeTest; import net.minecraft.world.level.levelgen.Heightmap; +import net.minecraft.world.level.levelgen.structure.BoundingBox; import net.minecraft.world.level.levelgen.structure.structures.NetherFortressStructure; import org.apache.commons.lang3.tuple.Pair; import org.jetbrains.annotations.Nullable; @@ -42,59 +43,48 @@ import java.util.HashMap; import java.util.HashSet; import java.util.List; -import java.util.Locale; public class SpawnReporter { - public static boolean mock_spawns = false; - - public static Long track_spawns = 0L; + private static final MobCategory[] CACHED_MOBCATEGORY_VALUES = MobCategory.values(); + public static boolean mockSpawns = false; + public static final HashMap, Integer> chunkCounts = new HashMap<>(); - public static final HashMap, MobCategory>, Object2LongMap>> spawn_stats = new HashMap<>(); + public static final HashMap, MobCategory>, Object2LongOpenHashMap>> spawn_stats = new HashMap<>(); public static double mobcap_exponent = 0.0D; - public static final HashMap, MobCategory>, Long> spawn_attempts = new HashMap<>(); - public static final HashMap, MobCategory>, Long> overall_spawn_ticks = new HashMap<>(); - public static final HashMap, MobCategory>, Long> spawn_ticks_full = new HashMap<>(); - public static final HashMap, MobCategory>, Long> spawn_ticks_fail = new HashMap<>(); - public static final HashMap, MobCategory>, Long> spawn_ticks_succ = new HashMap<>(); - public static final HashMap, MobCategory>, Long> spawn_ticks_spawns = new HashMap<>(); - public static final HashMap, MobCategory>, Long> spawn_cap_count = new HashMap<>(); + public static final Object2LongOpenHashMap, MobCategory>> spawn_attempts = new Object2LongOpenHashMap<>(); + public static final Object2LongOpenHashMap, MobCategory>> overall_spawn_ticks = new Object2LongOpenHashMap<>(); + public static final Object2LongOpenHashMap, MobCategory>> spawn_ticks_full = new Object2LongOpenHashMap<>(); + public static final Object2LongOpenHashMap, MobCategory>> spawn_ticks_fail = new Object2LongOpenHashMap<>(); + public static final Object2LongOpenHashMap, MobCategory>> spawn_ticks_succ = new Object2LongOpenHashMap<>(); + public static final Object2LongOpenHashMap, MobCategory>> spawn_ticks_spawns = new Object2LongOpenHashMap<>(); + public static final Object2LongOpenHashMap, MobCategory>> spawn_cap_count = new Object2LongOpenHashMap<>(); public static final HashMap, MobCategory>, EvictingQueue, BlockPos>>> spawned_mobs = new HashMap<>(); public static final HashMap spawn_tries = new HashMap<>(); - public static BlockPos lower_spawning_limit = null; - public static BlockPos upper_spawning_limit = null; + + private static int spawnTrackingStartTime = 0; + private static BoundingBox trackedSpawningArea = null; // in case game gets each thread for each world - these need to belong to workd. - public static HashMap local_spawns = null; // per world + public static Object2LongOpenHashMap local_spawns = null; // per world public static HashSet first_chunk_marker = null; - static { - reset_spawn_stats(null, true); - } - public static void registerSpawn(Mob mob, MobCategory cat, BlockPos pos) { - if (lower_spawning_limit != null) + if (trackedSpawningArea != null && !trackedSpawningArea.isInside(pos)) { - if (!( (lower_spawning_limit.getX() <= pos.getX() && pos.getX() <= upper_spawning_limit.getX()) && - (lower_spawning_limit.getY() <= pos.getY() && pos.getY() <= upper_spawning_limit.getY()) && - (lower_spawning_limit.getZ() <= pos.getZ() && pos.getZ() <= upper_spawning_limit.getZ()) - )) - { - return; - } + return; } Pair, MobCategory> key = Pair.of(mob.level().dimension(), cat); - long count = spawn_stats.get(key).getOrDefault(mob.getType(), 0L); - spawn_stats.get(key).put(mob.getType(), count + 1); + spawn_stats.get(key).addTo(mob.getType(), 1); spawned_mobs.get(key).put(Pair.of(mob.getType(), pos)); if (!local_spawns.containsKey(cat)) { CarpetSettings.LOG.error("Rogue spawn detected for category "+cat.getName()+" for mob "+mob.getType().getDescription().getString()+". If you see this message let carpet peeps know about it on github issues."); local_spawns.put(cat, 0L); } - local_spawns.put(cat, local_spawns.get(cat)+1); + local_spawns.addTo(cat, 1); } public static final int MAGIC_NUMBER = (int)Math.pow(17.0D, 2.0D); @@ -120,18 +110,18 @@ public static List printMobcapsForDimension(ServerLevel world, boolea } List shortCodes = new ArrayList<>(); - for (MobCategory enumcreaturetype : MobCategory.values()) + for (MobCategory category : cachedMobCategories()) { - int cur = dimCounts.getOrDefault(enumcreaturetype, -1); - int max = (int)(chunkcount * ((double)enumcreaturetype.getMaxInstancesPerChunk() / MAGIC_NUMBER)); // from ServerChunkManager.CHUNKS_ELIGIBLE_FOR_SPAWNING + int cur = dimCounts.getOrDefault(category, -1); + int max = (int)(chunkcount * ((double)category.getMaxInstancesPerChunk() / MAGIC_NUMBER)); // from ServerChunkManager.CHUNKS_ELIGIBLE_FOR_SPAWNING String color = Messenger.heatmap_color(cur, max); - String mobColor = Messenger.creatureTypeColor(enumcreaturetype); + String mobColor = Messenger.creatureTypeColor(category); if (multiline) { - int rounds = spawn_tries.get(enumcreaturetype); - lst.add(Messenger.c(String.format("w %s: ", enumcreaturetype.getName()), + int rounds = spawn_tries.get(category); + lst.add(Messenger.c(String.format("w %s: ", category.getName()), (cur < 0) ? "g -" : (color + " " + cur), "g / ", mobColor + " " + max, - (rounds == 1) ? "w " : String.format("gi (%d rounds/tick)", spawn_tries.get(enumcreaturetype)) + (rounds == 1) ? "w " : String.format("gi (%d rounds/tick)", spawn_tries.get(category)) )); } else @@ -144,7 +134,7 @@ public static List printMobcapsForDimension(ServerLevel world, boolea } if (!multiline) { - if (shortCodes.size()>0) + if (shortCodes.size() > 0) { shortCodes.remove(shortCodes.size() - 1); lst.add(Messenger.c(shortCodes.toArray(new Object[0]))); @@ -158,18 +148,18 @@ public static List printMobcapsForDimension(ServerLevel world, boolea return lst; } - public static List recent_spawns(Level world, MobCategory creature_type) + public static List getRecentSpawns(Level world, MobCategory category) { List lst = new ArrayList<>(); - if ((track_spawns == 0L)) + if (!trackingSpawns()) { lst.add(Messenger.s("Spawn tracking not started")); return lst; } - String type_code = creature_type.getName(); + String categoryName = category.getName(); - lst.add(Messenger.s(String.format("Recent %s spawns:",type_code))); - for (Pair, BlockPos> pair : spawned_mobs.get(Pair.of(world.dimension(), creature_type)).keySet()) // getDImTYpe + lst.add(Messenger.s(String.format("Recent %s spawns:", categoryName))); + for (Pair, BlockPos> pair : spawned_mobs.get(Pair.of(world.dimension(), category)).keySet()) { lst.add( Messenger.c( "w - ", @@ -178,7 +168,7 @@ public static List recent_spawns(Level world, MobCategory creature_ty )); } - if (lst.size()==1) + if (lst.size() == 1) { lst.add(Messenger.s(" - Nothing spawned yet, sorry.")); } @@ -186,37 +176,37 @@ public static List recent_spawns(Level world, MobCategory creature_ty } - public static List show_mobcaps(BlockPos pos, ServerLevel worldIn) + public static List handleWoolAction(BlockPos pos, ServerLevel worldIn) { DyeColor under = WoolTool.getWoolColorAtPosition(worldIn, pos.below()); if (under == null) { - if (track_spawns > 0L) + if (trackingSpawns()) { - return tracking_report(worldIn); + return makeTrackingReport(worldIn); } else { return printMobcapsForDimension(worldIn, true ); } } - MobCategory creature_type = get_type_code_from_wool_code(under); - if (creature_type != null) + MobCategory category = getCategoryFromWoolColor(under); + if (category != null) { - if (track_spawns > 0L) + if (trackingSpawns()) { - return recent_spawns(worldIn, creature_type); + return getRecentSpawns(worldIn, category); } else { - return printEntitiesByType(creature_type, worldIn, true); + return printEntitiesByType(category, worldIn, true); } } - if (track_spawns > 0L) + if (trackingSpawns()) { - return tracking_report(worldIn); + return makeTrackingReport(worldIn); } else { @@ -225,7 +215,7 @@ public static List show_mobcaps(BlockPos pos, ServerLevel worldIn) } - public static MobCategory get_type_code_from_wool_code(DyeColor color) + public static MobCategory getCategoryFromWoolColor(DyeColor color) { return switch (color) { @@ -238,13 +228,13 @@ public static MobCategory get_type_code_from_wool_code(DyeColor color) }; } - public static List printEntitiesByType(MobCategory cat, Level worldIn, boolean all) //Class entityType) + public static List printEntitiesByType(MobCategory cat, ServerLevel worldIn, boolean all) { List lst = new ArrayList<>(); - lst.add( Messenger.s(String.format("Loaded entities for %s class:", cat))); - for (Entity entity : ((ServerLevel)worldIn).getEntities(EntityTypeTest.forClass(Entity.class), (e) -> e.getType().getCategory()==cat)) + lst.add( Messenger.s(String.format("Loaded entities for %s category:", cat))); + for (Entity entity : worldIn.getEntities(EntityTypeTest.forClass(Entity.class), (e) -> e.getType().getCategory() == cat)) { - boolean persistent = entity instanceof Mob && ( ((Mob) entity).isPersistenceRequired() || ((Mob) entity).requiresCustomPersistence()); + boolean persistent = entity instanceof Mob mob && ( mob.isPersistenceRequired() || mob.requiresCustomPersistence()); if (!all && persistent) continue; @@ -252,104 +242,122 @@ public static List printEntitiesByType(MobCategory cat, Level worldIn BlockPos pos = entity.blockPosition(); lst.add( Messenger.c( "w - ", - Messenger.tp(persistent?"gb":"wb",pos), - String.format(persistent?"g : %s":"w : %s", type.getDescription().getString()) + Messenger.tp(persistent ? "gb" : "wb", pos), + String.format(persistent ? "g : %s" : "w : %s", type.getDescription().getString()) )); } - if (lst.size()==1) + if (lst.size() == 1) { lst.add(Messenger.s(" - Empty.")); } return lst; } - public static void initialize_mocking() + public static void initializeMocking() { - mock_spawns = true; - + mockSpawns = true; } - public static void stop_mocking() + public static void stopMocking() { - mock_spawns = false; + mockSpawns = false; } - public static void reset_spawn_stats(MinecraftServer server, boolean full) - { - spawn_stats.clear(); - spawned_mobs.clear(); - for (MobCategory enumcreaturetype : MobCategory.values()) + public static void resetSpawnStats(MinecraftServer server, boolean full) + { + if (full) { - if (full) - { - spawn_tries.put(enumcreaturetype, 1); - } - if (server != null) for (ResourceKey dim : server.levelKeys()) - { - Pair, MobCategory> key = Pair.of(dim, enumcreaturetype); - overall_spawn_ticks.put(key, 0L); - spawn_attempts.put(key, 0L); - spawn_ticks_full.put(key, 0L); - spawn_ticks_fail.put(key, 0L); - spawn_ticks_succ.put(key, 0L); - spawn_ticks_spawns.put(key, 0L); - spawn_cap_count.put(key, 0L); + for (MobCategory category : cachedMobCategories()) + spawn_tries.put(category, 1); + } + overall_spawn_ticks.clear(); + spawn_attempts.clear(); + spawn_ticks_full.clear(); + spawn_ticks_fail.clear(); + spawn_ticks_succ.clear(); + spawn_ticks_spawns.clear(); + spawn_cap_count.clear(); + + // can't fast-path to clear given different worlds could have different amount of worlds + for (MobCategory category : cachedMobCategories()) { + for (ResourceKey world : server.levelKeys()) { + Pair, MobCategory> key = Pair.of(world, category); spawn_stats.put(key, new Object2LongOpenHashMap<>()); spawned_mobs.put(key, new EvictingQueue<>()); } } - track_spawns = 0L; + spawnTrackingStartTime = 0; + } + + public static MobCategory[] cachedMobCategories() { + return CACHED_MOBCATEGORY_VALUES; + } + + public static boolean trackingSpawns() { + return spawnTrackingStartTime != 0L; + } + + public static void startTracking(MinecraftServer server, BoundingBox trackedArea) { + resetSpawnStats(server, false); + spawnTrackingStartTime = server.getTickCount(); + trackedSpawningArea = trackedArea; + } + + public static void stopTracking(MinecraftServer server) { + resetSpawnStats(server, false); + SpawnReporter.spawnTrackingStartTime = 0; + trackedSpawningArea = null; } private static String getWorldCode(ResourceKey world) { if (world == Level.OVERWORLD) return ""; - return "("+world.location().getPath().toUpperCase(Locale.ROOT).replace("THE_","").charAt(0)+")"; + return "("+Character.toUpperCase(world.location().getPath().charAt("THE_".length()))+")"; } - public static List tracking_report(Level worldIn) + public static List makeTrackingReport(Level worldIn) { - List report = new ArrayList<>(); - if (track_spawns == 0L) + if (!trackingSpawns()) { report.add(Messenger.c( - "w Spawn tracking disabled, type '", + "w Spawn tracking is disabled, type '", "wi /spawn tracking start","/spawn tracking start", "w ' to enable")); return report; } - long duration = worldIn.getServer().getTickCount() - track_spawns; + int duration = worldIn.getServer().getTickCount() - spawnTrackingStartTime; report.add(Messenger.c("bw --------------------")); - String simulated = mock_spawns?"[SIMULATED] ":""; - String location = (lower_spawning_limit != null)?String.format("[in (%d, %d, %d)x(%d, %d, %d)]", - lower_spawning_limit.getX(),lower_spawning_limit.getY(),lower_spawning_limit.getZ(), - upper_spawning_limit.getX(),upper_spawning_limit.getY(),upper_spawning_limit.getZ() ):""; + String simulated = mockSpawns ? "[SIMULATED] " : ""; + String location = (trackedSpawningArea != null) ? String.format("[in (%d, %d, %d)x(%d, %d, %d)]", + trackedSpawningArea.minX(), trackedSpawningArea.minY(), trackedSpawningArea.minZ(), + trackedSpawningArea.maxX(), trackedSpawningArea.maxY(), trackedSpawningArea.maxZ() ):""; report.add(Messenger.s(String.format("%sSpawn statistics %s: for %.1f min", simulated, location, (duration/72000.0)*60))); - for (MobCategory enumcreaturetype : MobCategory.values()) + + for (MobCategory category : cachedMobCategories()) { - //String type_code = String.format("%s", enumcreaturetype); - for (ResourceKey dim : worldIn.getServer().levelKeys()) //String world_code: new String[] {"", " (N)", " (E)"}) + for (ResourceKey dim : worldIn.getServer().levelKeys()) { - Pair, MobCategory> code = Pair.of(dim, enumcreaturetype); - if (spawn_ticks_spawns.get(code) > 0L) + Pair, MobCategory> key = Pair.of(dim, category); + if (spawn_ticks_spawns.getLong(key) > 0L) { - double hours = overall_spawn_ticks.get(code)/72000.0; + double hours = overall_spawn_ticks.getLong(key)/72000.0; + long spawnAttemptsForCategory = spawn_attempts.getLong(key); report.add(Messenger.s(String.format(" > %s%s (%.1f min), %.1f m/t, %%{%.1fF %.1f- %.1f+}; %.2f s/att", - enumcreaturetype.getName().substring(0,3), getWorldCode(dim), + category.getName().substring(0,3), getWorldCode(dim), 60*hours, - (1.0D*spawn_cap_count.get(code))/ spawn_attempts.get(code), - (100.0D*spawn_ticks_full.get(code))/ spawn_attempts.get(code), - (100.0D*spawn_ticks_fail.get(code))/ spawn_attempts.get(code), - (100.0D*spawn_ticks_succ.get(code))/ spawn_attempts.get(code), - (1.0D*spawn_ticks_spawns.get(code))/(spawn_ticks_fail.get(code)+spawn_ticks_succ.get(code)) + (1.0D * spawn_cap_count.getLong(key)) / spawnAttemptsForCategory, + (100.0D * spawn_ticks_full.getLong(key)) / spawnAttemptsForCategory, + (100.0D * spawn_ticks_fail.getLong(key)) / spawnAttemptsForCategory, + (100.0D * spawn_ticks_succ.getLong(key)) / spawnAttemptsForCategory, + (1.0D * spawn_ticks_spawns.getLong(key)) / (spawn_ticks_fail.getLong(key) + spawn_ticks_succ.getLong(key)) ))); - for (EntityType type: spawn_stats.get(code).keySet()) + for (Object2LongMap.Entry> entry: spawn_stats.get(key).object2LongEntrySet()) { report.add(Messenger.s(String.format(" - %s: %d spawns, %d per hour", - type.getDescription().getString(), - spawn_stats.get(code).getLong(type), - (72000 * spawn_stats.get(code).getLong(type)/duration )))); + entry.getKey().getDescription().getString(), + entry.getLongValue(), + (72000 * entry.getLongValue()/duration )))); } } } @@ -357,8 +365,6 @@ public static List tracking_report(Level worldIn) return report; } - - public static void killEntity(LivingEntity entity) { if (entity.isPassenger()) @@ -390,51 +396,48 @@ private static List getSpawnEntries(ServerLevel se public static List report(BlockPos pos, ServerLevel worldIn) { List rep = new ArrayList<>(); - int x = pos.getX(); int y = pos.getY(); int z = pos.getZ(); + int x = pos.getX(); + int y = pos.getY(); + int z = pos.getZ(); ChunkAccess chunk = worldIn.getChunk(pos); int lc = chunk.getHeight(Heightmap.Types.WORLD_SURFACE, x, z) + 1; - String where = String.format((y >= lc) ? "%d blocks above it." : "%d blocks below it.", Mth.abs(y-lc)); - if (y == lc) where = "right at it."; - rep.add(Messenger.s(String.format("Maximum spawn Y value for (%+d, %+d) is %d. You are "+where, x, z, lc ))); + String relativeHeight = (y == lc) ? "right at it." : String.format("%d blocks %s it.", Mth.abs(y - lc), (y >= lc) ? "above" : "below"); + rep.add(Messenger.s(String.format("Maximum spawn Y value for (%+d, %+d) is %d. You are " + relativeHeight, x, z, lc))); rep.add(Messenger.s("Spawns:")); - for (MobCategory enumcreaturetype : MobCategory.values()) + for (MobCategory category : cachedMobCategories()) { - String type_code = String.format("%s", enumcreaturetype).substring(0, 3); - List lst = getSpawnEntries(worldIn, worldIn.structureManager(), worldIn.getChunkSource().getGenerator(), enumcreaturetype, pos, worldIn.getBiome(pos) );// ((ChunkGenerator)worldIn.getChunkManager().getChunkGenerator()).getEntitySpawnList(, worldIn.getStructureAccessor(), enumcreaturetype, pos); + String categoryCode = String.valueOf(category).substring(0, 3); + List lst = getSpawnEntries(worldIn, worldIn.structureManager(), worldIn.getChunkSource().getGenerator(), category, pos, worldIn.getBiome(pos)); if (lst != null && !lst.isEmpty()) { for (MobSpawnSettings.SpawnerData spawnEntry : lst) { - if (SpawnPlacements.getPlacementType(spawnEntry.type)==null) + if (SpawnPlacements.getPlacementType(spawnEntry.type) == null) continue; // vanilla bug - boolean canspawn = NaturalSpawner.isSpawnPositionOk(SpawnPlacements.getPlacementType(spawnEntry.type), worldIn, pos, spawnEntry.type); - int will_spawn = -1; - boolean fits; - boolean fits1; + boolean canSpawn = NaturalSpawner.isSpawnPositionOk(SpawnPlacements.getPlacementType(spawnEntry.type), worldIn, pos, spawnEntry.type); + int willSpawn = -1; + boolean fits = false; Mob mob; try { mob = (Mob) spawnEntry.type.create(worldIn); } - catch (Exception exception) + catch (Exception e) { - CarpetSettings.LOG.warn("Exception while creating mob for spawn reporter", exception); + CarpetSettings.LOG.warn("Exception while creating mob for spawn reporter", e); return rep; } - boolean fits_true = false; - boolean fits_false = false; - - if (canspawn) + if (canSpawn) { - will_spawn = 0; + willSpawn = 0; for (int attempt = 0; attempt < 50; ++attempt) { float f = x + 0.5F; float f1 = z + 0.5F; mob.moveTo(f, y, f1, worldIn.random.nextFloat() * 360.0F, 0.0F); - fits1 = worldIn.noCollision(mob); + fits = worldIn.noCollision(mob); EntityType etype = mob.getType(); for (int i = 0; i < 20; ++i) @@ -453,20 +456,12 @@ public static List report(BlockPos pos, ServerLevel worldIn) continue; } } - will_spawn += 1; + willSpawn += 1; } } mob.finalizeSpawn(worldIn, worldIn.getCurrentDifficultyAt(mob.blockPosition()), MobSpawnType.NATURAL, null, null); // the code invokes onInitialSpawn after getCanSpawHere - fits = fits1 && worldIn.noCollision(mob); - if (fits) - { - fits_true = true; - } - else - { - fits_false = true; - } + fits = fits && worldIn.noCollision(mob); killEntity(mob); @@ -474,32 +469,32 @@ public static List report(BlockPos pos, ServerLevel worldIn) { mob = (Mob) spawnEntry.type.create(worldIn); } - catch (Exception exception) + catch (Exception e) { - CarpetSettings.LOG.warn("Exception while creating mob for spawn reporter", exception); + CarpetSettings.LOG.warn("Exception while creating mob for spawn reporter", e); return rep; } } } - String creature_name = mob.getType().getDescription().getString(); - String pack_size = String.format("%d", mob.getMaxSpawnClusterSize());//String.format("%d-%d", animal.minGroupCount, animal.maxGroupCount); + String mobTypeName = mob.getType().getDescription().getString(); + //String pack_size = Integer.toString(mob.getMaxSpawnClusterSize());//String.format("%d-%d", animal.minGroupCount, animal.maxGroupCount); int weight = spawnEntry.getWeight().asInt(); - if (canspawn) + if (canSpawn) { - String c = (fits_true && will_spawn>0)?"e":"gi"; + String color = (fits && willSpawn > 0) ? "e" : "gi"; rep.add(Messenger.c( - String.format("%s %s: %s (%d:%d-%d/%d), can: ",c,type_code,creature_name,weight,spawnEntry.minCount, spawnEntry.maxCount, mob.getMaxSpawnClusterSize()), + String.format("%s %s: %s (%d:%d-%d/%d), can: ", color, categoryCode, mobTypeName, weight, spawnEntry.minCount, spawnEntry.maxCount, mob.getMaxSpawnClusterSize()), "l YES", - c+" , fit: ", - ((fits_true && fits_false)?"y YES and NO":(fits_true?"l YES":"r NO")), - c+" , will: ", - ((will_spawn>0)?"l ":"r ")+Math.round((double)will_spawn)/10+"%" + color + " , fit: ", + (fits ? "l YES" : "r NO"), + color + " , will: ", + ((willSpawn > 0)?"l ":"r ") + Math.round((double)willSpawn) / 10 + "%" )); } else { - rep.add(Messenger.c(String.format("gi %s: %s (%d:%d-%d/%d), can: ",type_code,creature_name,weight,spawnEntry.minCount, spawnEntry.maxCount, mob.getMaxSpawnClusterSize()), "n NO")); + rep.add(Messenger.c(String.format("gi %s: %s (%d:%d-%d/%d), can: ", categoryCode, mobTypeName, weight, spawnEntry.minCount, spawnEntry.maxCount, mob.getMaxSpawnClusterSize()), "n NO")); } killEntity(mob); } diff --git a/src/main/java/carpet/utils/WoolTool.java b/src/main/java/carpet/utils/WoolTool.java index 23f16c5687..7d3fa7fa95 100644 --- a/src/main/java/carpet/utils/WoolTool.java +++ b/src/main/java/carpet/utils/WoolTool.java @@ -75,7 +75,7 @@ public static void carpetPlacedAction(DyeColor color, Player placer, BlockPos po break; case BLACK: if (!"false".equals(CarpetSettings.commandSpawn)) - Messenger.send(placer, SpawnReporter.show_mobcaps(pos, worldIn)); + Messenger.send(placer, SpawnReporter.handleWoolAction(pos, worldIn)); break; case BROWN: if (!"false".equals(CarpetSettings.commandDistance)) From fedccb4d61f6eab464cc998f70e71596259c4e82 Mon Sep 17 00:00:00 2001 From: altrisi Date: Fri, 28 Jul 2023 21:01:39 +0200 Subject: [PATCH 184/233] Remove `onPlayerLoggedOut` with one arg method It's never been API and but it has even been deprecated for a while so nothing should be using it --- src/main/java/carpet/CarpetServer.java | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/main/java/carpet/CarpetServer.java b/src/main/java/carpet/CarpetServer.java index 90897bbdf7..9863898972 100644 --- a/src/main/java/carpet/CarpetServer.java +++ b/src/main/java/carpet/CarpetServer.java @@ -172,11 +172,6 @@ public static void onPlayerLoggedIn(ServerPlayer player) scriptServer.onPlayerJoin(player); } - @Deprecated(forRemoval = true) - public static void onPlayerLoggedOut(ServerPlayer player) - { - onPlayerLoggedOut(player, Component.translatable("multiplayer.player.left")); - } public static void onPlayerLoggedOut(ServerPlayer player, Component reason) { ServerNetworkHandler.onPlayerLoggedOut(player); From a29b84ec0dfc5d811a4285474cf2d74af205b46f Mon Sep 17 00:00:00 2001 From: altrisi Date: Fri, 28 Jul 2023 21:10:17 +0200 Subject: [PATCH 185/233] Remove `lightEngineMaxBatchSize` rule (#1771) --- src/main/java/carpet/CarpetSettings.java | 37 ------------------- .../mixins/MinecraftServer_coreMixin.java | 2 - .../resources/assets/carpet/lang/fr_fr.json | 6 --- .../resources/assets/carpet/lang/pt_br.json | 6 --- .../resources/assets/carpet/lang/zh_tw.json | 5 --- 5 files changed, 56 deletions(-) diff --git a/src/main/java/carpet/CarpetSettings.java b/src/main/java/carpet/CarpetSettings.java index 871cb9d8c0..8bd8e2ac8f 100644 --- a/src/main/java/carpet/CarpetSettings.java +++ b/src/main/java/carpet/CarpetSettings.java @@ -866,43 +866,6 @@ public static class ChangeSpawnChunksValidator extends Validator { ) public static int spawnChunksSize = MinecraftServer.START_CHUNK_RADIUS; - public static class LightBatchValidator extends Validator { - public static void applyLightBatchSizes(MinecraftServer server, int maxBatchSize) - { - for (ServerLevel world : server.getAllLevels()) - { - //world.getChunkSource().getLightEngine().setTaskPerBatch(maxBatchSize); - } - } - @Override public Integer validate(CommandSourceStack source, CarpetRule currentRule, Integer newValue, String string) { - if (source == null) return newValue; - if (newValue < 0) - { - Messenger.m(source, "r light batch size has to be at least 0"); - return null; - } - if (currentRule.value().intValue() == newValue.intValue()) - { - //must been some startup thing - return newValue; - } - - applyLightBatchSizes(source.getServer(), newValue); // Apply new settings - - return newValue; - } - } - - @Rule( - desc = "Changes maximum light tasks batch size", - extra = {"Allows for a higher light suppression tolerance", "setting it to 5 - Default limit defined by the game"}, - category = {EXPERIMENTAL, OPTIMIZATION}, - strict = false, - options = {"5", "50", "100", "200"}, - validate = LightBatchValidator.class - ) - public static int lightEngineMaxBatchSize = 5; - public enum RenewableCoralMode { FALSE, EXPANDED, diff --git a/src/main/java/carpet/mixins/MinecraftServer_coreMixin.java b/src/main/java/carpet/mixins/MinecraftServer_coreMixin.java index 1d54415d4f..e8b5aba016 100644 --- a/src/main/java/carpet/mixins/MinecraftServer_coreMixin.java +++ b/src/main/java/carpet/mixins/MinecraftServer_coreMixin.java @@ -67,7 +67,5 @@ private void afterSpawnCreated(ChunkProgressListener worldGenerationProgressList { if (CarpetSettings.spawnChunksSize != 11) SpawnChunks.changeSpawnSize(overworld(), CarpetSettings.spawnChunksSize); - - CarpetSettings.LightBatchValidator.applyLightBatchSizes((MinecraftServer) (Object) this, CarpetSettings.lightEngineMaxBatchSize); } } diff --git a/src/main/resources/assets/carpet/lang/fr_fr.json b/src/main/resources/assets/carpet/lang/fr_fr.json index 047415349b..c5d39360b1 100644 --- a/src/main/resources/assets/carpet/lang/fr_fr.json +++ b/src/main/resources/assets/carpet/lang/fr_fr.json @@ -223,12 +223,6 @@ // language "carpet.rule.language.desc": "Définit la langue pour Carpet", - // lightEngineMaxBatchSize - "carpet.rule.lightEngineMaxBatchSize.desc": "Modifie la taille maximale du lot de tâches d'éclairage", - - "carpet.rule.lightEngineMaxBatchSize.extra.0": "Permet une tolérance supérieure à l'extinction de la lumière", - "carpet.rule.lightEngineMaxBatchSize.extra.1": "en le réglant sur 5 - Limite par défaut définie par le jeu", - // lightningKillsDropsFix "carpet.rule.lightningKillsDropsFix.desc": "La foudre détruit les objets qui tombent lorsque la foudre tue une entité", diff --git a/src/main/resources/assets/carpet/lang/pt_br.json b/src/main/resources/assets/carpet/lang/pt_br.json index f47e5b4baa..b827cd9b32 100644 --- a/src/main/resources/assets/carpet/lang/pt_br.json +++ b/src/main/resources/assets/carpet/lang/pt_br.json @@ -229,12 +229,6 @@ "carpet.rule.leadFix.extra.0": "Você ainda pode obter links de trela visivelmente quebrados no lado do cliente, mas no lado do servidor o link ainda está lá.", - // lightEngineMaxBatchSize - "carpet.rule.lightEngineMaxBatchSize.desc": "Altera o tamanho máximo do lote de tarefas leves", - - "carpet.rule.lightEngineMaxBatchSize.extra.0": "Permite uma maior tolerância de supressão de luz", - "carpet.rule.lightEngineMaxBatchSize.extra.1": "configurando para 5 - Limite padrão definido pelo jogo", - // lightningKillsDropsFix "carpet.rule.lightningKillsDropsFix.desc": "O relâmpago mata os itens que caem quando o relâmpago mata uma entidade", diff --git a/src/main/resources/assets/carpet/lang/zh_tw.json b/src/main/resources/assets/carpet/lang/zh_tw.json index 240b7b595b..9f68e0e245 100644 --- a/src/main/resources/assets/carpet/lang/zh_tw.json +++ b/src/main/resources/assets/carpet/lang/zh_tw.json @@ -253,11 +253,6 @@ "carpet.rule.renewableBlackstone.desc": "地獄玄武岩生成機,但在下方沒有靈魂沙", "carpet.rule.renewableBlackstone.extra.0": "..將會轉換成黑石", - "carpet.rule.lightEngineMaxBatchSize.name": "光照引擎最大批次大小", - "carpet.rule.lightEngineMaxBatchSize.desc": "更改光照引擎最大批次大小", - "carpet.rule.lightEngineMaxBatchSize.extra.0": "允許更高光照抑制容限", - "carpet.rule.lightEngineMaxBatchSize.extra.1": "設置成5-遊戲預設容限", - "carpet.rule.cleanLogs.name": "清除數據追蹤器", "carpet.rule.cleanLogs.desc": "從數據追蹤器中刪除令人討厭的信息", "carpet.rule.cleanLogs.extra.0": "在'達到最大聲音對象池247'時將不再顯示", From 1a73edbf76d6730506da3e3be2227592f1de2b26 Mon Sep 17 00:00:00 2001 From: altrisi Date: Tue, 1 Aug 2023 12:43:47 +0200 Subject: [PATCH 186/233] Fix chat signatures desyncing when cancelling `__on_player_message` (#1778) --- .../mixins/PlayerList_scarpetEventsMixin.java | 14 ++++++++++++++ ...rGamePacketListenerImpl_scarpetEventsMixin.java | 13 ------------- 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/src/main/java/carpet/mixins/PlayerList_scarpetEventsMixin.java b/src/main/java/carpet/mixins/PlayerList_scarpetEventsMixin.java index 99915f0585..0619221560 100644 --- a/src/main/java/carpet/mixins/PlayerList_scarpetEventsMixin.java +++ b/src/main/java/carpet/mixins/PlayerList_scarpetEventsMixin.java @@ -2,6 +2,8 @@ import carpet.fakes.ServerPlayerInterface; import carpet.script.external.Vanilla; +import net.minecraft.network.chat.ChatType; +import net.minecraft.network.chat.PlayerChatMessage; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.players.PlayerList; @@ -13,6 +15,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; +import static carpet.script.CarpetEventServer.Event.PLAYER_MESSAGE; import static carpet.script.CarpetEventServer.Event.PLAYER_RESPAWNS; @Mixin(PlayerList.class) @@ -26,6 +29,17 @@ private void onRespawn(ServerPlayer player, boolean olive, CallbackInfoReturnabl PLAYER_RESPAWNS.onPlayerEvent(player); } + @Inject(method = "broadcastChatMessage(Lnet/minecraft/network/chat/PlayerChatMessage;Lnet/minecraft/server/level/ServerPlayer;Lnet/minecraft/network/chat/ChatType$Bound;)V", + at = @At("HEAD"), + cancellable = true) + private void cancellableChatMessageEvent(PlayerChatMessage message, ServerPlayer player, ChatType.Bound params, CallbackInfo ci) { + // having this earlier breaks signatures + if (PLAYER_MESSAGE.isNeeded()) + { + if (PLAYER_MESSAGE.onPlayerMessage(player, message.signedContent())) ci.cancel(); + } + } + @Inject(method = "respawn", at = @At( value = "INVOKE", target = "Lnet/minecraft/server/level/ServerPlayer;initInventoryMenu()V" diff --git a/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_scarpetEventsMixin.java b/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_scarpetEventsMixin.java index 26749b59f7..5501163572 100644 --- a/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_scarpetEventsMixin.java +++ b/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_scarpetEventsMixin.java @@ -1,7 +1,6 @@ package carpet.mixins; import net.minecraft.network.protocol.game.ServerboundChatCommandPacket; -import net.minecraft.network.protocol.game.ServerboundChatPacket; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; @@ -26,7 +25,6 @@ import static carpet.script.CarpetEventServer.Event.PLAYER_SWAPS_HANDS; import static carpet.script.CarpetEventServer.Event.PLAYER_SWINGS_HAND; import static carpet.script.CarpetEventServer.Event.PLAYER_SWITCHES_SLOT; -import static carpet.script.CarpetEventServer.Event.PLAYER_MESSAGE; import static carpet.script.CarpetEventServer.Event.PLAYER_COMMAND; import static carpet.script.CarpetEventServer.Event.PLAYER_USES_ITEM; import static carpet.script.CarpetEventServer.Event.PLAYER_WAKES_UP; @@ -274,17 +272,6 @@ private void onSwing(ServerboundSwingPacket packet, CallbackInfo ci) } } - @Inject(method = "handleChat(Lnet/minecraft/network/protocol/game/ServerboundChatPacket;)V", - at = @At(value = "HEAD"), - cancellable = true - ) - private void onChatMessage(ServerboundChatPacket serverboundChatPacket, CallbackInfo ci) { - if (PLAYER_MESSAGE.isNeeded()) - { - if(PLAYER_MESSAGE.onPlayerMessage(player, serverboundChatPacket.message())) ci.cancel(); - } - } - @Inject(method = "handleChatCommand(Lnet/minecraft/network/protocol/game/ServerboundChatCommandPacket;)V", at = @At(value = "HEAD") ) From f564a9c49106231c2d4608caa8781bd9a011ae19 Mon Sep 17 00:00:00 2001 From: Blodhgarm Date: Tue, 1 Aug 2023 06:29:49 -0500 Subject: [PATCH 187/233] Refactor PistionStructureResolver API for better Compatiblity (#1775) * Implement better handling for custom block interactions within the `PistionStructureResolver` - Switch to a opt in system for piston interaction methods by moving to a dedicated interface and removing mixin that injects such into every block - Default to vanilla code for slime blocks and honey blocks behavior. - Keep `BlockBehaviourInterface` and `BlockBehaviour_customStickyMixin` for compatibility reasons --- .../carpet/fakes/BlockBehaviourInterface.java | 20 ------------ .../fakes/BlockPistonBehaviourInterface.java | 28 +++++++++++++++++ .../BlockBehaviour_customStickyMixin.java | 25 --------------- .../mixins/ChainBlock_customStickyMixin.java | 4 +-- .../mixins/ChestBlock_customStickyMixin.java | 5 +-- .../mixins/HoneyBlock_customStickyMixin.java | 26 ---------------- ...onStructureResolver_customStickyMixin.java | 31 +++++++++++++------ .../mixins/SlimeBlock_customStickyMixin.java | 26 ---------------- src/main/resources/carpet.mixins.json | 6 ++-- 9 files changed, 57 insertions(+), 114 deletions(-) delete mode 100644 src/main/java/carpet/fakes/BlockBehaviourInterface.java create mode 100644 src/main/java/carpet/fakes/BlockPistonBehaviourInterface.java delete mode 100644 src/main/java/carpet/mixins/BlockBehaviour_customStickyMixin.java delete mode 100644 src/main/java/carpet/mixins/HoneyBlock_customStickyMixin.java delete mode 100644 src/main/java/carpet/mixins/SlimeBlock_customStickyMixin.java diff --git a/src/main/java/carpet/fakes/BlockBehaviourInterface.java b/src/main/java/carpet/fakes/BlockBehaviourInterface.java deleted file mode 100644 index 289c0743ab..0000000000 --- a/src/main/java/carpet/fakes/BlockBehaviourInterface.java +++ /dev/null @@ -1,20 +0,0 @@ -package carpet.fakes; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.state.BlockState; - -public interface BlockBehaviourInterface { - - /** - * @return whether this block is sticky in any way when moved by pistons - */ - public boolean isSticky(BlockState state); - - /** - * @return whether the neighboring block is pulled along if this block is moved by pistons - */ - public boolean isStickyToNeighbor(Level level, BlockPos pos, BlockState state, BlockPos neighborPos, BlockState neighborState, Direction dir, Direction moveDir); - -} diff --git a/src/main/java/carpet/fakes/BlockPistonBehaviourInterface.java b/src/main/java/carpet/fakes/BlockPistonBehaviourInterface.java new file mode 100644 index 0000000000..d65ea525f1 --- /dev/null +++ b/src/main/java/carpet/fakes/BlockPistonBehaviourInterface.java @@ -0,0 +1,28 @@ +package carpet.fakes; + +import carpet.mixins.PistonStructureResolver_customStickyMixin; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.piston.PistonStructureResolver; +import net.minecraft.world.level.block.state.BlockState; + +/** + * Opt-in Interface that allows for more control on a blocks interaction within the {@link PistonStructureResolver} via {@link PistonStructureResolver_customStickyMixin} + */ +public interface BlockPistonBehaviourInterface { + + /** + * @return whether this block is sticky in any way when moved by pistons + */ + default boolean isSticky(BlockState state) { + return false; + } + + /** + * @return whether the neighboring block is pulled along if this block is moved by pistons + */ + default boolean isStickyToNeighbor(Level level, BlockPos pos, BlockState state, BlockPos neighborPos, BlockState neighborState, Direction dir, Direction moveDir) { + return false; + } +} diff --git a/src/main/java/carpet/mixins/BlockBehaviour_customStickyMixin.java b/src/main/java/carpet/mixins/BlockBehaviour_customStickyMixin.java deleted file mode 100644 index 55fc78b4f9..0000000000 --- a/src/main/java/carpet/mixins/BlockBehaviour_customStickyMixin.java +++ /dev/null @@ -1,25 +0,0 @@ -package carpet.mixins; - -import org.spongepowered.asm.mixin.Mixin; - -import carpet.fakes.BlockBehaviourInterface; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.state.BlockBehaviour; -import net.minecraft.world.level.block.state.BlockState; - -@Mixin(BlockBehaviour.class) -public class BlockBehaviour_customStickyMixin implements BlockBehaviourInterface { - - @Override - public boolean isSticky(BlockState state) { - return false; - } - - @Override - public boolean isStickyToNeighbor(Level level, BlockPos pos, BlockState state, BlockPos neighborPos, BlockState neighborState, Direction dir, Direction moveDir) { - return false; - } -} diff --git a/src/main/java/carpet/mixins/ChainBlock_customStickyMixin.java b/src/main/java/carpet/mixins/ChainBlock_customStickyMixin.java index 9cad0aea61..c7e3d727d7 100644 --- a/src/main/java/carpet/mixins/ChainBlock_customStickyMixin.java +++ b/src/main/java/carpet/mixins/ChainBlock_customStickyMixin.java @@ -1,10 +1,10 @@ package carpet.mixins; +import carpet.fakes.BlockPistonBehaviourInterface; import org.spongepowered.asm.mixin.Mixin; import carpet.CarpetSettings; import carpet.CarpetSettings.ChainStoneMode; -import carpet.fakes.BlockBehaviourInterface; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -17,7 +17,7 @@ import net.minecraft.world.level.block.state.BlockState; @Mixin(ChainBlock.class) -public class ChainBlock_customStickyMixin implements BlockBehaviourInterface { +public class ChainBlock_customStickyMixin implements BlockPistonBehaviourInterface { @Override public boolean isSticky(BlockState state) { diff --git a/src/main/java/carpet/mixins/ChestBlock_customStickyMixin.java b/src/main/java/carpet/mixins/ChestBlock_customStickyMixin.java index 6b98c1f84d..271a3b1cdd 100644 --- a/src/main/java/carpet/mixins/ChestBlock_customStickyMixin.java +++ b/src/main/java/carpet/mixins/ChestBlock_customStickyMixin.java @@ -1,9 +1,9 @@ package carpet.mixins; +import carpet.fakes.BlockPistonBehaviourInterface; import org.spongepowered.asm.mixin.Mixin; import carpet.CarpetSettings; -import carpet.fakes.BlockBehaviourInterface; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -16,7 +16,7 @@ import static net.minecraft.world.level.block.ChestBlock.getConnectedDirection; @Mixin(ChestBlock.class) -public class ChestBlock_customStickyMixin implements BlockBehaviourInterface { +public class ChestBlock_customStickyMixin implements BlockPistonBehaviourInterface { @Override public boolean isSticky(BlockState state) { @@ -35,6 +35,7 @@ public boolean isStickyToNeighbor(Level level, BlockPos pos, BlockState state, B if (type == ChestType.SINGLE || neighborType == ChestType.SINGLE) { return false; } + return getConnectedDirection(state) == dir; } } diff --git a/src/main/java/carpet/mixins/HoneyBlock_customStickyMixin.java b/src/main/java/carpet/mixins/HoneyBlock_customStickyMixin.java deleted file mode 100644 index d103e399e9..0000000000 --- a/src/main/java/carpet/mixins/HoneyBlock_customStickyMixin.java +++ /dev/null @@ -1,26 +0,0 @@ -package carpet.mixins; - -import org.spongepowered.asm.mixin.Mixin; - -import carpet.fakes.BlockBehaviourInterface; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.HoneyBlock; -import net.minecraft.world.level.block.state.BlockState; - -@Mixin(HoneyBlock.class) -public class HoneyBlock_customStickyMixin implements BlockBehaviourInterface { - - @Override - public boolean isSticky(BlockState state) { - return true; - } - - @Override - public boolean isStickyToNeighbor(Level level, BlockPos pos, BlockState state, BlockPos neighborPos, BlockState neighborState, Direction dir, Direction moveDir) { - return !neighborState.is(Blocks.SLIME_BLOCK); - } -} diff --git a/src/main/java/carpet/mixins/PistonStructureResolver_customStickyMixin.java b/src/main/java/carpet/mixins/PistonStructureResolver_customStickyMixin.java index 13abaec9eb..9d86898012 100644 --- a/src/main/java/carpet/mixins/PistonStructureResolver_customStickyMixin.java +++ b/src/main/java/carpet/mixins/PistonStructureResolver_customStickyMixin.java @@ -3,13 +3,14 @@ import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; -import carpet.fakes.BlockBehaviourInterface; +import carpet.fakes.BlockPistonBehaviourInterface; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -18,11 +19,13 @@ import net.minecraft.world.level.block.state.BlockState; @Mixin(PistonStructureResolver.class) -public class PistonStructureResolver_customStickyMixin { +public abstract class PistonStructureResolver_customStickyMixin { @Shadow @Final private Level level; @Shadow @Final private Direction pushDirection; + @Shadow private static boolean canStickToEachOther(BlockState blockState, BlockState blockState2) { return false; } + @Inject( method = "isSticky", cancellable = true, @@ -31,12 +34,14 @@ public class PistonStructureResolver_customStickyMixin { ) ) private static void isSticky(BlockState state, CallbackInfoReturnable cir) { - cir.setReturnValue(((BlockBehaviourInterface)state.getBlock()).isSticky(state)); + if(state.getBlock() instanceof BlockPistonBehaviourInterface behaviourInterface){ + cir.setReturnValue(behaviourInterface.isSticky(state)); + } } // fields that are needed because @Redirects cannot capture locals - private BlockPos pos_addBlockLine; - private BlockPos behindPos_addBlockLine; + @Unique private BlockPos pos_addBlockLine; + @Unique private BlockPos behindPos_addBlockLine; @Inject( method = "addBlockLine", @@ -60,12 +65,16 @@ private void captureBlockLinePositions(BlockPos pos, Direction fromDir, Callback ) ) private boolean onAddBlockLineCanStickToEachOther(BlockState state, BlockState behindState) { - return ((BlockBehaviourInterface)state.getBlock()).isStickyToNeighbor(level, pos_addBlockLine, state, behindPos_addBlockLine, behindState, pushDirection.getOpposite(), pushDirection); + if (state.getBlock() instanceof BlockPistonBehaviourInterface behaviourInterface) { + return behaviourInterface.isStickyToNeighbor(level, pos_addBlockLine, state, behindPos_addBlockLine, behindState, pushDirection.getOpposite(), pushDirection); + } + + return canStickToEachOther(state, behindState); } // fields that are needed because @Redirects cannot capture locals - private Direction dir_addBranchingBlocks; - private BlockPos neighborPos_addBranchingBlocks; + @Unique private Direction dir_addBranchingBlocks; + @Unique private BlockPos neighborPos_addBranchingBlocks; @Inject( method = "addBranchingBlocks", @@ -89,6 +98,10 @@ private void captureNeighborPositions(BlockPos pos, CallbackInfoReturnable Date: Tue, 1 Aug 2023 13:39:00 +0200 Subject: [PATCH 188/233] Tweaks on top of #1775 Make new interface not have default methods, make `Shadow` body throw and tiny style changes --- .../java/carpet/fakes/BlockPistonBehaviourInterface.java | 8 ++------ .../java/carpet/mixins/ChestBlock_customStickyMixin.java | 2 +- .../mixins/PistonStructureResolver_customStickyMixin.java | 8 +++++--- 3 files changed, 8 insertions(+), 10 deletions(-) diff --git a/src/main/java/carpet/fakes/BlockPistonBehaviourInterface.java b/src/main/java/carpet/fakes/BlockPistonBehaviourInterface.java index d65ea525f1..b88bf63042 100644 --- a/src/main/java/carpet/fakes/BlockPistonBehaviourInterface.java +++ b/src/main/java/carpet/fakes/BlockPistonBehaviourInterface.java @@ -15,14 +15,10 @@ public interface BlockPistonBehaviourInterface { /** * @return whether this block is sticky in any way when moved by pistons */ - default boolean isSticky(BlockState state) { - return false; - } + boolean isSticky(BlockState state); /** * @return whether the neighboring block is pulled along if this block is moved by pistons */ - default boolean isStickyToNeighbor(Level level, BlockPos pos, BlockState state, BlockPos neighborPos, BlockState neighborState, Direction dir, Direction moveDir) { - return false; - } + boolean isStickyToNeighbor(Level level, BlockPos pos, BlockState state, BlockPos neighborPos, BlockState neighborState, Direction dir, Direction moveDir); } diff --git a/src/main/java/carpet/mixins/ChestBlock_customStickyMixin.java b/src/main/java/carpet/mixins/ChestBlock_customStickyMixin.java index 271a3b1cdd..b31483615c 100644 --- a/src/main/java/carpet/mixins/ChestBlock_customStickyMixin.java +++ b/src/main/java/carpet/mixins/ChestBlock_customStickyMixin.java @@ -1,9 +1,9 @@ package carpet.mixins; -import carpet.fakes.BlockPistonBehaviourInterface; import org.spongepowered.asm.mixin.Mixin; import carpet.CarpetSettings; +import carpet.fakes.BlockPistonBehaviourInterface; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; diff --git a/src/main/java/carpet/mixins/PistonStructureResolver_customStickyMixin.java b/src/main/java/carpet/mixins/PistonStructureResolver_customStickyMixin.java index 9d86898012..88ab4fd8f1 100644 --- a/src/main/java/carpet/mixins/PistonStructureResolver_customStickyMixin.java +++ b/src/main/java/carpet/mixins/PistonStructureResolver_customStickyMixin.java @@ -19,12 +19,14 @@ import net.minecraft.world.level.block.state.BlockState; @Mixin(PistonStructureResolver.class) -public abstract class PistonStructureResolver_customStickyMixin { +public class PistonStructureResolver_customStickyMixin { @Shadow @Final private Level level; @Shadow @Final private Direction pushDirection; - @Shadow private static boolean canStickToEachOther(BlockState blockState, BlockState blockState2) { return false; } + @Shadow private static boolean canStickToEachOther(BlockState blockState, BlockState blockState2) { + throw new AssertionError(); + } @Inject( method = "isSticky", @@ -34,7 +36,7 @@ public abstract class PistonStructureResolver_customStickyMixin { ) ) private static void isSticky(BlockState state, CallbackInfoReturnable cir) { - if(state.getBlock() instanceof BlockPistonBehaviourInterface behaviourInterface){ + if (state.getBlock() instanceof BlockPistonBehaviourInterface behaviourInterface){ cir.setReturnValue(behaviourInterface.isSticky(state)); } } From 55a88c6cdc91b14dbfb6c52597925caed1e532f1 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Thu, 3 Aug 2023 12:32:34 +0200 Subject: [PATCH 189/233] 1.4.113 on 23w31a, many regressions including modded networking, fake players, scoreboard api and more. --- gradle.properties | 6 +- .../carpet/fakes/CarpetPacketPayload.java | 11 +++ .../carpet/helpers/FertilizableCoral.java | 2 +- ...nPacketListenerImpl_customPacketMixin.java | 28 ++++++ ...ientPacketListener_clientCommandMixin.java | 11 ++- ...ientPacketListener_customPacketsMixin.java | 30 +++--- ...CustomPayloadPacket_customPacketMixin.java | 35 +++++++ .../mixins/Connection_packetCounterMixin.java | 2 +- .../java/carpet/mixins/MinecraftMixin.java | 2 +- .../carpet/mixins/PlayerList_coreMixin.java | 2 +- .../mixins/PlayerList_fakePlayersMixin.java | 12 +-- ...monPacketListenerimpl_connectionMixin.java | 33 +++++++ .../ServerGamePacketListenerImplMixin.java | 17 +--- ...etListenerImpl_antiCheatDisabledMixin.java | 12 ++- ...erverGamePacketListenerImpl_coreMixin.java | 9 +- .../ServerboundCustomPayloadPacket_mixin.java | 52 ++++++++++ .../java/carpet/network/CarpetClient.java | 21 +++++ .../carpet/network/ClientNetworkHandler.java | 36 ++++++- .../carpet/network/ServerNetworkHandler.java | 94 ++++++++++++------- .../carpet/patches/EntityPlayerMPFake.java | 8 +- .../patches/NetHandlerPlayServerFake.java | 5 +- .../java/carpet/script/api/Scoreboards.java | 18 ++-- .../script/command/CommandArgument.java | 6 +- .../java/carpet/script/value/EntityValue.java | 2 +- src/main/resources/carpet.mixins.json | 11 ++- 25 files changed, 356 insertions(+), 109 deletions(-) create mode 100644 src/main/java/carpet/fakes/CarpetPacketPayload.java create mode 100644 src/main/java/carpet/mixins/ClientCommonPacketListenerImpl_customPacketMixin.java create mode 100644 src/main/java/carpet/mixins/ClientboundCustomPayloadPacket_customPacketMixin.java create mode 100644 src/main/java/carpet/mixins/ServerCommonPacketListenerimpl_connectionMixin.java create mode 100644 src/main/java/carpet/mixins/ServerboundCustomPayloadPacket_mixin.java diff --git a/gradle.properties b/gradle.properties index 8946439342..202bc782e0 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,13 +3,13 @@ org.gradle.jvmargs=-Xmx1G # Fabric Properties # check https://fabricmc.net/develop/ - minecraft_version=1.20.1 - loader_version=0.14.21 + minecraft_version=23w31a + loader_version=0.14.22 jsr305_version=3.0.2 fabric_version=0.83.0+1.20.1 # Mod Properties - mod_version = 1.4.112 + mod_version = 1.4.113 maven_group = carpet archives_base_name = fabric-carpet diff --git a/src/main/java/carpet/fakes/CarpetPacketPayload.java b/src/main/java/carpet/fakes/CarpetPacketPayload.java new file mode 100644 index 0000000000..d157675909 --- /dev/null +++ b/src/main/java/carpet/fakes/CarpetPacketPayload.java @@ -0,0 +1,11 @@ +package carpet.fakes; + +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.network.protocol.common.custom.DiscardedPayload; +import net.minecraft.resources.ResourceLocation; + +public interface CarpetPacketPayload extends CustomPacketPayload +{ + FriendlyByteBuf data(); +} diff --git a/src/main/java/carpet/helpers/FertilizableCoral.java b/src/main/java/carpet/helpers/FertilizableCoral.java index c1116af662..9c8bd43dde 100644 --- a/src/main/java/carpet/helpers/FertilizableCoral.java +++ b/src/main/java/carpet/helpers/FertilizableCoral.java @@ -33,7 +33,7 @@ public interface FertilizableCoral extends BonemealableBlock { boolean isEnabled(); @Override - public default boolean isValidBonemealTarget(LevelReader world, BlockPos pos, BlockState state, boolean var4) + public default boolean isValidBonemealTarget(LevelReader world, BlockPos pos, BlockState state) { return isEnabled() && state.getValue(BaseCoralPlantTypeBlock.WATERLOGGED) diff --git a/src/main/java/carpet/mixins/ClientCommonPacketListenerImpl_customPacketMixin.java b/src/main/java/carpet/mixins/ClientCommonPacketListenerImpl_customPacketMixin.java new file mode 100644 index 0000000000..3cd91bf68d --- /dev/null +++ b/src/main/java/carpet/mixins/ClientCommonPacketListenerImpl_customPacketMixin.java @@ -0,0 +1,28 @@ +package carpet.mixins; + +import carpet.network.CarpetClient; +import net.minecraft.client.multiplayer.ClientCommonPacketListenerImpl; +import net.minecraft.network.chat.Component; +import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(ClientCommonPacketListenerImpl.class) +public class ClientCommonPacketListenerImpl_customPacketMixin +{ + @Inject(method = "onDisconnect", at = @At("HEAD")) + private void onCMDisconnected(Component reason, CallbackInfo ci) + { + CarpetClient.disconnect(); + } + + @Inject(method = "handleCustomPayload(Lnet/minecraft/network/protocol/common/ClientboundCustomPayloadPacket;)V", + at = @At("HEAD")) + private void onOnCustomPayload(ClientboundCustomPayloadPacket packet, CallbackInfo ci) + { + //System.out.println("CustomPayload of : " + packet.payload()); + } + +} diff --git a/src/main/java/carpet/mixins/ClientPacketListener_clientCommandMixin.java b/src/main/java/carpet/mixins/ClientPacketListener_clientCommandMixin.java index 61ba0dd6d0..6690ea4992 100644 --- a/src/main/java/carpet/mixins/ClientPacketListener_clientCommandMixin.java +++ b/src/main/java/carpet/mixins/ClientPacketListener_clientCommandMixin.java @@ -3,8 +3,11 @@ import carpet.CarpetServer; import carpet.network.CarpetClient; import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientCommonPacketListenerImpl; import net.minecraft.client.multiplayer.ClientPacketListener; +import net.minecraft.client.multiplayer.CommonListenerCookie; import net.minecraft.client.player.LocalPlayer; +import net.minecraft.network.Connection; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -13,9 +16,13 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(ClientPacketListener.class) -public class ClientPacketListener_clientCommandMixin +public abstract class ClientPacketListener_clientCommandMixin extends ClientCommonPacketListenerImpl { - @Shadow @Final private Minecraft minecraft; + + protected ClientPacketListener_clientCommandMixin(final Minecraft minecraft, final Connection connection, final CommonListenerCookie commonListenerCookie) + { + super(minecraft, connection, commonListenerCookie); + } @Inject(method = "sendCommand", at = @At("HEAD")) private void inspectMessage(String string, CallbackInfo ci) diff --git a/src/main/java/carpet/mixins/ClientPacketListener_customPacketsMixin.java b/src/main/java/carpet/mixins/ClientPacketListener_customPacketsMixin.java index ce0736453c..d159ba3072 100644 --- a/src/main/java/carpet/mixins/ClientPacketListener_customPacketsMixin.java +++ b/src/main/java/carpet/mixins/ClientPacketListener_customPacketsMixin.java @@ -3,41 +3,39 @@ import carpet.network.CarpetClient; import carpet.network.ClientNetworkHandler; import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientCommonPacketListenerImpl; import net.minecraft.client.multiplayer.ClientPacketListener; +import net.minecraft.client.multiplayer.CommonListenerCookie; +import net.minecraft.network.Connection; +import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.chat.Component; -import net.minecraft.network.protocol.game.ClientboundCustomPayloadPacket; +import net.minecraft.network.protocol.common.ClientCommonPacketListener; +import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.network.protocol.common.custom.DiscardedPayload; import net.minecraft.network.protocol.game.ClientboundLoginPacket; +import net.minecraft.resources.ResourceLocation; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(ClientPacketListener.class) -public abstract class ClientPacketListener_customPacketsMixin +public abstract class ClientPacketListener_customPacketsMixin extends ClientCommonPacketListenerImpl { - @Final @Shadow private Minecraft minecraft; - @Inject(method = "handleCustomPayload", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/protocol/game/ClientboundCustomPayloadPacket;getIdentifier()Lnet/minecraft/resources/ResourceLocation;"), cancellable = true) - private void onOnCustomPayload(ClientboundCustomPayloadPacket packet, CallbackInfo ci) + protected ClientPacketListener_customPacketsMixin(final Minecraft minecraft, final Connection connection, final CommonListenerCookie commonListenerCookie) { - if (CarpetClient.CARPET_CHANNEL.equals(packet.getIdentifier())) - { - ClientNetworkHandler.handleData(packet.getData(), minecraft.player); - ci.cancel(); - } + super(minecraft, connection, commonListenerCookie); } @Inject(method = "handleLogin", at = @At("RETURN")) private void onGameJoined(ClientboundLoginPacket packet, CallbackInfo info) { - CarpetClient.gameJoined(minecraft.player); + CarpetClient.gameJoined( minecraft.player); } - @Inject(method = "onDisconnect", at = @At("HEAD")) - private void onCMDisconnected(Component reason, CallbackInfo ci) - { - CarpetClient.disconnect(); - } } diff --git a/src/main/java/carpet/mixins/ClientboundCustomPayloadPacket_customPacketMixin.java b/src/main/java/carpet/mixins/ClientboundCustomPayloadPacket_customPacketMixin.java new file mode 100644 index 0000000000..bb2f41e7f0 --- /dev/null +++ b/src/main/java/carpet/mixins/ClientboundCustomPayloadPacket_customPacketMixin.java @@ -0,0 +1,35 @@ +package carpet.mixins; + + +import carpet.network.CarpetClient; +import carpet.network.ClientNetworkHandler; +import net.minecraft.client.Minecraft; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.network.protocol.common.custom.DiscardedPayload; +import net.minecraft.resources.ResourceLocation; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(ClientboundCustomPayloadPacket.class) +public class ClientboundCustomPayloadPacket_customPacketMixin +{ + @Inject(method = "readPayload", at = @At("HEAD")) + private static void onOnCustomPayloadR(final ResourceLocation resourceLocation, final FriendlyByteBuf friendlyByteBuf, final CallbackInfoReturnable cir) + { + } + + @Inject(method = "readUnknownPayload", at = @At(value = "HEAD"), cancellable = true) + private static void onOnCustomPayload(ResourceLocation resourceLocation, FriendlyByteBuf friendlyByteBuf, CallbackInfoReturnable cir) + { + if (true) return; + if (CarpetClient.CARPET_CHANNEL.equals(resourceLocation) && Minecraft.getInstance().isSameThread()) + { + ClientNetworkHandler.handleData(friendlyByteBuf, Minecraft.getInstance().player); + cir.setReturnValue(new DiscardedPayload(resourceLocation)); + } + } +} diff --git a/src/main/java/carpet/mixins/Connection_packetCounterMixin.java b/src/main/java/carpet/mixins/Connection_packetCounterMixin.java index f83380ab2c..c7159e7329 100644 --- a/src/main/java/carpet/mixins/Connection_packetCounterMixin.java +++ b/src/main/java/carpet/mixins/Connection_packetCounterMixin.java @@ -28,7 +28,7 @@ private void packetInCount(ChannelHandlerContext channelHandlerContext_1, Packet // Add to the packet counter whenever a packet is sent. @Inject(method = "sendPacket", at = @At("HEAD")) - private void packetOutCount(Packet packet, @Nullable PacketSendListener packetSendListener, CallbackInfo ci) + private void packetOutCount(final Packet packet, final PacketSendListener packetSendListener, final boolean bl, final CallbackInfo ci) { PacketCounter.totalOut++; } diff --git a/src/main/java/carpet/mixins/MinecraftMixin.java b/src/main/java/carpet/mixins/MinecraftMixin.java index 7941cc25b1..c7105a35f1 100644 --- a/src/main/java/carpet/mixins/MinecraftMixin.java +++ b/src/main/java/carpet/mixins/MinecraftMixin.java @@ -20,7 +20,7 @@ public class MinecraftMixin implements MinecraftInterface { @Shadow public ClientLevel level; - @Inject(method = "clearLevel(Lnet/minecraft/client/gui/screens/Screen;)V", at = @At("HEAD")) + @Inject(method = "disconnect(Lnet/minecraft/client/gui/screens/Screen;)V", at = @At("HEAD")) private void onCloseGame(Screen screen, CallbackInfo ci) { CarpetClient.disconnect(); diff --git a/src/main/java/carpet/mixins/PlayerList_coreMixin.java b/src/main/java/carpet/mixins/PlayerList_coreMixin.java index e689d1535a..d52e0c4075 100644 --- a/src/main/java/carpet/mixins/PlayerList_coreMixin.java +++ b/src/main/java/carpet/mixins/PlayerList_coreMixin.java @@ -16,7 +16,7 @@ public class PlayerList_coreMixin { @Inject(method = "placeNewPlayer", at = @At("RETURN")) - private void onPlayerConnected(Connection connection, ServerPlayer player, CallbackInfo ci) + private void onPlayerConnected(Connection connection, ServerPlayer player, int i, CallbackInfo ci) { CarpetServer.onPlayerLoggedIn(player); } diff --git a/src/main/java/carpet/mixins/PlayerList_fakePlayersMixin.java b/src/main/java/carpet/mixins/PlayerList_fakePlayersMixin.java index 0792a72803..2cfdae2226 100644 --- a/src/main/java/carpet/mixins/PlayerList_fakePlayersMixin.java +++ b/src/main/java/carpet/mixins/PlayerList_fakePlayersMixin.java @@ -34,21 +34,21 @@ private void fixStartingPos(ServerPlayer serverPlayerEntity_1, CallbackInfoRetur } } - @Redirect(method = "placeNewPlayer", at = @At(value = "NEW", target = "net/minecraft/server/network/ServerGamePacketListenerImpl")) - private ServerGamePacketListenerImpl replaceNetworkHandler(MinecraftServer server, Connection clientConnection, ServerPlayer playerIn) + @Redirect(method = "placeNewPlayer", at = @At(value = "NEW", target = "(Lnet/minecraft/server/MinecraftServer;Lnet/minecraft/network/Connection;Lnet/minecraft/server/level/ServerPlayer;I)Lnet/minecraft/server/network/ServerGamePacketListenerImpl;")) + private ServerGamePacketListenerImpl replaceNetworkHandler( MinecraftServer server, Connection clientConnection, ServerPlayer playerIn, int i) { if (playerIn instanceof EntityPlayerMPFake fake) { - return new NetHandlerPlayServerFake(this.server, clientConnection, fake); + return new NetHandlerPlayServerFake(this.server, clientConnection, fake, i); } else { - return new ServerGamePacketListenerImpl(this.server, clientConnection, playerIn); + return new ServerGamePacketListenerImpl(this.server, clientConnection, playerIn, i); } } - @Redirect(method = "respawn", at = @At(value = "NEW", target = "net/minecraft/server/level/ServerPlayer")) - public ServerPlayer makePlayerForRespawn(MinecraftServer minecraftServer, ServerLevel serverLevel, GameProfile gameProfile, ServerPlayer serverPlayer, boolean bl) + @Redirect(method = "respawn", at = @At(value = "NEW", target = "(Lnet/minecraft/server/MinecraftServer;Lnet/minecraft/server/level/ServerLevel;Lcom/mojang/authlib/GameProfile;)Lnet/minecraft/server/level/ServerPlayer;")) + public ServerPlayer makePlayerForRespawn(MinecraftServer minecraftServer, ServerLevel serverLevel, GameProfile gameProfile, ServerPlayer serverPlayer, boolean i) { if (serverPlayer instanceof EntityPlayerMPFake) { return EntityPlayerMPFake.respawnFake(minecraftServer, serverLevel, gameProfile); diff --git a/src/main/java/carpet/mixins/ServerCommonPacketListenerimpl_connectionMixin.java b/src/main/java/carpet/mixins/ServerCommonPacketListenerimpl_connectionMixin.java new file mode 100644 index 0000000000..b606e0b3d8 --- /dev/null +++ b/src/main/java/carpet/mixins/ServerCommonPacketListenerimpl_connectionMixin.java @@ -0,0 +1,33 @@ +package carpet.mixins; + +import carpet.fakes.CarpetPacketPayload; +import carpet.network.ServerNetworkHandler; +import net.minecraft.network.protocol.PacketUtils; +import net.minecraft.network.protocol.common.ServerboundCustomPayloadPacket; +import net.minecraft.network.protocol.game.ServerGamePacketListener; +import net.minecraft.server.network.ServerCommonPacketListenerImpl; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(ServerCommonPacketListenerImpl.class) +public class ServerCommonPacketListenerimpl_connectionMixin +{ + @Inject(method = "handleCustomPayload", at = @At("HEAD"), cancellable = true) + private void onCustomCarpetPayload(ServerboundCustomPayloadPacket serverboundCustomPayloadPacket, CallbackInfo ci) + { + if (true) return; + Object thiss = this; + if (thiss instanceof ServerGamePacketListenerImpl impl && serverboundCustomPayloadPacket.payload() instanceof CarpetPacketPayload cpp) { + // We should force onto the main thread here + // ServerNetworkHandler.handleData can possibly mutate data that isn't + // thread safe, and also allows for client commands to be executed + PacketUtils.ensureRunningOnSameThread(serverboundCustomPayloadPacket, (ServerGamePacketListener) this, impl.player.serverLevel()); + ServerNetworkHandler.handleData(cpp.data(), impl.player); + ci.cancel(); + } + ci.cancel(); + } +} diff --git a/src/main/java/carpet/mixins/ServerGamePacketListenerImplMixin.java b/src/main/java/carpet/mixins/ServerGamePacketListenerImplMixin.java index 53788619b0..06aaa474f8 100644 --- a/src/main/java/carpet/mixins/ServerGamePacketListenerImplMixin.java +++ b/src/main/java/carpet/mixins/ServerGamePacketListenerImplMixin.java @@ -3,8 +3,8 @@ import carpet.network.CarpetClient; import carpet.network.ServerNetworkHandler; import net.minecraft.network.protocol.PacketUtils; +import net.minecraft.network.protocol.common.ServerboundCustomPayloadPacket; import net.minecraft.network.protocol.game.ServerGamePacketListener; -import net.minecraft.network.protocol.game.ServerboundCustomPayloadPacket; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.network.ServerGamePacketListenerImpl; @@ -19,18 +19,5 @@ public class ServerGamePacketListenerImplMixin { @Shadow public ServerPlayer player; - @Inject(method = "handleCustomPayload", at = @At("HEAD"), cancellable = true) - private void onCustomCarpetPayload(ServerboundCustomPayloadPacket packet, CallbackInfo ci) - { - ResourceLocation channel = packet.getIdentifier(); - if (CarpetClient.CARPET_CHANNEL.equals(channel)) - { - // We should force onto the main thread here - // ServerNetworkHandler.handleData can possibly mutate data that isn't - // thread safe, and also allows for client commands to be executed - PacketUtils.ensureRunningOnSameThread(packet, (ServerGamePacketListener) this, player.serverLevel()); - ServerNetworkHandler.handleData(packet.getData(), player); - ci.cancel(); - } - } + } diff --git a/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_antiCheatDisabledMixin.java b/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_antiCheatDisabledMixin.java index c49186d9f8..0b0ac1625b 100644 --- a/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_antiCheatDisabledMixin.java +++ b/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_antiCheatDisabledMixin.java @@ -1,7 +1,10 @@ package carpet.mixins; import carpet.CarpetSettings; +import net.minecraft.network.Connection; +import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerCommonPacketListenerImpl; import net.minecraft.server.network.ServerGamePacketListenerImpl; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -11,13 +14,18 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(ServerGamePacketListenerImpl.class) -public abstract class ServerGamePacketListenerImpl_antiCheatDisabledMixin +public abstract class ServerGamePacketListenerImpl_antiCheatDisabledMixin extends ServerCommonPacketListenerImpl { @Shadow private int aboveGroundTickCount; @Shadow private int aboveGroundVehicleTickCount; - @Shadow protected abstract boolean isSingleplayerOwner(); + public ServerGamePacketListenerImpl_antiCheatDisabledMixin(final MinecraftServer minecraftServer, final Connection connection, final int i) + { + super(minecraftServer, connection, i); + } + + //@Shadow protected abstract boolean isSingleplayerOwner(); @Inject(method = "tick", at = @At("HEAD")) private void restrictFloatingBits(CallbackInfo ci) diff --git a/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_coreMixin.java b/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_coreMixin.java index d9a8efcf2d..3d23a71c8f 100644 --- a/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_coreMixin.java +++ b/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_coreMixin.java @@ -4,7 +4,9 @@ import carpet.fakes.ServerGamePacketListenerImplInterface; import net.minecraft.network.Connection; import net.minecraft.network.chat.Component; +import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerCommonPacketListenerImpl; import net.minecraft.server.network.ServerGamePacketListenerImpl; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -14,11 +16,14 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(ServerGamePacketListenerImpl.class) -public class ServerGamePacketListenerImpl_coreMixin implements ServerGamePacketListenerImplInterface { +public abstract class ServerGamePacketListenerImpl_coreMixin extends ServerCommonPacketListenerImpl implements ServerGamePacketListenerImplInterface { @Shadow public ServerPlayer player; - @Shadow @Final private Connection connection; + public ServerGamePacketListenerImpl_coreMixin(final MinecraftServer minecraftServer, final Connection connection, final int i) + { + super(minecraftServer, connection, i); + } @Inject(method = "onDisconnect", at = @At("HEAD")) private void onPlayerDisconnect(Component reason, CallbackInfo ci) { diff --git a/src/main/java/carpet/mixins/ServerboundCustomPayloadPacket_mixin.java b/src/main/java/carpet/mixins/ServerboundCustomPayloadPacket_mixin.java new file mode 100644 index 0000000000..a7a1301d7e --- /dev/null +++ b/src/main/java/carpet/mixins/ServerboundCustomPayloadPacket_mixin.java @@ -0,0 +1,52 @@ +package carpet.mixins; + +import carpet.fakes.CarpetPacketPayload; +import carpet.network.CarpetClient; +import carpet.network.ClientNetworkHandler; +import net.minecraft.client.Minecraft; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.common.ServerboundCustomPayloadPacket; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.network.protocol.common.custom.DiscardedPayload; +import net.minecraft.resources.ResourceLocation; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(ServerboundCustomPayloadPacket.class) +public class ServerboundCustomPayloadPacket_mixin +{ + @Inject(method = "readPayload", at = @At( + value = "INVOKE", + target = "Lnet/minecraft/network/protocol/common/ServerboundCustomPayloadPacket;readUnknownPayload(Lnet/minecraft/resources/ResourceLocation;Lnet/minecraft/network/FriendlyByteBuf;)Lnet/minecraft/network/protocol/common/custom/DiscardedPayload;" + ), cancellable = true) + private static void onOnCustomPayload(ResourceLocation resourceLocation, FriendlyByteBuf friendlyByteBuf, CallbackInfoReturnable cir) + { + if (true) return; + if (CarpetClient.CARPET_CHANNEL.equals(resourceLocation)) + { + //ClientNetworkHandler.handleData(friendlyByteBuf, Minecraft.getInstance().player); + cir.setReturnValue(new CarpetPacketPayload() + { + @Override + public FriendlyByteBuf data() + { + return friendlyByteBuf; + } + + @Override + public void write(final FriendlyByteBuf friendlyByteBuf) + { + // noop - its a client side and we handle it server side only + } + + @Override + public ResourceLocation id() + { + return resourceLocation; + } + }); + } + } +} diff --git a/src/main/java/carpet/network/CarpetClient.java b/src/main/java/carpet/network/CarpetClient.java index 2bb3f0c845..8b268c4ea3 100644 --- a/src/main/java/carpet/network/CarpetClient.java +++ b/src/main/java/carpet/network/CarpetClient.java @@ -7,11 +7,32 @@ import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; import net.minecraft.nbt.Tag; +import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.chat.Component; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import net.minecraft.resources.ResourceLocation; public class CarpetClient { + public record CarpetPayload(CompoundTag data) implements CustomPacketPayload + { + public static final ResourceLocation ID = CARPET_CHANNEL; + + public CarpetPayload(final FriendlyByteBuf input) { + this(input.readNbt()); + } + + @Override + public void write(final FriendlyByteBuf output) { + output.writeNbt(data); + } + + @Override + public ResourceLocation id() { + return ID; + } + } + public static final int HI = 69; public static final int HELLO = 420; public static final int DATA = 1; diff --git a/src/main/java/carpet/network/ClientNetworkHandler.java b/src/main/java/carpet/network/ClientNetworkHandler.java index 0973b7e834..6b8ed288cf 100644 --- a/src/main/java/carpet/network/ClientNetworkHandler.java +++ b/src/main/java/carpet/network/ClientNetworkHandler.java @@ -19,7 +19,9 @@ import net.minecraft.nbt.NumericTag; import net.minecraft.nbt.Tag; import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.network.protocol.game.ServerboundCustomPayloadPacket; +import net.minecraft.network.protocol.common.ServerboundCustomPayloadPacket; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.resources.ResourceLocation; public class ClientNetworkHandler { @@ -129,8 +131,20 @@ private static void onHi(FriendlyByteBuf data) public static void respondHello() { CarpetClient.getPlayer().connection.send(new ServerboundCustomPayloadPacket( - CarpetClient.CARPET_CHANNEL, - (new FriendlyByteBuf(Unpooled.buffer())).writeVarInt(CarpetClient.HELLO).writeUtf(CarpetSettings.carpetVersion) + new CustomPacketPayload() + { + @Override + public void write(final FriendlyByteBuf friendlyByteBuf) + { + friendlyByteBuf.writeVarInt(CarpetClient.HELLO).writeUtf(CarpetSettings.carpetVersion); + } + + @Override + public ResourceLocation id() + { + return CarpetClient.CARPET_CHANNEL; + } + } )); } @@ -162,8 +176,20 @@ public static void clientCommand(String command) CompoundTag outer = new CompoundTag(); outer.put("clientCommand", tag); CarpetClient.getPlayer().connection.send(new ServerboundCustomPayloadPacket( - CarpetClient.CARPET_CHANNEL, - (new FriendlyByteBuf(Unpooled.buffer())).writeVarInt(CarpetClient.DATA).writeNbt(outer) + new CustomPacketPayload() + { + @Override + public void write( FriendlyByteBuf friendlyByteBuf) + { + friendlyByteBuf.writeVarInt(CarpetClient.DATA).writeNbt(outer); + } + + @Override + public ResourceLocation id() + { + return CarpetClient.CARPET_CHANNEL; + } + } )); } } diff --git a/src/main/java/carpet/network/ServerNetworkHandler.java b/src/main/java/carpet/network/ServerNetworkHandler.java index c2cf113d19..9a429ab23b 100644 --- a/src/main/java/carpet/network/ServerNetworkHandler.java +++ b/src/main/java/carpet/network/ServerNetworkHandler.java @@ -4,6 +4,7 @@ import carpet.CarpetSettings; import carpet.api.settings.CarpetRule; import carpet.api.settings.RuleHelper; +import carpet.fakes.CarpetPacketPayload; import carpet.fakes.MinecraftServerInterface; import carpet.fakes.ServerGamePacketListenerImplInterface; import carpet.helpers.ServerTickRateManager; @@ -16,19 +17,39 @@ import java.util.Map; import java.util.Set; import java.util.function.BiConsumer; +import java.util.function.Consumer; + import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; import net.minecraft.nbt.StringTag; import net.minecraft.nbt.Tag; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.chat.Component; -import net.minecraft.network.protocol.game.ClientboundCustomPayloadPacket; +import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; public class ServerNetworkHandler { + @FunctionalInterface + public interface CarpetCustomPayload extends CustomPacketPayload + { + void writeData(FriendlyByteBuf output); + + @Override + default void write(FriendlyByteBuf output) { + writeData(output); + } + + @Override + default ResourceLocation id() + { + return CarpetClient.CARPET_CHANNEL; + } + } private static final Map remoteCarpetPlayers = new HashMap<>(); private static final Set validCarpetPlayers = new HashSet<>(); @@ -52,24 +73,39 @@ public static void handleData(FriendlyByteBuf data, ServerPlayer player) + private static ClientboundCustomPayloadPacket make(Consumer accepter) { + return new ClientboundCustomPayloadPacket( + new CarpetCustomPayload() + { + @Override + public void writeData(final FriendlyByteBuf t) + { + accepter.accept(t); + } + } + ); + } + public static void onPlayerJoin(ServerPlayer playerEntity) { + if (true) return; if (!((ServerGamePacketListenerImplInterface)playerEntity.connection).getConnection().isMemoryConnection()) { - playerEntity.connection.send(new ClientboundCustomPayloadPacket( - CarpetClient.CARPET_CHANNEL, - (new FriendlyByteBuf(Unpooled.buffer())).writeVarInt(CarpetClient.HI).writeUtf(CarpetSettings.carpetVersion) + playerEntity.connection.send( make( output -> { + output.writeVarInt(CarpetClient.HI); + output.writeUtf(CarpetSettings.carpetVersion); + } )); } else { validCarpetPlayers.add(playerEntity); } - } public static void onHello(ServerPlayer playerEntity, FriendlyByteBuf packetData) { + if (true) return; validCarpetPlayers.add(playerEntity); String clientVersion = packetData.readUtf(64); remoteCarpetPlayers.put(playerEntity, clientVersion); @@ -79,13 +115,13 @@ public static void onHello(ServerPlayer playerEntity, FriendlyByteBuf packetData CarpetSettings.LOG.warn("Player "+playerEntity.getName().getString()+" joined with another carpet version: "+clientVersion); DataBuilder data = DataBuilder.create(playerEntity.server); // tickrate related settings are sent on world change CarpetServer.forEachManager(sm -> sm.getCarpetRules().forEach(data::withRule)); - playerEntity.connection.send(new ClientboundCustomPayloadPacket(CarpetClient.CARPET_CHANNEL, data.build() )); + playerEntity.connection.send(make(data::build)); } public static void sendPlayerLevelData(ServerPlayer player, ServerLevel level) { if (CarpetSettings.superSecretSetting || !validCarpetPlayers.contains(player)) return; DataBuilder data = DataBuilder.create(player.server).withTickRate().withFrozenState().withTickPlayerActiveTimeout(); // .withSuperHotState() - player.connection.send(new ClientboundCustomPayloadPacket(CarpetClient.CARPET_CHANNEL, data.build() )); + player.connection.send(make(data::build)); } @@ -113,9 +149,8 @@ private static void handleClientCommand(ServerPlayer player, CompoundTag command ListTag outputResult = new ListTag(); for (Component line: output) outputResult.add(StringTag.valueOf(Component.Serializer.toJson(line))); if (!output.isEmpty()) result.put("output", outputResult); - player.connection.send(new ClientboundCustomPayloadPacket( - CarpetClient.CARPET_CHANNEL, - DataBuilder.create(player.server).withCustomNbt("clientCommand", result).build() + player.connection.send(make( butebuf -> + DataBuilder.create(player.server).withCustomNbt("clientCommand", result).build(butebuf) )); // run command plug to command output, } @@ -139,9 +174,8 @@ public static void updateRuleWithConnectedClients(CarpetRule rule) if (CarpetSettings.superSecretSetting) return; for (ServerPlayer player : remoteCarpetPlayers.keySet()) { - player.connection.send(new ClientboundCustomPayloadPacket( - CarpetClient.CARPET_CHANNEL, - DataBuilder.create(player.server).withRule(rule).build() + player.connection.send(make( output -> + DataBuilder.create(player.server).withRule(rule).build(output) )); } } @@ -151,9 +185,8 @@ public static void updateTickSpeedToConnectedPlayers(MinecraftServer server) if (CarpetSettings.superSecretSetting) return; for (ServerPlayer player : validCarpetPlayers) { - player.connection.send(new ClientboundCustomPayloadPacket( - CarpetClient.CARPET_CHANNEL, - DataBuilder.create(player.server).withTickRate().build() + player.connection.send(make( output -> + DataBuilder.create(player.server).withTickRate().build(output) )); } } @@ -163,9 +196,8 @@ public static void updateFrozenStateToConnectedPlayers(MinecraftServer server) if (CarpetSettings.superSecretSetting) return; for (ServerPlayer player : validCarpetPlayers) { - player.connection.send(new ClientboundCustomPayloadPacket( - CarpetClient.CARPET_CHANNEL, - DataBuilder.create(player.server).withFrozenState().build() + player.connection.send(make( output -> + DataBuilder.create(player.server).withFrozenState().build(output) )); } } @@ -175,9 +207,8 @@ public static void updateSuperHotStateToConnectedPlayers(MinecraftServer server) if(CarpetSettings.superSecretSetting) return; for (ServerPlayer player : validCarpetPlayers) { - player.connection.send(new ClientboundCustomPayloadPacket( - CarpetClient.CARPET_CHANNEL, - DataBuilder.create(player.server).withSuperHotState().build() + player.connection.send(make(output -> + DataBuilder.create(player.server).withSuperHotState().build(output) )); } } @@ -187,9 +218,8 @@ public static void updateTickPlayerActiveTimeoutToConnectedPlayers(MinecraftServ if (CarpetSettings.superSecretSetting) return; for (ServerPlayer player : validCarpetPlayers) { - player.connection.send(new ClientboundCustomPayloadPacket( - CarpetClient.CARPET_CHANNEL, - DataBuilder.create(player.server).withTickPlayerActiveTimeout().build() + player.connection.send(make(output -> + DataBuilder.create(player.server).withTickPlayerActiveTimeout().build(output) )); } } @@ -199,9 +229,8 @@ public static void broadcastCustomCommand(String command, Tag data) if (CarpetSettings.superSecretSetting) return; for (ServerPlayer player : validCarpetPlayers) { - player.connection.send(new ClientboundCustomPayloadPacket( - CarpetClient.CARPET_CHANNEL, - DataBuilder.create(player.server).withCustomNbt(command, data).build() + player.connection.send(make(output -> + DataBuilder.create(player.server).withCustomNbt(command, data).build(output) )); } } @@ -210,9 +239,8 @@ public static void sendCustomCommand(ServerPlayer player, String command, Tag da { if (isValidCarpetPlayer(player)) { - player.connection.send(new ClientboundCustomPayloadPacket( - CarpetClient.CARPET_CHANNEL, - DataBuilder.create(player.server).withCustomNbt(command, data).build() + player.connection.send(make(output -> + DataBuilder.create(player.server).withCustomNbt(command, data).build(output) )); } } @@ -310,12 +338,10 @@ public DataBuilder withCustomNbt(String key, Tag value) return this; } - private FriendlyByteBuf build() + private void build(FriendlyByteBuf packetBuf) { - FriendlyByteBuf packetBuf = new FriendlyByteBuf(Unpooled.buffer()); packetBuf.writeVarInt(CarpetClient.DATA); packetBuf.writeNbt(tag); - return packetBuf; } diff --git a/src/main/java/carpet/patches/EntityPlayerMPFake.java b/src/main/java/carpet/patches/EntityPlayerMPFake.java index 617e718b2f..6c8cb8d885 100644 --- a/src/main/java/carpet/patches/EntityPlayerMPFake.java +++ b/src/main/java/carpet/patches/EntityPlayerMPFake.java @@ -63,12 +63,12 @@ public static EntityPlayerMPFake createFake(String username, MinecraftServer ser if (gameprofile.getProperties().containsKey("textures")) { AtomicReference result = new AtomicReference<>(); - SkullBlockEntity.updateGameprofile(gameprofile, result::set); - gameprofile = result.get(); + //SkullBlockEntity.updateGameprofile(gameprofile, result::set); + //gameprofile = result.get(); } EntityPlayerMPFake instance = new EntityPlayerMPFake(server, worldIn, gameprofile, false); instance.fixStartingPosition = () -> instance.moveTo(pos.x, pos.y, pos.z, (float) yaw, (float) pitch); - server.getPlayerList().placeNewPlayer(new FakeClientConnection(PacketFlow.SERVERBOUND), instance); + server.getPlayerList().placeNewPlayer(new FakeClientConnection(PacketFlow.SERVERBOUND), instance, 0); instance.teleportTo(worldIn, pos.x, pos.y, pos.z, (float) yaw, (float) pitch); instance.setHealth(20.0F); instance.unsetRemoved(); @@ -90,7 +90,7 @@ public static EntityPlayerMPFake createShadow(MinecraftServer server, ServerPlay GameProfile gameprofile = player.getGameProfile(); EntityPlayerMPFake playerShadow = new EntityPlayerMPFake(server, worldIn, gameprofile, true); playerShadow.setChatSession(player.getChatSession()); - server.getPlayerList().placeNewPlayer(new FakeClientConnection(PacketFlow.SERVERBOUND), playerShadow); + server.getPlayerList().placeNewPlayer(new FakeClientConnection(PacketFlow.SERVERBOUND), playerShadow, 0); playerShadow.setHealth(player.getHealth()); playerShadow.connection.teleport(player.getX(), player.getY(), player.getZ(), player.getYRot(), player.getXRot()); diff --git a/src/main/java/carpet/patches/NetHandlerPlayServerFake.java b/src/main/java/carpet/patches/NetHandlerPlayServerFake.java index a8e5b852e7..7eee43fe42 100644 --- a/src/main/java/carpet/patches/NetHandlerPlayServerFake.java +++ b/src/main/java/carpet/patches/NetHandlerPlayServerFake.java @@ -5,15 +5,16 @@ import net.minecraft.network.chat.contents.TranslatableContents; import net.minecraft.network.protocol.Packet; import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.network.ServerGamePacketListenerImpl; import net.minecraft.world.entity.RelativeMovement; import java.util.Set; public class NetHandlerPlayServerFake extends ServerGamePacketListenerImpl { - public NetHandlerPlayServerFake(MinecraftServer server, Connection cc, EntityPlayerMPFake playerIn) + public NetHandlerPlayServerFake(final MinecraftServer minecraftServer, final Connection connection, final ServerPlayer serverPlayer, final int i) { - super(server, cc, playerIn); + super(minecraftServer, connection, serverPlayer, i); } @Override diff --git a/src/main/java/carpet/script/api/Scoreboards.java b/src/main/java/carpet/script/api/Scoreboards.java index dd275e72b5..293e4c245e 100644 --- a/src/main/java/carpet/script/api/Scoreboards.java +++ b/src/main/java/carpet/script/api/Scoreboards.java @@ -61,7 +61,7 @@ public static void apply(Expression expression) return ListValue.wrap(scoreboard.getObjectiveNames().stream().map(StringValue::new)); } String objectiveName = lv.get(0).getString(); - Objective objective = scoreboard.getOrCreateObjective(objectiveName); + Objective objective = scoreboard.getObjective(objectiveName); if (objective == null) { return Value.NULL; @@ -103,7 +103,7 @@ public static void apply(Expression expression) CarpetContext cc = (CarpetContext) c; Scoreboard scoreboard = cc.server().getScoreboard(); String objectiveName = lv.get(0).getString(); - Objective objective = scoreboard.getOrCreateObjective(objectiveName); + Objective objective = scoreboard.getObjective(objectiveName); if (objective == null) { return Value.FALSE; @@ -151,7 +151,7 @@ public static void apply(Expression expression) } } - Objective objective = scoreboard.getOrCreateObjective(objectiveName); + Objective objective = scoreboard.getObjective(objectiveName); if (objective != null) { c.host.issueDeprecation("reading or modifying an objective's criterion with scoreboard_add"); @@ -181,7 +181,7 @@ public static void apply(Expression expression) } CarpetContext cc = (CarpetContext) c; Scoreboard scoreboard = cc.server().getScoreboard(); - Objective objective = scoreboard.getOrCreateObjective(lv.get(0).getString()); + Objective objective = scoreboard.getObjective(lv.get(0).getString()); if (objective == null) { return Value.NULL; @@ -225,7 +225,7 @@ public static void apply(Expression expression) } return new FormattedTextValue(objective.getDisplayName()); } - case "display_slot" -> { + case "display_slot" -> { /* if (modify) { int slotId = Scoreboard.getDisplaySlotByName(setValue.getString()); @@ -249,7 +249,8 @@ public static void apply(Expression expression) slots.add(StringValue.of(slotName)); } } - return ListValue.wrap(slots); + return ListValue.wrap(slots); */ + return Value.NULL; } case "render_type" -> { if (modify) @@ -269,7 +270,7 @@ public static void apply(Expression expression) }); expression.addContextFunction("scoreboard_display", 2, (c, t, lv) -> - { + { /* CarpetContext cc = (CarpetContext) c; Scoreboard scoreboard = cc.server().getScoreboard(); String location = lv.get(0).getString(); @@ -291,7 +292,8 @@ public static void apply(Expression expression) return Value.NULL; } scoreboard.setDisplayObjective(slot, objective); - return new NumericValue(slot); + return new NumericValue(slot); */ + return Value.NULL; }); expression.addContextFunction("team_list", -1, (c, t, lv) -> diff --git a/src/main/java/carpet/script/command/CommandArgument.java b/src/main/java/carpet/script/command/CommandArgument.java index 93276819fd..24f091604c 100644 --- a/src/main/java/carpet/script/command/CommandArgument.java +++ b/src/main/java/carpet/script/command/CommandArgument.java @@ -258,9 +258,9 @@ public static CommandSyntaxException error(String text) true ), new ScoreholderArgument(), - new VanillaUnconfigurableArgument("scoreboardslot", ScoreboardSlotArgument::displaySlot, - (c, p) -> StringValue.of(Scoreboard.getDisplaySlotName(ScoreboardSlotArgument.getDisplaySlot(c, p))), false - ), + //new VanillaUnconfigurableArgument("scoreboardslot", ScoreboardSlotArgument::displaySlot, + // (c, p) -> StringValue.of(Scoreboard.getDisplaySlotName(ScoreboardSlotArgument.getDisplaySlot(c, p))), false + //), new VanillaUnconfigurableArgument("swizzle", SwizzleArgument::swizzle, (c, p) -> StringValue.of(SwizzleArgument.getSwizzle(c, p).stream().map(Direction.Axis::getSerializedName).collect(Collectors.joining())), true ), diff --git a/src/main/java/carpet/script/value/EntityValue.java b/src/main/java/carpet/script/value/EntityValue.java index 24565a1dd7..140c30e639 100644 --- a/src/main/java/carpet/script/value/EntityValue.java +++ b/src/main/java/carpet/script/value/EntityValue.java @@ -633,7 +633,7 @@ public Value get(String what, @Nullable Value arg) put("client_brand", (e, a) -> e instanceof final ServerPlayer sp ? StringValue.of(Carpet.getPlayerStatus(sp)) : Value.NULL); put("team", (e, a) -> e.getTeam() == null ? Value.NULL : new StringValue(e.getTeam().getName())); - put("ping", (e, a) -> e instanceof final ServerPlayer sp ? new NumericValue(sp.latency) : Value.NULL); + put("ping", (e, a) -> e instanceof final ServerPlayer sp ? new NumericValue(sp.connection.latency()) : Value.NULL); //spectating_entity // isGlowing diff --git a/src/main/resources/carpet.mixins.json b/src/main/resources/carpet.mixins.json index 72dc63924c..f9daa6206f 100644 --- a/src/main/resources/carpet.mixins.json +++ b/src/main/resources/carpet.mixins.json @@ -181,7 +181,11 @@ "BlockBehaviourBlockStateBase_mixin", "ChainBlock_customStickyMixin", "ChestBlock_customStickyMixin", - "PistonStructureResolver_customStickyMixin" + "PistonStructureResolver_customStickyMixin", + + "ServerboundCustomPayloadPacket_mixin", + "ServerCommonPacketListenerimpl_connectionMixin", + "ClientboundCustomPayloadPacket_customPacketMixin" ], "client": [ @@ -200,7 +204,10 @@ "LevelRenderer_creativeNoClipMixin", "ClientPacketListener_customPacketsMixin", "DebugRenderer_scarpetRenderMixin", - "LevelRenderer_scarpetRenderMixin" + "LevelRenderer_scarpetRenderMixin", + + + "ClientCommonPacketListenerImpl_customPacketMixin" ], "injectors": { "defaultRequire": 1 From 4546b98cd39e26ddfe4d7768255bf73e53e25cbe Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Thu, 3 Aug 2023 10:59:34 +0000 Subject: [PATCH 190/233] Merge docs for 'Carpet Mod 1.4.113 for Minecraft 23w31a' --- docs/scarpet/Full.md | 65 +++++++++++++++++++++++++++++++------------- 1 file changed, 46 insertions(+), 19 deletions(-) diff --git a/docs/scarpet/Full.md b/docs/scarpet/Full.md index 77dc35af73..9f70764636 100644 --- a/docs/scarpet/Full.md +++ b/docs/scarpet/Full.md @@ -633,13 +633,13 @@ only take integer values, so if the input has a decimal part, it will be discard - `bitwise_xor(...)` -> Does the bitwise XOR operation on each number in order. - `bitwise_or(...)` -> Does the bitwise AND operation on each number in order. Note that with larger ranges of numbers this will tend to -1. - - `bitwise_shift_left(num, amount)` -> Shifts all the bits of the first number `amount` spots to the left. Note that shifting more - than 63 positions will result in a 0 (cos you shift out all the bits of the number) + - `bitwise_shift_left(num, amount)` -> Shifts all the bits of the first number `amount` spots to the left. Note that only the 6 + lowest-order bits of the amount are considered. - `bitwise_shift_right(num, amount)` -> Shifts all the bits of the first number `amount` spots to the right logically. That is, the - `amount` most significant bits will always be set to 0. Like with the above, shifting more than 63 bits results in a 0. + `amount` most significant bits will always be set to 0. Like with the above, only the 6 lowest-order bits of the amount are considered. - `bitwise_arithmetic_shift_right(num, amount)` -> Shifts all the bits of the first number `amount` spots to the right arithmetically. That is, if the most significant (sign) bit is a 1, it'll propagate the one to the `amount` most significant bits. Like with the above, - shifting more than 63 bits results in a 0. + only the 6 lowest-order bits of the amount are considered. - `bitwise_roll_left(num, amount)` -> Rolls the bits of the first number `amount` bits to the left. This is basically where you shift out the first `amount` bits and then add them on at the back, essentially 'rolling' the number. Note that unlike with shifting, you can roll more than 63 bits at a time, as it just makes the number roll over more times, which isn't an issue @@ -2570,9 +2570,10 @@ If called with no args, returns `'clear'`, `'rain` or `'thunder'` based on the c always return `'thunder'`, if not will return `'rain'` or `'clear'` based on the current weather. With one arg, (either `'clear'`, `'rain` or `'thunder'`), returns the number of remaining ticks for that weather type. -NB: It can thunder without there being a thunderstorm, there has to be both rain and thunder to form a storm. +NB: It can thunder without there being a thunderstorm; there has to be both rain and thunder to form a storm. So if +running `weather()` returns `'thunder'`, you can use `weather('rain')>0` to see if there's a storm going on. -With two args, sets the weather to `type` for `ticks` ticks. +With two args, sets the weather to the given `type` for `ticks` ticks. ## Block and World querying @@ -2621,6 +2622,7 @@ back in state definition in various applications where block properties are requ Throws `unknown_block` if the provided input is not valid.
      +set(x,y,z,'iron_block'); block_state(x,y,z)  => {}
       set(x,y,z,'iron_trapdoor','half','top'); block_state(x,y,z)  => {waterlogged: false, half: top, open: false, ...}
       set(x,y,z,'iron_trapdoor','half','top'); block_state(x,y,z,'half')  => top
       block_state('iron_trapdoor','half')  => top
      @@ -2632,7 +2634,14 @@ bool(block_state(block('iron_trapdoor[half=top]'),'powered'))  => 0
       
       ### `block_list()`, `block_list(tag)`
       
      -Returns list of all blocks. If tag is provided, returns list of blocks that belong to this block tag.
      +Returns list of all blocks in the game. If `tag` is provided, returns list of all blocks that belong to this block tag.
      +
      +block_list() => [dark_oak_button, wall_torch, structure_block, polished_blackstone_brick_slab, cherry_sapling... ]
      +block_list('impermeable') => [glass, white_stained_glass, orange_stained_glass, magenta_stained_glass... ] //All da glass
      +block_list('rails') => [rail, powered_rail, detector_rail, activator_rail]
      +block_list('not_a_valid_block_tag') => null //Not a valid block tag
      +
      + ### `block_tags()`, `block_tags(block)`, `block_tags(block, tag)` @@ -2642,12 +2651,21 @@ to this tag, and `true` if the block belongs to the tag. Throws `unknown_block` if `block` doesn't exist +
      +block_tags() => [geode_invalid_blocks, wall_post_override, ice, wooden_stairs, bamboo_blocks, stone_bricks... ]
      +block_tags('iron_block') => [mineable/pickaxe, needs_stone_tool, beacon_base_blocks]
      +block_tags('glass') => [impermeable]
      +block_tags('glass', 'impermeable') => true
      +block_tags('glass', 'beacon_base_blocks') => false
      +
      + ### `block_data(pos)` Return NBT string associated with specific location, or null if the block does not carry block data. Can be currently used to match specific information from it, or use it to copy to another block -
          block_data(x,y,z) => '{TransferCooldown:0,x:450,y:68, ... }'
      +
      +block_data(x,y,z) => '{TransferCooldown:0,x:450,y:68, ... }'
       
      ### `poi(pos), poi(pos, radius?, type?, status?, column_search?)` @@ -3150,13 +3168,15 @@ These functions help scan larger areas of blocks without using generic loop func Evaluates expression over area of blocks defined by its center `center = (cx, cy, cz)`, expanded in all directions by `range = (dx, dy, dz)` blocks, or optionally in negative with `range` coords, and `upper_range` coords in -positive values, so you can use that if you know the lower coord, and dimension by calling `'scan(center, 0, 0, 0, w, h, d, ...)`. +positive values. That means that if you want a box starting at the northwest coord with given base, width and height +dimensions, you can do `'scan(center, 0, 0, 0, w, h, d, ...)`. `center` can be defined either as three coordinates, a single tuple of three coords, or a block value. -`range` and `upper_range` can have the same representations, just if they are block values, it computes the distance to the center -as range instead of taking the values as is. +`range` and `upper_range` can have the same representations, just if they are block values, it computes the distance to +the center as range instead of taking the values as is. That way you can iterate from the center to a box whose surface +area constains the `range` and/or `upper_range` blocks. -`expr` receives `_x, _y, _z` as coords of current analyzed block and `_`, which represents the block itself. +`expr` receives `_x, _y, _z` variables as coords of current analyzed block and `_`, which represents the block itself. Returns number of successful evaluations of `expr` (with `true` boolean result) unless called in void context, which would cause the expression not be evaluated for their boolean value. @@ -3180,22 +3200,29 @@ Returns the list of 6 neighbouring blocks to the argument. Commonly used with ot for(neighbours(x,y,z),air(_)) => 4 // number of air blocks around a block
      -### `rect(centre, range?, upper_range?)` +### `rect(center, range?, upper_range?)` Returns an iterator, just like `range` function that iterates over a rectangular area of blocks. If only center -point is specified, it iterates over 27 blocks. If `range` arguments are specified, expands selection by the respective -number of blocks in each direction. If `positive_range` arguments are specified, - it uses `range` for negative offset, and `positive_range` for positive. +point is specified, it iterates over 27 blocks (range of 1). If `range` arguments are specified, expands selection by +the respective number of blocks in each direction. If `upper_range` arguments are specified, it uses `range` for +negative offset, and `upper_range` for positive, similar to `scan`. + +Basically the arguments are the same as the first three arguments of `scan`, except this function returns the list of +blocks that `scan` would evaluate over. If you are going to iterate over these blocks, like `for(rect(args), do_something())`, +then `scan(args, do_something())` is an equivalent, yet more compute-friendly alternative, especially for very large areas. -`centre` can be defined either as three coordinates, a list of three coords, or a block value. -`range` and `positive_range` can have the same representations, just if they are block values, it computes the distance to the center +`center` can be defined either as three coordinates, a list of three coords, or a block value. +`range` and `upper_range` can have the same representations, just if they are block values, it computes the distance to the center as range instead of taking the values as is.` -### `diamond(centre_pos, radius?, height?)` +### `diamond(center_pos, radius?, height?)` Iterates over a diamond like area of blocks. With no radius and height, its 7 blocks centered around the middle (block + neighbours). With a radius specified, it expands shape on x and z coords, and with a custom height, on y. Any of these can be zero as well. radius of 0 makes a stick, height of 0 makes a diamond shape pad. + +If radius and height are the same, creats a 3D diamond, of all the blocks which are a manhattan distance of `radius` away +from the center. # Entity API ## Entity Selection From 60e6dcd633c15720b7badc4698812cd3917e2040 Mon Sep 17 00:00:00 2001 From: Ghoulboy Date: Thu, 3 Aug 2023 13:45:06 +0200 Subject: [PATCH 191/233] Improve docs for `create_explosion()` (#1764) * Update incorrect docs for `create_explosion()` * Added descriptions of arguments, instead of just defaults --- docs/scarpet/api/BlocksAndWorldAccess.md | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/docs/scarpet/api/BlocksAndWorldAccess.md b/docs/scarpet/api/BlocksAndWorldAccess.md index 70c266a92f..d3f3c10a81 100644 --- a/docs/scarpet/api/BlocksAndWorldAccess.md +++ b/docs/scarpet/api/BlocksAndWorldAccess.md @@ -230,10 +230,14 @@ that block, a block doesn't get destroyed either. ### `create_explosion(pos, power?, mode?, fire?, source?, attacker?)` -Creates an explosion at a given position. Default values of optional parameters are: `'power'` - `4` (TNT power), -`'mode'` (block breaking effect `none`, `destroy` or `break`: `break`, `fire` (whether extra fire blocks should be created) - `false`, -`source` (exploding entity) - `null` and `attacker` (entity responsible for trigerring) - `null`. Explosions created with this -endpoint cannot be captured with `__on_explosion` event, however they will be captured by `__on_explosion_outcome`. +Creates an explosion at a given position. Parameters work as follows: + - `'power'` - how strong the blast is, negative values count as 0 (default: `4` (TNT power)) + - `'mode'` - how to deal with broken blocks: `keep` keeps them, `destroy` destroys them and drops items, and `destroy_with_decay` destroys them, but doesn't always drop the items (default: `destroy_with_decay`) + - `fire` - whether extra fire blocks should be created (default: `false`) + - `source` - entity that is exploding. Note that it will not take explosion damage from this explosion (default: `null`) + - `attacker` - entity responsible for triggering, this will be displayed in death messages, and count towards kill counts, and can be damaged by the explosion (default: `null`) +Explosions created with this endpoint cannot be captured with `__on_explosion` event, however they will be captured +by `__on_explosion_outcome`. ### `weather()`,`weather(type)`,`weather(type, ticks)` From cd37140b85639e3ce5027c5802dfa573e1ecf341 Mon Sep 17 00:00:00 2001 From: silnarm Date: Fri, 4 Aug 2023 21:52:00 +1000 Subject: [PATCH 192/233] fix-bots-for-new-networky-bits * override and no-op setListener() in FakeClientConnection * fixes error spawning bots. --- src/main/java/carpet/patches/FakeClientConnection.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/main/java/carpet/patches/FakeClientConnection.java b/src/main/java/carpet/patches/FakeClientConnection.java index bb9e9ea84e..5a7f8bafab 100644 --- a/src/main/java/carpet/patches/FakeClientConnection.java +++ b/src/main/java/carpet/patches/FakeClientConnection.java @@ -3,6 +3,7 @@ import carpet.fakes.ClientConnectionInterface; import io.netty.channel.embedded.EmbeddedChannel; import net.minecraft.network.Connection; +import net.minecraft.network.PacketListener; import net.minecraft.network.protocol.PacketFlow; public class FakeClientConnection extends Connection @@ -24,4 +25,9 @@ public void setReadOnly() public void handleDisconnection() { } + + @Override + public void setListener(PacketListener packetListener) + { + } } \ No newline at end of file From 08c5c3db31626e7df2188f96bae4e192dc7c6e93 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Mon, 7 Aug 2023 20:04:40 +0200 Subject: [PATCH 193/233] fix player skins not showing properly --- .../java/carpet/commands/PlayerCommand.java | 7 +-- .../carpet/patches/EntityPlayerMPFake.java | 53 +++++++++++-------- src/main/resources/carpet.accesswidener | 3 ++ 3 files changed, 35 insertions(+), 28 deletions(-) diff --git a/src/main/java/carpet/commands/PlayerCommand.java b/src/main/java/carpet/commands/PlayerCommand.java index 9cfbd1ec16..6bbde95552 100644 --- a/src/main/java/carpet/commands/PlayerCommand.java +++ b/src/main/java/carpet/commands/PlayerCommand.java @@ -293,13 +293,10 @@ private static int spawn(CommandContext context) throws Comm Messenger.m(source, "rb Player " + playerName + " cannot be placed outside of the world"); return 0; } - Player player = EntityPlayerMPFake.createFake(playerName, source.getServer(), pos, facing.y, facing.x, dimType, mode, flying); - if (player == null) - { + EntityPlayerMPFake.createFake(playerName, source.getServer(), pos, facing.y, facing.x, dimType, mode, flying, () -> { Messenger.m(source, "rb Player " + playerName + " doesn't exist and cannot spawn in online mode. " + "Turn the server offline to spawn non-existing players"); - return 0; - } + }); return 1; } diff --git a/src/main/java/carpet/patches/EntityPlayerMPFake.java b/src/main/java/carpet/patches/EntityPlayerMPFake.java index 6c8cb8d885..db02223034 100644 --- a/src/main/java/carpet/patches/EntityPlayerMPFake.java +++ b/src/main/java/carpet/patches/EntityPlayerMPFake.java @@ -31,7 +31,8 @@ import carpet.fakes.ServerPlayerInterface; import carpet.utils.Messenger; -import java.util.concurrent.atomic.AtomicReference; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; @SuppressWarnings("EntityConstructor") public class EntityPlayerMPFake extends ServerPlayer @@ -39,7 +40,7 @@ public class EntityPlayerMPFake extends ServerPlayer public Runnable fixStartingPosition = () -> {}; public boolean isAShadow; - public static EntityPlayerMPFake createFake(String username, MinecraftServer server, Vec3 pos, double yaw, double pitch, ResourceKey dimensionId, GameType gamemode, boolean flying) + public static void createFake(String username, MinecraftServer server, Vec3 pos, double yaw, double pitch, ResourceKey dimensionId, GameType gamemode, boolean flying, Runnable onError) { //prolly half of that crap is not necessary, but it works ServerLevel worldIn = server.getLevel(dimensionId); @@ -55,31 +56,37 @@ public static EntityPlayerMPFake createFake(String username, MinecraftServer ser { if (!CarpetSettings.allowSpawningOfflinePlayers) { - return null; + onError.run(); + return; } else { gameprofile = new GameProfile(UUIDUtil.createOfflinePlayerUUID(username), username); } } - if (gameprofile.getProperties().containsKey("textures")) - { - AtomicReference result = new AtomicReference<>(); - //SkullBlockEntity.updateGameprofile(gameprofile, result::set); - //gameprofile = result.get(); - } - EntityPlayerMPFake instance = new EntityPlayerMPFake(server, worldIn, gameprofile, false); - instance.fixStartingPosition = () -> instance.moveTo(pos.x, pos.y, pos.z, (float) yaw, (float) pitch); - server.getPlayerList().placeNewPlayer(new FakeClientConnection(PacketFlow.SERVERBOUND), instance, 0); - instance.teleportTo(worldIn, pos.x, pos.y, pos.z, (float) yaw, (float) pitch); - instance.setHealth(20.0F); - instance.unsetRemoved(); - instance.setMaxUpStep(0.6F); - instance.gameMode.changeGameModeForPlayer(gamemode); - server.getPlayerList().broadcastAll(new ClientboundRotateHeadPacket(instance, (byte) (instance.yHeadRot * 256 / 360)), dimensionId);//instance.dimension); - server.getPlayerList().broadcastAll(new ClientboundTeleportEntityPacket(instance), dimensionId);//instance.dimension); - //instance.world.getChunkManager(). updatePosition(instance); - instance.entityData.set(DATA_PLAYER_MODE_CUSTOMISATION, (byte) 0x7f); // show all model layers (incl. capes) - instance.getAbilities().flying = flying; - return instance; + GameProfile finalGP = gameprofile; + fetchGameProfile(gameprofile.getName()).thenAccept(p -> { + GameProfile current = finalGP; + if (p.isPresent()) + { + current = p.get(); + } + EntityPlayerMPFake instance = new EntityPlayerMPFake(server, worldIn, current, false); + instance.fixStartingPosition = () -> instance.moveTo(pos.x, pos.y, pos.z, (float) yaw, (float) pitch); + server.getPlayerList().placeNewPlayer(new FakeClientConnection(PacketFlow.SERVERBOUND), instance, 0); + instance.teleportTo(worldIn, pos.x, pos.y, pos.z, (float) yaw, (float) pitch); + instance.setHealth(20.0F); + instance.unsetRemoved(); + instance.setMaxUpStep(0.6F); + instance.gameMode.changeGameModeForPlayer(gamemode); + server.getPlayerList().broadcastAll(new ClientboundRotateHeadPacket(instance, (byte) (instance.yHeadRot * 256 / 360)), dimensionId);//instance.dimension); + server.getPlayerList().broadcastAll(new ClientboundTeleportEntityPacket(instance), dimensionId);//instance.dimension); + //instance.world.getChunkManager(). updatePosition(instance); + instance.entityData.set(DATA_PLAYER_MODE_CUSTOMISATION, (byte) 0x7f); // show all model layers (incl. capes) + instance.getAbilities().flying = flying; + }); + } + + private static CompletableFuture> fetchGameProfile(final String name) { + return SkullBlockEntity.fetchGameProfile(name); } public static EntityPlayerMPFake createShadow(MinecraftServer server, ServerPlayer player) diff --git a/src/main/resources/carpet.accesswidener b/src/main/resources/carpet.accesswidener index ebfed8ee50..8aa2dafeaf 100644 --- a/src/main/resources/carpet.accesswidener +++ b/src/main/resources/carpet.accesswidener @@ -10,8 +10,11 @@ accessible class net/minecraft/server/MinecraftServer$ReloadableResources accessible class net/minecraft/world/level/biome/Biome$ClimateSettings accessible class net/minecraft/world/level/block/entity/SculkSensorBlockEntity$VibrationUser +#TODO fields and methods should be fetched via interfaces unless there is a good reason not to accessible method net/minecraft/world/level/border/WorldBorder getListeners ()Ljava/util/List; accessible method net/minecraft/server/level/DistanceManager purgeStaleTickets ()V +#cause I don't want to deal with the interfaces until stuff is stable +accessible method net/minecraft/world/level/block/entity/SkullBlockEntity fetchGameProfile (Ljava/lang/String;)Ljava/util/concurrent/CompletableFuture; accessible field net/minecraft/world/level/block/state/BlockBehaviour UPDATE_SHAPE_ORDER [Lnet/minecraft/core/Direction; From 7a19bbe997c82e5937b1a3184580ecd912f3398e Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Tue, 8 Aug 2023 11:59:50 +0200 Subject: [PATCH 194/233] fix client communication for carpet --- .../carpet/fakes/CarpetPacketPayload.java | 11 -- ...ientPacketListener_customPacketsMixin.java | 21 ++-- ...CustomPayloadPacket_customPacketMixin.java | 15 +-- ...monPacketListenerimpl_connectionMixin.java | 8 +- .../ServerboundCustomPayloadPacket_mixin.java | 32 +---- .../java/carpet/network/CarpetClient.java | 13 +- .../carpet/network/ClientNetworkHandler.java | 54 ++------ .../carpet/network/ServerNetworkHandler.java | 117 +++++------------- 8 files changed, 70 insertions(+), 201 deletions(-) delete mode 100644 src/main/java/carpet/fakes/CarpetPacketPayload.java diff --git a/src/main/java/carpet/fakes/CarpetPacketPayload.java b/src/main/java/carpet/fakes/CarpetPacketPayload.java deleted file mode 100644 index d157675909..0000000000 --- a/src/main/java/carpet/fakes/CarpetPacketPayload.java +++ /dev/null @@ -1,11 +0,0 @@ -package carpet.fakes; - -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.network.protocol.common.custom.CustomPacketPayload; -import net.minecraft.network.protocol.common.custom.DiscardedPayload; -import net.minecraft.resources.ResourceLocation; - -public interface CarpetPacketPayload extends CustomPacketPayload -{ - FriendlyByteBuf data(); -} diff --git a/src/main/java/carpet/mixins/ClientPacketListener_customPacketsMixin.java b/src/main/java/carpet/mixins/ClientPacketListener_customPacketsMixin.java index d159ba3072..aec33e928f 100644 --- a/src/main/java/carpet/mixins/ClientPacketListener_customPacketsMixin.java +++ b/src/main/java/carpet/mixins/ClientPacketListener_customPacketsMixin.java @@ -7,21 +7,12 @@ import net.minecraft.client.multiplayer.ClientPacketListener; import net.minecraft.client.multiplayer.CommonListenerCookie; import net.minecraft.network.Connection; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.network.chat.Component; -import net.minecraft.network.protocol.common.ClientCommonPacketListener; -import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket; import net.minecraft.network.protocol.common.custom.CustomPacketPayload; -import net.minecraft.network.protocol.common.custom.DiscardedPayload; import net.minecraft.network.protocol.game.ClientboundLoginPacket; -import net.minecraft.resources.ResourceLocation; -import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(ClientPacketListener.class) public abstract class ClientPacketListener_customPacketsMixin extends ClientCommonPacketListenerImpl @@ -38,4 +29,16 @@ private void onGameJoined(ClientboundLoginPacket packet, CallbackInfo info) CarpetClient.gameJoined( minecraft.player); } + @Inject(method = "handleUnknownCustomPayload", at = @At( + value = "HEAD" + ), cancellable = true) + private void onOnCustomPayload(CustomPacketPayload packet, CallbackInfo ci) + { + if (packet instanceof CarpetClient.CarpetPayload cpp) + { + ClientNetworkHandler.handleData(cpp, minecraft.player); + ci.cancel(); + } + } + } diff --git a/src/main/java/carpet/mixins/ClientboundCustomPayloadPacket_customPacketMixin.java b/src/main/java/carpet/mixins/ClientboundCustomPayloadPacket_customPacketMixin.java index bb2f41e7f0..22d99c39b6 100644 --- a/src/main/java/carpet/mixins/ClientboundCustomPayloadPacket_customPacketMixin.java +++ b/src/main/java/carpet/mixins/ClientboundCustomPayloadPacket_customPacketMixin.java @@ -17,19 +17,12 @@ @Mixin(ClientboundCustomPayloadPacket.class) public class ClientboundCustomPayloadPacket_customPacketMixin { - @Inject(method = "readPayload", at = @At("HEAD")) - private static void onOnCustomPayloadR(final ResourceLocation resourceLocation, final FriendlyByteBuf friendlyByteBuf, final CallbackInfoReturnable cir) + @Inject(method = "readUnknownPayload", at = @At("HEAD"), cancellable = true) + private static void onOnCustomPayloadR(ResourceLocation resourceLocation, FriendlyByteBuf friendlyByteBuf, CallbackInfoReturnable cir) { - } - - @Inject(method = "readUnknownPayload", at = @At(value = "HEAD"), cancellable = true) - private static void onOnCustomPayload(ResourceLocation resourceLocation, FriendlyByteBuf friendlyByteBuf, CallbackInfoReturnable cir) - { - if (true) return; - if (CarpetClient.CARPET_CHANNEL.equals(resourceLocation) && Minecraft.getInstance().isSameThread()) + if (resourceLocation.equals(CarpetClient.CARPET_CHANNEL)) { - ClientNetworkHandler.handleData(friendlyByteBuf, Minecraft.getInstance().player); - cir.setReturnValue(new DiscardedPayload(resourceLocation)); + cir.setReturnValue(new CarpetClient.CarpetPayload(friendlyByteBuf)); } } } diff --git a/src/main/java/carpet/mixins/ServerCommonPacketListenerimpl_connectionMixin.java b/src/main/java/carpet/mixins/ServerCommonPacketListenerimpl_connectionMixin.java index b606e0b3d8..ed179aa338 100644 --- a/src/main/java/carpet/mixins/ServerCommonPacketListenerimpl_connectionMixin.java +++ b/src/main/java/carpet/mixins/ServerCommonPacketListenerimpl_connectionMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.fakes.CarpetPacketPayload; +import carpet.network.CarpetClient; import carpet.network.ServerNetworkHandler; import net.minecraft.network.protocol.PacketUtils; import net.minecraft.network.protocol.common.ServerboundCustomPayloadPacket; @@ -18,16 +18,14 @@ public class ServerCommonPacketListenerimpl_connectionMixin @Inject(method = "handleCustomPayload", at = @At("HEAD"), cancellable = true) private void onCustomCarpetPayload(ServerboundCustomPayloadPacket serverboundCustomPayloadPacket, CallbackInfo ci) { - if (true) return; Object thiss = this; - if (thiss instanceof ServerGamePacketListenerImpl impl && serverboundCustomPayloadPacket.payload() instanceof CarpetPacketPayload cpp) { + if (thiss instanceof ServerGamePacketListenerImpl impl && serverboundCustomPayloadPacket.payload() instanceof CarpetClient.CarpetPayload cpp) { // We should force onto the main thread here // ServerNetworkHandler.handleData can possibly mutate data that isn't // thread safe, and also allows for client commands to be executed PacketUtils.ensureRunningOnSameThread(serverboundCustomPayloadPacket, (ServerGamePacketListener) this, impl.player.serverLevel()); - ServerNetworkHandler.handleData(cpp.data(), impl.player); + ServerNetworkHandler.handleData(cpp, impl.player); ci.cancel(); } - ci.cancel(); } } diff --git a/src/main/java/carpet/mixins/ServerboundCustomPayloadPacket_mixin.java b/src/main/java/carpet/mixins/ServerboundCustomPayloadPacket_mixin.java index a7a1301d7e..d8abb5033e 100644 --- a/src/main/java/carpet/mixins/ServerboundCustomPayloadPacket_mixin.java +++ b/src/main/java/carpet/mixins/ServerboundCustomPayloadPacket_mixin.java @@ -1,13 +1,9 @@ package carpet.mixins; -import carpet.fakes.CarpetPacketPayload; import carpet.network.CarpetClient; -import carpet.network.ClientNetworkHandler; -import net.minecraft.client.Minecraft; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.protocol.common.ServerboundCustomPayloadPacket; import net.minecraft.network.protocol.common.custom.CustomPacketPayload; -import net.minecraft.network.protocol.common.custom.DiscardedPayload; import net.minecraft.resources.ResourceLocation; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; @@ -17,36 +13,12 @@ @Mixin(ServerboundCustomPayloadPacket.class) public class ServerboundCustomPayloadPacket_mixin { - @Inject(method = "readPayload", at = @At( - value = "INVOKE", - target = "Lnet/minecraft/network/protocol/common/ServerboundCustomPayloadPacket;readUnknownPayload(Lnet/minecraft/resources/ResourceLocation;Lnet/minecraft/network/FriendlyByteBuf;)Lnet/minecraft/network/protocol/common/custom/DiscardedPayload;" - ), cancellable = true) + @Inject(method = "readUnknownPayload", at = @At(value = "HEAD"), cancellable = true) private static void onOnCustomPayload(ResourceLocation resourceLocation, FriendlyByteBuf friendlyByteBuf, CallbackInfoReturnable cir) { - if (true) return; if (CarpetClient.CARPET_CHANNEL.equals(resourceLocation)) { - //ClientNetworkHandler.handleData(friendlyByteBuf, Minecraft.getInstance().player); - cir.setReturnValue(new CarpetPacketPayload() - { - @Override - public FriendlyByteBuf data() - { - return friendlyByteBuf; - } - - @Override - public void write(final FriendlyByteBuf friendlyByteBuf) - { - // noop - its a client side and we handle it server side only - } - - @Override - public ResourceLocation id() - { - return resourceLocation; - } - }); + cir.setReturnValue(new CarpetClient.CarpetPayload(friendlyByteBuf)); } } } diff --git a/src/main/java/carpet/network/CarpetClient.java b/src/main/java/carpet/network/CarpetClient.java index 8b268c4ea3..9a2c411418 100644 --- a/src/main/java/carpet/network/CarpetClient.java +++ b/src/main/java/carpet/network/CarpetClient.java @@ -14,22 +14,21 @@ public class CarpetClient { - public record CarpetPayload(CompoundTag data) implements CustomPacketPayload + public record CarpetPayload(int command, CompoundTag data) implements CustomPacketPayload { - public static final ResourceLocation ID = CARPET_CHANNEL; - - public CarpetPayload(final FriendlyByteBuf input) { - this(input.readNbt()); + public CarpetPayload(FriendlyByteBuf input) { + this(input.readInt(), input.readNbt()); } @Override - public void write(final FriendlyByteBuf output) { + public void write(FriendlyByteBuf output) { + output.writeInt(command); output.writeNbt(data); } @Override public ResourceLocation id() { - return ID; + return CARPET_CHANNEL; } } diff --git a/src/main/java/carpet/network/ClientNetworkHandler.java b/src/main/java/carpet/network/ClientNetworkHandler.java index 6b8ed288cf..960463b09b 100644 --- a/src/main/java/carpet/network/ClientNetworkHandler.java +++ b/src/main/java/carpet/network/ClientNetworkHandler.java @@ -99,22 +99,18 @@ public class ClientNetworkHandler }; // Ran on the Main Minecraft Thread - public static void handleData(FriendlyByteBuf data, LocalPlayer player) + public static void handleData(CarpetClient.CarpetPayload data, LocalPlayer player) { - if (data != null) - { - int id = data.readVarInt(); - if (id == CarpetClient.HI) - onHi(data); - if (id == CarpetClient.DATA) - onSyncData(data, player); - } + if (data.command() == CarpetClient.HI) + onHi(data.data()); + if (data.command() == CarpetClient.DATA) + onSyncData(data.data(), player); } - private static void onHi(FriendlyByteBuf data) + private static void onHi(CompoundTag data) { CarpetClient.setCarpet(); - CarpetClient.serverCarpetVersion = data.readUtf(64); + CarpetClient.serverCarpetVersion = data.getString("version"); if (CarpetSettings.carpetVersion.equals(CarpetClient.serverCarpetVersion)) { CarpetSettings.LOG.info("Joined carpet server with matching carpet version"); @@ -130,28 +126,15 @@ private static void onHi(FriendlyByteBuf data) public static void respondHello() { + CompoundTag data = new CompoundTag(); + data.putString("version", CarpetSettings.carpetVersion); CarpetClient.getPlayer().connection.send(new ServerboundCustomPayloadPacket( - new CustomPacketPayload() - { - @Override - public void write(final FriendlyByteBuf friendlyByteBuf) - { - friendlyByteBuf.writeVarInt(CarpetClient.HELLO).writeUtf(CarpetSettings.carpetVersion); - } - - @Override - public ResourceLocation id() - { - return CarpetClient.CARPET_CHANNEL; - } - } + new CarpetClient.CarpetPayload(CarpetClient.HELLO, data) )); } - private static void onSyncData(FriendlyByteBuf data, LocalPlayer player) + private static void onSyncData(CompoundTag compound, LocalPlayer player) { - CompoundTag compound = data.readNbt(); - if (compound == null) return; for (String key: compound.getAllKeys()) { if (dataHandlers.containsKey(key)) { @@ -176,20 +159,7 @@ public static void clientCommand(String command) CompoundTag outer = new CompoundTag(); outer.put("clientCommand", tag); CarpetClient.getPlayer().connection.send(new ServerboundCustomPayloadPacket( - new CustomPacketPayload() - { - @Override - public void write( FriendlyByteBuf friendlyByteBuf) - { - friendlyByteBuf.writeVarInt(CarpetClient.DATA).writeNbt(outer); - } - - @Override - public ResourceLocation id() - { - return CarpetClient.CARPET_CHANNEL; - } - } + new CarpetClient.CarpetPayload(CarpetClient.DATA, outer) )); } } diff --git a/src/main/java/carpet/network/ServerNetworkHandler.java b/src/main/java/carpet/network/ServerNetworkHandler.java index 9a429ab23b..d707281be2 100644 --- a/src/main/java/carpet/network/ServerNetworkHandler.java +++ b/src/main/java/carpet/network/ServerNetworkHandler.java @@ -4,12 +4,11 @@ import carpet.CarpetSettings; import carpet.api.settings.CarpetRule; import carpet.api.settings.RuleHelper; -import carpet.fakes.CarpetPacketPayload; import carpet.fakes.MinecraftServerInterface; import carpet.fakes.ServerGamePacketListenerImplInterface; import carpet.helpers.ServerTickRateManager; import carpet.script.utils.SnoopyCommandSource; -import io.netty.buffer.Unpooled; + import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -17,7 +16,6 @@ import java.util.Map; import java.util.Set; import java.util.function.BiConsumer; -import java.util.function.Consumer; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; @@ -34,22 +32,6 @@ public class ServerNetworkHandler { - @FunctionalInterface - public interface CarpetCustomPayload extends CustomPacketPayload - { - void writeData(FriendlyByteBuf output); - - @Override - default void write(FriendlyByteBuf output) { - writeData(output); - } - - @Override - default ResourceLocation id() - { - return CarpetClient.CARPET_CHANNEL; - } - } private static final Map remoteCarpetPlayers = new HashMap<>(); private static final Set validCarpetPlayers = new HashSet<>(); @@ -59,43 +41,31 @@ default ResourceLocation id() } ); - public static void handleData(FriendlyByteBuf data, ServerPlayer player) + public static void handleData(CarpetClient.CarpetPayload data, ServerPlayer player) { - if (data != null) - { - int id = data.readVarInt(); - if (id == CarpetClient.HELLO) - onHello(player, data); - if (id == CarpetClient.DATA) - onClientData(player, data); - } + int id = data.command(); + if (id == CarpetClient.HELLO) + onHello(player, data.data()); + if (id == CarpetClient.DATA) + onClientData(player, data.data()); } + private static ClientboundCustomPayloadPacket make(DataBuilder builder) { + CarpetClient.CarpetPayload carpetPayload = builder.build(); + return new ClientboundCustomPayloadPacket(carpetPayload); + } - - private static ClientboundCustomPayloadPacket make(Consumer accepter) { - return new ClientboundCustomPayloadPacket( - new CarpetCustomPayload() - { - @Override - public void writeData(final FriendlyByteBuf t) - { - accepter.accept(t); - } - } - ); + private static ClientboundCustomPayloadPacket make(int command, CompoundTag data) { + return new ClientboundCustomPayloadPacket(new CarpetClient.CarpetPayload(command, data)); } public static void onPlayerJoin(ServerPlayer playerEntity) { - if (true) return; if (!((ServerGamePacketListenerImplInterface)playerEntity.connection).getConnection().isMemoryConnection()) { - playerEntity.connection.send( make( output -> { - output.writeVarInt(CarpetClient.HI); - output.writeUtf(CarpetSettings.carpetVersion); - } - )); + CompoundTag data = new CompoundTag(); + data.putString("version", CarpetSettings.carpetVersion); + playerEntity.connection.send( make( CarpetClient.HI, data)); } else { @@ -103,11 +73,10 @@ public static void onPlayerJoin(ServerPlayer playerEntity) } } - public static void onHello(ServerPlayer playerEntity, FriendlyByteBuf packetData) + public static void onHello(ServerPlayer playerEntity, CompoundTag packetData) { - if (true) return; validCarpetPlayers.add(playerEntity); - String clientVersion = packetData.readUtf(64); + String clientVersion = packetData.getString("version"); remoteCarpetPlayers.put(playerEntity, clientVersion); if (clientVersion.equals(CarpetSettings.carpetVersion)) CarpetSettings.LOG.info("Player "+playerEntity.getName().getString()+" joined with a matching carpet client"); @@ -115,14 +84,13 @@ public static void onHello(ServerPlayer playerEntity, FriendlyByteBuf packetData CarpetSettings.LOG.warn("Player "+playerEntity.getName().getString()+" joined with another carpet version: "+clientVersion); DataBuilder data = DataBuilder.create(playerEntity.server); // tickrate related settings are sent on world change CarpetServer.forEachManager(sm -> sm.getCarpetRules().forEach(data::withRule)); - playerEntity.connection.send(make(data::build)); + playerEntity.connection.send(make(data)); } public static void sendPlayerLevelData(ServerPlayer player, ServerLevel level) { if (CarpetSettings.superSecretSetting || !validCarpetPlayers.contains(player)) return; DataBuilder data = DataBuilder.create(player.server).withTickRate().withFrozenState().withTickPlayerActiveTimeout(); // .withSuperHotState() - player.connection.send(make(data::build)); - + player.connection.send(make(data)); } private static void handleClientCommand(ServerPlayer player, CompoundTag commandData) @@ -149,17 +117,12 @@ private static void handleClientCommand(ServerPlayer player, CompoundTag command ListTag outputResult = new ListTag(); for (Component line: output) outputResult.add(StringTag.valueOf(Component.Serializer.toJson(line))); if (!output.isEmpty()) result.put("output", outputResult); - player.connection.send(make( butebuf -> - DataBuilder.create(player.server).withCustomNbt("clientCommand", result).build(butebuf) - )); + player.connection.send(make( DataBuilder.create(player.server).withCustomNbt("clientCommand", result))); // run command plug to command output, } - - private static void onClientData(ServerPlayer player, FriendlyByteBuf data) + private static void onClientData(ServerPlayer player, CompoundTag compound) { - CompoundTag compound = data.readNbt(); - if (compound == null) return; for (String key: compound.getAllKeys()) { if (dataHandlers.containsKey(key)) @@ -174,9 +137,7 @@ public static void updateRuleWithConnectedClients(CarpetRule rule) if (CarpetSettings.superSecretSetting) return; for (ServerPlayer player : remoteCarpetPlayers.keySet()) { - player.connection.send(make( output -> - DataBuilder.create(player.server).withRule(rule).build(output) - )); + player.connection.send(make(DataBuilder.create(player.server).withRule(rule))); } } @@ -185,9 +146,7 @@ public static void updateTickSpeedToConnectedPlayers(MinecraftServer server) if (CarpetSettings.superSecretSetting) return; for (ServerPlayer player : validCarpetPlayers) { - player.connection.send(make( output -> - DataBuilder.create(player.server).withTickRate().build(output) - )); + player.connection.send(make(DataBuilder.create(player.server).withTickRate())); } } @@ -196,9 +155,7 @@ public static void updateFrozenStateToConnectedPlayers(MinecraftServer server) if (CarpetSettings.superSecretSetting) return; for (ServerPlayer player : validCarpetPlayers) { - player.connection.send(make( output -> - DataBuilder.create(player.server).withFrozenState().build(output) - )); + player.connection.send(make(DataBuilder.create(player.server).withFrozenState())); } } @@ -207,9 +164,7 @@ public static void updateSuperHotStateToConnectedPlayers(MinecraftServer server) if(CarpetSettings.superSecretSetting) return; for (ServerPlayer player : validCarpetPlayers) { - player.connection.send(make(output -> - DataBuilder.create(player.server).withSuperHotState().build(output) - )); + player.connection.send(make(DataBuilder.create(player.server).withSuperHotState())); } } @@ -218,9 +173,7 @@ public static void updateTickPlayerActiveTimeoutToConnectedPlayers(MinecraftServ if (CarpetSettings.superSecretSetting) return; for (ServerPlayer player : validCarpetPlayers) { - player.connection.send(make(output -> - DataBuilder.create(player.server).withTickPlayerActiveTimeout().build(output) - )); + player.connection.send(make(DataBuilder.create(player.server).withTickPlayerActiveTimeout())); } } @@ -229,9 +182,7 @@ public static void broadcastCustomCommand(String command, Tag data) if (CarpetSettings.superSecretSetting) return; for (ServerPlayer player : validCarpetPlayers) { - player.connection.send(make(output -> - DataBuilder.create(player.server).withCustomNbt(command, data).build(output) - )); + player.connection.send(make(DataBuilder.create(player.server).withCustomNbt(command, data))); } } @@ -239,13 +190,10 @@ public static void sendCustomCommand(ServerPlayer player, String command, Tag da { if (isValidCarpetPlayer(player)) { - player.connection.send(make(output -> - DataBuilder.create(player.server).withCustomNbt(command, data).build(output) - )); + player.connection.send(make(DataBuilder.create(player.server).withCustomNbt(command, data))); } } - public static void onPlayerLoggedOut(ServerPlayer player) { validCarpetPlayers.remove(player); @@ -338,12 +286,9 @@ public DataBuilder withCustomNbt(String key, Tag value) return this; } - private void build(FriendlyByteBuf packetBuf) + private CarpetClient.CarpetPayload build() { - packetBuf.writeVarInt(CarpetClient.DATA); - packetBuf.writeNbt(tag); + return new CarpetClient.CarpetPayload(CarpetClient.DATA, tag); } - - } } From 36c09e3c884cdf38a91c1963d17753dc381a5058 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Tue, 8 Aug 2023 12:28:55 +0200 Subject: [PATCH 195/233] move handshake to data --- .../java/carpet/network/CarpetClient.java | 4 ++-- .../carpet/network/ClientNetworkHandler.java | 17 +++++--------- .../carpet/network/ServerNetworkHandler.java | 23 +++++++------------ 3 files changed, 16 insertions(+), 28 deletions(-) diff --git a/src/main/java/carpet/network/CarpetClient.java b/src/main/java/carpet/network/CarpetClient.java index 9a2c411418..762f21025f 100644 --- a/src/main/java/carpet/network/CarpetClient.java +++ b/src/main/java/carpet/network/CarpetClient.java @@ -32,8 +32,8 @@ public ResourceLocation id() { } } - public static final int HI = 69; - public static final int HELLO = 420; + public static final String HI = "69"; + public static final String HELLO = "420"; public static final int DATA = 1; public static ShapesRenderer shapes = null; diff --git a/src/main/java/carpet/network/ClientNetworkHandler.java b/src/main/java/carpet/network/ClientNetworkHandler.java index 960463b09b..cb621f92bc 100644 --- a/src/main/java/carpet/network/ClientNetworkHandler.java +++ b/src/main/java/carpet/network/ClientNetworkHandler.java @@ -8,7 +8,6 @@ import carpet.fakes.LevelInterface; import carpet.helpers.TickRateManager; import carpet.api.settings.SettingsManager; -import io.netty.buffer.Unpooled; import java.util.HashMap; import java.util.Map; import java.util.function.BiConsumer; @@ -18,16 +17,14 @@ import net.minecraft.nbt.ListTag; import net.minecraft.nbt.NumericTag; import net.minecraft.nbt.Tag; -import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.protocol.common.ServerboundCustomPayloadPacket; -import net.minecraft.network.protocol.common.custom.CustomPacketPayload; -import net.minecraft.resources.ResourceLocation; public class ClientNetworkHandler { private static final Map> dataHandlers = new HashMap>(); static { + dataHandlers.put(CarpetClient.HI, (p, t) -> onHi(t.getAsString())); dataHandlers.put("Rules", (p, t) -> { CompoundTag ruleset = (CompoundTag)t; for (String ruleKey: ruleset.getAllKeys()) @@ -96,21 +93,19 @@ public class ClientNetworkHandler dataHandlers.put("clientCommand", (p, t) -> { CarpetClient.onClientCommand(t); }); - }; + } // Ran on the Main Minecraft Thread public static void handleData(CarpetClient.CarpetPayload data, LocalPlayer player) { - if (data.command() == CarpetClient.HI) - onHi(data.data()); if (data.command() == CarpetClient.DATA) onSyncData(data.data(), player); } - private static void onHi(CompoundTag data) + private static void onHi(String version) { CarpetClient.setCarpet(); - CarpetClient.serverCarpetVersion = data.getString("version"); + CarpetClient.serverCarpetVersion = version; if (CarpetSettings.carpetVersion.equals(CarpetClient.serverCarpetVersion)) { CarpetSettings.LOG.info("Joined carpet server with matching carpet version"); @@ -127,9 +122,9 @@ private static void onHi(CompoundTag data) public static void respondHello() { CompoundTag data = new CompoundTag(); - data.putString("version", CarpetSettings.carpetVersion); + data.putString(CarpetClient.HELLO, CarpetSettings.carpetVersion); CarpetClient.getPlayer().connection.send(new ServerboundCustomPayloadPacket( - new CarpetClient.CarpetPayload(CarpetClient.HELLO, data) + new CarpetClient.CarpetPayload(CarpetClient.DATA, data) )); } diff --git a/src/main/java/carpet/network/ServerNetworkHandler.java b/src/main/java/carpet/network/ServerNetworkHandler.java index d707281be2..d82f450199 100644 --- a/src/main/java/carpet/network/ServerNetworkHandler.java +++ b/src/main/java/carpet/network/ServerNetworkHandler.java @@ -21,11 +21,8 @@ import net.minecraft.nbt.ListTag; import net.minecraft.nbt.StringTag; import net.minecraft.nbt.Tag; -import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.chat.Component; import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket; -import net.minecraft.network.protocol.common.custom.CustomPacketPayload; -import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; @@ -36,16 +33,13 @@ public class ServerNetworkHandler private static final Set validCarpetPlayers = new HashSet<>(); private static final Map> dataHandlers = Map.of( - "clientCommand", (p, t) -> { - handleClientCommand(p, (CompoundTag)t); - } + CarpetClient.HELLO, (p, t) -> onHello(p, t.getAsString()), + "clientCommand", (p, t) -> handleClientCommand(p, (CompoundTag)t) ); public static void handleData(CarpetClient.CarpetPayload data, ServerPlayer player) { int id = data.command(); - if (id == CarpetClient.HELLO) - onHello(player, data.data()); if (id == CarpetClient.DATA) onClientData(player, data.data()); } @@ -64,8 +58,8 @@ public static void onPlayerJoin(ServerPlayer playerEntity) if (!((ServerGamePacketListenerImplInterface)playerEntity.connection).getConnection().isMemoryConnection()) { CompoundTag data = new CompoundTag(); - data.putString("version", CarpetSettings.carpetVersion); - playerEntity.connection.send( make( CarpetClient.HI, data)); + data.putString(CarpetClient.HI, CarpetSettings.carpetVersion); + playerEntity.connection.send( make( CarpetClient.DATA, data)); } else { @@ -73,15 +67,14 @@ public static void onPlayerJoin(ServerPlayer playerEntity) } } - public static void onHello(ServerPlayer playerEntity, CompoundTag packetData) + public static void onHello(ServerPlayer playerEntity, String version) { validCarpetPlayers.add(playerEntity); - String clientVersion = packetData.getString("version"); - remoteCarpetPlayers.put(playerEntity, clientVersion); - if (clientVersion.equals(CarpetSettings.carpetVersion)) + remoteCarpetPlayers.put(playerEntity, version); + if (version.equals(CarpetSettings.carpetVersion)) CarpetSettings.LOG.info("Player "+playerEntity.getName().getString()+" joined with a matching carpet client"); else - CarpetSettings.LOG.warn("Player "+playerEntity.getName().getString()+" joined with another carpet version: "+clientVersion); + CarpetSettings.LOG.warn("Player "+playerEntity.getName().getString()+" joined with another carpet version: "+ version); DataBuilder data = DataBuilder.create(playerEntity.server); // tickrate related settings are sent on world change CarpetServer.forEachManager(sm -> sm.getCarpetRules().forEach(data::withRule)); playerEntity.connection.send(make(data)); From cd572695b6456ec9f8b7030fe2f11729d2162aab Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Tue, 8 Aug 2023 12:42:35 +0200 Subject: [PATCH 196/233] remove unnecessary command parameter --- ...ientPacketListener_customPacketsMixin.java | 2 +- ...monPacketListenerimpl_connectionMixin.java | 2 +- .../java/carpet/network/CarpetClient.java | 7 ++- .../carpet/network/ClientNetworkHandler.java | 11 ++--- .../carpet/network/ServerNetworkHandler.java | 46 ++++++------------- 5 files changed, 23 insertions(+), 45 deletions(-) diff --git a/src/main/java/carpet/mixins/ClientPacketListener_customPacketsMixin.java b/src/main/java/carpet/mixins/ClientPacketListener_customPacketsMixin.java index aec33e928f..489546027f 100644 --- a/src/main/java/carpet/mixins/ClientPacketListener_customPacketsMixin.java +++ b/src/main/java/carpet/mixins/ClientPacketListener_customPacketsMixin.java @@ -36,7 +36,7 @@ private void onOnCustomPayload(CustomPacketPayload packet, CallbackInfo ci) { if (packet instanceof CarpetClient.CarpetPayload cpp) { - ClientNetworkHandler.handleData(cpp, minecraft.player); + ClientNetworkHandler.onServerData(cpp.data(), minecraft.player); ci.cancel(); } } diff --git a/src/main/java/carpet/mixins/ServerCommonPacketListenerimpl_connectionMixin.java b/src/main/java/carpet/mixins/ServerCommonPacketListenerimpl_connectionMixin.java index ed179aa338..7bdf69c1ca 100644 --- a/src/main/java/carpet/mixins/ServerCommonPacketListenerimpl_connectionMixin.java +++ b/src/main/java/carpet/mixins/ServerCommonPacketListenerimpl_connectionMixin.java @@ -24,7 +24,7 @@ private void onCustomCarpetPayload(ServerboundCustomPayloadPacket serverboundCus // ServerNetworkHandler.handleData can possibly mutate data that isn't // thread safe, and also allows for client commands to be executed PacketUtils.ensureRunningOnSameThread(serverboundCustomPayloadPacket, (ServerGamePacketListener) this, impl.player.serverLevel()); - ServerNetworkHandler.handleData(cpp, impl.player); + ServerNetworkHandler.onClientData(impl.player, cpp.data()); ci.cancel(); } } diff --git a/src/main/java/carpet/network/CarpetClient.java b/src/main/java/carpet/network/CarpetClient.java index 762f21025f..601ba4d246 100644 --- a/src/main/java/carpet/network/CarpetClient.java +++ b/src/main/java/carpet/network/CarpetClient.java @@ -14,15 +14,14 @@ public class CarpetClient { - public record CarpetPayload(int command, CompoundTag data) implements CustomPacketPayload + public record CarpetPayload(CompoundTag data) implements CustomPacketPayload { public CarpetPayload(FriendlyByteBuf input) { - this(input.readInt(), input.readNbt()); + this(input.readNbt()); } @Override public void write(FriendlyByteBuf output) { - output.writeInt(command); output.writeNbt(data); } @@ -34,7 +33,7 @@ public ResourceLocation id() { public static final String HI = "69"; public static final String HELLO = "420"; - public static final int DATA = 1; + public static ShapesRenderer shapes = null; private static LocalPlayer clientPlayer = null; diff --git a/src/main/java/carpet/network/ClientNetworkHandler.java b/src/main/java/carpet/network/ClientNetworkHandler.java index cb621f92bc..ac23ada578 100644 --- a/src/main/java/carpet/network/ClientNetworkHandler.java +++ b/src/main/java/carpet/network/ClientNetworkHandler.java @@ -96,11 +96,6 @@ public class ClientNetworkHandler } // Ran on the Main Minecraft Thread - public static void handleData(CarpetClient.CarpetPayload data, LocalPlayer player) - { - if (data.command() == CarpetClient.DATA) - onSyncData(data.data(), player); - } private static void onHi(String version) { @@ -124,11 +119,11 @@ public static void respondHello() CompoundTag data = new CompoundTag(); data.putString(CarpetClient.HELLO, CarpetSettings.carpetVersion); CarpetClient.getPlayer().connection.send(new ServerboundCustomPayloadPacket( - new CarpetClient.CarpetPayload(CarpetClient.DATA, data) + new CarpetClient.CarpetPayload(data) )); } - private static void onSyncData(CompoundTag compound, LocalPlayer player) + public static void onServerData(CompoundTag compound, LocalPlayer player) { for (String key: compound.getAllKeys()) { @@ -154,7 +149,7 @@ public static void clientCommand(String command) CompoundTag outer = new CompoundTag(); outer.put("clientCommand", tag); CarpetClient.getPlayer().connection.send(new ServerboundCustomPayloadPacket( - new CarpetClient.CarpetPayload(CarpetClient.DATA, outer) + new CarpetClient.CarpetPayload(outer) )); } } diff --git a/src/main/java/carpet/network/ServerNetworkHandler.java b/src/main/java/carpet/network/ServerNetworkHandler.java index d82f450199..6c98c8e9aa 100644 --- a/src/main/java/carpet/network/ServerNetworkHandler.java +++ b/src/main/java/carpet/network/ServerNetworkHandler.java @@ -37,29 +37,13 @@ public class ServerNetworkHandler "clientCommand", (p, t) -> handleClientCommand(p, (CompoundTag)t) ); - public static void handleData(CarpetClient.CarpetPayload data, ServerPlayer player) - { - int id = data.command(); - if (id == CarpetClient.DATA) - onClientData(player, data.data()); - } - - private static ClientboundCustomPayloadPacket make(DataBuilder builder) { - CarpetClient.CarpetPayload carpetPayload = builder.build(); - return new ClientboundCustomPayloadPacket(carpetPayload); - } - - private static ClientboundCustomPayloadPacket make(int command, CompoundTag data) { - return new ClientboundCustomPayloadPacket(new CarpetClient.CarpetPayload(command, data)); - } - public static void onPlayerJoin(ServerPlayer playerEntity) { if (!((ServerGamePacketListenerImplInterface)playerEntity.connection).getConnection().isMemoryConnection()) { CompoundTag data = new CompoundTag(); data.putString(CarpetClient.HI, CarpetSettings.carpetVersion); - playerEntity.connection.send( make( CarpetClient.DATA, data)); + playerEntity.connection.send(new ClientboundCustomPayloadPacket(new CarpetClient.CarpetPayload(data))); } else { @@ -77,13 +61,13 @@ public static void onHello(ServerPlayer playerEntity, String version) CarpetSettings.LOG.warn("Player "+playerEntity.getName().getString()+" joined with another carpet version: "+ version); DataBuilder data = DataBuilder.create(playerEntity.server); // tickrate related settings are sent on world change CarpetServer.forEachManager(sm -> sm.getCarpetRules().forEach(data::withRule)); - playerEntity.connection.send(make(data)); + playerEntity.connection.send(data.build()); } public static void sendPlayerLevelData(ServerPlayer player, ServerLevel level) { if (CarpetSettings.superSecretSetting || !validCarpetPlayers.contains(player)) return; DataBuilder data = DataBuilder.create(player.server).withTickRate().withFrozenState().withTickPlayerActiveTimeout(); // .withSuperHotState() - player.connection.send(make(data)); + player.connection.send(data.build()); } private static void handleClientCommand(ServerPlayer player, CompoundTag commandData) @@ -110,11 +94,11 @@ private static void handleClientCommand(ServerPlayer player, CompoundTag command ListTag outputResult = new ListTag(); for (Component line: output) outputResult.add(StringTag.valueOf(Component.Serializer.toJson(line))); if (!output.isEmpty()) result.put("output", outputResult); - player.connection.send(make( DataBuilder.create(player.server).withCustomNbt("clientCommand", result))); + player.connection.send(DataBuilder.create(player.server).withCustomNbt("clientCommand", result).build()); // run command plug to command output, } - private static void onClientData(ServerPlayer player, CompoundTag compound) + public static void onClientData(ServerPlayer player, CompoundTag compound) { for (String key: compound.getAllKeys()) { @@ -130,16 +114,16 @@ public static void updateRuleWithConnectedClients(CarpetRule rule) if (CarpetSettings.superSecretSetting) return; for (ServerPlayer player : remoteCarpetPlayers.keySet()) { - player.connection.send(make(DataBuilder.create(player.server).withRule(rule))); + player.connection.send(DataBuilder.create(player.server).withRule(rule).build()); } } - + public static void updateTickSpeedToConnectedPlayers(MinecraftServer server) { if (CarpetSettings.superSecretSetting) return; for (ServerPlayer player : validCarpetPlayers) { - player.connection.send(make(DataBuilder.create(player.server).withTickRate())); + player.connection.send(DataBuilder.create(player.server).withTickRate().build()); } } @@ -148,7 +132,7 @@ public static void updateFrozenStateToConnectedPlayers(MinecraftServer server) if (CarpetSettings.superSecretSetting) return; for (ServerPlayer player : validCarpetPlayers) { - player.connection.send(make(DataBuilder.create(player.server).withFrozenState())); + player.connection.send(DataBuilder.create(player.server).withFrozenState().build()); } } @@ -157,7 +141,7 @@ public static void updateSuperHotStateToConnectedPlayers(MinecraftServer server) if(CarpetSettings.superSecretSetting) return; for (ServerPlayer player : validCarpetPlayers) { - player.connection.send(make(DataBuilder.create(player.server).withSuperHotState())); + player.connection.send(DataBuilder.create(player.server).withSuperHotState().build()); } } @@ -166,7 +150,7 @@ public static void updateTickPlayerActiveTimeoutToConnectedPlayers(MinecraftServ if (CarpetSettings.superSecretSetting) return; for (ServerPlayer player : validCarpetPlayers) { - player.connection.send(make(DataBuilder.create(player.server).withTickPlayerActiveTimeout())); + player.connection.send(DataBuilder.create(player.server).withTickPlayerActiveTimeout().build()); } } @@ -175,7 +159,7 @@ public static void broadcastCustomCommand(String command, Tag data) if (CarpetSettings.superSecretSetting) return; for (ServerPlayer player : validCarpetPlayers) { - player.connection.send(make(DataBuilder.create(player.server).withCustomNbt(command, data))); + player.connection.send(DataBuilder.create(player.server).withCustomNbt(command, data).build()); } } @@ -183,7 +167,7 @@ public static void sendCustomCommand(ServerPlayer player, String command, Tag da { if (isValidCarpetPlayer(player)) { - player.connection.send(make(DataBuilder.create(player.server).withCustomNbt(command, data))); + player.connection.send(DataBuilder.create(player.server).withCustomNbt(command, data).build()); } } @@ -279,9 +263,9 @@ public DataBuilder withCustomNbt(String key, Tag value) return this; } - private CarpetClient.CarpetPayload build() + private ClientboundCustomPayloadPacket build() { - return new CarpetClient.CarpetPayload(CarpetClient.DATA, tag); + return new ClientboundCustomPayloadPacket(new CarpetClient.CarpetPayload(tag)); } } } From 40cb29cd6bc7cf08f66add880b6434c794ae9e54 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Tue, 8 Aug 2023 12:45:00 +0200 Subject: [PATCH 197/233] code style --- .../java/carpet/network/CarpetClient.java | 27 ++-- .../carpet/network/ClientNetworkHandler.java | 56 ++++++--- .../carpet/network/ServerNetworkHandler.java | 116 +++++++++++++----- 3 files changed, 143 insertions(+), 56 deletions(-) diff --git a/src/main/java/carpet/network/CarpetClient.java b/src/main/java/carpet/network/CarpetClient.java index 601ba4d246..5075adaaea 100644 --- a/src/main/java/carpet/network/CarpetClient.java +++ b/src/main/java/carpet/network/CarpetClient.java @@ -16,17 +16,20 @@ public class CarpetClient { public record CarpetPayload(CompoundTag data) implements CustomPacketPayload { - public CarpetPayload(FriendlyByteBuf input) { + public CarpetPayload(FriendlyByteBuf input) + { this(input.readNbt()); } @Override - public void write(FriendlyByteBuf output) { + public void write(FriendlyByteBuf output) + { output.writeNbt(data); } @Override - public ResourceLocation id() { + public ResourceLocation id() + { return CARPET_CHANNEL; } } @@ -78,7 +81,10 @@ public static boolean isCarpet() public static boolean sendClientCommand(String command) { - if (!isServerCarpet && CarpetServer.minecraft_server == null) return false; + if (!isServerCarpet && CarpetServer.minecraft_server == null) + { + return false; + } ClientNetworkHandler.clientCommand(command); return true; } @@ -86,15 +92,20 @@ public static boolean sendClientCommand(String command) public static void onClientCommand(Tag t) { CarpetSettings.LOG.info("Server Response:"); - CompoundTag tag = (CompoundTag)t; - CarpetSettings.LOG.info(" - id: "+tag.getString("id")); - CarpetSettings.LOG.info(" - code: "+tag.getInt("code")); - if (tag.contains("error")) CarpetSettings.LOG.warn(" - error: "+tag.getString("error")); + CompoundTag tag = (CompoundTag) t; + CarpetSettings.LOG.info(" - id: " + tag.getString("id")); + CarpetSettings.LOG.info(" - code: " + tag.getInt("code")); + if (tag.contains("error")) + { + CarpetSettings.LOG.warn(" - error: " + tag.getString("error")); + } if (tag.contains("output")) { ListTag outputTag = (ListTag) tag.get("output"); for (int i = 0; i < outputTag.size(); i++) + { CarpetSettings.LOG.info(" - response: " + Component.Serializer.fromJson(outputTag.getString(i)).getString()); + } } } } diff --git a/src/main/java/carpet/network/ClientNetworkHandler.java b/src/main/java/carpet/network/ClientNetworkHandler.java index ac23ada578..52cfdecbde 100644 --- a/src/main/java/carpet/network/ClientNetworkHandler.java +++ b/src/main/java/carpet/network/ClientNetworkHandler.java @@ -8,9 +8,11 @@ import carpet.fakes.LevelInterface; import carpet.helpers.TickRateManager; import carpet.api.settings.SettingsManager; + import java.util.HashMap; import java.util.Map; import java.util.function.BiConsumer; + import net.minecraft.client.player.LocalPlayer; import net.minecraft.nbt.ByteTag; import net.minecraft.nbt.CompoundTag; @@ -22,12 +24,13 @@ public class ClientNetworkHandler { private static final Map> dataHandlers = new HashMap>(); + static { dataHandlers.put(CarpetClient.HI, (p, t) -> onHi(t.getAsString())); dataHandlers.put("Rules", (p, t) -> { - CompoundTag ruleset = (CompoundTag)t; - for (String ruleKey: ruleset.getAllKeys()) + CompoundTag ruleset = (CompoundTag) t; + for (String ruleKey : ruleset.getAllKeys()) { CompoundTag ruleNBT = (CompoundTag) ruleset.get(ruleKey); SettingsManager manager = null; @@ -42,7 +45,8 @@ public class ClientNetworkHandler } else { - for (CarpetExtension extension: CarpetServer.extensions) { + for (CarpetExtension extension : CarpetServer.extensions) + { SettingsManager eManager = extension.extensionSettingsManager(); if (eManager != null && managerName.equals(eManager.identifier())) { @@ -61,38 +65,46 @@ public class ClientNetworkHandler if (rule != null) { String value = ruleNBT.getString("Value"); - try { rule.set(null, value); } catch (InvalidRuleValueException ignored) { } + try + { + rule.set(null, value); + } + catch (InvalidRuleValueException ignored) + { + } } } }); dataHandlers.put("TickRate", (p, t) -> { - TickRateManager tickRateManager = ((LevelInterface)p.clientLevel).tickRateManager(); + TickRateManager tickRateManager = ((LevelInterface) p.clientLevel).tickRateManager(); tickRateManager.setTickRate(((NumericTag) t).getAsFloat()); }); dataHandlers.put("TickingState", (p, t) -> { - CompoundTag tickingState = (CompoundTag)t; - TickRateManager tickRateManager = ((LevelInterface)p.clientLevel).tickRateManager(); + CompoundTag tickingState = (CompoundTag) t; + TickRateManager tickRateManager = ((LevelInterface) p.clientLevel).tickRateManager(); tickRateManager.setFrozenState(tickingState.getBoolean("is_paused"), tickingState.getBoolean("deepFreeze")); }); dataHandlers.put("SuperHotState", (p, t) -> { - TickRateManager tickRateManager = ((LevelInterface)p.clientLevel).tickRateManager(); - tickRateManager.setSuperHot(((ByteTag) t).equals(ByteTag.ONE)); + TickRateManager tickRateManager = ((LevelInterface) p.clientLevel).tickRateManager(); + tickRateManager.setSuperHot(t.equals(ByteTag.ONE)); }); dataHandlers.put("TickPlayerActiveTimeout", (p, t) -> { - TickRateManager tickRateManager = ((LevelInterface)p.clientLevel).tickRateManager(); + TickRateManager tickRateManager = ((LevelInterface) p.clientLevel).tickRateManager(); tickRateManager.setPlayerActiveTimeout(((NumericTag) t).getAsInt()); }); dataHandlers.put("scShape", (p, t) -> { // deprecated // and unused // should remove for 1.17 if (CarpetClient.shapes != null) - CarpetClient.shapes.addShape((CompoundTag)t); + { + CarpetClient.shapes.addShape((CompoundTag) t); + } }); dataHandlers.put("scShapes", (p, t) -> { if (CarpetClient.shapes != null) + { CarpetClient.shapes.addShapes((ListTag) t); + } }); - dataHandlers.put("clientCommand", (p, t) -> { - CarpetClient.onClientCommand(t); - }); + dataHandlers.put("clientCommand", (p, t) -> CarpetClient.onClientCommand(t)); } // Ran on the Main Minecraft Thread @@ -107,7 +119,7 @@ private static void onHi(String version) } else { - CarpetSettings.LOG.warn("Joined carpet server with another carpet version: "+CarpetClient.serverCarpetVersion); + CarpetSettings.LOG.warn("Joined carpet server with another carpet version: " + CarpetClient.serverCarpetVersion); } // We can ensure that this packet is // processed AFTER the player has joined @@ -125,19 +137,23 @@ public static void respondHello() public static void onServerData(CompoundTag compound, LocalPlayer player) { - for (String key: compound.getAllKeys()) + for (String key : compound.getAllKeys()) { - if (dataHandlers.containsKey(key)) { - try { + if (dataHandlers.containsKey(key)) + { + try + { dataHandlers.get(key).accept(player, compound.get(key)); } catch (Exception exc) { - CarpetSettings.LOG.info("Corrupt carpet data for "+key); + CarpetSettings.LOG.info("Corrupt carpet data for " + key); } } else - CarpetSettings.LOG.error("Unknown carpet data: "+key); + { + CarpetSettings.LOG.error("Unknown carpet data: " + key); + } } } diff --git a/src/main/java/carpet/network/ServerNetworkHandler.java b/src/main/java/carpet/network/ServerNetworkHandler.java index 6c98c8e9aa..327fb20c35 100644 --- a/src/main/java/carpet/network/ServerNetworkHandler.java +++ b/src/main/java/carpet/network/ServerNetworkHandler.java @@ -34,12 +34,12 @@ public class ServerNetworkHandler private static final Map> dataHandlers = Map.of( CarpetClient.HELLO, (p, t) -> onHello(p, t.getAsString()), - "clientCommand", (p, t) -> handleClientCommand(p, (CompoundTag)t) + "clientCommand", (p, t) -> handleClientCommand(p, (CompoundTag) t) ); public static void onPlayerJoin(ServerPlayer playerEntity) { - if (!((ServerGamePacketListenerImplInterface)playerEntity.connection).getConnection().isMemoryConnection()) + if (!((ServerGamePacketListenerImplInterface) playerEntity.connection).getConnection().isMemoryConnection()) { CompoundTag data = new CompoundTag(); data.putString(CarpetClient.HI, CarpetSettings.carpetVersion); @@ -56,16 +56,24 @@ public static void onHello(ServerPlayer playerEntity, String version) validCarpetPlayers.add(playerEntity); remoteCarpetPlayers.put(playerEntity, version); if (version.equals(CarpetSettings.carpetVersion)) - CarpetSettings.LOG.info("Player "+playerEntity.getName().getString()+" joined with a matching carpet client"); + { + CarpetSettings.LOG.info("Player " + playerEntity.getName().getString() + " joined with a matching carpet client"); + } else - CarpetSettings.LOG.warn("Player "+playerEntity.getName().getString()+" joined with another carpet version: "+ version); + { + CarpetSettings.LOG.warn("Player " + playerEntity.getName().getString() + " joined with another carpet version: " + version); + } DataBuilder data = DataBuilder.create(playerEntity.server); // tickrate related settings are sent on world change CarpetServer.forEachManager(sm -> sm.getCarpetRules().forEach(data::withRule)); playerEntity.connection.send(data.build()); } - public static void sendPlayerLevelData(ServerPlayer player, ServerLevel level) { - if (CarpetSettings.superSecretSetting || !validCarpetPlayers.contains(player)) return; + public static void sendPlayerLevelData(ServerPlayer player, ServerLevel level) + { + if (CarpetSettings.superSecretSetting || !validCarpetPlayers.contains(player)) + { + return; + } DataBuilder data = DataBuilder.create(player.server).withTickRate().withFrozenState().withTickPlayerActiveTimeout(); // .withSuperHotState() player.connection.send(data.build()); } @@ -90,28 +98,44 @@ private static void handleClientCommand(ServerPlayer player, CompoundTag command CompoundTag result = new CompoundTag(); result.putString("id", id); result.putInt("code", resultCode); - if (error[0] != null) result.putString("error", error[0].getContents().toString()); + if (error[0] != null) + { + result.putString("error", error[0].getContents().toString()); + } ListTag outputResult = new ListTag(); - for (Component line: output) outputResult.add(StringTag.valueOf(Component.Serializer.toJson(line))); - if (!output.isEmpty()) result.put("output", outputResult); + for (Component line : output) + { + outputResult.add(StringTag.valueOf(Component.Serializer.toJson(line))); + } + if (!output.isEmpty()) + { + result.put("output", outputResult); + } player.connection.send(DataBuilder.create(player.server).withCustomNbt("clientCommand", result).build()); // run command plug to command output, } public static void onClientData(ServerPlayer player, CompoundTag compound) { - for (String key: compound.getAllKeys()) + for (String key : compound.getAllKeys()) { if (dataHandlers.containsKey(key)) + { dataHandlers.get(key).accept(player, compound.get(key)); + } else - CarpetSettings.LOG.warn("Unknown carpet client data: "+key); + { + CarpetSettings.LOG.warn("Unknown carpet client data: " + key); + } } } public static void updateRuleWithConnectedClients(CarpetRule rule) { - if (CarpetSettings.superSecretSetting) return; + if (CarpetSettings.superSecretSetting) + { + return; + } for (ServerPlayer player : remoteCarpetPlayers.keySet()) { player.connection.send(DataBuilder.create(player.server).withRule(rule).build()); @@ -120,7 +144,10 @@ public static void updateRuleWithConnectedClients(CarpetRule rule) public static void updateTickSpeedToConnectedPlayers(MinecraftServer server) { - if (CarpetSettings.superSecretSetting) return; + if (CarpetSettings.superSecretSetting) + { + return; + } for (ServerPlayer player : validCarpetPlayers) { player.connection.send(DataBuilder.create(player.server).withTickRate().build()); @@ -129,7 +156,10 @@ public static void updateTickSpeedToConnectedPlayers(MinecraftServer server) public static void updateFrozenStateToConnectedPlayers(MinecraftServer server) { - if (CarpetSettings.superSecretSetting) return; + if (CarpetSettings.superSecretSetting) + { + return; + } for (ServerPlayer player : validCarpetPlayers) { player.connection.send(DataBuilder.create(player.server).withFrozenState().build()); @@ -138,7 +168,10 @@ public static void updateFrozenStateToConnectedPlayers(MinecraftServer server) public static void updateSuperHotStateToConnectedPlayers(MinecraftServer server) { - if(CarpetSettings.superSecretSetting) return; + if (CarpetSettings.superSecretSetting) + { + return; + } for (ServerPlayer player : validCarpetPlayers) { player.connection.send(DataBuilder.create(player.server).withSuperHotState().build()); @@ -147,7 +180,10 @@ public static void updateSuperHotStateToConnectedPlayers(MinecraftServer server) public static void updateTickPlayerActiveTimeoutToConnectedPlayers(MinecraftServer server) { - if (CarpetSettings.superSecretSetting) return; + if (CarpetSettings.superSecretSetting) + { + return; + } for (ServerPlayer player : validCarpetPlayers) { player.connection.send(DataBuilder.create(player.server).withTickPlayerActiveTimeout().build()); @@ -156,7 +192,10 @@ public static void updateTickPlayerActiveTimeoutToConnectedPlayers(MinecraftServ public static void broadcastCustomCommand(String command, Tag data) { - if (CarpetSettings.superSecretSetting) return; + if (CarpetSettings.superSecretSetting) + { + return; + } for (ServerPlayer player : validCarpetPlayers) { player.connection.send(DataBuilder.create(player.server).withCustomNbt(command, data).build()); @@ -174,8 +213,10 @@ public static void sendCustomCommand(ServerPlayer player, String command, Tag da public static void onPlayerLoggedOut(ServerPlayer player) { validCarpetPlayers.remove(player); - if (!((ServerGamePacketListenerImplInterface)player.connection).getConnection().isMemoryConnection()) + if (!((ServerGamePacketListenerImplInterface) player.connection).getConnection().isMemoryConnection()) + { remoteCarpetPlayers.remove(player); + } } public static void close() @@ -186,15 +227,24 @@ public static void close() public static boolean isValidCarpetPlayer(ServerPlayer player) { - if (CarpetSettings.superSecretSetting) return false; + if (CarpetSettings.superSecretSetting) + { + return false; + } return validCarpetPlayers.contains(player); } public static String getPlayerStatus(ServerPlayer player) { - if (remoteCarpetPlayers.containsKey(player)) return "carpet "+remoteCarpetPlayers.get(player); - if (validCarpetPlayers.contains(player)) return "carpet "+CarpetSettings.carpetVersion; + if (remoteCarpetPlayers.containsKey(player)) + { + return "carpet " + remoteCarpetPlayers.get(player); + } + if (validCarpetPlayers.contains(player)) + { + return "carpet " + CarpetSettings.carpetVersion; + } return "vanilla"; } @@ -202,42 +252,49 @@ private static class DataBuilder { private CompoundTag tag; private MinecraftServer server; + private static DataBuilder create(final MinecraftServer server) { return new DataBuilder(server); } + private DataBuilder(MinecraftServer server) { tag = new CompoundTag(); this.server = server; } + private DataBuilder withTickRate() { - ServerTickRateManager trm = ((MinecraftServerInterface)server).getTickRateManager(); + ServerTickRateManager trm = ((MinecraftServerInterface) server).getTickRateManager(); tag.putFloat("TickRate", trm.tickrate()); return this; } + private DataBuilder withFrozenState() { - ServerTickRateManager trm = ((MinecraftServerInterface)server).getTickRateManager(); + ServerTickRateManager trm = ((MinecraftServerInterface) server).getTickRateManager(); CompoundTag tickingState = new CompoundTag(); tickingState.putBoolean("is_paused", trm.gameIsPaused()); tickingState.putBoolean("deepFreeze", trm.deeplyFrozen()); tag.put("TickingState", tickingState); return this; } + private DataBuilder withSuperHotState() { - ServerTickRateManager trm = ((MinecraftServerInterface)server).getTickRateManager(); - tag.putBoolean("SuperHotState", trm.isSuperHot()); - return this; + ServerTickRateManager trm = ((MinecraftServerInterface) server).getTickRateManager(); + tag.putBoolean("SuperHotState", trm.isSuperHot()); + return this; } + private DataBuilder withTickPlayerActiveTimeout() { - ServerTickRateManager trm = ((MinecraftServerInterface)server).getTickRateManager(); + ServerTickRateManager trm = ((MinecraftServerInterface) server).getTickRateManager(); tag.putInt("TickPlayerActiveTimeout", trm.getPlayerActiveTimeout()); return this; } + private DataBuilder withRule(CarpetRule rule) { CompoundTag rules = (CompoundTag) tag.get("Rules"); @@ -248,7 +305,10 @@ private DataBuilder withRule(CarpetRule rule) } String identifier = rule.settingsManager().identifier(); String key = rule.name(); - while (rules.contains(key)) { key = key+"2";} + while (rules.contains(key)) + { + key = key + "2"; + } CompoundTag ruleNBT = new CompoundTag(); ruleNBT.putString("Value", RuleHelper.toRuleString(rule.value())); ruleNBT.putString("Manager", identifier); From 7fdc6a97ef3f22863046963cf5e93ca1172cd4b4 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Tue, 8 Aug 2023 13:10:35 +0200 Subject: [PATCH 198/233] fixed server connection --- .../ClientboundCustomPayloadPacket_customPacketMixin.java | 5 ++++- .../carpet/mixins/ServerboundCustomPayloadPacket_mixin.java | 5 ++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/main/java/carpet/mixins/ClientboundCustomPayloadPacket_customPacketMixin.java b/src/main/java/carpet/mixins/ClientboundCustomPayloadPacket_customPacketMixin.java index 22d99c39b6..6933c13e18 100644 --- a/src/main/java/carpet/mixins/ClientboundCustomPayloadPacket_customPacketMixin.java +++ b/src/main/java/carpet/mixins/ClientboundCustomPayloadPacket_customPacketMixin.java @@ -17,7 +17,10 @@ @Mixin(ClientboundCustomPayloadPacket.class) public class ClientboundCustomPayloadPacket_customPacketMixin { - @Inject(method = "readUnknownPayload", at = @At("HEAD"), cancellable = true) + @Inject(method = "readPayload", at = @At( + value = "INVOKE", + target = "Lnet/minecraft/network/protocol/common/ClientboundCustomPayloadPacket;readUnknownPayload(Lnet/minecraft/resources/ResourceLocation;Lnet/minecraft/network/FriendlyByteBuf;)Lnet/minecraft/network/protocol/common/custom/DiscardedPayload;"), + cancellable = true) private static void onOnCustomPayloadR(ResourceLocation resourceLocation, FriendlyByteBuf friendlyByteBuf, CallbackInfoReturnable cir) { if (resourceLocation.equals(CarpetClient.CARPET_CHANNEL)) diff --git a/src/main/java/carpet/mixins/ServerboundCustomPayloadPacket_mixin.java b/src/main/java/carpet/mixins/ServerboundCustomPayloadPacket_mixin.java index d8abb5033e..2408ad38fd 100644 --- a/src/main/java/carpet/mixins/ServerboundCustomPayloadPacket_mixin.java +++ b/src/main/java/carpet/mixins/ServerboundCustomPayloadPacket_mixin.java @@ -13,7 +13,10 @@ @Mixin(ServerboundCustomPayloadPacket.class) public class ServerboundCustomPayloadPacket_mixin { - @Inject(method = "readUnknownPayload", at = @At(value = "HEAD"), cancellable = true) + @Inject(method = "readPayload", at = @At( + value = "INVOKE", + target = "Lnet/minecraft/network/protocol/common/ServerboundCustomPayloadPacket;readUnknownPayload(Lnet/minecraft/resources/ResourceLocation;Lnet/minecraft/network/FriendlyByteBuf;)Lnet/minecraft/network/protocol/common/custom/DiscardedPayload;" + ), cancellable = true) private static void onOnCustomPayload(ResourceLocation resourceLocation, FriendlyByteBuf friendlyByteBuf, CallbackInfoReturnable cir) { if (CarpetClient.CARPET_CHANNEL.equals(resourceLocation)) From c5e1a5a09e2bc4566e8db9711deff1520719df6f Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 9 Aug 2023 00:32:54 +0200 Subject: [PATCH 199/233] fixed scoreboardslot argument --- src/main/java/carpet/script/command/CommandArgument.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/carpet/script/command/CommandArgument.java b/src/main/java/carpet/script/command/CommandArgument.java index 24f091604c..4e6742e8b6 100644 --- a/src/main/java/carpet/script/command/CommandArgument.java +++ b/src/main/java/carpet/script/command/CommandArgument.java @@ -258,9 +258,9 @@ public static CommandSyntaxException error(String text) true ), new ScoreholderArgument(), - //new VanillaUnconfigurableArgument("scoreboardslot", ScoreboardSlotArgument::displaySlot, - // (c, p) -> StringValue.of(Scoreboard.getDisplaySlotName(ScoreboardSlotArgument.getDisplaySlot(c, p))), false - //), + new VanillaUnconfigurableArgument("scoreboardslot", ScoreboardSlotArgument::displaySlot, + (c, p) -> StringValue.of(ScoreboardSlotArgument.getDisplaySlot(c, p).getSerializedName()), false + ), new VanillaUnconfigurableArgument("swizzle", SwizzleArgument::swizzle, (c, p) -> StringValue.of(SwizzleArgument.getSwizzle(c, p).stream().map(Direction.Axis::getSerializedName).collect(Collectors.joining())), true ), From 442196709381725abd09596d4283a46e9bf62c86 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 9 Aug 2023 00:55:00 +0200 Subject: [PATCH 200/233] fixed scoreboard scarpet API --- .../java/carpet/script/api/Scoreboards.java | 34 +++++++++---------- 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/src/main/java/carpet/script/api/Scoreboards.java b/src/main/java/carpet/script/api/Scoreboards.java index 293e4c245e..4efe3af473 100644 --- a/src/main/java/carpet/script/api/Scoreboards.java +++ b/src/main/java/carpet/script/api/Scoreboards.java @@ -29,6 +29,7 @@ import net.minecraft.world.BossEvent; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; +import net.minecraft.world.scores.DisplaySlot; import net.minecraft.world.scores.Objective; import net.minecraft.world.scores.PlayerTeam; import net.minecraft.world.scores.Score; @@ -225,32 +226,30 @@ public static void apply(Expression expression) } return new FormattedTextValue(objective.getDisplayName()); } - case "display_slot" -> { /* + case "display_slot" -> { if (modify) { - int slotId = Scoreboard.getDisplaySlotByName(setValue.getString()); - if (slotId == -1) + DisplaySlot slot = DisplaySlot.CODEC.byName(setValue.getString()); + if (slot == null) { throw new InternalExpressionException("Unknown scoreboard display slot: " + setValue.getString()); } - if (objective.equals(scoreboard.getDisplayObjective(slotId))) + if (objective.equals(scoreboard.getDisplayObjective(slot))) { return Value.FALSE; } - scoreboard.setDisplayObjective(slotId, objective); + scoreboard.setDisplayObjective(slot, objective); return Value.TRUE; } List slots = new ArrayList<>(); - for (int i = 0; i < 19; i++) + for (DisplaySlot slot : DisplaySlot.values()) { - if (scoreboard.getDisplayObjective(i) == objective) + if (scoreboard.getDisplayObjective(slot) == objective) { - String slotName = Scoreboard.getDisplaySlotName(i); - slots.add(StringValue.of(slotName)); + slots.add(StringValue.of(slot.getSerializedName())); } } - return ListValue.wrap(slots); */ - return Value.NULL; + return ListValue.wrap(slots); } case "render_type" -> { if (modify) @@ -270,12 +269,12 @@ public static void apply(Expression expression) }); expression.addContextFunction("scoreboard_display", 2, (c, t, lv) -> - { /* + { CarpetContext cc = (CarpetContext) c; Scoreboard scoreboard = cc.server().getScoreboard(); String location = lv.get(0).getString(); - int slot = Scoreboard.getDisplaySlotByName(location); - if (slot < 0) + DisplaySlot slot = DisplaySlot.CODEC.byName(location); + if (slot == null) { throw new InternalExpressionException("Invalid objective slot: " + location); } @@ -283,17 +282,16 @@ public static void apply(Expression expression) if (target.isNull()) { scoreboard.setDisplayObjective(slot, null); - return new NumericValue(slot); + return StringValue.of(slot.getSerializedName()); } String objectiveString = target.getString(); - Objective objective = scoreboard.getOrCreateObjective(objectiveString); + Objective objective = scoreboard.getObjective(objectiveString); if (objective == null) { return Value.NULL; } scoreboard.setDisplayObjective(slot, objective); - return new NumericValue(slot); */ - return Value.NULL; + return StringValue.of(slot.getSerializedName()); }); expression.addContextFunction("team_list", -1, (c, t, lv) -> From 7ff55b2373c882c672476b851eeeb1c452e87853 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 9 Aug 2023 17:50:16 +0200 Subject: [PATCH 201/233] 23w32a --- gradle.properties | 2 +- src/main/java/carpet/script/value/ValueConversions.java | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/gradle.properties b/gradle.properties index 202bc782e0..5457ed4931 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,7 +3,7 @@ org.gradle.jvmargs=-Xmx1G # Fabric Properties # check https://fabricmc.net/develop/ - minecraft_version=23w31a + minecraft_version=23w32a loader_version=0.14.22 jsr305_version=3.0.2 fabric_version=0.83.0+1.20.1 diff --git a/src/main/java/carpet/script/value/ValueConversions.java b/src/main/java/carpet/script/value/ValueConversions.java index 1c595fca52..7254a3872e 100644 --- a/src/main/java/carpet/script/value/ValueConversions.java +++ b/src/main/java/carpet/script/value/ValueConversions.java @@ -3,7 +3,6 @@ import carpet.script.exception.InternalExpressionException; import carpet.script.exception.ThrowStatement; import carpet.script.exception.Throwables; -import carpet.script.external.Carpet; import carpet.script.external.Vanilla; import carpet.script.utils.Colors; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; @@ -91,7 +90,10 @@ public static Value of(MapColor color) public static Value of(MinMaxBounds range) { - return ListValue.of(NumericValue.of(range.getMin()), NumericValue.of(range.getMax())); + return ListValue.of( + range.min().map(NumericValue::of).orElse(Value.NULL), + range.min().map(NumericValue::of).orElse(Value.NULL) + ); } @Deprecated From c4a5ff76e2cad3e558497f745cc8a1c20c4f63b8 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 9 Aug 2023 18:02:14 +0200 Subject: [PATCH 202/233] 1.4.114 --- gradle.properties | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gradle.properties b/gradle.properties index 5457ed4931..90c25e2381 100644 --- a/gradle.properties +++ b/gradle.properties @@ -9,7 +9,7 @@ org.gradle.jvmargs=-Xmx1G fabric_version=0.83.0+1.20.1 # Mod Properties - mod_version = 1.4.113 + mod_version = 1.4.114 maven_group = carpet archives_base_name = fabric-carpet @@ -17,7 +17,7 @@ org.gradle.jvmargs=-Xmx1G # The Curseforge versions "names" or ids for the main branch (comma separated: 1.16.4,1.16.5) # This is needed because CF uses too vague names for prereleases and release candidates # Can also be the version ID directly coming from https://minecraft.curseforge.com/api/game/versions?token=[API_TOKEN] - release-curse-versions = Minecraft 1.20:1.20.1 + release-curse-versions = Minecraft 1.20:1.20.2-Snapshot # Whether or not to build another branch on release release-extra-branch = false # The name of the second branch to release From 8a9c4f0600577f4ea80e13931c5499eb15257373 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Wed, 9 Aug 2023 16:33:58 +0000 Subject: [PATCH 203/233] Merge docs for 'Carpet Mod 1.4.114 for Minecraft 23w32a' --- docs/scarpet/Full.md | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/docs/scarpet/Full.md b/docs/scarpet/Full.md index 9f70764636..0b0e0c7a11 100644 --- a/docs/scarpet/Full.md +++ b/docs/scarpet/Full.md @@ -2559,10 +2559,14 @@ that block, a block doesn't get destroyed either. ### `create_explosion(pos, power?, mode?, fire?, source?, attacker?)` -Creates an explosion at a given position. Default values of optional parameters are: `'power'` - `4` (TNT power), -`'mode'` (block breaking effect `none`, `destroy` or `break`: `break`, `fire` (whether extra fire blocks should be created) - `false`, -`source` (exploding entity) - `null` and `attacker` (entity responsible for trigerring) - `null`. Explosions created with this -endpoint cannot be captured with `__on_explosion` event, however they will be captured by `__on_explosion_outcome`. +Creates an explosion at a given position. Parameters work as follows: + - `'power'` - how strong the blast is, negative values count as 0 (default: `4` (TNT power)) + - `'mode'` - how to deal with broken blocks: `keep` keeps them, `destroy` destroys them and drops items, and `destroy_with_decay` destroys them, but doesn't always drop the items (default: `destroy_with_decay`) + - `fire` - whether extra fire blocks should be created (default: `false`) + - `source` - entity that is exploding. Note that it will not take explosion damage from this explosion (default: `null`) + - `attacker` - entity responsible for triggering, this will be displayed in death messages, and count towards kill counts, and can be damaged by the explosion (default: `null`) +Explosions created with this endpoint cannot be captured with `__on_explosion` event, however they will be captured +by `__on_explosion_outcome`. ### `weather()`,`weather(type)`,`weather(type, ticks)` From b197c5ec996a6b9fbbf936b6ae9f37fc6168ddca Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 9 Aug 2023 19:11:46 +0200 Subject: [PATCH 204/233] oups --- src/main/java/carpet/script/value/ValueConversions.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/carpet/script/value/ValueConversions.java b/src/main/java/carpet/script/value/ValueConversions.java index 7254a3872e..d752f34da2 100644 --- a/src/main/java/carpet/script/value/ValueConversions.java +++ b/src/main/java/carpet/script/value/ValueConversions.java @@ -92,7 +92,7 @@ public static Value of(MinMaxBounds range) { return ListValue.of( range.min().map(NumericValue::of).orElse(Value.NULL), - range.min().map(NumericValue::of).orElse(Value.NULL) + range.max().map(NumericValue::of).orElse(Value.NULL) ); } From 3493e2ce846d8b7aca16afb76c94bc602a7f4f0f Mon Sep 17 00:00:00 2001 From: altrisi Date: Fri, 11 Aug 2023 10:10:05 +0200 Subject: [PATCH 205/233] =?UTF-8?q?Set=20versi=C3=B3n=20bound=20to=20>1.20?= =?UTF-8?q?.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Prevents running it (and crashing) on 1.20/1.20.1 --- src/main/resources/fabric.mod.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json index 0cc0168dfe..159f6090f1 100644 --- a/src/main/resources/fabric.mod.json +++ b/src/main/resources/fabric.mod.json @@ -33,7 +33,7 @@ "accessWidener" : "carpet.accesswidener", "depends": { - "minecraft": ">1.19.4", + "minecraft": ">1.20.1", "fabricloader": ">=0.14.18", "java": ">=17" } From 82530dc2e8e9e4fae1bcf7d336ac266db210ef02 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Thu, 17 Aug 2023 23:19:06 +0200 Subject: [PATCH 206/233] 23w33a noop --- gradle.properties | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gradle.properties b/gradle.properties index 90c25e2381..4a2374d0bf 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,10 +3,10 @@ org.gradle.jvmargs=-Xmx1G # Fabric Properties # check https://fabricmc.net/develop/ - minecraft_version=23w32a + minecraft_version=23w33a loader_version=0.14.22 jsr305_version=3.0.2 - fabric_version=0.83.0+1.20.1 + fabric_version=0.87.1+1.20.2 # Mod Properties mod_version = 1.4.114 From ed91bfe95d53c50fdd0277a8f34b8c8f61a5d714 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 30 Aug 2023 21:58:54 +0200 Subject: [PATCH 207/233] 23w35a --- gradle.properties | 2 +- .../java/carpet/fakes/AbstractContainerMenuInterface.java | 4 ++-- .../carpet/mixins/AbstractContainerMenu_scarpetMixin.java | 4 ++-- .../java/carpet/mixins/RecipeBookMenu_scarpetMixin.java | 4 ++-- src/main/java/carpet/script/command/CommandArgument.java | 6 +++--- src/main/java/carpet/script/value/ScreenValue.java | 8 ++++---- 6 files changed, 14 insertions(+), 14 deletions(-) diff --git a/gradle.properties b/gradle.properties index 4a2374d0bf..fe7ebc39cd 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,7 +3,7 @@ org.gradle.jvmargs=-Xmx1G # Fabric Properties # check https://fabricmc.net/develop/ - minecraft_version=23w33a + minecraft_version=23w35a loader_version=0.14.22 jsr305_version=3.0.2 fabric_version=0.87.1+1.20.2 diff --git a/src/main/java/carpet/fakes/AbstractContainerMenuInterface.java b/src/main/java/carpet/fakes/AbstractContainerMenuInterface.java index 501784d4be..536285df32 100644 --- a/src/main/java/carpet/fakes/AbstractContainerMenuInterface.java +++ b/src/main/java/carpet/fakes/AbstractContainerMenuInterface.java @@ -3,11 +3,11 @@ import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.DataSlot; -import net.minecraft.world.item.crafting.Recipe; +import net.minecraft.world.item.crafting.RecipeHolder; public interface AbstractContainerMenuInterface { DataSlot getDataSlot(int index); boolean callButtonClickListener(int button, Player player); - boolean callSelectRecipeListener(ServerPlayer player, Recipe recipe, boolean craftAll); + boolean callSelectRecipeListener(ServerPlayer player, RecipeHolder recipe, boolean craftAll); } diff --git a/src/main/java/carpet/mixins/AbstractContainerMenu_scarpetMixin.java b/src/main/java/carpet/mixins/AbstractContainerMenu_scarpetMixin.java index 3f3fe6ce53..a1a55eecff 100644 --- a/src/main/java/carpet/mixins/AbstractContainerMenu_scarpetMixin.java +++ b/src/main/java/carpet/mixins/AbstractContainerMenu_scarpetMixin.java @@ -2,6 +2,7 @@ import carpet.fakes.AbstractContainerMenuInterface; import carpet.script.value.ScreenValue; +import net.minecraft.world.item.crafting.RecipeHolder; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -16,7 +17,6 @@ import net.minecraft.world.inventory.ClickType; import net.minecraft.world.inventory.ContainerListener; import net.minecraft.world.inventory.DataSlot; -import net.minecraft.world.item.crafting.Recipe; @Mixin(AbstractContainerMenu.class) public abstract class AbstractContainerMenu_scarpetMixin implements AbstractContainerMenuInterface @@ -61,7 +61,7 @@ public boolean callButtonClickListener(int button, Player player) { } @Override - public boolean callSelectRecipeListener(ServerPlayer player, Recipe recipe, boolean craftAll) { + public boolean callSelectRecipeListener(ServerPlayer player, RecipeHolder recipe, boolean craftAll) { for(ContainerListener screenHandlerListener : containerListeners) { if(screenHandlerListener instanceof ScreenValue.ScarpetScreenHandlerListener scarpetScreenHandlerListener) { if(scarpetScreenHandlerListener.onSelectRecipe(player, recipe, craftAll)) diff --git a/src/main/java/carpet/mixins/RecipeBookMenu_scarpetMixin.java b/src/main/java/carpet/mixins/RecipeBookMenu_scarpetMixin.java index c13ba04724..e28072b133 100644 --- a/src/main/java/carpet/mixins/RecipeBookMenu_scarpetMixin.java +++ b/src/main/java/carpet/mixins/RecipeBookMenu_scarpetMixin.java @@ -3,7 +3,7 @@ import carpet.fakes.AbstractContainerMenuInterface; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.inventory.RecipeBookMenu; -import net.minecraft.world.item.crafting.Recipe; +import net.minecraft.world.item.crafting.RecipeHolder; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -12,7 +12,7 @@ @Mixin(RecipeBookMenu.class) public class RecipeBookMenu_scarpetMixin { @Inject(method = "handlePlacement",at = @At("HEAD"), cancellable = true) - private void selectRecipeCallback(boolean craftAll, Recipe recipe, ServerPlayer player, CallbackInfo ci) { + private void selectRecipeCallback(boolean craftAll, RecipeHolder recipe, ServerPlayer player, CallbackInfo ci) { if(((AbstractContainerMenuInterface) this).callSelectRecipeListener(player,recipe,craftAll)) ci.cancel(); } diff --git a/src/main/java/carpet/script/command/CommandArgument.java b/src/main/java/carpet/script/command/CommandArgument.java index 4e6742e8b6..4b52dc463f 100644 --- a/src/main/java/carpet/script/command/CommandArgument.java +++ b/src/main/java/carpet/script/command/CommandArgument.java @@ -55,7 +55,7 @@ import java.util.stream.Collectors; import net.minecraft.ChatFormatting; -import net.minecraft.advancements.Advancement; +import net.minecraft.advancements.AdvancementHolder; import net.minecraft.advancements.critereon.MinMaxBounds; import net.minecraft.commands.CommandBuildContext; import net.minecraft.commands.CommandSourceStack; @@ -205,10 +205,10 @@ public static CommandSyntaxException error(String text) // resource / identifier section new VanillaUnconfigurableArgument("recipe", ResourceLocationArgument::id, - (c, p) -> ValueConversions.of(ResourceLocationArgument.getRecipe(c, p).getId()), SuggestionProviders.ALL_RECIPES + (c, p) -> ValueConversions.of(ResourceLocationArgument.getRecipe(c, p).id()), SuggestionProviders.ALL_RECIPES ), new VanillaUnconfigurableArgument("advancement", ResourceLocationArgument::id, - (c, p) -> ValueConversions.of(ResourceLocationArgument.getAdvancement(c, p).getId()), (ctx, builder) -> SharedSuggestionProvider.suggestResource(ctx.getSource().getServer().getAdvancements().getAllAdvancements().stream().map(Advancement::getId), builder) + (c, p) -> ValueConversions.of(ResourceLocationArgument.getAdvancement(c, p).id()), (ctx, builder) -> SharedSuggestionProvider.suggestResource(ctx.getSource().getServer().getAdvancements().getAllAdvancements().stream().map(AdvancementHolder::id), builder) ), new VanillaUnconfigurableArgument("lootcondition", ResourceLocationArgument::id, (c, p) -> ValueConversions.of(c.getSource().registryAccess().registryOrThrow(Registries.LOOT_CONDITION_TYPE).getKey(ResourceLocationArgument.getPredicate(c, p).getType())), (ctx, builder) -> SharedSuggestionProvider.suggestResource(ctx.getSource().getServer().getLootData().getKeys(LootDataType.PREDICATE), builder) diff --git a/src/main/java/carpet/script/value/ScreenValue.java b/src/main/java/carpet/script/value/ScreenValue.java index faa177b798..9ec9ccd799 100644 --- a/src/main/java/carpet/script/value/ScreenValue.java +++ b/src/main/java/carpet/script/value/ScreenValue.java @@ -54,7 +54,7 @@ import net.minecraft.world.inventory.SmokerMenu; import net.minecraft.world.inventory.StonecutterMenu; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.crafting.Recipe; +import net.minecraft.world.item.crafting.RecipeHolder; import javax.annotation.Nullable; @@ -252,10 +252,10 @@ public void onClose(ServerPlayer player) } @Override - public boolean onSelectRecipe(ServerPlayer player, Recipe recipe, boolean craftAll) + public boolean onSelectRecipe(ServerPlayer player, RecipeHolder recipe, boolean craftAll) { Map data = new HashMap<>(); - data.put(StringValue.of("recipe"), StringValue.of(recipe.getId().toString())); + data.put(StringValue.of("recipe"), ValueConversions.of(recipe.id())); data.put(StringValue.of("craft_all"), BooleanValue.of(craftAll)); return ScreenValue.this.callListener(player, "select_recipe", data); } @@ -398,7 +398,7 @@ public interface ScarpetScreenHandlerListener extends ContainerListener void onClose(ServerPlayer player); - boolean onSelectRecipe(ServerPlayer player, Recipe recipe, boolean craftAll); + boolean onSelectRecipe(ServerPlayer player, RecipeHolder recipe, boolean craftAll); } public static class ScreenHandlerInventory implements Container From ffbd1338b06c74ea97c40fca46f0d57ba50b2d55 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 30 Aug 2023 21:59:14 +0200 Subject: [PATCH 208/233] 1.4.115 --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index fe7ebc39cd..1a45b9dee4 100644 --- a/gradle.properties +++ b/gradle.properties @@ -9,7 +9,7 @@ org.gradle.jvmargs=-Xmx1G fabric_version=0.87.1+1.20.2 # Mod Properties - mod_version = 1.4.114 + mod_version = 1.4.115 maven_group = carpet archives_base_name = fabric-carpet From 5a77da26d4f7a2b7bb0f0b136a9628fea8a2aab6 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Tue, 5 Sep 2023 22:15:44 +0200 Subject: [PATCH 209/233] 1.20.2-pre1 --- gradle.properties | 4 +-- .../carpet/fakes/ServerPlayerInterface.java | 1 - .../carpet/mixins/PlayerList_coreMixin.java | 3 ++- .../mixins/PlayerList_fakePlayersMixin.java | 18 +++++++------ ...etListenerImpl_antiCheatDisabledMixin.java | 5 ++-- ...erverGamePacketListenerImpl_coreMixin.java | 4 +-- .../mixins/ServerPlayer_actionPackMixin.java | 3 ++- .../ServerPlayer_scarpetEventMixin.java | 17 ------------- .../carpet/patches/EntityPlayerMPFake.java | 18 +++++++------ .../patches/NetHandlerPlayServerFake.java | 3 ++- .../java/carpet/script/external/Vanilla.java | 2 +- .../script/utils/SnoopyCommandSource.java | 25 +++++++++++-------- 12 files changed, 49 insertions(+), 54 deletions(-) diff --git a/gradle.properties b/gradle.properties index 1a45b9dee4..07454d1508 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,10 +3,10 @@ org.gradle.jvmargs=-Xmx1G # Fabric Properties # check https://fabricmc.net/develop/ - minecraft_version=23w35a + minecraft_version=1.20.2-pre1 loader_version=0.14.22 jsr305_version=3.0.2 - fabric_version=0.87.1+1.20.2 + fabric_version=0.88.2+1.20.2 # Mod Properties mod_version = 1.4.115 diff --git a/src/main/java/carpet/fakes/ServerPlayerInterface.java b/src/main/java/carpet/fakes/ServerPlayerInterface.java index 06fea590e6..96c8e09a7e 100644 --- a/src/main/java/carpet/fakes/ServerPlayerInterface.java +++ b/src/main/java/carpet/fakes/ServerPlayerInterface.java @@ -7,5 +7,4 @@ public interface ServerPlayerInterface EntityPlayerActionPack getActionPack(); void invalidateEntityObjectReference(); boolean isInvalidEntityObject(); - String getLanguage(); } diff --git a/src/main/java/carpet/mixins/PlayerList_coreMixin.java b/src/main/java/carpet/mixins/PlayerList_coreMixin.java index d52e0c4075..fec5c66cb4 100644 --- a/src/main/java/carpet/mixins/PlayerList_coreMixin.java +++ b/src/main/java/carpet/mixins/PlayerList_coreMixin.java @@ -5,6 +5,7 @@ import net.minecraft.network.Connection; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.CommonListenerCookie; import net.minecraft.server.players.PlayerList; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; @@ -16,7 +17,7 @@ public class PlayerList_coreMixin { @Inject(method = "placeNewPlayer", at = @At("RETURN")) - private void onPlayerConnected(Connection connection, ServerPlayer player, int i, CallbackInfo ci) + private void onPlayerConnected(Connection connection, ServerPlayer player, CommonListenerCookie i, CallbackInfo ci) { CarpetServer.onPlayerLoggedIn(player); } diff --git a/src/main/java/carpet/mixins/PlayerList_fakePlayersMixin.java b/src/main/java/carpet/mixins/PlayerList_fakePlayersMixin.java index 2cfdae2226..3cd54ed3ae 100644 --- a/src/main/java/carpet/mixins/PlayerList_fakePlayersMixin.java +++ b/src/main/java/carpet/mixins/PlayerList_fakePlayersMixin.java @@ -4,8 +4,10 @@ import net.minecraft.nbt.CompoundTag; import net.minecraft.network.Connection; import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ClientInformation; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.CommonListenerCookie; import net.minecraft.server.network.ServerGamePacketListenerImpl; import net.minecraft.server.players.PlayerList; import org.spongepowered.asm.mixin.Final; @@ -34,25 +36,25 @@ private void fixStartingPos(ServerPlayer serverPlayerEntity_1, CallbackInfoRetur } } - @Redirect(method = "placeNewPlayer", at = @At(value = "NEW", target = "(Lnet/minecraft/server/MinecraftServer;Lnet/minecraft/network/Connection;Lnet/minecraft/server/level/ServerPlayer;I)Lnet/minecraft/server/network/ServerGamePacketListenerImpl;")) - private ServerGamePacketListenerImpl replaceNetworkHandler( MinecraftServer server, Connection clientConnection, ServerPlayer playerIn, int i) + @Redirect(method = "placeNewPlayer", at = @At(value = "NEW", target = "(Lnet/minecraft/server/MinecraftServer;Lnet/minecraft/network/Connection;Lnet/minecraft/server/level/ServerPlayer;Lnet/minecraft/server/network/CommonListenerCookie;)Lnet/minecraft/server/network/ServerGamePacketListenerImpl;")) + private ServerGamePacketListenerImpl replaceNetworkHandler(MinecraftServer server, Connection clientConnection, ServerPlayer playerIn, CommonListenerCookie cookie) { if (playerIn instanceof EntityPlayerMPFake fake) { - return new NetHandlerPlayServerFake(this.server, clientConnection, fake, i); + return new NetHandlerPlayServerFake(this.server, clientConnection, fake, cookie); } else { - return new ServerGamePacketListenerImpl(this.server, clientConnection, playerIn, i); + return new ServerGamePacketListenerImpl(this.server, clientConnection, playerIn, cookie); } } - @Redirect(method = "respawn", at = @At(value = "NEW", target = "(Lnet/minecraft/server/MinecraftServer;Lnet/minecraft/server/level/ServerLevel;Lcom/mojang/authlib/GameProfile;)Lnet/minecraft/server/level/ServerPlayer;")) - public ServerPlayer makePlayerForRespawn(MinecraftServer minecraftServer, ServerLevel serverLevel, GameProfile gameProfile, ServerPlayer serverPlayer, boolean i) + @Redirect(method = "respawn", at = @At(value = "NEW", target = "(Lnet/minecraft/server/MinecraftServer;Lnet/minecraft/server/level/ServerLevel;Lcom/mojang/authlib/GameProfile;Lnet/minecraft/server/level/ClientInformation;)Lnet/minecraft/server/level/ServerPlayer;")) + public ServerPlayer makePlayerForRespawn(MinecraftServer minecraftServer, ServerLevel serverLevel, GameProfile gameProfile, ClientInformation cli, ServerPlayer serverPlayer, boolean i) { if (serverPlayer instanceof EntityPlayerMPFake) { - return EntityPlayerMPFake.respawnFake(minecraftServer, serverLevel, gameProfile); + return EntityPlayerMPFake.respawnFake(minecraftServer, serverLevel, gameProfile, cli); } - return new ServerPlayer(minecraftServer, serverLevel, gameProfile); + return new ServerPlayer(minecraftServer, serverLevel, gameProfile, cli); } } diff --git a/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_antiCheatDisabledMixin.java b/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_antiCheatDisabledMixin.java index 0b0ac1625b..3aed91721d 100644 --- a/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_antiCheatDisabledMixin.java +++ b/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_antiCheatDisabledMixin.java @@ -4,6 +4,7 @@ import net.minecraft.network.Connection; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.CommonListenerCookie; import net.minecraft.server.network.ServerCommonPacketListenerImpl; import net.minecraft.server.network.ServerGamePacketListenerImpl; import org.spongepowered.asm.mixin.Mixin; @@ -20,9 +21,9 @@ public abstract class ServerGamePacketListenerImpl_antiCheatDisabledMixin extend @Shadow private int aboveGroundVehicleTickCount; - public ServerGamePacketListenerImpl_antiCheatDisabledMixin(final MinecraftServer minecraftServer, final Connection connection, final int i) + public ServerGamePacketListenerImpl_antiCheatDisabledMixin(final MinecraftServer minecraftServer, final Connection connection, CommonListenerCookie cci) { - super(minecraftServer, connection, i); + super(minecraftServer, connection, cci); } //@Shadow protected abstract boolean isSingleplayerOwner(); diff --git a/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_coreMixin.java b/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_coreMixin.java index 3d23a71c8f..4935d30e6a 100644 --- a/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_coreMixin.java +++ b/src/main/java/carpet/mixins/ServerGamePacketListenerImpl_coreMixin.java @@ -6,9 +6,9 @@ import net.minecraft.network.chat.Component; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.CommonListenerCookie; import net.minecraft.server.network.ServerCommonPacketListenerImpl; import net.minecraft.server.network.ServerGamePacketListenerImpl; -import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; @@ -20,7 +20,7 @@ public abstract class ServerGamePacketListenerImpl_coreMixin extends ServerCommo @Shadow public ServerPlayer player; - public ServerGamePacketListenerImpl_coreMixin(final MinecraftServer minecraftServer, final Connection connection, final int i) + public ServerGamePacketListenerImpl_coreMixin(final MinecraftServer minecraftServer, final Connection connection, final CommonListenerCookie i) { super(minecraftServer, connection, i); } diff --git a/src/main/java/carpet/mixins/ServerPlayer_actionPackMixin.java b/src/main/java/carpet/mixins/ServerPlayer_actionPackMixin.java index 6eda0884df..9f7a39f0ab 100644 --- a/src/main/java/carpet/mixins/ServerPlayer_actionPackMixin.java +++ b/src/main/java/carpet/mixins/ServerPlayer_actionPackMixin.java @@ -4,6 +4,7 @@ import carpet.helpers.EntityPlayerActionPack; import com.mojang.authlib.GameProfile; import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ClientInformation; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import org.spongepowered.asm.mixin.Mixin; @@ -24,7 +25,7 @@ public EntityPlayerActionPack getActionPack() } @Inject(method = "", at = @At(value = "RETURN")) - private void onServerPlayerEntityContructor(MinecraftServer minecraftServer, ServerLevel serverLevel, GameProfile gameProfile, CallbackInfo ci) + private void onServerPlayerEntityContructor(MinecraftServer minecraftServer, ServerLevel serverLevel, GameProfile gameProfile, ClientInformation cli, CallbackInfo ci) { this.actionPack = new EntityPlayerActionPack((ServerPlayer) (Object) this); } diff --git a/src/main/java/carpet/mixins/ServerPlayer_scarpetEventMixin.java b/src/main/java/carpet/mixins/ServerPlayer_scarpetEventMixin.java index 4f41fc067f..afba6cde38 100644 --- a/src/main/java/carpet/mixins/ServerPlayer_scarpetEventMixin.java +++ b/src/main/java/carpet/mixins/ServerPlayer_scarpetEventMixin.java @@ -5,7 +5,6 @@ import carpet.script.EntityEventsGroup; import com.mojang.authlib.GameProfile; import net.minecraft.core.BlockPos; -import net.minecraft.network.protocol.game.ServerboundClientInformationPacket; import net.minecraft.resources.ResourceKey; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; @@ -129,20 +128,4 @@ public boolean isInvalidEntityObject() { return isInvalidReference; } - - //getting player language - @Unique - private String language; - - @Override - public String getLanguage() - { - return this.language; - } - - @Inject(method = "updateOptions", at = @At("HEAD")) - public void setLanguage(ServerboundClientInformationPacket packet, CallbackInfo ci) - { - this.language = packet.language(); - } } diff --git a/src/main/java/carpet/patches/EntityPlayerMPFake.java b/src/main/java/carpet/patches/EntityPlayerMPFake.java index db02223034..62cffb72d4 100644 --- a/src/main/java/carpet/patches/EntityPlayerMPFake.java +++ b/src/main/java/carpet/patches/EntityPlayerMPFake.java @@ -14,8 +14,10 @@ import net.minecraft.resources.ResourceKey; import net.minecraft.server.MinecraftServer; import net.minecraft.server.TickTask; +import net.minecraft.server.level.ClientInformation; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.CommonListenerCookie; import net.minecraft.server.players.GameProfileCache; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.Entity; @@ -69,9 +71,9 @@ public static void createFake(String username, MinecraftServer server, Vec3 pos, { current = p.get(); } - EntityPlayerMPFake instance = new EntityPlayerMPFake(server, worldIn, current, false); + EntityPlayerMPFake instance = new EntityPlayerMPFake(server, worldIn, current, ClientInformation.createDefault(), false); instance.fixStartingPosition = () -> instance.moveTo(pos.x, pos.y, pos.z, (float) yaw, (float) pitch); - server.getPlayerList().placeNewPlayer(new FakeClientConnection(PacketFlow.SERVERBOUND), instance, 0); + server.getPlayerList().placeNewPlayer(new FakeClientConnection(PacketFlow.SERVERBOUND), instance, new CommonListenerCookie(current, 0, instance.clientInformation())); instance.teleportTo(worldIn, pos.x, pos.y, pos.z, (float) yaw, (float) pitch); instance.setHealth(20.0F); instance.unsetRemoved(); @@ -95,9 +97,9 @@ public static EntityPlayerMPFake createShadow(MinecraftServer server, ServerPlay player.connection.disconnect(Component.translatable("multiplayer.disconnect.duplicate_login")); ServerLevel worldIn = player.serverLevel();//.getWorld(player.dimension); GameProfile gameprofile = player.getGameProfile(); - EntityPlayerMPFake playerShadow = new EntityPlayerMPFake(server, worldIn, gameprofile, true); + EntityPlayerMPFake playerShadow = new EntityPlayerMPFake(server, worldIn, gameprofile, player.clientInformation(), true); playerShadow.setChatSession(player.getChatSession()); - server.getPlayerList().placeNewPlayer(new FakeClientConnection(PacketFlow.SERVERBOUND), playerShadow, 0); + server.getPlayerList().placeNewPlayer(new FakeClientConnection(PacketFlow.SERVERBOUND), playerShadow, new CommonListenerCookie(gameprofile, 0, player.clientInformation())); playerShadow.setHealth(player.getHealth()); playerShadow.connection.teleport(player.getX(), player.getY(), player.getZ(), player.getYRot(), player.getXRot()); @@ -114,14 +116,14 @@ public static EntityPlayerMPFake createShadow(MinecraftServer server, ServerPlay return playerShadow; } - public static EntityPlayerMPFake respawnFake(MinecraftServer server, ServerLevel level, GameProfile profile) + public static EntityPlayerMPFake respawnFake(MinecraftServer server, ServerLevel level, GameProfile profile, ClientInformation cli) { - return new EntityPlayerMPFake(server, level, profile, false); + return new EntityPlayerMPFake(server, level, profile, cli, false); } - private EntityPlayerMPFake(MinecraftServer server, ServerLevel worldIn, GameProfile profile, boolean shadow) + private EntityPlayerMPFake(MinecraftServer server, ServerLevel worldIn, GameProfile profile, ClientInformation cli, boolean shadow) { - super(server, worldIn, profile); + super(server, worldIn, profile, cli); isAShadow = shadow; } diff --git a/src/main/java/carpet/patches/NetHandlerPlayServerFake.java b/src/main/java/carpet/patches/NetHandlerPlayServerFake.java index 7eee43fe42..bfdd7f45f5 100644 --- a/src/main/java/carpet/patches/NetHandlerPlayServerFake.java +++ b/src/main/java/carpet/patches/NetHandlerPlayServerFake.java @@ -6,13 +6,14 @@ import net.minecraft.network.protocol.Packet; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.CommonListenerCookie; import net.minecraft.server.network.ServerGamePacketListenerImpl; import net.minecraft.world.entity.RelativeMovement; import java.util.Set; public class NetHandlerPlayServerFake extends ServerGamePacketListenerImpl { - public NetHandlerPlayServerFake(final MinecraftServer minecraftServer, final Connection connection, final ServerPlayer serverPlayer, final int i) + public NetHandlerPlayServerFake(final MinecraftServer minecraftServer, final Connection connection, final ServerPlayer serverPlayer, final CommonListenerCookie i) { super(minecraftServer, connection, serverPlayer, i); } diff --git a/src/main/java/carpet/script/external/Vanilla.java b/src/main/java/carpet/script/external/Vanilla.java index 67470b4d62..9e30a73880 100644 --- a/src/main/java/carpet/script/external/Vanilla.java +++ b/src/main/java/carpet/script/external/Vanilla.java @@ -230,7 +230,7 @@ public static boolean ServerPlayer_isInvalidEntityObject(ServerPlayer player) public static String ServerPlayer_getLanguage(ServerPlayer player) { - return ((ServerPlayerInterface) player).getLanguage(); + return player.clientInformation().language(); } public static GoalSelector Mob_getAI(Mob mob, boolean target) diff --git a/src/main/java/carpet/script/utils/SnoopyCommandSource.java b/src/main/java/carpet/script/utils/SnoopyCommandSource.java index 4fe3d8d575..adc181d79a 100644 --- a/src/main/java/carpet/script/utils/SnoopyCommandSource.java +++ b/src/main/java/carpet/script/utils/SnoopyCommandSource.java @@ -41,6 +41,8 @@ public class SnoopyCommandSource extends CommandSourceStack private final List chatOutput; private final CommandSigningContext signingContext; + private final TaskChainer taskChainer; + public SnoopyCommandSource(CommandSourceStack original, Component[] error, List chatOutput) { super(CommandSource.NULL, original.getPosition(), original.getRotation(), original.getLevel(), Vanilla.MinecraftServer_getRunPermissionLevel(original.getServer()), @@ -62,6 +64,7 @@ public SnoopyCommandSource(CommandSourceStack original, Component[] error, List< this.error = error; this.chatOutput = chatOutput; this.signingContext = original.getSigningContext(); + this.taskChainer = TaskChainer.immediate(original.getServer()); } public SnoopyCommandSource(ServerPlayer player, Component[] error, List output) @@ -85,15 +88,16 @@ public SnoopyCommandSource(ServerPlayer player, Component[] error, List consumer, EntityAnchorArgument.Anchor entityAnchor, CommandSigningContext context, + private SnoopyCommandSource(CommandSource output, Vec3 pos, Vec2 rot, ServerLevel world, int level, String simpleName, Component name, MinecraftServer server, @Nullable Entity entity, ResultConsumer consumer, EntityAnchorArgument.Anchor entityAnchor, CommandSigningContext context, TaskChainer chainer, Component[] error, List chatOutput ) { super(output, pos, rot, world, level, simpleName, name, server, entity, false, - consumer, entityAnchor, context, TaskChainer.immediate(server), i -> {}); + consumer, entityAnchor, context, chainer, i -> {}); this.output = output; this.position = pos; this.rotation = rot; @@ -108,30 +112,31 @@ private SnoopyCommandSource(CommandSource output, Vec3 pos, Vec2 rot, ServerLeve this.error = error; this.chatOutput = chatOutput; this.signingContext = context; + this.taskChainer = chainer; } @Override public CommandSourceStack withEntity(Entity entity) { - return new SnoopyCommandSource(output, position, rotation, world, level, entity.getName().getString(), entity.getDisplayName(), server, entity, resultConsumer, entityAnchor, signingContext, error, chatOutput); + return new SnoopyCommandSource(output, position, rotation, world, level, entity.getName().getString(), entity.getDisplayName(), server, entity, resultConsumer, entityAnchor, signingContext, taskChainer, error, chatOutput); } @Override public CommandSourceStack withPosition(Vec3 position) { - return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, resultConsumer, entityAnchor, signingContext, error, chatOutput); + return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, resultConsumer, entityAnchor, signingContext, taskChainer, error, chatOutput); } @Override public CommandSourceStack withRotation(Vec2 rotation) { - return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, resultConsumer, entityAnchor, signingContext, error, chatOutput); + return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, resultConsumer, entityAnchor, signingContext, taskChainer, error, chatOutput); } @Override public CommandSourceStack withCallback(ResultConsumer consumer) { - return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, consumer, entityAnchor, signingContext, error, chatOutput); + return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, consumer, entityAnchor, signingContext, taskChainer, error, chatOutput); } @Override @@ -160,13 +165,13 @@ public CommandSourceStack withMaximumPermission(int level) @Override public CommandSourceStack withAnchor(EntityAnchorArgument.Anchor anchor) { - return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, resultConsumer, anchor, signingContext, error, chatOutput); + return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, resultConsumer, anchor, signingContext, taskChainer, error, chatOutput); } @Override - public CommandSourceStack withSigningContext(CommandSigningContext commandSigningContext) + public CommandSourceStack withSigningContext(CommandSigningContext commandSigningContext, TaskChainer taskChainer) { - return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, resultConsumer, entityAnchor, commandSigningContext, error, chatOutput); + return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, resultConsumer, entityAnchor, commandSigningContext, taskChainer, error, chatOutput); } @Override @@ -174,7 +179,7 @@ public CommandSourceStack withLevel(ServerLevel world) { 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, signingContext, error, chatOutput); + return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, resultConsumer, entityAnchor, signingContext, taskChainer, error, chatOutput); } @Override From 9dd2b513ed41e328718abc64777044e40b1e831e Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Tue, 5 Sep 2023 22:17:12 +0200 Subject: [PATCH 210/233] 1.4.116 --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 07454d1508..88eb04d3d1 100644 --- a/gradle.properties +++ b/gradle.properties @@ -9,7 +9,7 @@ org.gradle.jvmargs=-Xmx1G fabric_version=0.88.2+1.20.2 # Mod Properties - mod_version = 1.4.115 + mod_version = 1.4.116 maven_group = carpet archives_base_name = fabric-carpet From e13c2566110bf09ea4c49bef376fefec207cb5a0 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Thu, 7 Sep 2023 23:01:53 +0200 Subject: [PATCH 211/233] 1.20.2-pre2 noop --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 88eb04d3d1..3364bb2a6b 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,7 +3,7 @@ org.gradle.jvmargs=-Xmx1G # Fabric Properties # check https://fabricmc.net/develop/ - minecraft_version=1.20.2-pre1 + minecraft_version=1.20.2-pre2 loader_version=0.14.22 jsr305_version=3.0.2 fabric_version=0.88.2+1.20.2 From 93079eb9ba964663a00e68fe86e9b6ad40f488c6 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Thu, 14 Sep 2023 02:19:02 +0200 Subject: [PATCH 212/233] 1.20.2-pre4 --- gradle.properties | 2 +- src/main/java/carpet/helpers/BlockRotator.java | 10 +++++----- src/main/java/carpet/script/argument/FileArgument.java | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/gradle.properties b/gradle.properties index 3364bb2a6b..50c8501020 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,7 +3,7 @@ org.gradle.jvmargs=-Xmx1G # Fabric Properties # check https://fabricmc.net/develop/ - minecraft_version=1.20.2-pre2 + minecraft_version=1.20.2-pre4 loader_version=0.14.22 jsr305_version=3.0.2 fabric_version=0.88.2+1.20.2 diff --git a/src/main/java/carpet/helpers/BlockRotator.java b/src/main/java/carpet/helpers/BlockRotator.java index 6794f9bbe5..ea876368d3 100644 --- a/src/main/java/carpet/helpers/BlockRotator.java +++ b/src/main/java/carpet/helpers/BlockRotator.java @@ -2,8 +2,8 @@ import carpet.fakes.PistonBlockInterface; import net.minecraft.core.BlockPos; -import net.minecraft.core.BlockSource; import net.minecraft.core.Direction; +import net.minecraft.core.dispenser.BlockSource; import net.minecraft.core.dispenser.DispenseItemBehavior; import net.minecraft.core.dispenser.OptionalDispenseItemBehavior; import net.minecraft.world.InteractionHand; @@ -51,9 +51,9 @@ public static boolean flipBlockWithCactus(BlockState state, Level world, Player public static ItemStack dispenserRotate(BlockSource source, ItemStack stack) { - Direction sourceFace = source.getBlockState().getValue(DispenserBlock.FACING); - Level world = source.getLevel(); - BlockPos blockpos = source.getPos().relative(sourceFace); // offset + Direction sourceFace = source.state().getValue(DispenserBlock.FACING); + Level world = source.level(); + BlockPos blockpos = source.pos().relative(sourceFace); // offset BlockState blockstate = world.getBlockState(blockpos); Block block = blockstate.getBlock(); @@ -100,7 +100,7 @@ else if (block == Blocks.HOPPER) } } // Send block update to the block that just have been rotated. - world.neighborChanged(blockpos, block, source.getPos()); + world.neighborChanged(blockpos, block, source.pos()); return stack; } diff --git a/src/main/java/carpet/script/argument/FileArgument.java b/src/main/java/carpet/script/argument/FileArgument.java index c5e3cb5336..dbc05859e8 100644 --- a/src/main/java/carpet/script/argument/FileArgument.java +++ b/src/main/java/carpet/script/argument/FileArgument.java @@ -461,7 +461,7 @@ public static Tag readTag(Path path) else { dataInputStream.readUTF(); - return TagTypes.getType(b).load(dataInputStream, 0, NbtAccounter.UNLIMITED); + return TagTypes.getType(b).load(dataInputStream, NbtAccounter.unlimitedHeap()); } } catch (IOException secondIO) From fbe8afce174eb14dbcd4212173c1e4b6a6438113 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Thu, 14 Sep 2023 02:20:39 +0200 Subject: [PATCH 213/233] 1.4.117 --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 50c8501020..fa0cec9e52 100644 --- a/gradle.properties +++ b/gradle.properties @@ -9,7 +9,7 @@ org.gradle.jvmargs=-Xmx1G fabric_version=0.88.2+1.20.2 # Mod Properties - mod_version = 1.4.116 + mod_version = 1.4.117 maven_group = carpet archives_base_name = fabric-carpet From 1205c9fdd14418dfa300fddb9ccb36abcb758f9f Mon Sep 17 00:00:00 2001 From: silnarm Date: Sun, 13 Aug 2023 08:36:27 +1000 Subject: [PATCH 214/233] fix-players-pushing-entities-in-tick-freeze * cancel pushEntities() if game paused * fixes #1779 --- .../mixins/LivingEntity_tickSpeedMixin.java | 25 +++++++++++++++++++ src/main/resources/carpet.mixins.json | 1 + 2 files changed, 26 insertions(+) create mode 100644 src/main/java/carpet/mixins/LivingEntity_tickSpeedMixin.java diff --git a/src/main/java/carpet/mixins/LivingEntity_tickSpeedMixin.java b/src/main/java/carpet/mixins/LivingEntity_tickSpeedMixin.java new file mode 100644 index 0000000000..e972f77957 --- /dev/null +++ b/src/main/java/carpet/mixins/LivingEntity_tickSpeedMixin.java @@ -0,0 +1,25 @@ +package carpet.mixins; + +import carpet.fakes.MinecraftServerInterface; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.LivingEntity; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(LivingEntity.class) +public class LivingEntity_tickSpeedMixin +{ + @Inject(method = "pushEntities", at = @At("HEAD"), cancellable = true) + private void onPushEntities(CallbackInfo ci) + { + if ((LivingEntity)(Object)this instanceof ServerPlayer) { + var server = (MinecraftServerInterface)((LivingEntity)(Object)this).level().getServer(); + if(server.getTickRateManager().gameIsPaused()) { + ci.cancel(); + } + } + } +} + diff --git a/src/main/resources/carpet.mixins.json b/src/main/resources/carpet.mixins.json index f9daa6206f..a5db8a8bea 100644 --- a/src/main/resources/carpet.mixins.json +++ b/src/main/resources/carpet.mixins.json @@ -67,6 +67,7 @@ "PistonStructureResolver_pushLimitMixin", "PoweredRailBlock_powerLimitMixin", "LivingEntity_maxCollisionsMixin", + "LivingEntity_tickSpeedMixin", "Level_getOtherEntitiesLimited", "CoralPlantBlock_renewableCoralMixin", "CoralFanBlock_renewableCoralMixin", From 4a2e20362ed7aa1fe7d35203f9a973f4051b8673 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Fri, 15 Sep 2023 23:15:30 +0200 Subject: [PATCH 215/233] 1.20.2-rc1 noop --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index fa0cec9e52..f837da4205 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,7 +3,7 @@ org.gradle.jvmargs=-Xmx1G # Fabric Properties # check https://fabricmc.net/develop/ - minecraft_version=1.20.2-pre4 + minecraft_version=1.20.2-rc1 loader_version=0.14.22 jsr305_version=3.0.2 fabric_version=0.88.2+1.20.2 From 7bd78be760ab329780fb271f2f2012e75b3bbb56 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Thu, 21 Sep 2023 22:48:20 +0200 Subject: [PATCH 216/233] 1.20.2 noop --- gradle.properties | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gradle.properties b/gradle.properties index f837da4205..cd36c7a59e 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,7 +3,7 @@ org.gradle.jvmargs=-Xmx1G # Fabric Properties # check https://fabricmc.net/develop/ - minecraft_version=1.20.2-rc1 + minecraft_version=1.20.2 loader_version=0.14.22 jsr305_version=3.0.2 fabric_version=0.88.2+1.20.2 @@ -17,7 +17,7 @@ org.gradle.jvmargs=-Xmx1G # The Curseforge versions "names" or ids for the main branch (comma separated: 1.16.4,1.16.5) # This is needed because CF uses too vague names for prereleases and release candidates # Can also be the version ID directly coming from https://minecraft.curseforge.com/api/game/versions?token=[API_TOKEN] - release-curse-versions = Minecraft 1.20:1.20.2-Snapshot + release-curse-versions = Minecraft 1.20:1.20.2 # Whether or not to build another branch on release release-extra-branch = false # The name of the second branch to release From cbdcc384745e7a3a88b83a823ce8ef826bd43693 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Thu, 21 Sep 2023 22:48:30 +0200 Subject: [PATCH 217/233] 1.4.118 --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index cd36c7a59e..6e400b7e3e 100644 --- a/gradle.properties +++ b/gradle.properties @@ -9,7 +9,7 @@ org.gradle.jvmargs=-Xmx1G fabric_version=0.88.2+1.20.2 # Mod Properties - mod_version = 1.4.117 + mod_version = 1.4.118 maven_group = carpet archives_base_name = fabric-carpet From cd1deed5e58284ff3de5511c09d09a6e57d354e1 Mon Sep 17 00:00:00 2001 From: manyrandomthings <42223559+manyrandomthings@users.noreply.github.com> Date: Sun, 24 Sep 2023 12:13:32 -0400 Subject: [PATCH 218/233] Fix `movableBlockEntities` crashing in 1.20.2 (#1817) --- src/main/java/carpet/mixins/PistonBaseBlock_movableBEMixin.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/carpet/mixins/PistonBaseBlock_movableBEMixin.java b/src/main/java/carpet/mixins/PistonBaseBlock_movableBEMixin.java index 4aef5956b6..ef1a2d3ebc 100644 --- a/src/main/java/carpet/mixins/PistonBaseBlock_movableBEMixin.java +++ b/src/main/java/carpet/mixins/PistonBaseBlock_movableBEMixin.java @@ -80,7 +80,7 @@ private static PushReaction moveGrindstones(BlockState blockState) } @Inject(method = "moveBlocks", at = @At(value = "INVOKE", shift = At.Shift.BEFORE, - target = "Ljava/util/List;size()I", ordinal = 4),locals = LocalCapture.CAPTURE_FAILHARD) + target = "Ljava/util/List;size()I", ordinal = 3),locals = LocalCapture.CAPTURE_FAILHARD) private void onMove(Level world_1, BlockPos blockPos_1, Direction direction_1, boolean boolean_1, CallbackInfoReturnable cir, BlockPos blockPos_2, PistonStructureResolver pistonHandler_1, Map map_1, List list_1, List list_2, List list_3, BlockState[] blockStates_1, From b0dafd6e3fa40522f6461e8152a98342699bf064 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Thu, 28 Sep 2023 22:39:32 +0200 Subject: [PATCH 219/233] 1.4.119 --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 6e400b7e3e..e0cdfdb673 100644 --- a/gradle.properties +++ b/gradle.properties @@ -9,7 +9,7 @@ org.gradle.jvmargs=-Xmx1G fabric_version=0.88.2+1.20.2 # Mod Properties - mod_version = 1.4.118 + mod_version = 1.4.119 maven_group = carpet archives_base_name = fabric-carpet From 83940f50b3eb4c5e8f372eea3a643c69deaea94d Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 4 Oct 2023 23:24:08 +0200 Subject: [PATCH 220/233] lol stupid mojang 23w40a --- gradle.properties | 4 ++-- .../carpet/mixins/SaplingBlock_desertShrubsMixin.java | 2 +- .../mixins/ServerPlayerGameMode_scarpetEventsMixin.java | 8 ++++---- src/main/java/carpet/utils/Messenger.java | 2 +- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/gradle.properties b/gradle.properties index e0cdfdb673..beaec5e96d 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,10 +3,10 @@ org.gradle.jvmargs=-Xmx1G # Fabric Properties # check https://fabricmc.net/develop/ - minecraft_version=1.20.2 + minecraft_version=23w40a loader_version=0.14.22 jsr305_version=3.0.2 - fabric_version=0.88.2+1.20.2 + fabric_version=0.89.3+1.20.2 # Mod Properties mod_version = 1.4.119 diff --git a/src/main/java/carpet/mixins/SaplingBlock_desertShrubsMixin.java b/src/main/java/carpet/mixins/SaplingBlock_desertShrubsMixin.java index b6ba5cc65c..140829c95f 100644 --- a/src/main/java/carpet/mixins/SaplingBlock_desertShrubsMixin.java +++ b/src/main/java/carpet/mixins/SaplingBlock_desertShrubsMixin.java @@ -23,7 +23,7 @@ public abstract class SaplingBlock_desertShrubsMixin { @Inject(method = "advanceTree", at = @At(value = "INVOKE", shift = At.Shift.BEFORE, - target = "Lnet/minecraft/world/level/block/grower/AbstractTreeGrower;growTree(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/level/chunk/ChunkGenerator;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/util/RandomSource;)Z"), + target = "Lnet/minecraft/world/level/block/grower/TreeGrower;growTree(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/level/chunk/ChunkGenerator;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/util/RandomSource;)Z"), cancellable = true) private void onGenerate(ServerLevel level, BlockPos pos, BlockState blockState, RandomSource random, CallbackInfo ci) { diff --git a/src/main/java/carpet/mixins/ServerPlayerGameMode_scarpetEventsMixin.java b/src/main/java/carpet/mixins/ServerPlayerGameMode_scarpetEventsMixin.java index 163d34cedb..ed3beb6da7 100644 --- a/src/main/java/carpet/mixins/ServerPlayerGameMode_scarpetEventsMixin.java +++ b/src/main/java/carpet/mixins/ServerPlayerGameMode_scarpetEventsMixin.java @@ -40,13 +40,13 @@ public class ServerPlayerGameMode_scarpetEventsMixin implements ServerPlayerInte @Inject(method = "destroyBlock", locals = LocalCapture.CAPTURE_FAILHARD, cancellable = true, at = @At( value = "INVOKE", - target = "Lnet/minecraft/world/level/block/Block;playerWillDestroy(Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/entity/player/Player;)V", + target = "Lnet/minecraft/server/level/ServerLevel;removeBlock(Lnet/minecraft/core/BlockPos;Z)Z", shift = At.Shift.BEFORE )) - private void onBlockBroken(BlockPos blockPos_1, CallbackInfoReturnable cir, BlockState blockState_1, BlockEntity be, Block b) + private void onBlockBroken(final BlockPos blockPos, final CallbackInfoReturnable cir, final BlockEntity blockEntity, final Block block, final BlockState blockState) { - if(PLAYER_BREAK_BLOCK.onBlockBroken(player, blockPos_1, blockState_1)) { - this.level.sendBlockUpdated(blockPos_1, blockState_1, blockState_1, 3); + if(PLAYER_BREAK_BLOCK.onBlockBroken(player, blockPos, blockState)) { + this.level.sendBlockUpdated(blockPos, blockState, blockState, 3); cir.setReturnValue(false); cir.cancel(); } diff --git a/src/main/java/carpet/utils/Messenger.java b/src/main/java/carpet/utils/Messenger.java index 067fadda56..1823157ff3 100644 --- a/src/main/java/carpet/utils/Messenger.java +++ b/src/main/java/carpet/utils/Messenger.java @@ -55,7 +55,7 @@ public enum CarpetFormatting BLACK ('k', (s, f) -> s.withColor(ChatFormatting.BLACK)), COLOR ('#', (s, f) -> { - TextColor color = TextColor.parseColor("#"+f); + TextColor color = TextColor.parseColor("#"+f).getOrThrow(false, LOG::warn); return color == null ? s : s.withColor(color); }, s -> { Matcher m = colorExtract.matcher(s); From 89fc0243b4e5e7b055070e57116c3ec0d5143fe7 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 4 Oct 2023 23:24:49 +0200 Subject: [PATCH 221/233] 1.4.120 --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index beaec5e96d..c4c39ee503 100644 --- a/gradle.properties +++ b/gradle.properties @@ -9,7 +9,7 @@ org.gradle.jvmargs=-Xmx1G fabric_version=0.89.3+1.20.2 # Mod Properties - mod_version = 1.4.119 + mod_version = 1.4.120 maven_group = carpet archives_base_name = fabric-carpet From 257c641bc071518dcf8ea081029cac931349dee1 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 4 Oct 2023 23:26:59 +0200 Subject: [PATCH 222/233] fix Curseforge versions --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index c4c39ee503..0beaf261b0 100644 --- a/gradle.properties +++ b/gradle.properties @@ -17,7 +17,7 @@ org.gradle.jvmargs=-Xmx1G # The Curseforge versions "names" or ids for the main branch (comma separated: 1.16.4,1.16.5) # This is needed because CF uses too vague names for prereleases and release candidates # Can also be the version ID directly coming from https://minecraft.curseforge.com/api/game/versions?token=[API_TOKEN] - release-curse-versions = Minecraft 1.20:1.20.2 + release-curse-versions = Minecraft 1.20:1.20.3-Snapshot # Whether or not to build another branch on release release-extra-branch = false # The name of the second branch to release From c70c3dc7cd92fcac29271a4d7e66b064407157e1 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 4 Oct 2023 23:30:31 +0200 Subject: [PATCH 223/233] this will never age well --- src/main/java/carpet/CarpetSettings.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/carpet/CarpetSettings.java b/src/main/java/carpet/CarpetSettings.java index 8bd8e2ac8f..8570b40156 100644 --- a/src/main/java/carpet/CarpetSettings.java +++ b/src/main/java/carpet/CarpetSettings.java @@ -50,7 +50,7 @@ public class CarpetSettings { public static final String carpetVersion = FabricLoader.getInstance().getModContainer("carpet").orElseThrow().getMetadata().getVersion().toString(); - public static final String releaseTarget = "1.19.4"; + public static final String releaseTarget = "1.20.3"; public static final Logger LOG = LoggerFactory.getLogger("carpet"); public static final ThreadLocal skipGenerationChecks = ThreadLocal.withInitial(() -> false); public static final ThreadLocal impendingFillSkipUpdates = ThreadLocal.withInitial(() -> false); From 47b68facd14e1e55df1c7f3d71c49c5f6084d2e9 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 4 Oct 2023 23:32:02 +0200 Subject: [PATCH 224/233] need to figure something out for this later --- src/main/java/carpet/script/external/Vanilla.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/carpet/script/external/Vanilla.java b/src/main/java/carpet/script/external/Vanilla.java index 9e30a73880..c055a2e81a 100644 --- a/src/main/java/carpet/script/external/Vanilla.java +++ b/src/main/java/carpet/script/external/Vanilla.java @@ -183,6 +183,7 @@ public static int MinecraftServer_getRunPermissionLevel(MinecraftServer server) return CarpetSettings.runPermissionLevel; } + @Deprecated public static String MinecraftServer_getReleaseTarget(MinecraftServer server) { return CarpetSettings.releaseTarget; From 453f5c0813178d046cd55292d8c99f2de9665d07 Mon Sep 17 00:00:00 2001 From: Spongecade Date: Fri, 6 Oct 2023 11:29:18 -0500 Subject: [PATCH 225/233] Update Minecraft wiki links to new domain (#1827) --- docs/scarpet/Full.md | 2 +- docs/scarpet/api/Scoreboard.md | 2 +- src/main/java/carpet/script/command/CommandArgument.java | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/scarpet/Full.md b/docs/scarpet/Full.md index 0b0e0c7a11..6400228d1a 100644 --- a/docs/scarpet/Full.md +++ b/docs/scarpet/Full.md @@ -5227,7 +5227,7 @@ Reads the `property` of the `team` if no `value` is specified. If a `value` is a * `color` * Type: String - * Options: See [team command](https://minecraft.gamepedia.com/Commands/team#Arguments) (same strings as `'teamcolor'` [command argument](https://github.com/gnembon/fabric-carpet/blob/master/docs/scarpet/Full.md#command-argument-types) options) + * Options: See [team command](https://minecraft.wiki/w/Commands/team#Arguments) (same strings as `'teamcolor'` [command argument](https://github.com/gnembon/fabric-carpet/blob/master/docs/scarpet/Full.md#command-argument-types) options) * `displayName` * Type: String or FormattedText, when querying returns FormattedText diff --git a/docs/scarpet/api/Scoreboard.md b/docs/scarpet/api/Scoreboard.md index 881df496f4..817edd7a41 100644 --- a/docs/scarpet/api/Scoreboard.md +++ b/docs/scarpet/api/Scoreboard.md @@ -80,7 +80,7 @@ Reads the `property` of the `team` if no `value` is specified. If a `value` is a * `color` * Type: String - * Options: See [team command](https://minecraft.gamepedia.com/Commands/team#Arguments) (same strings as `'teamcolor'` [command argument](https://github.com/gnembon/fabric-carpet/blob/master/docs/scarpet/Full.md#command-argument-types) options) + * Options: See [team command](https://minecraft.wiki/w/Commands/team#Arguments) (same strings as `'teamcolor'` [command argument](https://github.com/gnembon/fabric-carpet/blob/master/docs/scarpet/Full.md#command-argument-types) options) * `displayName` * Type: String or FormattedText, when querying returns FormattedText diff --git a/src/main/java/carpet/script/command/CommandArgument.java b/src/main/java/carpet/script/command/CommandArgument.java index 4b52dc463f..16e784fc7b 100644 --- a/src/main/java/carpet/script/command/CommandArgument.java +++ b/src/main/java/carpet/script/command/CommandArgument.java @@ -122,7 +122,7 @@ public static CommandSyntaxException error(String text) private static final List baseTypes = Lists.newArrayList( // default new StringArgument(), - // vanilla arguments as per https://minecraft.gamepedia.com/Argument_types + // vanilla arguments as per https://minecraft.wiki/w/Argument_types new VanillaUnconfigurableArgument("bool", BoolArgumentType::bool, (c, p) -> BooleanValue.of(BoolArgumentType.getBool(c, p)), false ), From 9039bbaa16083a8fb14e793c4fd9b4bbbdb27b39 Mon Sep 17 00:00:00 2001 From: altrisi Date: Fri, 6 Oct 2023 18:37:45 +0200 Subject: [PATCH 226/233] Fix hopper counters command error when guessing item color (#1826) * Fix hopper counters command crash when guessing item color * Less List types, slightly less copying and clearer Stream chain * Reverse result equal logic to not search through registries as much Gets the item being searched once outside instead of getting the id for every recipe --- .../carpet/fakes/RecipeManagerInterface.java | 2 +- .../mixins/RecipeManager_scarpetMixin.java | 27 ++++++++++--------- 2 files changed, 16 insertions(+), 13 deletions(-) diff --git a/src/main/java/carpet/fakes/RecipeManagerInterface.java b/src/main/java/carpet/fakes/RecipeManagerInterface.java index ff130d003e..78cfe42878 100644 --- a/src/main/java/carpet/fakes/RecipeManagerInterface.java +++ b/src/main/java/carpet/fakes/RecipeManagerInterface.java @@ -13,5 +13,5 @@ public interface RecipeManagerInterface * Gets all the recipes for a given item. Also used for {@link carpet.helpers.HopperCounter#guessColor} to guess the * colour of an item to display it prettily */ - List> getAllMatching(final RecipeType type, final ResourceLocation output, final RegistryAccess registryAccess); + List> getAllMatching(final RecipeType type, final ResourceLocation itemId, final RegistryAccess registryAccess); } diff --git a/src/main/java/carpet/mixins/RecipeManager_scarpetMixin.java b/src/main/java/carpet/mixins/RecipeManager_scarpetMixin.java index 217e8aef11..864601af50 100644 --- a/src/main/java/carpet/mixins/RecipeManager_scarpetMixin.java +++ b/src/main/java/carpet/mixins/RecipeManager_scarpetMixin.java @@ -1,21 +1,18 @@ package carpet.mixins; import carpet.fakes.RecipeManagerInterface; -import com.google.common.collect.Lists; import net.minecraft.core.Registry; import net.minecraft.core.RegistryAccess; -import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.Registries; import net.minecraft.world.item.Item; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; -import java.util.Collections; import java.util.List; import java.util.Map; -import java.util.stream.Collectors; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.crafting.Recipe; +import net.minecraft.world.item.crafting.RecipeHolder; import net.minecraft.world.item.crafting.RecipeManager; import net.minecraft.world.item.crafting.RecipeType; @@ -23,17 +20,23 @@ public class RecipeManager_scarpetMixin implements RecipeManagerInterface { - @Shadow private Map, Map>> recipes; + @Shadow private Map, Map>> recipes; @Override - public List> getAllMatching(RecipeType type, ResourceLocation output, final RegistryAccess registryAccess) + public List> getAllMatching(RecipeType type, ResourceLocation itemId, final RegistryAccess registryAccess) { - Map> typeRecipes = recipes.get(type); + Map> typeRecipes = recipes.get(type); // happens when mods add recipe to the registry without updating recipe manager - if (typeRecipes == null) return Collections.emptyList(); - if (typeRecipes.containsKey(output)) return Collections.singletonList(typeRecipes.get(output)); - final Registry regs = registryAccess.registryOrThrow(Registries.ITEM); - return Lists.newArrayList(typeRecipes.values().stream().filter( - r -> regs.getKey(r.getResultItem(registryAccess).getItem()).equals(output)).collect(Collectors.toList())); + if (typeRecipes == null) return List.of(); + RecipeHolder recipeFromMap = typeRecipes.get(itemId); + if (recipeFromMap != null) + return List.of(recipeFromMap.value()); + Registry regs = registryAccess.registryOrThrow(Registries.ITEM); + Item item = regs.get(itemId); + return typeRecipes.values() + .stream() + .>map(RecipeHolder::value) + .filter(r -> r.getResultItem(registryAccess).getItem() == item) + .toList(); } } From 52489bab00839a440cbfff5b1a0a9bfb0cf3d77a Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 11 Oct 2023 15:47:43 +0200 Subject: [PATCH 227/233] broader inventory syncing fixes #1515 --- .../java/carpet/script/api/Inventories.java | 23 +++++++------------ 1 file changed, 8 insertions(+), 15 deletions(-) diff --git a/src/main/java/carpet/script/api/Inventories.java b/src/main/java/carpet/script/api/Inventories.java index 755369d1c9..be4e42a324 100644 --- a/src/main/java/carpet/script/api/Inventories.java +++ b/src/main/java/carpet/script/api/Inventories.java @@ -29,15 +29,12 @@ import java.util.Set; import net.minecraft.commands.arguments.item.ItemInput; -import net.minecraft.core.Holder; import net.minecraft.core.HolderSet; import net.minecraft.core.Registry; import net.minecraft.core.RegistryAccess; import net.minecraft.core.registries.Registries; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; -import net.minecraft.network.protocol.game.ClientboundContainerSetSlotPacket; -import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; import net.minecraft.tags.TagKey; @@ -258,7 +255,7 @@ else if (recipe instanceof CustomRecipe) { // clear slot ItemStack removedStack = inventoryLocator.inventory().removeItemNoUpdate(slot); - syncPlayerInventory(inventoryLocator, slot); + syncPlayerInventory(inventoryLocator); return ValueConversions.of(removedStack, regs); } if (lv.size() < inventoryLocator.offset() + 3) @@ -267,7 +264,7 @@ else if (recipe instanceof CustomRecipe) ItemStack newStack = previousStack.copy(); newStack.setCount(count); inventoryLocator.inventory().setItem(slot, newStack); - syncPlayerInventory(inventoryLocator, slot); + syncPlayerInventory(inventoryLocator); return ValueConversions.of(previousStack, regs); } CompoundTag nbt = null; // skipping one argument @@ -288,7 +285,7 @@ else if (!nbtValue.isNull()) try { inventoryLocator.inventory().setItem(slot, newitem.createItemStack(count, false)); - syncPlayerInventory(inventoryLocator, slot); + syncPlayerInventory(inventoryLocator); } catch (CommandSyntaxException e) { @@ -369,11 +366,11 @@ else if (!nbtValue.isNull()) { stack.setCount(left); inventoryLocator.inventory().setItem(i, stack); - syncPlayerInventory(inventoryLocator, i); + syncPlayerInventory(inventoryLocator); return Value.TRUE; } inventoryLocator.inventory().removeItemNoUpdate(i); - syncPlayerInventory(inventoryLocator, i); + syncPlayerInventory(inventoryLocator); amount -= stack.getCount(); } if (amount > 0) @@ -510,15 +507,11 @@ else if (owner instanceof LivingEntity livingEntity) }); } - private static void syncPlayerInventory(NBTSerializableValue.InventoryLocator inventory, int slot) + private static void syncPlayerInventory(NBTSerializableValue.InventoryLocator inventory) { - if (inventory.owner() instanceof final ServerPlayer player && !inventory.isEnder() && !(inventory.inventory() instanceof ScreenValue.ScreenHandlerInventory)) + if (inventory.owner() instanceof ServerPlayer player && !inventory.isEnder() && !(inventory.inventory() instanceof ScreenValue.ScreenHandlerInventory)) { - player.connection.send(new ClientboundContainerSetSlotPacket( - -2, 0, // resolve mystery argument - slot, - inventory.inventory().getItem(slot) - )); + player.containerMenu.broadcastChanges(); } } } From 4a881264b44976bd976db028cab2cafd8ec85b0e Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 11 Oct 2023 15:52:10 +0200 Subject: [PATCH 228/233] fix NaaN comparisons. Fix #1576 --- src/main/java/carpet/script/value/NumericValue.java | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/main/java/carpet/script/value/NumericValue.java b/src/main/java/carpet/script/value/NumericValue.java index 7b15e09bf3..f801d70a5f 100644 --- a/src/main/java/carpet/script/value/NumericValue.java +++ b/src/main/java/carpet/script/value/NumericValue.java @@ -193,7 +193,15 @@ public boolean equals(Object o) } if (o instanceof final NumericValue no) { - return longValue != null && no.longValue != null ? longValue.equals(no.longValue) : !this.subtract(no).getBoolean(); + if (longValue != null && no.longValue != null) + { + return longValue.equals(no.longValue); + } + if (Double.isNaN(this.value) || Double.isNaN(no.value)) + { + return false; + } + return !this.subtract(no).getBoolean(); } return super.equals(o); } From 1fe486a5e8241ee8b7f8a46c7dd21d0d6569fbc1 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 11 Oct 2023 18:20:30 +0200 Subject: [PATCH 229/233] 23w41a --- docs/scarpet/api/Auxiliary.md | 8 ++++---- gradle.properties | 2 +- .../carpet/mixins/Commands_customCommandsMixin.java | 6 ++---- src/main/java/carpet/network/CarpetClient.java | 1 - .../java/carpet/network/ServerNetworkHandler.java | 4 +--- src/main/java/carpet/script/api/Auxiliary.java | 7 +++---- .../carpet/script/utils/SnoopyCommandSource.java | 12 ++++++------ 7 files changed, 17 insertions(+), 23 deletions(-) diff --git a/docs/scarpet/api/Auxiliary.md b/docs/scarpet/api/Auxiliary.md index 544ed6c2de..0d264bd8de 100644 --- a/docs/scarpet/api/Auxiliary.md +++ b/docs/scarpet/api/Auxiliary.md @@ -407,14 +407,14 @@ read_file('foo', 'shared_text') => ['one', 'two', 'three', '', 'four', '', ' ### `run(expr)` -Runs a vanilla command from the string result of the `expr` and returns a triple of success count, +Runs a vanilla command from the string result of the `expr` and returns a triple of 0 (unused after success count removal), intercepted list of output messages, and error message if the command resulted in a failure. Successful commands return `null` as their error.
      -run('fill 1 1 1 10 10 10 air') -> [123, ["Successfully filled 123 blocks"], null] // 123 block were filled, this operation was successful 123 times out of a possible 1000 block volume
      -run('give @s stone 4') -> [1, ["Gave 4 [Stone] to gnembon"], null] // this operation was successful once
      -run('seed') -> [-170661413, ["Seed: [4031384495743822299]"], null]
      +run('fill 1 1 1 10 10 10 air') -> [0, ["Successfully filled 123 blocks"], null]
      +run('give @s stone 4') -> [0, ["Gave 4 [Stone] to gnembon"], null]
      +run('seed') -> [0, ["Seed: [4031384495743822299]"], null]
       run('sed') -> [0, [], "sed<--[HERE]"] // wrong command
       
      diff --git a/gradle.properties b/gradle.properties index 0beaf261b0..d499899069 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,7 +3,7 @@ org.gradle.jvmargs=-Xmx1G # Fabric Properties # check https://fabricmc.net/develop/ - minecraft_version=23w40a + minecraft_version=23w41a loader_version=0.14.22 jsr305_version=3.0.2 fabric_version=0.89.3+1.20.2 diff --git a/src/main/java/carpet/mixins/Commands_customCommandsMixin.java b/src/main/java/carpet/mixins/Commands_customCommandsMixin.java index cac7058b6f..88de81457c 100644 --- a/src/main/java/carpet/mixins/Commands_customCommandsMixin.java +++ b/src/main/java/carpet/mixins/Commands_customCommandsMixin.java @@ -15,8 +15,6 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - @Mixin(Commands.class) public abstract class Commands_customCommandsMixin @@ -32,14 +30,14 @@ private void onRegister(Commands.CommandSelection commandSelection, CommandBuild } @Inject(method = "performCommand", at = @At("HEAD")) - private void onExecuteBegin(ParseResults parseResults, String string, CallbackInfoReturnable cir) + private void onExecuteBegin(ParseResults parseResults, String string, CallbackInfo ci) { if (!CarpetSettings.fillUpdates) CarpetSettings.impendingFillSkipUpdates.set(true); } @Inject(method = "performCommand", at = @At("RETURN")) - private void onExecuteEnd(ParseResults parseResults, String string, CallbackInfoReturnable cir) + private void onExecuteEnd(ParseResults parseResults, String string, CallbackInfo ci) { CarpetSettings.impendingFillSkipUpdates.set(false); } diff --git a/src/main/java/carpet/network/CarpetClient.java b/src/main/java/carpet/network/CarpetClient.java index 5075adaaea..5be5f45306 100644 --- a/src/main/java/carpet/network/CarpetClient.java +++ b/src/main/java/carpet/network/CarpetClient.java @@ -94,7 +94,6 @@ public static void onClientCommand(Tag t) CarpetSettings.LOG.info("Server Response:"); CompoundTag tag = (CompoundTag) t; CarpetSettings.LOG.info(" - id: " + tag.getString("id")); - CarpetSettings.LOG.info(" - code: " + tag.getInt("code")); if (tag.contains("error")) { CarpetSettings.LOG.warn(" - error: " + tag.getString("error")); diff --git a/src/main/java/carpet/network/ServerNetworkHandler.java b/src/main/java/carpet/network/ServerNetworkHandler.java index 327fb20c35..6bf8b15319 100644 --- a/src/main/java/carpet/network/ServerNetworkHandler.java +++ b/src/main/java/carpet/network/ServerNetworkHandler.java @@ -84,20 +84,18 @@ private static void handleClientCommand(ServerPlayer player, CompoundTag command String id = commandData.getString("id"); List output = new ArrayList<>(); Component[] error = {null}; - int resultCode = -1; if (player.getServer() == null) { error[0] = Component.literal("No Server"); } else { - resultCode = player.getServer().getCommands().performPrefixedCommand( + player.getServer().getCommands().performPrefixedCommand( new SnoopyCommandSource(player, error, output), command ); } CompoundTag result = new CompoundTag(); result.putString("id", id); - result.putInt("code", resultCode); if (error[0] != null) { result.putString("error", error[0].getContents().toString()); diff --git a/src/main/java/carpet/script/api/Auxiliary.java b/src/main/java/carpet/script/api/Auxiliary.java index fe2de59978..6fc6a1a42f 100644 --- a/src/main/java/carpet/script/api/Auxiliary.java +++ b/src/main/java/carpet/script/api/Auxiliary.java @@ -690,12 +690,11 @@ else if (!interactable && targetBlock == null) { Component[] error = {null}; List output = new ArrayList<>(); - Value retval = new NumericValue(s.getServer().getCommands().performPrefixedCommand( + s.getServer().getCommands().performPrefixedCommand( new SnoopyCommandSource(s, error, output), - lv.get(0).getString()) - ); + lv.get(0).getString()); return ListValue.of( - retval, + NumericValue.ZERO, ListValue.wrap(output.stream().map(FormattedTextValue::new)), FormattedTextValue.of(error[0]) ); diff --git a/src/main/java/carpet/script/utils/SnoopyCommandSource.java b/src/main/java/carpet/script/utils/SnoopyCommandSource.java index adc181d79a..7e7a89c617 100644 --- a/src/main/java/carpet/script/utils/SnoopyCommandSource.java +++ b/src/main/java/carpet/script/utils/SnoopyCommandSource.java @@ -1,7 +1,7 @@ package carpet.script.utils; import carpet.script.external.Vanilla; -import com.mojang.brigadier.ResultConsumer; +import net.minecraft.commands.CommandResultConsumer; import net.minecraft.commands.CommandSigningContext; import net.minecraft.commands.CommandSource; import net.minecraft.commands.CommandSourceStack; @@ -33,7 +33,7 @@ public class SnoopyCommandSource extends CommandSourceStack private final MinecraftServer server; // skipping silent since snooper is never silent private final Entity entity; - private final ResultConsumer resultConsumer; + private final CommandResultConsumer resultConsumer; private final EntityAnchorArgument.Anchor entityAnchor; private final Vec2 rotation; // good stuff @@ -91,7 +91,7 @@ public SnoopyCommandSource(ServerPlayer player, Component[] error, List consumer, EntityAnchorArgument.Anchor entityAnchor, CommandSigningContext context, TaskChainer chainer, + private SnoopyCommandSource(CommandSource output, Vec3 pos, Vec2 rot, ServerLevel world, int level, String simpleName, Component name, MinecraftServer server, @Nullable Entity entity, CommandResultConsumer consumer, EntityAnchorArgument.Anchor entityAnchor, CommandSigningContext context, TaskChainer chainer, Component[] error, List chatOutput ) { @@ -134,15 +134,15 @@ public CommandSourceStack withRotation(Vec2 rotation) } @Override - public CommandSourceStack withCallback(ResultConsumer consumer) + public CommandSourceStack withCallback(CommandResultConsumer consumer) { return new SnoopyCommandSource(output, position, rotation, world, level, simpleName, name, server, entity, consumer, entityAnchor, signingContext, taskChainer, error, chatOutput); } @Override - public CommandSourceStack withCallback(ResultConsumer consumer, BinaryOperator> binaryOperator) + public CommandSourceStack withCallback(CommandResultConsumer consumer, BinaryOperator> binaryOperator) { - ResultConsumer resultConsumer = binaryOperator.apply(this.resultConsumer, consumer); + CommandResultConsumer resultConsumer = binaryOperator.apply(this.resultConsumer, consumer); return this.withCallback(resultConsumer); } From 59aba60bf999f9d2ad80f5a3e4103e0d52ee9a50 Mon Sep 17 00:00:00 2001 From: gnembon <41132274+gnembon@users.noreply.github.com> Date: Wed, 11 Oct 2023 18:21:10 +0200 Subject: [PATCH 230/233] 1.4.121 --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index d499899069..ad2167db92 100644 --- a/gradle.properties +++ b/gradle.properties @@ -9,7 +9,7 @@ org.gradle.jvmargs=-Xmx1G fabric_version=0.89.3+1.20.2 # Mod Properties - mod_version = 1.4.120 + mod_version = 1.4.121 maven_group = carpet archives_base_name = fabric-carpet From 417024357015ec3fc05d22e28a5c85048c090cf9 Mon Sep 17 00:00:00 2001 From: altrisi Date: Wed, 11 Oct 2023 18:41:08 +0200 Subject: [PATCH 231/233] Also release a 1.20.2 version --- gradle.properties | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/gradle.properties b/gradle.properties index ad2167db92..2ccedb0336 100644 --- a/gradle.properties +++ b/gradle.properties @@ -19,10 +19,10 @@ org.gradle.jvmargs=-Xmx1G # Can also be the version ID directly coming from https://minecraft.curseforge.com/api/game/versions?token=[API_TOKEN] release-curse-versions = Minecraft 1.20:1.20.3-Snapshot # Whether or not to build another branch on release - release-extra-branch = false + release-extra-branch = true # The name of the second branch to release - release-extra-branch-name = hotfixx + release-extra-branch-name = 1.20.2 # The "name" or id of the Curseforge version for the secondary branch # This is needed because CF uses too vague names for snapshots # Can also be the version ID directly coming from https://minecraft.curseforge.com/api/game/versions?token=[API_TOKEN] - release-extra-curse-version = Minecraft 1.19:1.19.3 \ No newline at end of file + release-extra-curse-version = Minecraft 1.20:1.20.2 \ No newline at end of file From c6eec9cebb40f3d8c08af38c70ca00a67df115b8 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Wed, 11 Oct 2023 17:59:42 +0000 Subject: [PATCH 232/233] Merge docs for 'Carpet Mod 1.4.121 for Minecraft 1.20.2 and 23w41a' --- docs/scarpet/Full.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/scarpet/Full.md b/docs/scarpet/Full.md index 6400228d1a..9d755c7275 100644 --- a/docs/scarpet/Full.md +++ b/docs/scarpet/Full.md @@ -5729,14 +5729,14 @@ read_file('foo', 'shared_text') => ['one', 'two', 'three', '', 'four', '', ' ### `run(expr)` -Runs a vanilla command from the string result of the `expr` and returns a triple of success count, +Runs a vanilla command from the string result of the `expr` and returns a triple of 0 (unused after success count removal), intercepted list of output messages, and error message if the command resulted in a failure. Successful commands return `null` as their error.
      -run('fill 1 1 1 10 10 10 air') -> [123, ["Successfully filled 123 blocks"], null] // 123 block were filled, this operation was successful 123 times out of a possible 1000 block volume
      -run('give @s stone 4') -> [1, ["Gave 4 [Stone] to gnembon"], null] // this operation was successful once
      -run('seed') -> [-170661413, ["Seed: [4031384495743822299]"], null]
      +run('fill 1 1 1 10 10 10 air') -> [0, ["Successfully filled 123 blocks"], null]
      +run('give @s stone 4') -> [0, ["Gave 4 [Stone] to gnembon"], null]
      +run('seed') -> [0, ["Seed: [4031384495743822299]"], null]
       run('sed') -> [0, [], "sed<--[HERE]"] // wrong command
       
      From e3d11f744b88e5ce1d0db2ec32b2aefd1dcf231b Mon Sep 17 00:00:00 2001 From: altrisi Date: Fri, 13 Oct 2023 15:45:26 +0200 Subject: [PATCH 233/233] Use the game's constants for NBT types --- .../java/carpet/helpers/InventoryHelper.java | 17 ++--------------- 1 file changed, 2 insertions(+), 15 deletions(-) diff --git a/src/main/java/carpet/helpers/InventoryHelper.java b/src/main/java/carpet/helpers/InventoryHelper.java index ec856331a4..917013bdd1 100644 --- a/src/main/java/carpet/helpers/InventoryHelper.java +++ b/src/main/java/carpet/helpers/InventoryHelper.java @@ -3,23 +3,10 @@ import net.minecraft.nbt.CompoundTag; import net.minecraft.world.item.ItemStack; +import static net.minecraft.nbt.Tag.*; + public class InventoryHelper { - // From nbt/NbtElement.java createTag() - public static final int TAG_END = 0; - public static final int TAG_BYTE = 1; - public static final int TAG_SHORT = 2; - public static final int TAG_INT = 3; - public static final int TAG_LONG = 4; - public static final int TAG_FLOAT = 5; - public static final int TAG_DOUBLE = 6; - public static final int TAG_BYTEARRAY = 7; - public static final int TAG_STRING = 8; - public static final int TAG_LIST = 9; - public static final int TAG_COMPOUND = 10; - public static final int TAG_INTARRAY = 11; - public static final int TAG_LONGARRAY = 12; - public static boolean cleanUpShulkerBoxTag(ItemStack stack) { boolean changed = false;