Skip to content
CorruptionHades edited this page Aug 24, 2023 · 3 revisions

This page is about Hooks

What is a hook?

A Hook is basically injecting your own custom code into Minecraft.

As an example I want to display Text on the ingame Hud. Why do we need a hook? Minecraft requires a DrawContext (yarn) / Graphics (mojang) class to draw something to the screen. Like in fabric we need to mixin/hook into the IngameHud class.

To create a Hook, create a new class and make it a child class of the Hook class.

This will requires you to create a Constructor. The super takes in a Class<?> target. This is the Target class we want to inject our code into.

The Mojang mapped name for the IngameHud class is called eow. We can now pass that into the constructor by using the ReflectionHelper to find that class:

public ExampleHook() {
    // Our target class to hook into
    super(ReflectionHelper.getClass("eow"));
}

Now we can hook into the render method for getting the DrawContext Object. We use the IMethodHook Annotation to do so:

@IMethodHook(method = "a", location = CodeInjection.Location.BEFORE, params = {"eox", "float"})

Lets break this down: The method parameter is the name of the render method mojang mapped (obfuscated). The location is where our custom code should be injected to. Right now there are only 2 options. BEFORE and AFTER.

The params are the method defining parameters of the method. This is an array and we need these, for helping the compiler get the correct method (there are likely multiple methods named 'a' with different parameters)

This is the deobfuscated render method of the IngameHud class

image

It takes in 2 parameters, a DrawContext and a float. The obfuscated name for the DrawContext is eox. We can now pass these into the params parameter of the annotation (it needs to be the same order):

params = {"eox", "float"}

To now inject our custom code we create a new Method which returns a String:

public String renderHook() {
    "";
}

Here we can pass in our code in valid Javassist format (class references need to contain the full package path)

public String renderHook() {
    return "{ corruptionhades.hook.HookListener.onRender2D($$0); }";
}

For accessing the method parameters we use standard Java parameter accessing aka $$parameter number (starting at 0). Now just register it in the HookManager and we are all done!

image

Clone this wiki locally