summaryrefslogtreecommitdiff
path: root/src/main/java/moe/nea/kowalski/init/EventClassTransformer.java
blob: a80a5b596eca58e2157d5e80ad1594f175b49870 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package moe.nea.kowalski.init;

import net.minecraft.launchwrapper.IClassTransformer;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.*;

import java.util.ListIterator;

public class EventClassTransformer implements IClassTransformer {
    @Override
    public byte[] transform(String name, String transformedName, byte[] basicClass) {
        if (!"net.minecraftforge.fml.common.eventhandler.Event".equals(name))
            return basicClass;
        ClassNode classNode = new ClassNode();
        ClassReader classReader = new ClassReader(basicClass);
        classReader.accept(classNode, 0);
        for (MethodNode method : classNode.methods) {
            if (method.name.equals("setCanceled")) {
                transformCancelMethod(method);
            }
        }
        ClassWriter writer = new ClassWriter(0);
        classNode.accept(writer);
        return writer.toByteArray();
    }

    private void transformCancelMethod(MethodNode method) {
        ListIterator<AbstractInsnNode> iterator =
                method.instructions.iterator();
        while (iterator.hasNext()) {
            AbstractInsnNode insn = iterator.next();
            if (insn.getOpcode() != Opcodes.PUTFIELD) {
                continue;
            }
            method.instructions.insert(insn, buildCallKowalski());
        }
    }

    private InsnList buildCallKowalski() {
        InsnList insnList = new InsnList();
        insnList.add(new VarInsnNode(Opcodes.ALOAD, 0));
        insnList.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "moe/nea/kowalski/Kowalski", "eventIsBeingCancelled", "(Lnet/minecraftforge/fml/common/eventhandler/Event;)V", false));
        return insnList;
    }
}