Skip to content

Commit

Permalink
Merge changes from 1.20.1
Browse files Browse the repository at this point in the history
  • Loading branch information
MaxNeedsSnacks committed Mar 2, 2024
2 parents 99b2c98 + ca0b6b8 commit 46b3073
Show file tree
Hide file tree
Showing 13 changed files with 287 additions and 78 deletions.
2 changes: 1 addition & 1 deletion src/main/java/dev/latvian/mods/kubejs/bindings/KMath.java
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ public static double lerp(double value, double min, double max) {
return min + value * (max - min);
}

public static double lerp(double value, double min0, double max0, double min1, double max1) {
public static double map(double value, double min0, double max0, double min1, double max1) {
return min1 + (max1 - min1) * ((value - min0) / (max0 - min0));
}

Expand Down
97 changes: 72 additions & 25 deletions src/main/java/dev/latvian/mods/kubejs/command/KubeJSCommands.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package dev.latvian.mods.kubejs.command;

import com.google.common.base.Predicate;
import com.google.common.base.Strings;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.CommandDispatcher;
Expand Down Expand Up @@ -42,21 +43,24 @@
import net.minecraft.commands.arguments.ResourceLocationArgument;
import net.minecraft.commands.arguments.ScoreHolderArgument;
import net.minecraft.core.BlockPos;
import net.minecraft.core.HolderSet;
import net.minecraft.core.Registry;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtUtils;
import net.minecraft.network.chat.ClickEvent;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.HoverEvent;
import net.minecraft.network.chat.Style;
import net.minecraft.network.chat.TextColor;
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.tags.TagKey;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.ItemStack;
import net.neoforged.neoforge.fluids.FluidUtil;
import org.apache.commons.io.FileUtils;

import java.io.File;
Expand All @@ -83,6 +87,7 @@ public class KubeJSCommands {
);

public static void register(CommandDispatcher<CommandSourceStack> dispatcher) {
Predicate<CommandSourceStack> spOrOP = (source) -> source.getServer().isSingleplayer() || source.hasPermission(2);
var cmd = dispatcher.register(Commands.literal("kubejs")
.then(Commands.literal("help")
.executes(context -> help(context.getSource()))
Expand All @@ -107,11 +112,11 @@ public static void register(CommandDispatcher<CommandSourceStack> dispatcher) {
)
.then(Commands.literal("errors")
.then(Commands.literal("startup")
.requires(source -> source.getServer().isSingleplayer() || source.hasPermission(2))
.requires(spOrOP)
.executes(context -> errors(context.getSource(), ScriptType.STARTUP))
)
.then(Commands.literal("server")
.requires(source -> source.getServer().isSingleplayer() || source.hasPermission(2))
.requires(spOrOP)
.executes(context -> errors(context.getSource(), ScriptType.SERVER))
)
.then(Commands.literal("client")
Expand All @@ -121,15 +126,15 @@ public static void register(CommandDispatcher<CommandSourceStack> dispatcher) {
)
.then(Commands.literal("reload")
.then(Commands.literal("config")
.requires(source -> source.getServer().isSingleplayer() || source.hasPermission(2))
.requires(spOrOP)
.executes(context -> reloadConfig(context.getSource()))
)
.then(Commands.literal("startup_scripts")
.requires(source -> source.getServer().isSingleplayer() || source.hasPermission(2))
.requires(spOrOP)
.executes(context -> reloadStartup(context.getSource()))
)
.then(Commands.literal("server_scripts")
.requires(source -> source.getServer().isSingleplayer() || source.hasPermission(2))
.requires(spOrOP)
.executes(context -> reloadServer(context.getSource()))
)
.then(Commands.literal("client_scripts")
Expand All @@ -146,7 +151,7 @@ public static void register(CommandDispatcher<CommandSourceStack> dispatcher) {
)
)
.then(Commands.literal("export")
.requires(source -> source.getServer().isSingleplayer() || source.hasPermission(2))
.requires(spOrOP)
.executes(context -> export(context.getSource()))
.then(Commands.literal("pack_zips")
.executes(context -> exportPacks(context.getSource(), true))
Expand Down Expand Up @@ -197,6 +202,7 @@ public static void register(CommandDispatcher<CommandSourceStack> dispatcher) {
)
)
.then(Commands.literal("stages")
.requires(spOrOP)
.then(Commands.literal("add")
.then(Commands.argument("player", EntityArgument.players())
.then(Commands.argument("stage", StringArgumentType.string())
Expand All @@ -223,30 +229,32 @@ public static void register(CommandDispatcher<CommandSourceStack> dispatcher) {
)
)
.then(Commands.literal("painter")
.requires(spOrOP)
.then(Commands.argument("player", EntityArgument.players())
.then(Commands.argument("object", CompoundTagArgument.compoundTag())
.executes(context -> painter(context.getSource(), EntityArgument.getPlayers(context, "player"), CompoundTagArgument.getCompoundTag(context, "object")))
)
)
)
.then(Commands.literal("generate_typings")
.requires(source -> source.getServer().isSingleplayer())
.requires(spOrOP)
.executes(context -> generateTypings(context.getSource()))
)
.then(Commands.literal("packmode")
.requires(spOrOP)
.executes(context -> packmode(context.getSource(), ""))
.then(Commands.argument("name", StringArgumentType.word())
.executes(context -> packmode(context.getSource(), StringArgumentType.getString(context, "name")))
)
)
.then(Commands.literal("dump_internals")
.then(Commands.literal("events")
.requires(source -> source.getServer().isSingleplayer() || source.hasPermission(2))
.requires(spOrOP)
.executes(context -> dumpEvents(context.getSource()))
)
)
.then(Commands.literal("persistent_data")
.requires(source -> source.hasPermission(2))
.requires(spOrOP)
.then(addPersistentDataCommands(Commands.literal("server"), ctx -> Set.of(ctx.getSource().getServer())))
.then(Commands.literal("dimension")
.then(addPersistentDataCommands(Commands.literal("*"), ctx -> (Collection<ServerLevel>) ctx.getSource().getServer().getAllLevels()))
Expand Down Expand Up @@ -480,12 +488,15 @@ private static <T> Stream<TagKey<T>> allTags(CommandSourceStack source, Resource
}

private static Component copy(String s, ChatFormatting col, String info) {
var component = Component.literal("- ");
component.setStyle(component.getStyle().withColor(TextColor.fromLegacyFormat(ChatFormatting.GRAY)));
component.setStyle(component.getStyle().withClickEvent(new ClickEvent(ClickEvent.Action.COPY_TO_CLIPBOARD, s)));
component.setStyle(component.getStyle().withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Component.literal(info + " (Click to copy)"))));
component.append(Component.literal(s).withStyle(col));
return component;
return copy(Component.literal(s).withStyle(col), info);
}

private static Component copy(Component c, String info) {
return Component.literal("- ")
.withStyle(ChatFormatting.GRAY)
.withStyle(Style.EMPTY.withClickEvent(new ClickEvent(ClickEvent.Action.COPY_TO_CLIPBOARD, c.getString())))
.withStyle(Style.EMPTY.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Component.literal(info + " (Click to copy)"))))
.append(c);
}

private static void link(CommandSourceStack source, ChatFormatting color, String name, String url) {
Expand Down Expand Up @@ -517,23 +528,59 @@ private static int customCommand(CommandSourceStack source, String id) {
private static int hand(ServerPlayer player, InteractionHand hand) {
player.sendSystemMessage(Component.literal("Item in hand:"));
var stack = player.getItemInHand(hand);
player.sendSystemMessage(copy(ItemStackJS.toItemString(stack), ChatFormatting.GREEN, "Item ID"));

List<ResourceLocation> tags = new ArrayList<>(stack.kjs$getTags());
tags.sort(null);
var holder = stack.getItemHolder();

for (var id : tags) {
player.sendSystemMessage(copy("'#" + id + "'", ChatFormatting.YELLOW, "Item Tag [" + IngredientHelper.get().tag(id.toString()).kjs$getStacks().size() + " items]"));
// item info
// id
player.sendSystemMessage(copy(ItemStackJS.toItemString(stack), ChatFormatting.GREEN, "Item ID"));
// item tags
var itemTags = holder.tags().toList();
for (var tag : itemTags) {
var id = "'#%s'".formatted(tag.location());
var size = BuiltInRegistries.ITEM.getTag(tag).map(HolderSet::size).orElse(0);
player.sendSystemMessage(copy(id, ChatFormatting.YELLOW, "Item Tag [" + size + " items]"));
}

// mod
player.sendSystemMessage(copy("'@" + stack.kjs$getMod() + "'", ChatFormatting.AQUA, "Mod [" + IngredientHelper.get().mod(stack.kjs$getMod()).kjs$getStacks().size() + " items]"));

// TODO: creative tabs (neo has made them client only in 1.20.1, this is fixed in 1.20.4)
/*var cat = stack.getItem().getItemCategory();
if (cat != null) {
player.sendSystemMessage(copy("'%" + cat.getRecipeFolderName() + "'", ChatFormatting.LIGHT_PURPLE, "Item Group [" + IngredientPlatformHelper.get().creativeTab(cat).kjs$getStacks().size() + " items]"));
}*/

// block info
if (stack.getItem() instanceof BlockItem blockItem) {
player.sendSystemMessage(Component.literal("Held block:"));
var block = blockItem.getBlock();
var blockHolder = block.builtInRegistryHolder();
// id
player.sendSystemMessage(copy(block.kjs$getId(), ChatFormatting.GREEN, "Block ID"));
// block tags
var blockTags = blockHolder.tags().toList();
for (var tag : blockTags) {
var id = "'#%s'".formatted(tag.location());
var size = BuiltInRegistries.BLOCK.getTag(tag).map(HolderSet::size).orElse(0);
player.sendSystemMessage(copy(id, ChatFormatting.YELLOW, "Block Tag [" + size + " items]"));
}
}

// fluid info
var containedFluid = FluidUtil.getFluidContained(stack);
if (containedFluid.isPresent()) {
player.sendSystemMessage(Component.literal("Held fluid:"));
var fluid = containedFluid.orElseThrow();
var fluidHolder = fluid.getFluid().builtInRegistryHolder();
// id
player.sendSystemMessage(copy(fluidHolder.key().location().toString(), ChatFormatting.GREEN, "Fluid ID"));
// fluid tags
var fluidTags = fluidHolder.tags().toList();
for (var tag : fluidTags) {
var id = "'#%s'".formatted(tag.location());
var size = BuiltInRegistries.FLUID.getTag(tag).map(HolderSet::size).orElse(0);
player.sendSystemMessage(copy(id, ChatFormatting.YELLOW, "Fluid Tag [" + size + " items]"));
}
}

return 1;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,12 @@
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.item.ItemStack;
import org.jetbrains.annotations.Nullable;

import java.util.Map;
import java.util.UUID;

@RemapPrefixForJS("kjs$")
public interface MinecraftServerKJS extends WithAttachedData<MinecraftServer>, WithPersistentData, DataSenderKJS, MinecraftEnvironmentKJS {
default MinecraftServer kjs$self() {
Expand Down Expand Up @@ -111,4 +115,8 @@ public interface MinecraftServerKJS extends WithAttachedData<MinecraftServer>, W
ConsoleJS.SERVER.setCapturingErrors(false);
ConsoleJS.SERVER.info("Server resource reload complete!");
}

default Map<UUID, Map<Integer, ItemStack>> kjs$restoreInventories() {
throw new NoMixinException();
}
}
41 changes: 29 additions & 12 deletions src/main/java/dev/latvian/mods/kubejs/core/ServerPlayerKJS.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import org.jetbrains.annotations.Nullable;

import java.util.Date;
import java.util.HashMap;
import java.util.function.Consumer;

@RemapPrefixForJS("kjs$")
Expand Down Expand Up @@ -185,24 +186,40 @@ public AbstractContainerMenu createMenu(int i, Inventory inventory, Player playe
});
}

default ItemStack[] kjs$captureInventory(boolean autoRestore) {
var playerItems = kjs$self().getInventory().items;

var captured = new ItemStack[playerItems.size()];
var map = new HashMap<Integer, ItemStack>();

for (int i = 0; i < captured.length; i++) {
var c = playerItems.set(i, ItemStack.EMPTY);

if (autoRestore && !c.isEmpty()) {
map.put(i, c);
}

captured[i] = c.copy();
}

if (autoRestore && !map.isEmpty()) {
kjs$self().getServer().kjs$restoreInventories().put(kjs$self().getUUID(), map);
}

return captured;
}

default void kjs$openChestGUI(Component title, int rows, Consumer<ChestMenuData> gui) {
var data = new ChestMenuData(title, Mth.clamp(rows, 1, 6));
var data = new ChestMenuData(kjs$self(), title, Mth.clamp(rows, 1, 6));
gui.accept(data);

if (kjs$self().containerMenu instanceof CustomChestMenu open && open.data.rows == data.rows && open.data.title.equals(title)) {
data.playerInventory = open.data.playerInventory;
data.capturedInventory = open.data.capturedInventory;
open.data = data;
open.sendAllDataToRemote();
data.sync();
} else {
var playerItems = kjs$self().getInventory().items;

data.playerInventory = new ItemStack[playerItems.size()];

for (int i = 0; i < data.playerInventory.length; i++) {
data.playerInventory[i] = playerItems.set(i, ItemStack.EMPTY);
}

kjs$self().inventoryMenu.broadcastFullState();
data.capturedInventory = data.playerSlots ? new ItemStack[0] : kjs$captureInventory(true);
data.sync();

kjs$self().openMenu(new MenuProvider() {
@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import dev.latvian.mods.kubejs.KubeJSPlugin;
import dev.latvian.mods.kubejs.bindings.event.ServerEvents;
import dev.latvian.mods.kubejs.core.MinecraftServerKJS;
import dev.latvian.mods.kubejs.gui.chest.CustomChestMenu;
import dev.latvian.mods.kubejs.script.ScriptType;
import dev.latvian.mods.kubejs.server.ScheduledServerEvent;
import dev.latvian.mods.kubejs.server.ServerEventJS;
Expand All @@ -14,6 +15,7 @@
import net.minecraft.nbt.CompoundTag;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.item.ItemStack;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
Expand All @@ -25,6 +27,9 @@

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.function.BooleanSupplier;

Expand All @@ -49,6 +54,9 @@ public abstract class MinecraftServerMixin implements MinecraftServerKJS {
@Unique
private AttachedData<MinecraftServer> kjs$attachedData;

@Unique
private final Map<UUID, Map<Integer, ItemStack>> kjs$restoreInventories = new HashMap<>(1);

@Override
@Accessor("resources")
public abstract MinecraftServer.ReloadableResources kjs$getReloadableResources();
Expand Down Expand Up @@ -88,6 +96,22 @@ public abstract class MinecraftServerMixin implements MinecraftServerKJS {
kjs$scheduledEvents.tickAll(kjs$getOverworld().getGameTime());
}

if (!kjs$restoreInventories.isEmpty()) {
for (var player : kjs$self().getPlayerList().getPlayers()) {
var map = kjs$restoreInventories.get(player.getUUID());

if (map != null && player.isAlive() && !player.hasDisconnected() && !(player.containerMenu instanceof CustomChestMenu)) {
kjs$restoreInventories.remove(player.getUUID());

var playerItems = player.getInventory().items;

for (int i = 0; i < playerItems.size(); i++) {
playerItems.set(i, map.getOrDefault(i, ItemStack.EMPTY));
}
}
}
}

if (ServerEvents.TICK.hasListeners()) {
ServerEvents.TICK.post(ScriptType.SERVER, new ServerEventJS(kjs$self()));
}
Expand All @@ -102,6 +126,11 @@ public abstract class MinecraftServerMixin implements MinecraftServerKJS {
return kjs$scheduledEvents;
}

@Override
public Map<UUID, Map<Integer, ItemStack>> kjs$restoreInventories() {
return kjs$restoreInventories;
}

@Shadow
@RemapForJS("isDedicated")
public abstract boolean isDedicatedServer();
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
import net.minecraft.world.inventory.ClickType;

public class ChestMenuClickEvent {
public interface Callback {
void onClick(ChestMenuClickEvent event);
}

public final ChestMenuSlot slot;
public final ClickType type;
public final int button;
Expand Down
Loading

0 comments on commit 46b3073

Please sign in to comment.