Add mod command integration for Build 42: command hooks, lookup extensions, registry, and validation mechanisms. Include corresponding tests and documentation.

This commit is contained in:
Overlord committed 2026-10-03 11:27:06 +02:00
1 parent 22077514fe
commit af7174e128
26 files changed
+1117 -30

No files matched your search

@@ -18,6 +18,8 @@ public final class B42PatchSet implements PatchSet
new ServerTickPatch(),
new ServerStoppingPatch(),
new BackupStoragePatch(),
new CommandLookupPatch(),
new CommandListPatch(),
new IsoZombieVehiclePerformancePatch(),
new IsoZombieNetworkComponentPerformancePatch(),
new IsoZombieSpotChancePerformancePatch(),
@@ -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());
}
}
@@ -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)));
}
}
+2
View File
@@ -10,6 +10,8 @@ dependencies {
implementation(project(":api"))
compileOnly(files(projectZomboid.serverJar))
// ModCommandsTest checks command classes against the game's command framework.
testImplementation(files(projectZomboid.serverJar))
testImplementation(platform(libs.junit.bom))
testImplementation(libs.junit.jupiter)
testRuntimeOnly(libs.junit.platform.launcher)
@@ -1,11 +1,12 @@
package dev.overlord.zomboidforge.compat.b42;
import dev.overlord.zomboidforge.compat.b42.commands.ModCommands;
import dev.overlord.zomboidforge.core.Forge;
/** The one {@link Forge} of the server, shared by the hook classes. */
public final class ForgeInstance
{
public static final Forge FORGE = Forge.fromSystemProperties();
public static final Forge FORGE = Forge.fromSystemProperties(ModCommands::check);
private ForgeInstance() {}
}
@@ -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;
}
}
@@ -0,0 +1,10 @@
/**
* Admin commands of mods in Build 42: checks for registered command classes and the lookup that
* mirrors {@code zombie.commands.CommandBase.findCommandCls}.
*
* @noinspection UnstableApiUsage, RedundantSuppression
*/
@NotNullByDefault
package dev.overlord.zomboidforge.compat.b42.commands;
import org.jetbrains.annotations.NotNullByDefault;
@@ -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;
}
}
}
@@ -33,10 +33,8 @@ public final class ZombieVehicleHooks
* and is skipped here.
*/
public static @Nullable Vector3f getIntersectPoint(
@NotNull BaseVehicle vehicle,
@NotNull Vector3f start,
@NotNull Vector3f end,
@Nullable Vector3f result
BaseVehicle vehicle, Vector3f start,
Vector3f end, @Nullable Vector3f result
) {
VehicleScript script = vehicle.getScript();
Vector3f extents = script.getExtents();
@@ -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");
}
}