Add performance improvements for ZomboidFileSystem.init: implement MediaScan and ZomboidFileSystemHooks for efficient file system traversal, and replace directory checks with a single-pass approach. Integrate new patch into the performance patch set, and include unit tests for behavior validation.

This commit is contained in:
Overlord committed 2026-10-04 19:34:09 +02:00
1 parent 05a4b9dbd9
commit 38a15db299
6 files changed
+671 -1

No files matched your search

@@ -0,0 +1,59 @@
package dev.overlord.zomboidforge.compat.b42.hooks;
import dev.overlord.zomboidforge.compat.b42.util.MediaScan;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import zombie.ZomboidFileSystem;
import zombie.network.GameServer;
/** Hooks called by patched {@code zombie.ZomboidFileSystem} code. */
public final class ZomboidFileSystemHooks
{
private ZomboidFileSystemHooks() {}
/**
* Replaces the call {@code this.searchFolders(root)} in {@code ZomboidFileSystem.init}, which
* passes its fields {@code loadList} and {@code allAbsolutePaths}. Does what that call and the
* loop after it do, and empties {@code loadList}, so the loop finds nothing and the
* {@code loadList.clear()} after it has no effect.
*
* <p>The loop, per entry of {@code loadList}: the relative path
* ({@code getRelativeFile(entry)}), lowercased, maps to the absolute path, with a trailing
* separator for folders, in {@code activeFileMap}; the absolute path goes into
* {@code allAbsolutePaths}. Here the folder checks of {@code searchFolders}, of the loop, and
* of {@code getRelativeFile} come from one walk ({@link MediaScan}).
*
* <p>{@code searchFolders} also yields to the render loop on clients
* ({@code Core.DoFrameReady()} per entry); without {@code GameServer.server} the vanilla call
* runs unchanged.
*/
public static void searchAndIndex(ZomboidFileSystem fileSystem, File root, List<String> loadList, Set<String> allAbsolutePaths) throws IOException
{
if (!GameServer.server)
{
fileSystem.searchFolders(root);
return;
}
Map<String, Boolean> folders = MediaScan.walk(root, loadList);
for (String entry : loadList)
{
String relative = MediaScan.relativePath(fileSystem.base.lowercaseUri, entry, folders);
String absolute = new File(entry).getAbsoluteFile().getAbsolutePath();
if (MediaScan.isFolder(absolute, folders)) absolute = absolute + File.separator;
fileSystem.activeFileMap.put(relative.toLowerCase(Locale.ENGLISH), absolute);
allAbsolutePaths.add(absolute);
}
loadList.clear();
}
}
@@ -0,0 +1,121 @@
package dev.overlord.zomboidforge.compat.b42.util;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.FileVisitOption;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* The file list of {@code ZomboidFileSystem.searchFolders} and the paths of
* {@code ZomboidFileSystem.getRelativeFile(URI, String)}, with fewer file system calls.
*
* <p>Vanilla stats every entry under the media folder ({@code File.isDirectory}) and lists every
* folder; {@code init} then stats every entry again and builds two URIs per entry for its
* relative path. Here one walk stats each entry once and remembers which ones are folders.
*/
public final class MediaScan
{
private MediaScan() {}
/**
* Appends what {@code searchFolders(root)} appends to {@code loadList}: every file, and every
* folder whose path contains {@code media/maps/}, depth first, in directory order, links
* followed. Returns for each appended path whether it is a folder, for the paths whose
* appended form names the same file (vanilla appends {@code path.replace("\\", "/")
* .replace("./", "")}, which may name another file).
*/
public static Map<String, Boolean> walk(File root, List<String> loadList) throws IOException
{
Map<String, Boolean> folders = new HashMap<>();
Files.walkFileTree(root.toPath(), EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new SimpleFileVisitor<>()
{
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attributes)
{
String path = dir.toString();
String entry = MediaScan.entry(path);
if (entry.contains("media/maps/")) loadList.add(entry);
if (entry.equals(path)) folders.put(entry, Boolean.TRUE);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attributes)
{
MediaScan.addFile(file.toString(), loadList, folders);
return FileVisitResult.CONTINUE;
}
// Vanilla's isDirectory() is false for an entry it cannot read, so it appends it as a file.
@Override
public FileVisitResult visitFileFailed(Path file, IOException exception)
{
MediaScan.addFile(file.toString(), loadList, folders);
return FileVisitResult.CONTINUE;
}
});
return folders;
}
/**
* {@code getRelativeFile(root, path)}: the path relative to {@code root} (a folder URI from
* {@code File.toURI()}), lowercased, with a trailing slash for folders; {@code path} itself
* when it lies outside {@code root}. {@code File.toURI()} appends the slash when the
* <em>lowercased</em> path is a folder: known paths come from {@code folders}, other
* lowercased paths are checked on disk, as vanilla does.
*/
public static String relativePath(URI root, String path, Map<String, Boolean> folders)
{
String absolutePath = new File(path).getAbsolutePath();
String lowercase = absolutePath.toLowerCase(Locale.ENGLISH);
boolean folder = MediaScan.isFolder(lowercase, folders);
String uriPath = lowercase.replace(File.separatorChar, '/');
if (!uriPath.startsWith("/")) uriPath = "/" + uriPath;
if (folder && !uriPath.endsWith("/")) uriPath = uriPath + "/";
String rootPath = root.getPath();
if (!rootPath.endsWith("/")) rootPath = rootPath + "/";
if (!uriPath.startsWith(rootPath)) return path;
String relative = uriPath.substring(rootPath.length());
if (path.endsWith("/") && !relative.endsWith("/")) relative = relative + "/";
return relative;
}
/** {@code new File(path).isDirectory()}, from {@code folders} when the path is known. */
public static boolean isFolder(String path, Map<String, Boolean> folders)
{
Boolean known = folders.get(path);
return known != null ? known : new File(path).isDirectory();
}
private static void addFile(String path, List<String> loadList, Map<String, Boolean> folders)
{
String entry = MediaScan.entry(path);
loadList.add(entry);
if (entry.equals(path)) folders.put(entry, Boolean.FALSE);
}
/** The form {@code searchFolders} appends. */
private static String entry(String path)
{
return path.replace("\\", "/").replace("./", "");
}
}
@@ -0,0 +1,179 @@
package dev.overlord.zomboidforge.compat.b42.hooks;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import zombie.ZomboidFileSystem;
import zombie.network.GameServer;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
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 ZomboidFileSystemHooks#searchAndIndex} with vanilla: {@code searchFolders} of
* the game jar, followed by the loop of {@code ZomboidFileSystem.init} (copied below, it cannot
* run alone), on fresh {@code ZomboidFileSystem} instances.
*/
class ZomboidFileSystemHooksTest
{
private boolean server;
@BeforeEach
void serverMode()
{
this.server = GameServer.server;
GameServer.server = true;
}
@AfterEach
void restoreServerMode() { GameServer.server = this.server; }
/** The maps, lists and sets of one {@code ZomboidFileSystem} after the indexing. */
private record Index(List<String> loadList, Map<String, String> activeFileMap, Set<String> allAbsolutePaths) {}
private static ZomboidFileSystem newFileSystem(Path base) throws ReflectiveOperationException, IOException
{
Constructor<ZomboidFileSystem> constructor = ZomboidFileSystem.class.getDeclaredConstructor();
constructor.setAccessible(true);
ZomboidFileSystem fileSystem = constructor.newInstance();
fileSystem.base.set(base.toFile());
return fileSystem;
}
@SuppressWarnings("unchecked")
private static <T> T field(ZomboidFileSystem fileSystem, String name) throws ReflectiveOperationException
{
Field field = ZomboidFileSystem.class.getDeclaredField(name);
field.setAccessible(true);
return (T) field.get(fileSystem);
}
private static Index vanilla(Path base, File media) throws ReflectiveOperationException, IOException
{
ZomboidFileSystem fileSystem = ZomboidFileSystemHooksTest.newFileSystem(base);
List<String> loadList = ZomboidFileSystemHooksTest.field(fileSystem, "loadList");
Set<String> allAbsolutePaths = ZomboidFileSystemHooksTest.field(fileSystem, "allAbsolutePaths");
Map<String, String> activeFileMap = fileSystem.activeFileMap;
fileSystem.searchFolders(media);
List<String> searched = new ArrayList<>(loadList);
// The loop of ZomboidFileSystem.init after searchFolders.
for (int n = 0; n < loadList.size(); ++n)
{
String rel = fileSystem.getRelativeFile(loadList.get(n));
File file = new File(loadList.get(n)).getAbsoluteFile();
String abs = file.getAbsolutePath();
if (file.isDirectory()) abs = abs + File.separator;
activeFileMap.put(rel.toLowerCase(Locale.ENGLISH), abs);
allAbsolutePaths.add(abs);
}
loadList.clear();
return new Index(searched, new HashMap<>(activeFileMap), new HashSet<>(allAbsolutePaths));
}
private static Index hook(Path base, File media) throws ReflectiveOperationException, IOException
{
ZomboidFileSystem fileSystem = ZomboidFileSystemHooksTest.newFileSystem(base);
List<String> loadList = ZomboidFileSystemHooksTest.field(fileSystem, "loadList");
Set<String> allAbsolutePaths = ZomboidFileSystemHooksTest.field(fileSystem, "allAbsolutePaths");
List<String> searched = new ArrayList<>();
// Records what the walk appends: the hook empties the list before returning.
List<String> recording = new ArrayList<>(loadList)
{
@Override
public boolean add(String entry)
{
searched.add(entry);
return super.add(entry);
}
};
ZomboidFileSystemHooks.searchAndIndex(fileSystem, media, recording, allAbsolutePaths);
assertTrue(recording.isEmpty(), "The hook leaves entries in loadList.");
return new Index(searched, new HashMap<>(fileSystem.activeFileMap), new HashSet<>(allAbsolutePaths));
}
private static void file(Path path) throws IOException
{
Files.createDirectories(path.getParent());
Files.writeString(path, path.getFileName().toString());
}
@Test
void indexesEdgeCasesLikeVanilla(@TempDir Path temp) throws Exception
{
// A lowercase base: "Clash" lowercased then names the existing folder "clash".
Path base = temp.resolve("base");
Path media = base.resolve("media");
ZomboidFileSystemHooksTest.file(media.resolve("maps/Muldraugh, KY/world_1_2.lotpack"));
ZomboidFileSystemHooksTest.file(media.resolve("maps/Test%Map/objects.lua"));
ZomboidFileSystemHooksTest.file(media.resolve("scripts/Items/Weapon.txt"));
ZomboidFileSystemHooksTest.file(media.resolve("textures/Äpfel ö.png"));
ZomboidFileSystemHooksTest.file(media.resolve("clash/inside.txt"));
ZomboidFileSystemHooksTest.file(media.resolve("Clash")); // lowercased, a folder
ZomboidFileSystemHooksTest.file(media.resolve("back\\slash.txt")); // vanilla appends another path
ZomboidFileSystemHooksTest.file(media.resolve("dot./inside.txt")); // vanilla removes "./"
Files.createDirectories(media.resolve("empty"));
Files.createSymbolicLink(media.resolve("LinkedScripts"), media.resolve("scripts"));
Files.createSymbolicLink(media.resolve("broken"), media.resolve("missing"));
Index expected = ZomboidFileSystemHooksTest.vanilla(base, media.toFile());
Index actual = ZomboidFileSystemHooksTest.hook(base, media.toFile());
assertEquals(expected.loadList(), actual.loadList());
assertEquals(expected.activeFileMap(), actual.activeFileMap());
assertEquals(expected.allAbsolutePaths(), actual.allAbsolutePaths());
assertTrue(expected.activeFileMap().containsKey("media/clash/"), "The test tree misses the lowercase folder case.");
}
/**
* The media folder of an installed server, when the game jar is part of one
* ({@code <install>/java/projectzomboid.jar}, as {@code lib/server}); the image build uses a
* copied jar without it.
*/
@Test
void indexesTheGameMediaFolderLikeVanilla() throws Exception
{
Path jar = Path.of(ZomboidFileSystem.class.getProtectionDomain().getCodeSource().getLocation().toURI());
Path folder = jar.getParent();
assumeTrue(folder.getFileName() != null && folder.getFileName().toString().equals("java"), "The game jar " + jar + " is not in an installed server.");
Path base = folder.getParent();
Path media = base.resolve("media");
assumeTrue(Files.isDirectory(media.resolve("scripts")), "No media folder at " + media);
Index expected = ZomboidFileSystemHooksTest.vanilla(base, media.toRealPath().toFile());
Index actual = ZomboidFileSystemHooksTest.hook(base, media.toRealPath().toFile());
assertEquals(expected.loadList(), actual.loadList());
assertEquals(expected.activeFileMap(), actual.activeFileMap());
assertEquals(expected.allAbsolutePaths(), actual.allAbsolutePaths());
assertTrue(expected.activeFileMap().size() > 30_000, () -> "Only " + expected.activeFileMap().size() + " entries.");
}
}