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:
Overlord committed 2026-10-04 23:19:08 +02:00
1 parent e932c7401a
commit 2081235433
10 files changed
+1029 -1

No files matched your search

@@ -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);
}
}
@@ -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;
}
}
@@ -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); }
}
}