Add MethodBody implementation for method delegation and TileRules utility for optimised tile rule matching and caching. Include patches for WorldGenChunk performance and corresponding tests.
This commit is contained in:
1 parent
e932c7401a
commit
2081235433
10 files changed
+1029
-1
No files matched your search
+3
-1
@@ -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
|
||||
|
||||
+76
@@ -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}:
|
||||
*
|
||||
* <ul>
|
||||
* <li>the body of {@code isProtected(List, String)} becomes
|
||||
* {@code return WorldGenHooks.isProtected(protectedTiles, tile);}</li>
|
||||
* <li>in {@code cleanChunk(IsoChunk, String, String)}, {@code floorMaterial.matches(mat)}
|
||||
* becomes {@code WorldGenHooks.matches(floorMaterial, mat)}.</li>
|
||||
* </ul>
|
||||
*/
|
||||
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
|
||||
));
|
||||
}
|
||||
}
|
||||
+56
@@ -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:
|
||||
*
|
||||
* <pre>{@code
|
||||
* public boolean canPlace(List placement, String floorName)
|
||||
* {
|
||||
* return WorldGenHooks.canPlace(placement, floorName);
|
||||
* }
|
||||
* }</pre>
|
||||
*
|
||||
* 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);
|
||||
}
|
||||
}
|
||||
+160
@@ -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, "<init>", "()V", null, null);
|
||||
constructor.visitVarInsn(ALOAD, 0);
|
||||
constructor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()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<MethodInsnNode> calls(ClassNode node, String methodName)
|
||||
{
|
||||
MethodNode method = node.methods.stream().filter(m -> m.name.equals(methodName)).findFirst().orElseThrow();
|
||||
List<MethodInsnNode> 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<MethodInsnNode> 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<MethodInsnNode> 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")));
|
||||
}
|
||||
}
|
||||
+134
@@ -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, "<init>", "()V", null, null);
|
||||
constructor.visitVarInsn(ALOAD, 0);
|
||||
constructor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()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<AbstractInsnNode> instructions(ClassNode node)
|
||||
{
|
||||
MethodNode canPlace = node.methods.stream().filter(method -> method.name.equals("canPlace")).findFirst().orElseThrow();
|
||||
List<AbstractInsnNode> 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<AbstractInsnNode> 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")));
|
||||
}
|
||||
}
|
||||
+33
@@ -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);
|
||||
}
|
||||
}
|
||||
+121
@@ -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.
|
||||
*
|
||||
* <p>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<String, Pattern> PATTERNS = new ConcurrentHashMap<>();
|
||||
private static final ConcurrentHashMap<String, Placement> PLACEMENTS = new ConcurrentHashMap<>();
|
||||
private static final ConcurrentHashMap<String, Pattern> 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;
|
||||
}
|
||||
}
|
||||
+198
@@ -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<String> 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<String> 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<Object> 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<List<String>> ruleLists(List<String> rules)
|
||||
{
|
||||
List<List<String>> 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<List<String>> lists, List<String> names) throws ReflectiveOperationException
|
||||
{
|
||||
WorldGenChunk chunk = TileRulesTest.chunkWithoutConstructor();
|
||||
|
||||
for (List<String> 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<List<String>> 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<String> 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<String> rules = new TreeSet<>();
|
||||
try (Stream<Path> 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<String> 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<String> pool = new ArrayList<>(rules);
|
||||
List<List<String>> lists = new ArrayList<>();
|
||||
for (int i = 0; i < 2_000; i++)
|
||||
{
|
||||
List<String> 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<String> 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); }
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user