Add new performance patches for IsoGameCharacter and IsoZombie, including caching and early-exit optimizations. Added corresponding tests.

This commit is contained in:
Overlord committed 2026-10-01 15:44:18 +02:00
1 parent 1a53f833e3
commit c22aa29c88
7 files changed
+777 -2

No files matched your search

@@ -1,7 +1,9 @@
package dev.overlord.zomboidforge.compat.b42;
import dev.overlord.zomboidforge.compat.b42.patches.ServerStartedPatch;
import dev.overlord.zomboidforge.compat.b42.perf.IsoGameCharacterStateMachinePerformancePatch;
import dev.overlord.zomboidforge.compat.b42.perf.IsoZombieNetworkComponentPerformancePatch;
import dev.overlord.zomboidforge.compat.b42.perf.IsoZombieSpotChancePerformancePatch;
import dev.overlord.zomboidforge.compat.b42.perf.IsoZombieVehiclePerformancePatch;
import dev.overlord.zomboidforge.patcher.ClassPatch;
import dev.overlord.zomboidforge.patcher.PatchSet;
@@ -16,7 +18,9 @@ public final class B42PatchSet implements PatchSet
private static final List<ClassPatch> PATCHES = List.of(
new ServerStartedPatch(),
new IsoZombieVehiclePerformancePatch(),
new IsoZombieNetworkComponentPerformancePatch()
new IsoZombieNetworkComponentPerformancePatch(),
new IsoZombieSpotChancePerformancePatch(),
new IsoGameCharacterStateMachinePerformancePatch()
);
@Override
@@ -0,0 +1,172 @@
package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.patcher.Anchor;
import dev.overlord.zomboidforge.patcher.GameVersion;
import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.JumpInsnNode;
import org.objectweb.asm.tree.LabelNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.VarInsnNode;
import java.util.Arrays;
import java.util.List;
/**
* Stores the {@code StateMachineComponent} of an {@code IsoGameCharacter} in a field, so that
* {@code getStateMachineComponent()} does not look it up in the entity's component map on every
* call. The lookup walks the class hierarchy of the component class and reads a {@code HashMap}.
*
* <p>The method is {@code final} and its whole body is the lookup. Every access to the component
* goes through it: the 12 call sites in {@code IsoGameCharacter}, among them
* {@code getStateMachine()}, {@code getActionContext()} and {@code getAdvancedAnimator()}, which
* zombies, players and animals call every frame.
* The patched method returns the stored component only while the component's owner is this
* character. {@code ECSEntity.setECSComponent} and {@code removeECSComponent} set the owner of a
* replaced or removed component to {@code null}, and adding the component to another entity
* changes its owner. In every other case the original lookup runs (and throws when the component
* is missing, as before), and its result is stored.
*/
public final class IsoGameCharacterStateMachinePerformancePatch extends PerformancePatch
{
private static final String CHARACTER = "zombie/characters/IsoGameCharacter";
private static final String COMPONENT = "zombie/characters/component/StateMachineComponent";
private static final String ECS_COMPONENT = "zombie/characters/ecs/ECSComponent";
private static final String FIELD_NAME = "zomboidForge$stateMachineComponent";
private static final String FIELD_DESC = "L" + IsoGameCharacterStateMachinePerformancePatch.COMPONENT + ";";
private static final Anchor.Method GETTER = new Anchor.Method("getStateMachineComponent", "()" + IsoGameCharacterStateMachinePerformancePatch.FIELD_DESC);
/** {@code return (StateMachineComponent) this.getECSComponent(StateMachineComponent.class);} */
private static final Anchor.Sequence LOOKUP = new Anchor.Sequence(
IsoGameCharacterStateMachinePerformancePatch.GETTER,
new Anchor.Instruction.Opcode(Opcodes.ALOAD),
new Anchor.Instruction.Constant(Type.getObjectType(IsoGameCharacterStateMachinePerformancePatch.COMPONENT)),
new Anchor.Instruction.Invoke(
IsoGameCharacterStateMachinePerformancePatch.CHARACTER, "getECSComponent",
"(Ljava/lang/Class;)L" + IsoGameCharacterStateMachinePerformancePatch.ECS_COMPONENT + ";"
),
new Anchor.Instruction.Opcode(Opcodes.CHECKCAST),
new Anchor.Instruction.Opcode(Opcodes.ARETURN)
);
public IsoGameCharacterStateMachinePerformancePatch() {
super(IsoGameCharacterStateMachinePerformancePatch.CHARACTER, IsoGameCharacterStateMachinePerformancePatch.LOOKUP, null);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
@Override
public void apply(ClassNode node)
{
IsoGameCharacterStateMachinePerformancePatch.requireNoFieldNamed(node);
MethodNode method = IsoGameCharacterStateMachinePerformancePatch.GETTER.resolve(node);
List<AbstractInsnNode> lookup = IsoGameCharacterStateMachinePerformancePatch.LOOKUP.resolve(node);
long instructions = Arrays.stream(method.instructions.toArray())
.filter(instruction -> instruction.getOpcode() != -1)
.count();
if (instructions != lookup.size())
throw new IllegalStateException("'" + node.name + ".getStateMachineComponent' does more than the component lookup.");
node.fields.add(new FieldNode(
Opcodes.ACC_PRIVATE | Opcodes.ACC_SYNTHETIC,
IsoGameCharacterStateMachinePerformancePatch.FIELD_NAME,
IsoGameCharacterStateMachinePerformancePatch.FIELD_DESC,
null, null
));
method.instructions.insertBefore(lookup.getLast(), IsoGameCharacterStateMachinePerformancePatch.store());
// The body is only the lookup, so the first slot after 'this' and the arguments is free.
int stored = Type.getArgumentsAndReturnSizes(method.desc) >> 2;
method.instructions.insert(IsoGameCharacterStateMachinePerformancePatch.returnStored(stored));
}
/** The patch must not collide with a field of the game class, e.g. after an update. */
private static void requireNoFieldNamed(ClassNode node)
{
boolean exists = node.fields.stream()
.anyMatch(field -> field.name.equals(IsoGameCharacterStateMachinePerformancePatch.FIELD_NAME));
if (exists) throw new IllegalStateException("'" + node.name + "' already has a field named '" + IsoGameCharacterStateMachinePerformancePatch.FIELD_NAME + "'.");
}
/**
* Placed at the start of the method:
*
* <pre>{@code
* StateMachineComponent stored = this.zomboidForge$stateMachineComponent;
* if (stored != null && stored.getECSOwnerEntity() == this) return stored;
* }</pre>
*/
private static InsnList returnStored(int stored)
{
LabelNode lookup = new LabelNode();
InsnList code = new InsnList();
code.add(new VarInsnNode(Opcodes.ALOAD, 0));
code.add(IsoGameCharacterStateMachinePerformancePatch.field(Opcodes.GETFIELD));
code.add(new VarInsnNode(Opcodes.ASTORE, stored));
code.add(new VarInsnNode(Opcodes.ALOAD, stored));
code.add(new JumpInsnNode(Opcodes.IFNULL, lookup));
code.add(new VarInsnNode(Opcodes.ALOAD, stored));
code.add(new MethodInsnNode(
Opcodes.INVOKEVIRTUAL,
IsoGameCharacterStateMachinePerformancePatch.ECS_COMPONENT,
"getECSOwnerEntity",
"()Lzombie/characters/ecs/ECSEntity;",
false
));
code.add(new VarInsnNode(Opcodes.ALOAD, 0));
code.add(new JumpInsnNode(Opcodes.IF_ACMPNE, lookup));
code.add(new VarInsnNode(Opcodes.ALOAD, stored));
code.add(new InsnNode(Opcodes.ARETURN));
code.add(lookup);
return code;
}
/**
* Placed before the {@code areturn} of the lookup, with the component on the operand stack:
* {@code this.zomboidForge$stateMachineComponent = component}, leaving the component on the stack.
*/
private static InsnList store()
{
InsnList code = new InsnList();
code.add(new InsnNode(Opcodes.DUP));
code.add(new VarInsnNode(Opcodes.ALOAD, 0));
code.add(new InsnNode(Opcodes.SWAP));
code.add(IsoGameCharacterStateMachinePerformancePatch.field(Opcodes.PUTFIELD));
return code;
}
private static FieldInsnNode field(int opcode)
{
return new FieldInsnNode(
opcode,
IsoGameCharacterStateMachinePerformancePatch.CHARACTER,
IsoGameCharacterStateMachinePerformancePatch.FIELD_NAME,
IsoGameCharacterStateMachinePerformancePatch.FIELD_DESC
);
}
}
@@ -0,0 +1,126 @@
package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.patcher.Anchor;
import dev.overlord.zomboidforge.patcher.GameVersion;
import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.JumpInsnNode;
import org.objectweb.asm.tree.LabelNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.VarInsnNode;
import java.util.List;
/**
* Skips the spot-chance modifiers in {@code IsoZombie.spottedNew} when the chance is already 0.
*
* <p>Between {@code if (bForced) chance = 1000000F} and {@code chance = (float)
* PZMath.fastfloor(chance)} the method only multiplies or divides {@code chance}: bonus spot
* time, sight, inactivity, traits of the player, shelter ({@code getObstacleMod}),
* {@code isVehicleBetween}, worn items, eating. A chance of 0 stays 0, or becomes NaN when divided
* by 0, and the roll {@code Rand.Next(10000) / 100F < chance} fails for both. The chance is 0 when
* the player is outside the zombie's vision radius or behind it, and is never 0 for a forced spot.
*
* <p>The patch inserts {@code if (chance == 0F) goto rounding} after the forced-spot assignment.
* The rounding, the roll (with its {@code Rand.Next} draw) and the failed-roll branch run as in
* vanilla. The early return for a nearer current target comes before the jump. The skipped code
* writes no field or local that is read after the jump; it writes the shared scratch vector
* {@code IsoGameCharacter.tempo}, which other code sets before reading, except client debug drawing.
*/
public final class IsoZombieSpotChancePerformancePatch extends PerformancePatch
{
private static final Anchor.Method SPOTTED_NEW = new Anchor.Method("spottedNew", "(Lzombie/iso/IsoMovingObject;Z)V");
/** {@code if (bForced) chance = 1000000F;}: the store of the forced chance. */
private static final Anchor.Sequence FORCED_CHANCE = new Anchor.Sequence(
IsoZombieSpotChancePerformancePatch.SPOTTED_NEW,
new Anchor.Instruction.Constant(1000000.0F),
new Anchor.Instruction.Opcode(Opcodes.FSTORE)
);
/** {@code chance = (float) PZMath.fastfloor(chance);}: the rounding before the roll. */
private static final Anchor.Sequence ROUNDING = new Anchor.Sequence(
IsoZombieSpotChancePerformancePatch.SPOTTED_NEW,
new Anchor.Instruction.Opcode(Opcodes.FLOAD),
new Anchor.Instruction.Invoke("zombie/core/math/PZMath", "fastfloor", "(F)I"),
new Anchor.Instruction.Opcode(Opcodes.I2F),
new Anchor.Instruction.Opcode(Opcodes.FSTORE)
);
public IsoZombieSpotChancePerformancePatch() {
super("zombie/characters/IsoZombie", IsoZombieSpotChancePerformancePatch.FORCED_CHANCE, null);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
@Override
public void apply(ClassNode node)
{
MethodNode method = IsoZombieSpotChancePerformancePatch.SPOTTED_NEW.resolve(node);
List<AbstractInsnNode> forced = IsoZombieSpotChancePerformancePatch.FORCED_CHANCE.resolve(node);
List<AbstractInsnNode> rounding = IsoZombieSpotChancePerformancePatch.ROUNDING.resolve(node);
AbstractInsnNode forcedStore = forced.getLast();
AbstractInsnNode roundingLoad = rounding.getFirst();
int chance = ((VarInsnNode) forcedStore).var;
IsoZombieSpotChancePerformancePatch.requireVariable(roundingLoad, chance);
IsoZombieSpotChancePerformancePatch.requireVariable(rounding.getLast(), chance);
if (method.instructions.indexOf(roundingLoad) < method.instructions.indexOf(forcedStore))
throw new IllegalStateException("'" + node.name + ".spottedNew': the rounding of 'chance' comes before the forced-spot assignment.");
// The check goes after the label that the 'if (bForced)' jump targets, so both paths run it.
// Inserting it before the new label keeps it ahead of that label if both precede the same instruction.
LabelNode roundingLabel = new LabelNode();
method.instructions.insertBefore(
IsoZombieSpotChancePerformancePatch.nextInstruction(forcedStore),
IsoZombieSpotChancePerformancePatch.jumpIfZero(chance, roundingLabel)
);
method.instructions.insertBefore(roundingLoad, roundingLabel);
}
/**
* {@code if (chance == 0F) goto target}. {@code fcmpl} pushes -1 for NaN, so NaN does not
* jump; -0F does.
*/
private static InsnList jumpIfZero(int chance, LabelNode target)
{
InsnList code = new InsnList();
code.add(new VarInsnNode(Opcodes.FLOAD, chance));
code.add(new InsnNode(Opcodes.FCONST_0));
code.add(new InsnNode(Opcodes.FCMPL));
code.add(new JumpInsnNode(Opcodes.IFEQ, target));
return code;
}
private static void requireVariable(AbstractInsnNode instruction, int chance)
{
int variable = ((VarInsnNode) instruction).var;
if (variable != chance)
throw new IllegalStateException("'IsoZombie.spottedNew': the rounding uses local " + variable + ", the forced-spot assignment local " + chance + ".");
}
/** The closest later instruction that is not a label, line number, or frame. */
private static AbstractInsnNode nextInstruction(AbstractInsnNode instruction)
{
AbstractInsnNode next = instruction.getNext();
while (next != null && next.getOpcode() == -1) next = next.getNext();
if (next == null) throw new IllegalStateException("'IsoZombie.spottedNew' ends after the forced-spot assignment.");
return next;
}
}
@@ -0,0 +1,30 @@
package dev.overlord.zomboidforge.compat.b42.patches.support;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.tree.ClassNode;
/**
* Class loader that defines classes from {@link ClassNode}s, so patched test classes can be loaded
* and run. Lives in a subpackage so that the scanned packages do not contain it.
*/
public final class ClassDefiner extends ClassLoader
{
public ClassDefiner() { super(ClassDefiner.class.getClassLoader()); }
/**
* Writes {@code node} with computed frames and defines it. Classes that the frame computation
* needs (common superclasses) must be defined first.
*/
public Class<?> define(ClassNode node)
{
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES)
{
@Override
protected ClassLoader getClassLoader() { return ClassDefiner.this; }
};
node.accept(writer);
byte[] bytes = writer.toByteArray();
return this.defineClass(node.name.replace('/', '.'), bytes, 0, bytes.length);
}
}
@@ -0,0 +1,252 @@
package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
import dev.overlord.zomboidforge.patcher.GameVersion;
import org.jetbrains.annotations.Nullable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.MethodNode;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.objectweb.asm.Opcodes.ACC_ABSTRACT;
import static org.objectweb.asm.Opcodes.ACC_FINAL;
import static org.objectweb.asm.Opcodes.ACC_INTERFACE;
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static org.objectweb.asm.Opcodes.ACC_STATIC;
import static org.objectweb.asm.Opcodes.ALOAD;
import static org.objectweb.asm.Opcodes.ARETURN;
import static org.objectweb.asm.Opcodes.CHECKCAST;
import static org.objectweb.asm.Opcodes.GETFIELD;
import static org.objectweb.asm.Opcodes.GETSTATIC;
import static org.objectweb.asm.Opcodes.IADD;
import static org.objectweb.asm.Opcodes.ICONST_1;
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
import static org.objectweb.asm.Opcodes.NOP;
import static org.objectweb.asm.Opcodes.PUTSTATIC;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
class IsoGameCharacterStateMachinePerformancePatchTest
{
private static final String CHARACTER = "zombie/characters/IsoGameCharacter";
private static final String COMPONENT = "zombie/characters/component/StateMachineComponent";
private static final String ECS_COMPONENT = "zombie/characters/ecs/ECSComponent";
private static final String ECS_ENTITY = "zombie/characters/ecs/ECSEntity";
private Class<?> characterClass = Object.class;
private Class<?> componentClass = Object.class;
/**
* {@code IsoGameCharacter} whose lookup counts its calls and returns the field {@code current}:
*
* <pre>{@code
* public static int lookups;
* public ECSComponent current;
*
* public ECSComponent getECSComponent(Class type) { lookups++; return this.current; }
*
* public final StateMachineComponent getStateMachineComponent() {
* return (StateMachineComponent) this.getECSComponent(StateMachineComponent.class);
* }
* }</pre>
*/
private static ClassNode character()
{
ClassNode node = IsoGameCharacterStateMachinePerformancePatchTest.emptyClass(
IsoGameCharacterStateMachinePerformancePatchTest.CHARACTER, "java/lang/Object", IsoGameCharacterStateMachinePerformancePatchTest.ECS_ENTITY
);
String component = "L" + IsoGameCharacterStateMachinePerformancePatchTest.COMPONENT + ";";
String ecsComponent = "L" + IsoGameCharacterStateMachinePerformancePatchTest.ECS_COMPONENT + ";";
node.visitField(ACC_PUBLIC | ACC_STATIC, "lookups", "I", null, null);
node.visitField(ACC_PUBLIC, "current", ecsComponent, null, null);
MethodVisitor lookup = node.visitMethod(ACC_PUBLIC, "getECSComponent", "(Ljava/lang/Class;)" + ecsComponent, null, null);
lookup.visitFieldInsn(GETSTATIC, IsoGameCharacterStateMachinePerformancePatchTest.CHARACTER, "lookups", "I");
lookup.visitInsn(ICONST_1);
lookup.visitInsn(IADD);
lookup.visitFieldInsn(PUTSTATIC, IsoGameCharacterStateMachinePerformancePatchTest.CHARACTER, "lookups", "I");
lookup.visitVarInsn(ALOAD, 0);
lookup.visitFieldInsn(GETFIELD, IsoGameCharacterStateMachinePerformancePatchTest.CHARACTER, "current", ecsComponent);
lookup.visitInsn(ARETURN);
lookup.visitMaxs(0, 0);
MethodVisitor getter = node.visitMethod(ACC_PUBLIC | ACC_FINAL, "getStateMachineComponent", "()" + component, null, null);
getter.visitVarInsn(ALOAD, 0);
getter.visitLdcInsn(Type.getObjectType(IsoGameCharacterStateMachinePerformancePatchTest.COMPONENT));
getter.visitMethodInsn(INVOKEVIRTUAL, IsoGameCharacterStateMachinePerformancePatchTest.CHARACTER, "getECSComponent", "(Ljava/lang/Class;)" + ecsComponent, false);
getter.visitTypeInsn(CHECKCAST, IsoGameCharacterStateMachinePerformancePatchTest.COMPONENT);
getter.visitInsn(ARETURN);
getter.visitMaxs(0, 0);
return node;
}
/** {@code ECSComponent} with a public field {@code owner} that {@code getECSOwnerEntity()} returns. */
private static ClassNode ecsComponent()
{
ClassNode node = IsoGameCharacterStateMachinePerformancePatchTest.emptyClass(IsoGameCharacterStateMachinePerformancePatchTest.ECS_COMPONENT, "java/lang/Object", null);
String owner = "L" + IsoGameCharacterStateMachinePerformancePatchTest.ECS_ENTITY + ";";
node.visitField(ACC_PUBLIC, "owner", owner, null, null);
MethodVisitor getter = node.visitMethod(ACC_PUBLIC, "getECSOwnerEntity", "()" + owner, null, null);
getter.visitVarInsn(ALOAD, 0);
getter.visitFieldInsn(GETFIELD, IsoGameCharacterStateMachinePerformancePatchTest.ECS_COMPONENT, "owner", owner);
getter.visitInsn(ARETURN);
getter.visitMaxs(0, 0);
return node;
}
private static ClassNode ecsEntity()
{
ClassNode node = new ClassNode();
node.visit(V25, ACC_PUBLIC | ACC_INTERFACE | ACC_ABSTRACT, IsoGameCharacterStateMachinePerformancePatchTest.ECS_ENTITY, null, "java/lang/Object", null);
return node;
}
/** Public class with a public no-argument constructor. */
private static ClassNode emptyClass(String name, String superName, @Nullable String interfaceName)
{
ClassNode node = new ClassNode();
node.visit(V25, ACC_PUBLIC, name, null, superName, interfaceName == null ? null : new String[] { interfaceName });
MethodVisitor init = node.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
init.visitVarInsn(ALOAD, 0);
init.visitMethodInsn(INVOKESPECIAL, superName, "<init>", "()V", false);
init.visitInsn(RETURN);
init.visitMaxs(0, 0);
return node;
}
private static ClassNode patched()
{
ClassNode node = IsoGameCharacterStateMachinePerformancePatchTest.character();
new IsoGameCharacterStateMachinePerformancePatch().apply(node);
return node;
}
@BeforeEach
void loadPatchedClasses()
{
ClassDefiner definer = new ClassDefiner();
definer.define(IsoGameCharacterStateMachinePerformancePatchTest.ecsEntity());
definer.define(IsoGameCharacterStateMachinePerformancePatchTest.ecsComponent());
this.componentClass = definer.define(IsoGameCharacterStateMachinePerformancePatchTest.emptyClass(
IsoGameCharacterStateMachinePerformancePatchTest.COMPONENT, IsoGameCharacterStateMachinePerformancePatchTest.ECS_COMPONENT, null
));
this.characterClass = definer.define(IsoGameCharacterStateMachinePerformancePatchTest.patched());
}
private Object newCharacter() throws ReflectiveOperationException { return this.characterClass.getConstructor().newInstance(); }
/** A component owned by {@code owner} and registered as its {@code current} component. */
private Object addComponent(Object owner) throws ReflectiveOperationException
{
Object component = this.componentClass.getConstructor().newInstance();
this.componentClass.getField("owner").set(component, owner);
this.characterClass.getField("current").set(owner, component);
return component;
}
private Object stateMachineComponent(Object character) throws ReflectiveOperationException
{
return this.characterClass.getMethod("getStateMachineComponent").invoke(character);
}
private int lookups() throws ReflectiveOperationException { return this.characterClass.getField("lookups").getInt(null); }
@Test
void anchorMatchesTheTarget()
{
new IsoGameCharacterStateMachinePerformancePatch().anchor().verify(IsoGameCharacterStateMachinePerformancePatchTest.character());
}
@Test
void returnsTheStoredComponentWithoutALookup() throws ReflectiveOperationException
{
Object character = this.newCharacter();
Object component = this.addComponent(character);
assertSame(component, this.stateMachineComponent(character));
assertSame(component, this.stateMachineComponent(character));
assertEquals(1, this.lookups());
}
@Test
void looksUpAgainAfterTheComponentWasReplaced() throws ReflectiveOperationException
{
Object character = this.newCharacter();
Object first = this.addComponent(character);
assertSame(first, this.stateMachineComponent(character));
// ECSEntity.setECSComponent removes the old component, which sets its owner to null.
this.componentClass.getField("owner").set(first, null);
Object second = this.addComponent(character);
assertSame(second, this.stateMachineComponent(character));
assertSame(second, this.stateMachineComponent(character));
assertEquals(2, this.lookups());
}
@Test
void looksUpAgainAfterTheComponentMovedToAnotherCharacter() throws ReflectiveOperationException
{
Object character = this.newCharacter();
Object component = this.addComponent(character);
assertSame(component, this.stateMachineComponent(character));
this.componentClass.getField("owner").set(component, this.newCharacter());
this.characterClass.getField("current").set(character, null);
assertNull(this.stateMachineComponent(character));
assertEquals(2, this.lookups());
}
@Test
void failsWhenTheGetterDoesMoreThanTheLookup()
{
ClassNode node = IsoGameCharacterStateMachinePerformancePatchTest.character();
MethodNode getter = node.methods.stream().filter(method -> method.name.equals("getStateMachineComponent")).findFirst().orElseThrow();
getter.instructions.insert(new InsnNode(NOP));
assertThrows(IllegalStateException.class, () -> new IsoGameCharacterStateMachinePerformancePatch().apply(node));
}
@Test
void failsWhenTheGameClassAlreadyHasTheField()
{
ClassNode node = IsoGameCharacterStateMachinePerformancePatchTest.patched();
assertThrows(IllegalStateException.class, () -> new IsoGameCharacterStateMachinePerformancePatch().apply(node));
}
@Test
void appliesOnlyToVerifiedVersions()
{
IsoGameCharacterStateMachinePerformancePatch patch = new IsoGameCharacterStateMachinePerformancePatch();
assertTrue(patch.appliesTo(GameVersion.parse("42.21.0")));
assertFalse(patch.appliesTo(GameVersion.parse("42.20.3")));
assertFalse(patch.appliesTo(GameVersion.parse("42.22.0")));
}
}
@@ -0,0 +1,191 @@
package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
import dev.overlord.zomboidforge.patcher.GameVersion;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.ClassNode;
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.ALOAD;
import static org.objectweb.asm.Opcodes.F2I;
import static org.objectweb.asm.Opcodes.FLOAD;
import static org.objectweb.asm.Opcodes.FMUL;
import static org.objectweb.asm.Opcodes.FSTORE;
import static org.objectweb.asm.Opcodes.GETSTATIC;
import static org.objectweb.asm.Opcodes.I2F;
import static org.objectweb.asm.Opcodes.IADD;
import static org.objectweb.asm.Opcodes.ICONST_1;
import static org.objectweb.asm.Opcodes.IFEQ;
import static org.objectweb.asm.Opcodes.ILOAD;
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
import static org.objectweb.asm.Opcodes.INVOKESTATIC;
import static org.objectweb.asm.Opcodes.IRETURN;
import static org.objectweb.asm.Opcodes.PUTSTATIC;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
class IsoZombieSpotChancePerformancePatchTest
{
private static final String ZOMBIE = "zombie/characters/IsoZombie";
private static final String MOVING = "zombie/iso/IsoMovingObject";
private static final String MATH = "zombie/core/math/PZMath";
private static final int CHANCE = 5;
private record Result(int modifierRuns, float rounded) {}
/**
* {@code IsoZombie} with the shape of {@code spottedNew} around the patched range:
*
* <pre>{@code
* public static float input;
* public static int modifierRuns;
* public static float rounded;
*
* public void spottedNew(IsoMovingObject other, boolean bForced)
* {
* float chance = input; // local 5
* if (bForced) chance = 1000000F;
* modifierRuns++; // stands for the modifiers
* chance *= 2F;
* chance = (float) PZMath.fastfloor(chance); // local roundingLocal
* rounded = chance;
* }
* }</pre>
*/
private static ClassNode zombie(int roundingLocal)
{
ClassNode node = IsoZombieSpotChancePerformancePatchTest.emptyClass(IsoZombieSpotChancePerformancePatchTest.ZOMBIE);
node.visitField(ACC_PUBLIC | ACC_STATIC, "input", "F", null, null);
node.visitField(ACC_PUBLIC | ACC_STATIC, "modifierRuns", "I", null, null);
node.visitField(ACC_PUBLIC | ACC_STATIC, "rounded", "F", null, null);
MethodVisitor method = node.visitMethod(ACC_PUBLIC, "spottedNew", "(L" + IsoZombieSpotChancePerformancePatchTest.MOVING + ";Z)V", null, null);
Label notForced = new Label();
method.visitFieldInsn(GETSTATIC, IsoZombieSpotChancePerformancePatchTest.ZOMBIE, "input", "F");
method.visitVarInsn(FSTORE, IsoZombieSpotChancePerformancePatchTest.CHANCE);
method.visitVarInsn(ILOAD, 2);
method.visitJumpInsn(IFEQ, notForced);
method.visitLdcInsn(1000000.0F);
method.visitVarInsn(FSTORE, IsoZombieSpotChancePerformancePatchTest.CHANCE);
method.visitLabel(notForced);
method.visitFieldInsn(GETSTATIC, IsoZombieSpotChancePerformancePatchTest.ZOMBIE, "modifierRuns", "I");
method.visitInsn(ICONST_1);
method.visitInsn(IADD);
method.visitFieldInsn(PUTSTATIC, IsoZombieSpotChancePerformancePatchTest.ZOMBIE, "modifierRuns", "I");
method.visitVarInsn(FLOAD, IsoZombieSpotChancePerformancePatchTest.CHANCE);
method.visitLdcInsn(2.0F);
method.visitInsn(FMUL);
method.visitVarInsn(FSTORE, IsoZombieSpotChancePerformancePatchTest.CHANCE);
method.visitVarInsn(FLOAD, roundingLocal);
method.visitMethodInsn(INVOKESTATIC, IsoZombieSpotChancePerformancePatchTest.MATH, "fastfloor", "(F)I", false);
method.visitInsn(I2F);
method.visitVarInsn(FSTORE, roundingLocal);
method.visitVarInsn(FLOAD, IsoZombieSpotChancePerformancePatchTest.CHANCE);
method.visitFieldInsn(PUTSTATIC, IsoZombieSpotChancePerformancePatchTest.ZOMBIE, "rounded", "F");
method.visitInsn(RETURN);
method.visitMaxs(0, 0);
return node;
}
/** {@code PZMath} with {@code fastfloor} as {@code (int) value}, which equals it for the values used here. */
private static ClassNode math()
{
ClassNode node = IsoZombieSpotChancePerformancePatchTest.emptyClass(IsoZombieSpotChancePerformancePatchTest.MATH);
MethodVisitor fastfloor = node.visitMethod(ACC_PUBLIC | ACC_STATIC, "fastfloor", "(F)I", null, null);
fastfloor.visitVarInsn(FLOAD, 0);
fastfloor.visitInsn(F2I);
fastfloor.visitInsn(IRETURN);
fastfloor.visitMaxs(0, 0);
return node;
}
/** Public class with a public no-argument constructor. */
private static ClassNode emptyClass(String name)
{
ClassNode node = new ClassNode();
node.visit(V25, ACC_PUBLIC, name, null, "java/lang/Object", null);
MethodVisitor init = node.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
init.visitVarInsn(ALOAD, 0);
init.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
init.visitInsn(RETURN);
init.visitMaxs(0, 0);
return node;
}
/** Loads the patched {@code IsoZombie} and runs {@code spottedNew(null, forced)} with {@code input} as the chance. */
private static Result run(float input, boolean forced) throws ReflectiveOperationException
{
ClassNode zombie = IsoZombieSpotChancePerformancePatchTest.zombie(IsoZombieSpotChancePerformancePatchTest.CHANCE);
new IsoZombieSpotChancePerformancePatch().apply(zombie);
ClassDefiner definer = new ClassDefiner();
definer.define(IsoZombieSpotChancePerformancePatchTest.math());
Class<?> moving = definer.define(IsoZombieSpotChancePerformancePatchTest.emptyClass(IsoZombieSpotChancePerformancePatchTest.MOVING));
Class<?> loaded = definer.define(zombie);
loaded.getField("input").setFloat(null, input);
loaded.getMethod("spottedNew", moving, boolean.class).invoke(loaded.getConstructor().newInstance(), null, forced);
return new Result(loaded.getField("modifierRuns").getInt(null), loaded.getField("rounded").getFloat(null));
}
@Test
void anchorMatchesTheTarget()
{
new IsoZombieSpotChancePerformancePatch().anchor().verify(IsoZombieSpotChancePerformancePatchTest.zombie(IsoZombieSpotChancePerformancePatchTest.CHANCE));
}
@Test
void zeroChanceSkipsTheModifiersAndStillRounds() throws ReflectiveOperationException
{
assertEquals(new Result(0, 0.0F), IsoZombieSpotChancePerformancePatchTest.run(0.0F, false));
assertEquals(new Result(0, 0.0F), IsoZombieSpotChancePerformancePatchTest.run(-0.0F, false));
}
@Test
void otherChancesRunTheModifiers() throws ReflectiveOperationException
{
assertEquals(new Result(1, 6.0F), IsoZombieSpotChancePerformancePatchTest.run(3.0F, false));
assertEquals(new Result(1, 2000000.0F), IsoZombieSpotChancePerformancePatchTest.run(0.0F, true));
assertEquals(1, IsoZombieSpotChancePerformancePatchTest.run(Float.NaN, false).modifierRuns());
}
@Test
void failsWhenTheRoundingUsesAnotherLocal()
{
ClassNode zombie = IsoZombieSpotChancePerformancePatchTest.zombie(6);
assertThrows(IllegalStateException.class, () -> new IsoZombieSpotChancePerformancePatch().apply(zombie));
}
@Test
void appliesOnlyToVerifiedVersions()
{
IsoZombieSpotChancePerformancePatch patch = new IsoZombieSpotChancePerformancePatch();
assertTrue(patch.appliesTo(GameVersion.parse("42.21.0")));
assertFalse(patch.appliesTo(GameVersion.parse("42.20.3")));
assertFalse(patch.appliesTo(GameVersion.parse("42.22.0")));
}
}