Add client command integration for Build 42: define APIs, event system, hooks, patches, and Lua table converters. Include tests, documentation, and mod support.

This commit is contained in:
Overlord committed 2026-10-03 13:22:47 +02:00
1 parent af7174e128
commit a351fc237c
24 files changed
+870 -48

No files matched your search

@@ -1,12 +1,15 @@
package dev.overlord.zomboidforge.compat.b42;
import dev.overlord.zomboidforge.compat.b42.commands.ClientCommandChannel;
import dev.overlord.zomboidforge.compat.b42.commands.ModCommands;
import dev.overlord.zomboidforge.core.Forge;
/** The one {@link Forge} of the server, shared by the hook classes. */
public final class ForgeInstance
{
public static final Forge FORGE = Forge.fromSystemProperties(ModCommands::check);
public static final Forge FORGE = Forge.fromSystemProperties(
ModCommands::check, ClientCommandChannel::prepare
);
private ForgeInstance() {}
}
@@ -0,0 +1,55 @@
package dev.overlord.zomboidforge.compat.b42.commands;
import dev.overlord.zomboidforge.api.PlayerRef;
import org.jetbrains.annotations.Nullable;
import se.krka.kahlua.vm.KahluaTable;
import zombie.Lua.LuaManager;
import zombie.characters.IsoPlayer;
import zombie.network.GameServer;
import java.util.Map;
/** Client commands in Build 42: players as {@link PlayerRef}s, and server commands to clients. */
public final class ClientCommandChannel
{
private ClientCommandChannel() {}
public static PlayerRef ref(IsoPlayer player) { return new PlayerRef(player.getOnlineID(), player.getUsername()); }
/**
* Copies {@code args} at once and returns the action that sends the command with
* {@code GameServer.sendServerCommand}, to every connection when {@code player} is
* {@code null}. The action runs on the main thread and sends nothing when the player is no
* longer connected.
*
* @throws IllegalArgumentException naming a key or value that cannot be sent
*/
public static Runnable prepare(@Nullable PlayerRef player, String module, String command, Map<?, ?> args)
{
Map<Object, Object> copy = LuaTables.copy(args);
return () ->
{
KahluaTable table = copy.isEmpty() ? null : LuaTables.toLua(copy, LuaManager.platform::newTable);
if (player == null) {
GameServer.sendServerCommand(module, command, table);
return;
}
IsoPlayer target = ClientCommandChannel.find(player);
if (target != null) GameServer.sendServerCommand(target, module, command, table);
};
}
/** The connected player with the online id and the username of {@code player}, or {@code null}. Main thread. */
private static @Nullable IsoPlayer find(PlayerRef player)
{
Object connected = GameServer.IDToPlayerMap.get((short) player.onlineId());
return connected instanceof IsoPlayer target && player.username().equals(target.getUsername()) ? target : null;
}
}
@@ -0,0 +1,134 @@
package dev.overlord.zomboidforge.compat.b42.commands;
import org.jetbrains.annotations.Nullable;
import se.krka.kahlua.vm.KahluaTable;
import se.krka.kahlua.vm.KahluaTableIterator;
import zombie.inventory.InventoryItem;
import zombie.iso.IsoDirections;
import zombie.iso.objects.IsoDeadBody;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;
/**
* Conversion between the Kahlua tables of command arguments and the Java maps of the API. The
* types are those {@code TableNetworkUtils} sends: {@code String} and {@code Double} keys;
* {@code String}, {@code Double}, {@code Boolean}, table, {@code InventoryItem},
* {@code IsoDirections}, and {@code IsoDeadBody} values.
*/
public final class LuaTables
{
private LuaTables() {}
/** {@code table} as an unmodifiable map, nested tables as nested maps; empty for {@code null}. */
public static Map<Object, Object> toJava(@Nullable KahluaTable table)
{
if (table == null) return Map.of();
Map<Object, Object> map = new LinkedHashMap<>();
KahluaTableIterator iterator = table.iterator();
while (iterator.advance())
{
Object value = iterator.getValue();
map.put(iterator.getKey(), value instanceof KahluaTable nested ? LuaTables.toJava(nested) : value);
}
return Collections.unmodifiableMap(map);
}
/**
* A deep, unmodifiable copy of {@code args} in Lua's types: number keys and values become
* {@code Double}, lists become maps with the keys {@code 1.0}, {@code 2.0}, ....
*
* @throws IllegalArgumentException naming the first key or value that cannot be sent, or a
* map or list that contains itself
*/
public static Map<Object, Object> copy(Map<?, ?> args) { return LuaTables.copy(args, "args", Collections.newSetFromMap(new IdentityHashMap<>())); }
/** A new table with the entries of {@code args}, a result of {@link #copy}; nested maps become nested tables. */
public static KahluaTable toLua(Map<Object, Object> args, Supplier<KahluaTable> newTable)
{
KahluaTable table = newTable.get();
for (Map.Entry<Object, Object> entry : args.entrySet())
{
Object value = entry.getValue();
@SuppressWarnings("unchecked")
Object luaValue = value instanceof Map<?, ?> nested ? LuaTables.toLua((Map<Object, Object>) nested, newTable) : value;
table.rawset(entry.getKey(), luaValue);
}
return table;
}
private static Map<Object, Object> copy(Map<?, ?> map, String path, Set<Object> open)
{
if (!open.add(map)) throw new IllegalArgumentException("'" + path + "' contains itself.");
Map<Object, Object> copy = new LinkedHashMap<>();
for (Map.Entry<?, ?> entry : map.entrySet())
{
Object key = LuaTables.key(entry.getKey(), path);
String here = path + "[" + key + "]";
copy.put(key, LuaTables.value(entry.getValue(), here, open));
}
open.remove(map);
return Collections.unmodifiableMap(copy);
}
private static Map<Object, Object> copy(List<?> list, String path, Set<Object> open)
{
if (!open.add(list)) throw new IllegalArgumentException("'" + path + "' contains itself.");
Map<Object, Object> copy = new LinkedHashMap<>();
for (int i = 0; i < list.size(); i++) copy.put((double) (i + 1), LuaTables.value(list.get(i), path + "[" + (i + 1) + "]", open));
open.remove(list);
return Collections.unmodifiableMap(copy);
}
private static Object key(@Nullable Object key, String path)
{
if (key instanceof String) return key;
if (key instanceof Number number) return number.doubleValue();
throw new IllegalArgumentException("'" + path + "' has the key '" + key + "'" + LuaTables.typeOf(key) + "; keys are strings or numbers.");
}
private static Object value(@Nullable Object value, String path, Set<Object> open)
{
return switch (value)
{
case String string -> string;
case Boolean bool -> bool;
case Number number -> number.doubleValue();
case Map<?, ?> map -> LuaTables.copy(map, path, open);
case List<?> list -> LuaTables.copy(list, path, open);
case InventoryItem item -> item;
case IsoDirections direction -> direction;
case IsoDeadBody body -> body;
case null -> throw new IllegalArgumentException("'" + path + "' is null.");
default -> throw new IllegalArgumentException(
"'" + path + "' is a '" + value.getClass().getName() + "'; values are strings, numbers, booleans, maps, lists, inventory items, directions, or dead bodies."
);
};
}
private static String typeOf(@Nullable Object value) { return value == null ? "" : " ('" + value.getClass().getName() + "')"; }
}
@@ -1,6 +1,7 @@
/**
* Admin commands of mods in Build 42: checks for registered command classes and the lookup that
* mirrors {@code zombie.commands.CommandBase.findCommandCls}.
* Commands of mods in Build 42: checks for registered admin command classes and the lookup that
* mirrors {@code zombie.commands.CommandBase.findCommandCls}; client commands and the conversion
* of their Lua tables.
*
* @noinspection UnstableApiUsage, RedundantSuppression
*/
@@ -0,0 +1,54 @@
package dev.overlord.zomboidforge.compat.b42.hooks;
import dev.overlord.zomboidforge.api.ClientCommandEvent;
import dev.overlord.zomboidforge.compat.b42.ForgeInstance;
import dev.overlord.zomboidforge.compat.b42.commands.ClientCommandChannel;
import dev.overlord.zomboidforge.compat.b42.commands.LuaTables;
import org.jetbrains.annotations.Nullable;
import se.krka.kahlua.vm.KahluaTable;
import zombie.characters.IsoPlayer;
/**
* Hooks called by patched {@code zombie.network.GameServer.receiveClientCommand} code, on the main
* thread (client commands are queued for the main loop). Exceptions are caught here; the command
* then reaches Lua as in vanilla.
*/
@SuppressWarnings("CallToPrintStackTrace")
public final class ClientCommandHooks
{
private ClientCommandHooks() {}
/**
* Called directly before {@code LuaEventManager.triggerEvent("OnClientCommand", module, command, player, args)},
* after the vanilla checks (the player exists; {@code vehicle.remove} only with permission).
* Posts {@link ClientCommandEvent} when a mod listens for it.
*
* @param args {@code null} when the client sent no arguments
* @return {@code true} when a listener cancelled the event, which skips the Lua event
*/
public static boolean onClientCommand(String module, String command, IsoPlayer player, @Nullable KahluaTable args)
{
try
{
if (!ForgeInstance.FORGE.hasListeners(ClientCommandEvent.class)) return false;
ClientCommandEvent event = new ClientCommandEvent(
ClientCommandChannel.ref(player),
module, command,
LuaTables.toJava(args)
);
ForgeInstance.FORGE.post(event);
return event.isCancelled();
}
catch (Throwable t)
{
t.printStackTrace();
return false;
}
}
}
@@ -0,0 +1,127 @@
package dev.overlord.zomboidforge.compat.b42.commands;
import org.junit.jupiter.api.Test;
import se.krka.kahlua.j2se.KahluaTableImpl;
import se.krka.kahlua.vm.KahluaTable;
import zombie.iso.IsoDirections;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** Runs against the Kahlua classes of the server jar; {@code LuaManager.platform} is not used. */
class LuaTablesTest
{
private static final Supplier<KahluaTable> NEW_TABLE = () -> new KahluaTableImpl(new HashMap<>());
@Test
void convertsTablesToUnmodifiableMaps()
{
KahluaTable items = LuaTablesTest.NEW_TABLE.get();
items.rawset(1.0, "Base.Axe");
items.rawset(2.0, "Base.Saw");
KahluaTable table = LuaTablesTest.NEW_TABLE.get();
table.rawset("count", 3.0);
table.rawset("gift", true);
table.rawset("facing", IsoDirections.N);
table.rawset("items", items);
Map<Object, Object> args = LuaTables.toJava(table);
assertEquals(Map.of("count", 3.0, "gift", true, "facing", IsoDirections.N, "items", Map.of(1.0, "Base.Axe", 2.0, "Base.Saw")), args);
assertThrows(UnsupportedOperationException.class, () -> args.put("x", "y"));
assertThrows(UnsupportedOperationException.class, () -> ((Map<?, ?>) args.get("items")).clear());
}
@Test
void convertsMissingArgumentsToAnEmptyMap()
{
assertEquals(Map.of(), LuaTables.toJava(null));
}
@Test
void copiesJavaValuesInLuaTypes()
{
Map<String, Object> args = new LinkedHashMap<>();
args.put("count", 3);
args.put("price", 2.5F);
args.put("items", List.of("Base.Axe", "Base.Saw"));
args.put("seller", Map.of("name", "alice", 7, false));
assertEquals(
Map.of(
"count", 3.0,
"price", 2.5,
"items", Map.of(1.0, "Base.Axe", 2.0, "Base.Saw"),
"seller", Map.of("name", "alice", 7.0, false)
),
LuaTables.copy(args)
);
}
@Test
void copiesAtOnceSoLaterChangesAreNotSent()
{
Map<String, Object> args = new HashMap<>(Map.of("count", 1));
Map<Object, Object> copy = LuaTables.copy(args);
args.put("count", 2);
assertEquals(Map.of("count", 1.0), copy);
}
@Test
void buildsNestedTablesFromACopy()
{
KahluaTable table = LuaTables.toLua(LuaTables.copy(Map.of("count", 3, "items", List.of("Base.Axe"))), LuaTablesTest.NEW_TABLE);
assertEquals(3.0, table.rawget("count"));
KahluaTable items = (KahluaTable) table.rawget("items");
assertEquals("Base.Axe", items.rawget(1.0));
assertNull(items.rawget(2.0));
assertEquals(1, items.len());
}
@Test
void namesTheFirstValueThatCannotBeSent()
{
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class,
() -> LuaTables.copy(Map.of("seller", Map.of("since", new Object())))
);
assertTrue(e.getMessage().startsWith("'args[seller][since]' is a 'java.lang.Object'; values are strings, numbers, booleans,"), e.getMessage());
}
@Test
void rejectsNullValuesOtherKeysAndCycles()
{
Map<Object, Object> withNull = new HashMap<>();
withNull.put("name", null);
Map<Object, Object> withObjectKey = new HashMap<>();
withObjectKey.put(true, "yes");
List<Object> cycle = new ArrayList<>();
cycle.add(cycle);
assertEquals("'args[name]' is null.", assertThrows(IllegalArgumentException.class, () -> LuaTables.copy(withNull)).getMessage());
assertEquals(
"'args' has the key 'true' ('java.lang.Boolean'); keys are strings or numbers.",
assertThrows(IllegalArgumentException.class, () -> LuaTables.copy(withObjectKey)).getMessage()
);
assertEquals("'args[list][1]' contains itself.", assertThrows(IllegalArgumentException.class, () -> LuaTables.copy(Map.of("list", cycle))).getMessage());
}
}