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

+66 -14
View File
@@ -164,20 +164,21 @@ public final class ShopMod extends Mod
Methods of `Mod`, usable from the constructor on (also in field initializers): Methods of `Mod`, usable from the constructor on (also in field initializers):
| Method | Returns | Use | | Method | Returns | Use |
|-----------------|-----------------|---------------------------------------------------------------| |--------------------|------------------|---------------------------------------------------------------|
| `id()` | `String` | the mod's id from `mod.toml` | | `id()` | `String` | the mod's id from `mod.toml` |
| `version()` | `String` | the mod's version from `mod.toml` | | `version()` | `String` | the mod's version from `mod.toml` |
| `gameVersion()` | `GameVersion` | the running Project Zomboid version | | `gameVersion()` | `GameVersion` | the running Project Zomboid version |
| `config()` | `ModConfig` | settings from `config.toml`, bound to records or read by path | | `config()` | `ModConfig` | settings from `config.toml`, bound to records or read by path |
| `logger()` | `System.Logger` | messages in the Project Zomboid log, marked with the mod's id | | `logger()` | `System.Logger` | messages in the Project Zomboid log, marked with the mod's id |
| `directory()` | `Path` | the mod's folder, `<forge>/mods/<id>` | | `directory()` | `Path` | the mod's folder, `<forge>/mods/<id>` |
| `events()` | `Events` | event listeners | | `events()` | `Events` | event listeners |
| `main()` | `MainThread` | code that touches game objects | | `main()` | `MainThread` | code that touches game objects |
| `modThread()` | `ModThread` | the mod's own work, one task at a time | | `modThread()` | `ModThread` | the mod's own work, one task at a time |
| `async()` | `AsyncExecutor` | blocking work such as HTTP calls or file I/O | | `async()` | `AsyncExecutor` | blocking work such as HTTP calls or file I/O |
| `storage()` | `ModStorage` | the mod's tables in the world's `zomboidforge.db` | | `storage()` | `ModStorage` | the mod's tables in the world's `zomboidforge.db` |
| `commands()` | `Commands` | admin commands for chat, the server console, and RCON | | `commands()` | `Commands` | admin commands for chat, the server console, and RCON |
| `clientCommands()` | `ClientCommands` | server commands to clients, received by their Lua mods |
## Threads ## Threads
@@ -259,6 +260,57 @@ public void onLoad() { this.commands().register(HelloCommand.class); }
that the work started. that the work started.
- Project Zomboid's commands are looked up first; mods' commands follow in load order. - Project Zomboid's commands are looked up first; mods' commands follow in load order.
## Client commands
A Java mod on the server and a Lua mod on the client (for example from the Workshop) talk
through Project Zomboid's command channel, so players keep the official client.
Client to server: the Lua mod calls `sendClientCommand`, and the server posts
`ClientCommandEvent` on the main thread.
```lua
sendClientCommand(getPlayer(), "Shop", "buy", { item = "Base.Axe", count = 2 })
```
```java
this.events().onMain(ClientCommandEvent.class, event ->
{
if (!event.module().equals("Shop")) return;
event.cancel(); // Lua's OnClientCommand does not see it
String item = (String) event.args().get("item");
int count = ((Double) event.args().get("count")).intValue();
// ...
this.clientCommands().send(event.player(), "Shop", "bought", Map.of("item", item, "count", count));
});
```
Server to client: `clientCommands().send(player, ...)` and `sendToAll(...)`; the Lua mod
receives them in `Events.OnServerCommand`.
```lua
Events.OnServerCommand.Add(function(module, command, args)
if module == "Shop" and command == "bought" then print(args.item, args.count) end
end)
```
- **Every** client command is posted, including those of Project Zomboid (`vehicle`,
`player`, ...) and of other mods; filter by `module()`. The event is a `MainThreadEvent`.
- **`cancel()`** stops Project Zomboid from passing the command to Lua's `OnClientCommand`.
Every listener still runs; `isCancelled()` tells whether another one cancelled.
- **`args()`** is the Lua table as an unmodifiable map: keys are `String` or `Double` (Lua
arrays have the keys `1.0`, `2.0`, ...); values are `String`, `Double` (every Lua number),
`Boolean`, nested maps, or game objects (inventory items, directions, dead bodies). It is
empty when the client sent no table.
- **`player()`** is a `PlayerRef` (online id and username), a value that stays valid on other
threads and after the player left. Sending to a player who left sends nothing.
- **Sending** works from any thread. The arguments are copied and checked at once
(`IllegalArgumentException` for unsupported types, `null`, or cycles); numbers become Lua
numbers, lists become Lua arrays. The command is sent on the main thread: at once when
called there, otherwise as one of the mod's queued main-thread tasks.
- Client commands come from players and can be forged by a modified client. Check every
argument and the player's rights before acting on it.
## Storage ## Storage
Mod data belongs in `storage()`: tables in `zomboidforge.db`, a SQLite database in the world's Mod data belongs in `storage()`: tables in `zomboidforge.db`, a SQLite database in the world's
@@ -0,0 +1,14 @@
package dev.overlord.zomboidforge.api;
/**
* An event whose default action, what Project Zomboid does after the event, can be prevented.
* Only listeners on the main thread can cancel: the default action runs once every main-thread
* listener returned. Every listener is called, also after one cancelled.
*/
public interface Cancellable
{
/** Prevents the default action. */
void cancel();
boolean isCancelled();
}
@@ -0,0 +1,55 @@
package dev.overlord.zomboidforge.api;
import java.util.Map;
import java.util.Objects;
/**
* A client command arrived: a client called Lua's {@code sendClientCommand(module, command, args)}.
* Posted on the main thread for every client command, including those of Project Zomboid and of
* Lua mods, so listeners filter by {@link #module()}.
*
* <p>Default action: Project Zomboid passes the command to Lua's {@code Events.OnClientCommand}.
* {@link #cancel()} prevents that, for example when a Java mod handles the module itself.
*
* <p>{@link #args()} is the Lua table converted to Java: keys are {@code String} or
* {@code Double} (Lua arrays have the keys {@code 1.0}, {@code 2.0}, ...), values are
* {@code String}, {@code Double}, {@code Boolean}, a nested {@code Map} of the same kind, or a
* game object that Project Zomboid sends with commands (in Build 42 an inventory item, an
* {@code IsoDirections}, or a dead body). The maps cannot be modified.
*/
public final class ClientCommandEvent implements MainThreadEvent, Cancellable
{
private final PlayerRef player;
private final String module;
private final String command;
private final Map<Object, Object> args;
private boolean cancelled;
/** @param args the converted arguments; empty when the client sent none */
public ClientCommandEvent(PlayerRef player, String module, String command, Map<Object, Object> args)
{
this.player = Objects.requireNonNull(player, "player");
this.module = Objects.requireNonNull(module, "module");
this.command = Objects.requireNonNull(command, "command");
this.args = Objects.requireNonNull(args, "args");
}
/** The player who sent the command. */
public PlayerRef player() { return this.player; }
public String module() { return this.module; }
public String command() { return this.command; }
public Map<Object, Object> args() { return this.args; }
@Override
public void cancel() { this.cancelled = true; }
@Override
public boolean isCancelled() { return this.cancelled; }
@Override
public String toString() { return "ClientCommandEvent[" + this.player + ", " + this.module + "." + this.command + ", " + this.args + (this.cancelled ? ", cancelled" : "") + "]"; }
}
@@ -0,0 +1,35 @@
package dev.overlord.zomboidforge.api;
import java.util.Map;
/**
* Server commands to clients, the reply channel to {@link ClientCommandEvent}: a client receives
* them in Lua's {@code Events.OnServerCommand(module, command, args)}. Together, a Java mod on the
* server and a Lua mod on the client exchange commands while players keep the official client.
*
* <p>{@code args} becomes a Lua table: keys are {@code String} or a {@code Number} (sent as a
* Lua number), values are {@code String}, {@code Number}, {@code Boolean}, a nested {@code Map}, a
* {@code List} (a Lua array, indexed from 1), or a game object that Project Zomboid sends with
* commands (see {@link ClientCommandEvent}). {@code null} keys or values, and cycles, are not
* allowed. An empty map sends no arguments; the client then receives {@code nil}.
*
* <p>The methods can be called on any thread. The arguments are checked at once; the command is
* sent on the main thread, at once when called there, otherwise with the mod's queued
* main-thread tasks.
*/
public interface ClientCommands
{
/**
* Sends a command to {@code player}. Nothing is sent when the player is no longer connected.
*
* @throws IllegalArgumentException when {@code args} contains a key or value that cannot be sent
*/
void send(PlayerRef player, String module, String command, Map<?, ?> args);
/**
* Sends a command to every connected client.
*
* @throws IllegalArgumentException when {@code args} contains a key or value that cannot be sent
*/
void sendToAll(String module, String command, Map<?, ?> args);
}
@@ -87,4 +87,7 @@ public abstract class Mod
/** Admin command registration. */ /** Admin command registration. */
protected final Commands commands() { return this.context.commands(); } protected final Commands commands() { return this.context.commands(); }
/** Server commands to clients, received by their Lua mods. */
protected final ClientCommands clientCommands() { return this.context.clientCommands(); }
} }
@@ -45,4 +45,7 @@ public interface ModContext
/** Admin command registration. */ /** Admin command registration. */
Commands commands(); Commands commands();
/** Server commands to clients, received by their Lua mods. */
ClientCommands clientCommands();
} }
@@ -0,0 +1,19 @@
package dev.overlord.zomboidforge.api;
import java.util.Objects;
/**
* A connected player, by value: usable on any thread and after the player left. Project
* Zomboid reuses online ids of players who left, so ZomboidForge matches both the id and the
* username before it acts on a player.
*
* @param onlineId the player's online id while connected
* @param username the player's account name
*/
public record PlayerRef(int onlineId, String username)
{
public PlayerRef
{
Objects.requireNonNull(username, "username");
}
}
@@ -20,6 +20,7 @@ public final class B42PatchSet implements PatchSet
new BackupStoragePatch(), new BackupStoragePatch(),
new CommandLookupPatch(), new CommandLookupPatch(),
new CommandListPatch(), new CommandListPatch(),
new ClientCommandPatch(),
new IsoZombieVehiclePerformancePatch(), new IsoZombieVehiclePerformancePatch(),
new IsoZombieNetworkComponentPerformancePatch(), new IsoZombieNetworkComponentPerformancePatch(),
new IsoZombieSpotChancePerformancePatch(), new IsoZombieSpotChancePerformancePatch(),
@@ -0,0 +1,43 @@
package dev.overlord.zomboidforge.compat.b42.patches;
import dev.overlord.zomboidforge.patcher.Anchor;
import dev.overlord.zomboidforge.patcher.Hook;
import dev.overlord.zomboidforge.patcher.HookArgument;
import dev.overlord.zomboidforge.patcher.Patches.CancellableHookPatch;
import java.util.List;
/**
* Makes the Lua event {@code OnClientCommand} in {@code GameServer.receiveClientCommand} depend on
* {@code ClientCommandHooks.onClientCommand(module, command, player, tbl)}:
*
* <pre>{@code
* if (!ClientCommandHooks.onClientCommand(module, command, player, tbl))
* LuaEventManager.triggerEvent("OnClientCommand", module, command, player, tbl);
* }</pre>
*
* The arguments are the method's local variables of these names.
*/
public final class ClientCommandPatch extends CancellableHookPatch
{
private static final Anchor.Call ANCHOR = new Anchor.Call(
new Anchor.Method("receiveClientCommand", "(Lzombie/core/network/ByteBufferReader;Lzombie/core/raknet/UdpConnection;S)V"),
"zombie/Lua/LuaEventManager", "triggerEvent", "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)V"
);
private static final Hook HOOK = new Hook(
"dev/overlord/zomboidforge/compat/b42/hooks/ClientCommandHooks", "onClientCommand",
"(Ljava/lang/String;Ljava/lang/String;Lzombie/characters/IsoPlayer;Lse/krka/kahlua/vm/KahluaTable;)Z"
);
private static final List<HookArgument> ARGUMENTS = List.of(
new HookArgument.Local("module"),
new HookArgument.Local("command"),
new HookArgument.Local("player"),
new HookArgument.Local("tbl")
);
public ClientCommandPatch() {
super("zombie/network/GameServer", ClientCommandPatch.ANCHOR, ClientCommandPatch.HOOK, ClientCommandPatch.ARGUMENTS);
}
}
@@ -1,12 +1,15 @@
package dev.overlord.zomboidforge.compat.b42; 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.compat.b42.commands.ModCommands;
import dev.overlord.zomboidforge.core.Forge; import dev.overlord.zomboidforge.core.Forge;
/** The one {@link Forge} of the server, shared by the hook classes. */ /** The one {@link Forge} of the server, shared by the hook classes. */
public final class ForgeInstance 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() {} 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 * Commands of mods in Build 42: checks for registered admin command classes and the lookup that
* mirrors {@code zombie.commands.CommandBase.findCommandCls}. * mirrors {@code zombie.commands.CommandBase.findCommandCls}; client commands and the conversion
* of their Lua tables.
* *
* @noinspection UnstableApiUsage, RedundantSuppression * @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());
}
}
@@ -2,11 +2,14 @@ package dev.overlord.zomboidforge.core;
import dev.overlord.zomboidforge.api.Event; import dev.overlord.zomboidforge.api.Event;
import dev.overlord.zomboidforge.api.GameVersion; import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.api.MainThread;
import dev.overlord.zomboidforge.api.Mod; import dev.overlord.zomboidforge.api.Mod;
import dev.overlord.zomboidforge.api.TickEvent; import dev.overlord.zomboidforge.api.TickEvent;
import dev.overlord.zomboidforge.api.ZomboidForge; import dev.overlord.zomboidforge.api.ZomboidForge;
import dev.overlord.zomboidforge.api.storage.StorageException; import dev.overlord.zomboidforge.api.storage.StorageException;
import dev.overlord.zomboidforge.core.commands.ClientCommandSender;
import dev.overlord.zomboidforge.core.commands.CommandRegistry; import dev.overlord.zomboidforge.core.commands.CommandRegistry;
import dev.overlord.zomboidforge.core.commands.ModClientCommands;
import dev.overlord.zomboidforge.core.config.ForgeSettings; import dev.overlord.zomboidforge.core.config.ForgeSettings;
import dev.overlord.zomboidforge.core.mods.GameClasses; import dev.overlord.zomboidforge.core.mods.GameClasses;
import dev.overlord.zomboidforge.core.mods.ModDiscovery; import dev.overlord.zomboidforge.core.mods.ModDiscovery;
@@ -54,6 +57,7 @@ public final class Forge
private final Path directory; private final Path directory;
private final @Nullable ModVersion api; private final @Nullable ModVersion api;
private final CommandRegistry commands; private final CommandRegistry commands;
private final ClientCommandSender clientCommands;
private volatile List<ModLoader.LoadedMod> mods = List.of(); private volatile List<ModLoader.LoadedMod> mods = List.of();
private volatile ForgeSettings settings = ForgeSettings.DEFAULTS; private volatile ForgeSettings settings = ForgeSettings.DEFAULTS;
@@ -63,14 +67,16 @@ public final class Forge
* @param directory the ZomboidForge directory * @param directory the ZomboidForge directory
* @param api the API version mods are checked against, or {@code null} to skip the * @param api the API version mods are checked against, or {@code null} to skip the
* check * check
* @param commands checks the command classes that mods register against the running game * @param commands checks the command classes that mods register against the running
* version * game version
* @param clientCommands sends the mods' server commands to clients in the running game version
*/ */
public Forge(Path directory, @Nullable ModVersion api, CommandRegistry.Validator commands) public Forge(Path directory, @Nullable ModVersion api, CommandRegistry.Validator commands, ClientCommandSender clientCommands)
{ {
this.directory = directory; this.directory = directory;
this.api = api; this.api = api;
this.commands = new CommandRegistry(commands, this::commandsOpen); this.commands = new CommandRegistry(commands, this::commandsOpen);
this.clientCommands = clientCommands;
} }
/** /**
@@ -78,17 +84,18 @@ public final class Forge
* version from {@link ZomboidForge#VERSION}. Builds without a release version ({@code dev}, * version from {@link ZomboidForge#VERSION}. Builds without a release version ({@code dev},
* {@code 0.0.0-...}) skip the API check. * {@code 0.0.0-...}) skip the API check.
* *
* @param commands checks the command classes that mods register against the running game * @param commands checks the command classes that mods register against the running
* version * game version
* @param clientCommands sends the mods' server commands to clients in the running game version
*/ */
public static Forge fromSystemProperties(CommandRegistry.Validator commands) public static Forge fromSystemProperties(CommandRegistry.Validator commands, ClientCommandSender clientCommands)
{ {
Path directory = Path.of(System.getProperty(Forge.DIRECTORY_PROPERTY, Forge.DEFAULT_DIRECTORY)); Path directory = Path.of(System.getProperty(Forge.DIRECTORY_PROPERTY, Forge.DEFAULT_DIRECTORY));
ModVersion api = ModVersion.tryParse(ZomboidForge.VERSION) ModVersion api = ModVersion.tryParse(ZomboidForge.VERSION)
.filter(version -> version.major() != 0 || version.minor() != 0 || version.patch() != 0) .filter(version -> version.major() != 0 || version.minor() != 0 || version.patch() != 0)
.orElse(null); .orElse(null);
return new Forge(directory, api, commands); return new Forge(directory, api, commands, clientCommands);
} }
public Lifecycle.Phase phase() { return this.lifecycle.phase(); } public Lifecycle.Phase phase() { return this.lifecycle.phase(); }
@@ -197,6 +204,9 @@ public final class Forge
*/ */
public void post(Event event) { this.events.post(event); } public void post(Event event) { this.events.post(event); }
/** Whether any mod listens for {@code type}, so a hook can skip creating the event. */
public boolean hasListeners(Class<? extends Event> type) { return this.events.hasListeners(type); }
/** /**
* Pauses storage for a backup of the save folder (see {@link StorageDatabase#backupStarted()}). * Pauses storage for a backup of the save folder (see {@link StorageDatabase#backupStarted()}).
* Called by the patched {@code ZipBackup.makeBackupFile}, on the thread that makes the backup. * Called by the patched {@code ZipBackup.makeBackupFile}, on the thread that makes the backup.
@@ -268,14 +278,16 @@ public final class Forge
ModThreads.ModExecutors executors = this.threads.create(id, logger); ModThreads.ModExecutors executors = this.threads.create(id, logger);
StorageDatabase storage = Objects.requireNonNull(this.storage, "storage"); StorageDatabase storage = Objects.requireNonNull(this.storage, "storage");
MainThread main = this.queue.forMod(id, logger);
return new ModServices( return new ModServices(
this.events.forMod(id, executors.modThread(), logger), this.events.forMod(id, executors.modThread(), logger),
this.queue.forMod(id, logger), main,
executors.modThread(), executors.modThread(),
executors.async(), executors.async(),
new ModTables(id, storage, logger), new ModTables(id, storage, logger),
this.commands.forMod(logger) this.commands.forMod(logger),
new ModClientCommands(this.clientCommands, main)
); );
} }
} }
@@ -0,0 +1,21 @@
package dev.overlord.zomboidforge.core.commands;
import dev.overlord.zomboidforge.api.PlayerRef;
import org.jetbrains.annotations.Nullable;
import java.util.Map;
/** Sends server commands to clients; implemented by the compat module of the running game version. */
@FunctionalInterface
public interface ClientCommandSender
{
/**
* Checks {@code args} on the calling thread and returns the action that converts and sends
* the command, which runs on the main thread.
*
* @param player the receiving player, or {@code null} for every connected client
* @throws IllegalArgumentException naming a key or value that cannot be sent
*/
Runnable prepare(@Nullable PlayerRef player, String module, String command, Map<?, ?> args);
}
@@ -0,0 +1,45 @@
package dev.overlord.zomboidforge.core.commands;
import dev.overlord.zomboidforge.api.ClientCommands;
import dev.overlord.zomboidforge.api.MainThread;
import dev.overlord.zomboidforge.api.PlayerRef;
import java.util.Map;
import java.util.Objects;
/**
* The {@link ClientCommands} of one mod: checks on the calling thread, sends through the mod's
* {@link MainThread}, so a command sent off the main thread is one of the mod's queued tasks.
*/
public final class ModClientCommands implements ClientCommands
{
private final ClientCommandSender sender;
private final MainThread main;
public ModClientCommands(ClientCommandSender sender, MainThread main)
{
this.sender = Objects.requireNonNull(sender);
this.main = Objects.requireNonNull(main);
}
@Override
public void send(PlayerRef player, String module, String command, Map<?, ?> args)
{
Objects.requireNonNull(player, "player");
this.main.execute(this.sender.prepare(player, ModClientCommands.require(module, "module"), ModClientCommands.require(command, "command"), Objects.requireNonNull(args, "args")));
}
@Override
public void sendToAll(String module, String command, Map<?, ?> args)
{
this.main.execute(this.sender.prepare(null, ModClientCommands.require(module, "module"), ModClientCommands.require(command, "command"), Objects.requireNonNull(args, "args")));
}
private static String require(String value, String name)
{
if (Objects.requireNonNull(value, name).isEmpty()) throw new IllegalArgumentException("'" + name + "' is empty.");
return value;
}
}
@@ -1,5 +1,6 @@
/** /**
* Admin commands of loaded mods: the registry that the compat hooks consult. * Commands of loaded mods: the registry of admin commands that the compat hooks consult, and
* server commands to clients.
* *
* @noinspection UnstableApiUsage, RedundantSuppression * @noinspection UnstableApiUsage, RedundantSuppression
*/ */
@@ -1,6 +1,7 @@
package dev.overlord.zomboidforge.core.mods; package dev.overlord.zomboidforge.core.mods;
import dev.overlord.zomboidforge.api.AsyncExecutor; import dev.overlord.zomboidforge.api.AsyncExecutor;
import dev.overlord.zomboidforge.api.ClientCommands;
import dev.overlord.zomboidforge.api.Commands; import dev.overlord.zomboidforge.api.Commands;
import dev.overlord.zomboidforge.api.Events; import dev.overlord.zomboidforge.api.Events;
import dev.overlord.zomboidforge.api.GameVersion; import dev.overlord.zomboidforge.api.GameVersion;
@@ -37,18 +38,19 @@ public final class ModLoader
public record LoadedMod(ModDescriptor descriptor, Path directory, ClassLoader classLoader, Mod mod) {} public record LoadedMod(ModDescriptor descriptor, Path directory, ClassLoader classLoader, Mod mod) {}
private record Context( private record Context(
String id, String id,
String version, String version,
GameVersion gameVersion, GameVersion gameVersion,
System.Logger logger, System.Logger logger,
Path directory, Path directory,
ModConfig config, ModConfig config,
Events events, Events events,
MainThread main, MainThread main,
ModThread modThread, ModThread modThread,
AsyncExecutor async, AsyncExecutor async,
ModStorage storage, ModStorage storage,
Commands commands Commands commands,
ClientCommands clientCommands
) implements ModContext {} ) implements ModContext {}
private ModLoader() {} private ModLoader() {}
@@ -96,7 +98,8 @@ public final class ModLoader
provided.modThread(), provided.modThread(),
provided.async(), provided.async(),
provided.storage(), provided.storage(),
provided.commands() provided.commands(),
provided.clientCommands()
); );
loaded.add(new LoadedMod(descriptor, candidate.directory(), loader, ModLoader.create(descriptor, loader, context))); loaded.add(new LoadedMod(descriptor, candidate.directory(), loader, ModLoader.create(descriptor, loader, context)));
@@ -1,15 +1,23 @@
package dev.overlord.zomboidforge.core.mods; package dev.overlord.zomboidforge.core.mods;
import dev.overlord.zomboidforge.api.AsyncExecutor; import dev.overlord.zomboidforge.api.AsyncExecutor;
import dev.overlord.zomboidforge.api.ClientCommands;
import dev.overlord.zomboidforge.api.Commands; import dev.overlord.zomboidforge.api.Commands;
import dev.overlord.zomboidforge.api.Events; import dev.overlord.zomboidforge.api.Events;
import dev.overlord.zomboidforge.api.MainThread; import dev.overlord.zomboidforge.api.MainThread;
import dev.overlord.zomboidforge.api.ModThread; import dev.overlord.zomboidforge.api.ModThread;
import dev.overlord.zomboidforge.api.storage.ModStorage; import dev.overlord.zomboidforge.api.storage.ModStorage;
/** The threads, event and command registration, and storage of one mod, created before its entry point. */ /** The threads, event and command registration, storage, and client commands of one mod, created before its entry point. */
public record ModServices(Events events, MainThread main, ModThread modThread, AsyncExecutor async, ModStorage storage, Commands commands) public record ModServices(
{ Events events,
MainThread main,
ModThread modThread,
AsyncExecutor async,
ModStorage storage,
Commands commands,
ClientCommands clientCommands
) {
/** Creates the services of one mod. */ /** Creates the services of one mod. */
@FunctionalInterface @FunctionalInterface
public interface Factory public interface Factory
@@ -51,6 +51,9 @@ class ForgeTest
/** Classes that mods registered as commands, as {@code "<name> after <registered count>"}; every class is accepted. */ /** Classes that mods registered as commands, as {@code "<name> after <registered count>"}; every class is accepted. */
private final List<String> checkedCommands = new ArrayList<>(); private final List<String> checkedCommands = new ArrayList<>();
/** Client commands that mods sent, as {@code "<player or all> <module>.<command> <args>"}. */
private final List<String> sentClientCommands = new ArrayList<>();
@BeforeEach @BeforeEach
void setUp() throws IOException void setUp() throws IOException
{ {
@@ -64,7 +67,12 @@ class ForgeTest
private Forge forge() private Forge forge()
{ {
return new Forge(this.directory, ModVersion.parse("0.3.0"), (command, registered) -> this.checkedCommands.add(command.getName() + " after " + registered.size())); return new Forge(
this.directory,
ModVersion.parse("0.3.0"),
(command, registered) -> this.checkedCommands.add(command.getName() + " after " + registered.size()),
(player, module, command, args) -> () -> this.sentClientCommands.add((player == null ? "all" : player.username()) + " " + module + "." + command + " " + args)
);
} }
private Forge load() throws ModLoadException private Forge load() throws ModLoadException
@@ -133,6 +141,19 @@ class ForgeTest
assertEquals(1, forge.commands().size()); assertEquals(1, forge.commands().size());
} }
@Test
void modsSendClientCommandsThroughTheGameSender() throws Exception
{
TestMods.folder(this.mods, "commands", TestMods.toml("commands", CommandMod.class.getName(), ""), Map.of(
"testmods/CommandMod", TestMods.classFile(CommandMod.class),
"testmods/CommandMod$Command", TestMods.classFile(CommandMod.Command.class)
));
this.load().started();
assertEquals(List.of("all Test.started {count=1}"), this.sentClientCommands);
}
@Test @Test
void modsSeeTheirContextAndSettingsInTheConstructor() throws Exception void modsSeeTheirContextAndSettingsInTheConstructor() throws Exception
{ {
@@ -0,0 +1,107 @@
package dev.overlord.zomboidforge.core.commands;
import dev.overlord.zomboidforge.api.ClientCommands;
import dev.overlord.zomboidforge.api.PlayerRef;
import dev.overlord.zomboidforge.core.RecordingLogger;
import dev.overlord.zomboidforge.core.runtime.MainThreadQueue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
/** The test thread is the main thread. */
class ModClientCommandsTest
{
private static final PlayerRef PLAYER = new PlayerRef(3, "alice");
/** What the sender prepared ({@code "prepare ..."}) and sent ({@code "send ... on <thread>"}). */
private final List<String> log = new CopyOnWriteArrayList<>();
/** Records both steps; rejects arguments that contain the key {@code "bad"}. */
private final ClientCommandSender sender = (player, module, command, args) ->
{
if (args.containsKey("bad")) throw new IllegalArgumentException("'args[bad]' cannot be sent.");
String target = player == null ? "all" : player.username();
this.log.add("prepare " + target + " " + module + "." + command + " " + args);
return () -> this.log.add("send " + target + " " + module + "." + command + " on " + Thread.currentThread().getName());
};
private MainThreadQueue queue;
private ClientCommands commands;
@BeforeEach
void setUp()
{
this.queue = new MainThreadQueue(Duration.ofSeconds(10));
this.queue.bindToCurrentThread();
this.commands = new ModClientCommands(this.sender, this.queue.forMod("shop", new RecordingLogger()));
}
@Test
void sendsAtOnceOnTheMainThread()
{
this.commands.send(ModClientCommandsTest.PLAYER, "Shop", "bought", Map.of("item", "Base.Axe"));
this.commands.sendToAll("Shop", "opened", Map.of());
String main = Thread.currentThread().getName();
assertEquals(
List.of(
"prepare alice Shop.bought {item=Base.Axe}", "send alice Shop.bought on " + main,
"prepare all Shop.opened {}", "send all Shop.opened on " + main
),
this.log
);
}
@Test
void checksOnTheCallingThreadAndSendsOnTheMainThreadLater() throws InterruptedException
{
Thread other = Thread.ofPlatform().name("worker").start(() -> this.commands.sendToAll("Shop", "opened", Map.of()));
other.join();
assertEquals(List.of("prepare all Shop.opened {}"), this.log);
this.queue.drain();
assertEquals(List.of("prepare all Shop.opened {}", "send all Shop.opened on " + Thread.currentThread().getName()), this.log);
}
@Test
void rejectedArgumentsThrowToTheCallerOnAnyThread() throws InterruptedException
{
AtomicReference<Throwable> thrown = new AtomicReference<>();
Thread other = Thread.ofPlatform().start(() ->
{
try { this.commands.sendToAll("Shop", "opened", Map.of("bad", 1)); }
catch (Throwable t) { thrown.set(t); }
});
other.join();
assertInstanceOf(IllegalArgumentException.class, thrown.get());
this.queue.drain();
assertEquals(List.of(), this.log);
}
@Test
void rejectsEmptyModuleAndCommand()
{
assertThrows(IllegalArgumentException.class, () -> this.commands.sendToAll("", "opened", Map.of()));
assertThrows(IllegalArgumentException.class, () -> this.commands.send(ModClientCommandsTest.PLAYER, "Shop", "", Map.of()));
assertEquals(List.of(), this.log);
}
}
+6 -1
View File
@@ -4,9 +4,12 @@ import dev.overlord.zomboidforge.api.Mod;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.Map;
/** /**
* Entry point that tests package into a mod jar. Registers {@link Command} in {@code onLoad()} * Entry point that tests package into a mod jar. Registers {@link Command} in {@code onLoad()}
* and tries again in {@code onServerStarted()}, which is too late. * and tries again in {@code onServerStarted()}, which is too late; sends a client command to
* every client there.
*/ */
public final class CommandMod extends Mod public final class CommandMod extends Mod
{ {
@@ -23,5 +26,7 @@ public final class CommandMod extends Mod
{ {
try { this.commands().register(CommandMod.Command.class); } try { this.commands().register(CommandMod.Command.class); }
catch (RuntimeException e) { this.lateRegistration = e; } catch (RuntimeException e) { this.lateRegistration = e; }
this.clientCommands().sendToAll("Test", "started", Map.of("count", 1));
} }
} }