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 5b98fab..a392ad0 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 @@ -38,7 +38,8 @@ public final class B42PatchSet implements PatchSet new ZipBackupWaitPerformancePatch(), new ServerPlayersVehiclesRoundPerformancePatch(), new ServerPlayersVehiclesStopPerformancePatch(), - new ServerPlayerDBSaveWaitPerformancePatch() + new ServerPlayerDBSaveWaitPerformancePatch(), + new GameServerAssetLoadingPerformancePatch() ); @Override diff --git a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/perf/GameServerAssetLoadingPerformancePatch.java b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/perf/GameServerAssetLoadingPerformancePatch.java new file mode 100644 index 0000000..c45544f --- /dev/null +++ b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/perf/GameServerAssetLoadingPerformancePatch.java @@ -0,0 +1,63 @@ +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.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; + +/** + * Replaces the update call of the asset loop in {@code GameServer.doMinimumInit}: + * + *
{@code
+ * while (GameWindow.fileSystem.hasWork()) {
+ * AssetLoadingHooks.updateAsyncTransactions(GameWindow.fileSystem); // was GameWindow.fileSystem.updateAsyncTransactions()
+ * }
+ * }
+ *
+ * With the feature {@code experimental_performance} the hook grows the loader pool to one thread
+ * per CPU but one and parks the main thread between updates instead of spinning. Asset loading
+ * of an explored world: 4.8 to 3.2 s with 8 CPUs, 9.1 to 6.3 s with 4, 13.7 to 10.1 s with 2
+ * (startup 15.9 to 13.7 s, 20.0 to 17.2 s, 28.4 to 25.0 s). Off, it makes the vanilla call. The
+ * per-frame call in {@code GameServer.main} stays.
+ */
+public final class GameServerAssetLoadingPerformancePatch extends PerformancePatch
+{
+ private static final String FILE_SYSTEM = "zombie/fileSystem/FileSystem";
+
+ private static final Anchor.Call ANCHOR = new Anchor.Call(
+ new Anchor.Method("doMinimumInit", "()V"),
+ GameServerAssetLoadingPerformancePatch.FILE_SYSTEM, "updateAsyncTransactions", "()V"
+ );
+
+ private static final Hook HOOK = new Hook(
+ "dev/overlord/zomboidforge/compat/b42/hooks/AssetLoadingHooks", "updateAsyncTransactions", "(L" + GameServerAssetLoadingPerformancePatch.FILE_SYSTEM + ";)V"
+ );
+
+ public GameServerAssetLoadingPerformancePatch() {
+ super("zombie/network/GameServer", GameServerAssetLoadingPerformancePatch.ANCHOR, GameServerAssetLoadingPerformancePatch.HOOK);
+ }
+
+ //
+
+ @Override
+ public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
+
+ @Override
+ public void apply(ClassNode node)
+ {
+ MethodNode method = GameServerAssetLoadingPerformancePatch.ANCHOR.in().resolve(node);
+ MethodInsnNode update = GameServerAssetLoadingPerformancePatch.ANCHOR.resolve(node);
+
+ if (update.getOpcode() != Opcodes.INVOKEVIRTUAL)
+ throw new IllegalStateException("'" + node.name + ".doMinimumInit': 'FileSystem.updateAsyncTransactions' is not called virtually.");
+
+ // The hook takes the receiver of the virtual call as its argument: the stack is unchanged.
+ method.instructions.set(update, new MethodInsnNode(Opcodes.INVOKESTATIC, GameServerAssetLoadingPerformancePatch.HOOK.owner(),
+ GameServerAssetLoadingPerformancePatch.HOOK.name(), GameServerAssetLoadingPerformancePatch.HOOK.desc(), false));
+ }
+}
diff --git a/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/perf/GameServerAssetLoadingPerformancePatchTest.java b/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/perf/GameServerAssetLoadingPerformancePatchTest.java
new file mode 100644
index 0000000..cc43a70
--- /dev/null
+++ b/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/perf/GameServerAssetLoadingPerformancePatchTest.java
@@ -0,0 +1,120 @@
+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.Label;
+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.assertTrue;
+import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
+import static org.objectweb.asm.Opcodes.ACC_STATIC;
+import static org.objectweb.asm.Opcodes.GETSTATIC;
+import static org.objectweb.asm.Opcodes.GOTO;
+import static org.objectweb.asm.Opcodes.IFEQ;
+import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
+import static org.objectweb.asm.Opcodes.RETURN;
+import static org.objectweb.asm.Opcodes.V25;
+
+class GameServerAssetLoadingPerformancePatchTest
+{
+ private static final String GAME_SERVER = "zombie/network/GameServer";
+ private static final String FILE_SYSTEM = "zombie/fileSystem/FileSystem";
+
+ /**
+ * {@code GameServer} with the loop of {@code doMinimumInit} and the per-frame call of
+ * {@code main}: {@code while (GameWindow.fileSystem.hasWork()) GameWindow.fileSystem.updateAsyncTransactions();}
+ * and {@code GameWindow.fileSystem.updateAsyncTransactions();}.
+ */
+ private static ClassNode gameServer()
+ {
+ ClassNode node = new ClassNode();
+ node.visit(V25, ACC_PUBLIC, GameServerAssetLoadingPerformancePatchTest.GAME_SERVER, null, "java/lang/Object", null);
+
+ MethodVisitor init = node.visitMethod(ACC_PUBLIC | ACC_STATIC, "doMinimumInit", "()V", null, null);
+ Label check = new Label();
+ Label end = new Label();
+ init.visitLabel(check);
+ init.visitFieldInsn(GETSTATIC, "zombie/GameWindow", "fileSystem", "L" + GameServerAssetLoadingPerformancePatchTest.FILE_SYSTEM + ";");
+ init.visitMethodInsn(INVOKEVIRTUAL, GameServerAssetLoadingPerformancePatchTest.FILE_SYSTEM, "hasWork", "()Z", false);
+ init.visitJumpInsn(IFEQ, end);
+ init.visitFieldInsn(GETSTATIC, "zombie/GameWindow", "fileSystem", "L" + GameServerAssetLoadingPerformancePatchTest.FILE_SYSTEM + ";");
+ init.visitMethodInsn(INVOKEVIRTUAL, GameServerAssetLoadingPerformancePatchTest.FILE_SYSTEM, "updateAsyncTransactions", "()V", false);
+ init.visitJumpInsn(GOTO, check);
+ init.visitLabel(end);
+ init.visitInsn(RETURN);
+ init.visitMaxs(0, 0);
+
+ MethodVisitor main = node.visitMethod(ACC_PUBLIC | ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null);
+ main.visitFieldInsn(GETSTATIC, "zombie/GameWindow", "fileSystem", "L" + GameServerAssetLoadingPerformancePatchTest.FILE_SYSTEM + ";");
+ main.visitMethodInsn(INVOKEVIRTUAL, GameServerAssetLoadingPerformancePatchTest.FILE_SYSTEM, "updateAsyncTransactions", "()V", false);
+ main.visitInsn(RETURN);
+ main.visitMaxs(0, 0);
+
+ return node;
+ }
+
+ private static List{@code
+ * while (GameWindow.fileSystem.hasWork()) GameWindow.fileSystem.updateAsyncTransactions();
+ * }
+ *
+ * hands file tasks (model and animation imports, 16 at most in flight) to the loader threads of
+ * {@code FileSystemImpl} and collects their results on the main thread. It spins: the main
+ * thread takes a CPU that the loaders could use. Vanilla has 2 loader threads with up to 4
+ * CPUs, 4 with more.
+ */
+@SuppressWarnings("unused")
+public final class AssetLoadingHooks
+{
+ /** Pause of the main thread after each update; one task takes about 8 ms of loader time. */
+ private static final long PARK_NANOS = 500_000L;
+
+ /** {@code FileSystemImpl.executor}, private; {@code null} when it cannot be reached. */
+ private static final @Nullable VarHandle EXECUTOR;
+
+ static
+ {
+ VarHandle executor = null;
+ try
+ {
+ executor = MethodHandles.privateLookupIn(FileSystemImpl.class, MethodHandles.lookup())
+ .findVarHandle(FileSystemImpl.class, "executor", ExecutorService.class);
+ }
+ catch (ReflectiveOperationException e) { System.out.println("[ZomboidForge] Asset loading keeps its loader threads: 'FileSystemImpl.executor' not found: " + e); }
+
+ EXECUTOR = executor;
+ }
+
+ /** Whether the loader pool was checked; the main thread is the only caller. */
+ private static boolean poolChecked;
+
+ private AssetLoadingHooks() {}
+
+ /**
+ * Replaces {@code fileSystem.updateAsyncTransactions()} in that loop. With the feature off,
+ * only that call. On: the first call grows the loader pool to one thread per CPU but one (at
+ * least 2), and every call parks the main thread for 0.5 ms after the update instead of
+ * spinning. Fewer threads with a spinning main thread, or more threads alone, load slower.
+ * The pool keeps its size after startup; the loaders run the same tasks as in vanilla.
+ */
+ public static void updateAsyncTransactions(FileSystem fileSystem)
+ {
+ if (!ForgeInstance.FORGE.settings().enabled(Feature.EXPERIMENTAL_PERFORMANCE))
+ {
+ fileSystem.updateAsyncTransactions();
+ return;
+ }
+
+ if (!AssetLoadingHooks.poolChecked)
+ {
+ AssetLoadingHooks.poolChecked = true;
+
+ Object executor = AssetLoadingHooks.EXECUTOR != null && fileSystem instanceof FileSystemImpl ? AssetLoadingHooks.EXECUTOR.get(fileSystem) : null;
+ int threads = Math.max(2, Runtime.getRuntime().availableProcessors() - 1);
+
+ // A fixed pool: maximum first, the core size may not exceed it.
+ if (executor instanceof ThreadPoolExecutor pool && pool.getMaximumPoolSize() < threads)
+ {
+ System.out.println("[ZomboidForge] Asset loading: " + threads + " loader threads instead of " + pool.getMaximumPoolSize() + ".");
+ pool.setMaximumPoolSize(threads);
+ pool.setCorePoolSize(threads);
+ }
+ }
+
+ fileSystem.updateAsyncTransactions();
+ LockSupport.parkNanos(AssetLoadingHooks.PARK_NANOS);
+ }
+}
diff --git a/compat/b42/runtime/src/test/java/dev/overlord/zomboidforge/compat/b42/hooks/AssetLoadingHooksTest.java b/compat/b42/runtime/src/test/java/dev/overlord/zomboidforge/compat/b42/hooks/AssetLoadingHooksTest.java
new file mode 100644
index 0000000..f1c9791
--- /dev/null
+++ b/compat/b42/runtime/src/test/java/dev/overlord/zomboidforge/compat/b42/hooks/AssetLoadingHooksTest.java
@@ -0,0 +1,68 @@
+package dev.overlord.zomboidforge.compat.b42.hooks;
+
+import dev.overlord.zomboidforge.compat.b42.ForgeInstance;
+import dev.overlord.zomboidforge.core.Forge;
+import dev.overlord.zomboidforge.core.config.Feature;
+import dev.overlord.zomboidforge.core.config.ForgeSettings;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+
+import zombie.fileSystem.FileSystemImpl;
+
+import java.lang.reflect.Field;
+import java.time.Duration;
+import java.util.Set;
+import java.util.concurrent.ThreadPoolExecutor;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/** The hook on a real {@code FileSystemImpl}; the feature is switched through the settings of {@code ForgeInstance.FORGE}. */
+class AssetLoadingHooksTest
+{
+ private static void settings(ForgeSettings settings) throws ReflectiveOperationException
+ {
+ Field field = Forge.class.getDeclaredField("settings");
+ field.setAccessible(true);
+ field.set(ForgeInstance.FORGE, settings);
+ }
+
+ private static ThreadPoolExecutor pool(FileSystemImpl fileSystem) throws ReflectiveOperationException
+ {
+ Field field = FileSystemImpl.class.getDeclaredField("executor");
+ field.setAccessible(true);
+ return (ThreadPoolExecutor) field.get(fileSystem);
+ }
+
+ @AfterEach
+ void resetSettings() throws ReflectiveOperationException
+ {
+ AssetLoadingHooksTest.settings(ForgeSettings.DEFAULTS);
+ }
+
+ /** One test: the first call with the feature on grows the pool once per JVM. */
+ @Test
+ void growsTheLoaderPoolOnlyWithTheFeature() throws ReflectiveOperationException
+ {
+ FileSystemImpl fileSystem = new FileSystemImpl();
+ ThreadPoolExecutor pool = AssetLoadingHooksTest.pool(fileSystem);
+ int vanilla = Runtime.getRuntime().availableProcessors() <= 4 ? 2 : 4;
+ int expected = Math.max(vanilla, Math.max(2, Runtime.getRuntime().availableProcessors() - 1));
+
+ try
+ {
+ assertEquals(vanilla, pool.getMaximumPoolSize());
+
+ AssetLoadingHooks.updateAsyncTransactions(fileSystem);
+ assertEquals(vanilla, pool.getCorePoolSize());
+ assertEquals(vanilla, pool.getMaximumPoolSize());
+
+ AssetLoadingHooksTest.settings(new ForgeSettings(Duration.ofMillis(2), Duration.ofSeconds(10), Set.of(Feature.EXPERIMENTAL_PERFORMANCE)));
+ AssetLoadingHooks.updateAsyncTransactions(fileSystem);
+ AssetLoadingHooks.updateAsyncTransactions(fileSystem);
+ assertEquals(expected, pool.getCorePoolSize());
+ assertEquals(expected, pool.getMaximumPoolSize());
+ }
+ finally { pool.shutdownNow(); }
+ }
+}