Introduce FrameBudget utility and ServerMapCellBudgetPerformancePatch for frame-based workload distribution.

This commit is contained in:
Overlord committed 2026-10-04 20:16:38 +02:00
1 parent 38a15db299
commit 56e01c5cbe
6 files changed
+429 -1

No files matched your search

@@ -26,7 +26,8 @@ public final class B42PatchSet implements PatchSet
new IsoZombieSpotChancePerformancePatch(),
new IsoGameCharacterStateMachinePerformancePatch(),
new ZombieVoronoiPerformancePatch(),
new ZomboidFileSystemInitPerformancePatch()
new ZomboidFileSystemInitPerformancePatch(),
new ServerMapCellBudgetPerformancePatch()
);
@Override
@@ -0,0 +1,90 @@
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;
/**
* Spreads the integration of finished cells in {@code ServerMap.preupdate} over frames:
*
* <pre>{@code
* // was ServerLOS.instance.suspend()
* ServerMapHooks.beginIntegration(ServerLOS.instance);
*
* for (int x = 0; x < ServerCell.loaded2.size(); ++x)
* {
* ServerCell cell = ServerCell.loaded2.get(x);
*
* if (ServerMapHooks.integrate(cell)) {
* // was cell.Load2()
* --x; this.toLoad.remove(cell);
* }
* }
* }</pre>
*
* Vanilla integrates every cell that finished loading since the last frame (70 to 300 ms each
* on new terrain), so cells that finish together make one long frame. The hooks integrate cells
* until 40 ms are used, at least one per frame; the others stay in {@code loaded2} for the next
* frames. The work per cell is the same; only the frame it runs in changes, which the
* asynchronous loader already varies.
*/
public final class ServerMapCellBudgetPerformancePatch extends PerformancePatch
{
private static final String OWNER = "zombie/network/ServerMap";
private static final String CELL = "zombie/network/ServerMap$ServerCell";
private static final String LOS = "zombie/network/ServerLOS";
private static final String HOOKS = "dev/overlord/zomboidforge/compat/b42/hooks/ServerMapHooks";
private static final Anchor.Method PREUPDATE = new Anchor.Method("preupdate", "()V");
private static final Anchor.Call ANCHOR = new Anchor.Call(
ServerMapCellBudgetPerformancePatch.PREUPDATE, ServerMapCellBudgetPerformancePatch.CELL, "Load2", "()Z"
);
/** {@code ServerLOS.instance.suspend()} before the integration loop. */
private static final Anchor.Call SUSPEND = new Anchor.Call(
ServerMapCellBudgetPerformancePatch.PREUPDATE, ServerMapCellBudgetPerformancePatch.LOS, "suspend", "()V"
);
private static final Hook HOOK = new Hook(
ServerMapCellBudgetPerformancePatch.HOOKS, "integrate", "(L" + ServerMapCellBudgetPerformancePatch.CELL + ";)Z"
);
private static final Hook BEGIN = new Hook(
ServerMapCellBudgetPerformancePatch.HOOKS, "beginIntegration", "(L" + ServerMapCellBudgetPerformancePatch.LOS + ";)V"
);
public ServerMapCellBudgetPerformancePatch() {
super(ServerMapCellBudgetPerformancePatch.OWNER, ServerMapCellBudgetPerformancePatch.ANCHOR, ServerMapCellBudgetPerformancePatch.HOOK);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
@Override
public void apply(ClassNode node)
{
MethodNode method = ServerMapCellBudgetPerformancePatch.PREUPDATE.resolve(node);
MethodInsnNode load2 = ServerMapCellBudgetPerformancePatch.ANCHOR.resolve(node);
MethodInsnNode suspend = ServerMapCellBudgetPerformancePatch.SUSPEND.resolve(node);
if (method.instructions.indexOf(suspend) > method.instructions.indexOf(load2))
throw new IllegalStateException("'" + node.name + ".preupdate': 'ServerLOS.suspend' comes after 'ServerCell.Load2'.");
// Both hooks take the receiver of the virtual call as their argument: the stack is unchanged.
method.instructions.set(suspend, ServerMapCellBudgetPerformancePatch.call(ServerMapCellBudgetPerformancePatch.BEGIN));
method.instructions.set(load2, ServerMapCellBudgetPerformancePatch.call(ServerMapCellBudgetPerformancePatch.HOOK));
}
private static MethodInsnNode call(Hook hook)
{
return new MethodInsnNode(Opcodes.INVOKESTATIC, hook.owner(), hook.name(), hook.desc(), false);
}
}
@@ -0,0 +1,181 @@
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.GETSTATIC;
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.POP;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
class ServerMapCellBudgetPerformancePatchTest
{
private static final String MAP = "zombie/network/ServerMap";
private static final String CELL = "zombie/network/ServerMap$ServerCell";
private static final String LOS = "zombie/network/ServerLOS";
private static final String HOOKS = "dev/overlord/zomboidforge/compat/b42/hooks/ServerMapHooks";
/**
* {@code ServerMap} with a reduced {@code preupdate}:
*
* <pre>{@code
* public void preupdate()
* {
* ServerLOS.instance.suspend(); // when suspendFirst
* ((ServerCell) null).Load2();
* ServerLOS.instance.suspend(); // when suspendLast
* }
* }</pre>
*/
private static ClassNode serverMap(boolean suspendFirst, boolean suspendLast)
{
ClassNode node = new ClassNode();
node.visit(V25, ACC_PUBLIC, ServerMapCellBudgetPerformancePatchTest.MAP, 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 preupdate = node.visitMethod(ACC_PUBLIC, "preupdate", "()V", null, null);
if (suspendFirst) ServerMapCellBudgetPerformancePatchTest.suspend(preupdate);
preupdate.visitInsn(ACONST_NULL);
preupdate.visitTypeInsn(CHECKCAST, ServerMapCellBudgetPerformancePatchTest.CELL);
preupdate.visitMethodInsn(INVOKEVIRTUAL, ServerMapCellBudgetPerformancePatchTest.CELL, "Load2", "()Z", false);
preupdate.visitInsn(POP);
if (suspendLast) ServerMapCellBudgetPerformancePatchTest.suspend(preupdate);
preupdate.visitInsn(RETURN);
preupdate.visitMaxs(0, 0);
return node;
}
private static void suspend(MethodVisitor method)
{
method.visitFieldInsn(GETSTATIC, ServerMapCellBudgetPerformancePatchTest.LOS, "instance", "L" + ServerMapCellBudgetPerformancePatchTest.LOS + ";");
method.visitMethodInsn(INVOKEVIRTUAL, ServerMapCellBudgetPerformancePatchTest.LOS, "suspend", "()V", false);
}
private static ClassNode serverMap()
{
return ServerMapCellBudgetPerformancePatchTest.serverMap(true, false);
}
private static List<MethodInsnNode> calls(ClassNode node)
{
MethodNode preupdate = node.methods.stream().filter(method -> method.name.equals("preupdate")).findFirst().orElseThrow();
List<MethodInsnNode> calls = new ArrayList<>();
for (AbstractInsnNode instruction : preupdate.instructions) {
if (instruction instanceof MethodInsnNode call) calls.add(call);
}
return calls;
}
@Test
void anchorMatchesTheTarget()
{
new ServerMapCellBudgetPerformancePatch().anchor().verify(ServerMapCellBudgetPerformancePatchTest.serverMap());
}
@Test
void redirectsSuspendAndLoad2ToTheHooks()
{
ClassNode node = ServerMapCellBudgetPerformancePatchTest.serverMap();
new ServerMapCellBudgetPerformancePatch().apply(node);
List<MethodInsnNode> calls = ServerMapCellBudgetPerformancePatchTest.calls(node);
assertEquals(2, calls.size());
for (MethodInsnNode call : calls)
{
assertEquals(INVOKESTATIC, call.getOpcode());
assertEquals(ServerMapCellBudgetPerformancePatchTest.HOOKS, call.owner);
assertFalse(call.itf);
}
assertEquals("beginIntegration", calls.get(0).name);
assertEquals("(L" + ServerMapCellBudgetPerformancePatchTest.LOS + ";)V", calls.get(0).desc);
assertEquals("integrate", calls.get(1).name);
assertEquals("(L" + ServerMapCellBudgetPerformancePatchTest.CELL + ";)Z", calls.get(1).desc);
}
@Test
void patchedClassIsValid() throws ClassNotFoundException
{
ClassNode node = ServerMapCellBudgetPerformancePatchTest.serverMap();
new ServerMapCellBudgetPerformancePatch().apply(node);
// Initializing links the class, which runs the bytecode verifier on the changed method.
ClassDefiner definer = new ClassDefiner();
definer.define(node);
Class.forName(node.name.replace('/', '.'), true, definer);
}
@Test
void failsWithoutTheSuspend()
{
ClassNode node = ServerMapCellBudgetPerformancePatchTest.serverMap(false, false);
assertThrows(IllegalStateException.class, () -> new ServerMapCellBudgetPerformancePatch().apply(node));
}
@Test
void failsWhenTheSuspendComesAfterLoad2()
{
ClassNode node = ServerMapCellBudgetPerformancePatchTest.serverMap(false, true);
IllegalStateException e = assertThrows(IllegalStateException.class, () -> new ServerMapCellBudgetPerformancePatch().apply(node));
assertTrue(e.getMessage().contains("comes after"), e.getMessage());
}
/** {@code HookExistenceTest} checks the patch's {@code hook()}; this is the second one it calls. */
@Test
void beginIntegrationHookExistsAsPublicStaticMethod() throws IOException
{
ClassNode hooks = PackageScan.read(ServerMapCellBudgetPerformancePatchTest.HOOKS);
assertTrue(hooks.methods.stream().anyMatch(method ->
method.name.equals("beginIntegration")
&& method.desc.equals("(L" + ServerMapCellBudgetPerformancePatchTest.LOS + ";)V")
&& (method.access & ACC_PUBLIC) != 0 && (method.access & ACC_STATIC) != 0
));
}
@Test
void appliesOnlyToVerifiedVersions()
{
ServerMapCellBudgetPerformancePatch patch = new ServerMapCellBudgetPerformancePatch();
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")));
}
}
@@ -0,0 +1,48 @@
package dev.overlord.zomboidforge.compat.b42.hooks;
import dev.overlord.zomboidforge.compat.b42.util.FrameBudget;
import zombie.network.ServerLOS;
import zombie.network.ServerMap;
/** Hooks called by patched {@code zombie.network.ServerMap} code. */
public final class ServerMapHooks
{
/**
* Main-thread time per frame for integrating finished cells (frames target 100 ms). One
* integration takes 70 to 300 ms on new terrain, so in practice a frame integrates one cell,
* or a few small ones.
*/
private static final long BUDGET_NANOS = 40_000_000L;
private static final FrameBudget CELL_INTEGRATION = new FrameBudget(ServerMapHooks.BUDGET_NANOS, System::nanoTime);
private ServerMapHooks() {}
/**
* Replaces {@code ServerLOS.instance.suspend()} in {@code ServerMap.preupdate}, which precedes
* the loop that integrates the finished cells of this frame: suspends, then starts the
* frame's integration budget.
*/
public static void beginIntegration(ServerLOS los)
{
los.suspend();
ServerMapHooks.CELL_INTEGRATION.begin();
}
/**
* Replaces {@code cell.Load2()} in that loop. Vanilla integrates every finished cell in the
* frame it finishes; here a cell beyond the frame's budget is skipped: {@code false} keeps it
* in {@code ServerCell.loaded2}, at the front, and the loop of the next frame integrates it.
* The work per cell is unchanged; a cell becomes active up to a few frames later.
*/
public static boolean integrate(ServerMap.ServerCell cell)
{
if (!ServerMapHooks.CELL_INTEGRATION.allowsAnother()) return false;
boolean integrated = cell.Load2();
if (integrated) ServerMapHooks.CELL_INTEGRATION.count();
return integrated;
}
}
@@ -0,0 +1,40 @@
package dev.overlord.zomboidforge.compat.b42.util;
import java.util.function.LongSupplier;
/**
* A time budget for work spread over frames: after {@link #begin()}, work units are allowed
* until the budget is used up, but always the first one, so every frame makes progress.
* Not thread-safe; one instance per thread.
*/
public final class FrameBudget
{
private final long budgetNanos;
private final LongSupplier clock;
private long start;
private int units;
/** @param clock nanoseconds, e.g. {@code System::nanoTime} */
public FrameBudget(long budgetNanos, LongSupplier clock)
{
this.budgetNanos = budgetNanos;
this.clock = clock;
}
/** Starts the budget of a new frame. */
public void begin()
{
this.start = this.clock.getAsLong();
this.units = 0;
}
/** Whether another unit may run: the first of the frame always, later ones while time is left. */
public boolean allowsAnother()
{
return this.units == 0 || this.clock.getAsLong() - this.start < this.budgetNanos;
}
/** Records a unit that ran. */
public void count() { this.units++; }
}
@@ -0,0 +1,68 @@
package dev.overlord.zomboidforge.compat.b42.util;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class FrameBudgetTest
{
/** A clock the test sets; nanoseconds. */
private long now;
private FrameBudget budget(long budgetNanos)
{
return new FrameBudget(budgetNanos, () -> this.now);
}
@Test
void firstUnitOfAFrameRunsEvenWhenTheBudgetIsUsedUp()
{
FrameBudget budget = this.budget(40);
budget.begin();
this.now += 1_000;
assertTrue(budget.allowsAnother());
}
@Test
void laterUnitsRunWhileTimeIsLeft()
{
FrameBudget budget = this.budget(40);
budget.begin();
budget.count();
this.now += 39;
assertTrue(budget.allowsAnother());
this.now += 1;
assertFalse(budget.allowsAnother());
}
@Test
void aNewFrameStartsAFreshBudget()
{
FrameBudget budget = this.budget(40);
budget.begin();
budget.count();
this.now += 100;
assertFalse(budget.allowsAnother());
budget.begin();
assertTrue(budget.allowsAnother());
budget.count();
assertTrue(budget.allowsAnother());
}
@Test
void anUnusedSkipDoesNotCountAsAUnit()
{
// A frame where nothing ran yet still allows its first unit, however late.
FrameBudget budget = this.budget(40);
budget.begin();
this.now += 100;
assertTrue(budget.allowsAnother());
assertTrue(budget.allowsAnother());
}
}