Compare commits
3
Commits
22077514fe
...
v0.4.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a0cd30a0d7 | ||
|
|
a351fc237c | ||
|
|
af7174e128 |
No files matched your search
+114
-13
@@ -164,19 +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 |
|
||||||
|
| `clientCommands()` | `ClientCommands` | server commands to clients, received by their Lua mods |
|
||||||
|
|
||||||
## Threads
|
## Threads
|
||||||
|
|
||||||
@@ -210,6 +212,105 @@ Listeners are matched by the event's exact class. Events that carry live game ob
|
|||||||
removed after ten failures; both `onMain` and `onModThread` return a `Subscription` to remove
|
removed after ten failures; both `onMain` and `onModThread` return a `Subscription` to remove
|
||||||
it earlier.
|
it earlier.
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
Admin commands work wherever Project Zomboid's own commands work: in the in-game chat
|
||||||
|
(`/zfhello`), the server console, and RCON. They use Project Zomboid's command framework, so the
|
||||||
|
mod declares `game` versions. In Build 42 a command is a subclass of
|
||||||
|
`zombie.commands.CommandBase`:
|
||||||
|
|
||||||
|
```java
|
||||||
|
@CommandName(name = "zfhello")
|
||||||
|
@CommandArgs(optional = "(.+)")
|
||||||
|
@CommandHelp(helpText = "zfhello [name]: greets", shouldTranslated = false)
|
||||||
|
@RequiredCapability(requiredCapability = Capability.LoginOnServer)
|
||||||
|
public class HelloCommand extends CommandBase
|
||||||
|
{
|
||||||
|
public HelloCommand(String username, Role role, String command, UdpConnection connection) { super(username, role, command, connection); }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected String Command()
|
||||||
|
{
|
||||||
|
String name = this.getCommandArg(0);
|
||||||
|
return "Hello " + (name == null ? this.getExecutorUsername() : name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```java
|
||||||
|
@Override
|
||||||
|
public void onLoad() { this.commands().register(HelloCommand.class); }
|
||||||
|
```
|
||||||
|
|
||||||
|
- **Registration** happens in the entry point's constructor or `onLoad()`; later calls throw.
|
||||||
|
`register` checks the class and throws `IllegalArgumentException` listing every problem,
|
||||||
|
which stops the server like any other exception in `onLoad()`.
|
||||||
|
- **The class** is public and not abstract, with one public constructor
|
||||||
|
`(String, Role, String, UdpConnection)`.
|
||||||
|
- **Names** (`@CommandName`, repeatable for aliases) consist of letters, digits, and `_` and
|
||||||
|
differ, ignoring case, from the names of Project Zomboid's commands and other mods' commands.
|
||||||
|
A name matches when it is the first word of the input, ignoring case.
|
||||||
|
- **`@RequiredCapability`** is required: Project Zomboid refuses to run a command without one.
|
||||||
|
RCON and the server console run commands with the default admin role.
|
||||||
|
- **`@CommandArgs`** (regular expressions for the arguments; the capture groups become
|
||||||
|
`getCommandArg(n)`) and **`@CommandHelp`** (`help zfhello` and the `help` list; with
|
||||||
|
`shouldTranslated = false` the text is used as written) are optional.
|
||||||
|
- **`Command()`** runs on the main thread, for every use on a new instance; its return value
|
||||||
|
is the reply. Long work belongs on `modThread()` or `async()`; the reply then only confirms
|
||||||
|
that the work started.
|
||||||
|
- 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);
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package dev.overlord.zomboidforge.api;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registration of admin commands. A registered command works wherever Project Zomboid's own
|
||||||
|
* admin commands work: in the in-game chat ({@code /name}), the server console, and RCON. It
|
||||||
|
* is looked up after the commands of Project Zomboid and runs on the main thread.
|
||||||
|
*
|
||||||
|
* <p>A command is a class of the running Project Zomboid version's command framework, so a mod
|
||||||
|
* that registers commands declares {@code game} versions in {@code mod.toml}. In Build 42 it is
|
||||||
|
* a public, non-abstract subclass of {@code zombie.commands.CommandBase} with:
|
||||||
|
* <ul>
|
||||||
|
* <li>one public constructor {@code (String username, Role role, String command, UdpConnection connection)},
|
||||||
|
* which passes its arguments to {@code super};</li>
|
||||||
|
* <li>at least one {@code @CommandName}; names consist of letters, digits, and {@code _}, and
|
||||||
|
* differ (ignoring case) from every name of Project Zomboid and of other mods;</li>
|
||||||
|
* <li>at least one {@code @RequiredCapability}; Project Zomboid refuses to run a command
|
||||||
|
* without one;</li>
|
||||||
|
* <li>optionally {@code @CommandArgs} (argument patterns) and {@code @CommandHelp}
|
||||||
|
* ({@code help <name>} and the {@code help} list).</li>
|
||||||
|
* </ul>
|
||||||
|
* Project Zomboid creates a new instance for every use and calls its {@code Command()}, whose
|
||||||
|
* result is the reply.
|
||||||
|
*/
|
||||||
|
public interface Commands
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Registers {@code command}. Only on the main thread while the mod loads: in the entry point's
|
||||||
|
* constructor or {@link Mod#onLoad()}.
|
||||||
|
*
|
||||||
|
* @throws IllegalArgumentException when {@code command} does not meet the rules above, or is
|
||||||
|
* registered already
|
||||||
|
* @throws IllegalStateException when called later or on another thread
|
||||||
|
*/
|
||||||
|
void register(Class<?> command);
|
||||||
|
}
|
||||||
@@ -84,4 +84,10 @@ public abstract class Mod
|
|||||||
|
|
||||||
/** The mod's tables in the world's {@code zomboidforge.db}; not on the main thread once the server runs. */
|
/** The mod's tables in the world's {@code zomboidforge.db}; not on the main thread once the server runs. */
|
||||||
protected final ModStorage storage() { return this.context.storage(); }
|
protected final ModStorage storage() { return this.context.storage(); }
|
||||||
|
|
||||||
|
/** Admin command registration. */
|
||||||
|
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(); }
|
||||||
}
|
}
|
||||||
@@ -42,4 +42,10 @@ public interface ModContext
|
|||||||
|
|
||||||
/** The mod's tables in the world's {@code zomboidforge.db}. */
|
/** The mod's tables in the world's {@code zomboidforge.db}. */
|
||||||
ModStorage storage();
|
ModStorage storage();
|
||||||
|
|
||||||
|
/** Admin command registration. */
|
||||||
|
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");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -18,6 +18,9 @@ public final class B42PatchSet implements PatchSet
|
|||||||
new ServerTickPatch(),
|
new ServerTickPatch(),
|
||||||
new ServerStoppingPatch(),
|
new ServerStoppingPatch(),
|
||||||
new BackupStoragePatch(),
|
new BackupStoragePatch(),
|
||||||
|
new CommandLookupPatch(),
|
||||||
|
new CommandListPatch(),
|
||||||
|
new ClientCommandPatch(),
|
||||||
new IsoZombieVehiclePerformancePatch(),
|
new IsoZombieVehiclePerformancePatch(),
|
||||||
new IsoZombieNetworkComponentPerformancePatch(),
|
new IsoZombieNetworkComponentPerformancePatch(),
|
||||||
new IsoZombieSpotChancePerformancePatch(),
|
new IsoZombieSpotChancePerformancePatch(),
|
||||||
|
|||||||
+43
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
+32
@@ -0,0 +1,32 @@
|
|||||||
|
package dev.overlord.zomboidforge.compat.b42.patches;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||||
|
import dev.overlord.zomboidforge.patcher.Hook;
|
||||||
|
import dev.overlord.zomboidforge.patcher.Patches.ReturnHookPatch;
|
||||||
|
|
||||||
|
import org.objectweb.asm.Opcodes;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Makes {@code CommandBase.getSubClasses()} return
|
||||||
|
* {@code CommandHooks.listCommands(childrenClasses)}: Project Zomboid's command classes followed
|
||||||
|
* by the mods'. The {@code help} command lists commands through this method.
|
||||||
|
*/
|
||||||
|
public final class CommandListPatch extends ReturnHookPatch
|
||||||
|
{
|
||||||
|
/** The whole method: {@code getstatic childrenClasses}, {@code areturn}. */
|
||||||
|
private static final Anchor.Sequence ANCHOR = new Anchor.Sequence(
|
||||||
|
new Anchor.Method("getSubClasses", "()[Ljava/lang/Class;"),
|
||||||
|
new Anchor.Instruction.Opcode(Opcodes.GETSTATIC),
|
||||||
|
new Anchor.Instruction.Opcode(Opcodes.ARETURN)
|
||||||
|
);
|
||||||
|
|
||||||
|
private static final Hook HOOK = new Hook(
|
||||||
|
"dev/overlord/zomboidforge/compat/b42/hooks/CommandHooks", "listCommands", "([Ljava/lang/Class;)[Ljava/lang/Class;"
|
||||||
|
);
|
||||||
|
|
||||||
|
public CommandListPatch() {
|
||||||
|
super("zombie/commands/CommandBase", CommandListPatch.ANCHOR, CommandListPatch.HOOK, List.of());
|
||||||
|
}
|
||||||
|
}
|
||||||
+33
@@ -0,0 +1,33 @@
|
|||||||
|
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.ReturnHookPatch;
|
||||||
|
|
||||||
|
import org.objectweb.asm.Opcodes;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Makes {@code CommandBase.findCommandCls(command)} return
|
||||||
|
* {@code CommandHooks.findCommand(null, command)} where it returns {@code null}: when no command
|
||||||
|
* of Project Zomboid matches, the mods' commands are searched. The server console, RCON, chat
|
||||||
|
* commands, and {@code help <name>} look commands up through this method.
|
||||||
|
*/
|
||||||
|
public final class CommandLookupPatch extends ReturnHookPatch
|
||||||
|
{
|
||||||
|
private static final Anchor.Sequence ANCHOR = new Anchor.Sequence(
|
||||||
|
new Anchor.Method("findCommandCls", "(Ljava/lang/String;)Ljava/lang/Class;"),
|
||||||
|
new Anchor.Instruction.Opcode(Opcodes.ACONST_NULL),
|
||||||
|
new Anchor.Instruction.Opcode(Opcodes.ARETURN)
|
||||||
|
);
|
||||||
|
|
||||||
|
private static final Hook HOOK = new Hook(
|
||||||
|
"dev/overlord/zomboidforge/compat/b42/hooks/CommandHooks", "findCommand", "(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Class;"
|
||||||
|
);
|
||||||
|
|
||||||
|
public CommandLookupPatch() {
|
||||||
|
super("zombie/commands/CommandBase", CommandLookupPatch.ANCHOR, CommandLookupPatch.HOOK, List.of(new HookArgument.Parameter(0)));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,6 +10,8 @@ dependencies {
|
|||||||
implementation(project(":api"))
|
implementation(project(":api"))
|
||||||
compileOnly(files(projectZomboid.serverJar))
|
compileOnly(files(projectZomboid.serverJar))
|
||||||
|
|
||||||
|
// ModCommandsTest checks command classes against the game's command framework.
|
||||||
|
testImplementation(files(projectZomboid.serverJar))
|
||||||
testImplementation(platform(libs.junit.bom))
|
testImplementation(platform(libs.junit.bom))
|
||||||
testImplementation(libs.junit.jupiter)
|
testImplementation(libs.junit.jupiter)
|
||||||
testRuntimeOnly(libs.junit.platform.launcher)
|
testRuntimeOnly(libs.junit.platform.launcher)
|
||||||
|
|||||||
+5
-1
@@ -1,11 +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.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();
|
public static final Forge FORGE = Forge.fromSystemProperties(
|
||||||
|
ModCommands::check, ClientCommandChannel::prepare
|
||||||
|
);
|
||||||
|
|
||||||
private ForgeInstance() {}
|
private ForgeInstance() {}
|
||||||
}
|
}
|
||||||
+55
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
+134
@@ -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() + "')"; }
|
||||||
|
}
|
||||||
+111
@@ -0,0 +1,111 @@
|
|||||||
|
package dev.overlord.zomboidforge.compat.b42.commands;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
|
import zombie.characters.Role;
|
||||||
|
import zombie.commands.CommandBase;
|
||||||
|
import zombie.commands.CommandName;
|
||||||
|
import zombie.commands.RequiredCapability;
|
||||||
|
import zombie.core.raknet.UdpConnection;
|
||||||
|
|
||||||
|
import java.lang.reflect.Constructor;
|
||||||
|
import java.lang.reflect.Modifier;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Command classes of mods in Build 42: subclasses of {@code CommandBase}, which
|
||||||
|
* {@code GameServer.handleServerCommand} creates through {@code getConstructors()[0]} with
|
||||||
|
* {@code (username, role, command, connection)}.
|
||||||
|
*/
|
||||||
|
public final class ModCommands
|
||||||
|
{
|
||||||
|
private static final Class<?>[] CONSTRUCTOR = {String.class, Role.class, String.class, UdpConnection.class};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Names are inserted into a regular expression by {@code findCommandCls}, so they are limited
|
||||||
|
* to word characters. With such names, {@code ^name\b} matches the input exactly when its first
|
||||||
|
* word equals the name, ignoring case.
|
||||||
|
*/
|
||||||
|
private static final Pattern NAME = Pattern.compile("\\w+");
|
||||||
|
|
||||||
|
private ModCommands() {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fails unless {@code command} is a usable Build 42 command whose names are not taken by
|
||||||
|
* Project Zomboid's commands or by {@code registered}.
|
||||||
|
*
|
||||||
|
* @throws IllegalArgumentException listing every problem
|
||||||
|
*/
|
||||||
|
public static void check(Class<?> command, List<Class<?>> registered)
|
||||||
|
{
|
||||||
|
List<String> problems = new ArrayList<>();
|
||||||
|
int modifiers = command.getModifiers();
|
||||||
|
|
||||||
|
if (!CommandBase.class.isAssignableFrom(command)) problems.add("it does not extend '" + CommandBase.class.getName() + "'");
|
||||||
|
if (!Modifier.isPublic(modifiers)) problems.add("it is not public");
|
||||||
|
if (Modifier.isAbstract(modifiers)) problems.add("it is abstract");
|
||||||
|
|
||||||
|
Constructor<?>[] constructors = command.getConstructors();
|
||||||
|
if (constructors.length != 1 || !Arrays.equals(constructors[0].getParameterTypes(), ModCommands.CONSTRUCTOR))
|
||||||
|
problems.add("it needs exactly one public constructor '(String, Role, String, UdpConnection)'");
|
||||||
|
|
||||||
|
if (command.getAnnotationsByType(RequiredCapability.class).length == 0)
|
||||||
|
problems.add("it has no @RequiredCapability, and Project Zomboid runs no command without one");
|
||||||
|
|
||||||
|
CommandName[] names = command.getAnnotationsByType(CommandName.class);
|
||||||
|
if (names.length == 0) problems.add("it has no @CommandName");
|
||||||
|
|
||||||
|
for (CommandName name : names)
|
||||||
|
{
|
||||||
|
if (!ModCommands.NAME.matcher(name.name()).matches()) {
|
||||||
|
problems.add("the name '" + name.name() + "' contains characters other than letters, digits, and '_'");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
Class<?> owner = ModCommands.owner(name.name(), registered);
|
||||||
|
if (owner != null) problems.add("the name '" + name.name() + "' is taken by '" + owner.getName() + "'");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!problems.isEmpty()) throw new IllegalArgumentException("'" + command.getName() + "' cannot be a command: " + String.join("; ", problems) + ".");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The first class of {@code commands} that is not disabled and has a name that {@code input}
|
||||||
|
* starts with, matched like {@code CommandBase.findCommandCls} matches Project Zomboid's
|
||||||
|
* commands; {@code null} when there is none.
|
||||||
|
*/
|
||||||
|
public static @Nullable Class<?> find(List<Class<?>> commands, String input)
|
||||||
|
{
|
||||||
|
for (Class<?> command : commands)
|
||||||
|
{
|
||||||
|
if (CommandBase.isDisabled(command)) continue;
|
||||||
|
|
||||||
|
for (CommandName name : command.getAnnotationsByType(CommandName.class)) {
|
||||||
|
if (Pattern.compile("^" + name.name() + "\\b", Pattern.CASE_INSENSITIVE).matcher(input).find()) return command;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The class among Project Zomboid's commands and {@code registered} that has {@code name}, ignoring case. */
|
||||||
|
private static @Nullable Class<?> owner(String name, List<Class<?>> registered)
|
||||||
|
{
|
||||||
|
Set<Class<?>> taken = new LinkedHashSet<>(Arrays.<Class<?>>asList(CommandBase.getSubClasses()));
|
||||||
|
taken.addAll(registered);
|
||||||
|
|
||||||
|
for (Class<?> command : taken)
|
||||||
|
{
|
||||||
|
for (CommandName existing : command.getAnnotationsByType(CommandName.class)) {
|
||||||
|
if (existing.name().equalsIgnoreCase(name)) return command;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
+11
@@ -0,0 +1,11 @@
|
|||||||
|
/**
|
||||||
|
* 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
|
||||||
|
*/
|
||||||
|
@NotNullByDefault
|
||||||
|
package dev.overlord.zomboidforge.compat.b42.commands;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.NotNullByDefault;
|
||||||
+54
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+61
@@ -0,0 +1,61 @@
|
|||||||
|
package dev.overlord.zomboidforge.compat.b42.hooks;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.compat.b42.ForgeInstance;
|
||||||
|
import dev.overlord.zomboidforge.compat.b42.commands.ModCommands;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hooks called by patched {@code zombie.commands.CommandBase} code, on the main thread: the
|
||||||
|
* server console, RCON, and chat commands all run there. Exceptions are caught here, and the
|
||||||
|
* vanilla value is returned.
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("CallToPrintStackTrace")
|
||||||
|
public final class CommandHooks
|
||||||
|
{
|
||||||
|
private CommandHooks() {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Replaces the {@code null} that {@code CommandBase.findCommandCls} returns when no command of
|
||||||
|
* Project Zomboid matches {@code command}: the mods' command class for it, or {@code null}.
|
||||||
|
*/
|
||||||
|
public static @Nullable Class<?> findCommand(@Nullable Class<?> vanilla, String command)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return ModCommands.find(ForgeInstance.FORGE.commands(), command);
|
||||||
|
}
|
||||||
|
catch (Throwable t)
|
||||||
|
{
|
||||||
|
t.printStackTrace();
|
||||||
|
return vanilla;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Replaces the array that {@code CommandBase.getSubClasses} returns: Project Zomboid's
|
||||||
|
* command classes followed by the mods', in registration order. Without mod commands, the
|
||||||
|
* vanilla array itself.
|
||||||
|
*/
|
||||||
|
public static Class<?>[] listCommands(Class<?>[] vanilla)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
List<Class<?>> mods = ForgeInstance.FORGE.commands();
|
||||||
|
if (mods.isEmpty()) return vanilla;
|
||||||
|
|
||||||
|
Class<?>[] all = Arrays.copyOf(vanilla, vanilla.length + mods.size());
|
||||||
|
for (int i = 0; i < mods.size(); i++) all[vanilla.length + i] = mods.get(i);
|
||||||
|
|
||||||
|
return all;
|
||||||
|
}
|
||||||
|
catch (Throwable t)
|
||||||
|
{
|
||||||
|
t.printStackTrace();
|
||||||
|
return vanilla;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-4
@@ -33,10 +33,8 @@ public final class ZombieVehicleHooks
|
|||||||
* and is skipped here.
|
* and is skipped here.
|
||||||
*/
|
*/
|
||||||
public static @Nullable Vector3f getIntersectPoint(
|
public static @Nullable Vector3f getIntersectPoint(
|
||||||
@NotNull BaseVehicle vehicle,
|
BaseVehicle vehicle, Vector3f start,
|
||||||
@NotNull Vector3f start,
|
Vector3f end, @Nullable Vector3f result
|
||||||
@NotNull Vector3f end,
|
|
||||||
@Nullable Vector3f result
|
|
||||||
) {
|
) {
|
||||||
VehicleScript script = vehicle.getScript();
|
VehicleScript script = vehicle.getScript();
|
||||||
Vector3f extents = script.getExtents();
|
Vector3f extents = script.getExtents();
|
||||||
|
|||||||
+127
@@ -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());
|
||||||
|
}
|
||||||
|
}
|
||||||
+125
@@ -0,0 +1,125 @@
|
|||||||
|
package dev.overlord.zomboidforge.compat.b42.commands;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import zombie.characters.Capability;
|
||||||
|
import zombie.characters.Role;
|
||||||
|
import zombie.commands.CommandBase;
|
||||||
|
import zombie.commands.CommandName;
|
||||||
|
import zombie.commands.DisabledCommand;
|
||||||
|
import zombie.commands.RequiredCapability;
|
||||||
|
import zombie.core.raknet.UdpConnection;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
|
/** Runs against the classes of the server jar that the module compiles against. */
|
||||||
|
class ModCommandsTest
|
||||||
|
{
|
||||||
|
@CommandName(name = "zfshop")
|
||||||
|
@CommandName(name = "zfbuy")
|
||||||
|
@RequiredCapability(requiredCapability = Capability.LoginOnServer)
|
||||||
|
public static final class ShopCommand extends CommandBase
|
||||||
|
{
|
||||||
|
public ShopCommand(String username, Role role, String command, UdpConnection connection) { super(username, role, command, connection); }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected String Command() { return "shop"; }
|
||||||
|
}
|
||||||
|
|
||||||
|
@CommandName(name = "ZFSHOP")
|
||||||
|
@RequiredCapability(requiredCapability = Capability.LoginOnServer)
|
||||||
|
public static final class OtherShopCommand extends CommandBase
|
||||||
|
{
|
||||||
|
public OtherShopCommand(String username, Role role, String command, UdpConnection connection) { super(username, role, command, connection); }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected String Command() { return "other shop"; }
|
||||||
|
}
|
||||||
|
|
||||||
|
@CommandName(name = "Save")
|
||||||
|
@CommandName(name = "zf-save")
|
||||||
|
@RequiredCapability(requiredCapability = Capability.SaveWorld)
|
||||||
|
public static final class SaveCommand extends CommandBase
|
||||||
|
{
|
||||||
|
public SaveCommand(String username, Role role, String command, UdpConnection connection) { super(username, role, command, connection); }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected String Command() { return "save"; }
|
||||||
|
}
|
||||||
|
|
||||||
|
@DisabledCommand
|
||||||
|
@CommandName(name = "zfoff")
|
||||||
|
@RequiredCapability(requiredCapability = Capability.LoginOnServer)
|
||||||
|
public static final class DisabledShopCommand extends CommandBase
|
||||||
|
{
|
||||||
|
public DisabledShopCommand(String username, Role role, String command, UdpConnection connection) { super(username, role, command, connection); }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected String Command() { return "off"; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Neither a command nor annotated; its constructor has no parameters. */
|
||||||
|
public static final class NotACommand {}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void acceptsAUsableCommand()
|
||||||
|
{
|
||||||
|
assertDoesNotThrow(() -> ModCommands.check(ModCommandsTest.ShopCommand.class, List.of()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void listsEveryProblemOfAClassThatIsNoCommand()
|
||||||
|
{
|
||||||
|
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> ModCommands.check(ModCommandsTest.NotACommand.class, List.of()));
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
"'" + ModCommandsTest.NotACommand.class.getName() + "' cannot be a command: it does not extend 'zombie.commands.CommandBase';"
|
||||||
|
+ " it needs exactly one public constructor '(String, Role, String, UdpConnection)';"
|
||||||
|
+ " it has no @RequiredCapability, and Project Zomboid runs no command without one; it has no @CommandName.",
|
||||||
|
e.getMessage()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rejectsNamesOfProjectZomboidIgnoringCaseAndNamesWithOtherCharacters()
|
||||||
|
{
|
||||||
|
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> ModCommands.check(ModCommandsTest.SaveCommand.class, List.of()));
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
"'" + ModCommandsTest.SaveCommand.class.getName() + "' cannot be a command:"
|
||||||
|
+ " the name 'Save' is taken by 'zombie.commands.serverCommands.SaveCommand';"
|
||||||
|
+ " the name 'zf-save' contains characters other than letters, digits, and '_'.",
|
||||||
|
e.getMessage()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rejectsNamesOfRegisteredCommands()
|
||||||
|
{
|
||||||
|
IllegalArgumentException e = assertThrows(
|
||||||
|
IllegalArgumentException.class,
|
||||||
|
() -> ModCommands.check(ModCommandsTest.OtherShopCommand.class, List.of(ModCommandsTest.ShopCommand.class))
|
||||||
|
);
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
"'" + ModCommandsTest.OtherShopCommand.class.getName() + "' cannot be a command: the name 'ZFSHOP' is taken by '" + ModCommandsTest.ShopCommand.class.getName() + "'.",
|
||||||
|
e.getMessage()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void findsCommandsByTheirFirstWordIgnoringCase()
|
||||||
|
{
|
||||||
|
List<Class<?>> commands = List.of(ModCommandsTest.DisabledShopCommand.class, ModCommandsTest.ShopCommand.class);
|
||||||
|
|
||||||
|
assertEquals(ModCommandsTest.ShopCommand.class, ModCommands.find(commands, "zfshop"));
|
||||||
|
assertEquals(ModCommandsTest.ShopCommand.class, ModCommands.find(commands, "ZFBuy apple 3"));
|
||||||
|
assertNull(ModCommands.find(commands, "zfshopping"));
|
||||||
|
assertNull(ModCommands.find(commands, "zfoff"), "disabled commands are skipped, like Project Zomboid's");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,10 +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.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;
|
||||||
@@ -52,6 +56,8 @@ 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 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;
|
||||||
@@ -61,32 +67,44 @@ 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 version
|
||||||
|
* @param clientCommands sends the mods' server commands to clients in the running game version
|
||||||
*/
|
*/
|
||||||
public Forge(Path directory, @Nullable ModVersion api)
|
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.clientCommands = clientCommands;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Directory from {@value #DIRECTORY_PROPERTY} (default {@value #DEFAULT_DIRECTORY}); API
|
* Directory from {@value #DIRECTORY_PROPERTY} (default {@value #DEFAULT_DIRECTORY}); API
|
||||||
* 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 version
|
||||||
|
* @param clientCommands sends the mods' server commands to clients in the running game version
|
||||||
*/
|
*/
|
||||||
public static Forge fromSystemProperties()
|
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);
|
return new Forge(directory, api, commands, clientCommands);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Lifecycle.Phase phase() { return this.lifecycle.phase(); }
|
public Lifecycle.Phase phase() { return this.lifecycle.phase(); }
|
||||||
|
|
||||||
public List<ModLoader.LoadedMod> mods() { return this.mods; }
|
public List<ModLoader.LoadedMod> mods() { return this.mods; }
|
||||||
|
|
||||||
|
/** The admin command classes that mods registered, in registration order. */
|
||||||
|
public List<Class<?>> commands() { return this.commands.classes(); }
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Reads {@code forge.toml}, then discovers, checks, and loads every mod in
|
* Reads {@code forge.toml}, then discovers, checks, and loads every mod in
|
||||||
* {@code <directory>/mods}. Called once on the main thread, which becomes the thread of
|
* {@code <directory>/mods}. Called once on the main thread, which becomes the thread of
|
||||||
@@ -186,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.
|
||||||
@@ -246,6 +267,9 @@ public final class Forge
|
|||||||
catch (StorageException e) { this.logger.log(System.Logger.Level.ERROR, "Closing the storage failed.", e); }
|
catch (StorageException e) { this.logger.log(System.Logger.Level.ERROR, "Closing the storage failed.", e); }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Mods register commands on the main thread while they load. */
|
||||||
|
private boolean commandsOpen() { return this.queue.isMainThread() && this.lifecycle.phase() == Lifecycle.Phase.BOOTING; }
|
||||||
|
|
||||||
/** The main thread may use storage only before the main loop runs. */
|
/** The main thread may use storage only before the main loop runs. */
|
||||||
private boolean storageForbidden() { return this.queue.isMainThread() && this.lifecycle.phase() == Lifecycle.Phase.RUNNING; }
|
private boolean storageForbidden() { return this.queue.isMainThread() && this.lifecycle.phase() == Lifecycle.Phase.RUNNING; }
|
||||||
|
|
||||||
@@ -254,13 +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),
|
||||||
|
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,74 @@
|
|||||||
|
package dev.overlord.zomboidforge.core.commands;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.api.Commands;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.function.BooleanSupplier;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The admin command classes that mods registered, in registration order. What a command class
|
||||||
|
* has to look like depends on the Project Zomboid version, so a {@link Validator} from the compat
|
||||||
|
* module checks every class. Registration happens only while the mods load, on the main thread;
|
||||||
|
* the compat hooks read {@link #classes()} on the main thread afterwards.
|
||||||
|
*/
|
||||||
|
public final class CommandRegistry
|
||||||
|
{
|
||||||
|
/** Checks a command class against the command framework of the running game version. */
|
||||||
|
@FunctionalInterface
|
||||||
|
public interface Validator
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param registered the classes registered before, by any mod
|
||||||
|
* @throws IllegalArgumentException naming what is wrong with {@code command}
|
||||||
|
*/
|
||||||
|
void check(Class<?> command, List<Class<?>> registered);
|
||||||
|
}
|
||||||
|
|
||||||
|
private final Validator validator;
|
||||||
|
private final BooleanSupplier open;
|
||||||
|
|
||||||
|
private volatile List<Class<?>> classes = List.of();
|
||||||
|
|
||||||
|
/** @param open whether registration is allowed now, on the calling thread */
|
||||||
|
public CommandRegistry(Validator validator, BooleanSupplier open)
|
||||||
|
{
|
||||||
|
this.validator = Objects.requireNonNull(validator);
|
||||||
|
this.open = Objects.requireNonNull(open);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Every registered class, in registration order. */
|
||||||
|
public List<Class<?>> classes() { return this.classes; }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registration for one mod; registered classes are logged with {@code logger}. Exceptions do
|
||||||
|
* not name the mod: one thrown in the mod's {@code onLoad()} is reported with its id.
|
||||||
|
*/
|
||||||
|
public Commands forMod(System.Logger logger)
|
||||||
|
{
|
||||||
|
return command ->
|
||||||
|
{
|
||||||
|
this.register(command);
|
||||||
|
logger.log(System.Logger.Level.INFO, "Registered the command class '" + command.getName() + "'.");
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private synchronized void register(Class<?> command)
|
||||||
|
{
|
||||||
|
Objects.requireNonNull(command, "command");
|
||||||
|
|
||||||
|
if (!this.open.getAsBoolean())
|
||||||
|
throw new IllegalStateException("Commands can only be registered on the main thread while the mod loads (constructor or onLoad()).");
|
||||||
|
|
||||||
|
if (this.classes.contains(command))
|
||||||
|
throw new IllegalArgumentException("The command class '" + command.getName() + "' is registered already.");
|
||||||
|
|
||||||
|
this.validator.check(command, this.classes);
|
||||||
|
|
||||||
|
List<Class<?>> updated = new ArrayList<>(this.classes);
|
||||||
|
updated.add(command);
|
||||||
|
|
||||||
|
this.classes = List.copyOf(updated);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
/**
|
||||||
|
* Commands of loaded mods: the registry of admin commands that the compat hooks consult, and
|
||||||
|
* server commands to clients.
|
||||||
|
*
|
||||||
|
* @noinspection UnstableApiUsage, RedundantSuppression
|
||||||
|
*/
|
||||||
|
@NotNullByDefault
|
||||||
|
package dev.overlord.zomboidforge.core.commands;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.NotNullByDefault;
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
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.Events;
|
import dev.overlord.zomboidforge.api.Events;
|
||||||
import dev.overlord.zomboidforge.api.GameVersion;
|
import dev.overlord.zomboidforge.api.GameVersion;
|
||||||
import dev.overlord.zomboidforge.api.MainThread;
|
import dev.overlord.zomboidforge.api.MainThread;
|
||||||
@@ -36,17 +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,
|
||||||
|
ClientCommands clientCommands
|
||||||
) implements ModContext {}
|
) implements ModContext {}
|
||||||
|
|
||||||
private ModLoader() {}
|
private ModLoader() {}
|
||||||
@@ -93,7 +97,9 @@ public final class ModLoader
|
|||||||
provided.main(),
|
provided.main(),
|
||||||
provided.modThread(),
|
provided.modThread(),
|
||||||
provided.async(),
|
provided.async(),
|
||||||
provided.storage()
|
provided.storage(),
|
||||||
|
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,14 +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.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 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)
|
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
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import org.junit.jupiter.api.BeforeEach;
|
|||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.jupiter.api.io.TempDir;
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
|
|
||||||
|
import testmods.CommandMod;
|
||||||
import testmods.ContextMod;
|
import testmods.ContextMod;
|
||||||
import testmods.ErrorMod;
|
import testmods.ErrorMod;
|
||||||
import testmods.Recorder;
|
import testmods.Recorder;
|
||||||
@@ -19,6 +20,7 @@ import testmods.ThreadMod;
|
|||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.Comparator;
|
import java.util.Comparator;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
@@ -27,6 +29,7 @@ import java.util.function.BooleanSupplier;
|
|||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||||
import static org.junit.jupiter.api.Assertions.assertNotSame;
|
import static org.junit.jupiter.api.Assertions.assertNotSame;
|
||||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
@@ -45,6 +48,12 @@ class ForgeTest
|
|||||||
private Path gameJar;
|
private Path gameJar;
|
||||||
private Path storageFile;
|
private Path storageFile;
|
||||||
|
|
||||||
|
/** Classes that mods registered as commands, as {@code "<name> after <registered count>"}; every class is accepted. */
|
||||||
|
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
|
||||||
{
|
{
|
||||||
@@ -56,7 +65,15 @@ class ForgeTest
|
|||||||
Recorder.EVENTS.clear();
|
Recorder.EVENTS.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
private Forge forge() { return new Forge(this.directory, ModVersion.parse("0.3.0")); }
|
private Forge forge()
|
||||||
|
{
|
||||||
|
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
|
||||||
{
|
{
|
||||||
@@ -105,6 +122,38 @@ class ForgeTest
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void modsRegisterCommandsOnlyWhileTheyLoad() 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)
|
||||||
|
));
|
||||||
|
|
||||||
|
Forge forge = this.load();
|
||||||
|
|
||||||
|
assertEquals(List.of("testmods.CommandMod$Command"), forge.commands().stream().map(Class::getName).toList());
|
||||||
|
assertEquals(List.of("testmods.CommandMod$Command after 0"), this.checkedCommands);
|
||||||
|
|
||||||
|
forge.started();
|
||||||
|
|
||||||
|
assertInstanceOf(IllegalStateException.class, ForgeTest.field(forge.mods().getFirst().mod(), "lateRegistration"));
|
||||||
|
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,78 @@
|
|||||||
|
package dev.overlord.zomboidforge.core.commands;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.api.Commands;
|
||||||
|
import dev.overlord.zomboidforge.core.RecordingLogger;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
|
class CommandRegistryTest
|
||||||
|
{
|
||||||
|
private final List<String> checked = new ArrayList<>();
|
||||||
|
private final AtomicBoolean open = new AtomicBoolean(true);
|
||||||
|
private final RecordingLogger logger = new RecordingLogger();
|
||||||
|
|
||||||
|
/** Records every check as {@code "<simple name> after <registered count>"} and rejects {@link Integer}. */
|
||||||
|
private final CommandRegistry registry = new CommandRegistry(
|
||||||
|
(command, registered) ->
|
||||||
|
{
|
||||||
|
this.checked.add(command.getSimpleName() + " after " + registered.size());
|
||||||
|
if (command == Integer.class) throw new IllegalArgumentException("'java.lang.Integer' cannot be a command.");
|
||||||
|
},
|
||||||
|
this.open::get
|
||||||
|
);
|
||||||
|
|
||||||
|
private final Commands commands = this.registry.forMod(this.logger);
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void registersInOrderAndShowsTheValidatorTheEarlierClasses()
|
||||||
|
{
|
||||||
|
this.commands.register(String.class);
|
||||||
|
this.commands.register(Long.class);
|
||||||
|
|
||||||
|
assertEquals(List.of(String.class, Long.class), this.registry.classes());
|
||||||
|
assertEquals(List.of("String after 0", "Long after 1"), this.checked);
|
||||||
|
assertEquals(
|
||||||
|
List.of("INFO: Registered the command class 'java.lang.String'.", "INFO: Registered the command class 'java.lang.Long'."),
|
||||||
|
this.logger.messages
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rejectedClassesAreNotRegistered()
|
||||||
|
{
|
||||||
|
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> this.commands.register(Integer.class));
|
||||||
|
|
||||||
|
assertEquals("'java.lang.Integer' cannot be a command.", e.getMessage());
|
||||||
|
assertEquals(List.of(), this.registry.classes());
|
||||||
|
assertEquals(List.of(), this.logger.messages);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rejectsTheSameClassTwice()
|
||||||
|
{
|
||||||
|
this.commands.register(String.class);
|
||||||
|
|
||||||
|
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> this.commands.register(String.class));
|
||||||
|
|
||||||
|
assertEquals("The command class 'java.lang.String' is registered already.", e.getMessage());
|
||||||
|
assertEquals(List.of(String.class), this.registry.classes());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rejectsRegistrationWhileClosed()
|
||||||
|
{
|
||||||
|
this.open.set(false);
|
||||||
|
|
||||||
|
IllegalStateException e = assertThrows(IllegalStateException.class, () -> this.commands.register(String.class));
|
||||||
|
|
||||||
|
assertEquals("Commands can only be registered on the main thread while the mod loads (constructor or onLoad()).", e.getMessage());
|
||||||
|
assertEquals(List.of(), this.checked);
|
||||||
|
}
|
||||||
|
}
|
||||||
+107
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package testmods;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.api.Mod;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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; sends a client command to
|
||||||
|
* every client there.
|
||||||
|
*/
|
||||||
|
public final class CommandMod extends Mod
|
||||||
|
{
|
||||||
|
/** Stands in for a command class; the tests' validator accepts any class. */
|
||||||
|
public static final class Command {}
|
||||||
|
|
||||||
|
public volatile @Nullable RuntimeException lateRegistration;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onLoad() { this.commands().register(CommandMod.Command.class); }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onServerStarted()
|
||||||
|
{
|
||||||
|
try { this.commands().register(CommandMod.Command.class); }
|
||||||
|
catch (RuntimeException e) { this.lateRegistration = e; }
|
||||||
|
|
||||||
|
this.clientCommands().sendToAll("Test", "started", Map.of("count", 1));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@
|
|||||||
<trusted-artifacts>
|
<trusted-artifacts>
|
||||||
<trust file=".*-javadoc[.]jar" regex="true"/>
|
<trust file=".*-javadoc[.]jar" regex="true"/>
|
||||||
<trust file=".*-sources[.]jar" regex="true"/>
|
<trust file=".*-sources[.]jar" regex="true"/>
|
||||||
|
<trust group="gradle" name="gradle" file="gradle-.*-src[.]zip" regex="true"/>
|
||||||
</trusted-artifacts>
|
</trusted-artifacts>
|
||||||
</configuration>
|
</configuration>
|
||||||
<components>
|
<components>
|
||||||
@@ -159,6 +160,30 @@
|
|||||||
<sha256 value="d40318527f56033e0ff0789971cc38c856aa99a685eea11270814e7f1eda9fba" origin="Generated by Gradle"/>
|
<sha256 value="d40318527f56033e0ff0789971cc38c856aa99a685eea11270814e7f1eda9fba" origin="Generated by Gradle"/>
|
||||||
</artifact>
|
</artifact>
|
||||||
</component>
|
</component>
|
||||||
|
<component group="org.apache.groovy" name="groovy" version="4.0.33">
|
||||||
|
<artifact name="groovy-4.0.33.module">
|
||||||
|
<sha256 value="b51f0a5b8ecfba534d47612a49aa51b279ecdac72e7f790a8ed3130070d80dc5" origin="Generated by IntelliJ sync"/>
|
||||||
|
</artifact>
|
||||||
|
<artifact name="groovy-4.0.33.pom">
|
||||||
|
<sha256 value="4a077cc859cb0fabab55f8637e77889fe03b2489692c9d1da253e43715c28cf8" origin="Generated by IntelliJ sync"/>
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
|
<component group="org.apache.groovy" name="groovy-ant" version="4.0.33">
|
||||||
|
<artifact name="groovy-ant-4.0.33.module">
|
||||||
|
<sha256 value="c498aa114fb510a7f6841c94f973fb16d4580357c170ab978fd5ae2a8e4fb57a" origin="Generated by IntelliJ sync"/>
|
||||||
|
</artifact>
|
||||||
|
<artifact name="groovy-ant-4.0.33.pom">
|
||||||
|
<sha256 value="e64319f32699287e1d39c1f8da358a6a7740c8a8dc5516a7c43d606b0fa16298" origin="Generated by IntelliJ sync"/>
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
|
<component group="org.apache.groovy" name="groovy-astbuilder" version="4.0.33">
|
||||||
|
<artifact name="groovy-astbuilder-4.0.33.module">
|
||||||
|
<sha256 value="655c1b59499c7e590dbc3d643a9485f2d512e34145f1735fd477bcb03e3ced73" origin="Generated by IntelliJ sync"/>
|
||||||
|
</artifact>
|
||||||
|
<artifact name="groovy-astbuilder-4.0.33.pom">
|
||||||
|
<sha256 value="fe25b6081390bbb9cf32fc9cf5b373fa391cb3854bfdedcde81a238ea88ad68c" origin="Generated by IntelliJ sync"/>
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
<component group="org.apache.groovy" name="groovy-bom" version="4.0.27">
|
<component group="org.apache.groovy" name="groovy-bom" version="4.0.27">
|
||||||
<artifact name="groovy-bom-4.0.27.module">
|
<artifact name="groovy-bom-4.0.27.module">
|
||||||
<sha256 value="d6c2254c8347b84cda84caf74914a187c2f377e4284e8d8bb3f901521810aa8b" origin="Generated by Gradle"/>
|
<sha256 value="d6c2254c8347b84cda84caf74914a187c2f377e4284e8d8bb3f901521810aa8b" origin="Generated by Gradle"/>
|
||||||
@@ -167,6 +192,78 @@
|
|||||||
<sha256 value="aa44eb52bfdfe61d27b3e450d2b348d88deaa3437ab4d9d49a84095348f9f6fb" origin="Generated by Gradle"/>
|
<sha256 value="aa44eb52bfdfe61d27b3e450d2b348d88deaa3437ab4d9d49a84095348f9f6fb" origin="Generated by Gradle"/>
|
||||||
</artifact>
|
</artifact>
|
||||||
</component>
|
</component>
|
||||||
|
<component group="org.apache.groovy" name="groovy-bom" version="4.0.33">
|
||||||
|
<artifact name="groovy-bom-4.0.33.module">
|
||||||
|
<sha256 value="a87e4410ce69764f53e10ff399ba4ed8875bc59845b766181e9c82e9ddfc5f75" origin="Generated by IntelliJ sync"/>
|
||||||
|
</artifact>
|
||||||
|
<artifact name="groovy-bom-4.0.33.pom">
|
||||||
|
<sha256 value="c30cc3b9184251be043e8b98ec9f6f17c39b0925183e91c7856ea82b18d9f5ce" origin="Generated by IntelliJ sync"/>
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
|
<component group="org.apache.groovy" name="groovy-datetime" version="4.0.33">
|
||||||
|
<artifact name="groovy-datetime-4.0.33.module">
|
||||||
|
<sha256 value="97199c00ad134459c8c3c5244f16f0d9e3f08d61a8b2a7b1ad66e827f027d10e" origin="Generated by IntelliJ sync"/>
|
||||||
|
</artifact>
|
||||||
|
<artifact name="groovy-datetime-4.0.33.pom">
|
||||||
|
<sha256 value="691f2eb07b9a60f69926644902103fb2b4ae6370a4154eb4aac765d073fc9e1d" origin="Generated by IntelliJ sync"/>
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
|
<component group="org.apache.groovy" name="groovy-dateutil" version="4.0.33">
|
||||||
|
<artifact name="groovy-dateutil-4.0.33.module">
|
||||||
|
<sha256 value="b7848a9cf1159b796c11097d380a9f1cb3c2c60fdb9feb560dc88c5bb5b441bd" origin="Generated by IntelliJ sync"/>
|
||||||
|
</artifact>
|
||||||
|
<artifact name="groovy-dateutil-4.0.33.pom">
|
||||||
|
<sha256 value="c7bab371bf9f8666d6c738bcf268671b45ebc305160d2d170520110527ee106b" origin="Generated by IntelliJ sync"/>
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
|
<component group="org.apache.groovy" name="groovy-docgenerator" version="4.0.33">
|
||||||
|
<artifact name="groovy-docgenerator-4.0.33.module">
|
||||||
|
<sha256 value="594227fa51d93092f70be2d17ac90c1358960131a7ccd9e9c589b82bca3b640f" origin="Generated by IntelliJ sync"/>
|
||||||
|
</artifact>
|
||||||
|
<artifact name="groovy-docgenerator-4.0.33.pom">
|
||||||
|
<sha256 value="cfd1d47f567d2d8c1047c9fa69e5ac873d25c57088767204c5a7cb888d95104e" origin="Generated by IntelliJ sync"/>
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
|
<component group="org.apache.groovy" name="groovy-groovydoc" version="4.0.33">
|
||||||
|
<artifact name="groovy-groovydoc-4.0.33.module">
|
||||||
|
<sha256 value="70cf9d616c4757ebbe206e1db77e4f2225b9e238e9d79634a62ddc2cc45f706c" origin="Generated by IntelliJ sync"/>
|
||||||
|
</artifact>
|
||||||
|
<artifact name="groovy-groovydoc-4.0.33.pom">
|
||||||
|
<sha256 value="de5bec405a6a258dc48820cd136bd2d2920142a6bc620921a05271157be62945" origin="Generated by IntelliJ sync"/>
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
|
<component group="org.apache.groovy" name="groovy-json" version="4.0.33">
|
||||||
|
<artifact name="groovy-json-4.0.33.module">
|
||||||
|
<sha256 value="591dc453651b086a4301984b64c18679b5f8fb70fc6dd4f2ab25263d4119dfb4" origin="Generated by IntelliJ sync"/>
|
||||||
|
</artifact>
|
||||||
|
<artifact name="groovy-json-4.0.33.pom">
|
||||||
|
<sha256 value="d92a8fa210f6fb7777a1f0f123fe96f268a7d25d000666f1884d3520535b2900" origin="Generated by IntelliJ sync"/>
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
|
<component group="org.apache.groovy" name="groovy-nio" version="4.0.33">
|
||||||
|
<artifact name="groovy-nio-4.0.33.module">
|
||||||
|
<sha256 value="0a3d28bb3c364d2dd83e78127100facd2de4a7be491f8f64a58f7852be29d716" origin="Generated by IntelliJ sync"/>
|
||||||
|
</artifact>
|
||||||
|
<artifact name="groovy-nio-4.0.33.pom">
|
||||||
|
<sha256 value="044bfe5a61dce53a32031c1ee373efac9648c3eb27272a64f2c05e0eed4d1ec5" origin="Generated by IntelliJ sync"/>
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
|
<component group="org.apache.groovy" name="groovy-templates" version="4.0.33">
|
||||||
|
<artifact name="groovy-templates-4.0.33.module">
|
||||||
|
<sha256 value="8eae833715e00c5d56aafa0d3bb6dd7efcbb6245cd3e9ea5f6776de4c6e9eef1" origin="Generated by IntelliJ sync"/>
|
||||||
|
</artifact>
|
||||||
|
<artifact name="groovy-templates-4.0.33.pom">
|
||||||
|
<sha256 value="5819f6df4c0536bcd76d28aeb044e570e68aff3e2546118c6715a615460e92bf" origin="Generated by IntelliJ sync"/>
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
|
<component group="org.apache.groovy" name="groovy-xml" version="4.0.33">
|
||||||
|
<artifact name="groovy-xml-4.0.33.module">
|
||||||
|
<sha256 value="bd326e05cf9e63da4e509eeb03689889be869605eb4ac5459970adef5ba32202" origin="Generated by IntelliJ sync"/>
|
||||||
|
</artifact>
|
||||||
|
<artifact name="groovy-xml-4.0.33.pom">
|
||||||
|
<sha256 value="01eb2e96423efa4725424036b578ddf95647979438f3a92a017f2ed176ce5abd" origin="Generated by IntelliJ sync"/>
|
||||||
|
</artifact>
|
||||||
|
</component>
|
||||||
<component group="org.apache.logging.log4j" name="log4j" version="2.26.1">
|
<component group="org.apache.logging.log4j" name="log4j" version="2.26.1">
|
||||||
<artifact name="log4j-2.26.1.pom">
|
<artifact name="log4j-2.26.1.pom">
|
||||||
<sha256 value="ea4705725fd94bf5debe2911d4ea7af20898603f68354e64b2461a0f249e445d" origin="Generated by Gradle"/>
|
<sha256 value="ea4705725fd94bf5debe2911d4ea7af20898603f68354e64b2461a0f249e445d" origin="Generated by Gradle"/>
|
||||||
|
|||||||
@@ -11,18 +11,27 @@ import org.objectweb.asm.tree.InsnList;
|
|||||||
import org.objectweb.asm.tree.MethodInsnNode;
|
import org.objectweb.asm.tree.MethodInsnNode;
|
||||||
import org.objectweb.asm.tree.MethodNode;
|
import org.objectweb.asm.tree.MethodNode;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
/** The call of a {@link Hook} with its {@link HookArgument}s, shared by the hook patch types. */
|
/**
|
||||||
|
* The call of a {@link Hook} with its {@link HookArgument}s, shared by the hook patch types. A
|
||||||
|
* hook may also take values that are already on the operand stack where it is called; those
|
||||||
|
* come first in its parameter list, followed by one parameter per argument.
|
||||||
|
*/
|
||||||
final class HookCall
|
final class HookCall
|
||||||
{
|
{
|
||||||
private HookCall() {}
|
private HookCall() {}
|
||||||
|
|
||||||
|
/** {@link #checkShape(Hook, List, List, Type)} without values on the stack. */
|
||||||
|
static void checkShape(Hook hook, List<HookArgument> arguments, Type returnType) { HookCall.checkShape(hook, List.of(), arguments, returnType); }
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Fails unless {@code hook} returns {@code returnType} and takes {@code arguments} parameters.
|
* Fails unless {@code hook} returns {@code returnType}, takes the types {@code onStack} first,
|
||||||
* The parameter types are checked by {@link #invoke}, once the arguments are resolved.
|
* and then one parameter per argument. The types of those parameters are checked by
|
||||||
|
* {@link #invoke}, once the arguments are resolved.
|
||||||
*/
|
*/
|
||||||
static void checkShape(Hook hook, List<HookArgument> arguments, Type returnType)
|
static void checkShape(Hook hook, List<Type> onStack, List<HookArgument> arguments, Type returnType)
|
||||||
{
|
{
|
||||||
Type actualReturn = Type.getReturnType(hook.desc());
|
Type actualReturn = Type.getReturnType(hook.desc());
|
||||||
Type[] parameters = Type.getArgumentTypes(hook.desc());
|
Type[] parameters = Type.getArgumentTypes(hook.desc());
|
||||||
@@ -30,34 +39,55 @@ final class HookCall
|
|||||||
if (!actualReturn.equals(returnType))
|
if (!actualReturn.equals(returnType))
|
||||||
throw new IllegalArgumentException("Hook '" + hook + "' must return '" + returnType.getDescriptor() + "'.");
|
throw new IllegalArgumentException("Hook '" + hook + "' must return '" + returnType.getDescriptor() + "'.");
|
||||||
|
|
||||||
if (parameters.length != arguments.size())
|
if (parameters.length != onStack.size() + arguments.size())
|
||||||
throw new IllegalArgumentException("Hook '" + hook + "' must take " + arguments.size() + " parameter(s), one per argument " + arguments + ".");
|
throw new IllegalArgumentException("Hook '" + hook + "' must take " + (onStack.size() + arguments.size()) + " parameter(s): " + HookCall.describe(onStack, arguments) + ".");
|
||||||
|
|
||||||
|
for (int i = 0; i < onStack.size(); i++)
|
||||||
|
{
|
||||||
|
if (!parameters[i].equals(onStack.get(i)))
|
||||||
|
throw new IllegalArgumentException("Parameter " + i + " of hook '" + hook + "' must be '" + onStack.get(i).getDescriptor() + "'.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** {@link #invoke(Hook, List, List, Type, ClassNode, MethodNode, AbstractInsnNode)} without values on the stack. */
|
||||||
|
static InsnList invoke(Hook hook, List<HookArgument> arguments, Type returnType, ClassNode node, MethodNode method, AbstractInsnNode at)
|
||||||
|
{
|
||||||
|
return HookCall.invoke(hook, List.of(), arguments, returnType, node, method, at);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Instructions that push {@code arguments} and call {@code hook}, for insertion directly
|
* Instructions that push {@code arguments} and call {@code hook}, for insertion directly
|
||||||
* before or after {@code at} in {@code method}. Fails when the hook's descriptor does not
|
* before or after {@code at} in {@code method}, where the values of the types {@code onStack}
|
||||||
* match the types of the arguments.
|
* are on top of the operand stack. Fails when the hook's descriptor does not match.
|
||||||
*/
|
*/
|
||||||
static InsnList invoke(Hook hook, List<HookArgument> arguments, Type returnType, ClassNode node, MethodNode method, AbstractInsnNode at)
|
static InsnList invoke(Hook hook, List<Type> onStack, List<HookArgument> arguments, Type returnType, ClassNode node, MethodNode method, AbstractInsnNode at)
|
||||||
{
|
{
|
||||||
InsnList code = new InsnList();
|
InsnList code = new InsnList();
|
||||||
Type[] types = new Type[arguments.size()];
|
List<Type> types = new ArrayList<>(onStack);
|
||||||
|
|
||||||
for (int i = 0; i < arguments.size(); i++)
|
for (HookArgument argument : arguments)
|
||||||
{
|
{
|
||||||
HookArgument.Slot slot = arguments.get(i).resolve(node, method, at);
|
HookArgument.Slot slot = argument.resolve(node, method, at);
|
||||||
|
|
||||||
types[i] = slot.type();
|
types.add(slot.type());
|
||||||
code.add(slot.load());
|
code.add(slot.load());
|
||||||
}
|
}
|
||||||
|
|
||||||
String expected = Type.getMethodDescriptor(returnType, types);
|
String expected = Type.getMethodDescriptor(returnType, types.toArray(Type[]::new));
|
||||||
if (!hook.desc().equals(expected))
|
if (!hook.desc().equals(expected))
|
||||||
throw new IllegalStateException("Hook '" + hook + "' must have descriptor '" + expected + "' for the arguments " + arguments + ".");
|
throw new IllegalStateException("Hook '" + hook + "' must have descriptor '" + expected + "' for " + HookCall.describe(onStack, arguments) + ".");
|
||||||
|
|
||||||
code.add(new MethodInsnNode(Opcodes.INVOKESTATIC, hook.owner(), hook.name(), hook.desc(), false));
|
code.add(new MethodInsnNode(Opcodes.INVOKESTATIC, hook.owner(), hook.name(), hook.desc(), false));
|
||||||
|
|
||||||
return code;
|
return code;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** E.g. {@code the arguments [parameter 0]} or {@code the stack value(s) [Ljava/lang/Class;] and the arguments [parameter 0]}. */
|
||||||
|
private static String describe(List<Type> onStack, List<HookArgument> arguments)
|
||||||
|
{
|
||||||
|
String argumentsText = "the arguments " + arguments;
|
||||||
|
if (onStack.isEmpty()) return argumentsText;
|
||||||
|
|
||||||
|
return "the stack value(s) " + onStack.stream().map(Type::getDescriptor).toList() + " and " + argumentsText;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
package dev.overlord.zomboidforge.patcher.Patches;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||||
|
import dev.overlord.zomboidforge.patcher.ClassPatch;
|
||||||
|
import dev.overlord.zomboidforge.patcher.Hook;
|
||||||
|
import dev.overlord.zomboidforge.patcher.HookArgument;
|
||||||
|
|
||||||
|
import org.objectweb.asm.Opcodes;
|
||||||
|
import org.objectweb.asm.Type;
|
||||||
|
import org.objectweb.asm.tree.AbstractInsnNode;
|
||||||
|
import org.objectweb.asm.tree.ClassNode;
|
||||||
|
import org.objectweb.asm.tree.MethodNode;
|
||||||
|
import org.objectweb.asm.util.Printer;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Passes the value that one return instruction of a method is about to return to a
|
||||||
|
* {@link Hook}, which returns the value to return instead:
|
||||||
|
*
|
||||||
|
* <pre>{@code
|
||||||
|
* return Hooks.hook(value, arguments);
|
||||||
|
* }</pre>
|
||||||
|
*
|
||||||
|
* The anchor is a {@link Anchor.Sequence} whose last instruction is that return instruction;
|
||||||
|
* the instructions before it identify which return of the method is meant. The hook's first
|
||||||
|
* parameter and its return type are the method's return type, followed by one parameter per
|
||||||
|
* {@link HookArgument}. Other returns of the method are unchanged.
|
||||||
|
*/
|
||||||
|
public abstract class ReturnHookPatch implements ClassPatch
|
||||||
|
{
|
||||||
|
private final String target;
|
||||||
|
private final Anchor.Sequence anchor;
|
||||||
|
private final Hook hook;
|
||||||
|
private final List<HookArgument> arguments;
|
||||||
|
private final Type returned;
|
||||||
|
|
||||||
|
protected ReturnHookPatch(String target, Anchor.Sequence anchor, Hook hook, List<HookArgument> arguments)
|
||||||
|
{
|
||||||
|
Type returned = Type.getReturnType(anchor.in().desc());
|
||||||
|
|
||||||
|
if (returned.equals(Type.VOID_TYPE))
|
||||||
|
throw new IllegalArgumentException("Method '" + anchor.in().name() + anchor.in().desc() + "' returns no value.");
|
||||||
|
|
||||||
|
HookCall.checkShape(hook, List.of(returned), arguments, returned);
|
||||||
|
|
||||||
|
this.target = Objects.requireNonNull(target);
|
||||||
|
this.anchor = anchor;
|
||||||
|
this.hook = hook;
|
||||||
|
this.arguments = List.copyOf(arguments);
|
||||||
|
this.returned = returned;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final String target() { return this.target; }
|
||||||
|
@Override
|
||||||
|
public final Anchor.Sequence anchor() { return this.anchor; }
|
||||||
|
@Override
|
||||||
|
public final Hook hook() { return this.hook; }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public final void apply(ClassNode node)
|
||||||
|
{
|
||||||
|
MethodNode method = this.anchor.in().resolve(node);
|
||||||
|
AbstractInsnNode instruction = this.anchor.resolve(node).getLast();
|
||||||
|
int returnOpcode = this.returned.getOpcode(Opcodes.IRETURN);
|
||||||
|
|
||||||
|
if (instruction.getOpcode() != returnOpcode)
|
||||||
|
throw new IllegalStateException("The last instruction of the anchor must be '" + Printer.OPCODES[returnOpcode].toLowerCase(Locale.ROOT) + "'.");
|
||||||
|
|
||||||
|
method.instructions.insertBefore(instruction, HookCall.invoke(this.hook, List.of(this.returned), this.arguments, this.returned, node, method, instruction));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,185 @@
|
|||||||
|
package dev.overlord.zomboidforge.patcher;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.patcher.Patches.ReturnHookPatch;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
|
import org.objectweb.asm.ClassWriter;
|
||||||
|
import org.objectweb.asm.Label;
|
||||||
|
import org.objectweb.asm.MethodVisitor;
|
||||||
|
import org.objectweb.asm.Type;
|
||||||
|
|
||||||
|
import java.net.URL;
|
||||||
|
import java.net.URLClassLoader;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.zip.ZipEntry;
|
||||||
|
import java.util.zip.ZipOutputStream;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
|
||||||
|
import static org.objectweb.asm.Opcodes.ACC_STATIC;
|
||||||
|
import static org.objectweb.asm.Opcodes.ACONST_NULL;
|
||||||
|
import static org.objectweb.asm.Opcodes.ALOAD;
|
||||||
|
import static org.objectweb.asm.Opcodes.ARETURN;
|
||||||
|
import static org.objectweb.asm.Opcodes.IFEQ;
|
||||||
|
import static org.objectweb.asm.Opcodes.ILOAD;
|
||||||
|
import static org.objectweb.asm.Opcodes.LRETURN;
|
||||||
|
import static org.objectweb.asm.Opcodes.V25;
|
||||||
|
|
||||||
|
class ReturnHookPatchTest
|
||||||
|
{
|
||||||
|
private static final String CALLS = Type.getInternalName(ReturnHookPatchTest.Calls.class);
|
||||||
|
|
||||||
|
private static final Anchor.Method PICK = new Anchor.Method("pick", "(Ljava/lang/String;Z)Ljava/lang/String;");
|
||||||
|
private static final Anchor.Method WIDE = new Anchor.Method("wide", "()J");
|
||||||
|
|
||||||
|
@TempDir
|
||||||
|
Path dir;
|
||||||
|
|
||||||
|
/** The hooks. */
|
||||||
|
public static final class Calls
|
||||||
|
{
|
||||||
|
private Calls() {}
|
||||||
|
|
||||||
|
public static String replaceNull(@Nullable String value, String input) { return "hook " + value + " " + input; }
|
||||||
|
|
||||||
|
public static long doubled(long value) { return value * 2; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Replaces the {@code null} that {@code pick} returns; the hook gets {@code input}. */
|
||||||
|
private static final class NullPatch extends ReturnHookPatch
|
||||||
|
{
|
||||||
|
NullPatch() {
|
||||||
|
super(
|
||||||
|
"t/Target",
|
||||||
|
new Anchor.Sequence(ReturnHookPatchTest.PICK, new Anchor.Instruction.Opcode(ACONST_NULL), new Anchor.Instruction.Opcode(ARETURN)),
|
||||||
|
new Hook(ReturnHookPatchTest.CALLS, "replaceNull", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"),
|
||||||
|
List.of(new HookArgument.Parameter(0))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Doubles the {@code long} that {@code wide} returns. */
|
||||||
|
private static final class WidePatch extends ReturnHookPatch
|
||||||
|
{
|
||||||
|
WidePatch() {
|
||||||
|
super(
|
||||||
|
"t/Target",
|
||||||
|
new Anchor.Sequence(ReturnHookPatchTest.WIDE, new Anchor.Instruction.Constant(5L), new Anchor.Instruction.Opcode(LRETURN)),
|
||||||
|
new Hook(ReturnHookPatchTest.CALLS, "doubled", "(J)J"),
|
||||||
|
List.of()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Anchored on {@code aconst_null} alone, not on a return instruction. */
|
||||||
|
private static final class NoReturnPatch extends ReturnHookPatch
|
||||||
|
{
|
||||||
|
NoReturnPatch() {
|
||||||
|
super(
|
||||||
|
"t/Target",
|
||||||
|
new Anchor.Sequence(ReturnHookPatchTest.PICK, new Anchor.Instruction.Opcode(ACONST_NULL)),
|
||||||
|
new Hook(ReturnHookPatchTest.CALLS, "replaceNull", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"),
|
||||||
|
List.of(new HookArgument.Parameter(0))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@code static pick(String input, boolean keep)}: {@code return keep ? input : null;} and
|
||||||
|
* {@code static wide()}: {@code return 5L;}.
|
||||||
|
*/
|
||||||
|
private Path target() throws Exception
|
||||||
|
{
|
||||||
|
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
|
||||||
|
cw.visit(V25, ACC_PUBLIC, "t/Target", null, "java/lang/Object", null);
|
||||||
|
|
||||||
|
Label returnNull = new Label();
|
||||||
|
|
||||||
|
MethodVisitor pick = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "pick", ReturnHookPatchTest.PICK.desc(), null, null);
|
||||||
|
pick.visitVarInsn(ILOAD, 1);
|
||||||
|
pick.visitJumpInsn(IFEQ, returnNull);
|
||||||
|
pick.visitVarInsn(ALOAD, 0);
|
||||||
|
pick.visitInsn(ARETURN);
|
||||||
|
pick.visitLabel(returnNull);
|
||||||
|
pick.visitInsn(ACONST_NULL);
|
||||||
|
pick.visitInsn(ARETURN);
|
||||||
|
pick.visitMaxs(0, 0);
|
||||||
|
|
||||||
|
MethodVisitor wide = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "wide", ReturnHookPatchTest.WIDE.desc(), null, null);
|
||||||
|
wide.visitLdcInsn(5L);
|
||||||
|
wide.visitInsn(LRETURN);
|
||||||
|
wide.visitMaxs(0, 0);
|
||||||
|
|
||||||
|
cw.visitEnd();
|
||||||
|
|
||||||
|
Path jar = this.dir.resolve("in.jar");
|
||||||
|
|
||||||
|
try (ZipOutputStream zip = new ZipOutputStream(Files.newOutputStream(jar)))
|
||||||
|
{
|
||||||
|
zip.putNextEntry(new ZipEntry("t/Target.class"));
|
||||||
|
zip.write(cw.toByteArray());
|
||||||
|
zip.closeEntry();
|
||||||
|
}
|
||||||
|
|
||||||
|
return jar;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void replacesTheAnchoredReturnValueOnly() throws Exception
|
||||||
|
{
|
||||||
|
Path out = this.dir.resolve("patched.jar");
|
||||||
|
|
||||||
|
new JarPatcher(List.of(new NullPatch(), new WidePatch())).patch(this.target(), out);
|
||||||
|
|
||||||
|
try (URLClassLoader loader = new URLClassLoader(new URL[]{out.toUri().toURL()}, ReturnHookPatchTest.class.getClassLoader()))
|
||||||
|
{
|
||||||
|
Class<?> target = loader.loadClass("t.Target");
|
||||||
|
|
||||||
|
assertEquals("kept", target.getMethod("pick", String.class, boolean.class).invoke(null, "kept", true));
|
||||||
|
assertEquals("hook null input", target.getMethod("pick", String.class, boolean.class).invoke(null, "input", false));
|
||||||
|
assertEquals(10L, target.getMethod("wide").invoke(null));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void reportsAnchorThatDoesNotEndInAReturn() throws Exception
|
||||||
|
{
|
||||||
|
Path in = this.target();
|
||||||
|
|
||||||
|
IllegalStateException e = assertThrows(
|
||||||
|
IllegalStateException.class,
|
||||||
|
() -> new JarPatcher(List.of(new NoReturnPatch())).patch(in, this.dir.resolve("out.jar"))
|
||||||
|
);
|
||||||
|
|
||||||
|
assertEquals("'NoReturnPatch': The last instruction of the anchor must be 'areturn'.", e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rejectsMethodWithoutReturnValue()
|
||||||
|
{
|
||||||
|
Anchor.Sequence anchor = new Anchor.Sequence(new Anchor.Method("run", "()V"), new Anchor.Instruction.Opcode(ARETURN));
|
||||||
|
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new ReturnHookPatch("t/Target", anchor, new Hook("t/Hooks", "hook", "()V"), List.of()) {});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rejectsHookWhoseFirstParameterIsNotTheReturnType()
|
||||||
|
{
|
||||||
|
Anchor.Sequence anchor = new Anchor.Sequence(ReturnHookPatchTest.WIDE, new Anchor.Instruction.Opcode(LRETURN));
|
||||||
|
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new ReturnHookPatch("t/Target", anchor, new Hook("t/Hooks", "hook", "(I)J"), List.of()) {});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rejectsHookThatReturnsAnotherType()
|
||||||
|
{
|
||||||
|
Anchor.Sequence anchor = new Anchor.Sequence(ReturnHookPatchTest.WIDE, new Anchor.Instruction.Opcode(LRETURN));
|
||||||
|
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new ReturnHookPatch("t/Target", anchor, new Hook("t/Hooks", "hook", "(J)I"), List.of()) {});
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user