diff --git a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/B42PatchSet.java b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/B42PatchSet.java index 68376a4..7609371 100644 --- a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/B42PatchSet.java +++ b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/B42PatchSet.java @@ -27,7 +27,9 @@ public final class B42PatchSet implements PatchSet new IsoGameCharacterStateMachinePerformancePatch(), new ZombieVoronoiPerformancePatch(), new ZomboidFileSystemInitPerformancePatch(), - new ServerMapCellBudgetPerformancePatch() + new ServerMapCellBudgetPerformancePatch(), + new WorldGenUtilsPlacementPerformancePatch(), + new WorldGenChunkRulesPerformancePatch() ); @Override diff --git a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/perf/WorldGenChunkRulesPerformancePatch.java b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/perf/WorldGenChunkRulesPerformancePatch.java new file mode 100644 index 0000000..331faa4 --- /dev/null +++ b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/perf/WorldGenChunkRulesPerformancePatch.java @@ -0,0 +1,76 @@ +package dev.overlord.zomboidforge.compat.b42.perf; + +import dev.overlord.zomboidforge.api.GameVersion; +import dev.overlord.zomboidforge.patcher.Anchor; +import dev.overlord.zomboidforge.patcher.Hook; +import dev.overlord.zomboidforge.patcher.MethodBody; +import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch; + +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.MethodNode; + +/** + * The tile rules of {@code WorldGenChunk} with cached compiled patterns, like + * {@link WorldGenUtilsPlacementPerformancePatch}: + * + * + */ +public final class WorldGenChunkRulesPerformancePatch extends PerformancePatch +{ + private static final String STRING = "java/lang/String"; + private static final String MATCHES = "(Ljava/lang/String;)Z"; + private static final String HOOKS = "dev/overlord/zomboidforge/compat/b42/hooks/WorldGenHooks"; + + private static final Anchor.Call ANCHOR = new Anchor.Call( + new Anchor.Method("isProtected", "(Ljava/util/List;Ljava/lang/String;)Z"), + WorldGenChunkRulesPerformancePatch.STRING, "matches", WorldGenChunkRulesPerformancePatch.MATCHES + ); + + private static final Anchor.Call CLEAN_CHUNK = new Anchor.Call( + new Anchor.Method("cleanChunk", "(Lzombie/iso/IsoChunk;Ljava/lang/String;Ljava/lang/String;)V"), + WorldGenChunkRulesPerformancePatch.STRING, "matches", WorldGenChunkRulesPerformancePatch.MATCHES + ); + + private static final Hook HOOK = new Hook( + WorldGenChunkRulesPerformancePatch.HOOKS, "isProtected", "(Ljava/util/List;Ljava/lang/String;)Z" + ); + + private static final Hook MATCHES_HOOK = new Hook( + WorldGenChunkRulesPerformancePatch.HOOKS, "matches", "(Ljava/lang/String;Ljava/lang/String;)Z" + ); + + public WorldGenChunkRulesPerformancePatch() { + super("zombie/iso/worldgen/WorldGenChunk", WorldGenChunkRulesPerformancePatch.ANCHOR, WorldGenChunkRulesPerformancePatch.HOOK); + } + + // + + @Override + public boolean appliesTo(GameVersion version) { return version.matches("42.21"); } + + @Override + public void apply(ClassNode node) + { + MethodNode isProtected = WorldGenChunkRulesPerformancePatch.ANCHOR.in().resolve(node); + MethodNode cleanChunk = WorldGenChunkRulesPerformancePatch.CLEAN_CHUNK.in().resolve(node); + MethodInsnNode matches = WorldGenChunkRulesPerformancePatch.CLEAN_CHUNK.resolve(node); + + MethodBody.delegate(node, isProtected, WorldGenChunkRulesPerformancePatch.HOOK); + + // The hook takes the receiver as its first argument: the stack is unchanged. + cleanChunk.instructions.set(matches, new MethodInsnNode( + Opcodes.INVOKESTATIC, + WorldGenChunkRulesPerformancePatch.MATCHES_HOOK.owner(), + WorldGenChunkRulesPerformancePatch.MATCHES_HOOK.name(), + WorldGenChunkRulesPerformancePatch.MATCHES_HOOK.desc(), + false + )); + } +} diff --git a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/perf/WorldGenUtilsPlacementPerformancePatch.java b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/perf/WorldGenUtilsPlacementPerformancePatch.java new file mode 100644 index 0000000..deeeee9 --- /dev/null +++ b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/perf/WorldGenUtilsPlacementPerformancePatch.java @@ -0,0 +1,56 @@ +package dev.overlord.zomboidforge.compat.b42.perf; + +import dev.overlord.zomboidforge.api.GameVersion; +import dev.overlord.zomboidforge.patcher.Anchor; +import dev.overlord.zomboidforge.patcher.Hook; +import dev.overlord.zomboidforge.patcher.MethodBody; +import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch; + +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.MethodNode; + +/** + * Replaces the body of {@code WorldGenUtils.canPlace(List, String)} with a call to + * {@code WorldGenHooks.canPlace}, which caches the compiled rules: + * + *
{@code
+ * public boolean canPlace(List placement, String floorName)
+ * {
+ *     return WorldGenHooks.canPlace(placement, floorName);
+ * }
+ * }
+ * + * Vanilla builds and compiles a regular expression per rule per call, for every square of a new + * chunk, on the chunk loader thread. Together with {@link WorldGenChunkRulesPerformancePatch} + * this halves the time to create a new chunk and removes most of the garbage the server + * produces while players explore; {@link ServerMapCellBudgetPerformancePatch} keeps the faster + * cells from bunching up on the main thread. + */ +public final class WorldGenUtilsPlacementPerformancePatch extends PerformancePatch +{ + private static final Anchor.Call ANCHOR = new Anchor.Call( + new Anchor.Method("canPlace", "(Ljava/util/List;Ljava/lang/String;)Z"), + "java/lang/String", "matches", "(Ljava/lang/String;)Z" + ); + + private static final Hook HOOK = new Hook( + "dev/overlord/zomboidforge/compat/b42/hooks/WorldGenHooks", "canPlace", "(Ljava/util/List;Ljava/lang/String;)Z" + ); + + public WorldGenUtilsPlacementPerformancePatch() { + super("zombie/iso/worldgen/WorldGenUtils", WorldGenUtilsPlacementPerformancePatch.ANCHOR, WorldGenUtilsPlacementPerformancePatch.HOOK); + } + + // + + @Override + public boolean appliesTo(GameVersion version) { return version.matches("42.21"); } + + @Override + public void apply(ClassNode node) + { + MethodNode method = WorldGenUtilsPlacementPerformancePatch.ANCHOR.in().resolve(node); + + MethodBody.delegate(node, method, WorldGenUtilsPlacementPerformancePatch.HOOK); + } +} diff --git a/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/perf/WorldGenChunkRulesPerformancePatchTest.java b/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/perf/WorldGenChunkRulesPerformancePatchTest.java new file mode 100644 index 0000000..7a87235 --- /dev/null +++ b/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/perf/WorldGenChunkRulesPerformancePatchTest.java @@ -0,0 +1,160 @@ +package dev.overlord.zomboidforge.compat.b42.perf; + +import dev.overlord.zomboidforge.api.GameVersion; +import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner; +import dev.overlord.zomboidforge.compat.b42.patches.support.PackageScan; + +import org.junit.jupiter.api.Test; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.MethodNode; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +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.CHECKCAST; +import static org.objectweb.asm.Opcodes.INVOKESPECIAL; +import static org.objectweb.asm.Opcodes.INVOKESTATIC; +import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL; +import static org.objectweb.asm.Opcodes.IRETURN; +import static org.objectweb.asm.Opcodes.POP; +import static org.objectweb.asm.Opcodes.RETURN; +import static org.objectweb.asm.Opcodes.V25; + +class WorldGenChunkRulesPerformancePatchTest +{ + private static final String CHUNK = "zombie/iso/worldgen/WorldGenChunk"; + private static final String HOOKS = "dev/overlord/zomboidforge/compat/b42/hooks/WorldGenHooks"; + private static final String MATCHES = "(Ljava/lang/String;)Z"; + + /** + * {@code WorldGenChunk} with a reduced {@code isProtected} ({@code return tile.matches(null);}) + * and, when {@code withCleanChunk}, a reduced {@code cleanChunk} + * ({@code material.matches(filter);}). + */ + private static ClassNode chunk(boolean withCleanChunk) + { + ClassNode node = new ClassNode(); + node.visit(V25, ACC_PUBLIC, WorldGenChunkRulesPerformancePatchTest.CHUNK, null, "java/lang/Object", null); + + MethodVisitor constructor = node.visitMethod(ACC_PUBLIC, "", "()V", null, null); + constructor.visitVarInsn(ALOAD, 0); + constructor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "", "()V", false); + constructor.visitInsn(RETURN); + constructor.visitMaxs(0, 0); + + MethodVisitor isProtected = node.visitMethod(ACC_PUBLIC, "isProtected", "(Ljava/util/List;Ljava/lang/String;)Z", null, null); + isProtected.visitVarInsn(ALOAD, 2); + isProtected.visitInsn(ACONST_NULL); + isProtected.visitTypeInsn(CHECKCAST, "java/lang/String"); + isProtected.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "matches", WorldGenChunkRulesPerformancePatchTest.MATCHES, false); + isProtected.visitInsn(IRETURN); + isProtected.visitMaxs(0, 0); + + if (withCleanChunk) + { + MethodVisitor cleanChunk = node.visitMethod(ACC_PUBLIC, "cleanChunk", "(Lzombie/iso/IsoChunk;Ljava/lang/String;Ljava/lang/String;)V", null, null); + cleanChunk.visitVarInsn(ALOAD, 2); + cleanChunk.visitVarInsn(ALOAD, 3); + cleanChunk.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "matches", WorldGenChunkRulesPerformancePatchTest.MATCHES, false); + cleanChunk.visitInsn(POP); + cleanChunk.visitInsn(RETURN); + cleanChunk.visitMaxs(0, 0); + } + + return node; + } + + private static List calls(ClassNode node, String methodName) + { + MethodNode method = node.methods.stream().filter(m -> m.name.equals(methodName)).findFirst().orElseThrow(); + List calls = new ArrayList<>(); + + for (AbstractInsnNode instruction : method.instructions) { + if (instruction instanceof MethodInsnNode call) calls.add(call); + } + + return calls; + } + + @Test + void anchorMatchesTheTarget() + { + new WorldGenChunkRulesPerformancePatch().anchor().verify(WorldGenChunkRulesPerformancePatchTest.chunk(true)); + } + + @Test + void replacesIsProtectedAndTheMatchesCallOfCleanChunk() + { + ClassNode node = WorldGenChunkRulesPerformancePatchTest.chunk(true); + new WorldGenChunkRulesPerformancePatch().apply(node); + + List isProtected = WorldGenChunkRulesPerformancePatchTest.calls(node, "isProtected"); + assertEquals(1, isProtected.size()); + assertEquals(INVOKESTATIC, isProtected.getFirst().getOpcode()); + assertEquals(WorldGenChunkRulesPerformancePatchTest.HOOKS, isProtected.getFirst().owner); + assertEquals("isProtected", isProtected.getFirst().name); + + List cleanChunk = WorldGenChunkRulesPerformancePatchTest.calls(node, "cleanChunk"); + assertEquals(1, cleanChunk.size()); + assertEquals(INVOKESTATIC, cleanChunk.getFirst().getOpcode()); + assertEquals(WorldGenChunkRulesPerformancePatchTest.HOOKS, cleanChunk.getFirst().owner); + assertEquals("matches", cleanChunk.getFirst().name); + assertEquals("(Ljava/lang/String;Ljava/lang/String;)Z", cleanChunk.getFirst().desc); + } + + @Test + void patchedClassIsValid() throws ClassNotFoundException + { + ClassNode node = WorldGenChunkRulesPerformancePatchTest.chunk(true); + new WorldGenChunkRulesPerformancePatch().apply(node); + + // Initializing links the class, which runs the bytecode verifier on both changed methods. + ClassDefiner definer = new ClassDefiner(); + definer.define(node); + Class.forName(node.name.replace('/', '.'), true, definer); + } + + @Test + void failsWithoutCleanChunk() + { + ClassNode node = WorldGenChunkRulesPerformancePatchTest.chunk(false); + + assertThrows(IllegalStateException.class, () -> new WorldGenChunkRulesPerformancePatch().apply(node)); + } + + /** {@code HookExistenceTest} checks the patch's {@code hook()}; this is the second one it calls. */ + @Test + void matchesHookExistsAsPublicStaticMethod() throws IOException + { + ClassNode hooks = PackageScan.read(WorldGenChunkRulesPerformancePatchTest.HOOKS); + + assertTrue(hooks.methods.stream().anyMatch(method -> + method.name.equals("matches") + && method.desc.equals("(Ljava/lang/String;Ljava/lang/String;)Z") + && (method.access & ACC_PUBLIC) != 0 && (method.access & ACC_STATIC) != 0 + )); + } + + @Test + void appliesOnlyToVerifiedVersions() + { + WorldGenChunkRulesPerformancePatch patch = new WorldGenChunkRulesPerformancePatch(); + + assertTrue(patch.appliesTo(GameVersion.parse("42.21.0"))); + assertTrue(patch.appliesTo(GameVersion.parse("42.21.3"))); + assertFalse(patch.appliesTo(GameVersion.parse("42.20.3"))); + assertFalse(patch.appliesTo(GameVersion.parse("42.22.0"))); + } +} diff --git a/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/perf/WorldGenUtilsPlacementPerformancePatchTest.java b/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/perf/WorldGenUtilsPlacementPerformancePatchTest.java new file mode 100644 index 0000000..9fe47a5 --- /dev/null +++ b/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/perf/WorldGenUtilsPlacementPerformancePatchTest.java @@ -0,0 +1,134 @@ +package dev.overlord.zomboidforge.compat.b42.perf; + +import dev.overlord.zomboidforge.api.GameVersion; +import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner; + +import org.junit.jupiter.api.Test; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.MethodNode; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.objectweb.asm.Opcodes.ACC_PUBLIC; +import static org.objectweb.asm.Opcodes.ALOAD; +import static org.objectweb.asm.Opcodes.CHECKCAST; +import static org.objectweb.asm.Opcodes.ICONST_0; +import static org.objectweb.asm.Opcodes.INVOKEINTERFACE; +import static org.objectweb.asm.Opcodes.INVOKESPECIAL; +import static org.objectweb.asm.Opcodes.INVOKESTATIC; +import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL; +import static org.objectweb.asm.Opcodes.IRETURN; +import static org.objectweb.asm.Opcodes.POP; +import static org.objectweb.asm.Opcodes.RETURN; +import static org.objectweb.asm.Opcodes.V25; + +class WorldGenUtilsPlacementPerformancePatchTest +{ + private static final String UTILS = "zombie/iso/worldgen/WorldGenUtils"; + + /** + * {@code WorldGenUtils} with a reduced {@code canPlace}: + * {@code return floorName.matches((String) placement.get(0));}, reading {@code this} first + * when {@code usesThis}. + */ + private static ClassNode utils(boolean usesThis) + { + ClassNode node = new ClassNode(); + node.visit(V25, ACC_PUBLIC, WorldGenUtilsPlacementPerformancePatchTest.UTILS, null, "java/lang/Object", null); + + MethodVisitor constructor = node.visitMethod(ACC_PUBLIC, "", "()V", null, null); + constructor.visitVarInsn(ALOAD, 0); + constructor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "", "()V", false); + constructor.visitInsn(RETURN); + constructor.visitMaxs(0, 0); + + MethodVisitor canPlace = node.visitMethod(ACC_PUBLIC, "canPlace", "(Ljava/util/List;Ljava/lang/String;)Z", null, null); + if (usesThis) + { + canPlace.visitVarInsn(ALOAD, 0); + canPlace.visitInsn(POP); + } + canPlace.visitVarInsn(ALOAD, 2); + canPlace.visitVarInsn(ALOAD, 1); + canPlace.visitInsn(ICONST_0); + canPlace.visitMethodInsn(INVOKEINTERFACE, "java/util/List", "get", "(I)Ljava/lang/Object;", true); + canPlace.visitTypeInsn(CHECKCAST, "java/lang/String"); + canPlace.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "matches", "(Ljava/lang/String;)Z", false); + canPlace.visitInsn(IRETURN); + canPlace.visitMaxs(0, 0); + + return node; + } + + private static List instructions(ClassNode node) + { + MethodNode canPlace = node.methods.stream().filter(method -> method.name.equals("canPlace")).findFirst().orElseThrow(); + List instructions = new ArrayList<>(); + + for (AbstractInsnNode instruction : canPlace.instructions) { + if (instruction.getOpcode() != -1) instructions.add(instruction); + } + + return instructions; + } + + @Test + void anchorMatchesTheTarget() + { + new WorldGenUtilsPlacementPerformancePatch().anchor().verify(WorldGenUtilsPlacementPerformancePatchTest.utils(false)); + } + + @Test + void replacesTheBodyWithTheHookCall() + { + ClassNode node = WorldGenUtilsPlacementPerformancePatchTest.utils(false); + new WorldGenUtilsPlacementPerformancePatch().apply(node); + + List instructions = WorldGenUtilsPlacementPerformancePatchTest.instructions(node); + assertEquals(List.of(ALOAD, ALOAD, INVOKESTATIC, IRETURN), instructions.stream().map(AbstractInsnNode::getOpcode).toList()); + + MethodInsnNode call = (MethodInsnNode) instructions.get(2); + assertEquals("dev/overlord/zomboidforge/compat/b42/hooks/WorldGenHooks", call.owner); + assertEquals("canPlace", call.name); + assertEquals("(Ljava/util/List;Ljava/lang/String;)Z", call.desc); + } + + @Test + void patchedClassIsValid() throws ClassNotFoundException + { + ClassNode node = WorldGenUtilsPlacementPerformancePatchTest.utils(false); + new WorldGenUtilsPlacementPerformancePatch().apply(node); + + // Initializing links the class, which runs the bytecode verifier on the new body. + ClassDefiner definer = new ClassDefiner(); + definer.define(node); + Class.forName(node.name.replace('/', '.'), true, definer); + } + + @Test + void failsWhenTheBodyUsesThis() + { + ClassNode node = WorldGenUtilsPlacementPerformancePatchTest.utils(true); + + assertThrows(IllegalStateException.class, () -> new WorldGenUtilsPlacementPerformancePatch().apply(node)); + } + + @Test + void appliesOnlyToVerifiedVersions() + { + WorldGenUtilsPlacementPerformancePatch patch = new WorldGenUtilsPlacementPerformancePatch(); + + assertTrue(patch.appliesTo(GameVersion.parse("42.21.0"))); + assertTrue(patch.appliesTo(GameVersion.parse("42.21.3"))); + assertFalse(patch.appliesTo(GameVersion.parse("42.20.3"))); + assertFalse(patch.appliesTo(GameVersion.parse("42.22.0"))); + } +} diff --git a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/WorldGenHooks.java b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/WorldGenHooks.java new file mode 100644 index 0000000..63c88e1 --- /dev/null +++ b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/WorldGenHooks.java @@ -0,0 +1,33 @@ +package dev.overlord.zomboidforge.compat.b42.hooks; + +import dev.overlord.zomboidforge.compat.b42.util.TileRules; + +import java.util.List; + +/** + * Hooks called by patched {@code zombie.iso.worldgen.WorldGenUtils} and + * {@code zombie.iso.worldgen.WorldGenChunk} code. Each returns what the vanilla code returns + * ({@link TileRules}). + */ +public final class WorldGenHooks +{ + private WorldGenHooks() {} + + /** Replaces the body of {@code WorldGenUtils.canPlace(List, String)}, which reads no field. */ + public static boolean canPlace(List placement, String floorName) + { + return TileRules.canPlace(placement, floorName); + } + + /** Replaces the body of {@code WorldGenChunk.isProtected(List, String)}, which reads no field. */ + public static boolean isProtected(List protectedTiles, String tile) + { + return TileRules.isProtected(protectedTiles, tile); + } + + /** Replaces {@code floorMaterial.matches(mat)} in {@code WorldGenChunk.cleanChunk}. */ + public static boolean matches(String input, String regex) + { + return TileRules.matches(input, regex); + } +} diff --git a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/util/TileRules.java b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/util/TileRules.java new file mode 100644 index 0000000..18b0cb8 --- /dev/null +++ b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/util/TileRules.java @@ -0,0 +1,121 @@ +package dev.overlord.zomboidforge.compat.b42.util; + +import java.util.List; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.regex.Pattern; + +/** + * The tile rules of the world generation ({@code WorldGenUtils.canPlace}, + * {@code WorldGenChunk.isProtected} and {@code cleanChunk}) with compiled patterns cached. + * + *

Vanilla turns each rule into a regular expression per call ({@code "^" + rule}, then + * {@code .} quoted, {@code *} to {@code .*}, {@code ?} to {@code .?}) and matches it with + * {@code String.matches}, which compiles a new {@link Pattern} each time; this happens for every + * rule of every square of a new chunk. {@code String.matches(regex)} is + * {@code Pattern.compile(regex).matcher(this).matches()}, so a pattern compiled once gives the + * same answers. The rules come from the biome definitions, so the caches stay small. A rule that + * does not compile is not cached and throws on every call, as in vanilla. + */ +public final class TileRules +{ + private static final ConcurrentHashMap PATTERNS = new ConcurrentHashMap<>(); + private static final ConcurrentHashMap PLACEMENTS = new ConcurrentHashMap<>(); + private static final ConcurrentHashMap PROTECTED = new ConcurrentHashMap<>(); + + private TileRules() {} + + /** A placement rule: {@code allows} is {@code false} for rules starting with {@code !}. */ + private record Placement(boolean allows, Pattern pattern) {} + + /** {@code input.matches(regex)}. */ + public static boolean matches(String input, String regex) + { + // Vanilla calls matches on the input: a null input fails before the regex is compiled. + Objects.requireNonNull(input); + + Pattern pattern = TileRules.PATTERNS.get(regex); + if (pattern == null) + { + pattern = Pattern.compile(regex); + TileRules.PATTERNS.putIfAbsent(regex, pattern); + } + + return pattern.matcher(input).matches(); + } + + /** + * {@code WorldGenUtils.canPlace(placement, floorName)}: the last rule that matches decides, + * {@code false} when none matches. + */ + public static boolean canPlace(List placement, String floorName) + { + boolean toBePlaced = false; + + for (Object entry : placement) + { + String rule = (String) entry; + Placement compiled = TileRules.PLACEMENTS.get(rule); + + // Vanilla reads the rule first, then calls matches on floorName, then compiles. + Objects.requireNonNull(floorName); + if (compiled == null) + { + compiled = TileRules.placement(rule); + TileRules.PLACEMENTS.putIfAbsent(rule, compiled); + } + if (compiled.pattern().matcher(floorName).matches()) toBePlaced = compiled.allows(); + } + + return toBePlaced; + } + + /** + * {@code WorldGenChunk.isProtected(protectedTiles, tile)}: whether any rule matches. Vanilla + * builds {@code "^" + rule}, so a {@code null} rule is the text {@code null}; it shares the + * cache key of that text. + */ + public static boolean isProtected(List protectedTiles, String tile) + { + for (Object entry : protectedTiles) + { + String rule = String.valueOf((String) entry); + Pattern compiled = TileRules.PROTECTED.get(rule); + + Objects.requireNonNull(tile); + if (compiled == null) + { + compiled = Pattern.compile(TileRules.regex(rule)); + TileRules.PROTECTED.putIfAbsent(rule, compiled); + } + if (compiled.matcher(tile).matches()) return true; + } + + return false; + } + + private static Placement placement(String rule) + { + boolean allows = true; + String body = rule; + + if (body.startsWith("!")) + { + allows = false; + body = body.substring(1); + } + + return new Placement(allows, Pattern.compile(TileRules.regex(body))); + } + + /** The regular expression vanilla builds from a rule. */ + private static String regex(String rule) + { + String regex = "^" + rule; + regex = regex.replace(".", "\\."); + regex = regex.replace("*", ".*"); + regex = regex.replace("?", ".?"); + + return regex; + } +} diff --git a/compat/b42/runtime/src/test/java/dev/overlord/zomboidforge/compat/b42/util/TileRulesTest.java b/compat/b42/runtime/src/test/java/dev/overlord/zomboidforge/compat/b42/util/TileRulesTest.java new file mode 100644 index 0000000..de4accf --- /dev/null +++ b/compat/b42/runtime/src/test/java/dev/overlord/zomboidforge/compat/b42/util/TileRulesTest.java @@ -0,0 +1,198 @@ +package dev.overlord.zomboidforge.compat.b42.util; + +import org.junit.jupiter.api.Test; + +import zombie.iso.worldgen.WorldGenChunk; +import zombie.iso.worldgen.WorldGenUtils; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Random; +import java.util.TreeSet; +import java.util.concurrent.Callable; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +/** Compares {@link TileRules} with the vanilla methods of the game jar. */ +class TileRulesTest +{ + /** Rules with every special character of the conversion, negation, and edge cases. */ + private static final List RULES = List.of( + "blends_natural_01_*", "!blends_natural_02_*", "vegetation_drying*", "floors_exterior_natural_01_?", + "a.b", "*", "!*", "?", "blends_natural_01_1", "", "!", "null", "x*y?z" + ); + + private static final List NAMES = List.of( + "blends_natural_01_16", "blends_natural_02_3", "vegetation_drying_01_0", "floors_exterior_natural_01_1", + "floors_exterior_natural_01_12", "a.b", "axb", "", "null", "xyz", "x__y_z", "X", "blends_natural_01_1" + ); + + private static final Pattern QUOTED_RULE = Pattern.compile("\"(!?[A-Za-z0-9_.*?]+)\""); + + /** Outcome of a call: its result or the class of what it threw. */ + private static String outcome(Callable call) + { + try { return String.valueOf(call.call()); } + catch (Throwable t) { return t.getClass().getName(); } + } + + private static WorldGenChunk chunkWithoutConstructor() throws ReflectiveOperationException + { + // isProtected reads no field; WorldGenChunk's constructor needs a running world. + Class unsafeClass = Class.forName("sun.misc.Unsafe"); + Field field = unsafeClass.getDeclaredField("theUnsafe"); + field.setAccessible(true); + + return (WorldGenChunk) unsafeClass.getMethod("allocateInstance", Class.class).invoke(field.get(null), WorldGenChunk.class); + } + + /** All lists of up to three rules from {@code rules}, in every order. */ + private static List> ruleLists(List rules) + { + List> lists = new ArrayList<>(); + lists.add(List.of()); + + for (String first : rules) + { + lists.add(List.of(first)); + for (String second : rules) + { + lists.add(List.of(first, second)); + for (String third : rules) lists.add(List.of(first, second, third)); + } + } + + return lists; + } + + private static void compare(List> lists, List names) throws ReflectiveOperationException + { + WorldGenChunk chunk = TileRulesTest.chunkWithoutConstructor(); + + for (List rules : lists) + { + for (String name : names) + { + assertEquals( + TileRulesTest.outcome(() -> WorldGenUtils.INSTANCE.canPlace(rules, name)), + TileRulesTest.outcome(() -> TileRules.canPlace(rules, name)), + () -> "canPlace(" + rules + ", " + name + ")" + ); + assertEquals( + TileRulesTest.outcome(() -> chunk.isProtected(rules, name)), + TileRulesTest.outcome(() -> TileRules.isProtected(rules, name)), + () -> "isProtected(" + rules + ", " + name + ")" + ); + } + } + } + + @Test + void answersLikeVanillaForEdgeCases() throws ReflectiveOperationException + { + TileRulesTest.compare(TileRulesTest.ruleLists(TileRulesTest.RULES), TileRulesTest.NAMES); + } + + @Test + void throwsLikeVanillaForBrokenRules() throws ReflectiveOperationException + { + List> lists = new ArrayList<>(); + lists.add(List.of("a(b")); // not a valid regular expression + lists.add(List.of("vegetation_drying*", "a[b")); + lists.add(Arrays.asList("vegetation_drying*", null)); // canPlace fails, isProtected matches "^null" + lists.add(Arrays.asList((String) null)); + + List names = new ArrayList<>(TileRulesTest.NAMES); + names.add(null); + + TileRulesTest.compare(lists, names); + } + + /** + * The quoted rules of the game's world generation Lua files ({@code media/lua/server/WorldGen} + * next to the game jar, when the jar is part of an installed server), against names derived + * from them. + */ + @Test + void answersLikeVanillaForTheGameRules() throws Exception + { + Path jar = Path.of(WorldGenUtils.class.getProtectionDomain().getCodeSource().getLocation().toURI()); + Path parent = jar.getParent(); + assumeTrue(parent.getFileName() != null && parent.getFileName().toString().equals("java"), "The game jar " + jar + " is not in an installed server."); + + Path folder = parent.getParent().resolve("media/lua/server/WorldGen"); + assumeTrue(Files.isDirectory(folder), "No world generation scripts at " + folder); + + TreeSet rules = new TreeSet<>(); + try (Stream files = Files.walk(folder)) + { + for (Path file : files.filter(path -> path.toString().endsWith(".lua")).toList()) + { + Matcher matcher = TileRulesTest.QUOTED_RULE.matcher(TileRulesTest.read(file)); + while (matcher.find()) rules.add(matcher.group(1)); + } + } + assertTrue(rules.size() > 100, () -> "Only " + rules.size() + " rules in " + folder); + + // Names: each rule with its wildcards filled in, some of them changed. + Random random = new Random(7L); + List names = new ArrayList<>(); + for (String rule : rules) + { + String name = rule.replace("!", "").replace("*", String.valueOf(random.nextInt(64))).replace("?", ""); + names.add(name); + names.add(name + "x"); + } + + // Random rule lists of up to four rules, each against a sample of the names. + List pool = new ArrayList<>(rules); + List> lists = new ArrayList<>(); + for (int i = 0; i < 2_000; i++) + { + List list = new ArrayList<>(); + for (int n = random.nextInt(5); n > 0; n--) list.add(pool.get(random.nextInt(pool.size()))); + lists.add(list); + } + + WorldGenChunk chunk = TileRulesTest.chunkWithoutConstructor(); + for (List list : lists) + { + for (int i = 0; i < 20; i++) + { + String name = names.get(random.nextInt(names.size())); + + assertEquals(WorldGenUtils.INSTANCE.canPlace(list, name), TileRules.canPlace(list, name), () -> "canPlace(" + list + ", " + name + ")"); + assertEquals(chunk.isProtected(list, name), TileRules.isProtected(list, name), () -> "isProtected(" + list + ", " + name + ")"); + } + } + } + + @Test + void matchesLikeString() + { + for (String regex : List.of("^Sand", "^Road_.*", "^Road_.*", "^a\\.b", "^x.?")) + { + for (String input : List.of("Sand", "Sandy", "Road_1", "road_1", "a.b", "axb", "x", "xy", "xyz")) + { + assertEquals(input.matches(regex), TileRules.matches(input, regex), () -> input + " ~ " + regex); + } + } + } + + private static String read(Path file) + { + try { return Files.readString(file, StandardCharsets.ISO_8859_1); } + catch (IOException e) { throw new IllegalStateException("Cannot read '" + file + "'.", e); } + } +} diff --git a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/MethodBody.java b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/MethodBody.java new file mode 100644 index 0000000..8b2c6eb --- /dev/null +++ b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/MethodBody.java @@ -0,0 +1,68 @@ +package dev.overlord.zomboidforge.patcher; + +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.InsnNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.MethodNode; +import org.objectweb.asm.tree.VarInsnNode; + +import java.util.Arrays; + +/** Replaces the body of a method of the target class with a call to a {@link Hook}. */ +public final class MethodBody +{ + private MethodBody() {} + + /** + * Replaces the body of {@code method} with {@code return hook(arguments);}: the hook receives + * the method's arguments, without {@code this}, and has the method's parameter and return + * types. Fails when the method has no body, when the types differ, or when an instance + * method's old body uses {@code this}, which the hook would not receive. + */ + public static void delegate(ClassNode node, MethodNode method, Hook hook) + { + String name = "'" + node.name + "." + method.name + method.desc + "'"; + Type type = Type.getMethodType(method.desc); + Type hookType = Type.getMethodType(hook.desc()); + boolean isStatic = (method.access & Opcodes.ACC_STATIC) != 0; + + if ((method.access & (Opcodes.ACC_ABSTRACT | Opcodes.ACC_NATIVE)) != 0) + throw new IllegalStateException(name + " has no body."); + + if (!Arrays.equals(type.getArgumentTypes(), hookType.getArgumentTypes()) || !type.getReturnType().equals(hookType.getReturnType())) + throw new IllegalStateException(name + " and its hook '" + hook.owner() + "." + hook.name() + hook.desc() + "' have different types."); + + if (!isStatic && MethodBody.usesThis(method)) + throw new IllegalStateException(name + " uses 'this', which the hook does not receive."); + + // The local variable table and annotations refer to labels of the old body. + method.instructions.clear(); + method.tryCatchBlocks.clear(); + method.localVariables = null; + method.visibleLocalVariableAnnotations = null; + method.invisibleLocalVariableAnnotations = null; + + int slot = isStatic ? 0 : 1; + for (Type argument : type.getArgumentTypes()) + { + method.instructions.add(new VarInsnNode(argument.getOpcode(Opcodes.ILOAD), slot)); + slot += argument.getSize(); + } + + method.instructions.add(new MethodInsnNode(Opcodes.INVOKESTATIC, hook.owner(), hook.name(), hook.desc(), false)); + method.instructions.add(new InsnNode(type.getReturnType().getOpcode(Opcodes.IRETURN))); + } + + /** Whether the method reads or writes local variable 0, which holds {@code this}. */ + private static boolean usesThis(MethodNode method) + { + for (AbstractInsnNode instruction : method.instructions) { + if (instruction instanceof VarInsnNode variable && variable.var == 0) return true; + } + + return false; + } +} diff --git a/patcher/src/test/java/dev/overlord/zomboidforge/patcher/MethodBodyTest.java b/patcher/src/test/java/dev/overlord/zomboidforge/patcher/MethodBodyTest.java new file mode 100644 index 0000000..5219702 --- /dev/null +++ b/patcher/src/test/java/dev/overlord/zomboidforge/patcher/MethodBodyTest.java @@ -0,0 +1,180 @@ +package dev.overlord.zomboidforge.patcher; + +import org.junit.jupiter.api.Test; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.MethodNode; + +import java.lang.reflect.Method; +import java.util.ArrayList; + +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; +import static org.objectweb.asm.Opcodes.ACC_ABSTRACT; +import static org.objectweb.asm.Opcodes.ACC_PUBLIC; +import static org.objectweb.asm.Opcodes.ACC_STATIC; +import static org.objectweb.asm.Opcodes.ALOAD; +import static org.objectweb.asm.Opcodes.ICONST_0; +import static org.objectweb.asm.Opcodes.INVOKESPECIAL; +import static org.objectweb.asm.Opcodes.IRETURN; +import static org.objectweb.asm.Opcodes.LCONST_0; +import static org.objectweb.asm.Opcodes.LRETURN; +import static org.objectweb.asm.Opcodes.POP; +import static org.objectweb.asm.Opcodes.RETURN; +import static org.objectweb.asm.Opcodes.V25; + +/** Runs methods whose bodies {@link MethodBody#delegate} replaced with calls to the hooks below. */ +public class MethodBodyTest +{ + private static final String TARGET = "t/Target"; + private static final String HOOKS = "dev/overlord/zomboidforge/patcher/MethodBodyTest"; + + public static String recorded; + + public static int sum(int a, int b) { return a + b; } + + /** Two-slot arguments around a one-slot one, so wrong slot numbers show. */ + public static long combine(long a, String b, double c) { return a * 1000 + b.length() * 100 + (long) c; } + + public static void record(String value) { MethodBodyTest.recorded = value; } + + /** Defines classes from nodes, with the test classes as parent so the hooks resolve. */ + private static final class Definer extends ClassLoader + { + Definer() { super(MethodBodyTest.class.getClassLoader()); } + + Class define(ClassNode node) + { + ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES); + node.accept(writer); + byte[] bytes = writer.toByteArray(); + return this.defineClass(node.name.replace('/', '.'), bytes, 0, bytes.length); + } + } + + /** + * {@code t/Target} with a constructor and one method whose body returns a constant (or uses + * {@code this} when {@code usesThis}). + */ + private static ClassNode target(int access, String name, String desc, boolean usesThis) + { + ClassNode node = new ClassNode(); + node.visit(V25, ACC_PUBLIC | ((access & ACC_ABSTRACT) != 0 ? ACC_ABSTRACT : 0), MethodBodyTest.TARGET, null, "java/lang/Object", null); + + MethodVisitor constructor = node.visitMethod(ACC_PUBLIC, "", "()V", null, null); + constructor.visitVarInsn(ALOAD, 0); + constructor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "", "()V", false); + constructor.visitInsn(RETURN); + constructor.visitMaxs(0, 0); + + MethodVisitor method = node.visitMethod(access, name, desc, null, null); + if ((access & ACC_ABSTRACT) == 0) + { + if (usesThis) + { + method.visitVarInsn(ALOAD, 0); + method.visitInsn(POP); + } + switch (desc.charAt(desc.length() - 1)) + { + case 'I' -> { method.visitInsn(ICONST_0); method.visitInsn(IRETURN); } + case 'J' -> { method.visitInsn(LCONST_0); method.visitInsn(LRETURN); } + default -> method.visitInsn(RETURN); + } + method.visitMaxs(0, 0); + } + + return node; + } + + private static MethodNode method(ClassNode node, String name) + { + return node.methods.stream().filter(method -> method.name.equals(name)).findFirst().orElseThrow(); + } + + private static Object run(ClassNode node, String name, Class[] types, Object... arguments) throws ReflectiveOperationException + { + Class loaded = new Definer().define(node); + Method method = loaded.getMethod(name, types); + Object self = (method.getModifiers() & ACC_STATIC) != 0 ? null : loaded.getConstructor().newInstance(); + + return method.invoke(self, arguments); + } + + @Test + void staticMethodReturnsWhatTheHookReturns() throws ReflectiveOperationException + { + ClassNode node = MethodBodyTest.target(ACC_PUBLIC | ACC_STATIC, "add", "(II)I", false); + MethodBody.delegate(node, MethodBodyTest.method(node, "add"), new Hook(MethodBodyTest.HOOKS, "sum", "(II)I")); + + assertEquals(7, MethodBodyTest.run(node, "add", new Class[] { int.class, int.class }, 3, 4)); + } + + @Test + void instanceMethodPassesItsArgumentsWithoutThis() throws ReflectiveOperationException + { + ClassNode node = MethodBodyTest.target(ACC_PUBLIC, "mix", "(JLjava/lang/String;D)J", false); + MethodBody.delegate(node, MethodBodyTest.method(node, "mix"), new Hook(MethodBodyTest.HOOKS, "combine", "(JLjava/lang/String;D)J")); + + assertEquals(5_327L, MethodBodyTest.run(node, "mix", new Class[] { long.class, String.class, double.class }, 5L, "abc", 27.9)); + } + + @Test + void voidMethodCallsTheHook() throws ReflectiveOperationException + { + ClassNode node = MethodBodyTest.target(ACC_PUBLIC | ACC_STATIC, "save", "(Ljava/lang/String;)V", false); + MethodBody.delegate(node, MethodBodyTest.method(node, "save"), new Hook(MethodBodyTest.HOOKS, "record", "(Ljava/lang/String;)V")); + + MethodBodyTest.recorded = null; + assertNull(MethodBodyTest.run(node, "save", new Class[] { String.class }, "saved")); + assertEquals("saved", MethodBodyTest.recorded); + } + + @Test + void dropsTheLocalVariablesOfTheOldBody() + { + ClassNode node = MethodBodyTest.target(ACC_PUBLIC | ACC_STATIC, "add", "(II)I", false); + MethodNode method = MethodBodyTest.method(node, "add"); + method.localVariables = new ArrayList<>(); + + MethodBody.delegate(node, method, new Hook(MethodBodyTest.HOOKS, "sum", "(II)I")); + + assertNull(method.localVariables); + } + + @Test + void failsWhenTheTypesDiffer() + { + ClassNode node = MethodBodyTest.target(ACC_PUBLIC | ACC_STATIC, "add", "(II)I", false); + + IllegalStateException e = assertThrows(IllegalStateException.class, () -> + MethodBody.delegate(node, MethodBodyTest.method(node, "add"), new Hook(MethodBodyTest.HOOKS, "combine", "(JLjava/lang/String;D)J")) + ); + assertTrue(e.getMessage().contains("different types"), e.getMessage()); + } + + @Test + void failsWhenTheOldBodyUsesThis() + { + ClassNode node = MethodBodyTest.target(ACC_PUBLIC, "add", "(II)I", true); + + IllegalStateException e = assertThrows(IllegalStateException.class, () -> + MethodBody.delegate(node, MethodBodyTest.method(node, "add"), new Hook(MethodBodyTest.HOOKS, "sum", "(II)I")) + ); + assertTrue(e.getMessage().contains("uses 'this'"), e.getMessage()); + } + + @Test + void failsForAMethodWithoutBody() + { + ClassNode node = MethodBodyTest.target(ACC_PUBLIC | ACC_ABSTRACT, "add", "(II)I", false); + + IllegalStateException e = assertThrows(IllegalStateException.class, () -> + MethodBody.delegate(node, MethodBodyTest.method(node, "add"), new Hook(MethodBodyTest.HOOKS, "sum", "(II)I")) + ); + assertTrue(e.getMessage().contains("has no body"), e.getMessage()); + } +}