From 1b5a03cfc2ae09453ff26ac3713a8800bde6ccbb Mon Sep 17 00:00:00 2001 From: MehVahdJukaar Date: Tue, 30 Jul 2024 10:46:06 +0200 Subject: [PATCH 01/22] Added @ModuleInstance annotation. Annotate a static field inside your module class to have it populated with its instance, allowing for easy singleton patterns. This is opt in --- .../zeta/event/bus/ZetaEventBus.java | 4 +- .../zeta/event/bus/wip/ForgeZetaBus.java | 109 +++++++++++++++ .../zeta/event/bus/wip/ZetaBus.java | 125 ++++++++++++++++++ .../zetaimplforge/event/load/Test.java | 42 ------ 4 files changed, 237 insertions(+), 43 deletions(-) create mode 100644 src/main/java/org/violetmoon/zeta/event/bus/wip/ForgeZetaBus.java create mode 100644 src/main/java/org/violetmoon/zeta/event/bus/wip/ZetaBus.java delete mode 100644 src/main/java/org/violetmoon/zetaimplforge/event/load/Test.java diff --git a/src/main/java/org/violetmoon/zeta/event/bus/ZetaEventBus.java b/src/main/java/org/violetmoon/zeta/event/bus/ZetaEventBus.java index 001a5e4..ceaa8f5 100644 --- a/src/main/java/org/violetmoon/zeta/event/bus/ZetaEventBus.java +++ b/src/main/java/org/violetmoon/zeta/event/bus/ZetaEventBus.java @@ -169,6 +169,9 @@ private Listeners getListenersFor(Method method) { * Pausefrogeline */ private class Listeners { + + private final Map handles = new LinkedHashMap<>(); + private record Subscriber(@Nullable Object receiver, Class owningClazz, Method method) { @Override public boolean equals(Object object) { @@ -200,7 +203,6 @@ MethodHandle unreflect() { } } - private final Map handles = new LinkedHashMap<>(); void subscribe(@Nullable Object receiver, Class owningClazz, Method method) { try { diff --git a/src/main/java/org/violetmoon/zeta/event/bus/wip/ForgeZetaBus.java b/src/main/java/org/violetmoon/zeta/event/bus/wip/ForgeZetaBus.java new file mode 100644 index 0000000..b88db00 --- /dev/null +++ b/src/main/java/org/violetmoon/zeta/event/bus/wip/ForgeZetaBus.java @@ -0,0 +1,109 @@ +package org.violetmoon.zeta.event.bus.wip; + +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.eventbus.api.Event; +import net.minecraftforge.eventbus.api.IEventBus; +import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.violetmoon.zeta.Zeta; + +import java.lang.annotation.Annotation; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Consumer; +import java.util.function.Function; + +public class ForgeZetaBus extends ZetaBus { + + private final Map, Function> forgeToZetaMap = new HashMap<>(); + private final Map, Function> zetaToForgeMap = new HashMap<>(); + //ForgeZAddReloadListener.class, (Function) ForgeZAddReloadListener::new + + private final IEventBus forgeBus; + + /** + * @param subscriberAnnotation The annotation that subscribe()/unsubscribe() will pay attention to. + * @param eventRoot The superinterface of all events fired on this bus. + */ + public ForgeZetaBus(Zeta z, Class subscriberAnnotation, Class eventRoot, @Nullable Logger logSpam) { + super(z, subscriberAnnotation, eventRoot, logSpam); + this.forgeBus = MinecraftForge.EVENT_BUS; + } + + public void registerEventMappings(Class zetaEvent, + Function forgeToZeta, + Class forgeEvent, + Function zetaToForge) { + forgeToZetaMap.put(zetaEvent, forgeToZeta); + zetaToForgeMap.put(forgeEvent, zetaToForge); + } + + // takes a method that takes a zeta event and turns into one that takes a forge event + private Consumer remapMethod(MethodHandle zetaEventConsumer, Class zetaEventClass) { + Function forgeToZetaFunc = forgeToZetaMap.get(zetaEventClass); + return createForgeConsumer(zetaEventConsumer, forgeToZetaFunc); + } + + private Consumer createForgeConsumer(MethodHandle zetaEventConsumer, Function forgeToZetaFunc) { + return event -> { + try { + zetaEventConsumer.invoke(forgeToZetaFunc.apply(event)); + } catch (Throwable e) { + throw new RuntimeException(e); + } + }; + } + + @Override + protected void addListener(Method method, Object receiver, Class owningClazz) { + if (method.getParameterCount() != 1) + throw arityERR(method); + + Class eventType = method.getParameterTypes()[0]; + if (!eventRoot.isAssignableFrom(eventType)) + throw typeERR(method); + + MethodHandle handle; + try { + handle = MethodHandles.publicLookup().unreflect(method); + } catch (Exception e) { + throw new RuntimeException(e); + } + + //fill in the "this" parameter + if (receiver != null) + handle = handle.bindTo(receiver); + + forgeBus.addListener(remapMethod(handle, (Class) eventType)); + } + + @Override + protected void removeListener(Method m, Object receiver, Class owningClazz) { + + } + + + @Override + public T fire(@NotNull T event) { + forgeBus.post(remapEvent(event)); + return event; + } + + private Event remapEvent(@NotNull T event) { + Function zetaToForgeFunc = zetaToForgeMap.get(event.getClass()); + return createForgeEvent(event, zetaToForgeFunc); + } + + private Event createForgeEvent(@NotNull E event, Function function) { + return function.apply((T) event); + } + + @Override + public T fire(@NotNull T event, Class firedAs) { + return null; + } +} diff --git a/src/main/java/org/violetmoon/zeta/event/bus/wip/ZetaBus.java b/src/main/java/org/violetmoon/zeta/event/bus/wip/ZetaBus.java new file mode 100644 index 0000000..df92d0a --- /dev/null +++ b/src/main/java/org/violetmoon/zeta/event/bus/wip/ZetaBus.java @@ -0,0 +1,125 @@ +package org.violetmoon.zeta.event.bus.wip; + +import com.google.common.base.Preconditions; +import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.violetmoon.zeta.Zeta; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.Arrays; +import java.util.stream.Stream; + +public abstract class ZetaBus { + + protected final Class subscriberAnnotation; + protected final Class eventRoot; + protected final Zeta z; + protected final @Nullable Logger logSpam; + + /** + * @param subscriberAnnotation The annotation that subscribe()/unsubscribe() will pay attention to. + * @param eventRoot The superinterface of all events fired on this bus. + */ + public ZetaBus(Zeta z, Class subscriberAnnotation, Class eventRoot, @Nullable Logger logSpam) { + Preconditions.checkArgument(eventRoot.isInterface(), "Event roots should be an interface"); + + this.z = z; + this.subscriberAnnotation = subscriberAnnotation; + this.eventRoot = eventRoot; + this.logSpam = logSpam; + } + + /** + * If the parameter is a Class: subscribes all static methods from it (and its superclasses) to the event bus. + * Otherwise, subscribes all non-static methods on that object (and its superclasses) to the event bus. + * (Note that the event bus will hold a reference to this object.) + */ + public ZetaBus subscribe(@NotNull Object target) { + Preconditions.checkNotNull(target, "null passed to subscribe"); + + Object receiver; + Class owningClazz; + if (target instanceof Class clazz) { + receiver = null; + owningClazz = clazz; + } else { + receiver = target; + owningClazz = target.getClass(); + } + + streamAnnotatedMethods(owningClazz, receiver == null) + .forEach(m -> addListener(m, receiver, owningClazz)); + return this; + } + + protected abstract void addListener(Method m, Object receiver, Class owningClazz); + + /** + * If the parameter is a Class: unsubscribes all static methods from it (and its superclasses) from the event bus. + * Otherwise, unsubscribes all non-static methods on that object (and its superclasses) from the event bus. + */ + public ZetaBus unsubscribe(@NotNull Object target) { + Preconditions.checkNotNull(target, "null passed to unsubscribe"); + + Object receiver; + Class owningClazz; + if (target instanceof Class clazz) { + receiver = null; + owningClazz = clazz; + } else { + receiver = target; + owningClazz = target.getClass(); + } + + streamAnnotatedMethods(owningClazz, receiver == null) + .forEach(m -> removeListener(m, receiver, owningClazz)); + return this; + } + + protected abstract void removeListener(Method m, Object receiver, Class owningClazz); + + /** + * Fires an event on the event bus. Each subscriber will be visited in order. + */ + public abstract T fire(@NotNull T event); + + /** + * Fires an event on the event bus. Each subscriber will be visited in order. + * Listeners for "firedAs" will be invoked, instead of listeners for the event's own class. + *

+ * (The generic should be Class<? super T & ? extends E>, but unfortunately, javac.) + */ + public abstract T fire(@NotNull T event, Class firedAs); + + /** + * Grabs methods from this class (and its superclasses, recursively) that are annotated with this bus's + * annotation; and of the requested staticness. + */ + private Stream streamAnnotatedMethods(Class owningClazz, boolean wantStatic) { + return Arrays.stream(owningClazz.getMethods()) + .filter(m -> m.isAnnotationPresent(subscriberAnnotation) && ((m.getModifiers() & Modifier.STATIC) != 0) == wantStatic); + } + + protected RuntimeException arityERR(Method method) { + return methodProblem("Method annotated with @" + subscriberAnnotation.getSimpleName() + + " should take 1 parameter.", method, null); + } + + protected RuntimeException typeERR(Method method) { + return methodProblem("Method annotated with @" + subscriberAnnotation.getSimpleName() + + " should take an implementor of " + eventRoot.getSimpleName() + ".", method, null); + } + + protected RuntimeException unreflectERR(Method method, Throwable cause) { + return methodProblem("Exception unreflecting a @" + subscriberAnnotation.getSimpleName() + + " method, is it public?", method, cause); + } + + protected static RuntimeException methodProblem(String problem, Method method, @Nullable Throwable cause) { + return new RuntimeException("%s%nMethod class: %s%nMethod name: %s".formatted( + problem, method.getDeclaringClass().getName(), method.getName()), cause); + } +} diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/load/Test.java b/src/main/java/org/violetmoon/zetaimplforge/event/load/Test.java deleted file mode 100644 index 13e9efa..0000000 --- a/src/main/java/org/violetmoon/zetaimplforge/event/load/Test.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.violetmoon.zetaimplforge.event.load; - -import net.minecraftforge.event.AddReloadListenerEvent; -import net.minecraftforge.eventbus.EventBus; -import net.minecraftforge.eventbus.api.Event; -import org.jetbrains.annotations.NotNull; -import org.violetmoon.zeta.event.bus.IZetaLoadEvent; -import org.violetmoon.zeta.event.bus.ZetaEventBus; - -import java.util.Map; -import java.util.function.Consumer; -import java.util.function.Function; - -// This made sense when i wrote it. Now i have no clue -// Please somebody finish this -public class Test { - - private static final Map, Function> FORGE_TO_ZETA = Map.of( - ForgeZAddReloadListener.class, (Function) ForgeZAddReloadListener::new - ); - - public static Consumer remap(Consumer zetaEventConsumer, Class cl) { - Function forgeToZeta = (Function) FORGE_TO_ZETA.get(cl); - return getEventConsumer(zetaEventConsumer, forgeToZeta); - } - - @NotNull - private static Consumer getEventConsumer(Consumer zetaEventConsumer, Function forgeToZeta) { - return event -> zetaEventConsumer.accept(forgeToZeta.apply(event)); - } - - - public static class ExampleZetaBus{ - private EventBus forgeBus; - - public void addListener(Consumer zetaEventConsumer, Class cl){ - forgeBus.addListener(remap(zetaEventConsumer, cl)); - } - - } - -} From 037faad8bd52a9ef3258a418722cb7bdd6c89ec7 Mon Sep 17 00:00:00 2001 From: MehVahdJukaar Date: Tue, 30 Jul 2024 12:34:50 +0200 Subject: [PATCH 02/22] more sketchy work on forge specific zeta bus --- .../zeta/event/bus/wip/ForgeZetaBus.java | 117 ++++++++++++------ .../zeta/event/bus/wip/ZetaBus.java | 4 +- 2 files changed, 81 insertions(+), 40 deletions(-) diff --git a/src/main/java/org/violetmoon/zeta/event/bus/wip/ForgeZetaBus.java b/src/main/java/org/violetmoon/zeta/event/bus/wip/ForgeZetaBus.java index b88db00..c83171b 100644 --- a/src/main/java/org/violetmoon/zeta/event/bus/wip/ForgeZetaBus.java +++ b/src/main/java/org/violetmoon/zeta/event/bus/wip/ForgeZetaBus.java @@ -1,9 +1,9 @@ package org.violetmoon.zeta.event.bus.wip; -import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.eventbus.api.Event; import net.minecraftforge.eventbus.api.IEventBus; import org.apache.logging.log4j.Logger; +import org.checkerframework.checker.units.qual.A; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.violetmoon.zeta.Zeta; @@ -11,51 +11,31 @@ import java.lang.annotation.Annotation; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import java.util.function.Consumer; import java.util.function.Function; +// this is quite jank. Basically converts all zeta events to forge ones, then delegates to the forge bus directly public class ForgeZetaBus extends ZetaBus { private final Map, Function> forgeToZetaMap = new HashMap<>(); - private final Map, Function> zetaToForgeMap = new HashMap<>(); - //ForgeZAddReloadListener.class, (Function) ForgeZAddReloadListener::new + private final Map, Function> zetaToForgeMap = new HashMap<>(); private final IEventBus forgeBus; + private final Map convertedHandlers = new HashMap<>(); /** * @param subscriberAnnotation The annotation that subscribe()/unsubscribe() will pay attention to. * @param eventRoot The superinterface of all events fired on this bus. */ - public ForgeZetaBus(Zeta z, Class subscriberAnnotation, Class eventRoot, @Nullable Logger logSpam) { + public ForgeZetaBus(Zeta z, Class subscriberAnnotation, Class eventRoot, + @Nullable Logger logSpam, IEventBus forgeBus) { super(z, subscriberAnnotation, eventRoot, logSpam); - this.forgeBus = MinecraftForge.EVENT_BUS; - } - - public void registerEventMappings(Class zetaEvent, - Function forgeToZeta, - Class forgeEvent, - Function zetaToForge) { - forgeToZetaMap.put(zetaEvent, forgeToZeta); - zetaToForgeMap.put(forgeEvent, zetaToForge); - } - - // takes a method that takes a zeta event and turns into one that takes a forge event - private Consumer remapMethod(MethodHandle zetaEventConsumer, Class zetaEventClass) { - Function forgeToZetaFunc = forgeToZetaMap.get(zetaEventClass); - return createForgeConsumer(zetaEventConsumer, forgeToZetaFunc); - } - - private Consumer createForgeConsumer(MethodHandle zetaEventConsumer, Function forgeToZetaFunc) { - return event -> { - try { - zetaEventConsumer.invoke(forgeToZetaFunc.apply(event)); - } catch (Throwable e) { - throw new RuntimeException(e); - } - }; + this.forgeBus = forgeBus; } @Override @@ -78,32 +58,93 @@ protected void addListener(Method method, Object receiver, Class owningClazz) if (receiver != null) handle = handle.bindTo(receiver); - forgeBus.addListener(remapMethod(handle, (Class) eventType)); + Consumer consumer = remapMethod(handle, (Class) eventType); + forgeBus.addListener(consumer); + //store here so we can unregister later + convertedHandlers.put(new Key(method, receiver, owningClazz), consumer); } @Override - protected void removeListener(Method m, Object receiver, Class owningClazz) { - + protected void unregisterMethod(Method m, Object receiver, Class owningClazz) { + var handler = convertedHandlers.remove(new Key(m, receiver, owningClazz)); + if (handler != null) { + forgeBus.unregister(handler); + } } + private record Key(Method method, Object receiver, Class owningClazz) { + } @Override public T fire(@NotNull T event) { - forgeBus.post(remapEvent(event)); + forgeBus.post(remapEvent(event, event.getClass())); return event; } - private Event remapEvent(@NotNull T event) { - Function zetaToForgeFunc = zetaToForgeMap.get(event.getClass()); + @Override + public T fire(@NotNull T event, Class firedAs) { + forgeBus.post(remapEvent(event, firedAs)); + return event; + } + + // reflection hacks below. be warned + + private Event remapEvent(@NotNull T event, Class firedAs) { + Function zetaToForgeFunc = zetaToForgeMap.computeIfAbsent((Class) firedAs, this::findWrappedEvent); return createForgeEvent(event, zetaToForgeFunc); } + // takes a method that takes a zeta event and turns into one that takes a forge event + private Consumer remapMethod(MethodHandle zetaEventConsumer, Class zetaEventClass) { + Function forgeToZetaFunc = forgeToZetaMap.computeIfAbsent(zetaEventClass,this::findWrappingConstructor); + return createForgeConsumer(zetaEventConsumer, forgeToZetaFunc); + } + + + private Function findWrappedEvent(Class zetaEventClass) { + for (Field field : zetaEventClass.getDeclaredFields()) { + if (Event.class.isAssignableFrom(field.getType())) { + return instance -> { + try { + return (Event) field.get(instance); + } catch (IllegalAccessException illegalAccessException) { + throw new RuntimeException(illegalAccessException); + } + }; + } + } + throw new RuntimeException("No wrapped forge Event found for Zeta event class " + zetaEventClass); + } + + private Function findWrappingConstructor(Class zetaEventClass) { + // Find the constructor that takes a single parameter of type A + for (Constructor constructor : zetaEventClass.getConstructors()) { + Class[] parameterTypes = constructor.getParameterTypes(); + if (parameterTypes.length == 1 && Event.class.isAssignableFrom(parameterTypes[0])) { + return event -> { + try { + return (E) constructor.newInstance(event); + } catch (Exception e) { + throw new RuntimeException(e); + } + }; + } + } + throw new RuntimeException("No forge-Event-wrapping constructor found for Zeta event class " + zetaEventClass); + } + private Event createForgeEvent(@NotNull E event, Function function) { return function.apply((T) event); } - @Override - public T fire(@NotNull T event, Class firedAs) { - return null; + private Consumer createForgeConsumer(MethodHandle zetaEventConsumer, Function forgeToZetaFunc) { + return event -> { + try { + zetaEventConsumer.invoke(forgeToZetaFunc.apply(event)); + } catch (Throwable e) { + throw new RuntimeException(e); + } + }; } + } diff --git a/src/main/java/org/violetmoon/zeta/event/bus/wip/ZetaBus.java b/src/main/java/org/violetmoon/zeta/event/bus/wip/ZetaBus.java index df92d0a..2c6a064 100644 --- a/src/main/java/org/violetmoon/zeta/event/bus/wip/ZetaBus.java +++ b/src/main/java/org/violetmoon/zeta/event/bus/wip/ZetaBus.java @@ -75,11 +75,11 @@ public ZetaBus unsubscribe(@NotNull Object target) { } streamAnnotatedMethods(owningClazz, receiver == null) - .forEach(m -> removeListener(m, receiver, owningClazz)); + .forEach(m -> unregisterMethod(m, receiver, owningClazz)); return this; } - protected abstract void removeListener(Method m, Object receiver, Class owningClazz); + protected abstract void unregisterMethod(Method m, Object receiver, Class owningClazz); /** * Fires an event on the event bus. Each subscriber will be visited in order. From b5bd334cfbbf5fffdd99c59b9f5c403c85db6f78 Mon Sep 17 00:00:00 2001 From: MehVahdJukaar Date: Tue, 30 Jul 2024 12:57:41 +0200 Subject: [PATCH 03/22] impl --- src/main/java/org/violetmoon/zeta/Zeta.java | 13 +- .../zeta/event/bus/FabricZetaEventBus.java | 197 +++ ...rgeZetaBus.java => ForgeZetaEventBus.java} | 17 +- .../zeta/event/bus/ZetaEventBus.java | 374 ++---- .../zeta/event/bus/wip/ZetaBus.java | 125 -- .../violetmoon/zetaimplforge/ForgeZeta.java | 1098 ++++++++--------- 6 files changed, 834 insertions(+), 990 deletions(-) create mode 100644 src/main/java/org/violetmoon/zeta/event/bus/FabricZetaEventBus.java rename src/main/java/org/violetmoon/zeta/event/bus/{wip/ForgeZetaBus.java => ForgeZetaEventBus.java} (89%) delete mode 100644 src/main/java/org/violetmoon/zeta/event/bus/wip/ZetaBus.java diff --git a/src/main/java/org/violetmoon/zeta/Zeta.java b/src/main/java/org/violetmoon/zeta/Zeta.java index 1a147e7..a056b0f 100644 --- a/src/main/java/org/violetmoon/zeta/Zeta.java +++ b/src/main/java/org/violetmoon/zeta/Zeta.java @@ -11,11 +11,7 @@ import org.violetmoon.zeta.config.ConfigManager; import org.violetmoon.zeta.config.IZetaConfigInternals; import org.violetmoon.zeta.config.SectionDefinition; -import org.violetmoon.zeta.event.bus.IZetaLoadEvent; -import org.violetmoon.zeta.event.bus.IZetaPlayEvent; -import org.violetmoon.zeta.event.bus.LoadEvent; -import org.violetmoon.zeta.event.bus.PlayEvent; -import org.violetmoon.zeta.event.bus.ZetaEventBus; +import org.violetmoon.zeta.event.bus.*; import org.violetmoon.zeta.item.ext.ItemExtensionFactory; import org.violetmoon.zeta.module.ModuleFinder; import org.violetmoon.zeta.module.ZetaCategory; @@ -51,13 +47,14 @@ public abstract class Zeta implements IZeta { public static final String ZETA_ID = "zeta"; public static final Logger GLOBAL_LOG = LogManager.getLogger(ZETA_ID); - public Zeta(String modid, Logger log, ZetaSide side) { + public Zeta(String modid, Logger log, ZetaSide side, ZetaEventBus loadBus, ZetaEventBus playBus) { this.log = log; this.modid = modid; this.side = side; - this.loadBus = new ZetaEventBus<>(this, LoadEvent.class, IZetaLoadEvent.class, log); - this.playBus = new ZetaEventBus<>(this, PlayEvent.class, IZetaPlayEvent.class, null); + + this.loadBus = loadBus; + this.playBus = playBus; this.modules = createModuleManager(); this.registry = createRegistry(); diff --git a/src/main/java/org/violetmoon/zeta/event/bus/FabricZetaEventBus.java b/src/main/java/org/violetmoon/zeta/event/bus/FabricZetaEventBus.java new file mode 100644 index 0000000..69dcf72 --- /dev/null +++ b/src/main/java/org/violetmoon/zeta/event/bus/FabricZetaEventBus.java @@ -0,0 +1,197 @@ +package org.violetmoon.zeta.event.bus; + +import java.lang.annotation.Annotation; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; + +import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.violetmoon.zeta.Zeta; + +/** + * A polymorphic event bus. Events can be fired under one of their supertypes, allowing a sort of API/impl split of events. + * + * Due to implementation complexity, there is unfortunately no support for: + * - generic events (like Forge's RegistryEvent) + * - registering an anonymous `Consumer` (like Forge's "addListener" method) + * Supported Java reflection APIs don't expose this information. Forge can only get at it with a library internally using sun.misc.Unsafe. + */ +public class FabricZetaEventBus extends ZetaEventBus { + + private final Map, Listeners> listenerMap = new HashMap<>(); + + /** + * @param subscriberAnnotation The annotation that subscribe()/unsubscribe() will pay attention to. + * @param eventRoot The superinterface of all events fired on this bus. + * @param logSpam + */ + public FabricZetaEventBus(Class subscriberAnnotation, Class eventRoot, @Nullable Logger logSpam) { + super(subscriberAnnotation, eventRoot, logSpam); + } + + @Override + protected void subscribeMethod(Method m, Object receiver, Class owningClazz) { + getListenersFor(m).subscribe(receiver, owningClazz, m); + } + + @Override + protected void unsubscribeMethod(Method m, Object receiver, Class owningClazz) { + getListenersFor(m).unsubscribe(receiver, owningClazz, m); + } + + /** + * Fires an event on the event bus. Each subscriber will be visited in order. + */ + public T fire(@NotNull T event) { + Listeners subs = listenerMap.get(event.getClass()); + if(subs != null) { + if(logSpam != null) + logSpam.info("Dispatching {} to {} listener{}", logSpamSimpleName(event.getClass()), subs.size(), subs.size() > 1 ? "s" : ""); + + subs.doFire(event); + } + + return event; + } + + /** + * Fires an event on the event bus. Each subscriber will be visited in order. + * Listeners for "firedAs" will be invoked, instead of listeners for the event's own class. + *

+ * (The generic should be Class<? super T & ? extends E>, but unfortunately, javac.) + */ + public T fire(@NotNull T event, Class firedAs) { + Listeners subs = listenerMap.get(firedAs); + if(subs != null) { + if(logSpam != null) + logSpam.info("Dispatching {} (as {}) to {} listener{}", logSpamSimpleName(event.getClass()), logSpamSimpleName(firedAs), subs.size(), subs.size() > 1 ? "s" : ""); + + subs.doFire(event); + } + + return event; + } + + //this is really silly + private String logSpamSimpleName(Class clazz) { + String[] split = clazz.getName().split("\\."); + return split[split.length - 1]; + } + + public T fireExternal(@NotNull T event, Class firedAs) { + event = fire(event, firedAs); + + if(event instanceof Cancellable cancellable && cancellable.isCanceled()) + return event; + else{ + throw new RuntimeException(); + //TODO: re add. this shuld be put in loader specific bus code + //return z.fireExternalEvent(event); // Interfaces with the platform-specific event bus utility + } + + } + + /** + * Picks out the "Foo" in "void handleFoo(Foo event)", and gets/creates the Listeners corresponding to that type. + */ + @SuppressWarnings("unchecked") + private Listeners getListenersFor(Method method) { + if(method.getParameterCount() != 1) + throw arityERR(method); + + Class eventType = method.getParameterTypes()[0]; + if(!eventRoot.isAssignableFrom(eventType)) + throw typeERR(method); + + return listenerMap.computeIfAbsent((Class) eventType, __ -> new Listeners()); + } + + /** + * Mildly overengineered since I want method dispatching to hopefully be low-overhead... don't mind me + * MethodHandle is magic free performance right + * Pausefrogeline + */ + private class Listeners { + + private final Map handles = new LinkedHashMap<>(); + + private record Subscriber(@Nullable Object receiver, Class owningClazz, Method method) { + @Override + public boolean equals(Object object) { + if(this == object) return true; + if(object == null || getClass() != object.getClass()) return false; + Subscriber that = (Subscriber) object; + return receiver == that.receiver && //<-- object identity compare + Objects.equals(owningClazz, that.owningClazz) && + Objects.equals(method, that.method); + } + + @Override + public int hashCode() { + return System.identityHashCode(receiver) + owningClazz.hashCode() + method.hashCode(); + } + + MethodHandle unreflect() { + MethodHandle handle; + try { + handle = MethodHandles.publicLookup().unreflect(method); + } catch (Exception e) { + throw new RuntimeException(e); + } + + //fill in the "this" parameter + if(receiver != null) + handle = handle.bindTo(receiver); + return handle; + } + } + + + void subscribe(@Nullable Object receiver, Class owningClazz, Method method) { + try { + handles.computeIfAbsent(new Subscriber(receiver, owningClazz, method), Subscriber::unreflect); + } catch (Exception e) { + throw unreflectERR(method, e); + } + } + + void unsubscribe(@Nullable Object receiver, Class owningClazz, Method method) { + handles.remove(new Subscriber(receiver, owningClazz, method)); + } + + int size() { + return handles.size(); + } + + //just hoisting the instanceof out of the loop.. No profiling just vibes <3 + void doFire(E event) { + try { + if(event instanceof Cancellable cancellable) + doFireCancellable(cancellable); + else + doFireNonCancellable(event); + } catch (Throwable e) { + throw new RuntimeException("Exception while firing event " + event + ": ", e); + } + } + + void doFireCancellable(Cancellable event) throws Throwable { + for(MethodHandle handle : handles.values()) { + handle.invoke(event); + if(event.isCanceled()) break; + } + } + + void doFireNonCancellable(E event) throws Throwable { + for(MethodHandle handle : handles.values()) + handle.invoke(event); + } + } + +} diff --git a/src/main/java/org/violetmoon/zeta/event/bus/wip/ForgeZetaBus.java b/src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java similarity index 89% rename from src/main/java/org/violetmoon/zeta/event/bus/wip/ForgeZetaBus.java rename to src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java index c83171b..cccbf8c 100644 --- a/src/main/java/org/violetmoon/zeta/event/bus/wip/ForgeZetaBus.java +++ b/src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java @@ -1,9 +1,8 @@ -package org.violetmoon.zeta.event.bus.wip; +package org.violetmoon.zeta.event.bus; import net.minecraftforge.eventbus.api.Event; import net.minecraftforge.eventbus.api.IEventBus; import org.apache.logging.log4j.Logger; -import org.checkerframework.checker.units.qual.A; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.violetmoon.zeta.Zeta; @@ -20,7 +19,7 @@ import java.util.function.Function; // this is quite jank. Basically converts all zeta events to forge ones, then delegates to the forge bus directly -public class ForgeZetaBus extends ZetaBus { +public class ForgeZetaEventBus extends ZetaEventBus { private final Map, Function> forgeToZetaMap = new HashMap<>(); private final Map, Function> zetaToForgeMap = new HashMap<>(); @@ -32,14 +31,14 @@ public class ForgeZetaBus extends ZetaBus { * @param subscriberAnnotation The annotation that subscribe()/unsubscribe() will pay attention to. * @param eventRoot The superinterface of all events fired on this bus. */ - public ForgeZetaBus(Zeta z, Class subscriberAnnotation, Class eventRoot, - @Nullable Logger logSpam, IEventBus forgeBus) { - super(z, subscriberAnnotation, eventRoot, logSpam); + public ForgeZetaEventBus(Class subscriberAnnotation, Class eventRoot, + @Nullable Logger logSpam, IEventBus forgeBus) { + super(subscriberAnnotation, eventRoot, logSpam); this.forgeBus = forgeBus; } @Override - protected void addListener(Method method, Object receiver, Class owningClazz) { + protected void subscribeMethod(Method method, Object receiver, Class owningClazz) { if (method.getParameterCount() != 1) throw arityERR(method); @@ -65,7 +64,7 @@ protected void addListener(Method method, Object receiver, Class owningClazz) } @Override - protected void unregisterMethod(Method m, Object receiver, Class owningClazz) { + protected void unsubscribeMethod(Method m, Object receiver, Class owningClazz) { var handler = convertedHandlers.remove(new Key(m, receiver, owningClazz)); if (handler != null) { forgeBus.unregister(handler); @@ -82,7 +81,7 @@ public T fire(@NotNull T event) { } @Override - public T fire(@NotNull T event, Class firedAs) { + public T fire(@NotNull T event, Class firedAs) { forgeBus.post(remapEvent(event, firedAs)); return event; } diff --git a/src/main/java/org/violetmoon/zeta/event/bus/ZetaEventBus.java b/src/main/java/org/violetmoon/zeta/event/bus/ZetaEventBus.java index ceaa8f5..5dc991d 100644 --- a/src/main/java/org/violetmoon/zeta/event/bus/ZetaEventBus.java +++ b/src/main/java/org/violetmoon/zeta/event/bus/ZetaEventBus.java @@ -1,267 +1,125 @@ package org.violetmoon.zeta.event.bus; -import java.lang.annotation.Annotation; -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.Arrays; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; -import java.util.stream.Stream; - +import com.google.common.base.Preconditions; import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.violetmoon.zeta.Zeta; -import com.google.common.base.Preconditions; - -/** - * A polymorphic event bus. Events can be fired under one of their supertypes, allowing a sort of API/impl split of events. - * - * Due to implementation complexity, there is unfortunately no support for: - * - generic events (like Forge's RegistryEvent) - * - registering an anonymous `Consumer` (like Forge's "addListener" method) - * Supported Java reflection APIs don't expose this information. Forge can only get at it with a library internally using sun.misc.Unsafe. - */ -public class ZetaEventBus { - private final Zeta z; - private final Class subscriberAnnotation; - private final Class eventRoot; - private final @Nullable Logger logSpam; - - private final Map, Listeners> listenerMap = new HashMap<>(); - - /** - * @param subscriberAnnotation The annotation that subscribe()/unsubscribe() will pay attention to. - * @param eventRoot The superinterface of all events fired on this bus. - */ - public ZetaEventBus(Zeta z, Class subscriberAnnotation, Class eventRoot, @Nullable Logger logSpam) { - Preconditions.checkArgument(eventRoot.isInterface(), "Event roots should be an interface"); - - this.z = z; - this.subscriberAnnotation = subscriberAnnotation; - this.eventRoot = eventRoot; - this.logSpam = logSpam; - } - - /** - * If the parameter is a Class: subscribes all static methods from it (and its superclasses) to the event bus. - * Otherwise, subscribes all non-static methods on that object (and its superclasses) to the event bus. - * (Note that the event bus will hold a reference to this object.) - */ - public ZetaEventBus subscribe(@NotNull Object target) { - Preconditions.checkNotNull(target, "null passed to subscribe"); - - Object receiver; - Class owningClazz; - if(target instanceof Class clazz) { - receiver = null; - owningClazz = clazz; - } else { - receiver = target; - owningClazz = target.getClass(); - } - - streamAnnotatedMethods(owningClazz, receiver == null).forEach(m -> getListenersFor(m).subscribe(receiver, owningClazz, m)); - return this; - } - - /** - * If the parameter is a Class: unsubscribes all static methods from it (and its superclasses) from the event bus. - * Otherwise, unsubscribes all non-static methods on that object (and its superclasses) from the event bus. - */ - public ZetaEventBus unsubscribe(@NotNull Object target) { - Preconditions.checkNotNull(target, "null passed to unsubscribe"); - - Object receiver; - Class owningClazz; - if(target instanceof Class clazz) { - receiver = null; - owningClazz = clazz; - } else { - receiver = target; - owningClazz = target.getClass(); - } - - streamAnnotatedMethods(owningClazz, receiver == null).forEach(m -> getListenersFor(m).unsubscribe(receiver, owningClazz, m)); - return this; - } - - /** - * Fires an event on the event bus. Each subscriber will be visited in order. - */ - public T fire(@NotNull T event) { - Listeners subs = listenerMap.get(event.getClass()); - if(subs != null) { - if(logSpam != null) - logSpam.info("Dispatching {} to {} listener{}", logspamSimpleName(event.getClass()), subs.size(), subs.size() > 1 ? "s" : ""); - - subs.doFire(event); - } - - return event; - } - - /** - * Fires an event on the event bus. Each subscriber will be visited in order. - * Listeners for "firedAs" will be invoked, instead of listeners for the event's own class. - *

- * (The generic should be Class<? super T & ? extends E>, but unfortunately, javac.) - */ - public T fire(@NotNull T event, Class firedAs) { - Listeners subs = listenerMap.get(firedAs); - if(subs != null) { - if(logSpam != null) - logSpam.info("Dispatching {} (as {}) to {} listener{}", logspamSimpleName(event.getClass()), logspamSimpleName(firedAs), subs.size(), subs.size() > 1 ? "s" : ""); - - subs.doFire(event); - } - - return event; - } - - //this is really silly - private String logspamSimpleName(Class clazz) { - String[] split = clazz.getName().split("\\."); - return split[split.length - 1]; - } - - public T fireExternal(@NotNull T event, Class firedAs) { - event = fire(event, firedAs); - - if(event instanceof Cancellable cancellable && cancellable.isCanceled()) - return event; - else - return z.fireExternalEvent(event); // Interfaces with the platform-specific event bus utility - } - - /** - * Grabs methods from this class (and its superclasses, recursively) that are annotated with this bus's - * annotation; and of the requested staticness. - */ - private Stream streamAnnotatedMethods(Class owningClazz, boolean wantStatic) { - return Arrays.stream(owningClazz.getMethods()) - .filter(m -> m.isAnnotationPresent(subscriberAnnotation) && ((m.getModifiers() & Modifier.STATIC) != 0) == wantStatic); - } - - /** - * Picks out the "Foo" in "void handleFoo(Foo event)", and gets/creates the Listeners corresponding to that type. - */ - @SuppressWarnings("unchecked") - private Listeners getListenersFor(Method method) { - if(method.getParameterCount() != 1) - throw arityERR(method); - - Class eventType = method.getParameterTypes()[0]; - if(!eventRoot.isAssignableFrom(eventType)) - throw typeERR(method); - - return listenerMap.computeIfAbsent((Class) eventType, __ -> new Listeners()); - } - - /** - * Mildly overengineered since I want method dispatching to hopefully be low-overhead... don't mind me - * MethodHandle is magic free performance right - * Pausefrogeline - */ - private class Listeners { - - private final Map handles = new LinkedHashMap<>(); - - private record Subscriber(@Nullable Object receiver, Class owningClazz, Method method) { - @Override - public boolean equals(Object object) { - if(this == object) return true; - if(object == null || getClass() != object.getClass()) return false; - Subscriber that = (Subscriber) object; - return receiver == that.receiver && //<-- object identity compare - Objects.equals(owningClazz, that.owningClazz) && - Objects.equals(method, that.method); - } - - @Override - public int hashCode() { - return System.identityHashCode(receiver) + owningClazz.hashCode() + method.hashCode(); - } - - MethodHandle unreflect() { - MethodHandle handle; - try { - handle = MethodHandles.publicLookup().unreflect(method); - } catch (Exception e) { - throw new RuntimeException(e); - } - - //fill in the "this" parameter - if(receiver != null) - handle = handle.bindTo(receiver); - return handle; - } - } - - - void subscribe(@Nullable Object receiver, Class owningClazz, Method method) { - try { - handles.computeIfAbsent(new Subscriber(receiver, owningClazz, method), Subscriber::unreflect); - } catch (Exception e) { - throw unreflectERR(method, e); - } - } - - void unsubscribe(@Nullable Object receiver, Class owningClazz, Method method) { - handles.remove(new Subscriber(receiver, owningClazz, method)); - } - - int size() { - return handles.size(); - } - - //just hoisting the instanceof out of the loop.. No profiling just vibes <3 - void doFire(E event) { - try { - if(event instanceof Cancellable cancellable) - doFireCancellable(cancellable); - else - doFireNonCancellable(event); - } catch (Throwable e) { - throw new RuntimeException("Exception while firing event " + event + ": ", e); - } - } - - void doFireCancellable(Cancellable event) throws Throwable { - for(MethodHandle handle : handles.values()) { - handle.invoke(event); - if(event.isCanceled()) break; - } - } - - void doFireNonCancellable(E event) throws Throwable { - for(MethodHandle handle : handles.values()) - handle.invoke(event); - } - } - - private RuntimeException arityERR(Method method) { - return methodProblem("Method annotated with @" + subscriberAnnotation.getSimpleName() + - " should take 1 parameter.", method, null); - } - - private RuntimeException typeERR(Method method) { - return methodProblem("Method annotated with @" + subscriberAnnotation.getSimpleName() + - " should take an implementor of " + eventRoot.getSimpleName() + ".", method, null); - } - - private RuntimeException unreflectERR(Method method, Throwable cause) { - return methodProblem("Exception unreflecting a @" + subscriberAnnotation.getSimpleName() + - " method, is it public?", method, cause); - } +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.Arrays; +import java.util.stream.Stream; - private static RuntimeException methodProblem(String problem, Method method, @Nullable Throwable cause) { - return new RuntimeException("%s%nMethod class: %s%nMethod name: %s".formatted( - problem, method.getDeclaringClass().getName(), method.getName()), cause); - } +public abstract class ZetaEventBus { + + protected final Class subscriberAnnotation; + protected final Class eventRoot; + protected final @Nullable Logger logSpam; + + /** + * @param subscriberAnnotation The annotation that subscribe()/unsubscribe() will pay attention to. + * @param eventRoot The superinterface of all events fired on this bus. + */ + public ZetaEventBus(Class subscriberAnnotation, Class eventRoot, @Nullable Logger logSpam) { + Preconditions.checkArgument(eventRoot.isInterface(), "Event roots should be an interface"); + + this.subscriberAnnotation = subscriberAnnotation; + this.eventRoot = eventRoot; + this.logSpam = logSpam; + } + + /** + * If the parameter is a Class: subscribes all static methods from it (and its superclasses) to the event bus. + * Otherwise, subscribes all non-static methods on that object (and its superclasses) to the event bus. + * (Note that the event bus will hold a reference to this object.) + */ + public ZetaEventBus subscribe(@NotNull Object target) { + Preconditions.checkNotNull(target, "null passed to subscribe"); + + Object receiver; + Class owningClazz; + if (target instanceof Class clazz) { + receiver = null; + owningClazz = clazz; + } else { + receiver = target; + owningClazz = target.getClass(); + } + + streamAnnotatedMethods(owningClazz, receiver == null) + .forEach(m -> subscribeMethod(m, receiver, owningClazz)); + return this; + } + + + /** + * If the parameter is a Class: unsubscribes all static methods from it (and its superclasses) from the event bus. + * Otherwise, unsubscribes all non-static methods on that object (and its superclasses) from the event bus. + */ + public ZetaEventBus unsubscribe(@NotNull Object target) { + Preconditions.checkNotNull(target, "null passed to unsubscribe"); + + Object receiver; + Class owningClazz; + if (target instanceof Class clazz) { + receiver = null; + owningClazz = clazz; + } else { + receiver = target; + owningClazz = target.getClass(); + } + + streamAnnotatedMethods(owningClazz, receiver == null) + .forEach(m -> unsubscribeMethod(m, receiver, owningClazz)); + return this; + } + + protected abstract void unsubscribeMethod(Method m, Object receiver, Class owningClazz); + + protected abstract void subscribeMethod(Method m, Object receiver, Class owningClazz); + + + /** + * Fires an event on the event bus. Each subscriber will be visited in order. + */ + public abstract T fire(@NotNull T event); + + /** + * Fires an event on the event bus. Each subscriber will be visited in order. + * Listeners for "firedAs" will be invoked, instead of listeners for the event's own class. + *

+ * (The generic should be Class<? super T & ? extends E>, but unfortunately, javac.) + */ + public abstract T fire(@NotNull T event, Class firedAs); + + /** + * Grabs methods from this class (and its superclasses, recursively) that are annotated with this bus's + * annotation; and of the requested staticness. + */ + private Stream streamAnnotatedMethods(Class owningClazz, boolean wantStatic) { + return Arrays.stream(owningClazz.getMethods()) + .filter(m -> m.isAnnotationPresent(subscriberAnnotation) && ((m.getModifiers() & Modifier.STATIC) != 0) == wantStatic); + } + + protected RuntimeException arityERR(Method method) { + return methodProblem("Method annotated with @" + subscriberAnnotation.getSimpleName() + + " should take 1 parameter.", method, null); + } + + protected RuntimeException typeERR(Method method) { + return methodProblem("Method annotated with @" + subscriberAnnotation.getSimpleName() + + " should take an implementor of " + eventRoot.getSimpleName() + ".", method, null); + } + + protected RuntimeException unreflectERR(Method method, Throwable cause) { + return methodProblem("Exception unreflecting a @" + subscriberAnnotation.getSimpleName() + + " method, is it public?", method, cause); + } + + protected static RuntimeException methodProblem(String problem, Method method, @Nullable Throwable cause) { + return new RuntimeException("%s%nMethod class: %s%nMethod name: %s".formatted( + problem, method.getDeclaringClass().getName(), method.getName()), cause); + } } diff --git a/src/main/java/org/violetmoon/zeta/event/bus/wip/ZetaBus.java b/src/main/java/org/violetmoon/zeta/event/bus/wip/ZetaBus.java deleted file mode 100644 index 2c6a064..0000000 --- a/src/main/java/org/violetmoon/zeta/event/bus/wip/ZetaBus.java +++ /dev/null @@ -1,125 +0,0 @@ -package org.violetmoon.zeta.event.bus.wip; - -import com.google.common.base.Preconditions; -import org.apache.logging.log4j.Logger; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.violetmoon.zeta.Zeta; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.Arrays; -import java.util.stream.Stream; - -public abstract class ZetaBus { - - protected final Class subscriberAnnotation; - protected final Class eventRoot; - protected final Zeta z; - protected final @Nullable Logger logSpam; - - /** - * @param subscriberAnnotation The annotation that subscribe()/unsubscribe() will pay attention to. - * @param eventRoot The superinterface of all events fired on this bus. - */ - public ZetaBus(Zeta z, Class subscriberAnnotation, Class eventRoot, @Nullable Logger logSpam) { - Preconditions.checkArgument(eventRoot.isInterface(), "Event roots should be an interface"); - - this.z = z; - this.subscriberAnnotation = subscriberAnnotation; - this.eventRoot = eventRoot; - this.logSpam = logSpam; - } - - /** - * If the parameter is a Class: subscribes all static methods from it (and its superclasses) to the event bus. - * Otherwise, subscribes all non-static methods on that object (and its superclasses) to the event bus. - * (Note that the event bus will hold a reference to this object.) - */ - public ZetaBus subscribe(@NotNull Object target) { - Preconditions.checkNotNull(target, "null passed to subscribe"); - - Object receiver; - Class owningClazz; - if (target instanceof Class clazz) { - receiver = null; - owningClazz = clazz; - } else { - receiver = target; - owningClazz = target.getClass(); - } - - streamAnnotatedMethods(owningClazz, receiver == null) - .forEach(m -> addListener(m, receiver, owningClazz)); - return this; - } - - protected abstract void addListener(Method m, Object receiver, Class owningClazz); - - /** - * If the parameter is a Class: unsubscribes all static methods from it (and its superclasses) from the event bus. - * Otherwise, unsubscribes all non-static methods on that object (and its superclasses) from the event bus. - */ - public ZetaBus unsubscribe(@NotNull Object target) { - Preconditions.checkNotNull(target, "null passed to unsubscribe"); - - Object receiver; - Class owningClazz; - if (target instanceof Class clazz) { - receiver = null; - owningClazz = clazz; - } else { - receiver = target; - owningClazz = target.getClass(); - } - - streamAnnotatedMethods(owningClazz, receiver == null) - .forEach(m -> unregisterMethod(m, receiver, owningClazz)); - return this; - } - - protected abstract void unregisterMethod(Method m, Object receiver, Class owningClazz); - - /** - * Fires an event on the event bus. Each subscriber will be visited in order. - */ - public abstract T fire(@NotNull T event); - - /** - * Fires an event on the event bus. Each subscriber will be visited in order. - * Listeners for "firedAs" will be invoked, instead of listeners for the event's own class. - *

- * (The generic should be Class<? super T & ? extends E>, but unfortunately, javac.) - */ - public abstract T fire(@NotNull T event, Class firedAs); - - /** - * Grabs methods from this class (and its superclasses, recursively) that are annotated with this bus's - * annotation; and of the requested staticness. - */ - private Stream streamAnnotatedMethods(Class owningClazz, boolean wantStatic) { - return Arrays.stream(owningClazz.getMethods()) - .filter(m -> m.isAnnotationPresent(subscriberAnnotation) && ((m.getModifiers() & Modifier.STATIC) != 0) == wantStatic); - } - - protected RuntimeException arityERR(Method method) { - return methodProblem("Method annotated with @" + subscriberAnnotation.getSimpleName() + - " should take 1 parameter.", method, null); - } - - protected RuntimeException typeERR(Method method) { - return methodProblem("Method annotated with @" + subscriberAnnotation.getSimpleName() + - " should take an implementor of " + eventRoot.getSimpleName() + ".", method, null); - } - - protected RuntimeException unreflectERR(Method method, Throwable cause) { - return methodProblem("Exception unreflecting a @" + subscriberAnnotation.getSimpleName() + - " method, is it public?", method, cause); - } - - protected static RuntimeException methodProblem(String problem, Method method, @Nullable Throwable cause) { - return new RuntimeException("%s%nMethod class: %s%nMethod name: %s".formatted( - problem, method.getDeclaringClass().getName(), method.getName()), cause); - } -} diff --git a/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java b/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java index f11f24e..f0193c2 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java +++ b/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java @@ -1,5 +1,34 @@ package org.violetmoon.zetaimplforge; +import net.minecraft.core.BlockPos; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.FlowerPotBlock; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraftforge.common.ForgeConfigSpec; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.event.*; +import net.minecraftforge.event.entity.*; +import net.minecraftforge.event.entity.living.*; +import net.minecraftforge.event.entity.player.*; +import net.minecraftforge.event.furnace.FurnaceFuelBurnTimeEvent; +import net.minecraftforge.event.level.BlockEvent; +import net.minecraftforge.event.level.NoteBlockEvent; +import net.minecraftforge.event.village.VillagerTradesEvent; +import net.minecraftforge.event.village.WandererTradesEvent; +import net.minecraftforge.eventbus.api.Event; +import net.minecraftforge.eventbus.api.EventPriority; +import net.minecraftforge.eventbus.api.IEventBus; +import net.minecraftforge.fml.ModList; +import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; +import net.minecraftforge.fml.event.lifecycle.FMLLoadCompleteEvent; +import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; +import net.minecraftforge.fml.loading.FMLEnvironment; +import net.minecraftforge.registries.RegisterEvent; import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.Nullable; import org.violetmoon.zeta.Zeta; @@ -7,56 +36,19 @@ import org.violetmoon.zeta.capability.ZetaCapabilityManager; import org.violetmoon.zeta.config.IZetaConfigInternals; import org.violetmoon.zeta.config.SectionDefinition; -import org.violetmoon.zeta.event.bus.ZResult; -import org.violetmoon.zeta.event.load.ZAddReloadListener; -import org.violetmoon.zeta.event.load.ZCommonSetup; -import org.violetmoon.zeta.event.load.ZEntityAttributeCreation; -import org.violetmoon.zeta.event.load.ZGatherAdvancementModifiers; -import org.violetmoon.zeta.event.load.ZLoadComplete; -import org.violetmoon.zeta.event.load.ZRegister; -import org.violetmoon.zeta.event.load.ZTagsUpdated; -import org.violetmoon.zeta.event.play.ZAnvilRepair; -import org.violetmoon.zeta.event.play.ZAnvilUpdate; -import org.violetmoon.zeta.event.play.ZBlock; -import org.violetmoon.zeta.event.play.ZBonemeal; -import org.violetmoon.zeta.event.play.ZFurnaceFuelBurnTime; -import org.violetmoon.zeta.event.play.ZItemTooltip; -import org.violetmoon.zeta.event.play.ZLevelTick; -import org.violetmoon.zeta.event.play.ZPlayNoteBlock; -import org.violetmoon.zeta.event.play.ZServerTick; -import org.violetmoon.zeta.event.play.entity.ZEntityConstruct; -import org.violetmoon.zeta.event.play.entity.ZEntityInteract; -import org.violetmoon.zeta.event.play.entity.ZEntityItemPickup; -import org.violetmoon.zeta.event.play.entity.ZEntityJoinLevel; -import org.violetmoon.zeta.event.play.entity.ZEntityMobGriefing; -import org.violetmoon.zeta.event.play.entity.ZEntityTeleport; -import org.violetmoon.zeta.event.play.entity.living.ZAnimalTame; -import org.violetmoon.zeta.event.play.entity.living.ZBabyEntitySpawn; -import org.violetmoon.zeta.event.play.entity.living.ZLivingChangeTarget; -import org.violetmoon.zeta.event.play.entity.living.ZLivingConversion; -import org.violetmoon.zeta.event.play.entity.living.ZLivingDeath; -import org.violetmoon.zeta.event.play.entity.living.ZLivingDrops; -import org.violetmoon.zeta.event.play.entity.living.ZLivingFall; -import org.violetmoon.zeta.event.play.entity.living.ZLivingTick; -import org.violetmoon.zeta.event.play.entity.living.ZMobSpawnEvent; -import org.violetmoon.zeta.event.play.entity.living.ZSleepingLocationCheck; -import org.violetmoon.zeta.event.play.entity.player.ZPlayer; -import org.violetmoon.zeta.event.play.entity.player.ZPlayerDestroyItem; -import org.violetmoon.zeta.event.play.entity.player.ZPlayerInteract; -import org.violetmoon.zeta.event.play.entity.player.ZPlayerTick; -import org.violetmoon.zeta.event.play.entity.player.ZRightClickBlock; -import org.violetmoon.zeta.event.play.entity.player.ZRightClickItem; +import org.violetmoon.zeta.event.bus.*; +import org.violetmoon.zeta.event.load.*; +import org.violetmoon.zeta.event.play.*; +import org.violetmoon.zeta.event.play.entity.*; +import org.violetmoon.zeta.event.play.entity.living.*; +import org.violetmoon.zeta.event.play.entity.player.*; import org.violetmoon.zeta.event.play.loading.ZAttachCapabilities; import org.violetmoon.zeta.event.play.loading.ZLootTableLoad; import org.violetmoon.zeta.event.play.loading.ZVillagerTrades; import org.violetmoon.zeta.event.play.loading.ZWandererTrades; import org.violetmoon.zeta.item.ext.ItemExtensionFactory; import org.violetmoon.zeta.network.ZetaNetworkHandler; -import org.violetmoon.zeta.registry.BrewingRegistry; -import org.violetmoon.zeta.registry.CraftingExtensionsRegistry; -import org.violetmoon.zeta.registry.CreativeTabManager; -import org.violetmoon.zeta.registry.PottedPlantRegistry; -import org.violetmoon.zeta.registry.ZetaRegistry; +import org.violetmoon.zeta.registry.*; import org.violetmoon.zeta.util.RaytracingUtil; import org.violetmoon.zeta.util.ZetaSide; import org.violetmoon.zetaimplforge.api.GatherAdvancementModifiersEvent; @@ -69,37 +61,10 @@ import org.violetmoon.zetaimplforge.event.load.ForgeZCommonSetup; import org.violetmoon.zetaimplforge.event.load.ForgeZEntityAttributeCreation; import org.violetmoon.zetaimplforge.event.load.ForgeZLoadComplete; -import org.violetmoon.zetaimplforge.event.play.ForgeZAnvilRepair; -import org.violetmoon.zetaimplforge.event.play.ForgeZAnvilUpdate; -import org.violetmoon.zetaimplforge.event.play.ForgeZBlock; -import org.violetmoon.zetaimplforge.event.play.ForgeZBonemeal; -import org.violetmoon.zetaimplforge.event.play.ForgeZFurnaceFuelBurnTime; -import org.violetmoon.zetaimplforge.event.play.ForgeZItemTooltip; -import org.violetmoon.zetaimplforge.event.play.ForgeZLevelTick; -import org.violetmoon.zetaimplforge.event.play.ForgeZPlayNoteBlock; -import org.violetmoon.zetaimplforge.event.play.ForgeZServerTick; -import org.violetmoon.zetaimplforge.event.play.entity.ForgeZEntityConstruct; -import org.violetmoon.zetaimplforge.event.play.entity.ForgeZEntityInteract; -import org.violetmoon.zetaimplforge.event.play.entity.ForgeZEntityItemPickup; -import org.violetmoon.zetaimplforge.event.play.entity.ForgeZEntityJoinLevel; -import org.violetmoon.zetaimplforge.event.play.entity.ForgeZEntityMobGriefing; -import org.violetmoon.zetaimplforge.event.play.entity.ForgeZEntityTeleport; -import org.violetmoon.zetaimplforge.event.play.entity.living.ForgeZAnimalTame; -import org.violetmoon.zetaimplforge.event.play.entity.living.ForgeZBabyEntitySpawn; -import org.violetmoon.zetaimplforge.event.play.entity.living.ForgeZLivingChangeTarget; -import org.violetmoon.zetaimplforge.event.play.entity.living.ForgeZLivingConversion; -import org.violetmoon.zetaimplforge.event.play.entity.living.ForgeZLivingDeath; -import org.violetmoon.zetaimplforge.event.play.entity.living.ForgeZLivingDrops; -import org.violetmoon.zetaimplforge.event.play.entity.living.ForgeZLivingFall; -import org.violetmoon.zetaimplforge.event.play.entity.living.ForgeZLivingTick; -import org.violetmoon.zetaimplforge.event.play.entity.living.ForgeZMobSpawnEvent; -import org.violetmoon.zetaimplforge.event.play.entity.living.ForgeZSleepingLocationCheck; -import org.violetmoon.zetaimplforge.event.play.entity.player.ForgeZPlayer; -import org.violetmoon.zetaimplforge.event.play.entity.player.ForgeZPlayerDestroyItem; -import org.violetmoon.zetaimplforge.event.play.entity.player.ForgeZPlayerInteract; -import org.violetmoon.zetaimplforge.event.play.entity.player.ForgeZPlayerTick; -import org.violetmoon.zetaimplforge.event.play.entity.player.ForgeZRightClickBlock; -import org.violetmoon.zetaimplforge.event.play.entity.player.ForgeZRightClickItem; +import org.violetmoon.zetaimplforge.event.play.*; +import org.violetmoon.zetaimplforge.event.play.entity.*; +import org.violetmoon.zetaimplforge.event.play.entity.living.*; +import org.violetmoon.zetaimplforge.event.play.entity.player.*; import org.violetmoon.zetaimplforge.event.play.loading.ForgeZAttachCapabilities; import org.violetmoon.zetaimplforge.event.play.loading.ForgeZLootTableLoad; import org.violetmoon.zetaimplforge.event.play.loading.ForgeZVillagerTrades; @@ -111,523 +76,476 @@ import org.violetmoon.zetaimplforge.registry.ForgeZetaRegistry; import org.violetmoon.zetaimplforge.util.ForgeRaytracingUtil; -import net.minecraft.core.BlockPos; -import net.minecraft.world.InteractionHand; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.FlowerPotBlock; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.phys.BlockHitResult; -import net.minecraftforge.common.ForgeConfigSpec; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.event.AddReloadListenerEvent; -import net.minecraftforge.event.AnvilUpdateEvent; -import net.minecraftforge.event.AttachCapabilitiesEvent; -import net.minecraftforge.event.LootTableLoadEvent; -import net.minecraftforge.event.TagsUpdatedEvent; -import net.minecraftforge.event.TickEvent; -import net.minecraftforge.event.entity.EntityAttributeCreationEvent; -import net.minecraftforge.event.entity.EntityEvent; -import net.minecraftforge.event.entity.EntityJoinLevelEvent; -import net.minecraftforge.event.entity.EntityMobGriefingEvent; -import net.minecraftforge.event.entity.EntityTeleportEvent; -import net.minecraftforge.event.entity.living.AnimalTameEvent; -import net.minecraftforge.event.entity.living.BabyEntitySpawnEvent; -import net.minecraftforge.event.entity.living.LivingChangeTargetEvent; -import net.minecraftforge.event.entity.living.LivingConversionEvent; -import net.minecraftforge.event.entity.living.LivingDeathEvent; -import net.minecraftforge.event.entity.living.LivingDropsEvent; -import net.minecraftforge.event.entity.living.LivingEvent; -import net.minecraftforge.event.entity.living.LivingFallEvent; -import net.minecraftforge.event.entity.living.MobSpawnEvent; -import net.minecraftforge.event.entity.player.AnvilRepairEvent; -import net.minecraftforge.event.entity.player.BonemealEvent; -import net.minecraftforge.event.entity.player.EntityItemPickupEvent; -import net.minecraftforge.event.entity.player.ItemTooltipEvent; -import net.minecraftforge.event.entity.player.PlayerDestroyItemEvent; -import net.minecraftforge.event.entity.player.PlayerEvent; -import net.minecraftforge.event.entity.player.PlayerInteractEvent; -import net.minecraftforge.event.entity.player.SleepingLocationCheckEvent; -import net.minecraftforge.event.furnace.FurnaceFuelBurnTimeEvent; -import net.minecraftforge.event.level.BlockEvent; -import net.minecraftforge.event.level.NoteBlockEvent; -import net.minecraftforge.event.village.VillagerTradesEvent; -import net.minecraftforge.event.village.WandererTradesEvent; -import net.minecraftforge.eventbus.api.Event; -import net.minecraftforge.eventbus.api.EventPriority; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.fml.ModList; -import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; -import net.minecraftforge.fml.event.lifecycle.FMLLoadCompleteEvent; -import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; -import net.minecraftforge.fml.loading.FMLEnvironment; -import net.minecraftforge.registries.RegisterEvent; - /** * ideally do not touch quark from this package, it will later be split off */ public class ForgeZeta extends Zeta { - public ForgeZeta(String modid, Logger log) { - super(modid, log, ZetaSide.fromClient(FMLEnvironment.dist.isClient())); - } - - @Override - public boolean isModLoaded(String modid) { - return ModList.get().isLoaded(modid); - } - - @Override - public @Nullable String getModDisplayName(String modid) { - return ModList.get().getModContainerById(modid) - .map(c -> c.getModInfo().getDisplayName()) - .orElse(null); - } - - @Override - public IZetaConfigInternals makeConfigInternals(SectionDefinition rootSection) { - ForgeConfigSpec.Builder bob = new ForgeConfigSpec.Builder(); - ForgeBackedConfig forge = new ForgeBackedConfig(rootSection, bob); - ForgeConfigSpec spec = bob.build(); - - TerribleForgeConfigHackery.registerAndLoadConfigEarlierThanUsual(spec); - - return forge; - } - - @Override - public ZetaRegistry createRegistry() { - return new ForgeZetaRegistry(this); - } - - @Override - public CraftingExtensionsRegistry createCraftingExtensionsRegistry() { - return new ForgeCraftingExtensionsRegistry(); - } - - @Override - public BrewingRegistry createBrewingRegistry() { - return new ForgeBrewingRegistry(this); - } - - @Override - public PottedPlantRegistry createPottedPlantRegistry() { - return (resloc, potted) -> ((FlowerPotBlock)Blocks.FLOWER_POT).addPlant(resloc, () -> potted); - } - - @Override - public ZetaCapabilityManager createCapabilityManager() { - return new ForgeCapabilityManager(); - } - - @Override - public BlockExtensionFactory createBlockExtensionFactory() { - return block -> IForgeBlockBlockExtensions.INSTANCE; - } - - @Override - public ItemExtensionFactory createItemExtensionFactory() { - return stack -> IForgeItemItemExtensions.INSTANCE; - } - - @Override - public RaytracingUtil createRaytracingUtil() { - return new ForgeRaytracingUtil(); - } - - @Override - public ZetaNetworkHandler createNetworkHandler(int protocolVersion) { - return new ForgeZetaNetworkHandler(this, protocolVersion); - } - - @Override - public boolean fireRightClickBlock(Player player, InteractionHand hand, BlockPos pos, BlockHitResult bhr) { - return MinecraftForge.EVENT_BUS.post(new PlayerInteractEvent.RightClickBlock(player, hand, pos, bhr)); - } - - @Override - public T fireExternalEvent(T impl) { - if(impl instanceof ZGatherAdvancementModifiers advancementModifiers) - MinecraftForge.EVENT_BUS.post(new GatherAdvancementModifiersEvent(this, advancementModifiers)); - - return impl; - } - - @SuppressWarnings("duplicates") - @Override - public void start() { - //TODO: sort these somehow lol - - //load - IEventBus modbus = FMLJavaModLoadingContext.get().getModEventBus(); - modbus.addListener(EventPriority.HIGHEST, this::registerHighest); - modbus.addListener(this::commonSetup); - modbus.addListener(this::loadComplete); - modbus.addListener(this::entityAttributeCreation); - MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); - MinecraftForge.EVENT_BUS.addListener(this::tagsUpdated); - - // TODO FIX very ugly & bad - modbus.addListener(EventPriority.LOWEST, CreativeTabManager::buildContents); - modbus.addListener(ConfigEventDispatcher::configChanged); - - //play - MinecraftForge.EVENT_BUS.addListener(this::rightClickBlock); - MinecraftForge.EVENT_BUS.addListener(EventPriority.LOW, this::rightClickBlockLow); - MinecraftForge.EVENT_BUS.addListener(this::rightClickItem); - MinecraftForge.EVENT_BUS.addListener(this::livingDeath); - MinecraftForge.EVENT_BUS.addListener(EventPriority.LOWEST, this::livingDeathLowest); - MinecraftForge.EVENT_BUS.addListener(this::livingTick); - MinecraftForge.EVENT_BUS.addListener(this::playNoteBlock); - MinecraftForge.EVENT_BUS.addListener(this::lootTableLoad); - MinecraftForge.EVENT_BUS.addListener(this::livingConversion); - MinecraftForge.EVENT_BUS.addListener(this::livingConversionPre); - MinecraftForge.EVENT_BUS.addListener(this::livingConversionPost); - MinecraftForge.EVENT_BUS.addListener(this::anvilUpdate); - MinecraftForge.EVENT_BUS.addListener(EventPriority.LOWEST, this::anvilUpdateLowest); - MinecraftForge.EVENT_BUS.addListener(EventPriority.HIGHEST, this::anvilUpdateHighest); - MinecraftForge.EVENT_BUS.addListener(this::entityConstruct); - MinecraftForge.EVENT_BUS.addListener(this::entityInteract); - MinecraftForge.EVENT_BUS.addListener(this::entityMobGriefing); - MinecraftForge.EVENT_BUS.addListener(this::livingDrops); - MinecraftForge.EVENT_BUS.addListener(this::livingDropsLowest); - MinecraftForge.EVENT_BUS.addListener(this::playerTickStart); - MinecraftForge.EVENT_BUS.addListener(this::playerTickEnd); - MinecraftForge.EVENT_BUS.addListener(this::babyEntitySpawn); - MinecraftForge.EVENT_BUS.addListener(this::babyEntitySpawnLowest); - MinecraftForge.EVENT_BUS.addListener(this::entityJoinLevel); - - MinecraftForge.EVENT_BUS.addGenericListener(ItemStack.class, this::itemStackCaps); - MinecraftForge.EVENT_BUS.addGenericListener(BlockEntity.class, this::blockEntityCaps); - MinecraftForge.EVENT_BUS.addGenericListener(Level.class, this::levelCaps); - - MinecraftForge.EVENT_BUS.addListener(this::serverTickStart); - MinecraftForge.EVENT_BUS.addListener(this::serverTickEnd); - MinecraftForge.EVENT_BUS.addListener(this::levelTickStart); - MinecraftForge.EVENT_BUS.addListener(this::levelTickEnd); - MinecraftForge.EVENT_BUS.addListener(this::playerInteract); - MinecraftForge.EVENT_BUS.addListener(this::playerInteractEntityInteractSpecific); - MinecraftForge.EVENT_BUS.addListener(this::playerInteractEntityInteract); - MinecraftForge.EVENT_BUS.addListener(this::playerInteractRightClickBlock); - MinecraftForge.EVENT_BUS.addListener(this::playerInteractRightClickItem); - MinecraftForge.EVENT_BUS.addListener(this::playerDestroyItem); - MinecraftForge.EVENT_BUS.addListener(this::mobSpawn); - MinecraftForge.EVENT_BUS.addListener(this::mobSpawnFinalizeSpawn); - MinecraftForge.EVENT_BUS.addListener(this::mobSpawnFinalizeSpawnLowest); - MinecraftForge.EVENT_BUS.addListener(this::livingChangeTarget); - MinecraftForge.EVENT_BUS.addListener(this::sleepingLocationCheck); - MinecraftForge.EVENT_BUS.addListener(this::villagerTrades); - MinecraftForge.EVENT_BUS.addListener(this::anvilRepair); - MinecraftForge.EVENT_BUS.addListener(this::player); - MinecraftForge.EVENT_BUS.addListener(this::playerBreakSpeed); - MinecraftForge.EVENT_BUS.addListener(this::playerClone); - MinecraftForge.EVENT_BUS.addListener(this::playerLoggedIn); - MinecraftForge.EVENT_BUS.addListener(this::playerLoggedOut); - MinecraftForge.EVENT_BUS.addListener(this::entityItemPickup); - MinecraftForge.EVENT_BUS.addListener(this::blockBreak); - MinecraftForge.EVENT_BUS.addListener(this::blockEntityPlace); - MinecraftForge.EVENT_BUS.addListener(this::blockToolModification); - MinecraftForge.EVENT_BUS.addListener(this::animalTame); - MinecraftForge.EVENT_BUS.addListener(this::bonemeal); - MinecraftForge.EVENT_BUS.addListener(this::entityTeleport); - MinecraftForge.EVENT_BUS.addListener(this::livingFall); - MinecraftForge.EVENT_BUS.addListener(this::wandererTrades); - MinecraftForge.EVENT_BUS.addListener(this::furnaceFuelBurnTime); - MinecraftForge.EVENT_BUS.addListener(this::itemTooltip); - } - - private boolean registerDone = false; - public void registerHighest(RegisterEvent e) { - if(registerDone) - return; - - registerDone = true; // do this *before* actually registering to prevent weird ??race conditions?? or something? - //idk whats going on, all i know is i started the game, got a log with 136 "duplicate criterion id" errors, and i don't want to see that again - - loadBus.fire(new ZRegister(this)); - loadBus.fire(new ZRegister.Post()); - } - - public void commonSetup(FMLCommonSetupEvent e) { - loadBus.fire(new ForgeZCommonSetup(e), ZCommonSetup.class); - } - - public void loadComplete(FMLLoadCompleteEvent e) { - loadBus.fire(new ForgeZLoadComplete(e), ZLoadComplete.class); - } - - public void entityAttributeCreation(EntityAttributeCreationEvent e) { - loadBus.fire(new ForgeZEntityAttributeCreation(e), ZEntityAttributeCreation.class); - } - - public void addReloadListener(AddReloadListenerEvent e) { - loadBus.fire(new ForgeZAddReloadListener(e), ZAddReloadListener.class); - } - - public void tagsUpdated(TagsUpdatedEvent e) { - loadBus.fire(new ZTagsUpdated()); - } - - public void rightClickBlock(PlayerInteractEvent.RightClickBlock e) { - playBus.fire(new ForgeZRightClickBlock(e), ZRightClickBlock.class); - } - - public void rightClickBlockLow(PlayerInteractEvent.RightClickBlock e) { - playBus.fire(new ForgeZRightClickBlock.Low(e), ZRightClickBlock.Low.class); - } - - public void rightClickItem(PlayerInteractEvent.RightClickItem e) { - playBus.fire(new ForgeZRightClickItem(e), ZRightClickItem.class); - } - - public void livingDeath(LivingDeathEvent e) { - playBus.fire(new ForgeZLivingDeath(e), ZLivingDeath.class); - } - - public void livingDeathLowest(LivingDeathEvent e) { - playBus.fire(new ForgeZLivingDeath.Lowest(e), ZLivingDeath.Lowest.class); - } - - public void livingTick(LivingEvent.LivingTickEvent e) { - playBus.fire(new ForgeZLivingTick(e), ZLivingTick.class); - } - - public void playNoteBlock(NoteBlockEvent.Play e) { - playBus.fire(new ForgeZPlayNoteBlock(e), ZPlayNoteBlock.class); - } - - public void lootTableLoad(LootTableLoadEvent e) { - playBus.fire(new ForgeZLootTableLoad(e), ZLootTableLoad.class); - } - - public void livingConversion(LivingConversionEvent e) { - playBus.fire(new ForgeZLivingConversion(e), ZLivingConversion.class); - } - - public void livingConversionPre(LivingConversionEvent.Pre e) { - playBus.fire(new ForgeZLivingConversion.Pre(e), ZLivingConversion.Pre.class); - } - - public void livingConversionPost(LivingConversionEvent.Post e) { - playBus.fire(new ForgeZLivingConversion.Post(e), ZLivingConversion.Post.class); - } - - public void anvilUpdate(AnvilUpdateEvent e) { - playBus.fire(new ForgeZAnvilUpdate(e), ZAnvilUpdate.class); - } - - public void anvilUpdateLowest(AnvilUpdateEvent e) { - playBus.fire(new ForgeZAnvilUpdate.Lowest(e), ZAnvilUpdate.Lowest.class); - } - - public void anvilUpdateHighest(AnvilUpdateEvent e) { - playBus.fire(new ForgeZAnvilUpdate.Highest(e), ZAnvilUpdate.Highest.class); - } - - public void entityConstruct(EntityEvent.EntityConstructing e) { - playBus.fire(new ForgeZEntityConstruct(e), ZEntityConstruct.class); - } - - public void entityInteract(PlayerInteractEvent.EntityInteract e) { - playBus.fire(new ForgeZEntityInteract(e), ZEntityInteract.class); - } - - public void entityMobGriefing(EntityMobGriefingEvent e) { - playBus.fire(new ForgeZEntityMobGriefing(e), ZEntityMobGriefing.class); - } - - public void livingDrops(LivingDropsEvent e) { - playBus.fire(new ForgeZLivingDrops(e), ZLivingDrops.class); - } - - public void livingDropsLowest(LivingDropsEvent e) { - playBus.fire(new ForgeZLivingDrops.Lowest(e), ZLivingDrops.Lowest.class); - } - - public void playerTickStart(TickEvent.PlayerTickEvent e) { - if (e.phase == TickEvent.Phase.START) - playBus.fire(new ForgeZPlayerTick.Start(e), ZPlayerTick.Start.class); - } - - public void playerTickEnd(TickEvent.PlayerTickEvent e) { - if (e.phase == TickEvent.Phase.END) - playBus.fire(new ForgeZPlayerTick.End(e), ZPlayerTick.End.class); - } - - public void babyEntitySpawn(BabyEntitySpawnEvent e) { - playBus.fire(new ForgeZBabyEntitySpawn(e), ZBabyEntitySpawn.class); - } - - public void babyEntitySpawnLowest(BabyEntitySpawnEvent e) { - playBus.fire(new ForgeZBabyEntitySpawn.Lowest(e), ZBabyEntitySpawn.Lowest.class); - } - - public void entityJoinLevel(EntityJoinLevelEvent e) { - playBus.fire(new ForgeZEntityJoinLevel(e), ZEntityJoinLevel.class); - } - - public void itemStackCaps(AttachCapabilitiesEvent e) { - playBus.fire(new ForgeZAttachCapabilities.ItemStackCaps(capabilityManager, e), ZAttachCapabilities.ItemStackCaps.class); - } - - public void blockEntityCaps(AttachCapabilitiesEvent e) { - playBus.fire(new ForgeZAttachCapabilities.BlockEntityCaps(capabilityManager, e), ZAttachCapabilities.BlockEntityCaps.class); - } - - public void levelCaps(AttachCapabilitiesEvent e) { - playBus.fire(new ForgeZAttachCapabilities.LevelCaps(capabilityManager, e), ZAttachCapabilities.LevelCaps.class); - } - - public void serverTickStart(TickEvent.ServerTickEvent e) { - if (e.phase == TickEvent.Phase.START) - playBus.fire(new ForgeZServerTick.Start(e), ZServerTick.Start.class); - } - - public void serverTickEnd(TickEvent.ServerTickEvent e) { - if (e.phase == TickEvent.Phase.END) - playBus.fire(new ForgeZServerTick.End(e), ZServerTick.End.class); - } - - public void levelTickStart(TickEvent.LevelTickEvent e) { - if (e.phase == TickEvent.Phase.START) - playBus.fire(new ForgeZLevelTick.Start(e), ZLevelTick.Start.class); - } - - public void levelTickEnd(TickEvent.LevelTickEvent e) { - if (e.phase == TickEvent.Phase.END) - playBus.fire(new ForgeZLevelTick.End(e), ZLevelTick.End.class); - } - - public void playerInteract(PlayerInteractEvent e) { - playBus.fire(new ForgeZPlayerInteract(e), ZPlayerInteract.class); - } - - public void playerInteractEntityInteractSpecific(PlayerInteractEvent.EntityInteractSpecific e) { - playBus.fire(new ForgeZPlayerInteract.EntityInteractSpecific(e), ZPlayerInteract.EntityInteractSpecific.class); - } - - public void playerInteractEntityInteract(PlayerInteractEvent.EntityInteract e) { - playBus.fire(new ForgeZPlayerInteract.EntityInteract(e), ZPlayerInteract.EntityInteract.class); - } - - public void playerInteractRightClickBlock(PlayerInteractEvent.RightClickBlock e) { - playBus.fire(new ForgeZPlayerInteract.RightClickBlock(e), ZPlayerInteract.RightClickBlock.class); - } - - public void playerInteractRightClickItem(PlayerInteractEvent.RightClickItem e) { - playBus.fire(new ForgeZPlayerInteract.RightClickItem(e), ZPlayerInteract.RightClickItem.class); - } - - public void playerDestroyItem(PlayerDestroyItemEvent e) { - playBus.fire(new ForgeZPlayerDestroyItem(e), ZPlayerDestroyItem.class); - } - - public void mobSpawn(MobSpawnEvent e) { - playBus.fire(new ForgeZMobSpawnEvent(e), ZMobSpawnEvent.class); - } - - public void mobSpawnFinalizeSpawn(MobSpawnEvent.FinalizeSpawn e) { - playBus.fire(new ForgeZMobSpawnEvent.FinalizeSpawn(e), ZMobSpawnEvent.CheckSpawn.class); - } - - public void mobSpawnFinalizeSpawnLowest(MobSpawnEvent.FinalizeSpawn e) { - playBus.fire(new ForgeZMobSpawnEvent.FinalizeSpawn.Lowest(e), ZMobSpawnEvent.CheckSpawn.Lowest.class); - } - - public void livingChangeTarget(LivingChangeTargetEvent e) { - playBus.fire(new ForgeZLivingChangeTarget(e), ZLivingChangeTarget.class); - } - - public void sleepingLocationCheck(SleepingLocationCheckEvent e) { - playBus.fire(new ForgeZSleepingLocationCheck(e), ZSleepingLocationCheck.class); - } - - public void entityItemPickup(EntityItemPickupEvent e) { - playBus.fire(new ForgeZEntityItemPickup(e), ZEntityItemPickup.class); - } - - public void blockBreak(BlockEvent.BreakEvent e) { - playBus.fire(new ForgeZBlock.Break(e), ZBlock.Break.class); - } - - public void blockEntityPlace(BlockEvent.EntityPlaceEvent e) { - playBus.fire(new ForgeZBlock.EntityPlace(e), ZBlock.EntityPlace.class); - } - - public void blockToolModification(BlockEvent.BlockToolModificationEvent e) { - playBus.fire(new ForgeZBlock.BlockToolModification(e), ZBlock.BlockToolModification.class); - } - - public void animalTame(AnimalTameEvent e) { - playBus.fire(new ForgeZAnimalTame(e), ZAnimalTame.class); - } - - public void villagerTrades(VillagerTradesEvent e) { - playBus.fire(new ForgeZVillagerTrades(e), ZVillagerTrades.class); - } - - public void anvilRepair(AnvilRepairEvent e) { - playBus.fire(new ForgeZAnvilRepair(e), ZAnvilRepair.class); - } - - public void player(PlayerEvent e) { - playBus.fire(new ForgeZPlayer(e), ZPlayer.class); - } - - public void playerBreakSpeed(PlayerEvent.BreakSpeed e) { - playBus.fire(new ForgeZPlayer.BreakSpeed(e), ZPlayer.BreakSpeed.class); - } - - public void playerClone(PlayerEvent.Clone e) { - playBus.fire(new ForgeZPlayer.Clone(e), ZPlayer.Clone.class); - } - - public void playerLoggedIn(PlayerEvent.PlayerLoggedInEvent e) { - playBus.fire(new ForgeZPlayer.LoggedIn(e), ZPlayer.LoggedIn.class); - } - - public void playerLoggedOut(PlayerEvent.PlayerLoggedOutEvent e) { - playBus.fire(new ForgeZPlayer.LoggedOut(e), ZPlayer.LoggedOut.class); - } - - public void bonemeal(BonemealEvent e) { - playBus.fire(new ForgeZBonemeal(e), ZBonemeal.class); - } - - public void entityTeleport(EntityTeleportEvent e) { - playBus.fire(new ForgeZEntityTeleport(e), ZEntityTeleport.class); - } - - public void livingFall(LivingFallEvent e) { - playBus.fire(new ForgeZLivingFall(e), ZLivingFall.class); - } - - public void wandererTrades(WandererTradesEvent e) { - playBus.fire(new ForgeZWandererTrades(e), ZWandererTrades.class); - } - - public void furnaceFuelBurnTime(FurnaceFuelBurnTimeEvent e) { - playBus.fire(new ForgeZFurnaceFuelBurnTime(e), ZFurnaceFuelBurnTime.class); - } - - public void itemTooltip(ItemTooltipEvent e) { - playBus.fire(new ForgeZItemTooltip(e), ZItemTooltip.class); - } - - public static ZResult from(Event.Result r) { - return switch(r) { - case DENY -> ZResult.DENY; - case DEFAULT -> ZResult.DEFAULT; - case ALLOW -> ZResult.ALLOW; - }; - } - - public static Event.Result to(ZResult r) { - return switch(r) { - case DENY -> Event.Result.DENY; - case DEFAULT -> Event.Result.DEFAULT; - case ALLOW -> Event.Result.ALLOW; - }; - } + public ForgeZeta(String modid, Logger log) { + super(modid, log, ZetaSide.fromClient(FMLEnvironment.dist.isClient()), + new ForgeZetaEventBus<>(LoadEvent.class, IZetaLoadEvent.class, log, + FMLJavaModLoadingContext.get().getModEventBus()), + new ForgeZetaEventBus<>(PlayEvent.class, IZetaPlayEvent.class, null, + MinecraftForge.EVENT_BUS) + ); + + } + + @Override + public boolean isModLoaded(String modid) { + return ModList.get().isLoaded(modid); + } + + @Override + public @Nullable String getModDisplayName(String modid) { + return ModList.get().getModContainerById(modid) + .map(c -> c.getModInfo().getDisplayName()) + .orElse(null); + } + + @Override + public IZetaConfigInternals makeConfigInternals(SectionDefinition rootSection) { + ForgeConfigSpec.Builder bob = new ForgeConfigSpec.Builder(); + ForgeBackedConfig forge = new ForgeBackedConfig(rootSection, bob); + ForgeConfigSpec spec = bob.build(); + + TerribleForgeConfigHackery.registerAndLoadConfigEarlierThanUsual(spec); + + return forge; + } + + @Override + public ZetaRegistry createRegistry() { + return new ForgeZetaRegistry(this); + } + + @Override + public CraftingExtensionsRegistry createCraftingExtensionsRegistry() { + return new ForgeCraftingExtensionsRegistry(); + } + + @Override + public BrewingRegistry createBrewingRegistry() { + return new ForgeBrewingRegistry(this); + } + + @Override + public PottedPlantRegistry createPottedPlantRegistry() { + return (resloc, potted) -> ((FlowerPotBlock) Blocks.FLOWER_POT).addPlant(resloc, () -> potted); + } + + @Override + public ZetaCapabilityManager createCapabilityManager() { + return new ForgeCapabilityManager(); + } + + @Override + public BlockExtensionFactory createBlockExtensionFactory() { + return block -> IForgeBlockBlockExtensions.INSTANCE; + } + + @Override + public ItemExtensionFactory createItemExtensionFactory() { + return stack -> IForgeItemItemExtensions.INSTANCE; + } + + @Override + public RaytracingUtil createRaytracingUtil() { + return new ForgeRaytracingUtil(); + } + + @Override + public ZetaNetworkHandler createNetworkHandler(int protocolVersion) { + return new ForgeZetaNetworkHandler(this, protocolVersion); + } + + @Override + public boolean fireRightClickBlock(Player player, InteractionHand hand, BlockPos pos, BlockHitResult bhr) { + return MinecraftForge.EVENT_BUS.post(new PlayerInteractEvent.RightClickBlock(player, hand, pos, bhr)); + } + + @Override + public T fireExternalEvent(T impl) { + if (impl instanceof ZGatherAdvancementModifiers advancementModifiers) + MinecraftForge.EVENT_BUS.post(new GatherAdvancementModifiersEvent(this, advancementModifiers)); + + return impl; + } + + @SuppressWarnings("duplicates") + @Override + public void start() { + //TODO: sort these somehow lol + + //load + IEventBus modbus = FMLJavaModLoadingContext.get().getModEventBus(); + modbus.addListener(EventPriority.HIGHEST, this::registerHighest); + modbus.addListener(this::commonSetup); + modbus.addListener(this::loadComplete); + modbus.addListener(this::entityAttributeCreation); + MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); + MinecraftForge.EVENT_BUS.addListener(this::tagsUpdated); + + // TODO FIX very ugly & bad + modbus.addListener(EventPriority.LOWEST, CreativeTabManager::buildContents); + modbus.addListener(ConfigEventDispatcher::configChanged); + + //play + MinecraftForge.EVENT_BUS.addListener(this::rightClickBlock); + MinecraftForge.EVENT_BUS.addListener(EventPriority.LOW, this::rightClickBlockLow); + MinecraftForge.EVENT_BUS.addListener(this::rightClickItem); + MinecraftForge.EVENT_BUS.addListener(this::livingDeath); + MinecraftForge.EVENT_BUS.addListener(EventPriority.LOWEST, this::livingDeathLowest); + MinecraftForge.EVENT_BUS.addListener(this::livingTick); + MinecraftForge.EVENT_BUS.addListener(this::playNoteBlock); + MinecraftForge.EVENT_BUS.addListener(this::lootTableLoad); + MinecraftForge.EVENT_BUS.addListener(this::livingConversion); + MinecraftForge.EVENT_BUS.addListener(this::livingConversionPre); + MinecraftForge.EVENT_BUS.addListener(this::livingConversionPost); + MinecraftForge.EVENT_BUS.addListener(this::anvilUpdate); + MinecraftForge.EVENT_BUS.addListener(EventPriority.LOWEST, this::anvilUpdateLowest); + MinecraftForge.EVENT_BUS.addListener(EventPriority.HIGHEST, this::anvilUpdateHighest); + MinecraftForge.EVENT_BUS.addListener(this::entityConstruct); + MinecraftForge.EVENT_BUS.addListener(this::entityInteract); + MinecraftForge.EVENT_BUS.addListener(this::entityMobGriefing); + MinecraftForge.EVENT_BUS.addListener(this::livingDrops); + MinecraftForge.EVENT_BUS.addListener(this::livingDropsLowest); + MinecraftForge.EVENT_BUS.addListener(this::playerTickStart); + MinecraftForge.EVENT_BUS.addListener(this::playerTickEnd); + MinecraftForge.EVENT_BUS.addListener(this::babyEntitySpawn); + MinecraftForge.EVENT_BUS.addListener(this::babyEntitySpawnLowest); + MinecraftForge.EVENT_BUS.addListener(this::entityJoinLevel); + + MinecraftForge.EVENT_BUS.addGenericListener(ItemStack.class, this::itemStackCaps); + MinecraftForge.EVENT_BUS.addGenericListener(BlockEntity.class, this::blockEntityCaps); + MinecraftForge.EVENT_BUS.addGenericListener(Level.class, this::levelCaps); + + MinecraftForge.EVENT_BUS.addListener(this::serverTickStart); + MinecraftForge.EVENT_BUS.addListener(this::serverTickEnd); + MinecraftForge.EVENT_BUS.addListener(this::levelTickStart); + MinecraftForge.EVENT_BUS.addListener(this::levelTickEnd); + MinecraftForge.EVENT_BUS.addListener(this::playerInteract); + MinecraftForge.EVENT_BUS.addListener(this::playerInteractEntityInteractSpecific); + MinecraftForge.EVENT_BUS.addListener(this::playerInteractEntityInteract); + MinecraftForge.EVENT_BUS.addListener(this::playerInteractRightClickBlock); + MinecraftForge.EVENT_BUS.addListener(this::playerInteractRightClickItem); + MinecraftForge.EVENT_BUS.addListener(this::playerDestroyItem); + MinecraftForge.EVENT_BUS.addListener(this::mobSpawn); + MinecraftForge.EVENT_BUS.addListener(this::mobSpawnFinalizeSpawn); + MinecraftForge.EVENT_BUS.addListener(this::mobSpawnFinalizeSpawnLowest); + MinecraftForge.EVENT_BUS.addListener(this::livingChangeTarget); + MinecraftForge.EVENT_BUS.addListener(this::sleepingLocationCheck); + MinecraftForge.EVENT_BUS.addListener(this::villagerTrades); + MinecraftForge.EVENT_BUS.addListener(this::anvilRepair); + MinecraftForge.EVENT_BUS.addListener(this::player); + MinecraftForge.EVENT_BUS.addListener(this::playerBreakSpeed); + MinecraftForge.EVENT_BUS.addListener(this::playerClone); + MinecraftForge.EVENT_BUS.addListener(this::playerLoggedIn); + MinecraftForge.EVENT_BUS.addListener(this::playerLoggedOut); + MinecraftForge.EVENT_BUS.addListener(this::entityItemPickup); + MinecraftForge.EVENT_BUS.addListener(this::blockBreak); + MinecraftForge.EVENT_BUS.addListener(this::blockEntityPlace); + MinecraftForge.EVENT_BUS.addListener(this::blockToolModification); + MinecraftForge.EVENT_BUS.addListener(this::animalTame); + MinecraftForge.EVENT_BUS.addListener(this::bonemeal); + MinecraftForge.EVENT_BUS.addListener(this::entityTeleport); + MinecraftForge.EVENT_BUS.addListener(this::livingFall); + MinecraftForge.EVENT_BUS.addListener(this::wandererTrades); + MinecraftForge.EVENT_BUS.addListener(this::furnaceFuelBurnTime); + MinecraftForge.EVENT_BUS.addListener(this::itemTooltip); + } + + private boolean registerDone = false; + + public void registerHighest(RegisterEvent e) { + if (registerDone) + return; + + registerDone = true; // do this *before* actually registering to prevent weird ??race conditions?? or something? + //idk whats going on, all i know is i started the game, got a log with 136 "duplicate criterion id" errors, and i don't want to see that again + + loadBus.fire(new ZRegister(this)); + loadBus.fire(new ZRegister.Post()); + } + + public void commonSetup(FMLCommonSetupEvent e) { + loadBus.fire(new ForgeZCommonSetup(e), ZCommonSetup.class); + } + + public void loadComplete(FMLLoadCompleteEvent e) { + loadBus.fire(new ForgeZLoadComplete(e), ZLoadComplete.class); + } + + public void entityAttributeCreation(EntityAttributeCreationEvent e) { + loadBus.fire(new ForgeZEntityAttributeCreation(e), ZEntityAttributeCreation.class); + } + + public void addReloadListener(AddReloadListenerEvent e) { + loadBus.fire(new ForgeZAddReloadListener(e), ZAddReloadListener.class); + } + + public void tagsUpdated(TagsUpdatedEvent e) { + loadBus.fire(new ZTagsUpdated()); + } + + public void rightClickBlock(PlayerInteractEvent.RightClickBlock e) { + playBus.fire(new ForgeZRightClickBlock(e), ZRightClickBlock.class); + } + + public void rightClickBlockLow(PlayerInteractEvent.RightClickBlock e) { + playBus.fire(new ForgeZRightClickBlock.Low(e), ZRightClickBlock.Low.class); + } + + public void rightClickItem(PlayerInteractEvent.RightClickItem e) { + playBus.fire(new ForgeZRightClickItem(e), ZRightClickItem.class); + } + + public void livingDeath(LivingDeathEvent e) { + playBus.fire(new ForgeZLivingDeath(e), ZLivingDeath.class); + } + + public void livingDeathLowest(LivingDeathEvent e) { + playBus.fire(new ForgeZLivingDeath.Lowest(e), ZLivingDeath.Lowest.class); + } + + public void livingTick(LivingEvent.LivingTickEvent e) { + playBus.fire(new ForgeZLivingTick(e), ZLivingTick.class); + } + + public void playNoteBlock(NoteBlockEvent.Play e) { + playBus.fire(new ForgeZPlayNoteBlock(e), ZPlayNoteBlock.class); + } + + public void lootTableLoad(LootTableLoadEvent e) { + playBus.fire(new ForgeZLootTableLoad(e), ZLootTableLoad.class); + } + + public void livingConversion(LivingConversionEvent e) { + playBus.fire(new ForgeZLivingConversion(e), ZLivingConversion.class); + } + + public void livingConversionPre(LivingConversionEvent.Pre e) { + playBus.fire(new ForgeZLivingConversion.Pre(e), ZLivingConversion.Pre.class); + } + + public void livingConversionPost(LivingConversionEvent.Post e) { + playBus.fire(new ForgeZLivingConversion.Post(e), ZLivingConversion.Post.class); + } + + public void anvilUpdate(AnvilUpdateEvent e) { + playBus.fire(new ForgeZAnvilUpdate(e), ZAnvilUpdate.class); + } + + public void anvilUpdateLowest(AnvilUpdateEvent e) { + playBus.fire(new ForgeZAnvilUpdate.Lowest(e), ZAnvilUpdate.Lowest.class); + } + + public void anvilUpdateHighest(AnvilUpdateEvent e) { + playBus.fire(new ForgeZAnvilUpdate.Highest(e), ZAnvilUpdate.Highest.class); + } + + public void entityConstruct(EntityEvent.EntityConstructing e) { + playBus.fire(new ForgeZEntityConstruct(e), ZEntityConstruct.class); + } + + public void entityInteract(PlayerInteractEvent.EntityInteract e) { + playBus.fire(new ForgeZEntityInteract(e), ZEntityInteract.class); + } + + public void entityMobGriefing(EntityMobGriefingEvent e) { + playBus.fire(new ForgeZEntityMobGriefing(e), ZEntityMobGriefing.class); + } + + public void livingDrops(LivingDropsEvent e) { + playBus.fire(new ForgeZLivingDrops(e), ZLivingDrops.class); + } + + public void livingDropsLowest(LivingDropsEvent e) { + playBus.fire(new ForgeZLivingDrops.Lowest(e), ZLivingDrops.Lowest.class); + } + + public void playerTickStart(TickEvent.PlayerTickEvent e) { + if (e.phase == TickEvent.Phase.START) + playBus.fire(new ForgeZPlayerTick.Start(e), ZPlayerTick.Start.class); + } + + public void playerTickEnd(TickEvent.PlayerTickEvent e) { + if (e.phase == TickEvent.Phase.END) + playBus.fire(new ForgeZPlayerTick.End(e), ZPlayerTick.End.class); + } + + public void babyEntitySpawn(BabyEntitySpawnEvent e) { + playBus.fire(new ForgeZBabyEntitySpawn(e), ZBabyEntitySpawn.class); + } + + public void babyEntitySpawnLowest(BabyEntitySpawnEvent e) { + playBus.fire(new ForgeZBabyEntitySpawn.Lowest(e), ZBabyEntitySpawn.Lowest.class); + } + + public void entityJoinLevel(EntityJoinLevelEvent e) { + playBus.fire(new ForgeZEntityJoinLevel(e), ZEntityJoinLevel.class); + } + + public void itemStackCaps(AttachCapabilitiesEvent e) { + playBus.fire(new ForgeZAttachCapabilities.ItemStackCaps(capabilityManager, e), ZAttachCapabilities.ItemStackCaps.class); + } + + public void blockEntityCaps(AttachCapabilitiesEvent e) { + playBus.fire(new ForgeZAttachCapabilities.BlockEntityCaps(capabilityManager, e), ZAttachCapabilities.BlockEntityCaps.class); + } + + public void levelCaps(AttachCapabilitiesEvent e) { + playBus.fire(new ForgeZAttachCapabilities.LevelCaps(capabilityManager, e), ZAttachCapabilities.LevelCaps.class); + } + + public void serverTickStart(TickEvent.ServerTickEvent e) { + if (e.phase == TickEvent.Phase.START) + playBus.fire(new ForgeZServerTick.Start(e), ZServerTick.Start.class); + } + + public void serverTickEnd(TickEvent.ServerTickEvent e) { + if (e.phase == TickEvent.Phase.END) + playBus.fire(new ForgeZServerTick.End(e), ZServerTick.End.class); + } + + public void levelTickStart(TickEvent.LevelTickEvent e) { + if (e.phase == TickEvent.Phase.START) + playBus.fire(new ForgeZLevelTick.Start(e), ZLevelTick.Start.class); + } + + public void levelTickEnd(TickEvent.LevelTickEvent e) { + if (e.phase == TickEvent.Phase.END) + playBus.fire(new ForgeZLevelTick.End(e), ZLevelTick.End.class); + } + + public void playerInteract(PlayerInteractEvent e) { + playBus.fire(new ForgeZPlayerInteract(e), ZPlayerInteract.class); + } + + public void playerInteractEntityInteractSpecific(PlayerInteractEvent.EntityInteractSpecific e) { + playBus.fire(new ForgeZPlayerInteract.EntityInteractSpecific(e), ZPlayerInteract.EntityInteractSpecific.class); + } + + public void playerInteractEntityInteract(PlayerInteractEvent.EntityInteract e) { + playBus.fire(new ForgeZPlayerInteract.EntityInteract(e), ZPlayerInteract.EntityInteract.class); + } + + public void playerInteractRightClickBlock(PlayerInteractEvent.RightClickBlock e) { + playBus.fire(new ForgeZPlayerInteract.RightClickBlock(e), ZPlayerInteract.RightClickBlock.class); + } + + public void playerInteractRightClickItem(PlayerInteractEvent.RightClickItem e) { + playBus.fire(new ForgeZPlayerInteract.RightClickItem(e), ZPlayerInteract.RightClickItem.class); + } + + public void playerDestroyItem(PlayerDestroyItemEvent e) { + playBus.fire(new ForgeZPlayerDestroyItem(e), ZPlayerDestroyItem.class); + } + + public void mobSpawn(MobSpawnEvent e) { + playBus.fire(new ForgeZMobSpawnEvent(e), ZMobSpawnEvent.class); + } + + public void mobSpawnFinalizeSpawn(MobSpawnEvent.FinalizeSpawn e) { + playBus.fire(new ForgeZMobSpawnEvent.FinalizeSpawn(e), ZMobSpawnEvent.CheckSpawn.class); + } + + public void mobSpawnFinalizeSpawnLowest(MobSpawnEvent.FinalizeSpawn e) { + playBus.fire(new ForgeZMobSpawnEvent.FinalizeSpawn.Lowest(e), ZMobSpawnEvent.CheckSpawn.Lowest.class); + } + + public void livingChangeTarget(LivingChangeTargetEvent e) { + playBus.fire(new ForgeZLivingChangeTarget(e), ZLivingChangeTarget.class); + } + + public void sleepingLocationCheck(SleepingLocationCheckEvent e) { + playBus.fire(new ForgeZSleepingLocationCheck(e), ZSleepingLocationCheck.class); + } + + public void entityItemPickup(EntityItemPickupEvent e) { + playBus.fire(new ForgeZEntityItemPickup(e), ZEntityItemPickup.class); + } + + public void blockBreak(BlockEvent.BreakEvent e) { + playBus.fire(new ForgeZBlock.Break(e), ZBlock.Break.class); + } + + public void blockEntityPlace(BlockEvent.EntityPlaceEvent e) { + playBus.fire(new ForgeZBlock.EntityPlace(e), ZBlock.EntityPlace.class); + } + + public void blockToolModification(BlockEvent.BlockToolModificationEvent e) { + playBus.fire(new ForgeZBlock.BlockToolModification(e), ZBlock.BlockToolModification.class); + } + + public void animalTame(AnimalTameEvent e) { + playBus.fire(new ForgeZAnimalTame(e), ZAnimalTame.class); + } + + public void villagerTrades(VillagerTradesEvent e) { + playBus.fire(new ForgeZVillagerTrades(e), ZVillagerTrades.class); + } + + public void anvilRepair(AnvilRepairEvent e) { + playBus.fire(new ForgeZAnvilRepair(e), ZAnvilRepair.class); + } + + public void player(PlayerEvent e) { + playBus.fire(new ForgeZPlayer(e), ZPlayer.class); + } + + public void playerBreakSpeed(PlayerEvent.BreakSpeed e) { + playBus.fire(new ForgeZPlayer.BreakSpeed(e), ZPlayer.BreakSpeed.class); + } + + public void playerClone(PlayerEvent.Clone e) { + playBus.fire(new ForgeZPlayer.Clone(e), ZPlayer.Clone.class); + } + + public void playerLoggedIn(PlayerEvent.PlayerLoggedInEvent e) { + playBus.fire(new ForgeZPlayer.LoggedIn(e), ZPlayer.LoggedIn.class); + } + + public void playerLoggedOut(PlayerEvent.PlayerLoggedOutEvent e) { + playBus.fire(new ForgeZPlayer.LoggedOut(e), ZPlayer.LoggedOut.class); + } + + public void bonemeal(BonemealEvent e) { + playBus.fire(new ForgeZBonemeal(e), ZBonemeal.class); + } + + public void entityTeleport(EntityTeleportEvent e) { + playBus.fire(new ForgeZEntityTeleport(e), ZEntityTeleport.class); + } + + public void livingFall(LivingFallEvent e) { + playBus.fire(new ForgeZLivingFall(e), ZLivingFall.class); + } + + public void wandererTrades(WandererTradesEvent e) { + playBus.fire(new ForgeZWandererTrades(e), ZWandererTrades.class); + } + + public void furnaceFuelBurnTime(FurnaceFuelBurnTimeEvent e) { + playBus.fire(new ForgeZFurnaceFuelBurnTime(e), ZFurnaceFuelBurnTime.class); + } + + public void itemTooltip(ItemTooltipEvent e) { + playBus.fire(new ForgeZItemTooltip(e), ZItemTooltip.class); + } + + public static ZResult from(Event.Result r) { + return switch (r) { + case DENY -> ZResult.DENY; + case DEFAULT -> ZResult.DEFAULT; + case ALLOW -> ZResult.ALLOW; + }; + } + + public static Event.Result to(ZResult r) { + return switch (r) { + case DENY -> Event.Result.DENY; + case DEFAULT -> Event.Result.DEFAULT; + case ALLOW -> Event.Result.ALLOW; + }; + } } From f5eb9285c445ec8542473e2546b4c2eda39e46ae Mon Sep 17 00:00:00 2001 From: MehVahdJukaar Date: Tue, 30 Jul 2024 13:34:04 +0200 Subject: [PATCH 04/22] ugly stuff --- .../zeta/event/bus/FabricZetaEventBus.java | 4 +- .../zeta/event/bus/ForgeZetaEventBus.java | 64 +++++++++++-------- .../violetmoon/zetaimplforge/ForgeZeta.java | 56 ++++++++++++++++ 3 files changed, 96 insertions(+), 28 deletions(-) diff --git a/src/main/java/org/violetmoon/zeta/event/bus/FabricZetaEventBus.java b/src/main/java/org/violetmoon/zeta/event/bus/FabricZetaEventBus.java index 69dcf72..8f34886 100644 --- a/src/main/java/org/violetmoon/zeta/event/bus/FabricZetaEventBus.java +++ b/src/main/java/org/violetmoon/zeta/event/bus/FabricZetaEventBus.java @@ -36,12 +36,12 @@ public FabricZetaEventBus(Class subscriberAnnotation, Clas } @Override - protected void subscribeMethod(Method m, Object receiver, Class owningClazz) { + protected void subscribeMethod(Method m, Object receiver, Class owningClazz) { getListenersFor(m).subscribe(receiver, owningClazz, m); } @Override - protected void unsubscribeMethod(Method m, Object receiver, Class owningClazz) { + protected void unsubscribeMethod(Method m, Object receiver, Class owningClazz) { getListenersFor(m).unsubscribe(receiver, owningClazz, m); } diff --git a/src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java b/src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java index cccbf8c..4b72bec 100644 --- a/src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java +++ b/src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java @@ -5,7 +5,6 @@ import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.violetmoon.zeta.Zeta; import java.lang.annotation.Annotation; import java.lang.invoke.MethodHandle; @@ -37,6 +36,7 @@ public ForgeZetaEventBus(Class subscriberAnnotation, Class this.forgeBus = forgeBus; } + @Override protected void subscribeMethod(Method method, Object receiver, Class owningClazz) { if (method.getParameterCount() != 1) @@ -89,33 +89,43 @@ public T fire(@NotNull T event, Class firedAs) { // reflection hacks below. be warned private Event remapEvent(@NotNull T event, Class firedAs) { - Function zetaToForgeFunc = zetaToForgeMap.computeIfAbsent((Class) firedAs, this::findWrappedEvent); + Function zetaToForgeFunc = zetaToForgeMap.get((Class) firedAs); + if (zetaToForgeFunc == null) { + throw new RuntimeException("No wrapped forge Event found for Zeta event class. You must register its subclass using registerSubclass. " + firedAs); + } return createForgeEvent(event, zetaToForgeFunc); } // takes a method that takes a zeta event and turns into one that takes a forge event private Consumer remapMethod(MethodHandle zetaEventConsumer, Class zetaEventClass) { - Function forgeToZetaFunc = forgeToZetaMap.computeIfAbsent(zetaEventClass,this::findWrappingConstructor); + Function forgeToZetaFunc = forgeToZetaMap.get(zetaEventClass); + if (forgeToZetaFunc == null) { + throw new RuntimeException("No forge-Event-wrapping constructor found for Zeta event class. You must register its subclass using registerSubclass. " + zetaEventClass); + } return createForgeConsumer(zetaEventConsumer, forgeToZetaFunc); } + private Event createForgeEvent(@NotNull E event, Function function) { + return function.apply((T) event); + } - private Function findWrappedEvent(Class zetaEventClass) { - for (Field field : zetaEventClass.getDeclaredFields()) { - if (Event.class.isAssignableFrom(field.getType())) { - return instance -> { - try { - return (Event) field.get(instance); - } catch (IllegalAccessException illegalAccessException) { - throw new RuntimeException(illegalAccessException); - } - }; + private Consumer createForgeConsumer(MethodHandle zetaEventConsumer, Function forgeToZetaFunc) { + return event -> { + try { + zetaEventConsumer.invoke(forgeToZetaFunc.apply(event)); + } catch (Throwable e) { + throw new RuntimeException(e); } - } - throw new RuntimeException("No wrapped forge Event found for Zeta event class " + zetaEventClass); + }; } - private Function findWrappingConstructor(Class zetaEventClass) { + + public void registerSubClass(Class eventClass, Class zetaEventClass) { + forgeToZetaMap.put(eventClass, findWrappingConstructor(zetaEventClass)); + zetaToForgeMap.put(eventClass, findWrappedEvent(zetaEventClass)); + } + + private Function findWrappingConstructor(Class zetaEventClass) { // Find the constructor that takes a single parameter of type A for (Constructor constructor : zetaEventClass.getConstructors()) { Class[] parameterTypes = constructor.getParameterTypes(); @@ -132,18 +142,20 @@ private Function findWrappingConstructor(Class Event createForgeEvent(@NotNull E event, Function function) { - return function.apply((T) event); - } - private Consumer createForgeConsumer(MethodHandle zetaEventConsumer, Function forgeToZetaFunc) { - return event -> { - try { - zetaEventConsumer.invoke(forgeToZetaFunc.apply(event)); - } catch (Throwable e) { - throw new RuntimeException(e); + private Function findWrappedEvent(Class zetaEventClass) { + for (Field field : zetaEventClass.getDeclaredFields()) { + if (Event.class.isAssignableFrom(field.getType())) { + return instance -> { + try { + return (Event) field.get(instance); + } catch (IllegalAccessException illegalAccessException) { + throw new RuntimeException(illegalAccessException); + } + }; } - }; + } + throw new RuntimeException("No wrapped forge Event found for Zeta event class " + zetaEventClass); } } diff --git a/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java b/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java index f0193c2..868a85d 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java +++ b/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java @@ -88,6 +88,62 @@ public ForgeZeta(String modid, Logger log) { MinecraftForge.EVENT_BUS) ); + uglyPopulateForgePlayBus(); + uglyPopulateForgeLoadBus(); + } + + private void uglyPopulateForgeLoadBus(){ + var bus = (ForgeZetaEventBus) loadBus; + bus.registerSubClass(ZCommonSetup.class, ForgeZCommonSetup.class); + bus.registerSubClass(ZAddReloadListener.class, ForgeZAddReloadListener.class); + bus.registerSubClass(ZEntityAttributeCreation.class, ForgeZEntityAttributeCreation.class); + } + + private void uglyPopulateForgePlayBus() { + var bus = (ForgeZetaEventBus) playBus; + bus.registerSubClass(ZAnvilRepair.class, ForgeZAnvilRepair.class); + bus.registerSubClass(ZBabyEntitySpawn.class, ForgeZBabyEntitySpawn.class); + bus.registerSubClass(ZBlock.Break.class, ForgeZBlock.Break.class); + bus.registerSubClass(ZBlock.EntityPlace.class, ForgeZBlock.EntityPlace.class); + bus.registerSubClass(ZBlock.BlockToolModification.class, ForgeZBlock.BlockToolModification.class); + bus.registerSubClass(ZBonemeal.class, ForgeZBonemeal.class); + bus.registerSubClass(ZEntityConstruct.class, ForgeZEntityConstruct.class); + bus.registerSubClass(ZEntityInteract.class, ForgeZEntityInteract.class); + bus.registerSubClass(ZEntityItemPickup.class, ForgeZEntityItemPickup.class); + bus.registerSubClass(ZEntityJoinLevel.class, ForgeZEntityJoinLevel.class); + bus.registerSubClass(ZEntityMobGriefing.class, ForgeZEntityMobGriefing.class); + bus.registerSubClass(ZEntityTeleport.class, ForgeZEntityTeleport.class); + bus.registerSubClass(ZItemTooltip.class, ForgeZItemTooltip.class); + bus.registerSubClass(ZLivingChangeTarget.class, ForgeZLivingChangeTarget.class); + bus.registerSubClass(ZLivingConversion.class, ForgeZLivingConversion.class); + bus.registerSubClass(ZLivingConversion.Pre.class, ForgeZLivingConversion.Pre.class); + bus.registerSubClass(ZLivingConversion.Post.class, ForgeZLivingConversion.Post.class); + bus.registerSubClass(ZLivingDeath.class, ForgeZLivingDeath.class); + bus.registerSubClass(ZLivingDeath.Lowest.class, ForgeZLivingDeath.Lowest.class); + bus.registerSubClass(ZLivingDrops.class, ForgeZLivingDrops.class); + bus.registerSubClass(ZLivingDrops.Lowest.class, ForgeZLivingDrops.Lowest.class); + bus.registerSubClass(ZLivingFall.class, ForgeZLivingFall.class); + bus.registerSubClass(ZLivingTick.class, ForgeZLivingTick.class); + bus.registerSubClass(ZMobSpawnEvent.class, ForgeZMobSpawnEvent.class); + bus.registerSubClass(ZMobSpawnEvent.CheckSpawn.class, ForgeZMobSpawnEvent.FinalizeSpawn.class); + bus.registerSubClass(ZMobSpawnEvent.CheckSpawn.Lowest.class, ForgeZMobSpawnEvent.FinalizeSpawn.Lowest.class); + bus.registerSubClass(ZPlayNoteBlock.class, ForgeZPlayNoteBlock.class); + bus.registerSubClass(ZPlayer.class, ForgeZPlayer.class); + bus.registerSubClass(ZPlayer.BreakSpeed.class, ForgeZPlayer.BreakSpeed.class); + bus.registerSubClass(ZPlayer.Clone.class, ForgeZPlayer.Clone.class); + bus.registerSubClass(ZPlayerDestroyItem.class, ForgeZPlayerDestroyItem.class); + bus.registerSubClass(ZPlayer.LoggedIn.class, ForgeZPlayer.LoggedIn.class); + bus.registerSubClass(ZPlayer.LoggedOut.class, ForgeZPlayer.LoggedOut.class); + bus.registerSubClass(ZPlayerTick.Start.class, ForgeZPlayerTick.Start.class); + bus.registerSubClass(ZPlayerTick.End.class, ForgeZPlayerTick.End.class); + bus.registerSubClass(ZPlayerInteract.class, ForgeZPlayerInteract.class); + bus.registerSubClass(ZPlayerInteract.EntityInteractSpecific.class, ForgeZPlayerInteract.EntityInteractSpecific.class); + bus.registerSubClass(ZPlayerInteract.EntityInteract.class, ForgeZPlayerInteract.EntityInteract.class); + bus.registerSubClass(ZPlayerInteract.RightClickBlock.class, ForgeZPlayerInteract.RightClickBlock.class); + bus.registerSubClass(ZPlayerInteract.RightClickItem.class, ForgeZPlayerInteract.RightClickItem.class); + bus.registerSubClass(ZRightClickBlock.class, ForgeZRightClickBlock.class); + bus.registerSubClass(ZRightClickBlock.Low.class, ForgeZRightClickBlock.Low.class); + bus.registerSubClass(ZRightClickItem.class, ForgeZRightClickItem.class); } @Override From 79378dab918d8a6826b778b6e7563a42795fd725 Mon Sep 17 00:00:00 2001 From: MehVahdJukaar Date: Tue, 30 Jul 2024 13:55:57 +0200 Subject: [PATCH 05/22] fixe external stuff --- .../java/org/violetmoon/zeta/event/bus/ZetaEventBus.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/main/java/org/violetmoon/zeta/event/bus/ZetaEventBus.java b/src/main/java/org/violetmoon/zeta/event/bus/ZetaEventBus.java index 5dc991d..38c4066 100644 --- a/src/main/java/org/violetmoon/zeta/event/bus/ZetaEventBus.java +++ b/src/main/java/org/violetmoon/zeta/event/bus/ZetaEventBus.java @@ -122,4 +122,11 @@ protected static RuntimeException methodProblem(String problem, Method method, @ return new RuntimeException("%s%nMethod class: %s%nMethod name: %s".formatted( problem, method.getDeclaringClass().getName(), method.getName()), cause); } + + //TODO or remove entirely. Platform specific behavior should be in fire implementation on each platform bus + @Deprecated(forRemoval = true) + public T fireExternal(@NotNull T event, Class firedAs) { + + return event; + } } From cc4b30815b2aa6c0daf496e9f9e97499e4ba3b85 Mon Sep 17 00:00:00 2001 From: MehVahdJukaar Date: Tue, 30 Jul 2024 15:53:22 +0200 Subject: [PATCH 06/22] more forge bus work --- .../zeta/event/bus/ForgeZetaEventBus.java | 104 ++++- .../zeta/event/load/ZConfigChanged.java | 2 +- .../zeta/event/load/ZModulesReady.java | 2 +- .../violetmoon/zeta/event/load/ZRegister.java | 33 +- .../zeta/event/load/ZTagsUpdated.java | 9 +- .../violetmoon/zetaimplforge/ForgeZeta.java | 382 ++---------------- .../config/ConfigEventDispatcher.java | 4 +- .../event/load/ForgeZConfigChange.java | 9 + .../event/load/ForgeZModulesReady.java | 8 + .../event/load/ForgeZRegister.java | 46 +++ .../event/load/ForgeZTagsUpdated.java | 18 + .../event/play/ForgeZRecipeCrawl.java | 80 ++++ 12 files changed, 304 insertions(+), 393 deletions(-) create mode 100644 src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZConfigChange.java create mode 100644 src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZModulesReady.java create mode 100644 src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZRegister.java create mode 100644 src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZTagsUpdated.java create mode 100644 src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZRecipeCrawl.java diff --git a/src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java b/src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java index 4b72bec..2234a97 100644 --- a/src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java +++ b/src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java @@ -1,10 +1,18 @@ package org.violetmoon.zeta.event.bus; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraftforge.event.TickEvent; import net.minecraftforge.eventbus.api.Event; +import net.minecraftforge.eventbus.api.EventPriority; +import net.minecraftforge.eventbus.api.GenericEvent; import net.minecraftforge.eventbus.api.IEventBus; +import org.apache.commons.lang3.text.WordUtils; import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.violetmoon.zeta.event.play.loading.ZAttachCapabilities; import java.lang.annotation.Annotation; import java.lang.invoke.MethodHandle; @@ -43,7 +51,9 @@ protected void subscribeMethod(Method method, Object receiver, Class owningCl throw arityERR(method); Class eventType = method.getParameterTypes()[0]; - if (!eventRoot.isAssignableFrom(eventType)) + + //check if it's already a forge event or it's a zeta event + if (!eventRoot.isAssignableFrom(eventType) || !Event.class.isAssignableFrom(eventType)) throw typeERR(method); MethodHandle handle; @@ -57,12 +67,13 @@ protected void subscribeMethod(Method method, Object receiver, Class owningCl if (receiver != null) handle = handle.bindTo(receiver); - Consumer consumer = remapMethod(handle, (Class) eventType); - forgeBus.addListener(consumer); + Consumer consumer = remapMethod(handle, eventType); + registerListenerToForgeWithPriorityAndGenerics(owningClazz, consumer); //store here so we can unregister later convertedHandlers.put(new Key(method, receiver, owningClazz), consumer); } + @Override protected void unsubscribeMethod(Method m, Object receiver, Class owningClazz) { var handler = convertedHandlers.remove(new Key(m, receiver, owningClazz)); @@ -86,7 +97,9 @@ public T fire(@NotNull T event, Class firedAs) { return event; } - // reflection hacks below. be warned + // reflection hacks and ugly code below. Turn back now. You have been warned + + // good thing is most of this can be removed in 1.21 since Event is an interface there so we can pass zeta events directly. Just need to make zeta event extend Event private Event remapEvent(@NotNull T event, Class firedAs) { Function zetaToForgeFunc = zetaToForgeMap.get((Class) firedAs); @@ -97,21 +110,40 @@ private Event remapEvent(@NotNull T event, Class firedAs) { } // takes a method that takes a zeta event and turns into one that takes a forge event - private Consumer remapMethod(MethodHandle zetaEventConsumer, Class zetaEventClass) { + private Consumer remapMethod(MethodHandle originalEventConsumer, Class zetaEventClass) { + // if it's already a forge event, just call it + if (Event.class.isAssignableFrom(zetaEventClass)) { + return event -> { + try { + originalEventConsumer.invoke(event); + } catch (Throwable e) { + throw new RuntimeException(e); + } + }; + } + Function forgeToZetaFunc = forgeToZetaMap.get(zetaEventClass); if (forgeToZetaFunc == null) { throw new RuntimeException("No forge-Event-wrapping constructor found for Zeta event class. You must register its subclass using registerSubclass. " + zetaEventClass); } - return createForgeConsumer(zetaEventConsumer, forgeToZetaFunc); + return createForgeConsumer(originalEventConsumer, forgeToZetaFunc, zetaEventClass); } private Event createForgeEvent(@NotNull E event, Function function) { return function.apply((T) event); } - private Consumer createForgeConsumer(MethodHandle zetaEventConsumer, Function forgeToZetaFunc) { + private Consumer createForgeConsumer(MethodHandle zetaEventConsumer, Function forgeToZetaFunc, + Class zetaEventClass) { + //hack for tick events + Phase phase = Phase.guessFromClassName(zetaEventClass); return event -> { try { + //luckily this phase madness will go away with new neoforge + if (phase != Phase.NONE && event instanceof TickEvent te) { + if (phase == Phase.START && te.phase != TickEvent.Phase.START) return; + if (phase == Phase.END && te.phase != TickEvent.Phase.END) return; + } zetaEventConsumer.invoke(forgeToZetaFunc.apply(event)); } catch (Throwable e) { throw new RuntimeException(e); @@ -120,7 +152,7 @@ private Consumer createForgeConsumer(MethodHan } - public void registerSubClass(Class eventClass, Class zetaEventClass) { + public void registerSubClass(Class eventClass, Class zetaEventClass) { forgeToZetaMap.put(eventClass, findWrappingConstructor(zetaEventClass)); zetaToForgeMap.put(eventClass, findWrappedEvent(zetaEventClass)); } @@ -158,4 +190,60 @@ public void registerSubClass(Class eventClass, Cla throw new RuntimeException("No wrapped forge Event found for Zeta event class " + zetaEventClass); } + //bad string based conversions stuff mess + + //TODO: refactor in 1.21 using interfaces and stuff. This is just here for now as i want to keep binary compatibility + + private void registerListenerToForgeWithPriorityAndGenerics(Class owningClazz, Consumer consumer) { + EventPriority priority = guessPriorityFromClassName(owningClazz); + //harcoded caps bs. Alternatively a registerGenerics method could have been added to the bus. + Class generics = null; + if (owningClazz.isAssignableFrom(ZAttachCapabilities.BlockEntityCaps.class)) { + generics = BlockEntity.class; + } + if (owningClazz.isAssignableFrom(ZAttachCapabilities.ItemStackCaps.class)) { + generics = ItemStack.class; + } + if (owningClazz.isAssignableFrom(ZAttachCapabilities.LevelCaps.class)) { + generics = Level.class; + } + if (generics != null) { + forgeBus.addGenericListener(generics, priority, (Consumer) consumer); + } else { + forgeBus.addListener(priority, consumer); + } + } + + + private enum Phase { + NONE, START, END; + + private static Phase guessFromClassName(Class zetaEventClass) { + String simpleName = zetaEventClass.getSimpleName(); + if (simpleName.equals("Start")) { + return START; + } else if (simpleName.equals("End")) { + return END; + } else { + return NONE; + } + } + } + + + private static final Map, EventPriority> CACHE = new HashMap<>(); + + private static EventPriority guessPriorityFromClassName(Class zetaEventClass) { + return CACHE.computeIfAbsent(zetaEventClass, cl -> { + String simpleName = zetaEventClass.getSimpleName(); + for (EventPriority p : EventPriority.values()) { + String name = WordUtils.capitalizeFully(p.name().toLowerCase()); + if (simpleName.endsWith(name)) { + return p; + } + } + return EventPriority.NORMAL; + }); + } + } diff --git a/src/main/java/org/violetmoon/zeta/event/load/ZConfigChanged.java b/src/main/java/org/violetmoon/zeta/event/load/ZConfigChanged.java index 1e334e2..afa2e9d 100644 --- a/src/main/java/org/violetmoon/zeta/event/load/ZConfigChanged.java +++ b/src/main/java/org/violetmoon/zeta/event/load/ZConfigChanged.java @@ -2,4 +2,4 @@ import org.violetmoon.zeta.event.bus.IZetaLoadEvent; -public class ZConfigChanged implements IZetaLoadEvent { } +public interface ZConfigChanged extends IZetaLoadEvent { } diff --git a/src/main/java/org/violetmoon/zeta/event/load/ZModulesReady.java b/src/main/java/org/violetmoon/zeta/event/load/ZModulesReady.java index 25bb190..b6086fe 100644 --- a/src/main/java/org/violetmoon/zeta/event/load/ZModulesReady.java +++ b/src/main/java/org/violetmoon/zeta/event/load/ZModulesReady.java @@ -2,4 +2,4 @@ import org.violetmoon.zeta.event.bus.IZetaLoadEvent; -public class ZModulesReady implements IZetaLoadEvent { } +public interface ZModulesReady extends IZetaLoadEvent { } diff --git a/src/main/java/org/violetmoon/zeta/event/load/ZRegister.java b/src/main/java/org/violetmoon/zeta/event/load/ZRegister.java index b49697c..ba21fd6 100644 --- a/src/main/java/org/violetmoon/zeta/event/load/ZRegister.java +++ b/src/main/java/org/violetmoon/zeta/event/load/ZRegister.java @@ -10,36 +10,19 @@ import org.violetmoon.zeta.registry.ZetaRegistry; @SuppressWarnings("ClassCanBeRecord") -public class ZRegister implements IZetaLoadEvent { - public final Zeta zeta; +public interface ZRegister extends IZetaLoadEvent { - public ZRegister(Zeta zeta) { - this.zeta = zeta; - } + ZetaRegistry getRegistry(); - public ZetaRegistry getRegistry() { - return zeta.registry; - } + CraftingExtensionsRegistry getCraftingExtensionsRegistry(); - public CraftingExtensionsRegistry getCraftingExtensionsRegistry() { - return zeta.craftingExtensions; - } + BrewingRegistry getBrewingRegistry(); - public BrewingRegistry getBrewingRegistry() { - return zeta.brewingRegistry; - } + RenderLayerRegistry getRenderLayerRegistry(); - public RenderLayerRegistry getRenderLayerRegistry() { - return zeta.renderLayerRegistry; - } + AdvancementModifierRegistry getAdvancementModifierRegistry(); - public AdvancementModifierRegistry getAdvancementModifierRegistry() { - return zeta.advancementModifierRegistry; - } + VariantRegistry getVariantRegistry(); - public VariantRegistry getVariantRegistry() { - return zeta.variantRegistry; - } - - public static class Post implements IZetaLoadEvent { } + interface Post extends IZetaLoadEvent { } } diff --git a/src/main/java/org/violetmoon/zeta/event/load/ZTagsUpdated.java b/src/main/java/org/violetmoon/zeta/event/load/ZTagsUpdated.java index 8d8cfae..343c685 100644 --- a/src/main/java/org/violetmoon/zeta/event/load/ZTagsUpdated.java +++ b/src/main/java/org/violetmoon/zeta/event/load/ZTagsUpdated.java @@ -1,6 +1,13 @@ package org.violetmoon.zeta.event.load; +import net.minecraft.core.RegistryAccess; import org.violetmoon.zeta.event.bus.IZetaLoadEvent; //TODO: just used by RecipeCrawlHandler -public class ZTagsUpdated implements IZetaLoadEvent { } +public interface ZTagsUpdated extends IZetaLoadEvent { + + RegistryAccess getRegistryAccess(); + + boolean isOnClient(); + +} diff --git a/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java b/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java index 868a85d..ba79227 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java +++ b/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java @@ -57,10 +57,7 @@ import org.violetmoon.zetaimplforge.config.ConfigEventDispatcher; import org.violetmoon.zetaimplforge.config.ForgeBackedConfig; import org.violetmoon.zetaimplforge.config.TerribleForgeConfigHackery; -import org.violetmoon.zetaimplforge.event.load.ForgeZAddReloadListener; -import org.violetmoon.zetaimplforge.event.load.ForgeZCommonSetup; -import org.violetmoon.zetaimplforge.event.load.ForgeZEntityAttributeCreation; -import org.violetmoon.zetaimplforge.event.load.ForgeZLoadComplete; +import org.violetmoon.zetaimplforge.event.load.*; import org.violetmoon.zetaimplforge.event.play.*; import org.violetmoon.zetaimplforge.event.play.entity.*; import org.violetmoon.zetaimplforge.event.play.entity.living.*; @@ -92,11 +89,16 @@ public ForgeZeta(String modid, Logger log) { uglyPopulateForgeLoadBus(); } + // adds known events sub classes to the bus private void uglyPopulateForgeLoadBus(){ var bus = (ForgeZetaEventBus) loadBus; bus.registerSubClass(ZCommonSetup.class, ForgeZCommonSetup.class); bus.registerSubClass(ZAddReloadListener.class, ForgeZAddReloadListener.class); bus.registerSubClass(ZEntityAttributeCreation.class, ForgeZEntityAttributeCreation.class); + bus.registerSubClass(ZModulesReady.class, ForgeZModulesReady.class); + bus.registerSubClass(ZRegister.class, ForgeZRegister.class); + bus.registerSubClass(ZTagsUpdated.class, ForgeZTagsUpdated.class); + bus.registerSubClass(ZConfigChanged.class, ForgeZConfigChange.class); } private void uglyPopulateForgePlayBus() { @@ -144,6 +146,25 @@ private void uglyPopulateForgePlayBus() { bus.registerSubClass(ZRightClickBlock.class, ForgeZRightClickBlock.class); bus.registerSubClass(ZRightClickBlock.Low.class, ForgeZRightClickBlock.Low.class); bus.registerSubClass(ZRightClickItem.class, ForgeZRightClickItem.class); + bus.registerSubClass(ZLootTableLoad.class, ForgeZLootTableLoad.class); + bus.registerSubClass(ZVillagerTrades.class, ForgeZVillagerTrades.class); + bus.registerSubClass(ZWandererTrades.class, ForgeZWandererTrades.class); + + bus.registerSubClass(ZAttachCapabilities.BlockEntityCaps.class, ForgeZAttachCapabilities.BlockEntityCaps.class); + bus.registerSubClass(ZAttachCapabilities.ItemStackCaps.class, ForgeZAttachCapabilities.ItemStackCaps.class); + bus.registerSubClass(ZAttachCapabilities.LevelCaps.class, ForgeZAttachCapabilities.LevelCaps.class); + + // zeta specific ones + + bus.registerSubClass(ZRecipeCrawl.Digest.class, ForgeZRecipeCrawl.Digest.class); + bus.registerSubClass(ZRecipeCrawl.Reset.class, ForgeZRecipeCrawl.Reset.class); + bus.registerSubClass(ZRecipeCrawl.Starting.class, ForgeZRecipeCrawl.Starting.class); + bus.registerSubClass(ZRecipeCrawl.Visit.Cooking.class, ForgeZRecipeCrawl.Visit.Cooking.class); + bus.registerSubClass(ZRecipeCrawl.Visit.Custom.class, ForgeZRecipeCrawl.Visit.Custom.class); + bus.registerSubClass(ZRecipeCrawl.Visit.Misc.class, ForgeZRecipeCrawl.Visit.Misc.class); + bus.registerSubClass(ZRecipeCrawl.Visit.Shaped.class, ForgeZRecipeCrawl.Visit.Shaped.class); + bus.registerSubClass(ZRecipeCrawl.Visit.Shapeless.class, ForgeZRecipeCrawl.Visit.Shapeless.class); + } @Override @@ -219,6 +240,7 @@ public boolean fireRightClickBlock(Player player, InteractionHand hand, BlockPos return MinecraftForge.EVENT_BUS.post(new PlayerInteractEvent.RightClickBlock(player, hand, pos, bhr)); } + //TODO: @Override public T fireExternalEvent(T impl) { if (impl instanceof ZGatherAdvancementModifiers advancementModifiers) @@ -230,363 +252,11 @@ public T fireExternalEvent(T impl) { @SuppressWarnings("duplicates") @Override public void start() { - //TODO: sort these somehow lol - //load IEventBus modbus = FMLJavaModLoadingContext.get().getModEventBus(); - modbus.addListener(EventPriority.HIGHEST, this::registerHighest); - modbus.addListener(this::commonSetup); - modbus.addListener(this::loadComplete); - modbus.addListener(this::entityAttributeCreation); - MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); - MinecraftForge.EVENT_BUS.addListener(this::tagsUpdated); - // TODO FIX very ugly & bad modbus.addListener(EventPriority.LOWEST, CreativeTabManager::buildContents); modbus.addListener(ConfigEventDispatcher::configChanged); - - //play - MinecraftForge.EVENT_BUS.addListener(this::rightClickBlock); - MinecraftForge.EVENT_BUS.addListener(EventPriority.LOW, this::rightClickBlockLow); - MinecraftForge.EVENT_BUS.addListener(this::rightClickItem); - MinecraftForge.EVENT_BUS.addListener(this::livingDeath); - MinecraftForge.EVENT_BUS.addListener(EventPriority.LOWEST, this::livingDeathLowest); - MinecraftForge.EVENT_BUS.addListener(this::livingTick); - MinecraftForge.EVENT_BUS.addListener(this::playNoteBlock); - MinecraftForge.EVENT_BUS.addListener(this::lootTableLoad); - MinecraftForge.EVENT_BUS.addListener(this::livingConversion); - MinecraftForge.EVENT_BUS.addListener(this::livingConversionPre); - MinecraftForge.EVENT_BUS.addListener(this::livingConversionPost); - MinecraftForge.EVENT_BUS.addListener(this::anvilUpdate); - MinecraftForge.EVENT_BUS.addListener(EventPriority.LOWEST, this::anvilUpdateLowest); - MinecraftForge.EVENT_BUS.addListener(EventPriority.HIGHEST, this::anvilUpdateHighest); - MinecraftForge.EVENT_BUS.addListener(this::entityConstruct); - MinecraftForge.EVENT_BUS.addListener(this::entityInteract); - MinecraftForge.EVENT_BUS.addListener(this::entityMobGriefing); - MinecraftForge.EVENT_BUS.addListener(this::livingDrops); - MinecraftForge.EVENT_BUS.addListener(this::livingDropsLowest); - MinecraftForge.EVENT_BUS.addListener(this::playerTickStart); - MinecraftForge.EVENT_BUS.addListener(this::playerTickEnd); - MinecraftForge.EVENT_BUS.addListener(this::babyEntitySpawn); - MinecraftForge.EVENT_BUS.addListener(this::babyEntitySpawnLowest); - MinecraftForge.EVENT_BUS.addListener(this::entityJoinLevel); - - MinecraftForge.EVENT_BUS.addGenericListener(ItemStack.class, this::itemStackCaps); - MinecraftForge.EVENT_BUS.addGenericListener(BlockEntity.class, this::blockEntityCaps); - MinecraftForge.EVENT_BUS.addGenericListener(Level.class, this::levelCaps); - - MinecraftForge.EVENT_BUS.addListener(this::serverTickStart); - MinecraftForge.EVENT_BUS.addListener(this::serverTickEnd); - MinecraftForge.EVENT_BUS.addListener(this::levelTickStart); - MinecraftForge.EVENT_BUS.addListener(this::levelTickEnd); - MinecraftForge.EVENT_BUS.addListener(this::playerInteract); - MinecraftForge.EVENT_BUS.addListener(this::playerInteractEntityInteractSpecific); - MinecraftForge.EVENT_BUS.addListener(this::playerInteractEntityInteract); - MinecraftForge.EVENT_BUS.addListener(this::playerInteractRightClickBlock); - MinecraftForge.EVENT_BUS.addListener(this::playerInteractRightClickItem); - MinecraftForge.EVENT_BUS.addListener(this::playerDestroyItem); - MinecraftForge.EVENT_BUS.addListener(this::mobSpawn); - MinecraftForge.EVENT_BUS.addListener(this::mobSpawnFinalizeSpawn); - MinecraftForge.EVENT_BUS.addListener(this::mobSpawnFinalizeSpawnLowest); - MinecraftForge.EVENT_BUS.addListener(this::livingChangeTarget); - MinecraftForge.EVENT_BUS.addListener(this::sleepingLocationCheck); - MinecraftForge.EVENT_BUS.addListener(this::villagerTrades); - MinecraftForge.EVENT_BUS.addListener(this::anvilRepair); - MinecraftForge.EVENT_BUS.addListener(this::player); - MinecraftForge.EVENT_BUS.addListener(this::playerBreakSpeed); - MinecraftForge.EVENT_BUS.addListener(this::playerClone); - MinecraftForge.EVENT_BUS.addListener(this::playerLoggedIn); - MinecraftForge.EVENT_BUS.addListener(this::playerLoggedOut); - MinecraftForge.EVENT_BUS.addListener(this::entityItemPickup); - MinecraftForge.EVENT_BUS.addListener(this::blockBreak); - MinecraftForge.EVENT_BUS.addListener(this::blockEntityPlace); - MinecraftForge.EVENT_BUS.addListener(this::blockToolModification); - MinecraftForge.EVENT_BUS.addListener(this::animalTame); - MinecraftForge.EVENT_BUS.addListener(this::bonemeal); - MinecraftForge.EVENT_BUS.addListener(this::entityTeleport); - MinecraftForge.EVENT_BUS.addListener(this::livingFall); - MinecraftForge.EVENT_BUS.addListener(this::wandererTrades); - MinecraftForge.EVENT_BUS.addListener(this::furnaceFuelBurnTime); - MinecraftForge.EVENT_BUS.addListener(this::itemTooltip); - } - - private boolean registerDone = false; - - public void registerHighest(RegisterEvent e) { - if (registerDone) - return; - - registerDone = true; // do this *before* actually registering to prevent weird ??race conditions?? or something? - //idk whats going on, all i know is i started the game, got a log with 136 "duplicate criterion id" errors, and i don't want to see that again - - loadBus.fire(new ZRegister(this)); - loadBus.fire(new ZRegister.Post()); - } - - public void commonSetup(FMLCommonSetupEvent e) { - loadBus.fire(new ForgeZCommonSetup(e), ZCommonSetup.class); - } - - public void loadComplete(FMLLoadCompleteEvent e) { - loadBus.fire(new ForgeZLoadComplete(e), ZLoadComplete.class); - } - - public void entityAttributeCreation(EntityAttributeCreationEvent e) { - loadBus.fire(new ForgeZEntityAttributeCreation(e), ZEntityAttributeCreation.class); - } - - public void addReloadListener(AddReloadListenerEvent e) { - loadBus.fire(new ForgeZAddReloadListener(e), ZAddReloadListener.class); - } - - public void tagsUpdated(TagsUpdatedEvent e) { - loadBus.fire(new ZTagsUpdated()); - } - - public void rightClickBlock(PlayerInteractEvent.RightClickBlock e) { - playBus.fire(new ForgeZRightClickBlock(e), ZRightClickBlock.class); - } - - public void rightClickBlockLow(PlayerInteractEvent.RightClickBlock e) { - playBus.fire(new ForgeZRightClickBlock.Low(e), ZRightClickBlock.Low.class); - } - - public void rightClickItem(PlayerInteractEvent.RightClickItem e) { - playBus.fire(new ForgeZRightClickItem(e), ZRightClickItem.class); - } - - public void livingDeath(LivingDeathEvent e) { - playBus.fire(new ForgeZLivingDeath(e), ZLivingDeath.class); - } - - public void livingDeathLowest(LivingDeathEvent e) { - playBus.fire(new ForgeZLivingDeath.Lowest(e), ZLivingDeath.Lowest.class); - } - - public void livingTick(LivingEvent.LivingTickEvent e) { - playBus.fire(new ForgeZLivingTick(e), ZLivingTick.class); - } - - public void playNoteBlock(NoteBlockEvent.Play e) { - playBus.fire(new ForgeZPlayNoteBlock(e), ZPlayNoteBlock.class); - } - - public void lootTableLoad(LootTableLoadEvent e) { - playBus.fire(new ForgeZLootTableLoad(e), ZLootTableLoad.class); - } - - public void livingConversion(LivingConversionEvent e) { - playBus.fire(new ForgeZLivingConversion(e), ZLivingConversion.class); - } - - public void livingConversionPre(LivingConversionEvent.Pre e) { - playBus.fire(new ForgeZLivingConversion.Pre(e), ZLivingConversion.Pre.class); - } - - public void livingConversionPost(LivingConversionEvent.Post e) { - playBus.fire(new ForgeZLivingConversion.Post(e), ZLivingConversion.Post.class); - } - - public void anvilUpdate(AnvilUpdateEvent e) { - playBus.fire(new ForgeZAnvilUpdate(e), ZAnvilUpdate.class); - } - - public void anvilUpdateLowest(AnvilUpdateEvent e) { - playBus.fire(new ForgeZAnvilUpdate.Lowest(e), ZAnvilUpdate.Lowest.class); - } - - public void anvilUpdateHighest(AnvilUpdateEvent e) { - playBus.fire(new ForgeZAnvilUpdate.Highest(e), ZAnvilUpdate.Highest.class); - } - - public void entityConstruct(EntityEvent.EntityConstructing e) { - playBus.fire(new ForgeZEntityConstruct(e), ZEntityConstruct.class); - } - - public void entityInteract(PlayerInteractEvent.EntityInteract e) { - playBus.fire(new ForgeZEntityInteract(e), ZEntityInteract.class); - } - - public void entityMobGriefing(EntityMobGriefingEvent e) { - playBus.fire(new ForgeZEntityMobGriefing(e), ZEntityMobGriefing.class); - } - - public void livingDrops(LivingDropsEvent e) { - playBus.fire(new ForgeZLivingDrops(e), ZLivingDrops.class); - } - - public void livingDropsLowest(LivingDropsEvent e) { - playBus.fire(new ForgeZLivingDrops.Lowest(e), ZLivingDrops.Lowest.class); - } - - public void playerTickStart(TickEvent.PlayerTickEvent e) { - if (e.phase == TickEvent.Phase.START) - playBus.fire(new ForgeZPlayerTick.Start(e), ZPlayerTick.Start.class); - } - - public void playerTickEnd(TickEvent.PlayerTickEvent e) { - if (e.phase == TickEvent.Phase.END) - playBus.fire(new ForgeZPlayerTick.End(e), ZPlayerTick.End.class); - } - - public void babyEntitySpawn(BabyEntitySpawnEvent e) { - playBus.fire(new ForgeZBabyEntitySpawn(e), ZBabyEntitySpawn.class); - } - - public void babyEntitySpawnLowest(BabyEntitySpawnEvent e) { - playBus.fire(new ForgeZBabyEntitySpawn.Lowest(e), ZBabyEntitySpawn.Lowest.class); - } - - public void entityJoinLevel(EntityJoinLevelEvent e) { - playBus.fire(new ForgeZEntityJoinLevel(e), ZEntityJoinLevel.class); - } - - public void itemStackCaps(AttachCapabilitiesEvent e) { - playBus.fire(new ForgeZAttachCapabilities.ItemStackCaps(capabilityManager, e), ZAttachCapabilities.ItemStackCaps.class); - } - - public void blockEntityCaps(AttachCapabilitiesEvent e) { - playBus.fire(new ForgeZAttachCapabilities.BlockEntityCaps(capabilityManager, e), ZAttachCapabilities.BlockEntityCaps.class); - } - - public void levelCaps(AttachCapabilitiesEvent e) { - playBus.fire(new ForgeZAttachCapabilities.LevelCaps(capabilityManager, e), ZAttachCapabilities.LevelCaps.class); - } - - public void serverTickStart(TickEvent.ServerTickEvent e) { - if (e.phase == TickEvent.Phase.START) - playBus.fire(new ForgeZServerTick.Start(e), ZServerTick.Start.class); - } - - public void serverTickEnd(TickEvent.ServerTickEvent e) { - if (e.phase == TickEvent.Phase.END) - playBus.fire(new ForgeZServerTick.End(e), ZServerTick.End.class); - } - - public void levelTickStart(TickEvent.LevelTickEvent e) { - if (e.phase == TickEvent.Phase.START) - playBus.fire(new ForgeZLevelTick.Start(e), ZLevelTick.Start.class); - } - - public void levelTickEnd(TickEvent.LevelTickEvent e) { - if (e.phase == TickEvent.Phase.END) - playBus.fire(new ForgeZLevelTick.End(e), ZLevelTick.End.class); - } - - public void playerInteract(PlayerInteractEvent e) { - playBus.fire(new ForgeZPlayerInteract(e), ZPlayerInteract.class); - } - - public void playerInteractEntityInteractSpecific(PlayerInteractEvent.EntityInteractSpecific e) { - playBus.fire(new ForgeZPlayerInteract.EntityInteractSpecific(e), ZPlayerInteract.EntityInteractSpecific.class); - } - - public void playerInteractEntityInteract(PlayerInteractEvent.EntityInteract e) { - playBus.fire(new ForgeZPlayerInteract.EntityInteract(e), ZPlayerInteract.EntityInteract.class); - } - - public void playerInteractRightClickBlock(PlayerInteractEvent.RightClickBlock e) { - playBus.fire(new ForgeZPlayerInteract.RightClickBlock(e), ZPlayerInteract.RightClickBlock.class); - } - - public void playerInteractRightClickItem(PlayerInteractEvent.RightClickItem e) { - playBus.fire(new ForgeZPlayerInteract.RightClickItem(e), ZPlayerInteract.RightClickItem.class); - } - - public void playerDestroyItem(PlayerDestroyItemEvent e) { - playBus.fire(new ForgeZPlayerDestroyItem(e), ZPlayerDestroyItem.class); - } - - public void mobSpawn(MobSpawnEvent e) { - playBus.fire(new ForgeZMobSpawnEvent(e), ZMobSpawnEvent.class); - } - - public void mobSpawnFinalizeSpawn(MobSpawnEvent.FinalizeSpawn e) { - playBus.fire(new ForgeZMobSpawnEvent.FinalizeSpawn(e), ZMobSpawnEvent.CheckSpawn.class); - } - - public void mobSpawnFinalizeSpawnLowest(MobSpawnEvent.FinalizeSpawn e) { - playBus.fire(new ForgeZMobSpawnEvent.FinalizeSpawn.Lowest(e), ZMobSpawnEvent.CheckSpawn.Lowest.class); - } - - public void livingChangeTarget(LivingChangeTargetEvent e) { - playBus.fire(new ForgeZLivingChangeTarget(e), ZLivingChangeTarget.class); - } - - public void sleepingLocationCheck(SleepingLocationCheckEvent e) { - playBus.fire(new ForgeZSleepingLocationCheck(e), ZSleepingLocationCheck.class); - } - - public void entityItemPickup(EntityItemPickupEvent e) { - playBus.fire(new ForgeZEntityItemPickup(e), ZEntityItemPickup.class); - } - - public void blockBreak(BlockEvent.BreakEvent e) { - playBus.fire(new ForgeZBlock.Break(e), ZBlock.Break.class); - } - - public void blockEntityPlace(BlockEvent.EntityPlaceEvent e) { - playBus.fire(new ForgeZBlock.EntityPlace(e), ZBlock.EntityPlace.class); - } - - public void blockToolModification(BlockEvent.BlockToolModificationEvent e) { - playBus.fire(new ForgeZBlock.BlockToolModification(e), ZBlock.BlockToolModification.class); - } - - public void animalTame(AnimalTameEvent e) { - playBus.fire(new ForgeZAnimalTame(e), ZAnimalTame.class); - } - - public void villagerTrades(VillagerTradesEvent e) { - playBus.fire(new ForgeZVillagerTrades(e), ZVillagerTrades.class); - } - - public void anvilRepair(AnvilRepairEvent e) { - playBus.fire(new ForgeZAnvilRepair(e), ZAnvilRepair.class); - } - - public void player(PlayerEvent e) { - playBus.fire(new ForgeZPlayer(e), ZPlayer.class); - } - - public void playerBreakSpeed(PlayerEvent.BreakSpeed e) { - playBus.fire(new ForgeZPlayer.BreakSpeed(e), ZPlayer.BreakSpeed.class); - } - - public void playerClone(PlayerEvent.Clone e) { - playBus.fire(new ForgeZPlayer.Clone(e), ZPlayer.Clone.class); - } - - public void playerLoggedIn(PlayerEvent.PlayerLoggedInEvent e) { - playBus.fire(new ForgeZPlayer.LoggedIn(e), ZPlayer.LoggedIn.class); - } - - public void playerLoggedOut(PlayerEvent.PlayerLoggedOutEvent e) { - playBus.fire(new ForgeZPlayer.LoggedOut(e), ZPlayer.LoggedOut.class); - } - - public void bonemeal(BonemealEvent e) { - playBus.fire(new ForgeZBonemeal(e), ZBonemeal.class); - } - - public void entityTeleport(EntityTeleportEvent e) { - playBus.fire(new ForgeZEntityTeleport(e), ZEntityTeleport.class); - } - - public void livingFall(LivingFallEvent e) { - playBus.fire(new ForgeZLivingFall(e), ZLivingFall.class); - } - - public void wandererTrades(WandererTradesEvent e) { - playBus.fire(new ForgeZWandererTrades(e), ZWandererTrades.class); - } - - public void furnaceFuelBurnTime(FurnaceFuelBurnTimeEvent e) { - playBus.fire(new ForgeZFurnaceFuelBurnTime(e), ZFurnaceFuelBurnTime.class); - } - - public void itemTooltip(ItemTooltipEvent e) { - playBus.fire(new ForgeZItemTooltip(e), ZItemTooltip.class); } public static ZResult from(Event.Result r) { diff --git a/src/main/java/org/violetmoon/zetaimplforge/config/ConfigEventDispatcher.java b/src/main/java/org/violetmoon/zetaimplforge/config/ConfigEventDispatcher.java index 6c722fe..51caf4d 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/config/ConfigEventDispatcher.java +++ b/src/main/java/org/violetmoon/zetaimplforge/config/ConfigEventDispatcher.java @@ -4,6 +4,7 @@ import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.event.load.ZConfigChanged; import org.violetmoon.zeta.util.zetalist.ZetaList; +import org.violetmoon.zetaimplforge.event.load.ForgeZConfigChange; public class ConfigEventDispatcher { public static void configChanged(ModConfigEvent event) { @@ -16,6 +17,7 @@ public static void configChanged(ModConfigEvent event) { // "The Forge config api writes to the config file on every single change // to the config, which would cause the file watcher to trigger // a config reload while the config gui is committing changes." + //TODO: investigate. this doesnt look that sound if(System.currentTimeMillis() - z.configInternals.debounceTime() > 20) handleConfigChange(z); } @@ -28,7 +30,7 @@ public static void dispatchAllInitialLoads() { private static void handleConfigChange(Zeta z) { z.configManager.onReload(); - z.loadBus.fire(new ZConfigChanged()); + z.loadBus.fire(new ForgeZConfigChange()); } } diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZConfigChange.java b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZConfigChange.java new file mode 100644 index 0000000..20d4af3 --- /dev/null +++ b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZConfigChange.java @@ -0,0 +1,9 @@ +package org.violetmoon.zetaimplforge.event.load; + +import net.minecraftforge.eventbus.api.Event; +import org.violetmoon.zeta.event.load.ZConfigChanged; +import org.violetmoon.zeta.event.load.ZModulesReady; + +//aparently this cannot just be forge event. //TODO: investigate +public class ForgeZConfigChange extends Event implements ZConfigChanged { +} diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZModulesReady.java b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZModulesReady.java new file mode 100644 index 0000000..4e54201 --- /dev/null +++ b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZModulesReady.java @@ -0,0 +1,8 @@ +package org.violetmoon.zetaimplforge.event.load; + +import net.minecraftforge.eventbus.api.Event; +import org.violetmoon.zeta.event.load.ZModulesReady; +import org.violetmoon.zeta.event.load.ZTagsUpdated; + +public class ForgeZModulesReady extends Event implements ZModulesReady { +} diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZRegister.java b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZRegister.java new file mode 100644 index 0000000..24c18d4 --- /dev/null +++ b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZRegister.java @@ -0,0 +1,46 @@ +package org.violetmoon.zetaimplforge.event.load; + +import net.minecraftforge.eventbus.api.Event; +import org.violetmoon.zeta.Zeta; +import org.violetmoon.zeta.advancement.AdvancementModifierRegistry; +import org.violetmoon.zeta.event.load.ZRegister; +import org.violetmoon.zeta.registry.*; + +public class ForgeZRegister extends Event implements ZRegister { + + private final Zeta zeta; + + public ForgeZRegister(Zeta zeta) { + this.zeta = zeta; + } + + @Override + public ZetaRegistry getRegistry() { + return zeta.registry; + } + + @Override + public CraftingExtensionsRegistry getCraftingExtensionsRegistry() { + return zeta.craftingExtensions; + } + + @Override + public BrewingRegistry getBrewingRegistry() { + return zeta.brewingRegistry; + } + + @Override + public RenderLayerRegistry getRenderLayerRegistry() { + return zeta.renderLayerRegistry; + } + + @Override + public AdvancementModifierRegistry getAdvancementModifierRegistry() { + return zeta.advancementModifierRegistry; + } + + @Override + public VariantRegistry getVariantRegistry() { + return zeta.variantRegistry; + } +} diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZTagsUpdated.java b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZTagsUpdated.java new file mode 100644 index 0000000..d16ba84 --- /dev/null +++ b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZTagsUpdated.java @@ -0,0 +1,18 @@ +package org.violetmoon.zetaimplforge.event.load; + +import net.minecraft.core.RegistryAccess; +import net.minecraftforge.event.TagsUpdatedEvent; +import org.violetmoon.zeta.event.load.ZTagsUpdated; + +public record ForgeZTagsUpdated(TagsUpdatedEvent event) implements ZTagsUpdated { + + @Override + public RegistryAccess getRegistryAccess() { + return event.getRegistryAccess(); + } + + @Override + public boolean isOnClient() { + return event.getUpdateCause() == TagsUpdatedEvent.UpdateCause.CLIENT_PACKET_RECEIVED; + } +} diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZRecipeCrawl.java b/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZRecipeCrawl.java new file mode 100644 index 0000000..4ddaeb2 --- /dev/null +++ b/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZRecipeCrawl.java @@ -0,0 +1,80 @@ +package org.violetmoon.zetaimplforge.event.play; + +import net.minecraft.world.item.crafting.Recipe; +import net.minecraftforge.eventbus.api.Event; +import org.violetmoon.zeta.event.bus.IZetaPlayEvent; +import org.violetmoon.zeta.event.play.ZRecipeCrawl; + +public class ForgeZRecipeCrawl extends Event implements IZetaPlayEvent { + + private final W wrapped; + + public ForgeZRecipeCrawl(W wrapped) { + this.wrapped = wrapped; + } + + public W get() { + return wrapped; + } + + public static class Reset extends ForgeZRecipeCrawl { + public Reset(ZRecipeCrawl.Reset wrapped) { + super(wrapped); + } + } + + public static class Starting extends ForgeZRecipeCrawl { + public Starting(ZRecipeCrawl.Starting wrapped) { + super(wrapped); + } + } + + public static class Digest extends ForgeZRecipeCrawl { + public Digest(ZRecipeCrawl.Digest wrapped) { + super(wrapped); + } + } + + public static class Visit> extends ForgeZRecipeCrawl> { + public Visit(ZRecipeCrawl.Visit wrapped) { + super(wrapped); + } + + public static class Shaped extends ForgeZRecipeCrawl { + public Shaped(ZRecipeCrawl.Visit.Shaped wrapped) { + super(wrapped); + } + } + + public static class Shapeless extends ForgeZRecipeCrawl { + public Shapeless(ZRecipeCrawl.Visit.Shapeless wrapped) { + super(wrapped); + } + } + + public static class Custom extends ForgeZRecipeCrawl { + public Custom(ZRecipeCrawl.Visit.Custom wrapped) { + super(wrapped); + } + } + + public static class Cooking extends ForgeZRecipeCrawl { + public Cooking(ZRecipeCrawl.Visit.Cooking wrapped) { + super(wrapped); + } + } + + public static class Misc extends ForgeZRecipeCrawl { + public Misc(ZRecipeCrawl.Visit.Misc wrapped) { + super(wrapped); + } + } + + } + + + + + + +} From a506c21cc9a67c21fa9e6127c76a422fa588c3d5 Mon Sep 17 00:00:00 2001 From: MehVahdJukaar Date: Tue, 30 Jul 2024 19:35:30 +0200 Subject: [PATCH 07/22] I hate java type erasure --- src/main/java/org/violetmoon/zeta/Zeta.java | 378 +++++++++--------- .../violetmoon/zeta/config/ConfigManager.java | 5 +- .../zeta/event/bus/ForgeZetaEventBus.java | 180 +++++---- .../zeta/event/load/ZAddReloadListener.java | 1 + .../play/loading/ZGatherAdditionalFlags.java | 8 +- .../zeta/module/ZetaModuleManager.java | 3 +- .../violetmoon/zetaimplforge/ForgeZeta.java | 146 +++++-- .../client/event/play/ForgeZEarlyRender.java | 3 +- .../event/load/ForgeZConfigChange.java | 3 +- .../event/load/ForgeZModulesReady.java | 3 +- .../event/load/ForgeZRegister.java | 5 +- .../loading/ForgeZAttachCapabilities.java | 1 + .../loading/ForgeZGatherAdditionalFlags.java | 18 + 13 files changed, 458 insertions(+), 296 deletions(-) create mode 100644 src/main/java/org/violetmoon/zetaimplforge/event/play/loading/ForgeZGatherAdditionalFlags.java diff --git a/src/main/java/org/violetmoon/zeta/Zeta.java b/src/main/java/org/violetmoon/zeta/Zeta.java index a056b0f..6c10ff5 100644 --- a/src/main/java/org/violetmoon/zeta/Zeta.java +++ b/src/main/java/org/violetmoon/zeta/Zeta.java @@ -1,7 +1,9 @@ package org.violetmoon.zeta; -import java.util.function.Supplier; - +import net.minecraft.core.BlockPos; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.phys.BlockHitResult; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.Nullable; @@ -11,19 +13,15 @@ import org.violetmoon.zeta.config.ConfigManager; import org.violetmoon.zeta.config.IZetaConfigInternals; import org.violetmoon.zeta.config.SectionDefinition; -import org.violetmoon.zeta.event.bus.*; +import org.violetmoon.zeta.event.bus.IZetaLoadEvent; +import org.violetmoon.zeta.event.bus.IZetaPlayEvent; +import org.violetmoon.zeta.event.bus.ZetaEventBus; import org.violetmoon.zeta.item.ext.ItemExtensionFactory; import org.violetmoon.zeta.module.ModuleFinder; import org.violetmoon.zeta.module.ZetaCategory; import org.violetmoon.zeta.module.ZetaModuleManager; import org.violetmoon.zeta.network.ZetaNetworkHandler; -import org.violetmoon.zeta.registry.BrewingRegistry; -import org.violetmoon.zeta.registry.CraftingExtensionsRegistry; -import org.violetmoon.zeta.registry.DyeablesRegistry; -import org.violetmoon.zeta.registry.PottedPlantRegistry; -import org.violetmoon.zeta.registry.RenderLayerRegistry; -import org.violetmoon.zeta.registry.VariantRegistry; -import org.violetmoon.zeta.registry.ZetaRegistry; +import org.violetmoon.zeta.registry.*; import org.violetmoon.zeta.util.NameChanger; import org.violetmoon.zeta.util.RaytracingUtil; import org.violetmoon.zeta.util.RegistryUtil; @@ -34,180 +32,198 @@ import org.violetmoon.zeta.util.zetalist.ZetaList; import org.violetmoon.zeta.world.EntitySpawnHandler; -import net.minecraft.core.BlockPos; -import net.minecraft.world.InteractionHand; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.phys.BlockHitResult; +import java.util.function.Supplier; /** * do not touch forge OR quark from this package, it will later be split off */ public abstract class Zeta implements IZeta { - - public static final String ZETA_ID = "zeta"; - public static final Logger GLOBAL_LOG = LogManager.getLogger(ZETA_ID); - - public Zeta(String modid, Logger log, ZetaSide side, ZetaEventBus loadBus, ZetaEventBus playBus) { - this.log = log; - - this.modid = modid; - this.side = side; - - this.loadBus = loadBus; - this.playBus = playBus; - - this.modules = createModuleManager(); - this.registry = createRegistry(); - this.renderLayerRegistry = createRenderLayerRegistry(); - this.dyeables = createDyeablesRegistry(); - this.craftingExtensions = createCraftingExtensionsRegistry(); - this.brewingRegistry = createBrewingRegistry(); - this.advancementModifierRegistry = createAdvancementModifierRegistry(); - this.pottedPlantRegistry = createPottedPlantRegistry(); - - this.blockExtensions = createBlockExtensionFactory(); - this.itemExtensions = createItemExtensionFactory(); - this.capabilityManager = createCapabilityManager(); - - this.raytracingUtil = createRaytracingUtil(); - this.nameChanger = createNameChanger(); - this.fuel = createFuelHandler(); - - this.entitySpawn = createEntitySpawnHandler(); - - loadBus.subscribe(craftingExtensions) - .subscribe(dyeables) - .subscribe(brewingRegistry) - .subscribe(advancementModifierRegistry) - .subscribe(fuel) - .subscribe(entitySpawn); - - playBus.subscribe(fuel); - - ZetaList.INSTANCE.register(this); - } - - //core - public final Logger log; - public final String modid; - public final ZetaSide side; - public final ZetaEventBus loadBus; - public final ZetaEventBus playBus; - public final ZetaModuleManager modules; - - //registry - public final ZetaRegistry registry; - public final RegistryUtil registryUtil = new RegistryUtil(this); //TODO: Delete this, only needed cause there's no way to get early registry names. - public final RenderLayerRegistry renderLayerRegistry; - public final DyeablesRegistry dyeables; - public final CraftingExtensionsRegistry craftingExtensions; - public final BrewingRegistry brewingRegistry; - public final AdvancementModifierRegistry advancementModifierRegistry; - public final PottedPlantRegistry pottedPlantRegistry; - public final RequiredModTooltipHandler requiredModTooltipHandler = new RequiredModTooltipHandler(); //TODO, find better spot or remove this. - public final VariantRegistry variantRegistry = new VariantRegistry(this); - - //extensions - public final ZetaCapabilityManager capabilityManager; - public final BlockExtensionFactory blockExtensions; - public final ItemExtensionFactory itemExtensions; - - //misc :tada: - public final RaytracingUtil raytracingUtil; - public final NameChanger nameChanger; - public final FuelHandler fuel; - - //config (which isn't set in the constructor b/c module loading has to happen first) - public ConfigManager configManager; - public IZetaConfigInternals configInternals; - - //network (which isn't set in the constructor b/c it has a user-specified protocol version TODO this isnt good api design, imo) - public ZetaNetworkHandler network; - - // worldgen - public EntitySpawnHandler entitySpawn; - - /** - * @param categories List of module categories in this mod, if null, will not load Modules but still load general config - * @param finder Module finder instance to locate the modules this Zeta will load, if null, will not load Modules but still load general config - * @param rootPojo General config object root - */ - public void loadModules(@Nullable Iterable categories, @Nullable ModuleFinder finder, Object rootPojo) { - if(categories != null && finder != null) { - modules.initCategories(categories); - modules.load(finder); - } - - //The reason why there's a circular dependency between configManager and configInternals: - // - ConfigManager determines the shape and layout of the config file - // - The platform-specific configInternals loads the actual values, from the platform-specfic config file - // - Only then can ConfigManager do the initial config load - - this.configManager = new ConfigManager(this, rootPojo); - this.configInternals = makeConfigInternals(configManager.getRootConfig()); - this.configManager.onReload(); - } - - // modloader services - public abstract boolean isModLoaded(String modid); - public abstract @Nullable String getModDisplayName(String modid); - public T modIntegration(String compatWith, Supplier> yes, Supplier> no) { - try { - return (isModLoaded(compatWith) ? yes : no).get().get(); - } catch (Exception e) { - throw new RuntimeException("Zeta: " + modid + " threw exception initializing compat with " + compatWith, e); - } - } - - // config - public abstract IZetaConfigInternals makeConfigInternals(SectionDefinition rootSection); - - // general xplat stuff - public ZetaModuleManager createModuleManager() { - return new ZetaModuleManager(this); - } - public abstract ZetaRegistry createRegistry(); - public RenderLayerRegistry createRenderLayerRegistry() { - return new RenderLayerRegistry(); - } - public abstract CraftingExtensionsRegistry createCraftingExtensionsRegistry(); - public DyeablesRegistry createDyeablesRegistry() { - return new DyeablesRegistry(); - } - public abstract BrewingRegistry createBrewingRegistry(); - public AdvancementModifierRegistry createAdvancementModifierRegistry() { - return new AdvancementModifierRegistry(this); - } - public abstract PottedPlantRegistry createPottedPlantRegistry(); - public abstract ZetaCapabilityManager createCapabilityManager(); - public BlockExtensionFactory createBlockExtensionFactory() { - return BlockExtensionFactory.DEFAULT; - } - public abstract ItemExtensionFactory createItemExtensionFactory(); - public abstract RaytracingUtil createRaytracingUtil(); - public NameChanger createNameChanger() { - return new NameChanger(); - } - public FuelHandler createFuelHandler() { - return new FuelHandler(this); - } - public EntitySpawnHandler createEntitySpawnHandler() { - return new EntitySpawnHandler(this); - } - - public abstract ZetaNetworkHandler createNetworkHandler(int protocolVersion); - - // event bus - public abstract T fireExternalEvent(T impl); - - // ummmmmm why is this here - public abstract boolean fireRightClickBlock(Player player, InteractionHand hand, BlockPos pos, BlockHitResult bhr); - - // Let's Jump - public abstract void start(); - - @Override - public Zeta asZeta() { - return this; - } + + public static final String ZETA_ID = "zeta"; + public static final Logger GLOBAL_LOG = LogManager.getLogger(ZETA_ID); + + public Zeta(String modid, Logger log, ZetaSide side) { + this.log = log; + + this.modid = modid; + this.side = side; + + + this.modules = createModuleManager(); + this.registry = createRegistry(); + this.renderLayerRegistry = createRenderLayerRegistry(); + this.dyeables = createDyeablesRegistry(); + this.craftingExtensions = createCraftingExtensionsRegistry(); + this.brewingRegistry = createBrewingRegistry(); + this.advancementModifierRegistry = createAdvancementModifierRegistry(); + this.pottedPlantRegistry = createPottedPlantRegistry(); + + this.blockExtensions = createBlockExtensionFactory(); + this.itemExtensions = createItemExtensionFactory(); + this.capabilityManager = createCapabilityManager(); + + this.raytracingUtil = createRaytracingUtil(); + this.nameChanger = createNameChanger(); + this.fuel = createFuelHandler(); + + this.entitySpawn = createEntitySpawnHandler(); + + this.loadBus = this.createLoadBus(); + this.playBus = this.createPlayBus(); + + loadBus.subscribe(craftingExtensions) + .subscribe(dyeables) + .subscribe(brewingRegistry) + .subscribe(advancementModifierRegistry) + .subscribe(fuel) + .subscribe(entitySpawn); + + playBus.subscribe(fuel); + + ZetaList.INSTANCE.register(this); + } + + //core + public final Logger log; + public final String modid; + public final ZetaSide side; + public final ZetaEventBus loadBus; + public final ZetaEventBus playBus; + public final ZetaModuleManager modules; + + //registry + public final ZetaRegistry registry; + public final RegistryUtil registryUtil = new RegistryUtil(this); //TODO: Delete this, only needed cause there's no way to get early registry names. + public final RenderLayerRegistry renderLayerRegistry; + public final DyeablesRegistry dyeables; + public final CraftingExtensionsRegistry craftingExtensions; + public final BrewingRegistry brewingRegistry; + public final AdvancementModifierRegistry advancementModifierRegistry; + public final PottedPlantRegistry pottedPlantRegistry; + public final RequiredModTooltipHandler requiredModTooltipHandler = new RequiredModTooltipHandler(); //TODO, find better spot or remove this. + public final VariantRegistry variantRegistry = new VariantRegistry(this); + + //extensions + public final ZetaCapabilityManager capabilityManager; + public final BlockExtensionFactory blockExtensions; + public final ItemExtensionFactory itemExtensions; + + //misc :tada: + public final RaytracingUtil raytracingUtil; + public final NameChanger nameChanger; + public final FuelHandler fuel; + + //config (which isn't set in the constructor b/c module loading has to happen first) + public ConfigManager configManager; + public IZetaConfigInternals configInternals; + + //network (which isn't set in the constructor b/c it has a user-specified protocol version TODO this isnt good api design, imo) + public ZetaNetworkHandler network; + + // worldgen + public EntitySpawnHandler entitySpawn; + + protected abstract ZetaEventBus createPlayBus(); + + protected abstract ZetaEventBus createLoadBus(); + + /** + * @param categories List of module categories in this mod, if null, will not load Modules but still load general config + * @param finder Module finder instance to locate the modules this Zeta will load, if null, will not load Modules but still load general config + * @param rootPojo General config object root + */ + public void loadModules(@Nullable Iterable categories, @Nullable ModuleFinder finder, Object rootPojo) { + if (categories != null && finder != null) { + modules.initCategories(categories); + modules.load(finder); + } + + //The reason why there's a circular dependency between configManager and configInternals: + // - ConfigManager determines the shape and layout of the config file + // - The platform-specific configInternals loads the actual values, from the platform-specfic config file + // - Only then can ConfigManager do the initial config load + + this.configManager = new ConfigManager(this, rootPojo); + this.configInternals = makeConfigInternals(configManager.getRootConfig()); + this.configManager.onReload(); + } + + // modloader services + public abstract boolean isModLoaded(String modid); + + public abstract @Nullable String getModDisplayName(String modid); + + public T modIntegration(String compatWith, Supplier> yes, Supplier> no) { + try { + return (isModLoaded(compatWith) ? yes : no).get().get(); + } catch (Exception e) { + throw new RuntimeException("Zeta: " + modid + " threw exception initializing compat with " + compatWith, e); + } + } + + // config + public abstract IZetaConfigInternals makeConfigInternals(SectionDefinition rootSection); + + // general xplat stuff + public ZetaModuleManager createModuleManager() { + return new ZetaModuleManager(this); + } + + public abstract ZetaRegistry createRegistry(); + + public RenderLayerRegistry createRenderLayerRegistry() { + return new RenderLayerRegistry(); + } + + public abstract CraftingExtensionsRegistry createCraftingExtensionsRegistry(); + + public DyeablesRegistry createDyeablesRegistry() { + return new DyeablesRegistry(); + } + + public abstract BrewingRegistry createBrewingRegistry(); + + public AdvancementModifierRegistry createAdvancementModifierRegistry() { + return new AdvancementModifierRegistry(this); + } + + public abstract PottedPlantRegistry createPottedPlantRegistry(); + + public abstract ZetaCapabilityManager createCapabilityManager(); + + public BlockExtensionFactory createBlockExtensionFactory() { + return BlockExtensionFactory.DEFAULT; + } + + public abstract ItemExtensionFactory createItemExtensionFactory(); + + public abstract RaytracingUtil createRaytracingUtil(); + + public NameChanger createNameChanger() { + return new NameChanger(); + } + + public FuelHandler createFuelHandler() { + return new FuelHandler(this); + } + + public EntitySpawnHandler createEntitySpawnHandler() { + return new EntitySpawnHandler(this); + } + + public abstract ZetaNetworkHandler createNetworkHandler(int protocolVersion); + + // event bus + public abstract T fireExternalEvent(T impl); + + // ummmmmm why is this here + public abstract boolean fireRightClickBlock(Player player, InteractionHand hand, BlockPos pos, BlockHitResult bhr); + + // Let's Jump + public abstract void start(); + + @Override + public Zeta asZeta() { + return this; + } } diff --git a/src/main/java/org/violetmoon/zeta/config/ConfigManager.java b/src/main/java/org/violetmoon/zeta/config/ConfigManager.java index 781c8c5..f22dbfe 100644 --- a/src/main/java/org/violetmoon/zeta/config/ConfigManager.java +++ b/src/main/java/org/violetmoon/zeta/config/ConfigManager.java @@ -14,6 +14,7 @@ import org.violetmoon.zeta.module.ZetaCategory; import org.violetmoon.zeta.module.ZetaModule; import org.violetmoon.zeta.module.ZetaModuleManager; +import org.violetmoon.zetaimplforge.event.play.loading.ForgeZGatherAdditionalFlags; public class ConfigManager { private final Zeta z; @@ -109,7 +110,7 @@ public ConfigManager(Zeta z, Object rootPojo) { } //grab any extra flags - z.playBus.fire(new ZGatherAdditionalFlags(cfm)); + z.playBus.fire(new ForgeZGatherAdditionalFlags(cfm)); //managing module enablement in one go //adding this to the *start* of the list so modules are enabled before anything else runs @@ -123,7 +124,7 @@ public ConfigManager(Zeta z, Object rootPojo) { }); //update extra flags - z.playBus.fire(new ZGatherAdditionalFlags(cfm)); + z.playBus.fire(new ForgeZGatherAdditionalFlags(cfm)); }); this.rootConfig = rootConfigBuilder.build(); diff --git a/src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java b/src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java index 2234a97..0e87d4e 100644 --- a/src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java +++ b/src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java @@ -1,8 +1,5 @@ package org.violetmoon.zeta.event.bus; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraftforge.event.TickEvent; import net.minecraftforge.eventbus.api.Event; import net.minecraftforge.eventbus.api.EventPriority; @@ -12,7 +9,6 @@ import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.violetmoon.zeta.event.play.loading.ZAttachCapabilities; import java.lang.annotation.Annotation; import java.lang.invoke.MethodHandle; @@ -24,24 +20,28 @@ import java.util.Map; import java.util.function.Consumer; import java.util.function.Function; +import java.util.function.Predicate; // this is quite jank. Basically converts all zeta events to forge ones, then delegates to the forge bus directly -public class ForgeZetaEventBus extends ZetaEventBus { +public class ForgeZetaEventBus extends ZetaEventBus { - private final Map, Function> forgeToZetaMap = new HashMap<>(); - private final Map, Function> zetaToForgeMap = new HashMap<>(); + private final Map, Function> forgeToZetaMap = new HashMap<>(); + private final Map, Function> zetaToForgeMap = new HashMap<>(); + private final Map, Class> generics = new HashMap<>(); + private final Map convertedHandlers = new HashMap<>(); private final IEventBus forgeBus; - private final Map convertedHandlers = new HashMap<>(); + private final Class forgeEventRoot; //if Events should implement IModBusEvent /** * @param subscriberAnnotation The annotation that subscribe()/unsubscribe() will pay attention to. * @param eventRoot The superinterface of all events fired on this bus. */ - public ForgeZetaEventBus(Class subscriberAnnotation, Class eventRoot, - @Nullable Logger logSpam, IEventBus forgeBus) { + public ForgeZetaEventBus(Class subscriberAnnotation, Class eventRoot, + @Nullable Logger logSpam, IEventBus forgeBus, Class forgeEventRoot) { super(subscriberAnnotation, eventRoot, logSpam); this.forgeBus = forgeBus; + this.forgeEventRoot = forgeEventRoot; } @@ -50,10 +50,10 @@ protected void subscribeMethod(Method method, Object receiver, Class owningCl if (method.getParameterCount() != 1) throw arityERR(method); - Class eventType = method.getParameterTypes()[0]; + Class zetaEventClass = method.getParameterTypes()[0]; - //check if it's already a forge event or it's a zeta event - if (!eventRoot.isAssignableFrom(eventType) || !Event.class.isAssignableFrom(eventType)) + //check if it's already a forge event, or it's a zeta event + if (!eventRoot.isAssignableFrom(zetaEventClass) && !Event.class.isAssignableFrom(zetaEventClass)) throw typeERR(method); MethodHandle handle; @@ -67,7 +67,7 @@ protected void subscribeMethod(Method method, Object receiver, Class owningCl if (receiver != null) handle = handle.bindTo(receiver); - Consumer consumer = remapMethod(handle, eventType); + Consumer consumer = remapMethod(handle, zetaEventClass); registerListenerToForgeWithPriorityAndGenerics(owningClazz, consumer); //store here so we can unregister later convertedHandlers.put(new Key(method, receiver, owningClazz), consumer); @@ -86,13 +86,13 @@ private record Key(Method method, Object receiver, Class owningClazz) { } @Override - public T fire(@NotNull T event) { + public T fire(@NotNull T event) { forgeBus.post(remapEvent(event, event.getClass())); return event; } @Override - public T fire(@NotNull T event, Class firedAs) { + public T fire(@NotNull T event, Class firedAs) { forgeBus.post(remapEvent(event, firedAs)); return event; } @@ -101,8 +101,14 @@ public T fire(@NotNull T event, Class firedAs) { // good thing is most of this can be removed in 1.21 since Event is an interface there so we can pass zeta events directly. Just need to make zeta event extend Event - private Event remapEvent(@NotNull T event, Class firedAs) { - Function zetaToForgeFunc = zetaToForgeMap.get((Class) firedAs); + private F remapEvent(@NotNull T event, Class firedAs) { + + //if a forge event were to be passed here directly we don't touch it. Still this should not happen + if (forgeEventRoot.isAssignableFrom(event.getClass())) { + return (F) event; + } + + Function zetaToForgeFunc = zetaToForgeMap.get(firedAs); if (zetaToForgeFunc == null) { throw new RuntimeException("No wrapped forge Event found for Zeta event class. You must register its subclass using registerSubclass. " + firedAs); } @@ -110,63 +116,88 @@ private Event remapEvent(@NotNull T event, Class firedAs) { } // takes a method that takes a zeta event and turns into one that takes a forge event - private Consumer remapMethod(MethodHandle originalEventConsumer, Class zetaEventClass) { - // if it's already a forge event, just call it - if (Event.class.isAssignableFrom(zetaEventClass)) { - return event -> { - try { - originalEventConsumer.invoke(event); - } catch (Throwable e) { - throw new RuntimeException(e); - } - }; - } - - Function forgeToZetaFunc = forgeToZetaMap.get(zetaEventClass); + private Consumer remapMethod(MethodHandle originalEventConsumer, Class zetaEventClass) { + Function forgeToZetaFunc = forgeToZetaMap.get(zetaEventClass); if (forgeToZetaFunc == null) { throw new RuntimeException("No forge-Event-wrapping constructor found for Zeta event class. You must register its subclass using registerSubclass. " + zetaEventClass); } return createForgeConsumer(originalEventConsumer, forgeToZetaFunc, zetaEventClass); } - private Event createForgeEvent(@NotNull E event, Function function) { + private F createForgeEvent(@NotNull Z event, Function function) { return function.apply((T) event); } - private Consumer createForgeConsumer(MethodHandle zetaEventConsumer, Function forgeToZetaFunc, - Class zetaEventClass) { + private Consumer createForgeConsumer(MethodHandle zetaEventConsumer, Function forgeToZetaFunc, + Class zetaEventClass) { //hack for tick events Phase phase = Phase.guessFromClassName(zetaEventClass); - return event -> { - try { - //luckily this phase madness will go away with new neoforge - if (phase != Phase.NONE && event instanceof TickEvent te) { - if (phase == Phase.START && te.phase != TickEvent.Phase.START) return; - if (phase == Phase.END && te.phase != TickEvent.Phase.END) return; + Consumer consumer = new Consumer() { + @Override + public void accept(F2 event) { + try { + //luckily this phase madness will go away with new neoforge + if (phase != Phase.NONE && event instanceof TickEvent te) { + if (phase == Phase.START && te.phase != TickEvent.Phase.START) return; + if (phase == Phase.END && te.phase != TickEvent.Phase.END) return; + } + zetaEventConsumer.invoke(forgeToZetaFunc.apply((F2) event)); + } catch (Throwable e) { + throw new RuntimeException(e); } - zetaEventConsumer.invoke(forgeToZetaFunc.apply(event)); - } catch (Throwable e) { - throw new RuntimeException(e); } }; + return consumer; + } + + // for generic events + public void registerSubClass(Class eventClass, Class zetaEventClass, Class genericClass) { + registerSubClass(eventClass, zetaEventClass); + generics.put(eventClass, genericClass); + } + + public void registerSubClass(Class eventClass, Class zetaEventClass) { + var old1 = forgeToZetaMap.put(eventClass, findWrappingConstructor(zetaEventClass)); + var old2 = zetaToForgeMap.put(eventClass, findWrappedEvent(zetaEventClass)); + if (old1 != null || old2 != null) { + throw new RuntimeException("Already registered subclass " + eventClass); + } } + public void registerSubClass(Class eventClass, Class zetaEventClass, + Function constructor, Class genericClass) { + registerSubClass(eventClass, zetaEventClass, constructor); + generics.put(eventClass, genericClass); + } - public void registerSubClass(Class eventClass, Class zetaEventClass) { - forgeToZetaMap.put(eventClass, findWrappingConstructor(zetaEventClass)); + public void registerSubClass(Class eventClass, Class zetaEventClass, + Function constructor) { + forgeToZetaMap.put(eventClass, constructor); zetaToForgeMap.put(eventClass, findWrappedEvent(zetaEventClass)); } - private Function findWrappingConstructor(Class zetaEventClass) { + + private Function findWrappingConstructor(Class zetaEventClass) { + // if it's an Event already ust returns the no argument constructor + if (forgeEventRoot.isAssignableFrom(zetaEventClass)) { + return event -> { + try { + return zetaEventClass.getConstructor().newInstance(); + } catch (Exception e) { + throw new RuntimeException(e); + } + }; + } + // Find the constructor that takes a single parameter of type A for (Constructor constructor : zetaEventClass.getConstructors()) { Class[] parameterTypes = constructor.getParameterTypes(); if (parameterTypes.length == 1 && Event.class.isAssignableFrom(parameterTypes[0])) { return event -> { try { - return (E) constructor.newInstance(event); + return (Z2) constructor.newInstance(event); } catch (Exception e) { - throw new RuntimeException(e); + throw new RuntimeException("Failed to create new instance of event class " + zetaEventClass, e); } }; } @@ -175,40 +206,45 @@ public void registerSubClass(Class eventClass, Cla } - private Function findWrappedEvent(Class zetaEventClass) { - for (Field field : zetaEventClass.getDeclaredFields()) { - if (Event.class.isAssignableFrom(field.getType())) { - return instance -> { - try { - return (Event) field.get(instance); - } catch (IllegalAccessException illegalAccessException) { - throw new RuntimeException(illegalAccessException); - } - }; - } + private Function findWrappedEvent(Class zetaEventClass) { + // if it's an Event already ust returns the no argument constructor + if (forgeEventRoot.isAssignableFrom(zetaEventClass)) { + return instance -> (F) instance; + } + Field eventField = findFieldInClassHierarchy(zetaEventClass, f -> Event.class.isAssignableFrom(f.getType())); + if (eventField != null) { + return instance -> { + try { + return (F) eventField.get(instance); + } catch (IllegalAccessException illegalAccessException) { + throw new RuntimeException(illegalAccessException); + } + }; } throw new RuntimeException("No wrapped forge Event found for Zeta event class " + zetaEventClass); } + public static Field findFieldInClassHierarchy(Class clazz, Predicate predicate) { + while (clazz != null) { + for (Field f : clazz.getDeclaredFields()) { + if (predicate.test(f)) { + return f; + } + } + clazz = clazz.getSuperclass(); + } + return null; + } + //bad string based conversions stuff mess //TODO: refactor in 1.21 using interfaces and stuff. This is just here for now as i want to keep binary compatibility private void registerListenerToForgeWithPriorityAndGenerics(Class owningClazz, Consumer consumer) { EventPriority priority = guessPriorityFromClassName(owningClazz); - //harcoded caps bs. Alternatively a registerGenerics method could have been added to the bus. - Class generics = null; - if (owningClazz.isAssignableFrom(ZAttachCapabilities.BlockEntityCaps.class)) { - generics = BlockEntity.class; - } - if (owningClazz.isAssignableFrom(ZAttachCapabilities.ItemStackCaps.class)) { - generics = ItemStack.class; - } - if (owningClazz.isAssignableFrom(ZAttachCapabilities.LevelCaps.class)) { - generics = Level.class; - } - if (generics != null) { - forgeBus.addGenericListener(generics, priority, (Consumer) consumer); + Class gen = generics.get(owningClazz); + if (gen != null) { + forgeBus.addGenericListener(gen, priority, (Consumer) consumer); } else { forgeBus.addListener(priority, consumer); } diff --git a/src/main/java/org/violetmoon/zeta/event/load/ZAddReloadListener.java b/src/main/java/org/violetmoon/zeta/event/load/ZAddReloadListener.java index b46ce35..6351bb9 100644 --- a/src/main/java/org/violetmoon/zeta/event/load/ZAddReloadListener.java +++ b/src/main/java/org/violetmoon/zeta/event/load/ZAddReloadListener.java @@ -5,6 +5,7 @@ import net.minecraft.core.RegistryAccess; import net.minecraft.server.ReloadableServerResources; import net.minecraft.server.packs.resources.PreparableReloadListener; +import org.violetmoon.zeta.event.bus.IZetaPlayEvent; public interface ZAddReloadListener extends IZetaLoadEvent { ReloadableServerResources getServerResources(); diff --git a/src/main/java/org/violetmoon/zeta/event/play/loading/ZGatherAdditionalFlags.java b/src/main/java/org/violetmoon/zeta/event/play/loading/ZGatherAdditionalFlags.java index b0145d2..7e65d48 100644 --- a/src/main/java/org/violetmoon/zeta/event/play/loading/ZGatherAdditionalFlags.java +++ b/src/main/java/org/violetmoon/zeta/event/play/loading/ZGatherAdditionalFlags.java @@ -1,6 +1,12 @@ package org.violetmoon.zeta.event.play.loading; +import net.minecraftforge.eventbus.api.Event; import org.violetmoon.zeta.config.ConfigFlagManager; import org.violetmoon.zeta.event.bus.IZetaPlayEvent; -public record ZGatherAdditionalFlags(ConfigFlagManager flagManager) implements IZetaPlayEvent { } +import java.util.Objects; + +public interface ZGatherAdditionalFlags extends IZetaPlayEvent { + + ConfigFlagManager flagManager(); +} diff --git a/src/main/java/org/violetmoon/zeta/module/ZetaModuleManager.java b/src/main/java/org/violetmoon/zeta/module/ZetaModuleManager.java index b299fdf..724bbfb 100644 --- a/src/main/java/org/violetmoon/zeta/module/ZetaModuleManager.java +++ b/src/main/java/org/violetmoon/zeta/module/ZetaModuleManager.java @@ -15,6 +15,7 @@ import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.event.load.ZModulesReady; import org.violetmoon.zeta.util.ZetaSide; +import org.violetmoon.zetaimplforge.event.load.ForgeZModulesReady; /** * TODO: other forms of module discovery and replacement (like a Forge-only module, or other types of 'replacement' modules) @@ -129,7 +130,7 @@ public void load(ModuleFinder finder) { z.log.info("Constructed {} modules.", modulesByKey.size()); - z.loadBus.fire(new ZModulesReady()); + z.loadBus.fire(new ForgeZModulesReady()); } private ZetaModule constructAndSetup(TentativeModule t) { diff --git a/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java b/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java index ba79227..d60911a 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java +++ b/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java @@ -11,19 +11,15 @@ import net.minecraft.world.phys.BlockHitResult; import net.minecraftforge.common.ForgeConfigSpec; import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.event.*; -import net.minecraftforge.event.entity.*; -import net.minecraftforge.event.entity.living.*; -import net.minecraftforge.event.entity.player.*; -import net.minecraftforge.event.furnace.FurnaceFuelBurnTimeEvent; -import net.minecraftforge.event.level.BlockEvent; -import net.minecraftforge.event.level.NoteBlockEvent; -import net.minecraftforge.event.village.VillagerTradesEvent; -import net.minecraftforge.event.village.WandererTradesEvent; +import net.minecraftforge.event.AddReloadListenerEvent; +import net.minecraftforge.event.AttachCapabilitiesEvent; +import net.minecraftforge.event.entity.EntityAttributeCreationEvent; +import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.eventbus.api.Event; import net.minecraftforge.eventbus.api.EventPriority; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fml.ModList; +import net.minecraftforge.fml.event.IModBusEvent; import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; import net.minecraftforge.fml.event.lifecycle.FMLLoadCompleteEvent; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; @@ -34,6 +30,7 @@ import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.block.ext.BlockExtensionFactory; import org.violetmoon.zeta.capability.ZetaCapabilityManager; +import org.violetmoon.zeta.client.event.play.*; import org.violetmoon.zeta.config.IZetaConfigInternals; import org.violetmoon.zeta.config.SectionDefinition; import org.violetmoon.zeta.event.bus.*; @@ -42,10 +39,7 @@ import org.violetmoon.zeta.event.play.entity.*; import org.violetmoon.zeta.event.play.entity.living.*; import org.violetmoon.zeta.event.play.entity.player.*; -import org.violetmoon.zeta.event.play.loading.ZAttachCapabilities; -import org.violetmoon.zeta.event.play.loading.ZLootTableLoad; -import org.violetmoon.zeta.event.play.loading.ZVillagerTrades; -import org.violetmoon.zeta.event.play.loading.ZWandererTrades; +import org.violetmoon.zeta.event.play.loading.*; import org.violetmoon.zeta.item.ext.ItemExtensionFactory; import org.violetmoon.zeta.network.ZetaNetworkHandler; import org.violetmoon.zeta.registry.*; @@ -54,6 +48,7 @@ import org.violetmoon.zetaimplforge.api.GatherAdvancementModifiersEvent; import org.violetmoon.zetaimplforge.block.IForgeBlockBlockExtensions; import org.violetmoon.zetaimplforge.capability.ForgeCapabilityManager; +import org.violetmoon.zetaimplforge.client.event.play.*; import org.violetmoon.zetaimplforge.config.ConfigEventDispatcher; import org.violetmoon.zetaimplforge.config.ForgeBackedConfig; import org.violetmoon.zetaimplforge.config.TerribleForgeConfigHackery; @@ -62,10 +57,7 @@ import org.violetmoon.zetaimplforge.event.play.entity.*; import org.violetmoon.zetaimplforge.event.play.entity.living.*; import org.violetmoon.zetaimplforge.event.play.entity.player.*; -import org.violetmoon.zetaimplforge.event.play.loading.ForgeZAttachCapabilities; -import org.violetmoon.zetaimplforge.event.play.loading.ForgeZLootTableLoad; -import org.violetmoon.zetaimplforge.event.play.loading.ForgeZVillagerTrades; -import org.violetmoon.zetaimplforge.event.play.loading.ForgeZWandererTrades; +import org.violetmoon.zetaimplforge.event.play.loading.*; import org.violetmoon.zetaimplforge.item.IForgeItemItemExtensions; import org.violetmoon.zetaimplforge.network.ForgeZetaNetworkHandler; import org.violetmoon.zetaimplforge.registry.ForgeBrewingRegistry; @@ -73,36 +65,41 @@ import org.violetmoon.zetaimplforge.registry.ForgeZetaRegistry; import org.violetmoon.zetaimplforge.util.ForgeRaytracingUtil; +import java.util.function.Function; + /** * ideally do not touch quark from this package, it will later be split off */ public class ForgeZeta extends Zeta { public ForgeZeta(String modid, Logger log) { - super(modid, log, ZetaSide.fromClient(FMLEnvironment.dist.isClient()), - new ForgeZetaEventBus<>(LoadEvent.class, IZetaLoadEvent.class, log, - FMLJavaModLoadingContext.get().getModEventBus()), - new ForgeZetaEventBus<>(PlayEvent.class, IZetaPlayEvent.class, null, - MinecraftForge.EVENT_BUS) - ); - - uglyPopulateForgePlayBus(); - uglyPopulateForgeLoadBus(); + super(modid, log, ZetaSide.fromClient(FMLEnvironment.dist.isClient())); } - // adds known events sub classes to the bus - private void uglyPopulateForgeLoadBus(){ - var bus = (ForgeZetaEventBus) loadBus; + @Override + protected ZetaEventBus createLoadBus() { + if (true) return new FabricZetaEventBus<>(LoadEvent.class, + IZetaLoadEvent.class, log); + + // thanks forge and your dumb Event + IModEvent classes and hacky runtime genericst stuff. I cant get this to work + var bus = new ForgeZetaEventBus<>(LoadEvent.class, IZetaLoadEvent.class, log, + FMLJavaModLoadingContext.get().getModEventBus(), Event.class); + + // adds known events subclasses to the bus bus.registerSubClass(ZCommonSetup.class, ForgeZCommonSetup.class); - bus.registerSubClass(ZAddReloadListener.class, ForgeZAddReloadListener.class); bus.registerSubClass(ZEntityAttributeCreation.class, ForgeZEntityAttributeCreation.class); bus.registerSubClass(ZModulesReady.class, ForgeZModulesReady.class); bus.registerSubClass(ZRegister.class, ForgeZRegister.class); + bus.registerSubClass(ZRegister.Post.class, ForgeZRegister.Post.class); bus.registerSubClass(ZTagsUpdated.class, ForgeZTagsUpdated.class); bus.registerSubClass(ZConfigChanged.class, ForgeZConfigChange.class); + bus.registerSubClass(ZLoadComplete.class, ForgeZLoadComplete.class); + + return bus; } - private void uglyPopulateForgePlayBus() { - var bus = (ForgeZetaEventBus) playBus; + @Override + protected ForgeZetaEventBus createPlayBus() { + var bus = new ForgeZetaEventBus<>(PlayEvent.class, IZetaPlayEvent.class, log, MinecraftForge.EVENT_BUS, Event.class); bus.registerSubClass(ZAnvilRepair.class, ForgeZAnvilRepair.class); bus.registerSubClass(ZBabyEntitySpawn.class, ForgeZBabyEntitySpawn.class); bus.registerSubClass(ZBlock.Break.class, ForgeZBlock.Break.class); @@ -149,10 +146,50 @@ private void uglyPopulateForgePlayBus() { bus.registerSubClass(ZLootTableLoad.class, ForgeZLootTableLoad.class); bus.registerSubClass(ZVillagerTrades.class, ForgeZVillagerTrades.class); bus.registerSubClass(ZWandererTrades.class, ForgeZWandererTrades.class); + bus.registerSubClass(ZFurnaceFuelBurnTime.class, ForgeZFurnaceFuelBurnTime.class); + bus.registerSubClass(ZGatherAdditionalFlags.class, ForgeZGatherAdditionalFlags.class); + bus.registerSubClass(ZServerTick.Start.class, ForgeZServerTick.Start.class); + bus.registerSubClass(ZServerTick.End.class, ForgeZServerTick.End.class); + //Hmm client events here? maybe i should move them - bus.registerSubClass(ZAttachCapabilities.BlockEntityCaps.class, ForgeZAttachCapabilities.BlockEntityCaps.class); - bus.registerSubClass(ZAttachCapabilities.ItemStackCaps.class, ForgeZAttachCapabilities.ItemStackCaps.class); - bus.registerSubClass(ZAttachCapabilities.LevelCaps.class, ForgeZAttachCapabilities.LevelCaps.class); + bus.registerSubClass(ZClientTick.class, ForgeZClientTick.class); + bus.registerSubClass(ZEarlyRender.class, ForgeZEarlyRender.class); + bus.registerSubClass(ZGatherTooltipComponents.class, ForgeZGatherTooltipComponents.class); + bus.registerSubClass(ZHighlightBlock.class, ForgeZHighlightBlock.class); + bus.registerSubClass(ZInput.MouseButton.class, ForgeZInput.MouseButton.class); + bus.registerSubClass(ZInput.Key.class, ForgeZInput.Key.class); + bus.registerSubClass(ZInputUpdate.class, ForgeZInputUpdate.class); + bus.registerSubClass(ZRenderContainerScreen.class, ForgeZRenderContainerScreen.class); + bus.registerSubClass(ZRenderGuiOverlay.class, ForgeZRenderGuiOverlay.class); + bus.registerSubClass(ZRenderLiving.class, ForgeZRenderLiving.class); + bus.registerSubClass(ZRenderPlayer.class, ForgeZRenderPlayer.class); + bus.registerSubClass(ZRenderTick.class, ForgeZRenderTick.class); + bus.registerSubClass(ZRenderTooltip.GatherComponents.class, ForgeZRenderTooltip.GatherComponents.class); + bus.registerSubClass(ZScreen.Opening.class, ForgeZScreen.Opening.class); + bus.registerSubClass(ZScreen.CharacterTyped.class, ForgeZScreen.CharacterTyped.class); + bus.registerSubClass(ZScreen.Init.class, ForgeZScreen.Init.class); + bus.registerSubClass(ZScreen.KeyPressed.class, ForgeZScreen.KeyPressed.class); + bus.registerSubClass(ZScreen.MouseScrolled.class, ForgeZScreen.MouseScrolled.class); + bus.registerSubClass(ZScreen.MouseButtonPressed.class, ForgeZScreen.MouseButtonPressed.class); + bus.registerSubClass(ZScreen.Render.class, ForgeZScreen.Render.class); + + //this is ugly. generic events here + Zeta zeta = this; + bus.registerSubClass(ZAttachCapabilities.BlockEntityCaps.class, + ForgeZAttachCapabilities.BlockEntityCaps.class, + (Function, ForgeZAttachCapabilities.BlockEntityCaps>) inner -> + new ForgeZAttachCapabilities.BlockEntityCaps(zeta.capabilityManager, inner), + BlockEntity.class); + bus.registerSubClass(ZAttachCapabilities.ItemStackCaps.class, + ForgeZAttachCapabilities.ItemStackCaps.class, + (Function, ForgeZAttachCapabilities.ItemStackCaps>) inner -> + new ForgeZAttachCapabilities.ItemStackCaps(zeta.capabilityManager, inner), + ItemStack.class); + bus.registerSubClass(ZAttachCapabilities.LevelCaps.class, + ForgeZAttachCapabilities.LevelCaps.class, + (Function, ForgeZAttachCapabilities.LevelCaps>) inner -> + new ForgeZAttachCapabilities.LevelCaps(zeta.capabilityManager, inner), + Level.class); // zeta specific ones @@ -165,6 +202,7 @@ private void uglyPopulateForgePlayBus() { bus.registerSubClass(ZRecipeCrawl.Visit.Shaped.class, ForgeZRecipeCrawl.Visit.Shaped.class); bus.registerSubClass(ZRecipeCrawl.Visit.Shapeless.class, ForgeZRecipeCrawl.Visit.Shapeless.class); + return bus; } @Override @@ -257,6 +295,44 @@ public void start() { modbus.addListener(EventPriority.LOWEST, CreativeTabManager::buildContents); modbus.addListener(ConfigEventDispatcher::configChanged); + + modbus.addListener(EventPriority.HIGHEST, this::registerHighest); + modbus.addListener(this::commonSetup); + modbus.addListener(this::loadComplete); + modbus.addListener(this::entityAttributeCreation); + + //why is this load? + MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); + } + + private boolean registerDone = false; + + public void registerHighest(RegisterEvent e) { + if (registerDone) + return; + + registerDone = true; // do this *before* actually registering to prevent weird ??race conditions?? or something? + //idk whats going on, all i know is i started the game, got a log with 136 "duplicate criterion id" errors, and i don't want to see that again + + loadBus.fire(new ForgeZRegister(this)); + loadBus.fire(new ForgeZRegister.Post()); + } + + + public void addReloadListener(AddReloadListenerEvent e) { + loadBus.fire(new ForgeZAddReloadListener(e), ZAddReloadListener.class); + } + + public void commonSetup(FMLCommonSetupEvent e) { + loadBus.fire(new ForgeZCommonSetup(e), ZCommonSetup.class); + } + + public void loadComplete(FMLLoadCompleteEvent e) { + loadBus.fire(new ForgeZLoadComplete(e), ZLoadComplete.class); + } + + public void entityAttributeCreation(EntityAttributeCreationEvent e) { + loadBus.fire(new ForgeZEntityAttributeCreation(e), ZEntityAttributeCreation.class); } public static ZResult from(Event.Result r) { diff --git a/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZEarlyRender.java b/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZEarlyRender.java index 86e206c..06816e7 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZEarlyRender.java +++ b/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZEarlyRender.java @@ -1,11 +1,12 @@ package org.violetmoon.zetaimplforge.client.event.play; +import net.minecraftforge.eventbus.api.Event; import org.violetmoon.zeta.client.event.play.ZEarlyRender; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; -public class ForgeZEarlyRender implements ZEarlyRender { +public class ForgeZEarlyRender extends Event implements ZEarlyRender { @Override public GuiGraphics guiGraphics() { return new GuiGraphics(Minecraft.getInstance(), Minecraft.getInstance().renderBuffers().bufferSource()); diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZConfigChange.java b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZConfigChange.java index 20d4af3..87bc302 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZConfigChange.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZConfigChange.java @@ -1,9 +1,10 @@ package org.violetmoon.zetaimplforge.event.load; import net.minecraftforge.eventbus.api.Event; +import net.minecraftforge.fml.event.IModBusEvent; import org.violetmoon.zeta.event.load.ZConfigChanged; import org.violetmoon.zeta.event.load.ZModulesReady; //aparently this cannot just be forge event. //TODO: investigate -public class ForgeZConfigChange extends Event implements ZConfigChanged { +public class ForgeZConfigChange extends Event implements ZConfigChanged, IModBusEvent { } diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZModulesReady.java b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZModulesReady.java index 4e54201..adaa3ba 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZModulesReady.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZModulesReady.java @@ -1,8 +1,9 @@ package org.violetmoon.zetaimplforge.event.load; import net.minecraftforge.eventbus.api.Event; +import net.minecraftforge.fml.event.IModBusEvent; import org.violetmoon.zeta.event.load.ZModulesReady; import org.violetmoon.zeta.event.load.ZTagsUpdated; -public class ForgeZModulesReady extends Event implements ZModulesReady { +public class ForgeZModulesReady extends Event implements ZModulesReady, IModBusEvent { } diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZRegister.java b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZRegister.java index 24c18d4..d72f2ff 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZRegister.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZRegister.java @@ -1,12 +1,13 @@ package org.violetmoon.zetaimplforge.event.load; import net.minecraftforge.eventbus.api.Event; +import net.minecraftforge.fml.event.IModBusEvent; import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.advancement.AdvancementModifierRegistry; import org.violetmoon.zeta.event.load.ZRegister; import org.violetmoon.zeta.registry.*; -public class ForgeZRegister extends Event implements ZRegister { +public class ForgeZRegister extends Event implements ZRegister, IModBusEvent { private final Zeta zeta; @@ -43,4 +44,6 @@ public AdvancementModifierRegistry getAdvancementModifierRegistry() { public VariantRegistry getVariantRegistry() { return zeta.variantRegistry; } + + public static class Post extends Event implements ZRegister.Post, IModBusEvent { } } diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/play/loading/ForgeZAttachCapabilities.java b/src/main/java/org/violetmoon/zetaimplforge/event/play/loading/ForgeZAttachCapabilities.java index 95d342d..5fd2ca7 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/play/loading/ForgeZAttachCapabilities.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/play/loading/ForgeZAttachCapabilities.java @@ -1,5 +1,6 @@ package org.violetmoon.zetaimplforge.event.play.loading; +import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.capability.ZetaCapability; import org.violetmoon.zeta.capability.ZetaCapabilityManager; import org.violetmoon.zeta.event.play.loading.ZAttachCapabilities; diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/play/loading/ForgeZGatherAdditionalFlags.java b/src/main/java/org/violetmoon/zetaimplforge/event/play/loading/ForgeZGatherAdditionalFlags.java new file mode 100644 index 0000000..224fd4a --- /dev/null +++ b/src/main/java/org/violetmoon/zetaimplforge/event/play/loading/ForgeZGatherAdditionalFlags.java @@ -0,0 +1,18 @@ +package org.violetmoon.zetaimplforge.event.play.loading; + +import net.minecraftforge.eventbus.api.Event; +import org.violetmoon.zeta.config.ConfigFlagManager; +import org.violetmoon.zeta.event.play.loading.ZGatherAdditionalFlags; + +public class ForgeZGatherAdditionalFlags extends Event implements ZGatherAdditionalFlags { + private final ConfigFlagManager flagManager; + + public ForgeZGatherAdditionalFlags(ConfigFlagManager flagManager) { + this.flagManager = flagManager; + } + + @Override + public ConfigFlagManager flagManager() { + return flagManager; + } +} From e7cd5e719a21b66c7cd9d7c97ac62e03c5a42467 Mon Sep 17 00:00:00 2001 From: MehVahdJukaar Date: Wed, 31 Jul 2024 14:24:05 +0200 Subject: [PATCH 08/22] game boots :O --- src/main/java/org/violetmoon/zeta/Zeta.java | 5 +- .../AdvancementModifierRegistry.java | 10 +- .../zeta/client/ClientRegistryExtension.java | 27 +-- .../event/load/ZAddBlockColorHandlers.java | 5 - .../event/load/ZAddItemColorHandlers.java | 5 - .../violetmoon/zeta/config/ConfigManager.java | 4 +- .../zeta/event/bus/FabricZetaEventBus.java | 13 - .../zeta/event/bus/ForgeZetaEventBus.java | 150 ++++++++---- .../zeta/event/load/ZAddReloadListener.java | 2 +- .../load/ZGatherAdvancementModifiers.java | 3 +- .../zeta/event/load/ZTagsUpdated.java | 3 +- .../zeta/registry/ZetaRegistry.java | 46 +++- .../zeta/util/handler/RecipeCrawlHandler.java | 18 +- .../zeta/util/zetalist/ZetaList.java | 8 - .../violetmoon/zetaimplforge/ForgeZeta.java | 74 +++--- ... => ForgeZGatherAdvancementModifiers.java} | 22 +- .../zetaimplforge/client/ForgeZetaClient.java | 226 +----------------- .../load/ForgeZAddBlockColorHandlers.java | 80 +++---- .../load/ForgeZAddItemColorHandlers.java | 32 +-- .../client/event/load/ForgeZModel.java | 1 + .../loading/ForgeZGatherAdditionalFlags.java | 9 +- .../mixin/mixins/client/GameRenderMixin.java | 4 +- 22 files changed, 268 insertions(+), 479 deletions(-) rename src/main/java/org/violetmoon/zetaimplforge/api/{GatherAdvancementModifiersEvent.java => ForgeZGatherAdvancementModifiers.java} (54%) diff --git a/src/main/java/org/violetmoon/zeta/Zeta.java b/src/main/java/org/violetmoon/zeta/Zeta.java index 6c10ff5..525afde 100644 --- a/src/main/java/org/violetmoon/zeta/Zeta.java +++ b/src/main/java/org/violetmoon/zeta/Zeta.java @@ -213,10 +213,7 @@ public EntitySpawnHandler createEntitySpawnHandler() { public abstract ZetaNetworkHandler createNetworkHandler(int protocolVersion); - // event bus - public abstract T fireExternalEvent(T impl); - - // ummmmmm why is this here + // ummmmmm why is this here?? public abstract boolean fireRightClickBlock(Player player, InteractionHand hand, BlockPos pos, BlockHitResult bhr); // Let's Jump diff --git a/src/main/java/org/violetmoon/zeta/advancement/AdvancementModifierRegistry.java b/src/main/java/org/violetmoon/zeta/advancement/AdvancementModifierRegistry.java index 8c63bff..43bfa34 100644 --- a/src/main/java/org/violetmoon/zeta/advancement/AdvancementModifierRegistry.java +++ b/src/main/java/org/violetmoon/zeta/advancement/AdvancementModifierRegistry.java @@ -18,6 +18,7 @@ import org.violetmoon.zeta.api.IAdvancementModifier; import org.violetmoon.zeta.api.IAdvancementModifierDelegate; import org.violetmoon.zeta.event.bus.LoadEvent; +import org.violetmoon.zeta.event.bus.PlayEvent; import org.violetmoon.zeta.event.load.ZAddReloadListener; import org.violetmoon.zeta.event.load.ZGatherAdvancementModifiers; @@ -36,7 +37,10 @@ import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.block.Block; +import org.violetmoon.zetaimplforge.api.ForgeZGatherAdvancementModifiers; +import org.violetmoon.zetaimplforge.client.event.play.ForgeZEarlyRender; +//TODO: make this zeta-independent public class AdvancementModifierRegistry { protected final Zeta zeta; protected final Multimap modifiers = HashMultimap.create(); @@ -59,11 +63,11 @@ public void addModifier(IAdvancementModifier mod) { modifiers.put(r, mod); } - @LoadEvent + @PlayEvent public void addListeners(ZAddReloadListener event) { if(!gatheredAddons) { IAdvancementModifierDelegate delegateImpl = new DelegateImpl(); - zeta.loadBus.fireExternal(new ZGatherAdvancementModifiers() { + zeta.playBus.fire(new ZGatherAdvancementModifiers() { @Override public void register(IAdvancementModifier modifier) { addModifier(modifier); @@ -73,7 +77,7 @@ public void register(IAdvancementModifier modifier) { public IAdvancementModifierDelegate getDelegate() { return delegateImpl; } - }, ZGatherAdvancementModifiers.class); + }); gatheredAddons = true; } diff --git a/src/main/java/org/violetmoon/zeta/client/ClientRegistryExtension.java b/src/main/java/org/violetmoon/zeta/client/ClientRegistryExtension.java index 660f0a6..09e866f 100644 --- a/src/main/java/org/violetmoon/zeta/client/ClientRegistryExtension.java +++ b/src/main/java/org/violetmoon/zeta/client/ClientRegistryExtension.java @@ -9,6 +9,7 @@ import org.violetmoon.zeta.client.event.load.ZAddItemColorHandlers; import org.violetmoon.zeta.client.event.load.ZClientSetup; import org.violetmoon.zeta.event.bus.LoadEvent; +import org.violetmoon.zeta.event.load.ZLoadComplete; import org.violetmoon.zeta.registry.DyeablesRegistry; import org.violetmoon.zeta.registry.RenderLayerRegistry; import org.violetmoon.zeta.registry.ZetaRegistry; @@ -56,32 +57,16 @@ public void registerItemColorHandlers(ZAddItemColorHandlers event) { } } - //these are in Post events to give other listeners a chance to populate .registerNamed @LoadEvent - public void registerBlockColorsPost(ZAddBlockColorHandlers.Post event) { - registry.finalizeBlockColors((block, name) -> { - Function blockColorCreator = event.getNamedBlockColors().get(name); - if(blockColorCreator == null) - z.log.error("Unknown block color creator {} used on block {}", name, block); - else - event.register(blockColorCreator.apply(block), block); - }); + public void registerRenderLayers(ZClientSetup event) { + z.renderLayerRegistry.finalize(this::doSetRenderLayer); } - @LoadEvent - public void registerItemColorsPost(ZAddItemColorHandlers.Post event) { - registry.finalizeItemColors((item, name) -> { - Function itemColorCreator = event.getNamedItemColors().get(name); - if(itemColorCreator == null) - z.log.error("Unknown item color creator {} used on item {}", name, item); - else - event.register(itemColorCreator.apply(item), item); - }); - } + //I hope this won't run on dedicated servers @LoadEvent - public void registerRenderLayers(ZClientSetup event) { - z.renderLayerRegistry.finalize(this::doSetRenderLayer); + public void onLoadComplete(ZLoadComplete event){ + z.registry.validateColorsProviders(); } protected abstract void doSetRenderLayer(Block block, RenderLayerRegistry.Layer layer); diff --git a/src/main/java/org/violetmoon/zeta/client/event/load/ZAddBlockColorHandlers.java b/src/main/java/org/violetmoon/zeta/client/event/load/ZAddBlockColorHandlers.java index 5a7febc..1748b3d 100644 --- a/src/main/java/org/violetmoon/zeta/client/event/load/ZAddBlockColorHandlers.java +++ b/src/main/java/org/violetmoon/zeta/client/event/load/ZAddBlockColorHandlers.java @@ -13,9 +13,4 @@ public interface ZAddBlockColorHandlers extends IZetaLoadEvent { void register(BlockColor c, Block... blocks); void registerNamed(Function c, String... names); BlockColors getBlockColors(); - - Post makePostEvent(); - interface Post extends ZAddBlockColorHandlers { - Map> getNamedBlockColors(); - } } diff --git a/src/main/java/org/violetmoon/zeta/client/event/load/ZAddItemColorHandlers.java b/src/main/java/org/violetmoon/zeta/client/event/load/ZAddItemColorHandlers.java index 5e11982..d8cce85 100644 --- a/src/main/java/org/violetmoon/zeta/client/event/load/ZAddItemColorHandlers.java +++ b/src/main/java/org/violetmoon/zeta/client/event/load/ZAddItemColorHandlers.java @@ -14,9 +14,4 @@ public interface ZAddItemColorHandlers extends IZetaLoadEvent { void register(ItemColor c, ItemLike... items); void registerNamed(Function c, String... names); ItemColors getItemColors(); - - Post makePostEvent(); - interface Post extends ZAddItemColorHandlers { - Map> getNamedItemColors(); - } } diff --git a/src/main/java/org/violetmoon/zeta/config/ConfigManager.java b/src/main/java/org/violetmoon/zeta/config/ConfigManager.java index f22dbfe..0783265 100644 --- a/src/main/java/org/violetmoon/zeta/config/ConfigManager.java +++ b/src/main/java/org/violetmoon/zeta/config/ConfigManager.java @@ -110,7 +110,7 @@ public ConfigManager(Zeta z, Object rootPojo) { } //grab any extra flags - z.playBus.fire(new ForgeZGatherAdditionalFlags(cfm)); + z.playBus.fire(() -> cfm,ZGatherAdditionalFlags.class); //managing module enablement in one go //adding this to the *start* of the list so modules are enabled before anything else runs @@ -124,7 +124,7 @@ public ConfigManager(Zeta z, Object rootPojo) { }); //update extra flags - z.playBus.fire(new ForgeZGatherAdditionalFlags(cfm)); + z.playBus.fire(() -> cfm,ZGatherAdditionalFlags.class); }); this.rootConfig = rootConfigBuilder.build(); diff --git a/src/main/java/org/violetmoon/zeta/event/bus/FabricZetaEventBus.java b/src/main/java/org/violetmoon/zeta/event/bus/FabricZetaEventBus.java index 8f34886..47c4f0c 100644 --- a/src/main/java/org/violetmoon/zeta/event/bus/FabricZetaEventBus.java +++ b/src/main/java/org/violetmoon/zeta/event/bus/FabricZetaEventBus.java @@ -84,19 +84,6 @@ private String logSpamSimpleName(Class clazz) { return split[split.length - 1]; } - public T fireExternal(@NotNull T event, Class firedAs) { - event = fire(event, firedAs); - - if(event instanceof Cancellable cancellable && cancellable.isCanceled()) - return event; - else{ - throw new RuntimeException(); - //TODO: re add. this shuld be put in loader specific bus code - //return z.fireExternalEvent(event); // Interfaces with the platform-specific event bus utility - } - - } - /** * Picks out the "Foo" in "void handleFoo(Foo event)", and gets/creates the Listeners corresponding to that type. */ diff --git a/src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java b/src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java index 0e87d4e..7d14346 100644 --- a/src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java +++ b/src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java @@ -9,6 +9,9 @@ import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.violetmoon.zeta.client.event.load.ZAddBlockColorHandlers; +import org.violetmoon.zeta.event.load.ZRegister; +import org.violetmoon.zetaimplforge.event.load.ForgeZRegister; import java.lang.annotation.Annotation; import java.lang.invoke.MethodHandle; @@ -27,6 +30,7 @@ public class ForgeZetaEventBus extends ZetaEventBus { private final Map, Function> forgeToZetaMap = new HashMap<>(); private final Map, Function> zetaToForgeMap = new HashMap<>(); + private final Map, Class> zetaToForgeEventClass = new HashMap<>(); private final Map, Class> generics = new HashMap<>(); private final Map convertedHandlers = new HashMap<>(); @@ -53,7 +57,7 @@ protected void subscribeMethod(Method method, Object receiver, Class owningCl Class zetaEventClass = method.getParameterTypes()[0]; //check if it's already a forge event, or it's a zeta event - if (!eventRoot.isAssignableFrom(zetaEventClass) && !Event.class.isAssignableFrom(zetaEventClass)) + if (!eventRoot.isAssignableFrom(zetaEventClass) && !forgeEventRoot.isAssignableFrom(zetaEventClass)) throw typeERR(method); MethodHandle handle; @@ -68,7 +72,7 @@ protected void subscribeMethod(Method method, Object receiver, Class owningCl handle = handle.bindTo(receiver); Consumer consumer = remapMethod(handle, zetaEventClass); - registerListenerToForgeWithPriorityAndGenerics(owningClazz, consumer); + registerListenerToForgeWithPriorityAndGenerics(owningClazz, consumer, zetaEventClass); //store here so we can unregister later convertedHandlers.put(new Key(method, receiver, owningClazz), consumer); } @@ -82,6 +86,7 @@ protected void unsubscribeMethod(Method m, Object receiver, Class owningClazz } } + private record Key(Method method, Object receiver, Class owningClazz) { } @@ -101,25 +106,25 @@ public T fire(@NotNull T event, Class firedAs) { // good thing is most of this can be removed in 1.21 since Event is an interface there so we can pass zeta events directly. Just need to make zeta event extend Event - private F remapEvent(@NotNull T event, Class firedAs) { - - //if a forge event were to be passed here directly we don't touch it. Still this should not happen - if (forgeEventRoot.isAssignableFrom(event.getClass())) { - return (F) event; - } - + private F remapEvent(@NotNull Z2 zetaEvent, Class firedAs) { Function zetaToForgeFunc = zetaToForgeMap.get(firedAs); if (zetaToForgeFunc == null) { - throw new RuntimeException("No wrapped forge Event found for Zeta event class. You must register its subclass using registerSubclass. " + firedAs); + // remap is null. no checks because micro optimization. It means it must be a forge event already + return (F) zetaEvent; + //throw new RuntimeException("No wrapped forge Event found for Zeta event class. You must register its subclass using registerSubclass. " + firedAs); } - return createForgeEvent(event, zetaToForgeFunc); + return createForgeEvent(zetaEvent, zetaToForgeFunc); } // takes a method that takes a zeta event and turns into one that takes a forge event private Consumer remapMethod(MethodHandle originalEventConsumer, Class zetaEventClass) { Function forgeToZetaFunc = forgeToZetaMap.get(zetaEventClass); if (forgeToZetaFunc == null) { - throw new RuntimeException("No forge-Event-wrapping constructor found for Zeta event class. You must register its subclass using registerSubclass. " + zetaEventClass); + // no remap needed + if (forgeEventRoot.isAssignableFrom(zetaEventClass)) { + forgeToZetaFunc = event -> (Z) event; + } else + throw new RuntimeException("No forge-Event-wrapping constructor found for Zeta event class. You must register its subclass using registerSubclass. " + zetaEventClass); } return createForgeConsumer(originalEventConsumer, forgeToZetaFunc, zetaEventClass); } @@ -132,22 +137,18 @@ private Consumer createForgeConsumer(MethodHand Class zetaEventClass) { //hack for tick events Phase phase = Phase.guessFromClassName(zetaEventClass); - Consumer consumer = new Consumer() { - @Override - public void accept(F2 event) { - try { - //luckily this phase madness will go away with new neoforge - if (phase != Phase.NONE && event instanceof TickEvent te) { - if (phase == Phase.START && te.phase != TickEvent.Phase.START) return; - if (phase == Phase.END && te.phase != TickEvent.Phase.END) return; - } - zetaEventConsumer.invoke(forgeToZetaFunc.apply((F2) event)); - } catch (Throwable e) { - throw new RuntimeException(e); + return event -> { + try { + //luckily this phase madness will go away with new neoforge + if (phase != Phase.NONE && event instanceof TickEvent te) { + if (phase == Phase.START && te.phase != TickEvent.Phase.START) return; + if (phase == Phase.END && te.phase != TickEvent.Phase.END) return; } + zetaEventConsumer.invoke(forgeToZetaFunc.apply(event)); + } catch (Throwable e) { + throw new RuntimeException(e); } }; - return consumer; } // for generic events @@ -157,11 +158,9 @@ public void registerSubClass(Class eventClass, Cla } public void registerSubClass(Class eventClass, Class zetaEventClass) { - var old1 = forgeToZetaMap.put(eventClass, findWrappingConstructor(zetaEventClass)); - var old2 = zetaToForgeMap.put(eventClass, findWrappedEvent(zetaEventClass)); - if (old1 != null || old2 != null) { - throw new RuntimeException("Already registered subclass " + eventClass); - } + + Function wrappingConstructor = findForgeWrapper(zetaEventClass, eventClass); + registerSubClass(eventClass, zetaEventClass, wrappingConstructor); } public void registerSubClass(Class eventClass, Class zetaEventClass, @@ -171,28 +170,39 @@ public void registerSubClass(Class eventClass, Cla } public void registerSubClass(Class eventClass, Class zetaEventClass, - Function constructor) { - forgeToZetaMap.put(eventClass, constructor); - zetaToForgeMap.put(eventClass, findWrappedEvent(zetaEventClass)); + @Nullable Function constructor) { + Object old1 = null; + Object old2 = null; + if (constructor != null) { + old1 = forgeToZetaMap.put(eventClass, constructor); + } + Function zetaToForge = findWrappedForgeEvent(zetaEventClass, eventClass); + if (zetaToForge == null) { + zetaToForge = findZetaWrapper(zetaEventClass); + } + + if (zetaToForge != null) { + old2 = zetaToForgeMap.put(eventClass, zetaToForge); + } + + if (old1 != null || old2 != null) { + throw new RuntimeException("Event class " + eventClass + " already registered"); + } } - private Function findWrappingConstructor(Class zetaEventClass) { + private Function findForgeWrapper(Class zetaEventClass, Class baseZetaEventClass) { + // if it's an Event already ust returns the no argument constructor if (forgeEventRoot.isAssignableFrom(zetaEventClass)) { - return event -> { - try { - return zetaEventClass.getConstructor().newInstance(); - } catch (Exception e) { - throw new RuntimeException(e); - } - }; + zetaToForgeEventClass.put(baseZetaEventClass, zetaEventClass); + return event -> (Z2) event; } // Find the constructor that takes a single parameter of type A for (Constructor constructor : zetaEventClass.getConstructors()) { Class[] parameterTypes = constructor.getParameterTypes(); - if (parameterTypes.length == 1 && Event.class.isAssignableFrom(parameterTypes[0])) { + if (parameterTypes.length == 1 && forgeEventRoot.isAssignableFrom(parameterTypes[0])) { return event -> { try { return (Z2) constructor.newInstance(event); @@ -205,22 +215,54 @@ private Function findWrappingConstructor(Cl throw new RuntimeException("No forge-Event-wrapping constructor found for Zeta event class " + zetaEventClass); } - - private Function findWrappedEvent(Class zetaEventClass) { + private Function findZetaWrapper(Class zetaEventClass) { // if it's an Event already ust returns the no argument constructor + + // Find the constructor that takes a single parameter of type A + for (Constructor constructor : zetaEventClass.getConstructors()) { + Class[] parameterTypes = constructor.getParameterTypes(); + if (parameterTypes.length == 1 && eventRoot.isAssignableFrom(parameterTypes[0])) { + return event -> { + try { + return (F2) constructor.newInstance(event); + } catch (Exception e) { + throw new RuntimeException("Failed to create new instance of event class " + zetaEventClass, e); + } + }; + } + } + if (forgeEventRoot.isAssignableFrom(zetaEventClass)) { - return instance -> (F) instance; + return null; } - Field eventField = findFieldInClassHierarchy(zetaEventClass, f -> Event.class.isAssignableFrom(f.getType())); + + throw new RuntimeException("No Zeta-Event-wrapping constructor found for Zeta event class " + zetaEventClass); + } + + + private Function findWrappedForgeEvent(Class zetaEventClass, Class baseZetaEventClass) { + + Field eventField = findFieldInClassHierarchy(zetaEventClass, f -> + forgeEventRoot.isAssignableFrom(f.getType())); if (eventField != null) { + //hack + eventField.setAccessible(true); + zetaToForgeEventClass.put(baseZetaEventClass, eventField.getType()); return instance -> { try { - return (F) eventField.get(instance); - } catch (IllegalAccessException illegalAccessException) { - throw new RuntimeException(illegalAccessException); + return (F2) eventField.get(instance); + } catch (Exception e) { + throw new RuntimeException(e); } }; } + + //tries to unwrap first. Then if its already a forge event we just keep it + if (forgeEventRoot.isAssignableFrom(zetaEventClass)) { + zetaToForgeEventClass.put(baseZetaEventClass, zetaEventClass); + return null; + } + throw new RuntimeException("No wrapped forge Event found for Zeta event class " + zetaEventClass); } @@ -240,13 +282,17 @@ public static Field findFieldInClassHierarchy(Class clazz, Predicate p //TODO: refactor in 1.21 using interfaces and stuff. This is just here for now as i want to keep binary compatibility - private void registerListenerToForgeWithPriorityAndGenerics(Class owningClazz, Consumer consumer) { + private void registerListenerToForgeWithPriorityAndGenerics(Class owningClazz, Consumer consumer, Class zetaEventClass) { EventPriority priority = guessPriorityFromClassName(owningClazz); Class gen = generics.get(owningClazz); + Class eventType = zetaToForgeEventClass.get(zetaEventClass); + if (eventType == null) { + throw new RuntimeException("No event type found for " + zetaEventClass); + } if (gen != null) { - forgeBus.addGenericListener(gen, priority, (Consumer) consumer); + forgeBus.addGenericListener(gen, priority, false, eventType, (Consumer) consumer); } else { - forgeBus.addListener(priority, consumer); + forgeBus.addListener(priority, false, eventType, consumer); } } diff --git a/src/main/java/org/violetmoon/zeta/event/load/ZAddReloadListener.java b/src/main/java/org/violetmoon/zeta/event/load/ZAddReloadListener.java index 6351bb9..f7100c7 100644 --- a/src/main/java/org/violetmoon/zeta/event/load/ZAddReloadListener.java +++ b/src/main/java/org/violetmoon/zeta/event/load/ZAddReloadListener.java @@ -7,7 +7,7 @@ import net.minecraft.server.packs.resources.PreparableReloadListener; import org.violetmoon.zeta.event.bus.IZetaPlayEvent; -public interface ZAddReloadListener extends IZetaLoadEvent { +public interface ZAddReloadListener extends IZetaPlayEvent { ReloadableServerResources getServerResources(); RegistryAccess getRegistryAccess(); void addListener(PreparableReloadListener listener); diff --git a/src/main/java/org/violetmoon/zeta/event/load/ZGatherAdvancementModifiers.java b/src/main/java/org/violetmoon/zeta/event/load/ZGatherAdvancementModifiers.java index af535b5..aae4537 100644 --- a/src/main/java/org/violetmoon/zeta/event/load/ZGatherAdvancementModifiers.java +++ b/src/main/java/org/violetmoon/zeta/event/load/ZGatherAdvancementModifiers.java @@ -14,8 +14,9 @@ import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.block.Block; +import org.violetmoon.zeta.event.bus.IZetaPlayEvent; -public interface ZGatherAdvancementModifiers extends IZetaLoadEvent { +public interface ZGatherAdvancementModifiers extends IZetaPlayEvent { void register(IAdvancementModifier modifier); IAdvancementModifierDelegate getDelegate(); diff --git a/src/main/java/org/violetmoon/zeta/event/load/ZTagsUpdated.java b/src/main/java/org/violetmoon/zeta/event/load/ZTagsUpdated.java index 343c685..d5cbd46 100644 --- a/src/main/java/org/violetmoon/zeta/event/load/ZTagsUpdated.java +++ b/src/main/java/org/violetmoon/zeta/event/load/ZTagsUpdated.java @@ -2,9 +2,10 @@ import net.minecraft.core.RegistryAccess; import org.violetmoon.zeta.event.bus.IZetaLoadEvent; +import org.violetmoon.zeta.event.bus.IZetaPlayEvent; //TODO: just used by RecipeCrawlHandler -public interface ZTagsUpdated extends IZetaLoadEvent { +public interface ZTagsUpdated extends IZetaPlayEvent { RegistryAccess getRegistryAccess(); diff --git a/src/main/java/org/violetmoon/zeta/registry/ZetaRegistry.java b/src/main/java/org/violetmoon/zeta/registry/ZetaRegistry.java index 9787dc6..8fc463e 100644 --- a/src/main/java/org/violetmoon/zeta/registry/ZetaRegistry.java +++ b/src/main/java/org/violetmoon/zeta/registry/ZetaRegistry.java @@ -6,10 +6,11 @@ import java.util.IdentityHashMap; import java.util.List; import java.util.Map; -import java.util.function.BiConsumer; +import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; +import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Nullable; import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.item.ZetaBlockItem; @@ -141,14 +142,45 @@ public void clearDeferCache(ResourceLocation resourceLocation) { defers.removeAll(resourceLocation); } - public void finalizeBlockColors(BiConsumer consumer) { - blocksToColorProviderName.forEach(consumer); - blocksToColorProviderName.clear(); + @ApiStatus.Internal + public void assignBlockColor(String name, Consumer regFunc) { + boolean success = false; + var iterator = blocksToColorProviderName.entrySet().iterator(); + while(iterator.hasNext()) { + var entry = iterator.next(); + if(entry.getValue().equals(name)) { + success = true; + regFunc.accept(entry.getKey()); + iterator.remove(); + } + } + if (!success) + z.log.error("Unknown block color creator {} used on block", name); } - public void finalizeItemColors(BiConsumer consumer) { - itemsToColorProviderName.forEach(consumer); - itemsToColorProviderName.clear(); + @ApiStatus.Internal + public void assignItemColor(String name, Consumer regFunc) { + boolean success = false; + var iterator = itemsToColorProviderName.entrySet().iterator(); + while(iterator.hasNext()) { + var entry = iterator.next(); + if(entry.getValue().equals(name)) { + success = true; + regFunc.accept(entry.getKey()); + iterator.remove(); + } + } + if (!success) + z.log.error("Unknown item color creator {} used on item", name); + } + + @ApiStatus.Internal + public void validateColorsProviders(){ + if(!blocksToColorProviderName.isEmpty()) + z.log.error("Block color providers {} were not assigned to any blocks", blocksToColorProviderName.values()); + if(!itemsToColorProviderName.isEmpty()) + z.log.error("Item color providers {} were not assigned to any items", itemsToColorProviderName.values()); + } /// performing registration (dynamic registry jank - for registering ConfiguredFeature etc through code) /// diff --git a/src/main/java/org/violetmoon/zeta/util/handler/RecipeCrawlHandler.java b/src/main/java/org/violetmoon/zeta/util/handler/RecipeCrawlHandler.java index ff0784e..48fe47c 100644 --- a/src/main/java/org/violetmoon/zeta/util/handler/RecipeCrawlHandler.java +++ b/src/main/java/org/violetmoon/zeta/util/handler/RecipeCrawlHandler.java @@ -15,6 +15,7 @@ import org.violetmoon.zeta.event.load.ZTagsUpdated; import org.violetmoon.zeta.event.play.ZRecipeCrawl; import org.violetmoon.zeta.event.play.ZServerTick; +import org.violetmoon.zeta.mod.ZetaMod; import org.violetmoon.zeta.util.zetalist.ZetaList; import com.google.common.collect.HashMultimap; @@ -34,6 +35,7 @@ import net.minecraft.world.item.crafting.RecipeManager; import net.minecraft.world.item.crafting.ShapedRecipe; import net.minecraft.world.item.crafting.ShapelessRecipe; +import org.violetmoon.zetaimplforge.event.play.ForgeZRecipeCrawl; @ApiStatus.Internal public class RecipeCrawlHandler { @@ -47,7 +49,7 @@ public class RecipeCrawlHandler { private static boolean needsCrawl = false; private static boolean mayCrawl = false; - @LoadEvent + @PlayEvent public static void addListener(ZAddReloadListener event) { event.addListener(new SimplePreparableReloadListener() { @Override @@ -63,7 +65,7 @@ protected void apply(Void what, ResourceManager mgr, ProfilerFiller prof) { }); } - @LoadEvent + @PlayEvent public static void tagsHaveUpdated(ZTagsUpdated event) { mayCrawl = true; } @@ -74,7 +76,7 @@ private static void clear() { } private static void fire(IZetaPlayEvent event) { - ZetaList.INSTANCE.fireEvent(event); + ZetaMod.ZETA.playBus.fire(event); } @SuppressWarnings("ConstantValue") @@ -96,7 +98,8 @@ private static void load(RecipeManager manager, RegistryAccess access) { if (recipe.getResultItem(access) == null) throw new IllegalStateException("Recipe getResultItem is null"); - ZRecipeCrawl.Visit event; + boolean isMisc = false; + IZetaPlayEvent event; if (recipe instanceof ShapedRecipe sr) event = new ZRecipeCrawl.Visit.Shaped(sr, access); else if (recipe instanceof ShapelessRecipe sr) @@ -105,12 +108,13 @@ else if (recipe instanceof CustomRecipe cr) event = new ZRecipeCrawl.Visit.Custom(cr, access); else if (recipe instanceof AbstractCookingRecipe acr) event = new ZRecipeCrawl.Visit.Cooking(acr, access); - else + else { event = new ZRecipeCrawl.Visit.Misc(recipe, access); - + isMisc = true; + } //misc recipes could have custom logic that we cant make many assumptions on. For example FD cutting board recipes are lossy. //for instance a hanging sign can be cut into a plank. A hanging sign is magnetic but this does not mean planks are - if(!(event instanceof ZRecipeCrawl.Visit.Misc)) { + if(!isMisc) { vanillaRecipesToLazyDigest.add(recipe); } fire(event); diff --git a/src/main/java/org/violetmoon/zeta/util/zetalist/ZetaList.java b/src/main/java/org/violetmoon/zeta/util/zetalist/ZetaList.java index f59ac40..280b474 100644 --- a/src/main/java/org/violetmoon/zeta/util/zetalist/ZetaList.java +++ b/src/main/java/org/violetmoon/zeta/util/zetalist/ZetaList.java @@ -19,14 +19,6 @@ public void register(T z) { knownZetas.add(z); } - public void fireEvent(E event) { - knownZetas.forEach(z -> z.asZeta().playBus.fire(event)); - } - - public void fireEvent(E event, Class eventClass) { - knownZetas.forEach(z -> z.asZeta().playBus.fire(event, eventClass)); - } - public void fireEvent(E event) { knownZetas.forEach(z -> z.asZeta().loadBus.fire(event)); } diff --git a/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java b/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java index d60911a..8e007de 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java +++ b/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java @@ -9,18 +9,15 @@ import net.minecraft.world.level.block.FlowerPotBlock; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.phys.BlockHitResult; +import net.minecraftforge.client.event.RegisterColorHandlersEvent; import net.minecraftforge.common.ForgeConfigSpec; import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.event.AddReloadListenerEvent; import net.minecraftforge.event.AttachCapabilitiesEvent; -import net.minecraftforge.event.entity.EntityAttributeCreationEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.eventbus.api.Event; import net.minecraftforge.eventbus.api.EventPriority; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fml.ModList; -import net.minecraftforge.fml.event.IModBusEvent; -import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; import net.minecraftforge.fml.event.lifecycle.FMLLoadCompleteEvent; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import net.minecraftforge.fml.loading.FMLEnvironment; @@ -30,6 +27,9 @@ import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.block.ext.BlockExtensionFactory; import org.violetmoon.zeta.capability.ZetaCapabilityManager; +import org.violetmoon.zeta.client.ClientRegistryExtension; +import org.violetmoon.zeta.client.ZetaClient; +import org.violetmoon.zeta.client.event.load.*; import org.violetmoon.zeta.client.event.play.*; import org.violetmoon.zeta.config.IZetaConfigInternals; import org.violetmoon.zeta.config.SectionDefinition; @@ -45,9 +45,10 @@ import org.violetmoon.zeta.registry.*; import org.violetmoon.zeta.util.RaytracingUtil; import org.violetmoon.zeta.util.ZetaSide; -import org.violetmoon.zetaimplforge.api.GatherAdvancementModifiersEvent; +import org.violetmoon.zetaimplforge.api.ForgeZGatherAdvancementModifiers; import org.violetmoon.zetaimplforge.block.IForgeBlockBlockExtensions; import org.violetmoon.zetaimplforge.capability.ForgeCapabilityManager; +import org.violetmoon.zetaimplforge.client.event.load.*; import org.violetmoon.zetaimplforge.client.event.play.*; import org.violetmoon.zetaimplforge.config.ConfigEventDispatcher; import org.violetmoon.zetaimplforge.config.ForgeBackedConfig; @@ -77,10 +78,11 @@ public ForgeZeta(String modid, Logger log) { @Override protected ZetaEventBus createLoadBus() { - if (true) return new FabricZetaEventBus<>(LoadEvent.class, + if (false) return new FabricZetaEventBus<>(LoadEvent.class, IZetaLoadEvent.class, log); - // thanks forge and your dumb Event + IModEvent classes and hacky runtime genericst stuff. I cant get this to work + // thanks forge and your dumb Event + IModEvent classes and hacky runtime generic stuff. I cant get this to work + var bus = new ForgeZetaEventBus<>(LoadEvent.class, IZetaLoadEvent.class, log, FMLJavaModLoadingContext.get().getModEventBus(), Event.class); @@ -90,10 +92,27 @@ protected ZetaEventBus createLoadBus() { bus.registerSubClass(ZModulesReady.class, ForgeZModulesReady.class); bus.registerSubClass(ZRegister.class, ForgeZRegister.class); bus.registerSubClass(ZRegister.Post.class, ForgeZRegister.Post.class); - bus.registerSubClass(ZTagsUpdated.class, ForgeZTagsUpdated.class); bus.registerSubClass(ZConfigChanged.class, ForgeZConfigChange.class); bus.registerSubClass(ZLoadComplete.class, ForgeZLoadComplete.class); + // client ones again? + bus.registerSubClass(ZAddModels.class, ForgeZAddModels.class); + bus.registerSubClass(ZAddModelLayers.class, ForgeZAddModelLayers.class); + bus.registerSubClass(ZClientSetup.class, ForgeZClientSetup.class); + bus.registerSubClass(ZKeyMapping.class, ForgeZKeyMapping.class); + bus.registerSubClass(ZModel.RegisterGeometryLoaders.class, ForgeZModel.RegisterGeometryLoaders.class); + bus.registerSubClass(ZModel.RegisterAdditional.class, ForgeZModel.RegisterAdditional.class); + bus.registerSubClass(ZModel.BakingCompleted.class, ForgeZModel.BakingCompleted.class); + bus.registerSubClass(ZModel.ModifyBakingResult.class, ForgeZModel.ModifyBakingResult.class); + bus.registerSubClass(ZRegisterLayerDefinitions.class, ForgeZRegisterLayerDefinitions.class); + bus.registerSubClass(ZTooltipComponents.class, ForgeZTooltipComponents.class); + + bus.registerSubClass(ZAddBlockColorHandlers.class, ForgeZAddBlockColorHandlers.class, + (Function) inner -> + new ForgeZAddBlockColorHandlers(inner, this.registry)); + bus.registerSubClass(ZAddItemColorHandlers.class, ForgeZAddItemColorHandlers.class, + (Function) inner -> + new ForgeZAddItemColorHandlers(inner, this.registry)); return bus; } @@ -101,6 +120,7 @@ protected ZetaEventBus createLoadBus() { protected ForgeZetaEventBus createPlayBus() { var bus = new ForgeZetaEventBus<>(PlayEvent.class, IZetaPlayEvent.class, log, MinecraftForge.EVENT_BUS, Event.class); bus.registerSubClass(ZAnvilRepair.class, ForgeZAnvilRepair.class); + bus.registerSubClass(ZTagsUpdated.class, ForgeZTagsUpdated.class); bus.registerSubClass(ZBabyEntitySpawn.class, ForgeZBabyEntitySpawn.class); bus.registerSubClass(ZBlock.Break.class, ForgeZBlock.Break.class); bus.registerSubClass(ZBlock.EntityPlace.class, ForgeZBlock.EntityPlace.class); @@ -150,6 +170,9 @@ protected ZetaEventBus createLoadBus() { bus.registerSubClass(ZGatherAdditionalFlags.class, ForgeZGatherAdditionalFlags.class); bus.registerSubClass(ZServerTick.Start.class, ForgeZServerTick.Start.class); bus.registerSubClass(ZServerTick.End.class, ForgeZServerTick.End.class); + bus.registerSubClass(ZAddReloadListener.class, ForgeZAddReloadListener.class); + bus.registerSubClass(ZGatherAdvancementModifiers.class, ForgeZGatherAdvancementModifiers.class); + //Hmm client events here? maybe i should move them bus.registerSubClass(ZClientTick.class, ForgeZClientTick.class); @@ -160,7 +183,7 @@ protected ZetaEventBus createLoadBus() { bus.registerSubClass(ZInput.Key.class, ForgeZInput.Key.class); bus.registerSubClass(ZInputUpdate.class, ForgeZInputUpdate.class); bus.registerSubClass(ZRenderContainerScreen.class, ForgeZRenderContainerScreen.class); - bus.registerSubClass(ZRenderGuiOverlay.class, ForgeZRenderGuiOverlay.class); + //bus.registerSubClass(ZRenderGuiOverlay.class, ForgeZRenderGuiOverlay.class); bus.registerSubClass(ZRenderLiving.class, ForgeZRenderLiving.class); bus.registerSubClass(ZRenderPlayer.class, ForgeZRenderPlayer.class); bus.registerSubClass(ZRenderTick.class, ForgeZRenderTick.class); @@ -278,15 +301,6 @@ public boolean fireRightClickBlock(Player player, InteractionHand hand, BlockPos return MinecraftForge.EVENT_BUS.post(new PlayerInteractEvent.RightClickBlock(player, hand, pos, bhr)); } - //TODO: - @Override - public T fireExternalEvent(T impl) { - if (impl instanceof ZGatherAdvancementModifiers advancementModifiers) - MinecraftForge.EVENT_BUS.post(new GatherAdvancementModifiersEvent(this, advancementModifiers)); - - return impl; - } - @SuppressWarnings("duplicates") @Override public void start() { @@ -297,12 +311,8 @@ public void start() { modbus.addListener(ConfigEventDispatcher::configChanged); modbus.addListener(EventPriority.HIGHEST, this::registerHighest); - modbus.addListener(this::commonSetup); - modbus.addListener(this::loadComplete); - modbus.addListener(this::entityAttributeCreation); - //why is this load? - MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); + //MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); } private boolean registerDone = false; @@ -319,21 +329,9 @@ public void registerHighest(RegisterEvent e) { } - public void addReloadListener(AddReloadListenerEvent e) { - loadBus.fire(new ForgeZAddReloadListener(e), ZAddReloadListener.class); - } - - public void commonSetup(FMLCommonSetupEvent e) { - loadBus.fire(new ForgeZCommonSetup(e), ZCommonSetup.class); - } - - public void loadComplete(FMLLoadCompleteEvent e) { - loadBus.fire(new ForgeZLoadComplete(e), ZLoadComplete.class); - } - - public void entityAttributeCreation(EntityAttributeCreationEvent e) { - loadBus.fire(new ForgeZEntityAttributeCreation(e), ZEntityAttributeCreation.class); - } + //public void addReloadListener(AddReloadListenerEvent e) { + // loadBus.fire(new ForgeZAddReloadListener(e), ZAddReloadListener.class); + //} public static ZResult from(Event.Result r) { return switch (r) { diff --git a/src/main/java/org/violetmoon/zetaimplforge/api/GatherAdvancementModifiersEvent.java b/src/main/java/org/violetmoon/zetaimplforge/api/ForgeZGatherAdvancementModifiers.java similarity index 54% rename from src/main/java/org/violetmoon/zetaimplforge/api/GatherAdvancementModifiersEvent.java rename to src/main/java/org/violetmoon/zetaimplforge/api/ForgeZGatherAdvancementModifiers.java index e3630bb..3c27bff 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/api/GatherAdvancementModifiersEvent.java +++ b/src/main/java/org/violetmoon/zetaimplforge/api/ForgeZGatherAdvancementModifiers.java @@ -7,31 +7,21 @@ import net.minecraftforge.eventbus.api.Event; -public class GatherAdvancementModifiersEvent extends Event implements ZGatherAdvancementModifiers { - private final Zeta zeta; - private final ZGatherAdvancementModifiers inner; +public class ForgeZGatherAdvancementModifiers extends Event implements ZGatherAdvancementModifiers { + private final ZGatherAdvancementModifiers wrapped; - public GatherAdvancementModifiersEvent(Zeta zeta, ZGatherAdvancementModifiers inner) { - this.zeta = zeta; - this.inner = inner; - } - - public Zeta getZeta() { - return zeta; - } - - public String getModid() { - return zeta.modid; + public ForgeZGatherAdvancementModifiers(ZGatherAdvancementModifiers inner) { + this.wrapped = inner; } @Override public void register(IAdvancementModifier modifier) { - inner.register(modifier); + wrapped.register(modifier); } @Override public IAdvancementModifierDelegate getDelegate() { - return inner.getDelegate(); + return wrapped.getDelegate(); } //Note there are a ton of default methods available in ZGatherAdvancementModifiers for you to call. diff --git a/src/main/java/org/violetmoon/zetaimplforge/client/ForgeZetaClient.java b/src/main/java/org/violetmoon/zetaimplforge/client/ForgeZetaClient.java index d1b29b4..9f0deef 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/client/ForgeZetaClient.java +++ b/src/main/java/org/violetmoon/zetaimplforge/client/ForgeZetaClient.java @@ -1,5 +1,6 @@ package org.violetmoon.zetaimplforge.client; +import net.minecraftforge.client.gui.overlay.NamedGuiOverlay; import org.jetbrains.annotations.Nullable; import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.client.ClientRegistryExtension; @@ -139,116 +140,12 @@ public RegistryAccess hackilyGetCurrentClientLevelRegistryAccess() { public void start() { IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus(); - bus.addListener(this::registerBlockColors); - bus.addListener(this::registerItemColors); - bus.addListener(this::clientSetup); - bus.addListener(this::registerReloadListeners); - bus.addListener(this::modelModifyBakingResult); - bus.addListener(this::modelBakingCompleted); - bus.addListener(this::modelRegisterAdditional); - bus.addListener(this::modelRegisterGeometryLoaders); - bus.addListener(this::modelLayers); - bus.addListener(this::registerKeybinds); - bus.addListener(this::registerAdditionalModels); - bus.addListener(this::registerClientTooltipComponentFactories); - bus.addListener(this::registerLayerDefinitions); - - MinecraftForge.EVENT_BUS.addListener(this::renderTick); MinecraftForge.EVENT_BUS.addListener(this::clientTick); - MinecraftForge.EVENT_BUS.addListener(this::inputMouseButton); - MinecraftForge.EVENT_BUS.addListener(this::inputKey); - MinecraftForge.EVENT_BUS.addListener(this::screenshot); - MinecraftForge.EVENT_BUS.addListener(this::movementInputUpdate); - MinecraftForge.EVENT_BUS.addListener(this::renderBlockHighlight); - MinecraftForge.EVENT_BUS.addListener(this::gatherTooltipComponents); - MinecraftForge.EVENT_BUS.addListener(this::renderContainerScreenForeground); - MinecraftForge.EVENT_BUS.addListener(this::renderContainerScreenBackground); MinecraftForge.EVENT_BUS.addListener(this::renderGameOverlayNeitherPreNorPost); MinecraftForge.EVENT_BUS.addListener(this::renderGuiOverlayPre); MinecraftForge.EVENT_BUS.addListener(this::renderGuiOverlayPost); - MinecraftForge.EVENT_BUS.addListener(this::renderPlayerPre); - MinecraftForge.EVENT_BUS.addListener(this::renderPlayerPost); - MinecraftForge.EVENT_BUS.addListener(EventPriority.HIGHEST, this::renderLivingPreHighest); - MinecraftForge.EVENT_BUS.addListener(EventPriority.LOWEST, this::renderLivingPostLowest); - MinecraftForge.EVENT_BUS.addListener(this::renderTooltipGatherComponents); - MinecraftForge.EVENT_BUS.addListener(this::renderTooltipGatherComponentsLow); - - MinecraftForge.EVENT_BUS.addListener(this::screenInitPre); - MinecraftForge.EVENT_BUS.addListener(this::screenInitPost); - MinecraftForge.EVENT_BUS.addListener(this::screenRenderPre); - MinecraftForge.EVENT_BUS.addListener(this::screenRenderPost); - MinecraftForge.EVENT_BUS.addListener(this::screenMouseButtonPressedPre); - MinecraftForge.EVENT_BUS.addListener(this::screenMouseButtonPressedPost); - MinecraftForge.EVENT_BUS.addListener(this::screenMouseScrolledPre); - MinecraftForge.EVENT_BUS.addListener(this::screenMouseScrolledPost); - MinecraftForge.EVENT_BUS.addListener(this::screenKeyPressedPre); - MinecraftForge.EVENT_BUS.addListener(this::screenKeyPressedPost); - MinecraftForge.EVENT_BUS.addListener(this::screenCharacterTypedPre); - MinecraftForge.EVENT_BUS.addListener(this::screenCharacterTypedPost); - MinecraftForge.EVENT_BUS.addListener(this::screenOpening); - } - - public void registerBlockColors(RegisterColorHandlersEvent.Block event) { - ZAddBlockColorHandlers e = loadBus.fire(new ForgeZAddBlockColorHandlers(event), ZAddBlockColorHandlers.class); - loadBus.fire(e.makePostEvent(), ZAddBlockColorHandlers.Post.class); - } - - public void registerItemColors(RegisterColorHandlersEvent.Item event) { - ZAddItemColorHandlers e = loadBus.fire(new ForgeZAddItemColorHandlers(event), ZAddItemColorHandlers.class); - loadBus.fire(e.makePostEvent(), ZAddItemColorHandlers.Post.class); - } - - public void clientSetup(FMLClientSetupEvent event) { - loadBus.fire(new ForgeZClientSetup(event), ZClientSetup.class); - } - - public void registerReloadListeners(RegisterClientReloadListenersEvent event) { - loadBus.fire(new ZRegisterReloadListeners(event::registerReloadListener), ZRegisterReloadListeners.class); - } - - public void modelModifyBakingResult(ModelEvent.ModifyBakingResult e) { - loadBus.fire(new ForgeZModel.ModifyBakingResult(e), ZModel.ModifyBakingResult.class); - } - - public void modelBakingCompleted(ModelEvent.BakingCompleted e) { - loadBus.fire(new ForgeZModel.BakingCompleted(e), ZModel.BakingCompleted.class); - } - - public void modelRegisterAdditional(ModelEvent.RegisterAdditional e) { - loadBus.fire(new ForgeZModel.RegisterAdditional(e), ZModel.RegisterAdditional.class); - } - - public void modelRegisterGeometryLoaders(ModelEvent.RegisterGeometryLoaders e) { - loadBus.fire(new ForgeZModel.RegisterGeometryLoaders(e), ZModel.RegisterGeometryLoaders.class); - } - - public void modelLayers(EntityRenderersEvent.AddLayers event) { - loadBus.fire(new ForgeZAddModelLayers(event), ZAddModelLayers.class); - } - - public void registerKeybinds(RegisterKeyMappingsEvent event) { - loadBus.fire(new ForgeZKeyMapping(event), ZKeyMapping.class); - } - - public void registerAdditionalModels(ModelEvent.RegisterAdditional event) { - loadBus.fire(new ForgeZAddModels(event), ZAddModels.class); - } - - public void registerClientTooltipComponentFactories(RegisterClientTooltipComponentFactoriesEvent event) { - loadBus.fire(new ForgeZTooltipComponents(event), ZTooltipComponents.class); - } - - public void registerLayerDefinitions(EntityRenderersEvent.RegisterLayerDefinitions e) { - loadBus.fire(new ForgeZRegisterLayerDefinitions(e), ZRegisterLayerDefinitions.class); - } - - //TODO: move ticker stuff out of forge event handlers, subscribe to them from zeta - // Also these events are a mess lol; sometimes there's 2 start/end events, sometimes there's - // one event with multiple Phases... bad - public void renderTick(TickEvent.RenderTickEvent e) { - playBus.fire(new ForgeZRenderTick(e), ZRenderTick.class); } boolean clientTicked = false; @@ -261,37 +158,6 @@ public void clientTick(TickEvent.ClientTickEvent e) { playBus.fire(new ForgeZClientTick(e), ZClientTick.class); } - public void inputMouseButton(InputEvent.MouseButton e) { - playBus.fire(new ForgeZInput.MouseButton(e), ZInput.MouseButton.class); - } - - public void inputKey(InputEvent.Key e) { - playBus.fire(new ForgeZInput.Key(e), ZInput.Key.class); - } - - public void screenshot(ScreenshotEvent e) { - playBus.fire(new ZScreenshot()); - } - - public void movementInputUpdate(MovementInputUpdateEvent e) { - playBus.fire(new ForgeZInputUpdate(e), ZInputUpdate.class); - } - - public void renderBlockHighlight(RenderHighlightEvent.Block e) { - playBus.fire(new ForgeZHighlightBlock(e), ZHighlightBlock.class); - } - - public void gatherTooltipComponents(RenderTooltipEvent.GatherComponents e) { - playBus.fire(new ForgeZGatherTooltipComponents(e), ZGatherTooltipComponents.class); - } - - public void renderContainerScreenForeground(ContainerScreenEvent.Render.Foreground e) { - playBus.fire(new ForgeZRenderContainerScreen.Foreground(e), ZRenderContainerScreen.Foreground.class); - } - - public void renderContainerScreenBackground(ContainerScreenEvent.Render.Background e) { - playBus.fire(new ForgeZRenderContainerScreen.Background(e), ZRenderContainerScreen.Background.class); - } //TODO: This probably should have been a PRE/POST event (just copying quark here) public void renderGameOverlayNeitherPreNorPost(RenderGuiOverlayEvent e) { @@ -319,95 +185,21 @@ else if (e.getOverlay() == VanillaGuiOverlay.CHAT_PANEL.type()) } public void renderGuiOverlayPost(RenderGuiOverlayEvent.Post e) { - if (e.getOverlay() == VanillaGuiOverlay.HOTBAR.type()) + NamedGuiOverlay overlay = e.getOverlay(); + if (overlay == VanillaGuiOverlay.HOTBAR.type()) playBus.fire(new ForgeZRenderGuiOverlay.Hotbar.Post(e), ZRenderGuiOverlay.Hotbar.Post.class); - else if (e.getOverlay() == VanillaGuiOverlay.CROSSHAIR.type()) + else if (overlay == VanillaGuiOverlay.CROSSHAIR.type()) playBus.fire(new ForgeZRenderGuiOverlay.Crosshair.Post(e), ZRenderGuiOverlay.Crosshair.Post.class); - else if (e.getOverlay() == VanillaGuiOverlay.PLAYER_HEALTH.type()) + else if (overlay == VanillaGuiOverlay.PLAYER_HEALTH.type()) playBus.fire(new ForgeZRenderGuiOverlay.PlayerHealth.Post(e), ZRenderGuiOverlay.PlayerHealth.Post.class); - else if (e.getOverlay() == VanillaGuiOverlay.ARMOR_LEVEL.type()) + else if (overlay == VanillaGuiOverlay.ARMOR_LEVEL.type()) playBus.fire(new ForgeZRenderGuiOverlay.ArmorLevel.Post(e), ZRenderGuiOverlay.ArmorLevel.Post.class); - else if (e.getOverlay() == VanillaGuiOverlay.DEBUG_TEXT.type()) + else if (overlay == VanillaGuiOverlay.DEBUG_TEXT.type()) playBus.fire(new ForgeZRenderGuiOverlay.DebugText.Post(e), ZRenderGuiOverlay.DebugText.Post.class); - else if (e.getOverlay() == VanillaGuiOverlay.POTION_ICONS.type()) + else if (overlay == VanillaGuiOverlay.POTION_ICONS.type()) playBus.fire(new ForgeZRenderGuiOverlay.PotionIcons.Post(e), ZRenderGuiOverlay.PotionIcons.Post.class); - else if (e.getOverlay() == VanillaGuiOverlay.CHAT_PANEL.type()) + else if (overlay == VanillaGuiOverlay.CHAT_PANEL.type()) playBus.fire(new ForgeZRenderGuiOverlay.ChatPanel.Post(e), ZRenderGuiOverlay.ChatPanel.Post.class); } - public void renderPlayerPre(RenderPlayerEvent.Pre e) { - playBus.fire(new ForgeZRenderPlayer.Pre(e), ZRenderPlayer.Pre.class); - } - - public void renderPlayerPost(RenderPlayerEvent.Post e) { - playBus.fire(new ForgeZRenderPlayer.Post(e), ZRenderPlayer.Post.class); - } - - public void renderLivingPreHighest(RenderLivingEvent.Pre e) { - playBus.fire(new ForgeZRenderLiving.PreHighest(e), ZRenderLiving.PreHighest.class); - } - - public void renderLivingPostLowest(RenderLivingEvent.Post e) { - playBus.fire(new ForgeZRenderLiving.PostLowest(e), ZRenderLiving.PostLowest.class); - } - - public void renderTooltipGatherComponents(RenderTooltipEvent.GatherComponents e) { - playBus.fire(new ForgeZRenderTooltip.GatherComponents(e), ZRenderTooltip.GatherComponents.class); - } - - public void renderTooltipGatherComponentsLow(RenderTooltipEvent.GatherComponents e) { - playBus.fire(new ForgeZRenderTooltip.GatherComponents.Low(e), ZRenderTooltip.GatherComponents.Low.class); - } - - public void screenInitPre(ScreenEvent.Init.Pre e) { - playBus.fire(new ForgeZScreen.Init.Pre(e), ZScreen.Init.Pre.class); - } - - public void screenInitPost(ScreenEvent.Init.Post e) { - playBus.fire(new ForgeZScreen.Init.Post(e), ZScreen.Init.Post.class); - } - - public void screenRenderPre(ScreenEvent.Render.Pre e) { - playBus.fire(new ForgeZScreen.Render.Pre(e), ZScreen.Render.Pre.class); - } - - public void screenRenderPost(ScreenEvent.Render.Post e) { - playBus.fire(new ForgeZScreen.Render.Post(e), ZScreen.Render.Post.class); - } - - public void screenMouseButtonPressedPre(ScreenEvent.MouseButtonPressed.Pre e) { - playBus.fire(new ForgeZScreen.MouseButtonPressed.Pre(e), ZScreen.MouseButtonPressed.Pre.class); - } - - public void screenMouseButtonPressedPost(ScreenEvent.MouseButtonPressed.Post e) { - playBus.fire(new ForgeZScreen.MouseButtonPressed.Post(e), ZScreen.MouseButtonPressed.Post.class); - } - - public void screenMouseScrolledPre(ScreenEvent.MouseScrolled.Pre e) { - playBus.fire(new ForgeZScreen.MouseScrolled.Pre(e), ZScreen.MouseScrolled.Pre.class); - } - - public void screenMouseScrolledPost(ScreenEvent.MouseScrolled.Post e) { - playBus.fire(new ForgeZScreen.MouseScrolled.Post(e), ZScreen.MouseScrolled.Post.class); - } - - public void screenKeyPressedPre(ScreenEvent.KeyPressed.Pre e) { - playBus.fire(new ForgeZScreen.KeyPressed.Pre(e), ZScreen.KeyPressed.Pre.class); - } - - public void screenKeyPressedPost(ScreenEvent.KeyPressed.Post e) { - playBus.fire(new ForgeZScreen.KeyPressed.Post(e), ZScreen.KeyPressed.Post.class); - } - - public void screenCharacterTypedPre(ScreenEvent.CharacterTyped.Pre e) { - playBus.fire(new ForgeZScreen.CharacterTyped.Pre(e), ZScreen.CharacterTyped.Pre.class); - } - - public void screenCharacterTypedPost(ScreenEvent.CharacterTyped.Post e) { - playBus.fire(new ForgeZScreen.CharacterTyped.Post(e), ZScreen.CharacterTyped.Post.class); - } - - public void screenOpening(ScreenEvent.Opening e) { - playBus.fire(new ForgeZScreen.Opening(e), ZScreen.Opening.class); - } } diff --git a/src/main/java/org/violetmoon/zetaimplforge/client/event/load/ForgeZAddBlockColorHandlers.java b/src/main/java/org/violetmoon/zetaimplforge/client/event/load/ForgeZAddBlockColorHandlers.java index 8c705d3..09c2323 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/client/event/load/ForgeZAddBlockColorHandlers.java +++ b/src/main/java/org/violetmoon/zetaimplforge/client/event/load/ForgeZAddBlockColorHandlers.java @@ -1,58 +1,40 @@ package org.violetmoon.zetaimplforge.client.event.load; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; - -import org.violetmoon.zeta.client.event.load.ZAddBlockColorHandlers; - import net.minecraft.client.color.block.BlockColor; import net.minecraft.client.color.block.BlockColors; import net.minecraft.world.level.block.Block; import net.minecraftforge.client.event.RegisterColorHandlersEvent; +import org.violetmoon.zeta.client.event.load.ZAddBlockColorHandlers; +import org.violetmoon.zeta.registry.ZetaRegistry; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; public class ForgeZAddBlockColorHandlers implements ZAddBlockColorHandlers { - protected final RegisterColorHandlersEvent.Block e; - protected final Map> namedBlockColors; - - public ForgeZAddBlockColorHandlers(RegisterColorHandlersEvent.Block e) { - this(e, new HashMap<>()); - } - - protected ForgeZAddBlockColorHandlers(RegisterColorHandlersEvent.Block e, Map> namedBlockColors) { - this.e = e; - this.namedBlockColors = namedBlockColors; - } - - @Override - public void register(BlockColor blockColor, Block... blocks) { - e.register(blockColor, blocks); - } - - @Override - public void registerNamed(Function c, String... names) { - for(String name : names) - namedBlockColors.put(name, c); - } - - @Override - public BlockColors getBlockColors() { - return e.getBlockColors(); - } - - @Override - public ZAddBlockColorHandlers.Post makePostEvent() { - return new Post(e, namedBlockColors); - } - - public static class Post extends ForgeZAddBlockColorHandlers implements ZAddBlockColorHandlers.Post { - public Post(RegisterColorHandlersEvent.Block e, Map> namedBlockColors) { - super(e, namedBlockColors); - } - - @Override - public Map> getNamedBlockColors() { - return namedBlockColors; - } - } + protected final RegisterColorHandlersEvent.Block e; + private final ZetaRegistry zetaRegistry; + + public ForgeZAddBlockColorHandlers(RegisterColorHandlersEvent.Block e, ZetaRegistry zetaRegistry) { + this.e = e; + this.zetaRegistry = zetaRegistry; + } + + @Override + public void register(BlockColor blockColor, Block... blocks) { + e.register(blockColor, blocks); + } + + @Override + public void registerNamed(Function c, String... names) { + for (String name : names) { + zetaRegistry.assignBlockColor(name, b -> register(c.apply(b), b)); + } + } + + @Override + public BlockColors getBlockColors() { + return e.getBlockColors(); + } + } diff --git a/src/main/java/org/violetmoon/zetaimplforge/client/event/load/ForgeZAddItemColorHandlers.java b/src/main/java/org/violetmoon/zetaimplforge/client/event/load/ForgeZAddItemColorHandlers.java index de05e1c..4ea1843 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/client/event/load/ForgeZAddItemColorHandlers.java +++ b/src/main/java/org/violetmoon/zetaimplforge/client/event/load/ForgeZAddItemColorHandlers.java @@ -11,18 +11,16 @@ import net.minecraft.world.item.Item; import net.minecraft.world.level.ItemLike; import net.minecraftforge.client.event.RegisterColorHandlersEvent; +import org.violetmoon.zeta.registry.ZetaRegistry; public class ForgeZAddItemColorHandlers implements ZAddItemColorHandlers { protected final RegisterColorHandlersEvent.Item e; - protected final Map> namedItemColors; + protected final Map> namedItemColors = new HashMap<>(); + private final ZetaRegistry zetaRegistry; - public ForgeZAddItemColorHandlers(RegisterColorHandlersEvent.Item e) { - this(e, new HashMap<>()); - } - - public ForgeZAddItemColorHandlers(RegisterColorHandlersEvent.Item e, Map> namedItemColors) { + public ForgeZAddItemColorHandlers(RegisterColorHandlersEvent.Item e, ZetaRegistry zetaRegistry) { this.e = e; - this.namedItemColors = namedItemColors; + this.zetaRegistry = zetaRegistry; } @Override @@ -32,8 +30,9 @@ public void register(ItemColor c, ItemLike... items) { @Override public void registerNamed(Function c, String... names) { - for(String name : names) - namedItemColors.put(name, c); + for (String name : names) { + zetaRegistry.assignItemColor(name, b -> register(c.apply(b), b)); + } } @Override @@ -41,19 +40,4 @@ public ItemColors getItemColors() { return e.getItemColors(); } - @Override - public Post makePostEvent() { - return new Post(e, namedItemColors); - } - - public static class Post extends ForgeZAddItemColorHandlers implements ZAddItemColorHandlers.Post { - public Post(RegisterColorHandlersEvent.Item e, Map> namedItemColors) { - super(e, namedItemColors); - } - - @Override - public Map> getNamedItemColors() { - return namedItemColors; - } - } } diff --git a/src/main/java/org/violetmoon/zetaimplforge/client/event/load/ForgeZModel.java b/src/main/java/org/violetmoon/zetaimplforge/client/event/load/ForgeZModel.java index 3ad2b97..b897be6 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/client/event/load/ForgeZModel.java +++ b/src/main/java/org/violetmoon/zetaimplforge/client/event/load/ForgeZModel.java @@ -12,6 +12,7 @@ import net.minecraftforge.client.model.geometry.IGeometryLoader; public class ForgeZModel implements ZModel { + public static class ModifyBakingResult extends ForgeZModel implements ZModel.ModifyBakingResult { private final ModelEvent.ModifyBakingResult e; diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/play/loading/ForgeZGatherAdditionalFlags.java b/src/main/java/org/violetmoon/zetaimplforge/event/play/loading/ForgeZGatherAdditionalFlags.java index 224fd4a..89ea34b 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/play/loading/ForgeZGatherAdditionalFlags.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/play/loading/ForgeZGatherAdditionalFlags.java @@ -5,14 +5,15 @@ import org.violetmoon.zeta.event.play.loading.ZGatherAdditionalFlags; public class ForgeZGatherAdditionalFlags extends Event implements ZGatherAdditionalFlags { - private final ConfigFlagManager flagManager; - public ForgeZGatherAdditionalFlags(ConfigFlagManager flagManager) { - this.flagManager = flagManager; + private final ZGatherAdditionalFlags wrapped; + + public ForgeZGatherAdditionalFlags(ZGatherAdditionalFlags wrapped) { + this.wrapped = wrapped; } @Override public ConfigFlagManager flagManager() { - return flagManager; + return wrapped.flagManager(); } } diff --git a/src/main/java/org/violetmoon/zetaimplforge/mixin/mixins/client/GameRenderMixin.java b/src/main/java/org/violetmoon/zetaimplforge/mixin/mixins/client/GameRenderMixin.java index b582d40..59086e1 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/mixin/mixins/client/GameRenderMixin.java +++ b/src/main/java/org/violetmoon/zetaimplforge/mixin/mixins/client/GameRenderMixin.java @@ -5,6 +5,7 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.violetmoon.zeta.client.event.play.ZEarlyRender; +import org.violetmoon.zeta.mod.ZetaMod; import org.violetmoon.zeta.util.zetalist.ZetaClientList; import org.violetmoon.zetaimplforge.client.event.play.ForgeZEarlyRender; @@ -12,8 +13,9 @@ @Mixin(GameRenderer.class) public class GameRenderMixin { + @Inject(method = "render", at = @At(target = "Lnet/minecraft/util/profiling/ProfilerFiller;popPush(Ljava/lang/String;)V", value = "INVOKE", shift = At.Shift.AFTER)) private void quark$renderEvent(float v, long l, boolean b, CallbackInfo ci) { - ZetaClientList.INSTANCE.fireEvent(new ForgeZEarlyRender(), ZEarlyRender.class); + ZetaMod.ZETA.playBus.fire(new ForgeZEarlyRender(), ZEarlyRender.class); } } From 9fad6d1d90195a5d7280f58bc99e5d20b843892b Mon Sep 17 00:00:00 2001 From: MehVahdJukaar Date: Wed, 31 Jul 2024 16:08:59 +0200 Subject: [PATCH 09/22] zeta proxy refactor --- .../violetmoon/zeta/client/ZetaClient.java | 2 - .../violetmoon/zeta/config/ConfigManager.java | 364 +++++++++--------- .../zeta/event/bus/ForgeZetaEventBus.java | 116 ++++-- .../zeta/event/bus/ZetaEventBus.java | 2 +- .../violetmoon/zeta/mod/ZetaClientProxy.java | 26 -- .../java/org/violetmoon/zeta/mod/ZetaMod.java | 10 +- .../org/violetmoon/zeta/mod/ZetaModProxy.java | 32 -- .../zeta/util/handler/RecipeCrawlHandler.java | 6 + .../zeta/util/zetalist/ZetaList.java | 5 +- .../violetmoon/zetaimplforge/ForgeZeta.java | 15 +- .../zetaimplforge/client/ForgeZetaClient.java | 65 ---- .../event/play/ForgeZRenderGuiOverlay.java | 3 +- .../zetaimplforge/event/NotAForgeWrapper.java | 9 + .../zetaimplforge/mod/ZetaModClientProxy.java | 80 ++++ ...aForgeMod.java => ZetaModCommonProxy.java} | 56 +-- .../zetaimplforge/mod/ZetaModForge.java | 24 ++ 16 files changed, 417 insertions(+), 398 deletions(-) delete mode 100644 src/main/java/org/violetmoon/zeta/mod/ZetaClientProxy.java delete mode 100644 src/main/java/org/violetmoon/zeta/mod/ZetaModProxy.java create mode 100644 src/main/java/org/violetmoon/zetaimplforge/event/NotAForgeWrapper.java create mode 100644 src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModClientProxy.java rename src/main/java/org/violetmoon/zetaimplforge/mod/{ZetaForgeMod.java => ZetaModCommonProxy.java} (51%) create mode 100644 src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModForge.java diff --git a/src/main/java/org/violetmoon/zeta/client/ZetaClient.java b/src/main/java/org/violetmoon/zeta/client/ZetaClient.java index 83a6328..eea0198 100644 --- a/src/main/java/org/violetmoon/zeta/client/ZetaClient.java +++ b/src/main/java/org/violetmoon/zeta/client/ZetaClient.java @@ -87,8 +87,6 @@ public void sendToServer(IZetaMessage msg) { // The name is unwieldy on purpose, usages of this function should stick out. public abstract @Nullable RegistryAccess hackilyGetCurrentClientLevelRegistryAccess(); - public abstract void start(); - @Override public Zeta asZeta() { return zeta; diff --git a/src/main/java/org/violetmoon/zeta/config/ConfigManager.java b/src/main/java/org/violetmoon/zeta/config/ConfigManager.java index 0783265..395551e 100644 --- a/src/main/java/org/violetmoon/zeta/config/ConfigManager.java +++ b/src/main/java/org/violetmoon/zeta/config/ConfigManager.java @@ -1,196 +1,190 @@ package org.violetmoon.zeta.config; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Consumer; - import org.jetbrains.annotations.Nullable; import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.event.play.loading.ZGatherAdditionalFlags; import org.violetmoon.zeta.module.ZetaCategory; import org.violetmoon.zeta.module.ZetaModule; import org.violetmoon.zeta.module.ZetaModuleManager; -import org.violetmoon.zetaimplforge.event.play.loading.ForgeZGatherAdditionalFlags; + +import java.util.*; +import java.util.function.Consumer; public class ConfigManager { - private final Zeta z; - private final ConfigFlagManager cfm; - private final SectionDefinition rootConfig; - - //for updating the values of @Config annotations to match the current state of the config - // and other "listening for config load" purposes - private final List> databindings = new ArrayList<>(); - private Consumer onConfigReloadJEI; - - //ummmmmmm i think my abstraction isn't very good - private final @Nullable SectionDefinition generalSection; - private final Map categoriesToSections = new HashMap<>(); - - private final Map> categoryEnabledOptions = new HashMap<>(); - private final Map> ignoreAntiOverlapOptions = new HashMap<>(); - private final Map> moduleEnabledOptions = new HashMap<>(); - - //state - private final Set enabledCategories = new HashSet<>(); - - public ConfigManager(Zeta z, Object rootPojo) { - this.z = z; - this.cfm = new ConfigFlagManager(z); - ZetaModuleManager modules = z.modules; - - //all modules are enabled by default - enabledCategories.addAll(modules.getCategories()); - - SectionDefinition.Builder rootConfigBuilder = new SectionDefinition.Builder().name(""); - - // "general" section - if(rootPojo == null) - generalSection = null; - else { - //TODO: where to put this lol - z.loadBus.subscribe(rootPojo).subscribe(rootPojo.getClass()); - z.playBus.subscribe(rootPojo).subscribe(rootPojo.getClass()); - - generalSection = rootConfigBuilder.addSubsection(general -> ConfigObjectMapper.readInto(general.name("general"), rootPojo, databindings, cfm)); - } - - // "categories" section, holding the category enablement options - rootConfigBuilder.addSubsection(categories -> { - categories.name("categories"); - for(ZetaCategory category : modules.getInhabitedCategories()) - categoryEnabledOptions.put(category, categories.addValue(b -> b.name(category.name).defaultValue(true))); - }); - - // per-category options - for(ZetaCategory category : modules.getInhabitedCategories()) { - categoriesToSections.put(category, rootConfigBuilder.addSubsection(categorySectionBuilder -> { - categorySectionBuilder.name(category.name); - for(ZetaModule module : modules.modulesInCategory(category)) { - // module flag - cfm.putModuleFlag(module); - - // module enablement option - moduleEnabledOptions.put(module, categorySectionBuilder.addValue(moduleEnabledOptionBuilder -> moduleEnabledOptionBuilder - .name(module.displayName) - .englishDisplayName(module.displayName) - .comment(module.description) - .defaultValue(module.enabledByDefault))); - - // per-module options - categorySectionBuilder.addSubsection(moduleSectionBuilder -> { - moduleSectionBuilder - .name(module.lowercaseName) - .englishDisplayName(module.displayName) - .comment(module.description); - - // @Config options - ConfigObjectMapper.readInto(moduleSectionBuilder, module, databindings, cfm); - - // anti overlap option - if(!module.antiOverlap.isEmpty()) { - ignoreAntiOverlapOptions.put(module, moduleSectionBuilder.addValue(antiOverlapOptionBuilder -> { - antiOverlapOptionBuilder.name("Ignore Anti Overlap") - .comment("This feature disables itself if any of the following mods are loaded:") - .defaultValue(false); - - for(String modid : module.antiOverlap) - antiOverlapOptionBuilder.comment(" - " + modid); - - antiOverlapOptionBuilder.comment("This is done to prevent content overlap.") - .comment("You can turn this on to force the feature to be loaded even if the above mods are also loaded."); - })); - } - }); - } - })); - } - - //grab any extra flags - z.playBus.fire(() -> cfm,ZGatherAdditionalFlags.class); - - //managing module enablement in one go - //adding this to the *start* of the list so modules are enabled before anything else runs - //Its Janky ! - databindings.add(0, i -> { - categoryEnabledOptions.forEach((category, option) -> setCategoryEnabled(category, i.get(option))); - ignoreAntiOverlapOptions.forEach((module, option) -> module.ignoreAntiOverlap = !ZetaGeneralConfig.useAntiOverlap || i.get(option)); - moduleEnabledOptions.forEach((module, option) -> { - setModuleEnabled(module, i.get(option)); - cfm.putModuleFlag(module); - }); - - //update extra flags - z.playBus.fire(() -> cfm,ZGatherAdditionalFlags.class); - }); - - this.rootConfig = rootConfigBuilder.build(); - rootConfig.finish(); - } - - public SectionDefinition getRootConfig() { - return rootConfig; - } - - // mapping between internal and external representations of the config (??????) - - public @Nullable SectionDefinition getGeneralSection() { - return generalSection; - } - - public SectionDefinition getCategorySection(ZetaCategory cat) { - return categoriesToSections.get(cat); - } - - public ValueDefinition getCategoryEnabledOption(ZetaCategory cat) { - return categoryEnabledOptions.get(cat); - } - - public ValueDefinition getModuleEnabledOption(ZetaModule module) { - return moduleEnabledOptions.get(module); - } - - // support for the options added by this class - - private void setCategoryEnabled(ZetaCategory cat, boolean enabled) { - if(enabled) - enabledCategories.add(cat); - else - enabledCategories.remove(cat); - - //TODO: hacky, just forcing setEnabled to rerun since it checks category enablement - for(ZetaModule mod : z.modules.modulesInCategory(cat)) { - mod.setEnabled(z, mod.enabled); - } - } - - private void setModuleEnabled(ZetaModule module, boolean enabled) { - module.setEnabled(z, enabled); - } - - public boolean isCategoryEnabled(ZetaCategory cat) { - return enabledCategories.contains(cat); - } - - // ummm - - public ConfigFlagManager getConfigFlagManager() { - return cfm; - } - - public void onReload() { - IZetaConfigInternals internals = z.configInternals; - databindings.forEach(c -> c.accept(internals)); - - if(onConfigReloadJEI != null) - onConfigReloadJEI.accept(internals); - } - - public void setJeiReloadListener(Consumer consumer) { - this.onConfigReloadJEI = consumer; - consumer.accept(z.configInternals); //run it now as well - } + private final Zeta z; + private final ConfigFlagManager cfm; + private final SectionDefinition rootConfig; + + //for updating the values of @Config annotations to match the current state of the config + // and other "listening for config load" purposes + private final List> databindings = new ArrayList<>(); + private Consumer onConfigReloadJEI; + + //ummmmmmm i think my abstraction isn't very good + private final @Nullable SectionDefinition generalSection; + private final Map categoriesToSections = new HashMap<>(); + + private final Map> categoryEnabledOptions = new HashMap<>(); + private final Map> ignoreAntiOverlapOptions = new HashMap<>(); + private final Map> moduleEnabledOptions = new HashMap<>(); + + //state + private final Set enabledCategories = new HashSet<>(); + + public ConfigManager(Zeta z, Object rootPojo) { + this.z = z; + this.cfm = new ConfigFlagManager(z); + ZetaModuleManager modules = z.modules; + + //all modules are enabled by default + enabledCategories.addAll(modules.getCategories()); + + SectionDefinition.Builder rootConfigBuilder = new SectionDefinition.Builder().name(""); + + // "general" section + if (rootPojo == null) + generalSection = null; + else { + //TODO: where to put this lol + z.loadBus.subscribe(rootPojo).subscribe(rootPojo.getClass()); + z.playBus.subscribe(rootPojo).subscribe(rootPojo.getClass()); + + generalSection = rootConfigBuilder.addSubsection(general -> ConfigObjectMapper.readInto(general.name("general"), rootPojo, databindings, cfm)); + } + + // "categories" section, holding the category enablement options + rootConfigBuilder.addSubsection(categories -> { + categories.name("categories"); + for (ZetaCategory category : modules.getInhabitedCategories()) + categoryEnabledOptions.put(category, categories.addValue(b -> b.name(category.name).defaultValue(true))); + }); + + // per-category options + for (ZetaCategory category : modules.getInhabitedCategories()) { + categoriesToSections.put(category, rootConfigBuilder.addSubsection(categorySectionBuilder -> { + categorySectionBuilder.name(category.name); + for (ZetaModule module : modules.modulesInCategory(category)) { + // module flag + cfm.putModuleFlag(module); + + // module enablement option + moduleEnabledOptions.put(module, categorySectionBuilder.addValue(moduleEnabledOptionBuilder -> moduleEnabledOptionBuilder + .name(module.displayName) + .englishDisplayName(module.displayName) + .comment(module.description) + .defaultValue(module.enabledByDefault))); + + // per-module options + categorySectionBuilder.addSubsection(moduleSectionBuilder -> { + moduleSectionBuilder + .name(module.lowercaseName) + .englishDisplayName(module.displayName) + .comment(module.description); + + // @Config options + ConfigObjectMapper.readInto(moduleSectionBuilder, module, databindings, cfm); + + // anti overlap option + if (!module.antiOverlap.isEmpty()) { + ignoreAntiOverlapOptions.put(module, moduleSectionBuilder.addValue(antiOverlapOptionBuilder -> { + antiOverlapOptionBuilder.name("Ignore Anti Overlap") + .comment("This feature disables itself if any of the following mods are loaded:") + .defaultValue(false); + + for (String modid : module.antiOverlap) + antiOverlapOptionBuilder.comment(" - " + modid); + + antiOverlapOptionBuilder.comment("This is done to prevent content overlap.") + .comment("You can turn this on to force the feature to be loaded even if the above mods are also loaded."); + })); + } + }); + } + })); + } + + //grab any extra flags + z.playBus.fire(() -> cfm, ZGatherAdditionalFlags.class); + + //managing module enablement in one go + //adding this to the *start* of the list so modules are enabled before anything else runs + //Its Janky ! + databindings.add(0, i -> { + categoryEnabledOptions.forEach((category, option) -> setCategoryEnabled(category, i.get(option))); + ignoreAntiOverlapOptions.forEach((module, option) -> module.ignoreAntiOverlap = !ZetaGeneralConfig.useAntiOverlap || i.get(option)); + moduleEnabledOptions.forEach((module, option) -> { + setModuleEnabled(module, i.get(option)); + cfm.putModuleFlag(module); + }); + + //update extra flags + z.playBus.fire(() -> cfm, ZGatherAdditionalFlags.class); + }); + + this.rootConfig = rootConfigBuilder.build(); + rootConfig.finish(); + } + + public SectionDefinition getRootConfig() { + return rootConfig; + } + + // mapping between internal and external representations of the config (??????) + + public @Nullable SectionDefinition getGeneralSection() { + return generalSection; + } + + public SectionDefinition getCategorySection(ZetaCategory cat) { + return categoriesToSections.get(cat); + } + + public ValueDefinition getCategoryEnabledOption(ZetaCategory cat) { + return categoryEnabledOptions.get(cat); + } + + public ValueDefinition getModuleEnabledOption(ZetaModule module) { + return moduleEnabledOptions.get(module); + } + + // support for the options added by this class + + private void setCategoryEnabled(ZetaCategory cat, boolean enabled) { + if (enabled) + enabledCategories.add(cat); + else + enabledCategories.remove(cat); + + //TODO: hacky, just forcing setEnabled to rerun since it checks category enablement + for (ZetaModule mod : z.modules.modulesInCategory(cat)) { + mod.setEnabled(z, mod.enabled); + } + } + + private void setModuleEnabled(ZetaModule module, boolean enabled) { + module.setEnabled(z, enabled); + } + + public boolean isCategoryEnabled(ZetaCategory cat) { + return enabledCategories.contains(cat); + } + + // ummm + + public ConfigFlagManager getConfigFlagManager() { + return cfm; + } + + public void onReload() { + IZetaConfigInternals internals = z.configInternals; + databindings.forEach(c -> c.accept(internals)); + + if (onConfigReloadJEI != null) + onConfigReloadJEI.accept(internals); + } + + public void setJeiReloadListener(Consumer consumer) { + this.onConfigReloadJEI = consumer; + consumer.accept(z.configInternals); //run it now as well + } } diff --git a/src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java b/src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java index 7d14346..487639d 100644 --- a/src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java +++ b/src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java @@ -9,9 +9,9 @@ import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.violetmoon.zeta.client.event.load.ZAddBlockColorHandlers; -import org.violetmoon.zeta.event.load.ZRegister; -import org.violetmoon.zetaimplforge.event.load.ForgeZRegister; +import org.violetmoon.zeta.event.load.ZModulesReady; +import org.violetmoon.zetaimplforge.event.NotAForgeWrapper; +import org.violetmoon.zetaimplforge.event.load.ForgeZConfigChange; import java.lang.annotation.Annotation; import java.lang.invoke.MethodHandle; @@ -25,7 +25,7 @@ import java.util.function.Function; import java.util.function.Predicate; -// this is quite jank. Basically converts all zeta events to forge ones, then delegates to the forge bus directly +// this is super jank. Basically converts all zeta events to forge ones, then delegates to the forge bus directly public class ForgeZetaEventBus extends ZetaEventBus { private final Map, Function> forgeToZetaMap = new HashMap<>(); @@ -106,37 +106,47 @@ public T fire(@NotNull T event, Class firedAs) { // good thing is most of this can be removed in 1.21 since Event is an interface there so we can pass zeta events directly. Just need to make zeta event extend Event + /** + * Given an event object which is NOT a subtype of Event class, remap it to a forge event + */ private F remapEvent(@NotNull Z2 zetaEvent, Class firedAs) { Function zetaToForgeFunc = zetaToForgeMap.get(firedAs); if (zetaToForgeFunc == null) { // remap is null. no checks because micro optimization. It means it must be a forge event already return (F) zetaEvent; - //throw new RuntimeException("No wrapped forge Event found for Zeta event class. You must register its subclass using registerSubclass. " + firedAs); } return createForgeEvent(zetaEvent, zetaToForgeFunc); } // takes a method that takes a zeta event and turns into one that takes a forge event - private Consumer remapMethod(MethodHandle originalEventConsumer, Class zetaEventClass) { - Function forgeToZetaFunc = forgeToZetaMap.get(zetaEventClass); + + /** + * Given a MethodHandle of a method which takes a Zeta event, remaps it to a method which takes a Forge event, so we can register it with Forge event bus + */ + private Consumer remapMethod(MethodHandle originalEventConsumer, Class zetaEventBaseClass) { + Function forgeToZetaFunc = forgeToZetaMap.get(zetaEventBaseClass); if (forgeToZetaFunc == null) { // no remap needed - if (forgeEventRoot.isAssignableFrom(zetaEventClass)) { + if (forgeEventRoot.isAssignableFrom(zetaEventBaseClass)) { forgeToZetaFunc = event -> (Z) event; } else - throw new RuntimeException("No forge-Event-wrapping constructor found for Zeta event class. You must register its subclass using registerSubclass. " + zetaEventClass); + throw new RuntimeException("No forge-Event-wrapping constructor found for Zeta event class. You must register its subclass using registerSubclass. " + zetaEventBaseClass); } - return createForgeConsumer(originalEventConsumer, forgeToZetaFunc, zetaEventClass); + return createForgeConsumer(originalEventConsumer, forgeToZetaFunc, zetaEventBaseClass); } + + // generic bs private F createForgeEvent(@NotNull Z event, Function function) { return function.apply((T) event); } + // generic bs + // Creates the Forge Event Consumer that will be registered with Forge Event Bus private Consumer createForgeConsumer(MethodHandle zetaEventConsumer, Function forgeToZetaFunc, - Class zetaEventClass) { + Class zetaEventBaseClass) { //hack for tick events - Phase phase = Phase.guessFromClassName(zetaEventClass); + Phase phase = Phase.guessFromClassName(zetaEventBaseClass); return event -> { try { //luckily this phase madness will go away with new neoforge @@ -152,52 +162,74 @@ private Consumer createForgeConsumer(MethodHand } // for generic events - public void registerSubClass(Class eventClass, Class zetaEventClass, Class genericClass) { - registerSubClass(eventClass, zetaEventClass); - generics.put(eventClass, genericClass); + public void registerSubClassWithGeneric(Class baseZetaEventClass, Class forgeZetaEventClass, Class genericClass) { + registerSubClass(baseZetaEventClass, forgeZetaEventClass); + generics.put(baseZetaEventClass, genericClass); } - public void registerSubClass(Class eventClass, Class zetaEventClass) { + public void registerSubClass(Class baseZetaEventClass, Class forgeZetaEventClass) { - Function wrappingConstructor = findForgeWrapper(zetaEventClass, eventClass); - registerSubClass(eventClass, zetaEventClass, wrappingConstructor); + registerSubClass(baseZetaEventClass, forgeZetaEventClass, null); } - public void registerSubClass(Class eventClass, Class zetaEventClass, - Function constructor, Class genericClass) { - registerSubClass(eventClass, zetaEventClass, constructor); - generics.put(eventClass, genericClass); + public void registerSubClassWithGeneric(Class baseZetaEventClass, Class forgeZetaEventClass, + Function constructor, Class genericClass) { + registerSubClass(baseZetaEventClass, forgeZetaEventClass, constructor); + generics.put(baseZetaEventClass, genericClass); } - public void registerSubClass(Class eventClass, Class zetaEventClass, - @Nullable Function constructor) { + public void registerSubClass(Class baseZetaEventClass, Class forgeZetaEventClass, + @Nullable Function constructor) { Object old1 = null; Object old2 = null; - if (constructor != null) { - old1 = forgeToZetaMap.put(eventClass, constructor); + boolean isNoWrapper = false; + if (constructor == null) { + // if it's an Event already just returns the no argument constructor + if (forgeEventRoot.isAssignableFrom(forgeZetaEventClass)) { + zetaToForgeEventClass.put(baseZetaEventClass, forgeZetaEventClass); + constructor = event -> (ZF) event; + isNoWrapper = true; + } + else constructor = findForgeWrapper(forgeZetaEventClass); + } + if (constructor == null) { + throw new RuntimeException("No forge-Event-wrapping constructor found for Zeta event class " + forgeZetaEventClass); + } else { + old1 = forgeToZetaMap.put(baseZetaEventClass, constructor); + } + + Function zetaToForge = null; + if (!isNoWrapper) { + zetaToForge = findWrappedForgeEvent(forgeZetaEventClass, baseZetaEventClass); } - Function zetaToForge = findWrappedForgeEvent(zetaEventClass, eventClass); + if (zetaToForge == null) { - zetaToForge = findZetaWrapper(zetaEventClass); + zetaToForge = findZetaWrapper(forgeZetaEventClass); } if (zetaToForge != null) { - old2 = zetaToForgeMap.put(eventClass, zetaToForge); + old2 = zetaToForgeMap.put(baseZetaEventClass, zetaToForge); } if (old1 != null || old2 != null) { - throw new RuntimeException("Event class " + eventClass + " already registered"); + throw new RuntimeException("Event class " + baseZetaEventClass + " already registered"); } } + // This is where the magic happens - private Function findForgeWrapper(Class zetaEventClass, Class baseZetaEventClass) { + // Explanation: + // The whole point of these methods is to automatically convert a Zeta event to a Forge event, and vice versa. + // This is done since we can only have zeta event consumer methods in our common code, however we can only register to the forge bus a consumer of the forge Event class. + // For this reason here we have some functions that, with a lot of assumptions, try to find wrappers and unwrapper functions for each Forge-Zeta classes pair - // if it's an Event already ust returns the no argument constructor - if (forgeEventRoot.isAssignableFrom(zetaEventClass)) { - zetaToForgeEventClass.put(baseZetaEventClass, zetaEventClass); - return event -> (Z2) event; - } + /** + * @param zetaEventClass i.e: ForgeZClientSetup.class + *

+ * Attempts to find a constructor of zetaEventClass which takes an Event as a parameter. This is used for simple forge Event wrappers + * in this example the one found will be new ForgeZClientSetup(FMLClientSetupEvent event) + */ + private Function findForgeWrapper(Class zetaEventClass) { // Find the constructor that takes a single parameter of type A for (Constructor constructor : zetaEventClass.getConstructors()) { @@ -212,12 +244,18 @@ private Function findForgeWrapper(Class }; } } - throw new RuntimeException("No forge-Event-wrapping constructor found for Zeta event class " + zetaEventClass); + return null; } + /** + * @param zetaEventClass i.e: ForgeZRegister.class + *

+ * Tries to find a constructor that takes a single parameter with type of Zeta event. This convention is used to create Zeta specific event. + * The wrapper pattern is used here to provide platform specific implementation. + * In this example the one returned would be new ForgeZRegister(ZRegister event) + * If no wrapper constructor is found and the provided class implements Event already returns null. Exception otherwise. + */ private Function findZetaWrapper(Class zetaEventClass) { - // if it's an Event already ust returns the no argument constructor - // Find the constructor that takes a single parameter of type A for (Constructor constructor : zetaEventClass.getConstructors()) { Class[] parameterTypes = constructor.getParameterTypes(); diff --git a/src/main/java/org/violetmoon/zeta/event/bus/ZetaEventBus.java b/src/main/java/org/violetmoon/zeta/event/bus/ZetaEventBus.java index 38c4066..e10100b 100644 --- a/src/main/java/org/violetmoon/zeta/event/bus/ZetaEventBus.java +++ b/src/main/java/org/violetmoon/zeta/event/bus/ZetaEventBus.java @@ -5,6 +5,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.violetmoon.zeta.Zeta; +import org.violetmoon.zeta.util.handler.RecipeCrawlHandler; import java.lang.annotation.Annotation; import java.lang.reflect.Method; @@ -47,7 +48,6 @@ public ZetaEventBus subscribe(@NotNull Object target) { receiver = target; owningClazz = target.getClass(); } - streamAnnotatedMethods(owningClazz, receiver == null) .forEach(m -> subscribeMethod(m, receiver, owningClazz)); return this; diff --git a/src/main/java/org/violetmoon/zeta/mod/ZetaClientProxy.java b/src/main/java/org/violetmoon/zeta/mod/ZetaClientProxy.java deleted file mode 100644 index 706b2ea..0000000 --- a/src/main/java/org/violetmoon/zeta/mod/ZetaClientProxy.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.violetmoon.zeta.mod; - -import org.violetmoon.zeta.Zeta; -import org.violetmoon.zeta.client.TopLayerTooltipHandler; -import org.violetmoon.zeta.client.ZetaClient; -import org.violetmoon.zeta.util.handler.RequiredModTooltipHandler; - -public class ZetaClientProxy extends ZetaModProxy { - - public static ZetaClient ZETA_CLIENT; - - @Override - public void registerEvents(Zeta zeta) { - super.registerEvents(zeta); - - zeta.playBus - .subscribe(TopLayerTooltipHandler.class) - .subscribe(new RequiredModTooltipHandler.Client(zeta)); - } - - @Override - public void setClientZeta(Object obj) { - ZETA_CLIENT = (ZetaClient) obj; - } - -} diff --git a/src/main/java/org/violetmoon/zeta/mod/ZetaMod.java b/src/main/java/org/violetmoon/zeta/mod/ZetaMod.java index bea5684..7bcfc15 100644 --- a/src/main/java/org/violetmoon/zeta/mod/ZetaMod.java +++ b/src/main/java/org/violetmoon/zeta/mod/ZetaMod.java @@ -2,25 +2,19 @@ import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.config.ZetaGeneralConfig; -import org.violetmoon.zeta.event.bus.LoadEvent; -import org.violetmoon.zeta.event.load.ZCommonSetup; import org.violetmoon.zeta.network.ZetaModInternalNetwork; -import org.violetmoon.zetaimplforge.config.ConfigEventDispatcher; public class ZetaMod { public static Zeta ZETA; - public static ZetaModProxy proxy; - - public static void start(Zeta zeta, ZetaModProxy proxy) { + + public static void start(Zeta zeta) { ZetaMod.ZETA = zeta; - ZetaMod.proxy = proxy; ZETA.start(); ZETA.loadModules(null, null, ZetaGeneralConfig.INSTANCE); ZetaModInternalNetwork.init(); - proxy.registerEvents(zeta); } } diff --git a/src/main/java/org/violetmoon/zeta/mod/ZetaModProxy.java b/src/main/java/org/violetmoon/zeta/mod/ZetaModProxy.java deleted file mode 100644 index 1ed6586..0000000 --- a/src/main/java/org/violetmoon/zeta/mod/ZetaModProxy.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.violetmoon.zeta.mod; - -import org.violetmoon.zeta.Zeta; -import org.violetmoon.zeta.config.SyncedFlagHandler; -import org.violetmoon.zeta.config.ZetaGeneralConfig; -import org.violetmoon.zeta.util.handler.RecipeCrawlHandler; -import org.violetmoon.zeta.util.handler.ToolInteractionHandler; -import org.violetmoon.zeta.world.EntitySpawnHandler; -import org.violetmoon.zeta.world.WorldGenHandler; - -public class ZetaModProxy { - - public void registerEvents(Zeta zeta) { - zeta.loadBus - .subscribe(RecipeCrawlHandler.class) - .subscribe(ToolInteractionHandler.class) - .subscribe(EntitySpawnHandler.class) - .subscribe(WorldGenHandler.class) - .subscribe(ZetaGeneralConfig.class); - - zeta.playBus - .subscribe(RecipeCrawlHandler.class) - .subscribe(ToolInteractionHandler.class) - .subscribe(SyncedFlagHandler.class); - } - - // Cast up obj to ZetaClient on the client proxy - public void setClientZeta(Object obj) { - // NO-OP - } - -} diff --git a/src/main/java/org/violetmoon/zeta/util/handler/RecipeCrawlHandler.java b/src/main/java/org/violetmoon/zeta/util/handler/RecipeCrawlHandler.java index 48fe47c..860bb9c 100644 --- a/src/main/java/org/violetmoon/zeta/util/handler/RecipeCrawlHandler.java +++ b/src/main/java/org/violetmoon/zeta/util/handler/RecipeCrawlHandler.java @@ -8,6 +8,7 @@ import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Nullable; import org.violetmoon.zeta.Zeta; +import org.violetmoon.zeta.client.event.play.ZRenderGuiOverlay; import org.violetmoon.zeta.event.bus.IZetaPlayEvent; import org.violetmoon.zeta.event.bus.LoadEvent; import org.violetmoon.zeta.event.bus.PlayEvent; @@ -128,6 +129,11 @@ else if (recipe instanceof AbstractCookingRecipe acr) } } + @PlayEvent + public static void a (ZRenderGuiOverlay.ArmorLevel.Pre aa){ + int aaa = 1; + } + @PlayEvent public static void onTick(ZServerTick.Start tick) { synchronized (mutex) { diff --git a/src/main/java/org/violetmoon/zeta/util/zetalist/ZetaList.java b/src/main/java/org/violetmoon/zeta/util/zetalist/ZetaList.java index 280b474..e424f11 100644 --- a/src/main/java/org/violetmoon/zeta/util/zetalist/ZetaList.java +++ b/src/main/java/org/violetmoon/zeta/util/zetalist/ZetaList.java @@ -5,7 +5,6 @@ import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.event.bus.IZetaLoadEvent; -import org.violetmoon.zeta.event.bus.IZetaPlayEvent; public class ZetaList { @@ -19,11 +18,11 @@ public void register(T z) { knownZetas.add(z); } - public void fireEvent(E event) { + public void fireLoadEvent(E event) { knownZetas.forEach(z -> z.asZeta().loadBus.fire(event)); } - public void fireEvent(E event, Class eventClass) { + public void fireLoadEvent(E event, Class eventClass) { knownZetas.forEach(z -> z.asZeta().loadBus.fire(event, eventClass)); } diff --git a/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java b/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java index 8e007de..0d23211 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java +++ b/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java @@ -31,6 +31,7 @@ import org.violetmoon.zeta.client.ZetaClient; import org.violetmoon.zeta.client.event.load.*; import org.violetmoon.zeta.client.event.play.*; +import org.violetmoon.zeta.config.ConfigManager; import org.violetmoon.zeta.config.IZetaConfigInternals; import org.violetmoon.zeta.config.SectionDefinition; import org.violetmoon.zeta.event.bus.*; @@ -48,6 +49,7 @@ import org.violetmoon.zetaimplforge.api.ForgeZGatherAdvancementModifiers; import org.violetmoon.zetaimplforge.block.IForgeBlockBlockExtensions; import org.violetmoon.zetaimplforge.capability.ForgeCapabilityManager; +import org.violetmoon.zetaimplforge.client.ForgeZetaClient; import org.violetmoon.zetaimplforge.client.event.load.*; import org.violetmoon.zetaimplforge.client.event.play.*; import org.violetmoon.zetaimplforge.config.ConfigEventDispatcher; @@ -81,8 +83,6 @@ protected ZetaEventBus createLoadBus() { if (false) return new FabricZetaEventBus<>(LoadEvent.class, IZetaLoadEvent.class, log); - // thanks forge and your dumb Event + IModEvent classes and hacky runtime generic stuff. I cant get this to work - var bus = new ForgeZetaEventBus<>(LoadEvent.class, IZetaLoadEvent.class, log, FMLJavaModLoadingContext.get().getModEventBus(), Event.class); @@ -183,7 +183,6 @@ protected ZetaEventBus createLoadBus() { bus.registerSubClass(ZInput.Key.class, ForgeZInput.Key.class); bus.registerSubClass(ZInputUpdate.class, ForgeZInputUpdate.class); bus.registerSubClass(ZRenderContainerScreen.class, ForgeZRenderContainerScreen.class); - //bus.registerSubClass(ZRenderGuiOverlay.class, ForgeZRenderGuiOverlay.class); bus.registerSubClass(ZRenderLiving.class, ForgeZRenderLiving.class); bus.registerSubClass(ZRenderPlayer.class, ForgeZRenderPlayer.class); bus.registerSubClass(ZRenderTick.class, ForgeZRenderTick.class); @@ -195,20 +194,22 @@ protected ZetaEventBus createLoadBus() { bus.registerSubClass(ZScreen.MouseScrolled.class, ForgeZScreen.MouseScrolled.class); bus.registerSubClass(ZScreen.MouseButtonPressed.class, ForgeZScreen.MouseButtonPressed.class); bus.registerSubClass(ZScreen.Render.class, ForgeZScreen.Render.class); + bus.registerSubClass(ZRenderGuiOverlay.ArmorLevel.Pre.class, ForgeZRenderGuiOverlay.ArmorLevel.Pre.class); + bus.registerSubClass(ZRenderGuiOverlay.ArmorLevel.Post.class, ForgeZRenderGuiOverlay.ArmorLevel.Post.class); //this is ugly. generic events here Zeta zeta = this; - bus.registerSubClass(ZAttachCapabilities.BlockEntityCaps.class, + bus.registerSubClassWithGeneric(ZAttachCapabilities.BlockEntityCaps.class, ForgeZAttachCapabilities.BlockEntityCaps.class, (Function, ForgeZAttachCapabilities.BlockEntityCaps>) inner -> new ForgeZAttachCapabilities.BlockEntityCaps(zeta.capabilityManager, inner), BlockEntity.class); - bus.registerSubClass(ZAttachCapabilities.ItemStackCaps.class, + bus.registerSubClassWithGeneric(ZAttachCapabilities.ItemStackCaps.class, ForgeZAttachCapabilities.ItemStackCaps.class, (Function, ForgeZAttachCapabilities.ItemStackCaps>) inner -> new ForgeZAttachCapabilities.ItemStackCaps(zeta.capabilityManager, inner), ItemStack.class); - bus.registerSubClass(ZAttachCapabilities.LevelCaps.class, + bus.registerSubClassWithGeneric(ZAttachCapabilities.LevelCaps.class, ForgeZAttachCapabilities.LevelCaps.class, (Function, ForgeZAttachCapabilities.LevelCaps>) inner -> new ForgeZAttachCapabilities.LevelCaps(zeta.capabilityManager, inner), @@ -311,8 +312,6 @@ public void start() { modbus.addListener(ConfigEventDispatcher::configChanged); modbus.addListener(EventPriority.HIGHEST, this::registerHighest); - //why is this load? - //MinecraftForge.EVENT_BUS.addListener(this::addReloadListener); } private boolean registerDone = false; diff --git a/src/main/java/org/violetmoon/zetaimplforge/client/ForgeZetaClient.java b/src/main/java/org/violetmoon/zetaimplforge/client/ForgeZetaClient.java index 9f0deef..444206e 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/client/ForgeZetaClient.java +++ b/src/main/java/org/violetmoon/zetaimplforge/client/ForgeZetaClient.java @@ -136,70 +136,5 @@ public RegistryAccess hackilyGetCurrentClientLevelRegistryAccess() { return conn == null ? null : conn.registryAccess(); } - @Override - public void start() { - IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus(); - - MinecraftForge.EVENT_BUS.addListener(this::clientTick); - - - MinecraftForge.EVENT_BUS.addListener(this::renderGameOverlayNeitherPreNorPost); - MinecraftForge.EVENT_BUS.addListener(this::renderGuiOverlayPre); - MinecraftForge.EVENT_BUS.addListener(this::renderGuiOverlayPost); - } - - boolean clientTicked = false; - public void clientTick(TickEvent.ClientTickEvent e) { - if(!clientTicked) { - loadBus.fire(new ZFirstClientTick()); - clientTicked = true; - } - - playBus.fire(new ForgeZClientTick(e), ZClientTick.class); - } - - - //TODO: This probably should have been a PRE/POST event (just copying quark here) - public void renderGameOverlayNeitherPreNorPost(RenderGuiOverlayEvent e) { - if(e.getOverlay() == VanillaGuiOverlay.CROSSHAIR.type()) - playBus.fire(new ForgeZRenderGuiOverlay.Crosshair(e), ZRenderGuiOverlay.Crosshair.class); - else if(e.getOverlay() == VanillaGuiOverlay.HOTBAR.type()) - playBus.fire(new ForgeZRenderGuiOverlay.Hotbar(e), ZRenderGuiOverlay.Hotbar.class); - } - - public void renderGuiOverlayPre(RenderGuiOverlayEvent.Pre e) { - if (e.getOverlay() == VanillaGuiOverlay.HOTBAR.type()) - playBus.fire(new ForgeZRenderGuiOverlay.Hotbar.Pre(e), ZRenderGuiOverlay.Hotbar.Pre.class); - else if (e.getOverlay() == VanillaGuiOverlay.CROSSHAIR.type()) - playBus.fire(new ForgeZRenderGuiOverlay.Crosshair.Pre(e), ZRenderGuiOverlay.Crosshair.Pre.class); - else if (e.getOverlay() == VanillaGuiOverlay.PLAYER_HEALTH.type()) - playBus.fire(new ForgeZRenderGuiOverlay.PlayerHealth.Pre(e), ZRenderGuiOverlay.PlayerHealth.Pre.class); - else if (e.getOverlay() == VanillaGuiOverlay.ARMOR_LEVEL.type()) - playBus.fire(new ForgeZRenderGuiOverlay.ArmorLevel.Pre(e), ZRenderGuiOverlay.ArmorLevel.Pre.class); - else if (e.getOverlay() == VanillaGuiOverlay.DEBUG_TEXT.type()) - playBus.fire(new ForgeZRenderGuiOverlay.DebugText.Pre(e), ZRenderGuiOverlay.DebugText.Pre.class); - else if (e.getOverlay() == VanillaGuiOverlay.POTION_ICONS.type()) - playBus.fire(new ForgeZRenderGuiOverlay.PotionIcons.Pre(e), ZRenderGuiOverlay.PotionIcons.Pre.class); - else if (e.getOverlay() == VanillaGuiOverlay.CHAT_PANEL.type()) - playBus.fire(new ForgeZRenderGuiOverlay.ChatPanel.Pre(e), ZRenderGuiOverlay.ChatPanel.Pre.class); - } - - public void renderGuiOverlayPost(RenderGuiOverlayEvent.Post e) { - NamedGuiOverlay overlay = e.getOverlay(); - if (overlay == VanillaGuiOverlay.HOTBAR.type()) - playBus.fire(new ForgeZRenderGuiOverlay.Hotbar.Post(e), ZRenderGuiOverlay.Hotbar.Post.class); - else if (overlay == VanillaGuiOverlay.CROSSHAIR.type()) - playBus.fire(new ForgeZRenderGuiOverlay.Crosshair.Post(e), ZRenderGuiOverlay.Crosshair.Post.class); - else if (overlay == VanillaGuiOverlay.PLAYER_HEALTH.type()) - playBus.fire(new ForgeZRenderGuiOverlay.PlayerHealth.Post(e), ZRenderGuiOverlay.PlayerHealth.Post.class); - else if (overlay == VanillaGuiOverlay.ARMOR_LEVEL.type()) - playBus.fire(new ForgeZRenderGuiOverlay.ArmorLevel.Post(e), ZRenderGuiOverlay.ArmorLevel.Post.class); - else if (overlay == VanillaGuiOverlay.DEBUG_TEXT.type()) - playBus.fire(new ForgeZRenderGuiOverlay.DebugText.Post(e), ZRenderGuiOverlay.DebugText.Post.class); - else if (overlay == VanillaGuiOverlay.POTION_ICONS.type()) - playBus.fire(new ForgeZRenderGuiOverlay.PotionIcons.Post(e), ZRenderGuiOverlay.PotionIcons.Post.class); - else if (overlay == VanillaGuiOverlay.CHAT_PANEL.type()) - playBus.fire(new ForgeZRenderGuiOverlay.ChatPanel.Post(e), ZRenderGuiOverlay.ChatPanel.Post.class); - } } diff --git a/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderGuiOverlay.java b/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderGuiOverlay.java index 3a589a4..2679201 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderGuiOverlay.java +++ b/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderGuiOverlay.java @@ -1,5 +1,6 @@ package org.violetmoon.zetaimplforge.client.event.play; +import net.minecraftforge.eventbus.api.Event; import org.violetmoon.zeta.client.event.play.ZRenderGuiOverlay; import com.mojang.blaze3d.platform.Window; @@ -9,7 +10,7 @@ import net.minecraftforge.client.event.RenderGuiOverlayEvent; import net.minecraftforge.client.gui.overlay.ForgeGui; -public class ForgeZRenderGuiOverlay implements ZRenderGuiOverlay { +public class ForgeZRenderGuiOverlay extends Event implements ZRenderGuiOverlay { private final RenderGuiOverlayEvent e; public ForgeZRenderGuiOverlay(RenderGuiOverlayEvent e) { diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/NotAForgeWrapper.java b/src/main/java/org/violetmoon/zetaimplforge/event/NotAForgeWrapper.java new file mode 100644 index 0000000..249ca03 --- /dev/null +++ b/src/main/java/org/violetmoon/zetaimplforge/event/NotAForgeWrapper.java @@ -0,0 +1,9 @@ +package org.violetmoon.zetaimplforge.event; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +// Hideous marker interface used to denote Zeta specific events that are NOT supposed to be remapped to forge events +@Retention(RetentionPolicy.RUNTIME) +public @interface NotAForgeWrapper { +} diff --git a/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModClientProxy.java b/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModClientProxy.java new file mode 100644 index 0000000..77399d5 --- /dev/null +++ b/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModClientProxy.java @@ -0,0 +1,80 @@ +package org.violetmoon.zetaimplforge.mod; + +import net.minecraftforge.client.event.RenderGuiOverlayEvent; +import net.minecraftforge.client.gui.overlay.NamedGuiOverlay; +import net.minecraftforge.client.gui.overlay.VanillaGuiOverlay; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.event.TickEvent; +import org.violetmoon.zeta.Zeta; +import org.violetmoon.zeta.client.TopLayerTooltipHandler; +import org.violetmoon.zeta.client.event.play.ZFirstClientTick; +import org.violetmoon.zeta.client.event.play.ZRenderGuiOverlay; +import org.violetmoon.zeta.util.handler.RequiredModTooltipHandler; +import org.violetmoon.zeta.util.zetalist.ZetaList; +import org.violetmoon.zetaimplforge.client.ForgeZetaClient; +import org.violetmoon.zetaimplforge.client.event.play.ForgeZRenderGuiOverlay; + +public class ZetaModClientProxy extends ZetaModCommonProxy { + + private final ForgeZetaClient clientZeta; + + public ZetaModClientProxy(Zeta zeta) { + super(zeta); + this.clientZeta = new ForgeZetaClient(zeta); + + zeta.playBus + .subscribe(TopLayerTooltipHandler.class) + .subscribe(new RequiredModTooltipHandler.Client(zeta)); + + MinecraftForge.EVENT_BUS.addListener(this::clientTick); + + MinecraftForge.EVENT_BUS.addListener(this::renderGuiOverlayPre); + MinecraftForge.EVENT_BUS.addListener(this::renderGuiOverlayPost); + } + + // added once per zeta. Its fine as we then fire it on zeta load bos which is one per zeta too. + boolean clientTicked = false; + public void clientTick(TickEvent.ClientTickEvent e) { + if(!clientTicked) { + ZetaList.INSTANCE.fireLoadEvent(new ZFirstClientTick()); + clientTicked = true; + } + } + + public void renderGuiOverlayPre(RenderGuiOverlayEvent.Pre e) { + NamedGuiOverlay overlay = e.getOverlay(); + if (overlay == VanillaGuiOverlay.HOTBAR.type()) + clientZeta.playBus.fire(new ForgeZRenderGuiOverlay.Hotbar.Pre(e), ZRenderGuiOverlay.Hotbar.Pre.class); + else if (overlay == VanillaGuiOverlay.CROSSHAIR.type()) + clientZeta.playBus.fire(new ForgeZRenderGuiOverlay.Crosshair.Pre(e), ZRenderGuiOverlay.Crosshair.Pre.class); + else if (overlay == VanillaGuiOverlay.PLAYER_HEALTH.type()) + clientZeta.playBus.fire(new ForgeZRenderGuiOverlay.PlayerHealth.Pre(e), ZRenderGuiOverlay.PlayerHealth.Pre.class); + else if (overlay == VanillaGuiOverlay.ARMOR_LEVEL.type()) + clientZeta.playBus.fire(new ForgeZRenderGuiOverlay.ArmorLevel.Pre(e), ZRenderGuiOverlay.ArmorLevel.Pre.class); + else if (overlay == VanillaGuiOverlay.DEBUG_TEXT.type()) + clientZeta.playBus.fire(new ForgeZRenderGuiOverlay.DebugText.Pre(e), ZRenderGuiOverlay.DebugText.Pre.class); + else if (overlay == VanillaGuiOverlay.POTION_ICONS.type()) + clientZeta.playBus.fire(new ForgeZRenderGuiOverlay.PotionIcons.Pre(e), ZRenderGuiOverlay.PotionIcons.Pre.class); + else if (overlay == VanillaGuiOverlay.CHAT_PANEL.type()) + clientZeta.playBus.fire(new ForgeZRenderGuiOverlay.ChatPanel.Pre(e), ZRenderGuiOverlay.ChatPanel.Pre.class); + } + + public void renderGuiOverlayPost(RenderGuiOverlayEvent.Post e) { + NamedGuiOverlay overlay = e.getOverlay(); + if (overlay == VanillaGuiOverlay.HOTBAR.type()) + clientZeta.playBus.fire(new ForgeZRenderGuiOverlay.Hotbar.Post(e), ZRenderGuiOverlay.Hotbar.Post.class); + else if (overlay == VanillaGuiOverlay.CROSSHAIR.type()) + clientZeta.playBus.fire(new ForgeZRenderGuiOverlay.Crosshair.Post(e), ZRenderGuiOverlay.Crosshair.Post.class); + else if (overlay == VanillaGuiOverlay.PLAYER_HEALTH.type()) + clientZeta.playBus.fire(new ForgeZRenderGuiOverlay.PlayerHealth.Post(e), ZRenderGuiOverlay.PlayerHealth.Post.class); + else if (overlay == VanillaGuiOverlay.ARMOR_LEVEL.type()) + clientZeta.playBus.fire(new ForgeZRenderGuiOverlay.ArmorLevel.Post(e), ZRenderGuiOverlay.ArmorLevel.Post.class); + else if (overlay == VanillaGuiOverlay.DEBUG_TEXT.type()) + clientZeta.playBus.fire(new ForgeZRenderGuiOverlay.DebugText.Post(e), ZRenderGuiOverlay.DebugText.Post.class); + else if (overlay == VanillaGuiOverlay.POTION_ICONS.type()) + clientZeta.playBus.fire(new ForgeZRenderGuiOverlay.PotionIcons.Post(e), ZRenderGuiOverlay.PotionIcons.Post.class); + else if (overlay == VanillaGuiOverlay.CHAT_PANEL.type()) + clientZeta.playBus.fire(new ForgeZRenderGuiOverlay.ChatPanel.Post(e), ZRenderGuiOverlay.ChatPanel.Post.class); + } + +} diff --git a/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaForgeMod.java b/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModCommonProxy.java similarity index 51% rename from src/main/java/org/violetmoon/zetaimplforge/mod/ZetaForgeMod.java rename to src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModCommonProxy.java index 38bd970..297b02c 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaForgeMod.java +++ b/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModCommonProxy.java @@ -1,42 +1,42 @@ package org.violetmoon.zetaimplforge.mod; -import org.apache.logging.log4j.LogManager; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.eventbus.api.IEventBus; +import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; +import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import org.violetmoon.zeta.Zeta; -import org.violetmoon.zeta.mod.ZetaClientProxy; -import org.violetmoon.zeta.mod.ZetaMod; -import org.violetmoon.zeta.mod.ZetaModProxy; +import org.violetmoon.zeta.config.SyncedFlagHandler; +import org.violetmoon.zeta.config.ZetaGeneralConfig; +import org.violetmoon.zeta.util.handler.RecipeCrawlHandler; import org.violetmoon.zeta.util.handler.ToolInteractionHandler; -import org.violetmoon.zetaimplforge.ForgeZeta; -import org.violetmoon.zetaimplforge.client.ForgeZetaClient; +import org.violetmoon.zeta.world.EntitySpawnHandler; +import org.violetmoon.zeta.world.WorldGenHandler; import org.violetmoon.zetaimplforge.config.ConfigEventDispatcher; import org.violetmoon.zetaimplforge.world.ZetaBiomeModifier; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.fml.DistExecutor; -import net.minecraftforge.fml.common.Mod; -import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; -import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; +public class ZetaModCommonProxy { -@Mod("zeta") -public class ZetaForgeMod { - - public ZetaForgeMod() { - ForgeZeta zeta = new ForgeZeta(Zeta.ZETA_ID, LogManager.getLogger(Zeta.ZETA_ID + "-internal")); - - ZetaModProxy proxy = DistExecutor.runForDist(() -> ZetaClientProxy::new, () -> ZetaModProxy::new); - Object zetaClient = DistExecutor.runForDist(() -> () -> new ForgeZetaClient(zeta), () -> () -> new Object()); - - ZetaMod.start(zeta, proxy); - ZetaMod.proxy.setClientZeta(zetaClient); - - MinecraftForge.EVENT_BUS.register(ToolInteractionHandler.class); - ZetaBiomeModifier.registerBiomeModifier(FMLJavaModLoadingContext.get().getModEventBus()); - + public ZetaModCommonProxy(Zeta zeta) { IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus(); bus.addListener(this::setup); + + zeta.loadBus + .subscribe(RecipeCrawlHandler.class) + .subscribe(ToolInteractionHandler.class) + .subscribe(EntitySpawnHandler.class) + .subscribe(WorldGenHandler.class) + .subscribe(ZetaGeneralConfig.class); + + zeta.playBus + .subscribe(RecipeCrawlHandler.class) + .subscribe(ToolInteractionHandler.class) + .subscribe(SyncedFlagHandler.class); + + + MinecraftForge.EVENT_BUS.register(ToolInteractionHandler.class); + ZetaBiomeModifier.registerBiomeModifier(FMLJavaModLoadingContext.get().getModEventBus()); } - + public void setup(FMLCommonSetupEvent event) { event.enqueueWork(ConfigEventDispatcher::dispatchAllInitialLoads); } diff --git a/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModForge.java b/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModForge.java new file mode 100644 index 0000000..bda1cd2 --- /dev/null +++ b/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModForge.java @@ -0,0 +1,24 @@ +package org.violetmoon.zetaimplforge.mod; + +import org.apache.logging.log4j.LogManager; +import org.violetmoon.zeta.Zeta; +import org.violetmoon.zeta.mod.ZetaMod; +import org.violetmoon.zetaimplforge.ForgeZeta; + +import net.minecraftforge.fml.DistExecutor; +import net.minecraftforge.fml.common.Mod; + +@Mod("zeta") +public class ZetaModForge { + + public ZetaModForge() { + ForgeZeta zeta = new ForgeZeta(Zeta.ZETA_ID, LogManager.getLogger(Zeta.ZETA_ID + "-internal")); + + // creates 2 dist specific objects that will handle zeta specific & loader specific events needed for zeta to work + DistExecutor.runForDist(() -> () -> new ZetaModClientProxy(zeta), () -> () -> new ZetaModCommonProxy(zeta)); + + ZetaMod.start(zeta); + } + + +} From f69f054cc1aeed7537b58908c7cfe28960c1961c Mon Sep 17 00:00:00 2001 From: MehVahdJukaar Date: Wed, 31 Jul 2024 16:28:12 +0200 Subject: [PATCH 10/22] done? --- build.properties | 2 +- .../client/event/play/ZFirstClientTick.java | 2 +- .../zeta/client/event/play/ZScreenshot.java | 2 +- .../zeta/event/bus/ForgeZetaEventBus.java | 7 +- ...ntBus.java => StandaloneZetaEventBus.java} | 5 +- .../zeta/util/handler/RecipeCrawlHandler.java | 5 - .../violetmoon/zetaimplforge/ForgeZeta.java | 23 ++- .../zetaimplforge/client/ForgeZetaClient.java | 154 +++++------------- .../zetaimplforge/event/NotAForgeWrapper.java | 9 - .../event/load/ForgeZFirstClientTick.java | 8 + .../event/play/ForgeZScreenshot.java | 7 + .../zetaimplforge/mod/ZetaModClientProxy.java | 6 +- .../zetaimplforge/mod/ZetaModForge.java | 2 +- 13 files changed, 85 insertions(+), 147 deletions(-) rename src/main/java/org/violetmoon/zeta/event/bus/{FabricZetaEventBus.java => StandaloneZetaEventBus.java} (96%) delete mode 100644 src/main/java/org/violetmoon/zetaimplforge/event/NotAForgeWrapper.java create mode 100644 src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZFirstClientTick.java create mode 100644 src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZScreenshot.java diff --git a/build.properties b/build.properties index 3375784..e0a2228 100644 --- a/build.properties +++ b/build.properties @@ -5,5 +5,5 @@ mod_name=Zeta mc_version=1.20.1 mapping_channel=official mod_id=zeta -build_number=20 +build_number=20-event dir_output=../Build Output/Zeta/ diff --git a/src/main/java/org/violetmoon/zeta/client/event/play/ZFirstClientTick.java b/src/main/java/org/violetmoon/zeta/client/event/play/ZFirstClientTick.java index e0c09a7..5b67350 100644 --- a/src/main/java/org/violetmoon/zeta/client/event/play/ZFirstClientTick.java +++ b/src/main/java/org/violetmoon/zeta/client/event/play/ZFirstClientTick.java @@ -2,4 +2,4 @@ import org.violetmoon.zeta.event.bus.IZetaLoadEvent; -public class ZFirstClientTick implements IZetaLoadEvent { } +public interface ZFirstClientTick extends IZetaLoadEvent { } diff --git a/src/main/java/org/violetmoon/zeta/client/event/play/ZScreenshot.java b/src/main/java/org/violetmoon/zeta/client/event/play/ZScreenshot.java index 8492d4e..22e6bd7 100644 --- a/src/main/java/org/violetmoon/zeta/client/event/play/ZScreenshot.java +++ b/src/main/java/org/violetmoon/zeta/client/event/play/ZScreenshot.java @@ -2,4 +2,4 @@ import org.violetmoon.zeta.event.bus.IZetaPlayEvent; -public class ZScreenshot implements IZetaPlayEvent { } +public interface ZScreenshot extends IZetaPlayEvent { } diff --git a/src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java b/src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java index 487639d..8bbfced 100644 --- a/src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java +++ b/src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java @@ -9,9 +9,6 @@ import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.violetmoon.zeta.event.load.ZModulesReady; -import org.violetmoon.zetaimplforge.event.NotAForgeWrapper; -import org.violetmoon.zetaimplforge.event.load.ForgeZConfigChange; import java.lang.annotation.Annotation; import java.lang.invoke.MethodHandle; @@ -180,7 +177,7 @@ public void registerSubClassWithGeneric(Class b public void registerSubClass(Class baseZetaEventClass, Class forgeZetaEventClass, @Nullable Function constructor) { - Object old1 = null; + Object old1; Object old2 = null; boolean isNoWrapper = false; if (constructor == null) { @@ -193,7 +190,7 @@ public void registerSubClass(Class baseZetaEven else constructor = findForgeWrapper(forgeZetaEventClass); } if (constructor == null) { - throw new RuntimeException("No forge-Event-wrapping constructor found for Zeta event class " + forgeZetaEventClass); + throw new RuntimeException("No Forge-Event-wrapping constructor found for Zeta event class " + forgeZetaEventClass); } else { old1 = forgeToZetaMap.put(baseZetaEventClass, constructor); } diff --git a/src/main/java/org/violetmoon/zeta/event/bus/FabricZetaEventBus.java b/src/main/java/org/violetmoon/zeta/event/bus/StandaloneZetaEventBus.java similarity index 96% rename from src/main/java/org/violetmoon/zeta/event/bus/FabricZetaEventBus.java rename to src/main/java/org/violetmoon/zeta/event/bus/StandaloneZetaEventBus.java index 47c4f0c..e0d9966 100644 --- a/src/main/java/org/violetmoon/zeta/event/bus/FabricZetaEventBus.java +++ b/src/main/java/org/violetmoon/zeta/event/bus/StandaloneZetaEventBus.java @@ -12,7 +12,6 @@ import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.violetmoon.zeta.Zeta; /** * A polymorphic event bus. Events can be fired under one of their supertypes, allowing a sort of API/impl split of events. @@ -22,7 +21,7 @@ * - registering an anonymous `Consumer` (like Forge's "addListener" method) * Supported Java reflection APIs don't expose this information. Forge can only get at it with a library internally using sun.misc.Unsafe. */ -public class FabricZetaEventBus extends ZetaEventBus { +public class StandaloneZetaEventBus extends ZetaEventBus { private final Map, Listeners> listenerMap = new HashMap<>(); @@ -31,7 +30,7 @@ public class FabricZetaEventBus extends ZetaEventBus { * @param eventRoot The superinterface of all events fired on this bus. * @param logSpam */ - public FabricZetaEventBus(Class subscriberAnnotation, Class eventRoot, @Nullable Logger logSpam) { + public StandaloneZetaEventBus(Class subscriberAnnotation, Class eventRoot, @Nullable Logger logSpam) { super(subscriberAnnotation, eventRoot, logSpam); } diff --git a/src/main/java/org/violetmoon/zeta/util/handler/RecipeCrawlHandler.java b/src/main/java/org/violetmoon/zeta/util/handler/RecipeCrawlHandler.java index 860bb9c..eb41002 100644 --- a/src/main/java/org/violetmoon/zeta/util/handler/RecipeCrawlHandler.java +++ b/src/main/java/org/violetmoon/zeta/util/handler/RecipeCrawlHandler.java @@ -129,11 +129,6 @@ else if (recipe instanceof AbstractCookingRecipe acr) } } - @PlayEvent - public static void a (ZRenderGuiOverlay.ArmorLevel.Pre aa){ - int aaa = 1; - } - @PlayEvent public static void onTick(ZServerTick.Start tick) { synchronized (mutex) { diff --git a/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java b/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java index 0d23211..7ba7007 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java +++ b/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java @@ -18,7 +18,6 @@ import net.minecraftforge.eventbus.api.EventPriority; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fml.ModList; -import net.minecraftforge.fml.event.lifecycle.FMLLoadCompleteEvent; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import net.minecraftforge.fml.loading.FMLEnvironment; import net.minecraftforge.registries.RegisterEvent; @@ -27,11 +26,8 @@ import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.block.ext.BlockExtensionFactory; import org.violetmoon.zeta.capability.ZetaCapabilityManager; -import org.violetmoon.zeta.client.ClientRegistryExtension; -import org.violetmoon.zeta.client.ZetaClient; import org.violetmoon.zeta.client.event.load.*; import org.violetmoon.zeta.client.event.play.*; -import org.violetmoon.zeta.config.ConfigManager; import org.violetmoon.zeta.config.IZetaConfigInternals; import org.violetmoon.zeta.config.SectionDefinition; import org.violetmoon.zeta.event.bus.*; @@ -49,7 +45,6 @@ import org.violetmoon.zetaimplforge.api.ForgeZGatherAdvancementModifiers; import org.violetmoon.zetaimplforge.block.IForgeBlockBlockExtensions; import org.violetmoon.zetaimplforge.capability.ForgeCapabilityManager; -import org.violetmoon.zetaimplforge.client.ForgeZetaClient; import org.violetmoon.zetaimplforge.client.event.load.*; import org.violetmoon.zetaimplforge.client.event.play.*; import org.violetmoon.zetaimplforge.config.ConfigEventDispatcher; @@ -80,8 +75,7 @@ public ForgeZeta(String modid, Logger log) { @Override protected ZetaEventBus createLoadBus() { - if (false) return new FabricZetaEventBus<>(LoadEvent.class, - IZetaLoadEvent.class, log); + //return new StandaloneZetaEventBus<>(LoadEvent.class, IZetaLoadEvent.class, log); var bus = new ForgeZetaEventBus<>(LoadEvent.class, IZetaLoadEvent.class, log, FMLJavaModLoadingContext.get().getModEventBus(), Event.class); @@ -106,6 +100,7 @@ protected ZetaEventBus createLoadBus() { bus.registerSubClass(ZModel.ModifyBakingResult.class, ForgeZModel.ModifyBakingResult.class); bus.registerSubClass(ZRegisterLayerDefinitions.class, ForgeZRegisterLayerDefinitions.class); bus.registerSubClass(ZTooltipComponents.class, ForgeZTooltipComponents.class); + bus.registerSubClass(ZFirstClientTick.class, ForgeZFirstClientTick.class); bus.registerSubClass(ZAddBlockColorHandlers.class, ForgeZAddBlockColorHandlers.class, (Function) inner -> @@ -196,6 +191,20 @@ protected ZetaEventBus createLoadBus() { bus.registerSubClass(ZScreen.Render.class, ForgeZScreen.Render.class); bus.registerSubClass(ZRenderGuiOverlay.ArmorLevel.Pre.class, ForgeZRenderGuiOverlay.ArmorLevel.Pre.class); bus.registerSubClass(ZRenderGuiOverlay.ArmorLevel.Post.class, ForgeZRenderGuiOverlay.ArmorLevel.Post.class); + bus.registerSubClass(ZRenderGuiOverlay.Crosshair.Pre.class, ForgeZRenderGuiOverlay.Crosshair.Post.class); + bus.registerSubClass(ZRenderGuiOverlay.Crosshair.Post.class, ForgeZRenderGuiOverlay.Crosshair.Pre.class); + bus.registerSubClass(ZRenderGuiOverlay.DebugText.Pre.class, ForgeZRenderGuiOverlay.DebugText.Pre.class); + bus.registerSubClass(ZRenderGuiOverlay.DebugText.Post.class, ForgeZRenderGuiOverlay.DebugText.Post.class); + bus.registerSubClass(ZRenderGuiOverlay.Hotbar.Pre.class, ForgeZRenderGuiOverlay.Hotbar.Pre.class); + bus.registerSubClass(ZRenderGuiOverlay.Hotbar.Post.class, ForgeZRenderGuiOverlay.Hotbar.Post.class); + bus.registerSubClass(ZRenderGuiOverlay.PlayerHealth.Pre.class, ForgeZRenderGuiOverlay.PlayerHealth.Pre.class); + bus.registerSubClass(ZRenderGuiOverlay.PlayerHealth.Post.class, ForgeZRenderGuiOverlay.PlayerHealth.Post.class); + bus.registerSubClass(ZRenderGuiOverlay.PotionIcons.Pre.class, ForgeZRenderGuiOverlay.PotionIcons.Pre.class); + bus.registerSubClass(ZRenderGuiOverlay.PotionIcons.Post.class, ForgeZRenderGuiOverlay.PotionIcons.Post.class); + bus.registerSubClass(ZRenderGuiOverlay.ChatPanel.Pre.class, ForgeZRenderGuiOverlay.ChatPanel.Pre.class); + bus.registerSubClass(ZRenderGuiOverlay.ChatPanel.Post.class, ForgeZRenderGuiOverlay.ChatPanel.Post.class); + bus.registerSubClass(ZScreenshot.class, ForgeZScreenshot.class); + //this is ugly. generic events here Zeta zeta = this; diff --git a/src/main/java/org/violetmoon/zetaimplforge/client/ForgeZetaClient.java b/src/main/java/org/violetmoon/zetaimplforge/client/ForgeZetaClient.java index 444206e..a136840 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/client/ForgeZetaClient.java +++ b/src/main/java/org/violetmoon/zetaimplforge/client/ForgeZetaClient.java @@ -1,60 +1,5 @@ package org.violetmoon.zetaimplforge.client; -import net.minecraftforge.client.gui.overlay.NamedGuiOverlay; -import org.jetbrains.annotations.Nullable; -import org.violetmoon.zeta.Zeta; -import org.violetmoon.zeta.client.ClientRegistryExtension; -import org.violetmoon.zeta.client.HumanoidArmorModelGetter; -import org.violetmoon.zeta.client.ZetaClient; -import org.violetmoon.zeta.client.event.load.ZAddBlockColorHandlers; -import org.violetmoon.zeta.client.event.load.ZAddItemColorHandlers; -import org.violetmoon.zeta.client.event.load.ZAddModelLayers; -import org.violetmoon.zeta.client.event.load.ZAddModels; -import org.violetmoon.zeta.client.event.load.ZClientSetup; -import org.violetmoon.zeta.client.event.load.ZKeyMapping; -import org.violetmoon.zeta.client.event.load.ZModel; -import org.violetmoon.zeta.client.event.load.ZRegisterLayerDefinitions; -import org.violetmoon.zeta.client.event.load.ZRegisterReloadListeners; -import org.violetmoon.zeta.client.event.load.ZTooltipComponents; -import org.violetmoon.zeta.client.event.play.ZClientTick; -import org.violetmoon.zeta.client.event.play.ZFirstClientTick; -import org.violetmoon.zeta.client.event.play.ZGatherTooltipComponents; -import org.violetmoon.zeta.client.event.play.ZHighlightBlock; -import org.violetmoon.zeta.client.event.play.ZInput; -import org.violetmoon.zeta.client.event.play.ZInputUpdate; -import org.violetmoon.zeta.client.event.play.ZRenderContainerScreen; -import org.violetmoon.zeta.client.event.play.ZRenderGuiOverlay; -import org.violetmoon.zeta.client.event.play.ZRenderLiving; -import org.violetmoon.zeta.client.event.play.ZRenderPlayer; -import org.violetmoon.zeta.client.event.play.ZRenderTick; -import org.violetmoon.zeta.client.event.play.ZRenderTooltip; -import org.violetmoon.zeta.client.event.play.ZScreen; -import org.violetmoon.zeta.client.event.play.ZScreenshot; -import org.violetmoon.zeta.util.zetalist.ZetaClientList; -import org.violetmoon.zetaimplforge.client.event.load.ForgeZAddBlockColorHandlers; -import org.violetmoon.zetaimplforge.client.event.load.ForgeZAddItemColorHandlers; -import org.violetmoon.zetaimplforge.client.event.load.ForgeZAddModelLayers; -import org.violetmoon.zetaimplforge.client.event.load.ForgeZAddModels; -import org.violetmoon.zetaimplforge.client.event.load.ForgeZClientSetup; -import org.violetmoon.zetaimplforge.client.event.load.ForgeZKeyMapping; -import org.violetmoon.zetaimplforge.client.event.load.ForgeZModel; -import org.violetmoon.zetaimplforge.client.event.load.ForgeZRegisterLayerDefinitions; -import org.violetmoon.zetaimplforge.client.event.load.ForgeZTooltipComponents; -import org.violetmoon.zetaimplforge.client.event.play.ForgeZClientTick; -import org.violetmoon.zetaimplforge.client.event.play.ForgeZGatherTooltipComponents; -import org.violetmoon.zetaimplforge.client.event.play.ForgeZHighlightBlock; -import org.violetmoon.zetaimplforge.client.event.play.ForgeZInput; -import org.violetmoon.zetaimplforge.client.event.play.ForgeZInputUpdate; -import org.violetmoon.zetaimplforge.client.event.play.ForgeZRenderContainerScreen; -import org.violetmoon.zetaimplforge.client.event.play.ForgeZRenderGuiOverlay; -import org.violetmoon.zetaimplforge.client.event.play.ForgeZRenderLiving; -import org.violetmoon.zetaimplforge.client.event.play.ForgeZRenderPlayer; -import org.violetmoon.zetaimplforge.client.event.play.ForgeZRenderTick; -import org.violetmoon.zetaimplforge.client.event.play.ForgeZRenderTooltip; -import org.violetmoon.zetaimplforge.client.event.play.ForgeZScreen; -import org.violetmoon.zetaimplforge.mixin.mixins.client.AccessorBlockColors; -import org.violetmoon.zetaimplforge.mixin.mixins.client.AccessorItemColors; - import net.minecraft.client.Minecraft; import net.minecraft.client.color.block.BlockColor; import net.minecraft.client.color.block.BlockColors; @@ -66,75 +11,58 @@ import net.minecraft.world.item.Item; import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.block.Block; -import net.minecraftforge.client.event.ContainerScreenEvent; -import net.minecraftforge.client.event.EntityRenderersEvent; -import net.minecraftforge.client.event.InputEvent; -import net.minecraftforge.client.event.ModelEvent; -import net.minecraftforge.client.event.MovementInputUpdateEvent; -import net.minecraftforge.client.event.RegisterClientReloadListenersEvent; -import net.minecraftforge.client.event.RegisterClientTooltipComponentFactoriesEvent; -import net.minecraftforge.client.event.RegisterColorHandlersEvent; -import net.minecraftforge.client.event.RegisterKeyMappingsEvent; -import net.minecraftforge.client.event.RenderGuiOverlayEvent; -import net.minecraftforge.client.event.RenderHighlightEvent; -import net.minecraftforge.client.event.RenderLivingEvent; -import net.minecraftforge.client.event.RenderPlayerEvent; -import net.minecraftforge.client.event.RenderTooltipEvent; -import net.minecraftforge.client.event.ScreenEvent; -import net.minecraftforge.client.event.ScreenshotEvent; -import net.minecraftforge.client.gui.overlay.VanillaGuiOverlay; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.event.TickEvent; -import net.minecraftforge.eventbus.api.EventPriority; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; -import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import net.minecraftforge.fml.util.thread.EffectiveSide; import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.server.ServerLifecycleHooks; +import org.jetbrains.annotations.Nullable; +import org.violetmoon.zeta.Zeta; +import org.violetmoon.zeta.client.ClientRegistryExtension; +import org.violetmoon.zeta.client.HumanoidArmorModelGetter; +import org.violetmoon.zeta.client.ZetaClient; +import org.violetmoon.zetaimplforge.mixin.mixins.client.AccessorBlockColors; +import org.violetmoon.zetaimplforge.mixin.mixins.client.AccessorItemColors; public class ForgeZetaClient extends ZetaClient { - public ForgeZetaClient(Zeta z) { - super(z); - } - - @Override - public @Nullable BlockColor getBlockColor(BlockColors bcs, Block block) { - return ForgeRegistries.BLOCKS.getDelegate(block) - .map(ref -> ((AccessorBlockColors) bcs).zeta$getBlockColors().get(ref)) - .orElse(null); - } + public ForgeZetaClient(Zeta z) { + super(z); + } - @Override - public @Nullable ItemColor getItemColor(ItemColors ics, ItemLike itemlike) { - return ForgeRegistries.ITEMS.getDelegate(itemlike.asItem()) - .map(ref -> ((AccessorItemColors) ics).zeta$getItemColors().get(ref)) - .orElse(null); - } + @Override + public @Nullable BlockColor getBlockColor(BlockColors bcs, Block block) { + return ForgeRegistries.BLOCKS.getDelegate(block) + .map(ref -> ((AccessorBlockColors) bcs).zeta$getBlockColors().get(ref)) + .orElse(null); + } - @Override - public ClientRegistryExtension createClientRegistryExtension() { - return new ForgeClientRegistryExtension(zeta); - } + @Override + public @Nullable ItemColor getItemColor(ItemColors ics, ItemLike itemlike) { + return ForgeRegistries.ITEMS.getDelegate(itemlike.asItem()) + .map(ref -> ((AccessorItemColors) ics).zeta$getItemColors().get(ref)) + .orElse(null); + } - @Override - public void setBlockEntityWithoutLevelRenderer(Item item, BlockEntityWithoutLevelRenderer bewlr) { - ((IZetaForgeItemStuff) item).zeta$setBlockEntityWithoutLevelRenderer(bewlr); - } + @Override + public ClientRegistryExtension createClientRegistryExtension() { + return new ForgeClientRegistryExtension(zeta); + } - @Override - public void setHumanoidArmorModel(Item item, HumanoidArmorModelGetter modelGetter) { - ((IZetaForgeItemStuff) item).zeta$setHumanoidArmorModel(modelGetter); - } + @Override + public void setBlockEntityWithoutLevelRenderer(Item item, BlockEntityWithoutLevelRenderer bewlr) { + ((IZetaForgeItemStuff) item).zeta$setBlockEntityWithoutLevelRenderer(bewlr); + } - @Override - public RegistryAccess hackilyGetCurrentClientLevelRegistryAccess() { - if(EffectiveSide.get().isServer()) - return ServerLifecycleHooks.getCurrentServer().registryAccess(); + @Override + public void setHumanoidArmorModel(Item item, HumanoidArmorModelGetter modelGetter) { + ((IZetaForgeItemStuff) item).zeta$setHumanoidArmorModel(modelGetter); + } - ClientPacketListener conn = Minecraft.getInstance().getConnection(); - return conn == null ? null : conn.registryAccess(); - } + @Override + public RegistryAccess hackilyGetCurrentClientLevelRegistryAccess() { + if (EffectiveSide.get().isServer()) + return ServerLifecycleHooks.getCurrentServer().registryAccess(); + ClientPacketListener conn = Minecraft.getInstance().getConnection(); + return conn == null ? null : conn.registryAccess(); + } } diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/NotAForgeWrapper.java b/src/main/java/org/violetmoon/zetaimplforge/event/NotAForgeWrapper.java deleted file mode 100644 index 249ca03..0000000 --- a/src/main/java/org/violetmoon/zetaimplforge/event/NotAForgeWrapper.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.violetmoon.zetaimplforge.event; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -// Hideous marker interface used to denote Zeta specific events that are NOT supposed to be remapped to forge events -@Retention(RetentionPolicy.RUNTIME) -public @interface NotAForgeWrapper { -} diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZFirstClientTick.java b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZFirstClientTick.java new file mode 100644 index 0000000..d881ed7 --- /dev/null +++ b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZFirstClientTick.java @@ -0,0 +1,8 @@ +package org.violetmoon.zetaimplforge.event.load; + +import net.minecraftforge.eventbus.api.Event; +import org.violetmoon.zeta.client.event.play.ZFirstClientTick; + +public class ForgeZFirstClientTick extends Event implements ZFirstClientTick { + +} diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZScreenshot.java b/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZScreenshot.java new file mode 100644 index 0000000..65db1bc --- /dev/null +++ b/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZScreenshot.java @@ -0,0 +1,7 @@ +package org.violetmoon.zetaimplforge.event.play; + +import net.minecraftforge.eventbus.api.Event; +import org.violetmoon.zeta.client.event.play.ZScreenshot; + +public class ForgeZScreenshot extends Event implements ZScreenshot { +} diff --git a/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModClientProxy.java b/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModClientProxy.java index 77399d5..0a8b3c8 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModClientProxy.java +++ b/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModClientProxy.java @@ -5,14 +5,18 @@ import net.minecraftforge.client.gui.overlay.VanillaGuiOverlay; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.TickEvent; +import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.client.TopLayerTooltipHandler; import org.violetmoon.zeta.client.event.play.ZFirstClientTick; import org.violetmoon.zeta.client.event.play.ZRenderGuiOverlay; import org.violetmoon.zeta.util.handler.RequiredModTooltipHandler; +import org.violetmoon.zeta.util.handler.ToolInteractionHandler; import org.violetmoon.zeta.util.zetalist.ZetaList; import org.violetmoon.zetaimplforge.client.ForgeZetaClient; import org.violetmoon.zetaimplforge.client.event.play.ForgeZRenderGuiOverlay; +import org.violetmoon.zetaimplforge.event.load.ForgeZFirstClientTick; +import org.violetmoon.zetaimplforge.world.ZetaBiomeModifier; public class ZetaModClientProxy extends ZetaModCommonProxy { @@ -36,7 +40,7 @@ public ZetaModClientProxy(Zeta zeta) { boolean clientTicked = false; public void clientTick(TickEvent.ClientTickEvent e) { if(!clientTicked) { - ZetaList.INSTANCE.fireLoadEvent(new ZFirstClientTick()); + ZetaList.INSTANCE.fireLoadEvent(new ForgeZFirstClientTick()); clientTicked = true; } } diff --git a/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModForge.java b/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModForge.java index bda1cd2..64d1c7c 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModForge.java +++ b/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModForge.java @@ -13,11 +13,11 @@ public class ZetaModForge { public ZetaModForge() { ForgeZeta zeta = new ForgeZeta(Zeta.ZETA_ID, LogManager.getLogger(Zeta.ZETA_ID + "-internal")); + ZetaMod.start(zeta); // creates 2 dist specific objects that will handle zeta specific & loader specific events needed for zeta to work DistExecutor.runForDist(() -> () -> new ZetaModClientProxy(zeta), () -> () -> new ZetaModCommonProxy(zeta)); - ZetaMod.start(zeta); } From 95aa7f7cafe6d9578c7de19e04d0df88435ec26c Mon Sep 17 00:00:00 2001 From: MehVahdJukaar Date: Wed, 31 Jul 2024 16:33:31 +0200 Subject: [PATCH 11/22] shut up PMD >:( --- .../org/violetmoon/zeta/event/bus/StandaloneZetaEventBus.java | 2 ++ .../org/violetmoon/zetaimplforge/client/ForgeZetaClient.java | 1 + 2 files changed, 3 insertions(+) diff --git a/src/main/java/org/violetmoon/zeta/event/bus/StandaloneZetaEventBus.java b/src/main/java/org/violetmoon/zeta/event/bus/StandaloneZetaEventBus.java index e0d9966..6f3ad33 100644 --- a/src/main/java/org/violetmoon/zeta/event/bus/StandaloneZetaEventBus.java +++ b/src/main/java/org/violetmoon/zeta/event/bus/StandaloneZetaEventBus.java @@ -47,6 +47,7 @@ protected void unsubscribeMethod(Method m, Object receiver, Class owningClazz /** * Fires an event on the event bus. Each subscriber will be visited in order. */ + @Override public T fire(@NotNull T event) { Listeners subs = listenerMap.get(event.getClass()); if(subs != null) { @@ -65,6 +66,7 @@ public T fire(@NotNull T event) { *

* (The generic should be Class<? super T & ? extends E>, but unfortunately, javac.) */ + @Override public T fire(@NotNull T event, Class firedAs) { Listeners subs = listenerMap.get(firedAs); if(subs != null) { diff --git a/src/main/java/org/violetmoon/zetaimplforge/client/ForgeZetaClient.java b/src/main/java/org/violetmoon/zetaimplforge/client/ForgeZetaClient.java index a136840..f6c6d42 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/client/ForgeZetaClient.java +++ b/src/main/java/org/violetmoon/zetaimplforge/client/ForgeZetaClient.java @@ -19,6 +19,7 @@ import org.violetmoon.zeta.client.ClientRegistryExtension; import org.violetmoon.zeta.client.HumanoidArmorModelGetter; import org.violetmoon.zeta.client.ZetaClient; +import org.violetmoon.zeta.event.bus.StandaloneZetaEventBus; import org.violetmoon.zetaimplforge.mixin.mixins.client.AccessorBlockColors; import org.violetmoon.zetaimplforge.mixin.mixins.client.AccessorItemColors; From 6997e7efe3604d5f2fbc5d458ac6de38adac8888 Mon Sep 17 00:00:00 2001 From: MehVahdJukaar Date: Wed, 31 Jul 2024 18:54:46 +0200 Subject: [PATCH 12/22] gather hints event --- build.properties | 2 +- .../AdvancementModifierRegistry.java | 10 ++++ .../violetmoon/zeta/client/ClientTicker.java | 1 + .../zeta/event/bus/ForgeZetaEventBus.java | 23 +++++----- .../zeta/event/bus/ZetaEventBus.java | 4 ++ .../violetmoon/zetaimplforge/ForgeZeta.java | 33 +++++++++---- .../event/load/ForgeZGatherHints.java | 46 +++++++++++++++++++ 7 files changed, 97 insertions(+), 22 deletions(-) create mode 100644 src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZGatherHints.java diff --git a/build.properties b/build.properties index e0a2228..d719a66 100644 --- a/build.properties +++ b/build.properties @@ -5,5 +5,5 @@ mod_name=Zeta mc_version=1.20.1 mapping_channel=official mod_id=zeta -build_number=20-event +build_number=20-event11 dir_output=../Build Output/Zeta/ diff --git a/src/main/java/org/violetmoon/zeta/advancement/AdvancementModifierRegistry.java b/src/main/java/org/violetmoon/zeta/advancement/AdvancementModifierRegistry.java index 43bfa34..2948dd8 100644 --- a/src/main/java/org/violetmoon/zeta/advancement/AdvancementModifierRegistry.java +++ b/src/main/java/org/violetmoon/zeta/advancement/AdvancementModifierRegistry.java @@ -17,6 +17,7 @@ import org.violetmoon.zeta.advancement.modifier.WaxModifier; import org.violetmoon.zeta.api.IAdvancementModifier; import org.violetmoon.zeta.api.IAdvancementModifierDelegate; +import org.violetmoon.zeta.client.event.play.ZScreen; import org.violetmoon.zeta.event.bus.LoadEvent; import org.violetmoon.zeta.event.bus.PlayEvent; import org.violetmoon.zeta.event.load.ZAddReloadListener; @@ -62,6 +63,15 @@ public void addModifier(IAdvancementModifier mod) { for(ResourceLocation r : mod.getTargets()) modifiers.put(r, mod); } + @PlayEvent + public void test(ZScreen.Init.Post e){ + int aa = 1; + } + + @PlayEvent + public void onInitGui(ZScreen.Init.Pre event) { +int aa = 1; + } @PlayEvent public void addListeners(ZAddReloadListener event) { diff --git a/src/main/java/org/violetmoon/zeta/client/ClientTicker.java b/src/main/java/org/violetmoon/zeta/client/ClientTicker.java index cb28ee2..8a6bd69 100644 --- a/src/main/java/org/violetmoon/zeta/client/ClientTicker.java +++ b/src/main/java/org/violetmoon/zeta/client/ClientTicker.java @@ -8,6 +8,7 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screens.Screen; +//TODO: 1.21. replace with minecraft own ticker. Tbh this is legacy already and should be replaced with Minecraft.getPartialTicks() public final class ClientTicker { public int ticksInGame = 0; public float partialTicks = 0; diff --git a/src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java b/src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java index 8bbfced..0203457 100644 --- a/src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java +++ b/src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java @@ -1,5 +1,6 @@ package org.violetmoon.zeta.event.bus; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import net.minecraftforge.event.TickEvent; import net.minecraftforge.eventbus.api.Event; import net.minecraftforge.eventbus.api.EventPriority; @@ -16,8 +17,8 @@ import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; -import java.util.HashMap; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; @@ -25,11 +26,11 @@ // this is super jank. Basically converts all zeta events to forge ones, then delegates to the forge bus directly public class ForgeZetaEventBus extends ZetaEventBus { - private final Map, Function> forgeToZetaMap = new HashMap<>(); - private final Map, Function> zetaToForgeMap = new HashMap<>(); - private final Map, Class> zetaToForgeEventClass = new HashMap<>(); - private final Map, Class> generics = new HashMap<>(); - private final Map convertedHandlers = new HashMap<>(); + private final Map, Function> forgeToZetaMap = new Object2ObjectOpenHashMap<>(); + private final Map, Function> zetaToForgeMap = new Object2ObjectOpenHashMap<>(); + private final Map, Class> zetaToForgeEventClass = new Object2ObjectOpenHashMap<>(); + private final Map, Class> generics = new Object2ObjectOpenHashMap<>(); + private final Map convertedHandlers = new Object2ObjectOpenHashMap<>(); private final IEventBus forgeBus; private final Class forgeEventRoot; //if Events should implement IModBusEvent @@ -72,6 +73,7 @@ protected void subscribeMethod(Method method, Object receiver, Class owningCl registerListenerToForgeWithPriorityAndGenerics(owningClazz, consumer, zetaEventClass); //store here so we can unregister later convertedHandlers.put(new Key(method, receiver, owningClazz), consumer); + } @@ -127,7 +129,7 @@ private Consumer remapMethod(MethodHandle originalEventConsumer, Cl if (forgeEventRoot.isAssignableFrom(zetaEventBaseClass)) { forgeToZetaFunc = event -> (Z) event; } else - throw new RuntimeException("No forge-Event-wrapping constructor found for Zeta event class. You must register its subclass using registerSubclass. " + zetaEventBaseClass); + throw new RuntimeException("Could not convert Zeta event class " + zetaEventBaseClass + " to Forge event. You must register its subclass using registerSubclass."); } return createForgeConsumer(originalEventConsumer, forgeToZetaFunc, zetaEventBaseClass); } @@ -186,8 +188,7 @@ public void registerSubClass(Class baseZetaEven zetaToForgeEventClass.put(baseZetaEventClass, forgeZetaEventClass); constructor = event -> (ZF) event; isNoWrapper = true; - } - else constructor = findForgeWrapper(forgeZetaEventClass); + } else constructor = findForgeWrapper(forgeZetaEventClass); } if (constructor == null) { throw new RuntimeException("No Forge-Event-wrapping constructor found for Zeta event class " + forgeZetaEventClass); @@ -319,7 +320,7 @@ public static Field findFieldInClassHierarchy(Class clazz, Predicate p private void registerListenerToForgeWithPriorityAndGenerics(Class owningClazz, Consumer consumer, Class zetaEventClass) { EventPriority priority = guessPriorityFromClassName(owningClazz); - Class gen = generics.get(owningClazz); + Class gen = generics.get(zetaEventClass); Class eventType = zetaToForgeEventClass.get(zetaEventClass); if (eventType == null) { throw new RuntimeException("No event type found for " + zetaEventClass); @@ -348,7 +349,7 @@ private static Phase guessFromClassName(Class zetaEventClass) { } - private static final Map, EventPriority> CACHE = new HashMap<>(); + private static final Map, EventPriority> CACHE = new ConcurrentHashMap<>(); private static EventPriority guessPriorityFromClassName(Class zetaEventClass) { return CACHE.computeIfAbsent(zetaEventClass, cl -> { diff --git a/src/main/java/org/violetmoon/zeta/event/bus/ZetaEventBus.java b/src/main/java/org/violetmoon/zeta/event/bus/ZetaEventBus.java index e10100b..d649ec8 100644 --- a/src/main/java/org/violetmoon/zeta/event/bus/ZetaEventBus.java +++ b/src/main/java/org/violetmoon/zeta/event/bus/ZetaEventBus.java @@ -5,6 +5,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.violetmoon.zeta.Zeta; +import org.violetmoon.zeta.advancement.AdvancementModifierRegistry; import org.violetmoon.zeta.util.handler.RecipeCrawlHandler; import java.lang.annotation.Annotation; @@ -48,6 +49,9 @@ public ZetaEventBus subscribe(@NotNull Object target) { receiver = target; owningClazz = target.getClass(); } + if(owningClazz == AdvancementModifierRegistry.class){ + int aa = 1; + } streamAnnotatedMethods(owningClazz, receiver == null) .forEach(m -> subscribeMethod(m, receiver, owningClazz)); return this; diff --git a/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java b/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java index 7ba7007..3196cfc 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java +++ b/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java @@ -115,7 +115,10 @@ protected ZetaEventBus createLoadBus() { protected ForgeZetaEventBus createPlayBus() { var bus = new ForgeZetaEventBus<>(PlayEvent.class, IZetaPlayEvent.class, log, MinecraftForge.EVENT_BUS, Event.class); bus.registerSubClass(ZAnvilRepair.class, ForgeZAnvilRepair.class); + bus.registerSubClass(ZAnvilUpdate.Highest.class, ForgeZAnvilUpdate.Highest.class); + bus.registerSubClass(ZAnvilUpdate.Lowest.class, ForgeZAnvilUpdate.Lowest.class); bus.registerSubClass(ZTagsUpdated.class, ForgeZTagsUpdated.class); + bus.registerSubClass(ZBabyEntitySpawn.Lowest.class, ForgeZBabyEntitySpawn.Lowest.class); bus.registerSubClass(ZBabyEntitySpawn.class, ForgeZBabyEntitySpawn.class); bus.registerSubClass(ZBlock.Break.class, ForgeZBlock.Break.class); bus.registerSubClass(ZBlock.EntityPlace.class, ForgeZBlock.EntityPlace.class); @@ -167,6 +170,7 @@ protected ZetaEventBus createLoadBus() { bus.registerSubClass(ZServerTick.End.class, ForgeZServerTick.End.class); bus.registerSubClass(ZAddReloadListener.class, ForgeZAddReloadListener.class); bus.registerSubClass(ZGatherAdvancementModifiers.class, ForgeZGatherAdvancementModifiers.class); + bus.registerSubClass(ZGatherHints.class, ForgeZGatherHints.class); //Hmm client events here? maybe i should move them @@ -177,18 +181,28 @@ protected ZetaEventBus createLoadBus() { bus.registerSubClass(ZInput.MouseButton.class, ForgeZInput.MouseButton.class); bus.registerSubClass(ZInput.Key.class, ForgeZInput.Key.class); bus.registerSubClass(ZInputUpdate.class, ForgeZInputUpdate.class); - bus.registerSubClass(ZRenderContainerScreen.class, ForgeZRenderContainerScreen.class); - bus.registerSubClass(ZRenderLiving.class, ForgeZRenderLiving.class); - bus.registerSubClass(ZRenderPlayer.class, ForgeZRenderPlayer.class); + bus.registerSubClass(ZRenderContainerScreen.Background.class, ForgeZRenderContainerScreen.Background.class); + bus.registerSubClass(ZRenderContainerScreen.Foreground.class, ForgeZRenderContainerScreen.Foreground.class); + bus.registerSubClass(ZRenderLiving.PostLowest.class, ForgeZRenderLiving.PostLowest.class); + bus.registerSubClass(ZRenderLiving.PreHighest.class, ForgeZRenderLiving.PreHighest.class); + bus.registerSubClass(ZRenderPlayer.Post.class, ForgeZRenderPlayer.Post.class); + bus.registerSubClass(ZRenderPlayer.Pre.class, ForgeZRenderPlayer.Pre.class); bus.registerSubClass(ZRenderTick.class, ForgeZRenderTick.class); bus.registerSubClass(ZRenderTooltip.GatherComponents.class, ForgeZRenderTooltip.GatherComponents.class); + bus.registerSubClass(ZRenderTooltip.GatherComponents.Low.class, ForgeZRenderTooltip.GatherComponents.Low.class); bus.registerSubClass(ZScreen.Opening.class, ForgeZScreen.Opening.class); - bus.registerSubClass(ZScreen.CharacterTyped.class, ForgeZScreen.CharacterTyped.class); - bus.registerSubClass(ZScreen.Init.class, ForgeZScreen.Init.class); - bus.registerSubClass(ZScreen.KeyPressed.class, ForgeZScreen.KeyPressed.class); - bus.registerSubClass(ZScreen.MouseScrolled.class, ForgeZScreen.MouseScrolled.class); - bus.registerSubClass(ZScreen.MouseButtonPressed.class, ForgeZScreen.MouseButtonPressed.class); - bus.registerSubClass(ZScreen.Render.class, ForgeZScreen.Render.class); + bus.registerSubClass(ZScreen.CharacterTyped.Pre.class, ForgeZScreen.CharacterTyped.Pre.class); + bus.registerSubClass(ZScreen.CharacterTyped.Post.class, ForgeZScreen.CharacterTyped.Post.class); + bus.registerSubClass(ZScreen.Init.Post.class, ForgeZScreen.Init.Post.class); + bus.registerSubClass(ZScreen.Init.Pre.class, ForgeZScreen.Init.Pre.class); + bus.registerSubClass(ZScreen.KeyPressed.Post.class, ForgeZScreen.KeyPressed.Post.class); + bus.registerSubClass(ZScreen.KeyPressed.Pre.class, ForgeZScreen.KeyPressed.Pre.class); + bus.registerSubClass(ZScreen.MouseScrolled.Post.class, ForgeZScreen.MouseScrolled.Post.class); + bus.registerSubClass(ZScreen.MouseScrolled.Pre.class, ForgeZScreen.MouseScrolled.Pre.class); + bus.registerSubClass(ZScreen.MouseButtonPressed.Post.class, ForgeZScreen.MouseButtonPressed.Post.class); + bus.registerSubClass(ZScreen.MouseButtonPressed.Pre.class, ForgeZScreen.MouseButtonPressed.Pre.class); + bus.registerSubClass(ZScreen.Render.Post.class, ForgeZScreen.Render.Post.class); + bus.registerSubClass(ZScreen.Render.Pre.class, ForgeZScreen.Render.Pre.class); bus.registerSubClass(ZRenderGuiOverlay.ArmorLevel.Pre.class, ForgeZRenderGuiOverlay.ArmorLevel.Pre.class); bus.registerSubClass(ZRenderGuiOverlay.ArmorLevel.Post.class, ForgeZRenderGuiOverlay.ArmorLevel.Post.class); bus.registerSubClass(ZRenderGuiOverlay.Crosshair.Pre.class, ForgeZRenderGuiOverlay.Crosshair.Post.class); @@ -205,7 +219,6 @@ protected ZetaEventBus createLoadBus() { bus.registerSubClass(ZRenderGuiOverlay.ChatPanel.Post.class, ForgeZRenderGuiOverlay.ChatPanel.Post.class); bus.registerSubClass(ZScreenshot.class, ForgeZScreenshot.class); - //this is ugly. generic events here Zeta zeta = this; bus.registerSubClassWithGeneric(ZAttachCapabilities.BlockEntityCaps.class, diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZGatherHints.java b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZGatherHints.java new file mode 100644 index 0000000..a47556b --- /dev/null +++ b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZGatherHints.java @@ -0,0 +1,46 @@ +package org.violetmoon.zetaimplforge.event.load; + +import net.minecraft.core.RegistryAccess; +import net.minecraft.network.chat.Component; +import net.minecraft.server.ReloadableServerResources; +import net.minecraft.server.packs.resources.PreparableReloadListener; +import net.minecraft.world.level.ItemLike; +import net.minecraftforge.event.AddReloadListenerEvent; +import net.minecraftforge.eventbus.api.Event; +import org.violetmoon.zeta.Zeta; +import org.violetmoon.zeta.config.ConfigFlagManager; +import org.violetmoon.zeta.event.play.loading.ZGatherHints; +import org.violetmoon.zeta.module.ZetaModule; + +public class ForgeZGatherHints extends Event implements ZGatherHints { + private final ZGatherHints wrapped; + + public ForgeZGatherHints(ZGatherHints e) { + this.wrapped = e; + } + + @Override + public void accept(ItemLike itemLike, Component extra) { + wrapped.accept(itemLike, extra); + } + + @Override + public RegistryAccess getRegistryAccess() { + return wrapped.getRegistryAccess(); + } + + @Override + public void hintItem(Zeta zeta, ItemLike itemLike, Object... extra) { + wrapped.hintItem(zeta, itemLike, extra); + } + + @Override + public void hintItem(Zeta zeta, ItemLike itemLike, String key, Object... extra) { + wrapped.hintItem(zeta, itemLike, key, extra); + } + + @Override + public void gatherHintsFromModule(ZetaModule module, ConfigFlagManager cfm) { + wrapped.gatherHintsFromModule(module, cfm); + } +} From 6919d050df26c1831fad30b1c73ec105c85ea3bc Mon Sep 17 00:00:00 2001 From: MehVahdJukaar Date: Wed, 31 Jul 2024 19:53:32 +0200 Subject: [PATCH 13/22] more missing events --- build.properties | 2 +- src/main/java/org/violetmoon/zeta/Zeta.java | 4 +-- .../AdvancementModifierRegistry.java | 11 +------- .../zeta/event/bus/ForgeZetaEventBus.java | 26 ++++++++++++++----- .../violetmoon/zetaimplforge/ForgeZeta.java | 2 ++ .../client/event/play/ForgeZScreen.java | 4 +-- .../event/load/ForgeZFirstClientTick.java | 3 ++- 7 files changed, 29 insertions(+), 23 deletions(-) diff --git a/build.properties b/build.properties index d719a66..c2ba099 100644 --- a/build.properties +++ b/build.properties @@ -5,5 +5,5 @@ mod_name=Zeta mc_version=1.20.1 mapping_channel=official mod_id=zeta -build_number=20-event11 +build_number=20-event15 dir_output=../Build Output/Zeta/ diff --git a/src/main/java/org/violetmoon/zeta/Zeta.java b/src/main/java/org/violetmoon/zeta/Zeta.java index 525afde..0e48649 100644 --- a/src/main/java/org/violetmoon/zeta/Zeta.java +++ b/src/main/java/org/violetmoon/zeta/Zeta.java @@ -74,11 +74,11 @@ public Zeta(String modid, Logger log, ZetaSide side) { loadBus.subscribe(craftingExtensions) .subscribe(dyeables) .subscribe(brewingRegistry) - .subscribe(advancementModifierRegistry) .subscribe(fuel) .subscribe(entitySpawn); - playBus.subscribe(fuel); + playBus.subscribe(fuel) + .subscribe(advancementModifierRegistry); ZetaList.INSTANCE.register(this); } diff --git a/src/main/java/org/violetmoon/zeta/advancement/AdvancementModifierRegistry.java b/src/main/java/org/violetmoon/zeta/advancement/AdvancementModifierRegistry.java index 2948dd8..8284839 100644 --- a/src/main/java/org/violetmoon/zeta/advancement/AdvancementModifierRegistry.java +++ b/src/main/java/org/violetmoon/zeta/advancement/AdvancementModifierRegistry.java @@ -63,15 +63,6 @@ public void addModifier(IAdvancementModifier mod) { for(ResourceLocation r : mod.getTargets()) modifiers.put(r, mod); } - @PlayEvent - public void test(ZScreen.Init.Post e){ - int aa = 1; - } - - @PlayEvent - public void onInitGui(ZScreen.Init.Pre event) { -int aa = 1; - } @PlayEvent public void addListeners(ZAddReloadListener event) { @@ -87,7 +78,7 @@ public void register(IAdvancementModifier modifier) { public IAdvancementModifierDelegate getDelegate() { return delegateImpl; } - }); + }, ZGatherAdvancementModifiers.class); gatheredAddons = true; } diff --git a/src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java b/src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java index 0203457..fbcb6be 100644 --- a/src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java +++ b/src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java @@ -10,6 +10,7 @@ import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.violetmoon.zeta.Zeta; import java.lang.annotation.Annotation; import java.lang.invoke.MethodHandle; @@ -28,9 +29,13 @@ public class ForgeZetaEventBus extends ZetaEventBus { private final Map, Function> forgeToZetaMap = new Object2ObjectOpenHashMap<>(); private final Map, Function> zetaToForgeMap = new Object2ObjectOpenHashMap<>(); - private final Map, Class> zetaToForgeEventClass = new Object2ObjectOpenHashMap<>(); private final Map, Class> generics = new Object2ObjectOpenHashMap<>(); + + // needed so we can unregister later private final Map convertedHandlers = new Object2ObjectOpenHashMap<>(); + // hack needed to store classes of each Z event to Forge event. + // Needed because java has type erasure so forge be able to add listeners to anonymous generic lambdas without being passed an event type class + private final Map, Class> zetaToForgeEventClassHack = new Object2ObjectOpenHashMap<>(); private final IEventBus forgeBus; private final Class forgeEventRoot; //if Events should implement IModBusEvent @@ -185,10 +190,10 @@ public void registerSubClass(Class baseZetaEven if (constructor == null) { // if it's an Event already just returns the no argument constructor if (forgeEventRoot.isAssignableFrom(forgeZetaEventClass)) { - zetaToForgeEventClass.put(baseZetaEventClass, forgeZetaEventClass); + zetaToForgeEventClassHack.put(baseZetaEventClass, forgeZetaEventClass); constructor = event -> (ZF) event; isNoWrapper = true; - } else constructor = findForgeWrapper(forgeZetaEventClass); + } else constructor = findForgeWrapper(forgeZetaEventClass, baseZetaEventClass); } if (constructor == null) { throw new RuntimeException("No Forge-Event-wrapping constructor found for Zeta event class " + forgeZetaEventClass); @@ -223,16 +228,19 @@ public void registerSubClass(Class baseZetaEven /** * @param zetaEventClass i.e: ForgeZClientSetup.class + * @param baseZetaEventClass i.e: ZClientSetup.class *

* Attempts to find a constructor of zetaEventClass which takes an Event as a parameter. This is used for simple forge Event wrappers * in this example the one found will be new ForgeZClientSetup(FMLClientSetupEvent event) */ - private Function findForgeWrapper(Class zetaEventClass) { + private Function findForgeWrapper(Class zetaEventClass, Class baseZetaEventClass) { // Find the constructor that takes a single parameter of type A for (Constructor constructor : zetaEventClass.getConstructors()) { Class[] parameterTypes = constructor.getParameterTypes(); if (parameterTypes.length == 1 && forgeEventRoot.isAssignableFrom(parameterTypes[0])) { + zetaToForgeEventClassHack.put(baseZetaEventClass, parameterTypes[0]); + return event -> { try { return (Z2) constructor.newInstance(event); @@ -283,7 +291,9 @@ private Function findWrappedForgeEvent(Clas if (eventField != null) { //hack eventField.setAccessible(true); - zetaToForgeEventClass.put(baseZetaEventClass, eventField.getType()); + if(!zetaToForgeEventClassHack.containsKey(baseZetaEventClass)){ + zetaToForgeEventClassHack.put(baseZetaEventClass, eventField.getType()); + } return instance -> { try { return (F2) eventField.get(instance); @@ -295,7 +305,9 @@ private Function findWrappedForgeEvent(Clas //tries to unwrap first. Then if its already a forge event we just keep it if (forgeEventRoot.isAssignableFrom(zetaEventClass)) { - zetaToForgeEventClass.put(baseZetaEventClass, zetaEventClass); + if(!zetaToForgeEventClassHack.containsKey(baseZetaEventClass)){ + zetaToForgeEventClassHack.put(baseZetaEventClass, zetaEventClass); + } return null; } @@ -321,7 +333,7 @@ public static Field findFieldInClassHierarchy(Class clazz, Predicate p private void registerListenerToForgeWithPriorityAndGenerics(Class owningClazz, Consumer consumer, Class zetaEventClass) { EventPriority priority = guessPriorityFromClassName(owningClazz); Class gen = generics.get(zetaEventClass); - Class eventType = zetaToForgeEventClass.get(zetaEventClass); + Class eventType = zetaToForgeEventClassHack.get(zetaEventClass); if (eventType == null) { throw new RuntimeException("No event type found for " + zetaEventClass); } diff --git a/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java b/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java index 3196cfc..7dc92a0 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java +++ b/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java @@ -171,6 +171,8 @@ protected ZetaEventBus createLoadBus() { bus.registerSubClass(ZAddReloadListener.class, ForgeZAddReloadListener.class); bus.registerSubClass(ZGatherAdvancementModifiers.class, ForgeZGatherAdvancementModifiers.class); bus.registerSubClass(ZGatherHints.class, ForgeZGatherHints.class); + bus.registerSubClass(ZSleepingLocationCheck.class, ForgeZSleepingLocationCheck.class); + bus.registerSubClass(ZAnimalTame.class, ForgeZAnimalTame.class); //Hmm client events here? maybe i should move them diff --git a/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZScreen.java b/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZScreen.java index ae7b6f6..2348f3e 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZScreen.java +++ b/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZScreen.java @@ -81,13 +81,13 @@ public int getMouseY() { } public static class Pre extends ForgeZScreen.Render implements ZScreen.Render.Pre { - public Pre(ScreenEvent.Render e) { + public Pre(ScreenEvent.Render.Pre e) { super(e); } } public static class Post extends ForgeZScreen.Render implements ZScreen.Render.Post { - public Post(ScreenEvent.Render e) { + public Post(ScreenEvent.Render.Post e) { super(e); } } diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZFirstClientTick.java b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZFirstClientTick.java index d881ed7..5a47771 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZFirstClientTick.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZFirstClientTick.java @@ -1,8 +1,9 @@ package org.violetmoon.zetaimplforge.event.load; import net.minecraftforge.eventbus.api.Event; +import net.minecraftforge.fml.event.IModBusEvent; import org.violetmoon.zeta.client.event.play.ZFirstClientTick; -public class ForgeZFirstClientTick extends Event implements ZFirstClientTick { +public class ForgeZFirstClientTick extends Event implements ZFirstClientTick, IModBusEvent { } From bd134092169cfceb019dfc097c2b3c9987a5a474 Mon Sep 17 00:00:00 2001 From: MehVahdJukaar Date: Wed, 31 Jul 2024 20:46:59 +0200 Subject: [PATCH 14/22] removed top layer tooltip hack. made client ticker a singleton. No need to create more than 1, just waste of resources when its contents are always the same --- build.properties | 2 +- .../violetmoon/zeta/client/ClientTicker.java | 11 +++ .../zeta/client/TopLayerTooltipHandler.java | 76 ------------------- .../violetmoon/zeta/client/ZetaClient.java | 12 +-- .../load/ZRegisterClientReloadListener.java | 12 +++ .../event/load/ZRegisterReloadListeners.java | 14 ---- .../violetmoon/zetaimplforge/ForgeZeta.java | 3 + .../ForgeZRegisterClientReloadListener.java | 13 ++++ .../ForgeZAddReloadListener.java | 2 +- .../zetaimplforge/mod/ZetaModClientProxy.java | 8 +- 10 files changed, 44 insertions(+), 109 deletions(-) delete mode 100644 src/main/java/org/violetmoon/zeta/client/TopLayerTooltipHandler.java create mode 100644 src/main/java/org/violetmoon/zeta/client/event/load/ZRegisterClientReloadListener.java delete mode 100644 src/main/java/org/violetmoon/zeta/client/event/load/ZRegisterReloadListeners.java create mode 100644 src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZRegisterClientReloadListener.java rename src/main/java/org/violetmoon/zetaimplforge/event/{load => play}/ForgeZAddReloadListener.java (93%) diff --git a/build.properties b/build.properties index c2ba099..9a11ebe 100644 --- a/build.properties +++ b/build.properties @@ -5,5 +5,5 @@ mod_name=Zeta mc_version=1.20.1 mapping_channel=official mod_id=zeta -build_number=20-event15 +build_number=20-event17 dir_output=../Build Output/Zeta/ diff --git a/src/main/java/org/violetmoon/zeta/client/ClientTicker.java b/src/main/java/org/violetmoon/zeta/client/ClientTicker.java index 8a6bd69..50d1368 100644 --- a/src/main/java/org/violetmoon/zeta/client/ClientTicker.java +++ b/src/main/java/org/violetmoon/zeta/client/ClientTicker.java @@ -7,9 +7,15 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screens.Screen; +import org.violetmoon.zeta.event.play.ZRecipeCrawl; //TODO: 1.21. replace with minecraft own ticker. Tbh this is legacy already and should be replaced with Minecraft.getPartialTicks() +@Deprecated public final class ClientTicker { + + //no need to have more than 1 instance of this class. Ticks are always the same + public static final ClientTicker INSTANCE = new ClientTicker(); + public int ticksInGame = 0; public float partialTicks = 0; public float delta = 0; @@ -37,6 +43,11 @@ public void onEndClientTick(ZClientTick event) { endRenderTick(); } + @PlayEvent + public void a(ZRecipeCrawl.Digest e){ + int aa = 1; + } + public void endRenderTick() { float oldTotal = total; total = ticksInGame + partialTicks; diff --git a/src/main/java/org/violetmoon/zeta/client/TopLayerTooltipHandler.java b/src/main/java/org/violetmoon/zeta/client/TopLayerTooltipHandler.java deleted file mode 100644 index c590f35..0000000 --- a/src/main/java/org/violetmoon/zeta/client/TopLayerTooltipHandler.java +++ /dev/null @@ -1,76 +0,0 @@ -package org.violetmoon.zeta.client; - -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; - -import org.joml.Matrix4f; -import org.violetmoon.zeta.client.event.play.ZRenderTick; -import org.violetmoon.zeta.event.bus.PlayEvent; - -import com.mojang.blaze3d.platform.Window; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.blaze3d.vertex.VertexSorting; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.network.chat.Component; - -@Deprecated // Very hacky for what it does. -public class TopLayerTooltipHandler { - - private List tooltip; - private int tooltipX, tooltipY; - - @PlayEvent - public void renderTick(ZRenderTick event) { - if(tooltip != null && event.isEndPhase()) { - Minecraft mc = Minecraft.getInstance(); - Screen screen = mc.screen; - - Matrix4f projectionMatrix = RenderSystem.getProjectionMatrix(); - VertexSorting vertexSorting = RenderSystem.getVertexSorting(); - - // Set correct projection matrix - Window window = mc.getWindow(); - Matrix4f matrix4f = new Matrix4f().setOrtho( - 0.0F, - (float) ((double) window.getWidth() / window.getGuiScale()), - (float) ((double) window.getHeight() / window.getGuiScale()), - 0.0F, - 1000.0F, - net.minecraftforge.client.ForgeHooksClient.getGuiFarPlane() - ); - RenderSystem.setProjectionMatrix(matrix4f, VertexSorting.ORTHOGRAPHIC_Z); - PoseStack posestack = RenderSystem.getModelViewStack(); - posestack.pushPose(); - posestack.setIdentity(); - posestack.translate(0.0D, 0.0D, 1000F - net.minecraftforge.client.ForgeHooksClient.getGuiFarPlane()); - RenderSystem.applyModelViewMatrix(); - // End - - GuiGraphics guiGraphics = new GuiGraphics(mc, mc.renderBuffers().bufferSource()); - - if(screen != null) - guiGraphics.renderTooltip(mc.font, tooltip, Optional.empty(), tooltipX, tooltipY); - - // Reset projection matrix - guiGraphics.flush(); - posestack.popPose(); - RenderSystem.applyModelViewMatrix(); - RenderSystem.setProjectionMatrix(projectionMatrix, vertexSorting); - // End - - tooltip = null; - } - } - - public void setTooltip(List tooltip, int x, int y) { - this.tooltip = tooltip.stream().map(Component::literal).collect(Collectors.toList()); - this.tooltipX = x; - this.tooltipY = y; - } - -} diff --git a/src/main/java/org/violetmoon/zeta/client/ZetaClient.java b/src/main/java/org/violetmoon/zeta/client/ZetaClient.java index eea0198..c159b8f 100644 --- a/src/main/java/org/violetmoon/zeta/client/ZetaClient.java +++ b/src/main/java/org/violetmoon/zeta/client/ZetaClient.java @@ -23,22 +23,18 @@ import net.minecraft.world.level.block.Block; public abstract class ZetaClient implements IZeta { + public ZetaClient(Zeta zeta) { this.zeta = zeta; this.loadBus = zeta.loadBus; this.playBus = zeta.playBus; - this.ticker = createClientTicker(); this.clientConfigManager = createClientConfigManager(); - this.topLayerTooltipHandler = createTopLayerTooltipHandler(); this.clientRegistryExtension = createClientRegistryExtension(); loadBus.subscribe(clientRegistryExtension) .subscribe(clientConfigManager); - playBus.subscribe(ticker) - .subscribe(topLayerTooltipHandler); - ZetaClientList.INSTANCE.register(this); } @@ -48,9 +44,7 @@ public ZetaClient(Zeta zeta) { public ResourceLocation generalIcons = new ResourceLocation("zeta", "textures/gui/general_icons.png"); - public final ClientTicker ticker; public final ClientConfigManager clientConfigManager; - public final TopLayerTooltipHandler topLayerTooltipHandler; public final ClientRegistryExtension clientRegistryExtension; public ClientTicker createClientTicker() { @@ -61,10 +55,6 @@ public ClientConfigManager createClientConfigManager() { return new ClientConfigManager(this); } - public TopLayerTooltipHandler createTopLayerTooltipHandler() { - return new TopLayerTooltipHandler(); - } - //ummm ?? public void sendToServer(IZetaMessage msg) { if(Minecraft.getInstance().getConnection() == null) diff --git a/src/main/java/org/violetmoon/zeta/client/event/load/ZRegisterClientReloadListener.java b/src/main/java/org/violetmoon/zeta/client/event/load/ZRegisterClientReloadListener.java new file mode 100644 index 0000000..52e5fc5 --- /dev/null +++ b/src/main/java/org/violetmoon/zeta/client/event/load/ZRegisterClientReloadListener.java @@ -0,0 +1,12 @@ +package org.violetmoon.zeta.client.event.load; + +import java.util.function.Consumer; + +import org.violetmoon.zeta.event.bus.IZetaLoadEvent; + +import net.minecraft.server.packs.resources.PreparableReloadListener; + +public interface ZRegisterClientReloadListener extends IZetaLoadEvent, Consumer { + @Override + void accept(PreparableReloadListener bleh); +} diff --git a/src/main/java/org/violetmoon/zeta/client/event/load/ZRegisterReloadListeners.java b/src/main/java/org/violetmoon/zeta/client/event/load/ZRegisterReloadListeners.java deleted file mode 100644 index a828ea9..0000000 --- a/src/main/java/org/violetmoon/zeta/client/event/load/ZRegisterReloadListeners.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.violetmoon.zeta.client.event.load; - -import java.util.function.Consumer; - -import org.violetmoon.zeta.event.bus.IZetaLoadEvent; - -import net.minecraft.server.packs.resources.PreparableReloadListener; - -public record ZRegisterReloadListeners(Consumer manager) implements IZetaLoadEvent, Consumer { - @Override - public void accept(PreparableReloadListener bleh) { - manager.accept(bleh); - } -} diff --git a/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java b/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java index 7dc92a0..95196a1 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java +++ b/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java @@ -100,6 +100,7 @@ protected ZetaEventBus createLoadBus() { bus.registerSubClass(ZModel.ModifyBakingResult.class, ForgeZModel.ModifyBakingResult.class); bus.registerSubClass(ZRegisterLayerDefinitions.class, ForgeZRegisterLayerDefinitions.class); bus.registerSubClass(ZTooltipComponents.class, ForgeZTooltipComponents.class); + bus.registerSubClass(ZRegisterClientReloadListener.class, ForgeZRegisterClientReloadListener.class); bus.registerSubClass(ZFirstClientTick.class, ForgeZFirstClientTick.class); bus.registerSubClass(ZAddBlockColorHandlers.class, ForgeZAddBlockColorHandlers.class, @@ -173,6 +174,8 @@ protected ZetaEventBus createLoadBus() { bus.registerSubClass(ZGatherHints.class, ForgeZGatherHints.class); bus.registerSubClass(ZSleepingLocationCheck.class, ForgeZSleepingLocationCheck.class); bus.registerSubClass(ZAnimalTame.class, ForgeZAnimalTame.class); + bus.registerSubClass(ZLevelTick.End.class, ForgeZLevelTick.End.class); + bus.registerSubClass(ZLevelTick.Start.class, ForgeZLevelTick.Start.class); //Hmm client events here? maybe i should move them diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZRegisterClientReloadListener.java b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZRegisterClientReloadListener.java new file mode 100644 index 0000000..538ed25 --- /dev/null +++ b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZRegisterClientReloadListener.java @@ -0,0 +1,13 @@ +package org.violetmoon.zetaimplforge.event.load; + +import net.minecraft.server.packs.resources.PreparableReloadListener; +import net.minecraftforge.client.event.RegisterClientReloadListenersEvent; +import org.violetmoon.zeta.client.event.load.ZRegisterClientReloadListener; + +public record ForgeZRegisterClientReloadListener(RegisterClientReloadListenersEvent event) implements ZRegisterClientReloadListener { + + @Override + public void accept(PreparableReloadListener bleh) { + event.registerReloadListener(bleh); + } +} diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZAddReloadListener.java b/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZAddReloadListener.java similarity index 93% rename from src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZAddReloadListener.java rename to src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZAddReloadListener.java index e9ff204..0a49ba6 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZAddReloadListener.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZAddReloadListener.java @@ -1,4 +1,4 @@ -package org.violetmoon.zetaimplforge.event.load; +package org.violetmoon.zetaimplforge.event.play; import org.violetmoon.zeta.event.load.ZAddReloadListener; diff --git a/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModClientProxy.java b/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModClientProxy.java index 0a8b3c8..37c7708 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModClientProxy.java +++ b/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModClientProxy.java @@ -5,18 +5,14 @@ import net.minecraftforge.client.gui.overlay.VanillaGuiOverlay; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.TickEvent; -import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import org.violetmoon.zeta.Zeta; -import org.violetmoon.zeta.client.TopLayerTooltipHandler; -import org.violetmoon.zeta.client.event.play.ZFirstClientTick; +import org.violetmoon.zeta.client.ClientTicker; import org.violetmoon.zeta.client.event.play.ZRenderGuiOverlay; import org.violetmoon.zeta.util.handler.RequiredModTooltipHandler; -import org.violetmoon.zeta.util.handler.ToolInteractionHandler; import org.violetmoon.zeta.util.zetalist.ZetaList; import org.violetmoon.zetaimplforge.client.ForgeZetaClient; import org.violetmoon.zetaimplforge.client.event.play.ForgeZRenderGuiOverlay; import org.violetmoon.zetaimplforge.event.load.ForgeZFirstClientTick; -import org.violetmoon.zetaimplforge.world.ZetaBiomeModifier; public class ZetaModClientProxy extends ZetaModCommonProxy { @@ -27,7 +23,7 @@ public ZetaModClientProxy(Zeta zeta) { this.clientZeta = new ForgeZetaClient(zeta); zeta.playBus - .subscribe(TopLayerTooltipHandler.class) + .subscribe(ClientTicker.INSTANCE) .subscribe(new RequiredModTooltipHandler.Client(zeta)); MinecraftForge.EVENT_BUS.addListener(this::clientTick); From 67bbf16a66d9ff8b0ae5b56e6c161737cb6646f2 Mon Sep 17 00:00:00 2001 From: MehVahdJukaar Date: Thu, 1 Aug 2024 00:49:40 +0200 Subject: [PATCH 15/22] removed client tick phase. Added subclass instead refactored ZetaMod. split hacky remap code into its own class --- build.properties | 2 +- src/main/java/org/violetmoon/zeta/Zeta.java | 30 +- .../violetmoon/zeta/client/ClientTicker.java | 15 +- .../violetmoon/zeta/client/ZetaClient.java | 4 - .../event/load/ZAddBlockColorHandlers.java | 3 +- .../event/load/ZAddItemColorHandlers.java | 3 +- .../zeta/client/event/play/ZClientTick.java | 8 +- .../zeta/config/ZetaGeneralConfig.java | 5 +- .../event/bus/StandaloneZetaEventBus.java | 5 +- .../org/violetmoon/zeta/event/bus/ZPhase.java | 5 - .../zeta/event/bus/ZetaEventBus.java | 33 +- .../java/org/violetmoon/zeta/mod/ZetaMod.java | 16 +- .../piston/ZetaPistonStructureResolver.java | 8 +- .../zeta/registry/CreativeTabManager.java | 10 +- .../org/violetmoon/zeta/util/ZetaSide.java | 4 + .../zeta/util/handler/RecipeCrawlHandler.java | 9 +- .../violetmoon/zetaimplforge/ForgeZeta.java | 182 +-------- .../capability/ForgeCapabilityManager.java | 9 + .../load/ForgeZAddBlockColorHandlers.java | 10 +- .../load/ForgeZAddItemColorHandlers.java | 13 +- .../client/event/play/ForgeZClientTick.java | 24 +- .../event/ForgeEventsRemapper.java} | 180 +++++---- .../event/ForgeZetaEventBus.java | 346 ++++++++++++++++++ .../zetaimplforge/mod/ZetaModCommonProxy.java | 33 +- .../zetaimplforge/mod/ZetaModForge.java | 11 +- .../world/ZetaBiomeModifier.java | 7 +- 26 files changed, 596 insertions(+), 379 deletions(-) delete mode 100644 src/main/java/org/violetmoon/zeta/event/bus/ZPhase.java rename src/main/java/org/violetmoon/{zeta/event/bus/ForgeZetaEventBus.java => zetaimplforge/event/ForgeEventsRemapper.java} (72%) create mode 100644 src/main/java/org/violetmoon/zetaimplforge/event/ForgeZetaEventBus.java diff --git a/build.properties b/build.properties index 9a11ebe..4a63212 100644 --- a/build.properties +++ b/build.properties @@ -5,5 +5,5 @@ mod_name=Zeta mc_version=1.20.1 mapping_channel=official mod_id=zeta -build_number=20-event17 +build_number=20-event21 dir_output=../Build Output/Zeta/ diff --git a/src/main/java/org/violetmoon/zeta/Zeta.java b/src/main/java/org/violetmoon/zeta/Zeta.java index 0e48649..2d87485 100644 --- a/src/main/java/org/violetmoon/zeta/Zeta.java +++ b/src/main/java/org/violetmoon/zeta/Zeta.java @@ -1,5 +1,6 @@ package org.violetmoon.zeta; +import com.google.common.base.Stopwatch; import net.minecraft.core.BlockPos; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.player.Player; @@ -39,14 +40,12 @@ */ public abstract class Zeta implements IZeta { - public static final String ZETA_ID = "zeta"; - public static final Logger GLOBAL_LOG = LogManager.getLogger(ZETA_ID); - - public Zeta(String modid, Logger log, ZetaSide side) { + public Zeta(String modid, Logger log, ZetaSide side, boolean isProduction) { this.log = log; this.modid = modid; this.side = side; + this.isProduction = isProduction; this.modules = createModuleManager(); @@ -68,17 +67,10 @@ public Zeta(String modid, Logger log, ZetaSide side) { this.entitySpawn = createEntitySpawnHandler(); + Stopwatch stopwatch = Stopwatch.createStarted(); this.loadBus = this.createLoadBus(); this.playBus = this.createPlayBus(); - - loadBus.subscribe(craftingExtensions) - .subscribe(dyeables) - .subscribe(brewingRegistry) - .subscribe(fuel) - .subscribe(entitySpawn); - - playBus.subscribe(fuel) - .subscribe(advancementModifierRegistry); + long elapsed = stopwatch.stop().elapsed().toMillis(); ZetaList.INSTANCE.register(this); } @@ -87,6 +79,7 @@ public Zeta(String modid, Logger log, ZetaSide side) { public final Logger log; public final String modid; public final ZetaSide side; + public final boolean isProduction; public final ZetaEventBus loadBus; public final ZetaEventBus playBus; public final ZetaModuleManager modules; @@ -217,7 +210,16 @@ public EntitySpawnHandler createEntitySpawnHandler() { public abstract boolean fireRightClickBlock(Player player, InteractionHand hand, BlockPos pos, BlockHitResult bhr); // Let's Jump - public abstract void start(); + public void start(){ + loadBus.subscribe(craftingExtensions) + .subscribe(dyeables) + .subscribe(brewingRegistry) + .subscribe(fuel) + .subscribe(entitySpawn); + + playBus.subscribe(fuel) + .subscribe(advancementModifierRegistry); + } @Override public Zeta asZeta() { diff --git a/src/main/java/org/violetmoon/zeta/client/ClientTicker.java b/src/main/java/org/violetmoon/zeta/client/ClientTicker.java index 50d1368..fcb3817 100644 --- a/src/main/java/org/violetmoon/zeta/client/ClientTicker.java +++ b/src/main/java/org/violetmoon/zeta/client/ClientTicker.java @@ -1,5 +1,6 @@ package org.violetmoon.zeta.client; +import org.jetbrains.annotations.ApiStatus; import org.violetmoon.zeta.client.event.play.ZClientTick; import org.violetmoon.zeta.client.event.play.ZRenderTick; import org.violetmoon.zeta.event.bus.PlayEvent; @@ -16,11 +17,15 @@ public final class ClientTicker { //no need to have more than 1 instance of this class. Ticks are always the same public static final ClientTicker INSTANCE = new ClientTicker(); + private ClientTicker() { + } + public int ticksInGame = 0; public float partialTicks = 0; public float delta = 0; public float total = 0; + @ApiStatus.Internal @PlayEvent public void onRenderTick(ZRenderTick event) { if(event.isStartPhase()) @@ -29,8 +34,9 @@ public void onRenderTick(ZRenderTick event) { endRenderTick(); } + @ApiStatus.Internal @PlayEvent - public void onEndClientTick(ZClientTick event) { + public void onEndClientTick(ZClientTick.Start event) { if(event.getPhase() != ZPhase.END) return; @@ -43,12 +49,7 @@ public void onEndClientTick(ZClientTick event) { endRenderTick(); } - @PlayEvent - public void a(ZRecipeCrawl.Digest e){ - int aa = 1; - } - - public void endRenderTick() { + private void endRenderTick() { float oldTotal = total; total = ticksInGame + partialTicks; delta = total - oldTotal; diff --git a/src/main/java/org/violetmoon/zeta/client/ZetaClient.java b/src/main/java/org/violetmoon/zeta/client/ZetaClient.java index c159b8f..e0f03a6 100644 --- a/src/main/java/org/violetmoon/zeta/client/ZetaClient.java +++ b/src/main/java/org/violetmoon/zeta/client/ZetaClient.java @@ -47,10 +47,6 @@ public ZetaClient(Zeta zeta) { public final ClientConfigManager clientConfigManager; public final ClientRegistryExtension clientRegistryExtension; - public ClientTicker createClientTicker() { - return new ClientTicker(); - } - public ClientConfigManager createClientConfigManager() { return new ClientConfigManager(this); } diff --git a/src/main/java/org/violetmoon/zeta/client/event/load/ZAddBlockColorHandlers.java b/src/main/java/org/violetmoon/zeta/client/event/load/ZAddBlockColorHandlers.java index 1748b3d..1d75b70 100644 --- a/src/main/java/org/violetmoon/zeta/client/event/load/ZAddBlockColorHandlers.java +++ b/src/main/java/org/violetmoon/zeta/client/event/load/ZAddBlockColorHandlers.java @@ -3,6 +3,7 @@ import java.util.Map; import java.util.function.Function; +import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.event.bus.IZetaLoadEvent; import net.minecraft.client.color.block.BlockColor; @@ -11,6 +12,6 @@ public interface ZAddBlockColorHandlers extends IZetaLoadEvent { void register(BlockColor c, Block... blocks); - void registerNamed(Function c, String... names); + void registerNamed(Zeta myZeta, Function c, String... names); BlockColors getBlockColors(); } diff --git a/src/main/java/org/violetmoon/zeta/client/event/load/ZAddItemColorHandlers.java b/src/main/java/org/violetmoon/zeta/client/event/load/ZAddItemColorHandlers.java index d8cce85..ad32f37 100644 --- a/src/main/java/org/violetmoon/zeta/client/event/load/ZAddItemColorHandlers.java +++ b/src/main/java/org/violetmoon/zeta/client/event/load/ZAddItemColorHandlers.java @@ -3,6 +3,7 @@ import java.util.Map; import java.util.function.Function; +import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.event.bus.IZetaLoadEvent; import net.minecraft.client.color.item.ItemColor; @@ -12,6 +13,6 @@ public interface ZAddItemColorHandlers extends IZetaLoadEvent { void register(ItemColor c, ItemLike... items); - void registerNamed(Function c, String... names); + void registerNamed(Zeta myZeta, Function c, String... names); ItemColors getItemColors(); } diff --git a/src/main/java/org/violetmoon/zeta/client/event/play/ZClientTick.java b/src/main/java/org/violetmoon/zeta/client/event/play/ZClientTick.java index 10a9ae3..b5671ca 100644 --- a/src/main/java/org/violetmoon/zeta/client/event/play/ZClientTick.java +++ b/src/main/java/org/violetmoon/zeta/client/event/play/ZClientTick.java @@ -1,8 +1,12 @@ package org.violetmoon.zeta.client.event.play; import org.violetmoon.zeta.event.bus.IZetaPlayEvent; -import org.violetmoon.zeta.event.bus.ZPhase; public interface ZClientTick extends IZetaPlayEvent { - ZPhase getPhase(); + + interface Start extends ZClientTick { + } + + interface End extends ZClientTick { + } } diff --git a/src/main/java/org/violetmoon/zeta/config/ZetaGeneralConfig.java b/src/main/java/org/violetmoon/zeta/config/ZetaGeneralConfig.java index 3ecc06e..c9f7f91 100644 --- a/src/main/java/org/violetmoon/zeta/config/ZetaGeneralConfig.java +++ b/src/main/java/org/violetmoon/zeta/config/ZetaGeneralConfig.java @@ -5,6 +5,7 @@ import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.event.bus.LoadEvent; import org.violetmoon.zeta.event.load.ZConfigChanged; +import org.violetmoon.zeta.mod.ZetaMod; import org.violetmoon.zeta.piston.ZetaPistonStructureResolver; import com.google.common.collect.Lists; @@ -59,8 +60,8 @@ private ZetaGeneralConfig() { @LoadEvent public static void configChanged(ZConfigChanged e) { - ZetaPistonStructureResolver.GlobalSettings.requestEnabled(Zeta.ZETA_ID, usePistonLogicRepl); - ZetaPistonStructureResolver.GlobalSettings.requestPushLimit(Zeta.ZETA_ID, pistonPushLimit); + ZetaPistonStructureResolver.GlobalSettings.requestEnabled(ZetaMod.ZETA_ID, usePistonLogicRepl); + ZetaPistonStructureResolver.GlobalSettings.requestPushLimit(ZetaMod.ZETA_ID, pistonPushLimit); } } diff --git a/src/main/java/org/violetmoon/zeta/event/bus/StandaloneZetaEventBus.java b/src/main/java/org/violetmoon/zeta/event/bus/StandaloneZetaEventBus.java index 6f3ad33..4bdc955 100644 --- a/src/main/java/org/violetmoon/zeta/event/bus/StandaloneZetaEventBus.java +++ b/src/main/java/org/violetmoon/zeta/event/bus/StandaloneZetaEventBus.java @@ -12,6 +12,7 @@ import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.violetmoon.zeta.Zeta; /** * A polymorphic event bus. Events can be fired under one of their supertypes, allowing a sort of API/impl split of events. @@ -30,8 +31,8 @@ public class StandaloneZetaEventBus extends ZetaEventBus { * @param eventRoot The superinterface of all events fired on this bus. * @param logSpam */ - public StandaloneZetaEventBus(Class subscriberAnnotation, Class eventRoot, @Nullable Logger logSpam) { - super(subscriberAnnotation, eventRoot, logSpam); + public StandaloneZetaEventBus(Class subscriberAnnotation, Class eventRoot, @Nullable Logger logSpam, Zeta ofZeta) { + super(subscriberAnnotation, eventRoot, logSpam, ofZeta); } @Override diff --git a/src/main/java/org/violetmoon/zeta/event/bus/ZPhase.java b/src/main/java/org/violetmoon/zeta/event/bus/ZPhase.java deleted file mode 100644 index aad6d02..0000000 --- a/src/main/java/org/violetmoon/zeta/event/bus/ZPhase.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.violetmoon.zeta.event.bus; - -public enum ZPhase { - START, END; -} diff --git a/src/main/java/org/violetmoon/zeta/event/bus/ZetaEventBus.java b/src/main/java/org/violetmoon/zeta/event/bus/ZetaEventBus.java index d649ec8..5df5d37 100644 --- a/src/main/java/org/violetmoon/zeta/event/bus/ZetaEventBus.java +++ b/src/main/java/org/violetmoon/zeta/event/bus/ZetaEventBus.java @@ -5,13 +5,16 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.violetmoon.zeta.Zeta; -import org.violetmoon.zeta.advancement.AdvancementModifierRegistry; -import org.violetmoon.zeta.util.handler.RecipeCrawlHandler; +import org.violetmoon.zeta.client.ClientTicker; +import org.violetmoon.zeta.mod.ZetaMod; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Modifier; +import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; +import java.util.List; import java.util.stream.Stream; public abstract class ZetaEventBus { @@ -19,17 +22,21 @@ public abstract class ZetaEventBus { protected final Class subscriberAnnotation; protected final Class eventRoot; protected final @Nullable Logger logSpam; + //each bus belongs to a specific zeta. Internally they can however delegate to an internal shared data structure such as to the forge event bus + protected final Zeta ofZeta; /** * @param subscriberAnnotation The annotation that subscribe()/unsubscribe() will pay attention to. * @param eventRoot The superinterface of all events fired on this bus. */ - public ZetaEventBus(Class subscriberAnnotation, Class eventRoot, @Nullable Logger logSpam) { + public ZetaEventBus(Class subscriberAnnotation, Class eventRoot, + @Nullable Logger logSpam, Zeta ofZeta) { Preconditions.checkArgument(eventRoot.isInterface(), "Event roots should be an interface"); this.subscriberAnnotation = subscriberAnnotation; this.eventRoot = eventRoot; this.logSpam = logSpam; + this.ofZeta = ofZeta; } /** @@ -49,9 +56,6 @@ public ZetaEventBus subscribe(@NotNull Object target) { receiver = target; owningClazz = target.getClass(); } - if(owningClazz == AdvancementModifierRegistry.class){ - int aa = 1; - } streamAnnotatedMethods(owningClazz, receiver == null) .forEach(m -> subscribeMethod(m, receiver, owningClazz)); return this; @@ -103,10 +107,23 @@ public ZetaEventBus unsubscribe(@NotNull Object target) { * annotation; and of the requested staticness. */ private Stream streamAnnotatedMethods(Class owningClazz, boolean wantStatic) { - return Arrays.stream(owningClazz.getMethods()) - .filter(m -> m.isAnnotationPresent(subscriberAnnotation) && ((m.getModifiers() & Modifier.STATIC) != 0) == wantStatic); + Stream methods; + if (ofZeta.isProduction) { + // faster + methods = Arrays.stream(owningClazz.getMethods()); + } else { + // here for debug purposes as this will catch private stuff too + List list = new ArrayList<>(); + while (owningClazz != null) { + Collections.addAll(list, owningClazz.getDeclaredMethods()); + owningClazz = owningClazz.getSuperclass(); + } + methods = list.stream(); + } + return methods.filter(m -> m.isAnnotationPresent(subscriberAnnotation) && ((m.getModifiers() & Modifier.STATIC) != 0) == wantStatic); } + protected RuntimeException arityERR(Method method) { return methodProblem("Method annotated with @" + subscriberAnnotation.getSimpleName() + " should take 1 parameter.", method, null); diff --git a/src/main/java/org/violetmoon/zeta/mod/ZetaMod.java b/src/main/java/org/violetmoon/zeta/mod/ZetaMod.java index 7bcfc15..46d43d5 100644 --- a/src/main/java/org/violetmoon/zeta/mod/ZetaMod.java +++ b/src/main/java/org/violetmoon/zeta/mod/ZetaMod.java @@ -1,19 +1,29 @@ package org.violetmoon.zeta.mod; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.config.ZetaGeneralConfig; import org.violetmoon.zeta.network.ZetaModInternalNetwork; public class ZetaMod { + public static final String ZETA_ID = "zeta"; + public static final Logger LOGGER = LogManager.getLogger(ZETA_ID); + + //zeta mod own zeta thing public static Zeta ZETA; - public static void start(Zeta zeta) { - ZetaMod.ZETA = zeta; + public ZetaMod(Zeta zeta) { + ZETA = zeta; + + start(); + } + private void start() { ZETA.start(); ZETA.loadModules(null, null, ZetaGeneralConfig.INSTANCE); - + ZetaModInternalNetwork.init(); } diff --git a/src/main/java/org/violetmoon/zeta/piston/ZetaPistonStructureResolver.java b/src/main/java/org/violetmoon/zeta/piston/ZetaPistonStructureResolver.java index d9a9fe5..4bffb78 100644 --- a/src/main/java/org/violetmoon/zeta/piston/ZetaPistonStructureResolver.java +++ b/src/main/java/org/violetmoon/zeta/piston/ZetaPistonStructureResolver.java @@ -7,7 +7,6 @@ import org.apache.commons.lang3.tuple.Pair; import org.jetbrains.annotations.NotNull; -import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.api.ICollateralMover; import org.violetmoon.zeta.api.ICollateralMover.MoveResult; import org.violetmoon.zeta.api.IConditionalSticky; @@ -27,6 +26,7 @@ import net.minecraft.world.level.block.piston.PistonStructureResolver; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.PushReaction; +import org.violetmoon.zeta.mod.ZetaMod; public class ZetaPistonStructureResolver extends PistonStructureResolver { @@ -60,9 +60,9 @@ public static void requestEnabled(String modid, boolean enablePlease) { enabled = !wantsEnabled.isEmpty(); if(!wasEnabled && enabled) - Zeta.GLOBAL_LOG.info("'{}' is enabling Zeta's piston structure resolver.", modid); + ZetaMod.LOGGER.info("'{}' is enabling Zeta's piston structure resolver.", modid); else if(wasEnabled && !enabled) - Zeta.GLOBAL_LOG.info("Zeta's piston structure resolver is now disabled."); + ZetaMod.LOGGER.info("Zeta's piston structure resolver is now disabled."); } public static void requestPushLimit(String modid, int pushLimitPlease) { @@ -72,7 +72,7 @@ public static void requestPushLimit(String modid, int pushLimitPlease) { pushLimit = wantsPushLimit.values().intStream().max().orElse(12); if(wasPushLimit < pushLimit) - Zeta.GLOBAL_LOG.info("'{}' is raising Zeta's piston structure resolver push limit to {} blocks.", modid, pushLimit); + ZetaMod.LOGGER.info("'{}' is raising Zeta's piston structure resolver push limit to {} blocks.", modid, pushLimit); } } diff --git a/src/main/java/org/violetmoon/zeta/registry/CreativeTabManager.java b/src/main/java/org/violetmoon/zeta/registry/CreativeTabManager.java index 7fb0f92..0dcab31 100644 --- a/src/main/java/org/violetmoon/zeta/registry/CreativeTabManager.java +++ b/src/main/java/org/violetmoon/zeta/registry/CreativeTabManager.java @@ -11,8 +11,8 @@ import java.util.Map.Entry; import java.util.function.Supplier; -import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.config.ZetaGeneralConfig; +import org.violetmoon.zeta.mod.ZetaMod; import org.violetmoon.zeta.module.IDisableable; import com.google.common.collect.HashMultimap; @@ -144,7 +144,7 @@ public static void buildContents(BuildCreativeModeTabContentsEvent event) { logVerbose(() -> "front empty=" + front.isEmpty() + " / behind empty=" + behind.isEmpty()); if(entries.isEmpty()) { - Zeta.GLOBAL_LOG.error("entries map for tab " + tabKey + " is empty, this should never happen"); + ZetaMod.LOGGER.error("entries map for tab " + tabKey + " is empty, this should never happen"); return; } @@ -235,8 +235,8 @@ private static boolean appendNextTo(ResourceKey tabKey, Mutable logVerbose(() -> "target is " + target); if(log) { - Zeta.GLOBAL_LOG.error("Creative tab loop found when adding {} next to {}", firstSetItem, target); - Zeta.GLOBAL_LOG.error("For more info enable Creative Verbose Logging in the Zeta config, or set Force Creative Tab Appends to true to disable this behavior"); + ZetaMod.LOGGER.error("Creative tab loop found when adding {} next to {}", firstSetItem, target); + ZetaMod.LOGGER.error("For more info enable Creative Verbose Logging in the Zeta config, or set Force Creative Tab Appends to true to disable this behavior"); } map.remove(firstSet); @@ -277,7 +277,7 @@ private static boolean appendNextTo(ResourceKey tabKey, Mutable private static void logVerbose(Supplier s) { if(ZetaGeneralConfig.enableCreativeVerboseLogging) - Zeta.GLOBAL_LOG.warn(s.get()); + ZetaMod.LOGGER.warn(s.get()); } private static class CreativeTabAdditions { diff --git a/src/main/java/org/violetmoon/zeta/util/ZetaSide.java b/src/main/java/org/violetmoon/zeta/util/ZetaSide.java index 7db143a..7d6eb42 100644 --- a/src/main/java/org/violetmoon/zeta/util/ZetaSide.java +++ b/src/main/java/org/violetmoon/zeta/util/ZetaSide.java @@ -1,5 +1,9 @@ package org.violetmoon.zeta.util; +/** + * Don't confuse with logical side. + * These two are better called as "Local Game" and "Dedicated Server" + */ public enum ZetaSide { CLIENT, SERVER; diff --git a/src/main/java/org/violetmoon/zeta/util/handler/RecipeCrawlHandler.java b/src/main/java/org/violetmoon/zeta/util/handler/RecipeCrawlHandler.java index eb41002..a0bbe0e 100644 --- a/src/main/java/org/violetmoon/zeta/util/handler/RecipeCrawlHandler.java +++ b/src/main/java/org/violetmoon/zeta/util/handler/RecipeCrawlHandler.java @@ -7,17 +7,13 @@ import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Nullable; -import org.violetmoon.zeta.Zeta; -import org.violetmoon.zeta.client.event.play.ZRenderGuiOverlay; import org.violetmoon.zeta.event.bus.IZetaPlayEvent; -import org.violetmoon.zeta.event.bus.LoadEvent; import org.violetmoon.zeta.event.bus.PlayEvent; import org.violetmoon.zeta.event.load.ZAddReloadListener; import org.violetmoon.zeta.event.load.ZTagsUpdated; import org.violetmoon.zeta.event.play.ZRecipeCrawl; import org.violetmoon.zeta.event.play.ZServerTick; import org.violetmoon.zeta.mod.ZetaMod; -import org.violetmoon.zeta.util.zetalist.ZetaList; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; @@ -36,7 +32,6 @@ import net.minecraft.world.item.crafting.RecipeManager; import net.minecraft.world.item.crafting.ShapedRecipe; import net.minecraft.world.item.crafting.ShapelessRecipe; -import org.violetmoon.zetaimplforge.event.play.ForgeZRecipeCrawl; @ApiStatus.Internal public class RecipeCrawlHandler { @@ -121,9 +116,9 @@ else if (recipe instanceof AbstractCookingRecipe acr) fire(event); } catch (Exception e) { if (recipe == null) - Zeta.GLOBAL_LOG.error("Encountered null recipe in RecipeManager.getRecipes. This is not good"); + ZetaMod.LOGGER.error("Encountered null recipe in RecipeManager.getRecipes. This is not good"); else - Zeta.GLOBAL_LOG.error("Failed to scan recipe " + recipe.getId() + ". This should be reported to " + recipe.getId().getNamespace() + "!", e); + ZetaMod.LOGGER.error("Failed to scan recipe " + recipe.getId() + ". This should be reported to " + recipe.getId().getNamespace() + "!", e); } } } diff --git a/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java b/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java index 95196a1..ec558bd 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java +++ b/src/main/java/org/violetmoon/zetaimplforge/ForgeZeta.java @@ -50,6 +50,7 @@ import org.violetmoon.zetaimplforge.config.ConfigEventDispatcher; import org.violetmoon.zetaimplforge.config.ForgeBackedConfig; import org.violetmoon.zetaimplforge.config.TerribleForgeConfigHackery; +import org.violetmoon.zetaimplforge.event.ForgeZetaEventBus; import org.violetmoon.zetaimplforge.event.load.*; import org.violetmoon.zetaimplforge.event.play.*; import org.violetmoon.zetaimplforge.event.play.entity.*; @@ -70,190 +71,18 @@ */ public class ForgeZeta extends Zeta { public ForgeZeta(String modid, Logger log) { - super(modid, log, ZetaSide.fromClient(FMLEnvironment.dist.isClient())); + super(modid, log, ZetaSide.fromClient(FMLEnvironment.dist.isClient()), FMLEnvironment.production); } @Override protected ZetaEventBus createLoadBus() { //return new StandaloneZetaEventBus<>(LoadEvent.class, IZetaLoadEvent.class, log); - - var bus = new ForgeZetaEventBus<>(LoadEvent.class, IZetaLoadEvent.class, log, - FMLJavaModLoadingContext.get().getModEventBus(), Event.class); - - // adds known events subclasses to the bus - bus.registerSubClass(ZCommonSetup.class, ForgeZCommonSetup.class); - bus.registerSubClass(ZEntityAttributeCreation.class, ForgeZEntityAttributeCreation.class); - bus.registerSubClass(ZModulesReady.class, ForgeZModulesReady.class); - bus.registerSubClass(ZRegister.class, ForgeZRegister.class); - bus.registerSubClass(ZRegister.Post.class, ForgeZRegister.Post.class); - bus.registerSubClass(ZConfigChanged.class, ForgeZConfigChange.class); - bus.registerSubClass(ZLoadComplete.class, ForgeZLoadComplete.class); - - // client ones again? - bus.registerSubClass(ZAddModels.class, ForgeZAddModels.class); - bus.registerSubClass(ZAddModelLayers.class, ForgeZAddModelLayers.class); - bus.registerSubClass(ZClientSetup.class, ForgeZClientSetup.class); - bus.registerSubClass(ZKeyMapping.class, ForgeZKeyMapping.class); - bus.registerSubClass(ZModel.RegisterGeometryLoaders.class, ForgeZModel.RegisterGeometryLoaders.class); - bus.registerSubClass(ZModel.RegisterAdditional.class, ForgeZModel.RegisterAdditional.class); - bus.registerSubClass(ZModel.BakingCompleted.class, ForgeZModel.BakingCompleted.class); - bus.registerSubClass(ZModel.ModifyBakingResult.class, ForgeZModel.ModifyBakingResult.class); - bus.registerSubClass(ZRegisterLayerDefinitions.class, ForgeZRegisterLayerDefinitions.class); - bus.registerSubClass(ZTooltipComponents.class, ForgeZTooltipComponents.class); - bus.registerSubClass(ZRegisterClientReloadListener.class, ForgeZRegisterClientReloadListener.class); - bus.registerSubClass(ZFirstClientTick.class, ForgeZFirstClientTick.class); - - bus.registerSubClass(ZAddBlockColorHandlers.class, ForgeZAddBlockColorHandlers.class, - (Function) inner -> - new ForgeZAddBlockColorHandlers(inner, this.registry)); - bus.registerSubClass(ZAddItemColorHandlers.class, ForgeZAddItemColorHandlers.class, - (Function) inner -> - new ForgeZAddItemColorHandlers(inner, this.registry)); - return bus; + return ForgeZetaEventBus.ofLoadBus( log, this); } @Override protected ForgeZetaEventBus createPlayBus() { - var bus = new ForgeZetaEventBus<>(PlayEvent.class, IZetaPlayEvent.class, log, MinecraftForge.EVENT_BUS, Event.class); - bus.registerSubClass(ZAnvilRepair.class, ForgeZAnvilRepair.class); - bus.registerSubClass(ZAnvilUpdate.Highest.class, ForgeZAnvilUpdate.Highest.class); - bus.registerSubClass(ZAnvilUpdate.Lowest.class, ForgeZAnvilUpdate.Lowest.class); - bus.registerSubClass(ZTagsUpdated.class, ForgeZTagsUpdated.class); - bus.registerSubClass(ZBabyEntitySpawn.Lowest.class, ForgeZBabyEntitySpawn.Lowest.class); - bus.registerSubClass(ZBabyEntitySpawn.class, ForgeZBabyEntitySpawn.class); - bus.registerSubClass(ZBlock.Break.class, ForgeZBlock.Break.class); - bus.registerSubClass(ZBlock.EntityPlace.class, ForgeZBlock.EntityPlace.class); - bus.registerSubClass(ZBlock.BlockToolModification.class, ForgeZBlock.BlockToolModification.class); - bus.registerSubClass(ZBonemeal.class, ForgeZBonemeal.class); - bus.registerSubClass(ZEntityConstruct.class, ForgeZEntityConstruct.class); - bus.registerSubClass(ZEntityInteract.class, ForgeZEntityInteract.class); - bus.registerSubClass(ZEntityItemPickup.class, ForgeZEntityItemPickup.class); - bus.registerSubClass(ZEntityJoinLevel.class, ForgeZEntityJoinLevel.class); - bus.registerSubClass(ZEntityMobGriefing.class, ForgeZEntityMobGriefing.class); - bus.registerSubClass(ZEntityTeleport.class, ForgeZEntityTeleport.class); - bus.registerSubClass(ZItemTooltip.class, ForgeZItemTooltip.class); - bus.registerSubClass(ZLivingChangeTarget.class, ForgeZLivingChangeTarget.class); - bus.registerSubClass(ZLivingConversion.class, ForgeZLivingConversion.class); - bus.registerSubClass(ZLivingConversion.Pre.class, ForgeZLivingConversion.Pre.class); - bus.registerSubClass(ZLivingConversion.Post.class, ForgeZLivingConversion.Post.class); - bus.registerSubClass(ZLivingDeath.class, ForgeZLivingDeath.class); - bus.registerSubClass(ZLivingDeath.Lowest.class, ForgeZLivingDeath.Lowest.class); - bus.registerSubClass(ZLivingDrops.class, ForgeZLivingDrops.class); - bus.registerSubClass(ZLivingDrops.Lowest.class, ForgeZLivingDrops.Lowest.class); - bus.registerSubClass(ZLivingFall.class, ForgeZLivingFall.class); - bus.registerSubClass(ZLivingTick.class, ForgeZLivingTick.class); - bus.registerSubClass(ZMobSpawnEvent.class, ForgeZMobSpawnEvent.class); - bus.registerSubClass(ZMobSpawnEvent.CheckSpawn.class, ForgeZMobSpawnEvent.FinalizeSpawn.class); - bus.registerSubClass(ZMobSpawnEvent.CheckSpawn.Lowest.class, ForgeZMobSpawnEvent.FinalizeSpawn.Lowest.class); - bus.registerSubClass(ZPlayNoteBlock.class, ForgeZPlayNoteBlock.class); - bus.registerSubClass(ZPlayer.class, ForgeZPlayer.class); - bus.registerSubClass(ZPlayer.BreakSpeed.class, ForgeZPlayer.BreakSpeed.class); - bus.registerSubClass(ZPlayer.Clone.class, ForgeZPlayer.Clone.class); - bus.registerSubClass(ZPlayerDestroyItem.class, ForgeZPlayerDestroyItem.class); - bus.registerSubClass(ZPlayer.LoggedIn.class, ForgeZPlayer.LoggedIn.class); - bus.registerSubClass(ZPlayer.LoggedOut.class, ForgeZPlayer.LoggedOut.class); - bus.registerSubClass(ZPlayerTick.Start.class, ForgeZPlayerTick.Start.class); - bus.registerSubClass(ZPlayerTick.End.class, ForgeZPlayerTick.End.class); - bus.registerSubClass(ZPlayerInteract.class, ForgeZPlayerInteract.class); - bus.registerSubClass(ZPlayerInteract.EntityInteractSpecific.class, ForgeZPlayerInteract.EntityInteractSpecific.class); - bus.registerSubClass(ZPlayerInteract.EntityInteract.class, ForgeZPlayerInteract.EntityInteract.class); - bus.registerSubClass(ZPlayerInteract.RightClickBlock.class, ForgeZPlayerInteract.RightClickBlock.class); - bus.registerSubClass(ZPlayerInteract.RightClickItem.class, ForgeZPlayerInteract.RightClickItem.class); - bus.registerSubClass(ZRightClickBlock.class, ForgeZRightClickBlock.class); - bus.registerSubClass(ZRightClickBlock.Low.class, ForgeZRightClickBlock.Low.class); - bus.registerSubClass(ZRightClickItem.class, ForgeZRightClickItem.class); - bus.registerSubClass(ZLootTableLoad.class, ForgeZLootTableLoad.class); - bus.registerSubClass(ZVillagerTrades.class, ForgeZVillagerTrades.class); - bus.registerSubClass(ZWandererTrades.class, ForgeZWandererTrades.class); - bus.registerSubClass(ZFurnaceFuelBurnTime.class, ForgeZFurnaceFuelBurnTime.class); - bus.registerSubClass(ZGatherAdditionalFlags.class, ForgeZGatherAdditionalFlags.class); - bus.registerSubClass(ZServerTick.Start.class, ForgeZServerTick.Start.class); - bus.registerSubClass(ZServerTick.End.class, ForgeZServerTick.End.class); - bus.registerSubClass(ZAddReloadListener.class, ForgeZAddReloadListener.class); - bus.registerSubClass(ZGatherAdvancementModifiers.class, ForgeZGatherAdvancementModifiers.class); - bus.registerSubClass(ZGatherHints.class, ForgeZGatherHints.class); - bus.registerSubClass(ZSleepingLocationCheck.class, ForgeZSleepingLocationCheck.class); - bus.registerSubClass(ZAnimalTame.class, ForgeZAnimalTame.class); - bus.registerSubClass(ZLevelTick.End.class, ForgeZLevelTick.End.class); - bus.registerSubClass(ZLevelTick.Start.class, ForgeZLevelTick.Start.class); - - //Hmm client events here? maybe i should move them - - bus.registerSubClass(ZClientTick.class, ForgeZClientTick.class); - bus.registerSubClass(ZEarlyRender.class, ForgeZEarlyRender.class); - bus.registerSubClass(ZGatherTooltipComponents.class, ForgeZGatherTooltipComponents.class); - bus.registerSubClass(ZHighlightBlock.class, ForgeZHighlightBlock.class); - bus.registerSubClass(ZInput.MouseButton.class, ForgeZInput.MouseButton.class); - bus.registerSubClass(ZInput.Key.class, ForgeZInput.Key.class); - bus.registerSubClass(ZInputUpdate.class, ForgeZInputUpdate.class); - bus.registerSubClass(ZRenderContainerScreen.Background.class, ForgeZRenderContainerScreen.Background.class); - bus.registerSubClass(ZRenderContainerScreen.Foreground.class, ForgeZRenderContainerScreen.Foreground.class); - bus.registerSubClass(ZRenderLiving.PostLowest.class, ForgeZRenderLiving.PostLowest.class); - bus.registerSubClass(ZRenderLiving.PreHighest.class, ForgeZRenderLiving.PreHighest.class); - bus.registerSubClass(ZRenderPlayer.Post.class, ForgeZRenderPlayer.Post.class); - bus.registerSubClass(ZRenderPlayer.Pre.class, ForgeZRenderPlayer.Pre.class); - bus.registerSubClass(ZRenderTick.class, ForgeZRenderTick.class); - bus.registerSubClass(ZRenderTooltip.GatherComponents.class, ForgeZRenderTooltip.GatherComponents.class); - bus.registerSubClass(ZRenderTooltip.GatherComponents.Low.class, ForgeZRenderTooltip.GatherComponents.Low.class); - bus.registerSubClass(ZScreen.Opening.class, ForgeZScreen.Opening.class); - bus.registerSubClass(ZScreen.CharacterTyped.Pre.class, ForgeZScreen.CharacterTyped.Pre.class); - bus.registerSubClass(ZScreen.CharacterTyped.Post.class, ForgeZScreen.CharacterTyped.Post.class); - bus.registerSubClass(ZScreen.Init.Post.class, ForgeZScreen.Init.Post.class); - bus.registerSubClass(ZScreen.Init.Pre.class, ForgeZScreen.Init.Pre.class); - bus.registerSubClass(ZScreen.KeyPressed.Post.class, ForgeZScreen.KeyPressed.Post.class); - bus.registerSubClass(ZScreen.KeyPressed.Pre.class, ForgeZScreen.KeyPressed.Pre.class); - bus.registerSubClass(ZScreen.MouseScrolled.Post.class, ForgeZScreen.MouseScrolled.Post.class); - bus.registerSubClass(ZScreen.MouseScrolled.Pre.class, ForgeZScreen.MouseScrolled.Pre.class); - bus.registerSubClass(ZScreen.MouseButtonPressed.Post.class, ForgeZScreen.MouseButtonPressed.Post.class); - bus.registerSubClass(ZScreen.MouseButtonPressed.Pre.class, ForgeZScreen.MouseButtonPressed.Pre.class); - bus.registerSubClass(ZScreen.Render.Post.class, ForgeZScreen.Render.Post.class); - bus.registerSubClass(ZScreen.Render.Pre.class, ForgeZScreen.Render.Pre.class); - bus.registerSubClass(ZRenderGuiOverlay.ArmorLevel.Pre.class, ForgeZRenderGuiOverlay.ArmorLevel.Pre.class); - bus.registerSubClass(ZRenderGuiOverlay.ArmorLevel.Post.class, ForgeZRenderGuiOverlay.ArmorLevel.Post.class); - bus.registerSubClass(ZRenderGuiOverlay.Crosshair.Pre.class, ForgeZRenderGuiOverlay.Crosshair.Post.class); - bus.registerSubClass(ZRenderGuiOverlay.Crosshair.Post.class, ForgeZRenderGuiOverlay.Crosshair.Pre.class); - bus.registerSubClass(ZRenderGuiOverlay.DebugText.Pre.class, ForgeZRenderGuiOverlay.DebugText.Pre.class); - bus.registerSubClass(ZRenderGuiOverlay.DebugText.Post.class, ForgeZRenderGuiOverlay.DebugText.Post.class); - bus.registerSubClass(ZRenderGuiOverlay.Hotbar.Pre.class, ForgeZRenderGuiOverlay.Hotbar.Pre.class); - bus.registerSubClass(ZRenderGuiOverlay.Hotbar.Post.class, ForgeZRenderGuiOverlay.Hotbar.Post.class); - bus.registerSubClass(ZRenderGuiOverlay.PlayerHealth.Pre.class, ForgeZRenderGuiOverlay.PlayerHealth.Pre.class); - bus.registerSubClass(ZRenderGuiOverlay.PlayerHealth.Post.class, ForgeZRenderGuiOverlay.PlayerHealth.Post.class); - bus.registerSubClass(ZRenderGuiOverlay.PotionIcons.Pre.class, ForgeZRenderGuiOverlay.PotionIcons.Pre.class); - bus.registerSubClass(ZRenderGuiOverlay.PotionIcons.Post.class, ForgeZRenderGuiOverlay.PotionIcons.Post.class); - bus.registerSubClass(ZRenderGuiOverlay.ChatPanel.Pre.class, ForgeZRenderGuiOverlay.ChatPanel.Pre.class); - bus.registerSubClass(ZRenderGuiOverlay.ChatPanel.Post.class, ForgeZRenderGuiOverlay.ChatPanel.Post.class); - bus.registerSubClass(ZScreenshot.class, ForgeZScreenshot.class); - - //this is ugly. generic events here - Zeta zeta = this; - bus.registerSubClassWithGeneric(ZAttachCapabilities.BlockEntityCaps.class, - ForgeZAttachCapabilities.BlockEntityCaps.class, - (Function, ForgeZAttachCapabilities.BlockEntityCaps>) inner -> - new ForgeZAttachCapabilities.BlockEntityCaps(zeta.capabilityManager, inner), - BlockEntity.class); - bus.registerSubClassWithGeneric(ZAttachCapabilities.ItemStackCaps.class, - ForgeZAttachCapabilities.ItemStackCaps.class, - (Function, ForgeZAttachCapabilities.ItemStackCaps>) inner -> - new ForgeZAttachCapabilities.ItemStackCaps(zeta.capabilityManager, inner), - ItemStack.class); - bus.registerSubClassWithGeneric(ZAttachCapabilities.LevelCaps.class, - ForgeZAttachCapabilities.LevelCaps.class, - (Function, ForgeZAttachCapabilities.LevelCaps>) inner -> - new ForgeZAttachCapabilities.LevelCaps(zeta.capabilityManager, inner), - Level.class); - - // zeta specific ones - - bus.registerSubClass(ZRecipeCrawl.Digest.class, ForgeZRecipeCrawl.Digest.class); - bus.registerSubClass(ZRecipeCrawl.Reset.class, ForgeZRecipeCrawl.Reset.class); - bus.registerSubClass(ZRecipeCrawl.Starting.class, ForgeZRecipeCrawl.Starting.class); - bus.registerSubClass(ZRecipeCrawl.Visit.Cooking.class, ForgeZRecipeCrawl.Visit.Cooking.class); - bus.registerSubClass(ZRecipeCrawl.Visit.Custom.class, ForgeZRecipeCrawl.Visit.Custom.class); - bus.registerSubClass(ZRecipeCrawl.Visit.Misc.class, ForgeZRecipeCrawl.Visit.Misc.class); - bus.registerSubClass(ZRecipeCrawl.Visit.Shaped.class, ForgeZRecipeCrawl.Visit.Shaped.class); - bus.registerSubClass(ZRecipeCrawl.Visit.Shapeless.class, ForgeZRecipeCrawl.Visit.Shapeless.class); - - return bus; + return ForgeZetaEventBus.ofPlayBus(log, this); } @Override @@ -301,7 +130,7 @@ public PottedPlantRegistry createPottedPlantRegistry() { @Override public ZetaCapabilityManager createCapabilityManager() { - return new ForgeCapabilityManager(); + return ForgeCapabilityManager.INSTANCE; } @Override @@ -332,6 +161,7 @@ public boolean fireRightClickBlock(Player player, InteractionHand hand, BlockPos @SuppressWarnings("duplicates") @Override public void start() { + super.start(); //load IEventBus modbus = FMLJavaModLoadingContext.get().getModEventBus(); diff --git a/src/main/java/org/violetmoon/zetaimplforge/capability/ForgeCapabilityManager.java b/src/main/java/org/violetmoon/zetaimplforge/capability/ForgeCapabilityManager.java index ffef9b3..e572102 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/capability/ForgeCapabilityManager.java +++ b/src/main/java/org/violetmoon/zetaimplforge/capability/ForgeCapabilityManager.java @@ -19,6 +19,15 @@ import net.minecraftforge.event.AttachCapabilitiesEvent; public class ForgeCapabilityManager implements ZetaCapabilityManager { + + //Why is this a singleton instance? + // Because attach capability event fires on the mod-independent PLAY bus and this would have to be passed in the event which just fires once instead of once per mod. + + public static final ForgeCapabilityManager INSTANCE = new ForgeCapabilityManager(); + + private ForgeCapabilityManager() { + } + protected Map, Capability> toForge = new IdentityHashMap<>(); @SuppressWarnings("unchecked") diff --git a/src/main/java/org/violetmoon/zetaimplforge/client/event/load/ForgeZAddBlockColorHandlers.java b/src/main/java/org/violetmoon/zetaimplforge/client/event/load/ForgeZAddBlockColorHandlers.java index 09c2323..4b194c5 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/client/event/load/ForgeZAddBlockColorHandlers.java +++ b/src/main/java/org/violetmoon/zetaimplforge/client/event/load/ForgeZAddBlockColorHandlers.java @@ -4,6 +4,7 @@ import net.minecraft.client.color.block.BlockColors; import net.minecraft.world.level.block.Block; import net.minecraftforge.client.event.RegisterColorHandlersEvent; +import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.client.event.load.ZAddBlockColorHandlers; import org.violetmoon.zeta.registry.ZetaRegistry; @@ -13,11 +14,9 @@ public class ForgeZAddBlockColorHandlers implements ZAddBlockColorHandlers { protected final RegisterColorHandlersEvent.Block e; - private final ZetaRegistry zetaRegistry; - public ForgeZAddBlockColorHandlers(RegisterColorHandlersEvent.Block e, ZetaRegistry zetaRegistry) { + public ForgeZAddBlockColorHandlers(RegisterColorHandlersEvent.Block e) { this.e = e; - this.zetaRegistry = zetaRegistry; } @Override @@ -25,10 +24,11 @@ public void register(BlockColor blockColor, Block... blocks) { e.register(blockColor, blocks); } + // yes passing zeta like this here is terribly ugly but i cant add more params to this event since it's a forge event wrapper @Override - public void registerNamed(Function c, String... names) { + public void registerNamed(Zeta myZeta, Function c, String... names) { for (String name : names) { - zetaRegistry.assignBlockColor(name, b -> register(c.apply(b), b)); + myZeta.registry.assignBlockColor(name, b -> register(c.apply(b), b)); } } diff --git a/src/main/java/org/violetmoon/zetaimplforge/client/event/load/ForgeZAddItemColorHandlers.java b/src/main/java/org/violetmoon/zetaimplforge/client/event/load/ForgeZAddItemColorHandlers.java index 4ea1843..1579372 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/client/event/load/ForgeZAddItemColorHandlers.java +++ b/src/main/java/org/violetmoon/zetaimplforge/client/event/load/ForgeZAddItemColorHandlers.java @@ -1,9 +1,8 @@ package org.violetmoon.zetaimplforge.client.event.load; -import java.util.HashMap; -import java.util.Map; import java.util.function.Function; +import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.client.event.load.ZAddItemColorHandlers; import net.minecraft.client.color.item.ItemColor; @@ -11,16 +10,12 @@ import net.minecraft.world.item.Item; import net.minecraft.world.level.ItemLike; import net.minecraftforge.client.event.RegisterColorHandlersEvent; -import org.violetmoon.zeta.registry.ZetaRegistry; public class ForgeZAddItemColorHandlers implements ZAddItemColorHandlers { protected final RegisterColorHandlersEvent.Item e; - protected final Map> namedItemColors = new HashMap<>(); - private final ZetaRegistry zetaRegistry; - public ForgeZAddItemColorHandlers(RegisterColorHandlersEvent.Item e, ZetaRegistry zetaRegistry) { + public ForgeZAddItemColorHandlers(RegisterColorHandlersEvent.Item e) { this.e = e; - this.zetaRegistry = zetaRegistry; } @Override @@ -29,9 +24,9 @@ public void register(ItemColor c, ItemLike... items) { } @Override - public void registerNamed(Function c, String... names) { + public void registerNamed(Zeta myZeta, Function c, String... names) { for (String name : names) { - zetaRegistry.assignItemColor(name, b -> register(c.apply(b), b)); + myZeta.registry.assignItemColor(name, b -> register(c.apply(b), b)); } } diff --git a/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZClientTick.java b/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZClientTick.java index 3a82e0f..60b5b5c 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZClientTick.java +++ b/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZClientTick.java @@ -1,10 +1,8 @@ package org.violetmoon.zetaimplforge.client.event.play; import org.violetmoon.zeta.client.event.play.ZClientTick; -import org.violetmoon.zeta.event.bus.ZPhase; import net.minecraftforge.event.TickEvent.ClientTickEvent; -import net.minecraftforge.event.TickEvent.Phase; public class ForgeZClientTick implements ZClientTick { private final ClientTickEvent e; @@ -13,22 +11,16 @@ public ForgeZClientTick(ClientTickEvent e) { this.e = e; } - @Override - public ZPhase getPhase() { - return from(e.phase); + public static class Start extends ForgeZClientTick implements ZClientTick.Start { + public Start(ClientTickEvent e) { + super(e); + } } - public static ZPhase from(Phase r) { - return switch(r) { - case START -> ZPhase.START; - case END -> ZPhase.END; - }; + public static class End extends ForgeZClientTick implements ZClientTick.End { + public End(ClientTickEvent e) { + super(e); + } } - public static Phase to(ZPhase r) { - return switch(r) { - case START -> Phase.START; - case END -> Phase.END; - }; - } } diff --git a/src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java b/src/main/java/org/violetmoon/zetaimplforge/event/ForgeEventsRemapper.java similarity index 72% rename from src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java rename to src/main/java/org/violetmoon/zetaimplforge/event/ForgeEventsRemapper.java index fbcb6be..92b28c3 100644 --- a/src/main/java/org/violetmoon/zeta/event/bus/ForgeZetaEventBus.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/ForgeEventsRemapper.java @@ -1,4 +1,4 @@ -package org.violetmoon.zeta.event.bus; +package org.violetmoon.zetaimplforge.event; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import net.minecraftforge.event.TickEvent; @@ -7,103 +7,39 @@ import net.minecraftforge.eventbus.api.GenericEvent; import net.minecraftforge.eventbus.api.IEventBus; import org.apache.commons.lang3.text.WordUtils; -import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.violetmoon.zeta.Zeta; +import org.violetmoon.zeta.event.bus.IZetaLoadEvent; +import org.violetmoon.zeta.event.bus.IZetaPlayEvent; +import org.violetmoon.zeta.event.load.ZCommonSetup; +import org.violetmoon.zetaimplforge.event.load.ForgeZCommonSetup; -import java.lang.annotation.Annotation; import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; import java.lang.reflect.Constructor; import java.lang.reflect.Field; -import java.lang.reflect.Method; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; -// this is super jank. Basically converts all zeta events to forge ones, then delegates to the forge bus directly -public class ForgeZetaEventBus extends ZetaEventBus { +public class ForgeEventsRemapper { + + private final Class forgeEventRoot; + private final Class zetaEventRoot; private final Map, Function> forgeToZetaMap = new Object2ObjectOpenHashMap<>(); private final Map, Function> zetaToForgeMap = new Object2ObjectOpenHashMap<>(); private final Map, Class> generics = new Object2ObjectOpenHashMap<>(); - // needed so we can unregister later - private final Map convertedHandlers = new Object2ObjectOpenHashMap<>(); + // hack needed to store classes of each Z event to Forge event. // Needed because java has type erasure so forge be able to add listeners to anonymous generic lambdas without being passed an event type class private final Map, Class> zetaToForgeEventClassHack = new Object2ObjectOpenHashMap<>(); - private final IEventBus forgeBus; - private final Class forgeEventRoot; //if Events should implement IModBusEvent - - /** - * @param subscriberAnnotation The annotation that subscribe()/unsubscribe() will pay attention to. - * @param eventRoot The superinterface of all events fired on this bus. - */ - public ForgeZetaEventBus(Class subscriberAnnotation, Class eventRoot, - @Nullable Logger logSpam, IEventBus forgeBus, Class forgeEventRoot) { - super(subscriberAnnotation, eventRoot, logSpam); - this.forgeBus = forgeBus; + public ForgeEventsRemapper(Class zetaEventRoot, Class forgeEventRoot) { this.forgeEventRoot = forgeEventRoot; - } - - - @Override - protected void subscribeMethod(Method method, Object receiver, Class owningClazz) { - if (method.getParameterCount() != 1) - throw arityERR(method); - - Class zetaEventClass = method.getParameterTypes()[0]; - - //check if it's already a forge event, or it's a zeta event - if (!eventRoot.isAssignableFrom(zetaEventClass) && !forgeEventRoot.isAssignableFrom(zetaEventClass)) - throw typeERR(method); - - MethodHandle handle; - try { - handle = MethodHandles.publicLookup().unreflect(method); - } catch (Exception e) { - throw new RuntimeException(e); - } - - //fill in the "this" parameter - if (receiver != null) - handle = handle.bindTo(receiver); - - Consumer consumer = remapMethod(handle, zetaEventClass); - registerListenerToForgeWithPriorityAndGenerics(owningClazz, consumer, zetaEventClass); - //store here so we can unregister later - convertedHandlers.put(new Key(method, receiver, owningClazz), consumer); - - } - - - @Override - protected void unsubscribeMethod(Method m, Object receiver, Class owningClazz) { - var handler = convertedHandlers.remove(new Key(m, receiver, owningClazz)); - if (handler != null) { - forgeBus.unregister(handler); - } - } - - - private record Key(Method method, Object receiver, Class owningClazz) { - } - - @Override - public T fire(@NotNull T event) { - forgeBus.post(remapEvent(event, event.getClass())); - return event; - } - - @Override - public T fire(@NotNull T event, Class firedAs) { - forgeBus.post(remapEvent(event, firedAs)); - return event; + this.zetaEventRoot = zetaEventRoot; } // reflection hacks and ugly code below. Turn back now. You have been warned @@ -113,7 +49,7 @@ public T fire(@NotNull T event, Class firedAs) { /** * Given an event object which is NOT a subtype of Event class, remap it to a forge event */ - private F remapEvent(@NotNull Z2 zetaEvent, Class firedAs) { + protected F remapEvent(@NotNull Z2 zetaEvent, Class firedAs) { Function zetaToForgeFunc = zetaToForgeMap.get(firedAs); if (zetaToForgeFunc == null) { // remap is null. no checks because micro optimization. It means it must be a forge event already @@ -127,12 +63,18 @@ private F remapEvent(@NotNull Z2 zetaEvent, Class firedAs) { /** * Given a MethodHandle of a method which takes a Zeta event, remaps it to a method which takes a Forge event, so we can register it with Forge event bus */ - private Consumer remapMethod(MethodHandle originalEventConsumer, Class zetaEventBaseClass) { + protected Consumer remapMethod(MethodHandle originalEventConsumer, Class zetaEventBaseClass) { Function forgeToZetaFunc = forgeToZetaMap.get(zetaEventBaseClass); if (forgeToZetaFunc == null) { // no remap needed if (forgeEventRoot.isAssignableFrom(zetaEventBaseClass)) { - forgeToZetaFunc = event -> (Z) event; + forgeToZetaFunc = event -> { + try { + return (Z) event; + } catch (Exception e) { + throw new RuntimeException(e); + } + }; } else throw new RuntimeException("Could not convert Zeta event class " + zetaEventBaseClass + " to Forge event. You must register its subclass using registerSubclass."); } @@ -147,8 +89,8 @@ private F createForgeEvent(@NotNull Z event, Function Consumer createForgeConsumer(MethodHandle zetaEventConsumer, Function forgeToZetaFunc, - Class zetaEventBaseClass) { + private Consumer createForgeConsumer( + MethodHandle zetaEventConsumer, Function forgeToZetaFunc, Class zetaEventBaseClass) { //hack for tick events Phase phase = Phase.guessFromClassName(zetaEventBaseClass); return event -> { @@ -166,12 +108,12 @@ private Consumer createForgeConsumer(MethodHand } // for generic events - public void registerSubClassWithGeneric(Class baseZetaEventClass, Class forgeZetaEventClass, Class genericClass) { + public void registerSubClassWithGeneric(Class baseZetaEventClass, Class forgeZetaEventClass, Class genericClass) { registerSubClass(baseZetaEventClass, forgeZetaEventClass); generics.put(baseZetaEventClass, genericClass); } - public void registerSubClass(Class baseZetaEventClass, Class forgeZetaEventClass) { + public void registerSubClass(Class baseZetaEventClass, Class forgeZetaEventClass) { registerSubClass(baseZetaEventClass, forgeZetaEventClass, null); } @@ -187,13 +129,33 @@ public void registerSubClass(Class baseZetaEven Object old1; Object old2 = null; boolean isNoWrapper = false; + + if ((Class) forgeZetaEventClass == ForgeZCommonSetup.class) { + int aa = 1; + } + if (constructor == null) { - // if it's an Event already just returns the no argument constructor + // if it's an Event already just returns the no argument constructor. Provided it subclasses its abstract impl if (forgeEventRoot.isAssignableFrom(forgeZetaEventClass)) { zetaToForgeEventClassHack.put(baseZetaEventClass, forgeZetaEventClass); - constructor = event -> (ZF) event; + + if (baseZetaEventClass.isAssignableFrom(forgeZetaEventClass)) { + constructor = event -> { + try { + return (ZF) event; + } catch (Exception e) { + throw new RuntimeException(e); + } + }; + } else { + constructor = findWrappedZetaEvent(forgeZetaEventClass, baseZetaEventClass); + } + isNoWrapper = true; - } else constructor = findForgeWrapper(forgeZetaEventClass, baseZetaEventClass); + } + if (constructor == null) { + constructor = findForgeWrapper(forgeZetaEventClass, baseZetaEventClass); + } } if (constructor == null) { throw new RuntimeException("No Forge-Event-wrapping constructor found for Zeta event class " + forgeZetaEventClass); @@ -227,11 +189,11 @@ public void registerSubClass(Class baseZetaEven // For this reason here we have some functions that, with a lot of assumptions, try to find wrappers and unwrapper functions for each Forge-Zeta classes pair /** - * @param zetaEventClass i.e: ForgeZClientSetup.class + * @param zetaEventClass i.e: ForgeZClientSetup.class * @param baseZetaEventClass i.e: ZClientSetup.class - *

- * Attempts to find a constructor of zetaEventClass which takes an Event as a parameter. This is used for simple forge Event wrappers - * in this example the one found will be new ForgeZClientSetup(FMLClientSetupEvent event) + *

+ * Attempts to find a constructor of zetaEventClass which takes an Event as a parameter. This is used for simple forge Event wrappers + * in this example the one found will be new ForgeZClientSetup(FMLClientSetupEvent event) */ private Function findForgeWrapper(Class zetaEventClass, Class baseZetaEventClass) { @@ -265,7 +227,7 @@ private Function findZetaWrapper(Class // Find the constructor that takes a single parameter of type A for (Constructor constructor : zetaEventClass.getConstructors()) { Class[] parameterTypes = constructor.getParameterTypes(); - if (parameterTypes.length == 1 && eventRoot.isAssignableFrom(parameterTypes[0])) { + if (parameterTypes.length == 1 && zetaEventRoot.isAssignableFrom(parameterTypes[0])) { return event -> { try { return (F2) constructor.newInstance(event); @@ -291,7 +253,7 @@ private Function findWrappedForgeEvent(Clas if (eventField != null) { //hack eventField.setAccessible(true); - if(!zetaToForgeEventClassHack.containsKey(baseZetaEventClass)){ + if (!zetaToForgeEventClassHack.containsKey(baseZetaEventClass)) { zetaToForgeEventClassHack.put(baseZetaEventClass, eventField.getType()); } return instance -> { @@ -305,7 +267,7 @@ private Function findWrappedForgeEvent(Clas //tries to unwrap first. Then if its already a forge event we just keep it if (forgeEventRoot.isAssignableFrom(zetaEventClass)) { - if(!zetaToForgeEventClassHack.containsKey(baseZetaEventClass)){ + if (!zetaToForgeEventClassHack.containsKey(baseZetaEventClass)) { zetaToForgeEventClassHack.put(baseZetaEventClass, zetaEventClass); } return null; @@ -314,6 +276,23 @@ private Function findWrappedForgeEvent(Clas throw new RuntimeException("No wrapped forge Event found for Zeta event class " + zetaEventClass); } + private Function findWrappedZetaEvent(Class zetaEventClass, Class baseZetaEventClass) { + Field eventField = findFieldInClassHierarchy(zetaEventClass, f -> zetaEventRoot.isAssignableFrom(f.getType())); + if (eventField != null) { + //hack + eventField.setAccessible(true); + return instance -> { + try { + return (Z2) eventField.get(instance); + } catch (Exception e) { + throw new RuntimeException(e); + } + }; + } + + throw new RuntimeException("No wrapped Zeta Event found for Zeta event class " + zetaEventClass); + } + public static Field findFieldInClassHierarchy(Class clazz, Predicate predicate) { while (clazz != null) { for (Field f : clazz.getDeclaredFields()) { @@ -330,7 +309,7 @@ public static Field findFieldInClassHierarchy(Class clazz, Predicate p //TODO: refactor in 1.21 using interfaces and stuff. This is just here for now as i want to keep binary compatibility - private void registerListenerToForgeWithPriorityAndGenerics(Class owningClazz, Consumer consumer, Class zetaEventClass) { + protected void registerListenerToForgeWithPriorityAndGenerics(IEventBus bus, Class owningClazz, Consumer consumer, Class zetaEventClass) { EventPriority priority = guessPriorityFromClassName(owningClazz); Class gen = generics.get(zetaEventClass); Class eventType = zetaToForgeEventClassHack.get(zetaEventClass); @@ -338,9 +317,9 @@ private void registerListenerToForgeWithPriorityAndGenerics(Class owningClazz throw new RuntimeException("No event type found for " + zetaEventClass); } if (gen != null) { - forgeBus.addGenericListener(gen, priority, false, eventType, (Consumer) consumer); + bus.addGenericListener(gen, priority, false, eventType, (Consumer) consumer); } else { - forgeBus.addListener(priority, false, eventType, consumer); + bus.addListener(priority, false, eventType, consumer); } } @@ -376,4 +355,13 @@ private static EventPriority guessPriorityFromClassName(Class zetaEventClass) }); } + public ForgeEventsRemapper makeCopy() { + ForgeEventsRemapper copy = new ForgeEventsRemapper<>(zetaEventRoot, forgeEventRoot); + copy.forgeToZetaMap.putAll(forgeToZetaMap); + copy.zetaToForgeMap.putAll(zetaToForgeMap); + copy.generics.putAll(generics); + copy.zetaToForgeEventClassHack.putAll(zetaToForgeEventClassHack); + return copy; + } + } diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/ForgeZetaEventBus.java b/src/main/java/org/violetmoon/zetaimplforge/event/ForgeZetaEventBus.java new file mode 100644 index 0000000..2e221f6 --- /dev/null +++ b/src/main/java/org/violetmoon/zetaimplforge/event/ForgeZetaEventBus.java @@ -0,0 +1,346 @@ +package org.violetmoon.zetaimplforge.event; + +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import net.minecraft.Util; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.event.AttachCapabilitiesEvent; +import net.minecraftforge.eventbus.api.Event; +import net.minecraftforge.eventbus.api.IEventBus; +import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; +import net.minecraftforge.fml.loading.FMLEnvironment; +import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.violetmoon.zeta.Zeta; +import org.violetmoon.zeta.client.event.load.*; +import org.violetmoon.zeta.client.event.play.*; +import org.violetmoon.zeta.event.bus.*; +import org.violetmoon.zeta.event.load.*; +import org.violetmoon.zeta.event.play.*; +import org.violetmoon.zeta.event.play.entity.*; +import org.violetmoon.zeta.event.play.entity.living.*; +import org.violetmoon.zeta.event.play.entity.player.*; +import org.violetmoon.zeta.event.play.loading.*; +import org.violetmoon.zetaimplforge.api.ForgeZGatherAdvancementModifiers; +import org.violetmoon.zetaimplforge.capability.ForgeCapabilityManager; +import org.violetmoon.zetaimplforge.client.event.load.*; +import org.violetmoon.zetaimplforge.client.event.play.*; +import org.violetmoon.zetaimplforge.event.load.*; +import org.violetmoon.zetaimplforge.event.play.*; +import org.violetmoon.zetaimplforge.event.play.entity.*; +import org.violetmoon.zetaimplforge.event.play.entity.living.*; +import org.violetmoon.zetaimplforge.event.play.entity.player.*; +import org.violetmoon.zetaimplforge.event.play.loading.*; + +import java.lang.annotation.Annotation; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.reflect.Method; +import java.util.Map; +import java.util.function.Consumer; +import java.util.function.Function; + +// this is super jank. Basically converts all zeta events to forge ones, then delegates to the forge bus directly +public class ForgeZetaEventBus extends ZetaEventBus { + + // needed so we can unregister later + private final Map convertedHandlers = new Object2ObjectOpenHashMap<>(); + + private final IEventBus forgeBus; + private final Class forgeEventRoot; //probably not needed can be replaced with Event + private final ForgeEventsRemapper remapper; + + /** + * @param subscriberAnnotation The annotation that subscribe()/unsubscribe() will pay attention to. + * @param eventRoot The superinterface of all events fired on this bus. + */ + protected ForgeZetaEventBus(Class subscriberAnnotation, Class eventRoot, + @Nullable Logger logSpam, IEventBus forgeBus, Class forgeEventRoot, + Zeta ofZeta, ForgeEventsRemapper remapper) { + super(subscriberAnnotation, eventRoot, logSpam, ofZeta); + this.forgeBus = forgeBus; + this.forgeEventRoot = forgeEventRoot; + this.remapper = remapper; + } + + public static ForgeZetaEventBus ofLoadBus(@Nullable Logger logSpam, Zeta ofZeta) { + return new ForgeZetaEventBus<>( + LoadEvent.class, IZetaLoadEvent.class, + logSpam, FMLJavaModLoadingContext.get().getModEventBus(), Event.class, + ofZeta, LOAD_EVENTS_REMAPPER); + } + + public static ForgeZetaEventBus ofPlayBus(@Nullable Logger logSpam, Zeta ofZeta) { + return new ForgeZetaEventBus<>( + PlayEvent.class, IZetaPlayEvent.class, + logSpam, MinecraftForge.EVENT_BUS, Event.class, + ofZeta, PLAY_EVENTS_REMAPPER); + } + + + @Override + protected void subscribeMethod(Method method, Object receiver, Class owningClazz) { + if (method.getParameterCount() != 1) + throw arityERR(method); + + Class zetaEventClass = method.getParameterTypes()[0]; + + //check if it's already a forge event, or it's a zeta event + if (!eventRoot.isAssignableFrom(zetaEventClass) && !forgeEventRoot.isAssignableFrom(zetaEventClass)) + throw typeERR(method); + + MethodHandle handle; + try { + handle = MethodHandles.publicLookup().unreflect(method); + } catch (Exception e) { + throw new RuntimeException(e); + } + + //fill in the "this" parameter + if (receiver != null) + handle = handle.bindTo(receiver); + + Consumer consumer = remapper.remapMethod(handle, zetaEventClass); + remapper.registerListenerToForgeWithPriorityAndGenerics(forgeBus, owningClazz, consumer, zetaEventClass); + //store here so we can unregister later + convertedHandlers.put(new Key(method, receiver, owningClazz), consumer); + } + + @Override + protected void unsubscribeMethod(Method m, Object receiver, Class owningClazz) { + var handler = convertedHandlers.remove(new Key(m, receiver, owningClazz)); + if (handler != null) { + forgeBus.unregister(handler); + } + } + + private record Key(Method method, Object receiver, Class owningClazz) { + } + + @Override + public T fire(@NotNull T event) { + forgeBus.post(remapper.remapEvent(event, event.getClass())); + return event; + } + + @Override + public T fire(@NotNull T event, Class firedAs) { + forgeBus.post(remapper.remapEvent(event, firedAs)); + return event; + } + + // all these are for bus specific events. The only bus that should have specific stuff is the play one + + // for generic events + public void registerSubClassWithGeneric(Class baseZetaEventClass, Class forgeZetaEventClass, Class genericClass) { + synchronized (remapper) { + remapper.registerSubClassWithGeneric(baseZetaEventClass, forgeZetaEventClass, genericClass); + } + } + + public void registerSubClass(Class baseZetaEventClass, Class forgeZetaEventClass) { + synchronized (remapper) { + remapper.registerSubClass(baseZetaEventClass, forgeZetaEventClass, null); + } + } + + public void registerSubClassWithGeneric(Class baseZetaEventClass, Class forgeZetaEventClass, + Function constructor, Class genericClass) { + synchronized (remapper) { + remapper.registerSubClassWithGeneric(baseZetaEventClass, forgeZetaEventClass, constructor, genericClass); + } + } + + public void registerSubClass(Class baseZetaEventClass, Class forgeZetaEventClass, + @Nullable Function constructor) { + synchronized (remapper) { + remapper.registerSubClass(baseZetaEventClass, forgeZetaEventClass, constructor); + } + } + + // I would love to put this code in the mod proxy but that needs to do event setup stuff which requires these busses to be fully initialized + + // instances so we don't create multiple as reflections take time and memory + private static final ForgeEventsRemapper LOAD_EVENTS_REMAPPER = Util.make(new ForgeEventsRemapper<>(IZetaLoadEvent.class, Event.class), r -> { + + // adds known events subclasses to the bus + r.registerSubClass(ZCommonSetup.class, ForgeZCommonSetup.class); + r.registerSubClass(ZEntityAttributeCreation.class, ForgeZEntityAttributeCreation.class); + r.registerSubClass(ZModulesReady.class, ForgeZModulesReady.class); + r.registerSubClass(ZRegister.class, ForgeZRegister.class); + r.registerSubClass(ZRegister.Post.class, ForgeZRegister.Post.class); + r.registerSubClass(ZConfigChanged.class, ForgeZConfigChange.class); + r.registerSubClass(ZLoadComplete.class, ForgeZLoadComplete.class); + + // client ones again? + if(FMLEnvironment.dist == Dist.DEDICATED_SERVER) return; + + r.registerSubClass(ZAddModels.class, ForgeZAddModels.class); + r.registerSubClass(ZAddModelLayers.class, ForgeZAddModelLayers.class); + r.registerSubClass(ZClientSetup.class, ForgeZClientSetup.class); + r.registerSubClass(ZKeyMapping.class, ForgeZKeyMapping.class); + r.registerSubClass(ZModel.RegisterGeometryLoaders.class, ForgeZModel.RegisterGeometryLoaders.class); + r.registerSubClass(ZModel.RegisterAdditional.class, ForgeZModel.RegisterAdditional.class); + r.registerSubClass(ZModel.BakingCompleted.class, ForgeZModel.BakingCompleted.class); + r.registerSubClass(ZModel.ModifyBakingResult.class, ForgeZModel.ModifyBakingResult.class); + r.registerSubClass(ZRegisterLayerDefinitions.class, ForgeZRegisterLayerDefinitions.class); + r.registerSubClass(ZTooltipComponents.class, ForgeZTooltipComponents.class); + r.registerSubClass(ZRegisterClientReloadListener.class, ForgeZRegisterClientReloadListener.class); + r.registerSubClass(ZFirstClientTick.class, ForgeZFirstClientTick.class); + + r.registerSubClass(ZAddBlockColorHandlers.class, ForgeZAddBlockColorHandlers.class); + r.registerSubClass(ZAddItemColorHandlers.class, ForgeZAddItemColorHandlers.class); + }); + + private static final ForgeEventsRemapper PLAY_EVENTS_REMAPPER = Util.make(new ForgeEventsRemapper<>(IZetaPlayEvent.class, Event.class), r -> { + + r.registerSubClass(ZAnvilRepair.class, ForgeZAnvilRepair.class); + r.registerSubClass(ZAnvilUpdate.Highest.class, ForgeZAnvilUpdate.Highest.class); + r.registerSubClass(ZAnvilUpdate.Lowest.class, ForgeZAnvilUpdate.Lowest.class); + r.registerSubClass(ZTagsUpdated.class, ForgeZTagsUpdated.class); + r.registerSubClass(ZBabyEntitySpawn.Lowest.class, ForgeZBabyEntitySpawn.Lowest.class); + r.registerSubClass(ZBabyEntitySpawn.class, ForgeZBabyEntitySpawn.class); + r.registerSubClass(ZBlock.Break.class, ForgeZBlock.Break.class); + r.registerSubClass(ZBlock.EntityPlace.class, ForgeZBlock.EntityPlace.class); + r.registerSubClass(ZBlock.BlockToolModification.class, ForgeZBlock.BlockToolModification.class); + r.registerSubClass(ZBonemeal.class, ForgeZBonemeal.class); + r.registerSubClass(ZEntityConstruct.class, ForgeZEntityConstruct.class); + r.registerSubClass(ZEntityInteract.class, ForgeZEntityInteract.class); + r.registerSubClass(ZEntityItemPickup.class, ForgeZEntityItemPickup.class); + r.registerSubClass(ZEntityJoinLevel.class, ForgeZEntityJoinLevel.class); + r.registerSubClass(ZEntityMobGriefing.class, ForgeZEntityMobGriefing.class); + r.registerSubClass(ZEntityTeleport.class, ForgeZEntityTeleport.class); + r.registerSubClass(ZItemTooltip.class, ForgeZItemTooltip.class); + r.registerSubClass(ZLivingChangeTarget.class, ForgeZLivingChangeTarget.class); + r.registerSubClass(ZLivingConversion.class, ForgeZLivingConversion.class); + r.registerSubClass(ZLivingConversion.Pre.class, ForgeZLivingConversion.Pre.class); + r.registerSubClass(ZLivingConversion.Post.class, ForgeZLivingConversion.Post.class); + r.registerSubClass(ZLivingDeath.class, ForgeZLivingDeath.class); + r.registerSubClass(ZLivingDeath.Lowest.class, ForgeZLivingDeath.Lowest.class); + r.registerSubClass(ZLivingDrops.class, ForgeZLivingDrops.class); + r.registerSubClass(ZLivingDrops.Lowest.class, ForgeZLivingDrops.Lowest.class); + r.registerSubClass(ZLivingFall.class, ForgeZLivingFall.class); + r.registerSubClass(ZLivingTick.class, ForgeZLivingTick.class); + r.registerSubClass(ZMobSpawnEvent.class, ForgeZMobSpawnEvent.class); + r.registerSubClass(ZMobSpawnEvent.CheckSpawn.class, ForgeZMobSpawnEvent.FinalizeSpawn.class); + r.registerSubClass(ZMobSpawnEvent.CheckSpawn.Lowest.class, ForgeZMobSpawnEvent.FinalizeSpawn.Lowest.class); + r.registerSubClass(ZPlayNoteBlock.class, ForgeZPlayNoteBlock.class); + r.registerSubClass(ZPlayer.class, ForgeZPlayer.class); + r.registerSubClass(ZPlayer.BreakSpeed.class, ForgeZPlayer.BreakSpeed.class); + r.registerSubClass(ZPlayer.Clone.class, ForgeZPlayer.Clone.class); + r.registerSubClass(ZPlayerDestroyItem.class, ForgeZPlayerDestroyItem.class); + r.registerSubClass(ZPlayer.LoggedIn.class, ForgeZPlayer.LoggedIn.class); + r.registerSubClass(ZPlayer.LoggedOut.class, ForgeZPlayer.LoggedOut.class); + r.registerSubClass(ZPlayerTick.Start.class, ForgeZPlayerTick.Start.class); + r.registerSubClass(ZPlayerTick.End.class, ForgeZPlayerTick.End.class); + r.registerSubClass(ZPlayerInteract.class, ForgeZPlayerInteract.class); + r.registerSubClass(ZPlayerInteract.EntityInteractSpecific.class, ForgeZPlayerInteract.EntityInteractSpecific.class); + r.registerSubClass(ZPlayerInteract.EntityInteract.class, ForgeZPlayerInteract.EntityInteract.class); + r.registerSubClass(ZPlayerInteract.RightClickBlock.class, ForgeZPlayerInteract.RightClickBlock.class); + r.registerSubClass(ZPlayerInteract.RightClickItem.class, ForgeZPlayerInteract.RightClickItem.class); + r.registerSubClass(ZRightClickBlock.class, ForgeZRightClickBlock.class); + r.registerSubClass(ZRightClickBlock.Low.class, ForgeZRightClickBlock.Low.class); + r.registerSubClass(ZRightClickItem.class, ForgeZRightClickItem.class); + r.registerSubClass(ZLootTableLoad.class, ForgeZLootTableLoad.class); + r.registerSubClass(ZVillagerTrades.class, ForgeZVillagerTrades.class); + r.registerSubClass(ZWandererTrades.class, ForgeZWandererTrades.class); + r.registerSubClass(ZFurnaceFuelBurnTime.class, ForgeZFurnaceFuelBurnTime.class); + r.registerSubClass(ZGatherAdditionalFlags.class, ForgeZGatherAdditionalFlags.class); + r.registerSubClass(ZServerTick.Start.class, ForgeZServerTick.Start.class); + r.registerSubClass(ZServerTick.End.class, ForgeZServerTick.End.class); + r.registerSubClass(ZAddReloadListener.class, ForgeZAddReloadListener.class); + r.registerSubClass(ZGatherAdvancementModifiers.class, ForgeZGatherAdvancementModifiers.class); + r.registerSubClass(ZGatherHints.class, ForgeZGatherHints.class); + r.registerSubClass(ZSleepingLocationCheck.class, ForgeZSleepingLocationCheck.class); + r.registerSubClass(ZAnimalTame.class, ForgeZAnimalTame.class); + r.registerSubClass(ZLevelTick.End.class, ForgeZLevelTick.End.class); + r.registerSubClass(ZLevelTick.Start.class, ForgeZLevelTick.Start.class); + + + + //this is ugly. generic events here + r.registerSubClassWithGeneric(ZAttachCapabilities.BlockEntityCaps.class, + ForgeZAttachCapabilities.BlockEntityCaps.class, + (Function, ForgeZAttachCapabilities.BlockEntityCaps>) inner -> + new ForgeZAttachCapabilities.BlockEntityCaps(ForgeCapabilityManager.INSTANCE, inner), + BlockEntity.class); + r.registerSubClassWithGeneric(ZAttachCapabilities.ItemStackCaps.class, + ForgeZAttachCapabilities.ItemStackCaps.class, + (Function, ForgeZAttachCapabilities.ItemStackCaps>) inner -> + new ForgeZAttachCapabilities.ItemStackCaps(ForgeCapabilityManager.INSTANCE, inner), + ItemStack.class); + r.registerSubClassWithGeneric(ZAttachCapabilities.LevelCaps.class, + ForgeZAttachCapabilities.LevelCaps.class, + (Function, ForgeZAttachCapabilities.LevelCaps>) inner -> + new ForgeZAttachCapabilities.LevelCaps(ForgeCapabilityManager.INSTANCE, inner), + Level.class); + + // zeta specific ones + + r.registerSubClass(ZRecipeCrawl.Digest.class, ForgeZRecipeCrawl.Digest.class); + r.registerSubClass(ZRecipeCrawl.Reset.class, ForgeZRecipeCrawl.Reset.class); + r.registerSubClass(ZRecipeCrawl.Starting.class, ForgeZRecipeCrawl.Starting.class); + r.registerSubClass(ZRecipeCrawl.Visit.Cooking.class, ForgeZRecipeCrawl.Visit.Cooking.class); + r.registerSubClass(ZRecipeCrawl.Visit.Custom.class, ForgeZRecipeCrawl.Visit.Custom.class); + r.registerSubClass(ZRecipeCrawl.Visit.Misc.class, ForgeZRecipeCrawl.Visit.Misc.class); + r.registerSubClass(ZRecipeCrawl.Visit.Shaped.class, ForgeZRecipeCrawl.Visit.Shaped.class); + r.registerSubClass(ZRecipeCrawl.Visit.Shapeless.class, ForgeZRecipeCrawl.Visit.Shapeless.class); + + + //Hmm client events here? maybe i should move them + if(FMLEnvironment.dist == Dist.DEDICATED_SERVER) return; + + r.registerSubClass(ZClientTick.End.class, ForgeZClientTick.End.class); + r.registerSubClass(ZClientTick.Start.class, ForgeZClientTick.Start.class); + r.registerSubClass(ZEarlyRender.class, ForgeZEarlyRender.class); + r.registerSubClass(ZGatherTooltipComponents.class, ForgeZGatherTooltipComponents.class); + r.registerSubClass(ZHighlightBlock.class, ForgeZHighlightBlock.class); + r.registerSubClass(ZInput.MouseButton.class, ForgeZInput.MouseButton.class); + r.registerSubClass(ZInput.Key.class, ForgeZInput.Key.class); + r.registerSubClass(ZInputUpdate.class, ForgeZInputUpdate.class); + r.registerSubClass(ZRenderContainerScreen.Background.class, ForgeZRenderContainerScreen.Background.class); + r.registerSubClass(ZRenderContainerScreen.Foreground.class, ForgeZRenderContainerScreen.Foreground.class); + r.registerSubClass(ZRenderLiving.PostLowest.class, ForgeZRenderLiving.PostLowest.class); + r.registerSubClass(ZRenderLiving.PreHighest.class, ForgeZRenderLiving.PreHighest.class); + r.registerSubClass(ZRenderPlayer.Post.class, ForgeZRenderPlayer.Post.class); + r.registerSubClass(ZRenderPlayer.Pre.class, ForgeZRenderPlayer.Pre.class); + r.registerSubClass(ZRenderTick.class, ForgeZRenderTick.class); + r.registerSubClass(ZRenderTooltip.GatherComponents.class, ForgeZRenderTooltip.GatherComponents.class); + r.registerSubClass(ZRenderTooltip.GatherComponents.Low.class, ForgeZRenderTooltip.GatherComponents.Low.class); + r.registerSubClass(ZScreen.Opening.class, ForgeZScreen.Opening.class); + r.registerSubClass(ZScreen.CharacterTyped.Pre.class, ForgeZScreen.CharacterTyped.Pre.class); + r.registerSubClass(ZScreen.CharacterTyped.Post.class, ForgeZScreen.CharacterTyped.Post.class); + r.registerSubClass(ZScreen.Init.Post.class, ForgeZScreen.Init.Post.class); + r.registerSubClass(ZScreen.Init.Pre.class, ForgeZScreen.Init.Pre.class); + r.registerSubClass(ZScreen.KeyPressed.Post.class, ForgeZScreen.KeyPressed.Post.class); + r.registerSubClass(ZScreen.KeyPressed.Pre.class, ForgeZScreen.KeyPressed.Pre.class); + r.registerSubClass(ZScreen.MouseScrolled.Post.class, ForgeZScreen.MouseScrolled.Post.class); + r.registerSubClass(ZScreen.MouseScrolled.Pre.class, ForgeZScreen.MouseScrolled.Pre.class); + r.registerSubClass(ZScreen.MouseButtonPressed.Post.class, ForgeZScreen.MouseButtonPressed.Post.class); + r.registerSubClass(ZScreen.MouseButtonPressed.Pre.class, ForgeZScreen.MouseButtonPressed.Pre.class); + r.registerSubClass(ZScreen.Render.Post.class, ForgeZScreen.Render.Post.class); + r.registerSubClass(ZScreen.Render.Pre.class, ForgeZScreen.Render.Pre.class); + r.registerSubClass(ZRenderGuiOverlay.ArmorLevel.Pre.class, ForgeZRenderGuiOverlay.ArmorLevel.Pre.class); + r.registerSubClass(ZRenderGuiOverlay.ArmorLevel.Post.class, ForgeZRenderGuiOverlay.ArmorLevel.Post.class); + r.registerSubClass(ZRenderGuiOverlay.Crosshair.Post.class, ForgeZRenderGuiOverlay.Crosshair.Post.class); + r.registerSubClass(ZRenderGuiOverlay.Crosshair.Pre.class, ForgeZRenderGuiOverlay.Crosshair.Pre.class); + r.registerSubClass(ZRenderGuiOverlay.DebugText.Pre.class, ForgeZRenderGuiOverlay.DebugText.Pre.class); + r.registerSubClass(ZRenderGuiOverlay.DebugText.Post.class, ForgeZRenderGuiOverlay.DebugText.Post.class); + r.registerSubClass(ZRenderGuiOverlay.Hotbar.Pre.class, ForgeZRenderGuiOverlay.Hotbar.Pre.class); + r.registerSubClass(ZRenderGuiOverlay.Hotbar.Post.class, ForgeZRenderGuiOverlay.Hotbar.Post.class); + r.registerSubClass(ZRenderGuiOverlay.PlayerHealth.Pre.class, ForgeZRenderGuiOverlay.PlayerHealth.Pre.class); + r.registerSubClass(ZRenderGuiOverlay.PlayerHealth.Post.class, ForgeZRenderGuiOverlay.PlayerHealth.Post.class); + r.registerSubClass(ZRenderGuiOverlay.PotionIcons.Pre.class, ForgeZRenderGuiOverlay.PotionIcons.Pre.class); + r.registerSubClass(ZRenderGuiOverlay.PotionIcons.Post.class, ForgeZRenderGuiOverlay.PotionIcons.Post.class); + r.registerSubClass(ZRenderGuiOverlay.ChatPanel.Pre.class, ForgeZRenderGuiOverlay.ChatPanel.Pre.class); + r.registerSubClass(ZRenderGuiOverlay.ChatPanel.Post.class, ForgeZRenderGuiOverlay.ChatPanel.Post.class); + r.registerSubClass(ZScreenshot.class, ForgeZScreenshot.class); + + }); + + +} diff --git a/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModCommonProxy.java b/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModCommonProxy.java index 297b02c..c77f491 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModCommonProxy.java +++ b/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModCommonProxy.java @@ -1,19 +1,47 @@ package org.violetmoon.zetaimplforge.mod; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraftforge.client.event.RegisterColorHandlersEvent; import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.common.capabilities.CapabilityManager; +import net.minecraftforge.event.AttachCapabilitiesEvent; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import org.violetmoon.zeta.Zeta; +import org.violetmoon.zeta.capability.ZetaCapabilityManager; +import org.violetmoon.zeta.client.event.load.*; +import org.violetmoon.zeta.client.event.play.*; import org.violetmoon.zeta.config.SyncedFlagHandler; import org.violetmoon.zeta.config.ZetaGeneralConfig; +import org.violetmoon.zeta.event.load.*; +import org.violetmoon.zeta.event.play.*; +import org.violetmoon.zeta.event.play.entity.*; +import org.violetmoon.zeta.event.play.entity.living.*; +import org.violetmoon.zeta.event.play.entity.player.*; +import org.violetmoon.zeta.event.play.loading.*; import org.violetmoon.zeta.util.handler.RecipeCrawlHandler; import org.violetmoon.zeta.util.handler.ToolInteractionHandler; import org.violetmoon.zeta.world.EntitySpawnHandler; import org.violetmoon.zeta.world.WorldGenHandler; +import org.violetmoon.zetaimplforge.api.ForgeZGatherAdvancementModifiers; +import org.violetmoon.zetaimplforge.capability.ForgeCapabilityManager; +import org.violetmoon.zetaimplforge.client.event.load.*; +import org.violetmoon.zetaimplforge.client.event.play.*; import org.violetmoon.zetaimplforge.config.ConfigEventDispatcher; +import org.violetmoon.zetaimplforge.event.ForgeEventsRemapper; +import org.violetmoon.zetaimplforge.event.load.*; +import org.violetmoon.zetaimplforge.event.play.*; +import org.violetmoon.zetaimplforge.event.play.entity.*; +import org.violetmoon.zetaimplforge.event.play.entity.living.*; +import org.violetmoon.zetaimplforge.event.play.entity.player.*; +import org.violetmoon.zetaimplforge.event.play.loading.*; import org.violetmoon.zetaimplforge.world.ZetaBiomeModifier; +import java.util.function.Function; + public class ZetaModCommonProxy { public ZetaModCommonProxy(Zeta zeta) { @@ -35,10 +63,13 @@ public ZetaModCommonProxy(Zeta zeta) { MinecraftForge.EVENT_BUS.register(ToolInteractionHandler.class); ZetaBiomeModifier.registerBiomeModifier(FMLJavaModLoadingContext.get().getModEventBus()); + } + public void setup(FMLCommonSetupEvent event) { event.enqueueWork(ConfigEventDispatcher::dispatchAllInitialLoads); } - + + } diff --git a/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModForge.java b/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModForge.java index 64d1c7c..b4c5824 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModForge.java +++ b/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModForge.java @@ -1,22 +1,19 @@ package org.violetmoon.zetaimplforge.mod; -import org.apache.logging.log4j.LogManager; -import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.mod.ZetaMod; import org.violetmoon.zetaimplforge.ForgeZeta; import net.minecraftforge.fml.DistExecutor; import net.minecraftforge.fml.common.Mod; -@Mod("zeta") -public class ZetaModForge { +@Mod(ZetaMod.ZETA_ID) +public class ZetaModForge extends ZetaMod{ public ZetaModForge() { - ForgeZeta zeta = new ForgeZeta(Zeta.ZETA_ID, LogManager.getLogger(Zeta.ZETA_ID + "-internal")); - ZetaMod.start(zeta); + super(new ForgeZeta(ZetaMod.ZETA_ID, ZetaMod.LOGGER)); // creates 2 dist specific objects that will handle zeta specific & loader specific events needed for zeta to work - DistExecutor.runForDist(() -> () -> new ZetaModClientProxy(zeta), () -> () -> new ZetaModCommonProxy(zeta)); + DistExecutor.runForDist(() -> () -> new ZetaModClientProxy(ZetaMod.ZETA), () -> () -> new ZetaModCommonProxy(ZetaMod.ZETA)); } diff --git a/src/main/java/org/violetmoon/zetaimplforge/world/ZetaBiomeModifier.java b/src/main/java/org/violetmoon/zetaimplforge/world/ZetaBiomeModifier.java index 36b21e3..7b8b259 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/world/ZetaBiomeModifier.java +++ b/src/main/java/org/violetmoon/zetaimplforge/world/ZetaBiomeModifier.java @@ -3,6 +3,7 @@ import java.util.List; import org.violetmoon.zeta.Zeta; +import org.violetmoon.zeta.mod.ZetaMod; import org.violetmoon.zeta.util.zetalist.ZetaList; import org.violetmoon.zeta.world.WorldGenHandler; @@ -24,8 +25,8 @@ public class ZetaBiomeModifier implements BiomeModifier { - public static final ResourceLocation RESOURCE = new ResourceLocation(Zeta.ZETA_ID, "biome_modifier"); - private static final RegistryObject> SERIALIZER = RegistryObject.create(RESOURCE, ForgeRegistries.Keys.BIOME_MODIFIER_SERIALIZERS, Zeta.ZETA_ID); + public static final ResourceLocation RESOURCE = new ResourceLocation(ZetaMod.ZETA_ID, "biome_modifier"); + private static final RegistryObject> SERIALIZER = RegistryObject.create(RESOURCE, ForgeRegistries.Keys.BIOME_MODIFIER_SERIALIZERS, ZetaMod.ZETA_ID); @Override public void modify(Holder biome, Phase phase, BiomeInfo.Builder builder) { @@ -56,7 +57,7 @@ public static void modifyBiome(Holder biome, ModifiableBiomeInfo.BiomeInf } public static void registerBiomeModifier(IEventBus bus) { - DeferredRegister> biomeModifiers = DeferredRegister.create(ForgeRegistries.Keys.BIOME_MODIFIER_SERIALIZERS, Zeta.ZETA_ID); + DeferredRegister> biomeModifiers = DeferredRegister.create(ForgeRegistries.Keys.BIOME_MODIFIER_SERIALIZERS, ZetaMod.ZETA_ID); biomeModifiers.register(bus); biomeModifiers.register(ZetaBiomeModifier.RESOURCE.getPath(), ZetaBiomeModifier::makeCodec); } From 87f0e6be4c41809edb6a4fe4acc0b6067272cd46 Mon Sep 17 00:00:00 2001 From: MehVahdJukaar Date: Thu, 1 Aug 2024 01:25:19 +0200 Subject: [PATCH 16/22] added render tick phase classes --- .../violetmoon/zeta/client/ClientTicker.java | 71 +++++++------------ .../zeta/client/event/play/ZRenderTick.java | 7 +- .../client/event/play/ForgeZRenderTick.java | 30 ++++++-- .../event/ForgeEventsRemapper.java | 54 +++++++------- .../event/ForgeZetaEventBus.java | 14 ++-- 5 files changed, 89 insertions(+), 87 deletions(-) diff --git a/src/main/java/org/violetmoon/zeta/client/ClientTicker.java b/src/main/java/org/violetmoon/zeta/client/ClientTicker.java index fcb3817..2165dde 100644 --- a/src/main/java/org/violetmoon/zeta/client/ClientTicker.java +++ b/src/main/java/org/violetmoon/zeta/client/ClientTicker.java @@ -1,57 +1,38 @@ package org.violetmoon.zeta.client; +import net.minecraft.client.Minecraft; import org.jetbrains.annotations.ApiStatus; import org.violetmoon.zeta.client.event.play.ZClientTick; import org.violetmoon.zeta.client.event.play.ZRenderTick; import org.violetmoon.zeta.event.bus.PlayEvent; -import org.violetmoon.zeta.event.bus.ZPhase; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.screens.Screen; -import org.violetmoon.zeta.event.play.ZRecipeCrawl; //TODO: 1.21. replace with minecraft own ticker. Tbh this is legacy already and should be replaced with Minecraft.getPartialTicks() @Deprecated public final class ClientTicker { - //no need to have more than 1 instance of this class. Ticks are always the same - public static final ClientTicker INSTANCE = new ClientTicker(); - - private ClientTicker() { - } - - public int ticksInGame = 0; - public float partialTicks = 0; - public float delta = 0; - public float total = 0; - - @ApiStatus.Internal - @PlayEvent - public void onRenderTick(ZRenderTick event) { - if(event.isStartPhase()) - partialTicks = event.getRenderTickTime(); - else - endRenderTick(); - } - - @ApiStatus.Internal - @PlayEvent - public void onEndClientTick(ZClientTick.Start event) { - if(event.getPhase() != ZPhase.END) - return; - - Screen gui = Minecraft.getInstance().screen; - if(gui == null || !gui.isPauseScreen()) { - ticksInGame++; - partialTicks = 0; - } - - endRenderTick(); - } - - private void endRenderTick() { - float oldTotal = total; - total = ticksInGame + partialTicks; - delta = total - oldTotal; - } + //no need to have more than 1 instance of this class. Ticks are always the same + public static final ClientTicker INSTANCE = new ClientTicker(); + + private ClientTicker() { + } + + public float partialTicks = 0; + public float delta = 0; + + public int ticksInGame = 0; + + @ApiStatus.Internal + @PlayEvent + public void onRenderTick(ZRenderTick.Start event) { + partialTicks = Minecraft.getInstance().getPartialTick(); + delta = Minecraft.getInstance().getDeltaFrameTime(); + } + + @ApiStatus.Internal + @PlayEvent + public void onEndClientTick(ZClientTick.End event) { + if (!Minecraft.getInstance().isPaused()) { + ticksInGame++; + } + } } diff --git a/src/main/java/org/violetmoon/zeta/client/event/play/ZRenderTick.java b/src/main/java/org/violetmoon/zeta/client/event/play/ZRenderTick.java index 697bcaf..48d8a0b 100644 --- a/src/main/java/org/violetmoon/zeta/client/event/play/ZRenderTick.java +++ b/src/main/java/org/violetmoon/zeta/client/event/play/ZRenderTick.java @@ -10,9 +10,10 @@ */ public interface ZRenderTick extends IZetaPlayEvent { float getRenderTickTime(); - boolean isEndPhase(); - default boolean isStartPhase() { - return !isEndPhase(); + interface Start extends ZRenderTick { + } + + interface End extends ZRenderTick { } } diff --git a/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderTick.java b/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderTick.java index b79fa10..059d58d 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderTick.java +++ b/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderTick.java @@ -4,14 +4,30 @@ import net.minecraftforge.event.TickEvent; -public record ForgeZRenderTick(TickEvent.RenderTickEvent e) implements ZRenderTick { - @Override - public float getRenderTickTime() { - return e.renderTickTime; +import java.util.Objects; + +public class ForgeZRenderTick implements ZRenderTick { + private final TickEvent.RenderTickEvent e; + + public ForgeZRenderTick(TickEvent.RenderTickEvent e) { + this.e = e; + } + + @Override + public float getRenderTickTime() { + return e.renderTickTime; + } + + public static class Start extends ForgeZRenderTick implements ZRenderTick.Start { + public Start(TickEvent.RenderTickEvent e) { + super(e); + } } - @Override - public boolean isEndPhase() { - return e.phase == TickEvent.Phase.END; + public static class End extends ForgeZRenderTick implements ZRenderTick.End { + public End(TickEvent.RenderTickEvent e) { + super(e); + } } + } diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/ForgeEventsRemapper.java b/src/main/java/org/violetmoon/zetaimplforge/event/ForgeEventsRemapper.java index 92b28c3..b7b127c 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/ForgeEventsRemapper.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/ForgeEventsRemapper.java @@ -9,10 +9,6 @@ import org.apache.commons.lang3.text.WordUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.violetmoon.zeta.event.bus.IZetaLoadEvent; -import org.violetmoon.zeta.event.bus.IZetaPlayEvent; -import org.violetmoon.zeta.event.load.ZCommonSetup; -import org.violetmoon.zetaimplforge.event.load.ForgeZCommonSetup; import java.lang.invoke.MethodHandle; import java.lang.reflect.Constructor; @@ -23,6 +19,7 @@ import java.util.function.Function; import java.util.function.Predicate; +//@SuppressWarnings({"unchecked","rawtypes"}) public class ForgeEventsRemapper { private final Class forgeEventRoot; @@ -49,7 +46,7 @@ public ForgeEventsRemapper(Class zetaEventRoot, Class forgeEventRoot) { /** * Given an event object which is NOT a subtype of Event class, remap it to a forge event */ - protected F remapEvent(@NotNull Z2 zetaEvent, Class firedAs) { + protected F remapEvent(@NotNull Z2 zetaEvent, Class firedAs) { Function zetaToForgeFunc = zetaToForgeMap.get(firedAs); if (zetaToForgeFunc == null) { // remap is null. no checks because micro optimization. It means it must be a forge event already @@ -63,7 +60,7 @@ protected F remapEvent(@NotNull Z2 zetaEvent, Class firedAs) /** * Given a MethodHandle of a method which takes a Zeta event, remaps it to a method which takes a Forge event, so we can register it with Forge event bus */ - protected Consumer remapMethod(MethodHandle originalEventConsumer, Class zetaEventBaseClass) { + protected Consumer remapMethod(MethodHandle originalEventConsumer, Class zetaEventBaseClass, Class forgeEventClass) { Function forgeToZetaFunc = forgeToZetaMap.get(zetaEventBaseClass); if (forgeToZetaFunc == null) { // no remap needed @@ -78,7 +75,7 @@ protected Consumer remapMethod(MethodHandle originalEventConsumer, } else throw new RuntimeException("Could not convert Zeta event class " + zetaEventBaseClass + " to Forge event. You must register its subclass using registerSubclass."); } - return createForgeConsumer(originalEventConsumer, forgeToZetaFunc, zetaEventBaseClass); + return createForgeConsumer(originalEventConsumer, forgeToZetaFunc, zetaEventBaseClass, forgeEventClass); } @@ -90,13 +87,15 @@ private F createForgeEvent(@NotNull Z event, Function Consumer createForgeConsumer( - MethodHandle zetaEventConsumer, Function forgeToZetaFunc, Class zetaEventBaseClass) { + MethodHandle zetaEventConsumer, Function forgeToZetaFunc, Class zetaEventBaseClass, Class forgeEventClass) { //hack for tick events - Phase phase = Phase.guessFromClassName(zetaEventBaseClass); + Phase phase = Phase.guessFromClassName(zetaEventBaseClass, forgeEventClass); + return event -> { try { //luckily this phase madness will go away with new neoforge - if (phase != Phase.NONE && event instanceof TickEvent te) { + if (phase != Phase.NONE) { + TickEvent te = (TickEvent) event; if (phase == Phase.START && te.phase != TickEvent.Phase.START) return; if (phase == Phase.END && te.phase != TickEvent.Phase.END) return; } @@ -108,12 +107,12 @@ private Consumer createForgeConsumer( } // for generic events - public void registerSubClassWithGeneric(Class baseZetaEventClass, Class forgeZetaEventClass, Class genericClass) { + public void registerSubClassWithGeneric(Class baseZetaEventClass, Class forgeZetaEventClass, Class genericClass) { registerSubClass(baseZetaEventClass, forgeZetaEventClass); generics.put(baseZetaEventClass, genericClass); } - public void registerSubClass(Class baseZetaEventClass, Class forgeZetaEventClass) { + public void registerSubClass(Class baseZetaEventClass, Class forgeZetaEventClass) { registerSubClass(baseZetaEventClass, forgeZetaEventClass, null); } @@ -130,10 +129,6 @@ public void registerSubClass(Class baseZetaEven Object old2 = null; boolean isNoWrapper = false; - if ((Class) forgeZetaEventClass == ForgeZCommonSetup.class) { - int aa = 1; - } - if (constructor == null) { // if it's an Event already just returns the no argument constructor. Provided it subclasses its abstract impl if (forgeEventRoot.isAssignableFrom(forgeZetaEventClass)) { @@ -309,25 +304,36 @@ public static Field findFieldInClassHierarchy(Class clazz, Predicate p //TODO: refactor in 1.21 using interfaces and stuff. This is just here for now as i want to keep binary compatibility - protected void registerListenerToForgeWithPriorityAndGenerics(IEventBus bus, Class owningClazz, Consumer consumer, Class zetaEventClass) { + protected void registerListenerToForgeWithPriorityAndGenerics( + IEventBus bus, Class owningClazz, Consumer consumer, Class zetaEventClass, Class forgeEventClass) { EventPriority priority = guessPriorityFromClassName(owningClazz); Class gen = generics.get(zetaEventClass); - Class eventType = zetaToForgeEventClassHack.get(zetaEventClass); - if (eventType == null) { + if (forgeEventClass == null) { throw new RuntimeException("No event type found for " + zetaEventClass); } if (gen != null) { - bus.addGenericListener(gen, priority, false, eventType, (Consumer) consumer); + bus.addGenericListener(gen, priority, false, forgeEventClass, (Consumer) (Object) consumer); } else { - bus.addListener(priority, false, eventType, consumer); + bus.addListener(priority, false, forgeEventClass, consumer); } } + public Object remapAndRegister(IEventBus forgeBus, Class owningClazz, MethodHandle handle, Class zetaEventClass) { + Class forgeEventClass = zetaToForgeEventClassHack.get(zetaEventClass); + + Consumer consumer = this.remapMethod(handle, zetaEventClass, forgeEventClass); + + registerListenerToForgeWithPriorityAndGenerics(forgeBus, owningClazz, consumer, zetaEventClass, forgeEventClass); + + return consumer; + } + private enum Phase { NONE, START, END; - private static Phase guessFromClassName(Class zetaEventClass) { + private static Phase guessFromClassName(Class zetaEventClass, Class forgeClass) { + if (forgeClass.isAssignableFrom(TickEvent.class)) return NONE; String simpleName = zetaEventClass.getSimpleName(); if (simpleName.equals("Start")) { return START; @@ -355,8 +361,8 @@ private static EventPriority guessPriorityFromClassName(Class zetaEventClass) }); } - public ForgeEventsRemapper makeCopy() { - ForgeEventsRemapper copy = new ForgeEventsRemapper<>(zetaEventRoot, forgeEventRoot); + public ForgeEventsRemapper makeCopy() { + ForgeEventsRemapper copy = new ForgeEventsRemapper<>(zetaEventRoot, forgeEventRoot); copy.forgeToZetaMap.putAll(forgeToZetaMap); copy.zetaToForgeMap.putAll(zetaToForgeMap); copy.generics.putAll(generics); diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/ForgeZetaEventBus.java b/src/main/java/org/violetmoon/zetaimplforge/event/ForgeZetaEventBus.java index 2e221f6..d6ff82a 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/ForgeZetaEventBus.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/ForgeZetaEventBus.java @@ -41,7 +41,6 @@ import java.lang.invoke.MethodHandles; import java.lang.reflect.Method; import java.util.Map; -import java.util.function.Consumer; import java.util.function.Function; // this is super jank. Basically converts all zeta events to forge ones, then delegates to the forge bus directly @@ -104,10 +103,9 @@ protected void subscribeMethod(Method method, Object receiver, Class owningCl if (receiver != null) handle = handle.bindTo(receiver); - Consumer consumer = remapper.remapMethod(handle, zetaEventClass); - remapper.registerListenerToForgeWithPriorityAndGenerics(forgeBus, owningClazz, consumer, zetaEventClass); + var converted = remapper.remapAndRegister(forgeBus, owningClazz, handle, zetaEventClass); //store here so we can unregister later - convertedHandlers.put(new Key(method, receiver, owningClazz), consumer); + convertedHandlers.put(new Key(method, receiver, owningClazz), converted); } @Override @@ -177,7 +175,7 @@ public void registerSubClass(Class baseZetaEven r.registerSubClass(ZLoadComplete.class, ForgeZLoadComplete.class); // client ones again? - if(FMLEnvironment.dist == Dist.DEDICATED_SERVER) return; + if (FMLEnvironment.dist == Dist.DEDICATED_SERVER) return; r.registerSubClass(ZAddModels.class, ForgeZAddModels.class); r.registerSubClass(ZAddModelLayers.class, ForgeZAddModelLayers.class); @@ -261,7 +259,6 @@ public void registerSubClass(Class baseZetaEven r.registerSubClass(ZLevelTick.Start.class, ForgeZLevelTick.Start.class); - //this is ugly. generic events here r.registerSubClassWithGeneric(ZAttachCapabilities.BlockEntityCaps.class, ForgeZAttachCapabilities.BlockEntityCaps.class, @@ -292,7 +289,7 @@ public void registerSubClass(Class baseZetaEven //Hmm client events here? maybe i should move them - if(FMLEnvironment.dist == Dist.DEDICATED_SERVER) return; + if (FMLEnvironment.dist == Dist.DEDICATED_SERVER) return; r.registerSubClass(ZClientTick.End.class, ForgeZClientTick.End.class); r.registerSubClass(ZClientTick.Start.class, ForgeZClientTick.Start.class); @@ -308,7 +305,8 @@ public void registerSubClass(Class baseZetaEven r.registerSubClass(ZRenderLiving.PreHighest.class, ForgeZRenderLiving.PreHighest.class); r.registerSubClass(ZRenderPlayer.Post.class, ForgeZRenderPlayer.Post.class); r.registerSubClass(ZRenderPlayer.Pre.class, ForgeZRenderPlayer.Pre.class); - r.registerSubClass(ZRenderTick.class, ForgeZRenderTick.class); + r.registerSubClass(ZRenderTick.End.class, ForgeZRenderTick.End.class); + r.registerSubClass(ZRenderTick.Start.class, ForgeZRenderTick.Start.class); r.registerSubClass(ZRenderTooltip.GatherComponents.class, ForgeZRenderTooltip.GatherComponents.class); r.registerSubClass(ZRenderTooltip.GatherComponents.Low.class, ForgeZRenderTooltip.GatherComponents.Low.class); r.registerSubClass(ZScreen.Opening.class, ForgeZScreen.Opening.class); From 8075d2cdba9e46363792546f4fe9ddf6a18d8ef7 Mon Sep 17 00:00:00 2001 From: MehVahdJukaar Date: Thu, 1 Aug 2024 01:54:54 +0200 Subject: [PATCH 17/22] client ticker refactor --- build.properties | 2 +- src/main/java/org/violetmoon/zeta/client/ClientTicker.java | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/build.properties b/build.properties index 4a63212..b56c513 100644 --- a/build.properties +++ b/build.properties @@ -5,5 +5,5 @@ mod_name=Zeta mc_version=1.20.1 mapping_channel=official mod_id=zeta -build_number=20-event21 +build_number=20-event23 dir_output=../Build Output/Zeta/ diff --git a/src/main/java/org/violetmoon/zeta/client/ClientTicker.java b/src/main/java/org/violetmoon/zeta/client/ClientTicker.java index 2165dde..020f277 100644 --- a/src/main/java/org/violetmoon/zeta/client/ClientTicker.java +++ b/src/main/java/org/violetmoon/zeta/client/ClientTicker.java @@ -18,6 +18,7 @@ private ClientTicker() { public float partialTicks = 0; public float delta = 0; + public float total = 0; public int ticksInGame = 0; @@ -26,6 +27,7 @@ private ClientTicker() { public void onRenderTick(ZRenderTick.Start event) { partialTicks = Minecraft.getInstance().getPartialTick(); delta = Minecraft.getInstance().getDeltaFrameTime(); + total = ticksInGame + partialTicks; } @ApiStatus.Internal From 398dc1b68a0f73aaf679bf50c6e5502031e9f588 Mon Sep 17 00:00:00 2001 From: MehVahdJukaar Date: Thu, 1 Aug 2024 02:03:04 +0200 Subject: [PATCH 18/22] adv modifiers back to load bus. Idk why this was moved --- .../zeta/advancement/AdvancementModifierRegistry.java | 2 +- .../zeta/event/load/ZGatherAdvancementModifiers.java | 2 +- .../zetaimplforge/api/ForgeZGatherAdvancementModifiers.java | 3 ++- .../org/violetmoon/zetaimplforge/event/ForgeZetaEventBus.java | 4 +++- 4 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/violetmoon/zeta/advancement/AdvancementModifierRegistry.java b/src/main/java/org/violetmoon/zeta/advancement/AdvancementModifierRegistry.java index 8284839..4c4df9f 100644 --- a/src/main/java/org/violetmoon/zeta/advancement/AdvancementModifierRegistry.java +++ b/src/main/java/org/violetmoon/zeta/advancement/AdvancementModifierRegistry.java @@ -68,7 +68,7 @@ public void addModifier(IAdvancementModifier mod) { public void addListeners(ZAddReloadListener event) { if(!gatheredAddons) { IAdvancementModifierDelegate delegateImpl = new DelegateImpl(); - zeta.playBus.fire(new ZGatherAdvancementModifiers() { + zeta.loadBus.fire(new ZGatherAdvancementModifiers() { @Override public void register(IAdvancementModifier modifier) { addModifier(modifier); diff --git a/src/main/java/org/violetmoon/zeta/event/load/ZGatherAdvancementModifiers.java b/src/main/java/org/violetmoon/zeta/event/load/ZGatherAdvancementModifiers.java index aae4537..51b4d56 100644 --- a/src/main/java/org/violetmoon/zeta/event/load/ZGatherAdvancementModifiers.java +++ b/src/main/java/org/violetmoon/zeta/event/load/ZGatherAdvancementModifiers.java @@ -16,7 +16,7 @@ import net.minecraft.world.level.block.Block; import org.violetmoon.zeta.event.bus.IZetaPlayEvent; -public interface ZGatherAdvancementModifiers extends IZetaPlayEvent { +public interface ZGatherAdvancementModifiers extends IZetaLoadEvent { void register(IAdvancementModifier modifier); IAdvancementModifierDelegate getDelegate(); diff --git a/src/main/java/org/violetmoon/zetaimplforge/api/ForgeZGatherAdvancementModifiers.java b/src/main/java/org/violetmoon/zetaimplforge/api/ForgeZGatherAdvancementModifiers.java index 3c27bff..fc827ac 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/api/ForgeZGatherAdvancementModifiers.java +++ b/src/main/java/org/violetmoon/zetaimplforge/api/ForgeZGatherAdvancementModifiers.java @@ -1,5 +1,6 @@ package org.violetmoon.zetaimplforge.api; +import net.minecraftforge.fml.event.IModBusEvent; import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.api.IAdvancementModifier; import org.violetmoon.zeta.api.IAdvancementModifierDelegate; @@ -7,7 +8,7 @@ import net.minecraftforge.eventbus.api.Event; -public class ForgeZGatherAdvancementModifiers extends Event implements ZGatherAdvancementModifiers { +public class ForgeZGatherAdvancementModifiers extends Event implements ZGatherAdvancementModifiers, IModBusEvent { private final ZGatherAdvancementModifiers wrapped; public ForgeZGatherAdvancementModifiers(ZGatherAdvancementModifiers inner) { diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/ForgeZetaEventBus.java b/src/main/java/org/violetmoon/zetaimplforge/event/ForgeZetaEventBus.java index d6ff82a..a0b62a9 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/ForgeZetaEventBus.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/ForgeZetaEventBus.java @@ -174,6 +174,9 @@ public void registerSubClass(Class baseZetaEven r.registerSubClass(ZConfigChanged.class, ForgeZConfigChange.class); r.registerSubClass(ZLoadComplete.class, ForgeZLoadComplete.class); + //zeta own + r.registerSubClass(ZGatherAdvancementModifiers.class, ForgeZGatherAdvancementModifiers.class); + // client ones again? if (FMLEnvironment.dist == Dist.DEDICATED_SERVER) return; @@ -251,7 +254,6 @@ public void registerSubClass(Class baseZetaEven r.registerSubClass(ZServerTick.Start.class, ForgeZServerTick.Start.class); r.registerSubClass(ZServerTick.End.class, ForgeZServerTick.End.class); r.registerSubClass(ZAddReloadListener.class, ForgeZAddReloadListener.class); - r.registerSubClass(ZGatherAdvancementModifiers.class, ForgeZGatherAdvancementModifiers.class); r.registerSubClass(ZGatherHints.class, ForgeZGatherHints.class); r.registerSubClass(ZSleepingLocationCheck.class, ForgeZSleepingLocationCheck.class); r.registerSubClass(ZAnimalTame.class, ForgeZAnimalTame.class); From 1c078bd53284deaefdacb786a25f02f07b6bd606 Mon Sep 17 00:00:00 2001 From: MehVahdJukaar Date: Sat, 3 Aug 2024 21:50:14 +0200 Subject: [PATCH 19/22] no more nested render hud events --- build.properties | 2 +- .../play/loading/ZGatherAdditionalFlags.java | 3 - .../client/event/play/ForgeZClientTick.java | 2 +- .../event/play/ForgeZRenderGuiOverlay.java | 4 +- .../client/event/play/ForgeZRenderLiving.java | 2 +- .../client/event/play/ForgeZRenderPlayer.java | 7 +- .../client/event/play/ForgeZRenderTick.java | 2 +- .../client/event/play/ForgeZScreen.java | 4 +- .../event/ForgeEventsRemapper.java | 105 ++++- .../event/ForgeZetaEventBus.java | 366 ++++++++++-------- .../load/ForgeZEntityAttributeCreation.java | 7 +- .../event/play/ForgeZItemTooltip.java | 7 +- .../event/play/ForgeZLevelTick.java | 2 +- .../event/play/ForgeZServerTick.java | 2 +- .../play/entity/ForgeZEntityInteract.java | 8 +- .../entity/living/ForgeZBabyEntitySpawn.java | 18 +- .../living/ForgeZLivingChangeTarget.java | 7 +- .../play/entity/living/ForgeZLivingDrops.java | 2 +- .../entity/living/ForgeZMobSpawnEvent.java | 4 +- .../play/entity/player/ForgeZPlayerTick.java | 2 +- .../zetaimplforge/mod/ZetaModClientProxy.java | 77 +--- 21 files changed, 346 insertions(+), 287 deletions(-) diff --git a/build.properties b/build.properties index b56c513..dc36927 100644 --- a/build.properties +++ b/build.properties @@ -5,5 +5,5 @@ mod_name=Zeta mc_version=1.20.1 mapping_channel=official mod_id=zeta -build_number=20-event23 +build_number=20-event27 dir_output=../Build Output/Zeta/ diff --git a/src/main/java/org/violetmoon/zeta/event/play/loading/ZGatherAdditionalFlags.java b/src/main/java/org/violetmoon/zeta/event/play/loading/ZGatherAdditionalFlags.java index 7e65d48..a1b60ce 100644 --- a/src/main/java/org/violetmoon/zeta/event/play/loading/ZGatherAdditionalFlags.java +++ b/src/main/java/org/violetmoon/zeta/event/play/loading/ZGatherAdditionalFlags.java @@ -1,11 +1,8 @@ package org.violetmoon.zeta.event.play.loading; -import net.minecraftforge.eventbus.api.Event; import org.violetmoon.zeta.config.ConfigFlagManager; import org.violetmoon.zeta.event.bus.IZetaPlayEvent; -import java.util.Objects; - public interface ZGatherAdditionalFlags extends IZetaPlayEvent { ConfigFlagManager flagManager(); diff --git a/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZClientTick.java b/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZClientTick.java index 60b5b5c..a950ad9 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZClientTick.java +++ b/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZClientTick.java @@ -5,7 +5,7 @@ import net.minecraftforge.event.TickEvent.ClientTickEvent; public class ForgeZClientTick implements ZClientTick { - private final ClientTickEvent e; + public final ClientTickEvent e; public ForgeZClientTick(ClientTickEvent e) { this.e = e; diff --git a/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderGuiOverlay.java b/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderGuiOverlay.java index 2679201..6843279 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderGuiOverlay.java +++ b/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderGuiOverlay.java @@ -10,8 +10,8 @@ import net.minecraftforge.client.event.RenderGuiOverlayEvent; import net.minecraftforge.client.gui.overlay.ForgeGui; -public class ForgeZRenderGuiOverlay extends Event implements ZRenderGuiOverlay { - private final RenderGuiOverlayEvent e; +public class ForgeZRenderGuiOverlay implements ZRenderGuiOverlay { + public final RenderGuiOverlayEvent e; public ForgeZRenderGuiOverlay(RenderGuiOverlayEvent e) { this.e = e; diff --git a/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderLiving.java b/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderLiving.java index 23b6fd3..385a837 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderLiving.java +++ b/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderLiving.java @@ -8,7 +8,7 @@ import net.minecraftforge.client.event.RenderLivingEvent; public abstract class ForgeZRenderLiving implements ZRenderLiving { - protected final RenderLivingEvent e; + public final RenderLivingEvent e; public ForgeZRenderLiving(RenderLivingEvent e) { this.e = e; diff --git a/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderPlayer.java b/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderPlayer.java index 76019e1..2988bc1 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderPlayer.java +++ b/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderPlayer.java @@ -8,9 +8,10 @@ import net.minecraft.client.renderer.entity.player.PlayerRenderer; import net.minecraft.world.entity.player.Player; import net.minecraftforge.client.event.RenderPlayerEvent; +import org.violetmoon.zeta.event.bus.IZetaPlayEvent; public abstract class ForgeZRenderPlayer implements ZRenderPlayer { - private final RenderPlayerEvent e; + public final RenderPlayerEvent e; public ForgeZRenderPlayer(RenderPlayerEvent e) { this.e = e; @@ -35,12 +36,14 @@ public ForgeZRenderPlayer(RenderPlayerEvent e) { public Player getEntity() {return e.getEntity();} public static class Pre extends ForgeZRenderPlayer implements ZRenderPlayer.Pre { + public Pre(RenderPlayerEvent.Pre e) { super(e); } } - public static class Post extends ForgeZRenderPlayer implements ZRenderPlayer.Post { + public static class Post extends ForgeZRenderPlayer implements ZRenderPlayer.Post, IZetaPlayEvent { + public Post(RenderPlayerEvent.Post e) { super(e); } diff --git a/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderTick.java b/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderTick.java index 059d58d..d8611d3 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderTick.java +++ b/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZRenderTick.java @@ -7,7 +7,7 @@ import java.util.Objects; public class ForgeZRenderTick implements ZRenderTick { - private final TickEvent.RenderTickEvent e; + public final TickEvent.RenderTickEvent e; public ForgeZRenderTick(TickEvent.RenderTickEvent e) { this.e = e; diff --git a/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZScreen.java b/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZScreen.java index 2348f3e..be632e2 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZScreen.java +++ b/src/main/java/org/violetmoon/zetaimplforge/client/event/play/ForgeZScreen.java @@ -10,7 +10,7 @@ import net.minecraftforge.client.event.ScreenEvent; public class ForgeZScreen implements ZScreen { - private final ScreenEvent e; + public final ScreenEvent e; public ForgeZScreen(ScreenEvent e) { this.e = e; @@ -58,7 +58,7 @@ public Post(ScreenEvent.Init.Post e) { } public static class Render extends ForgeZScreen implements ZScreen.Render { - private final ScreenEvent.Render e; + public final ScreenEvent.Render e; public Render(ScreenEvent.Render e) { super(e); diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/ForgeEventsRemapper.java b/src/main/java/org/violetmoon/zetaimplforge/event/ForgeEventsRemapper.java index b7b127c..ca4a939 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/ForgeEventsRemapper.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/ForgeEventsRemapper.java @@ -1,6 +1,8 @@ package org.violetmoon.zetaimplforge.event; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import net.minecraftforge.client.event.RenderGuiOverlayEvent; +import net.minecraftforge.client.gui.overlay.VanillaGuiOverlay; import net.minecraftforge.event.TickEvent; import net.minecraftforge.eventbus.api.Event; import net.minecraftforge.eventbus.api.EventPriority; @@ -88,17 +90,41 @@ private F createForgeEvent(@NotNull Z event, Function Consumer createForgeConsumer( MethodHandle zetaEventConsumer, Function forgeToZetaFunc, Class zetaEventBaseClass, Class forgeEventClass) { + + //special cases fo forge events that are to be sub divided into phases + + // for gui overlay event + VanillaGuiOverlay overlay = guessGuiOverlayFromClassName(zetaEventBaseClass, forgeEventClass.getSuperclass()); + if (overlay != null) { + //here we know that phase must not be null + return event -> { + try { + RenderGuiOverlayEvent rge = (RenderGuiOverlayEvent) event; + if (rge.getOverlay() != overlay.type()) return; + zetaEventConsumer.invoke(forgeToZetaFunc.apply(event)); + } catch (Throwable e) { + throw new RuntimeException(e); + } + }; + } + //hack for tick events Phase phase = Phase.guessFromClassName(zetaEventBaseClass, forgeEventClass); + if (phase != Phase.NONE) { + return event -> { + try { + //luckily this phase madness will go away with new neoforge + TickEvent te = (TickEvent) event; + if ((phase == Phase.START) ^ (te.phase == TickEvent.Phase.START)) return; + zetaEventConsumer.invoke(forgeToZetaFunc.apply(event)); + } catch (Throwable e) { + throw new RuntimeException(e); + } + }; + } return event -> { try { - //luckily this phase madness will go away with new neoforge - if (phase != Phase.NONE) { - TickEvent te = (TickEvent) event; - if (phase == Phase.START && te.phase != TickEvent.Phase.START) return; - if (phase == Phase.END && te.phase != TickEvent.Phase.END) return; - } zetaEventConsumer.invoke(forgeToZetaFunc.apply(event)); } catch (Throwable e) { throw new RuntimeException(e); @@ -107,24 +133,47 @@ private Consumer createForgeConsumer( } // for generic events - public void registerSubClassWithGeneric(Class baseZetaEventClass, Class forgeZetaEventClass, Class genericClass) { - registerSubClass(baseZetaEventClass, forgeZetaEventClass); + // auto register ones are deprecated. Register manually, its faster and requires no reflection hacks + @Deprecated + public void registerWrapperWithGeneric(Class baseZetaEventClass, Class forgeZetaEventClass, Class genericClass) { + registerWrapper(baseZetaEventClass, forgeZetaEventClass); generics.put(baseZetaEventClass, genericClass); } - public void registerSubClass(Class baseZetaEventClass, Class forgeZetaEventClass) { + @Deprecated + public void registerWrapper(Class baseZetaEventClass, Class forgeZetaEventClass) { + + registerWrapper(baseZetaEventClass, forgeZetaEventClass, null); + } + + @Deprecated + public void registerWrapperWithGeneric(Class baseZetaEventClass, Class forgeZetaEventClass, + Function constructor, Class genericClass) { + registerWrapper(baseZetaEventClass, forgeZetaEventClass, constructor); + generics.put(baseZetaEventClass, genericClass); + } - registerSubClass(baseZetaEventClass, forgeZetaEventClass, null); + //register known ones + public void registerWrapper(Class baseZetaEventClass, Class forgeEventClass, + Function constructor, Function unwrapper) { + zetaToForgeEventClassHack.put(baseZetaEventClass, forgeEventClass); + forgeToZetaMap.put(baseZetaEventClass, constructor); + zetaToForgeMap.put(baseZetaEventClass, unwrapper); } - public void registerSubClassWithGeneric(Class baseZetaEventClass, Class forgeZetaEventClass, - Function constructor, Class genericClass) { - registerSubClass(baseZetaEventClass, forgeZetaEventClass, constructor); + public void registerWrapperWithGenerics(Class baseZetaEventClass, Class forgeEventClass, + Function constructor, Function unwrapper, + Class genericClass) { + zetaToForgeEventClassHack.put(baseZetaEventClass, forgeEventClass); + forgeToZetaMap.put(baseZetaEventClass, constructor); + zetaToForgeMap.put(baseZetaEventClass, unwrapper); generics.put(baseZetaEventClass, genericClass); } - public void registerSubClass(Class baseZetaEventClass, Class forgeZetaEventClass, - @Nullable Function constructor) { + + @Deprecated + public void registerWrapper(Class baseZetaEventClass, Class forgeZetaEventClass, + @Nullable Function constructor) { Object old1; Object old2 = null; boolean isNoWrapper = false; @@ -268,7 +317,7 @@ private Function findWrappedForgeEvent(Clas return null; } - throw new RuntimeException("No wrapped forge Event found for Zeta event class " + zetaEventClass); + throw new RuntimeException("No e forge Event found for Zeta event class " + zetaEventClass); } private Function findWrappedZetaEvent(Class zetaEventClass, Class baseZetaEventClass) { @@ -285,7 +334,7 @@ private Function findWrappedZetaEvent(Class }; } - throw new RuntimeException("No wrapped Zeta Event found for Zeta event class " + zetaEventClass); + throw new RuntimeException("No e Zeta Event found for Zeta event class " + zetaEventClass); } public static Field findFieldInClassHierarchy(Class clazz, Predicate predicate) { @@ -345,12 +394,28 @@ private static Phase guessFromClassName(Class zetaEventClass, Class forgeC } } + private static final Map, VanillaGuiOverlay> GUI_OVERLAY_CACHE = new ConcurrentHashMap<>(); - private static final Map, EventPriority> CACHE = new ConcurrentHashMap<>(); + @Nullable + private static VanillaGuiOverlay guessGuiOverlayFromClassName(Class zetaEventClass, Class forgeClass) { + if (forgeClass.isAssignableFrom(RenderGuiOverlayEvent.class)) return null; + return GUI_OVERLAY_CACHE.computeIfAbsent(zetaEventClass, zec -> { + String simpleName = zec.getSimpleName(); + for (VanillaGuiOverlay overlay : VanillaGuiOverlay.values()) { + if (simpleName.toUpperCase().equals(overlay.name().replace("_", ""))) { + return overlay; + } + } + return null; + }); + } + + + private static final Map, EventPriority> PRIORITY_CACHE = new ConcurrentHashMap<>(); private static EventPriority guessPriorityFromClassName(Class zetaEventClass) { - return CACHE.computeIfAbsent(zetaEventClass, cl -> { - String simpleName = zetaEventClass.getSimpleName(); + return PRIORITY_CACHE.computeIfAbsent(zetaEventClass, zec -> { + String simpleName = zec.getSimpleName(); for (EventPriority p : EventPriority.values()) { String name = WordUtils.capitalizeFully(p.name().toLowerCase()); if (simpleName.endsWith(name)) { diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/ForgeZetaEventBus.java b/src/main/java/org/violetmoon/zetaimplforge/event/ForgeZetaEventBus.java index a0b62a9..84c807a 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/ForgeZetaEventBus.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/ForgeZetaEventBus.java @@ -6,10 +6,20 @@ import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.client.event.RenderGuiOverlayEvent; +import net.minecraftforge.client.event.RenderLivingEvent; +import net.minecraftforge.client.event.RenderPlayerEvent; +import net.minecraftforge.client.event.ScreenEvent; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.AttachCapabilitiesEvent; +import net.minecraftforge.event.TickEvent; +import net.minecraftforge.event.entity.EntityAttributeCreationEvent; +import net.minecraftforge.event.entity.living.*; +import net.minecraftforge.event.entity.player.ItemTooltipEvent; +import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.eventbus.api.Event; import net.minecraftforge.eventbus.api.IEventBus; +import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import net.minecraftforge.fml.loading.FMLEnvironment; import org.apache.logging.log4j.Logger; @@ -103,9 +113,9 @@ protected void subscribeMethod(Method method, Object receiver, Class owningCl if (receiver != null) handle = handle.bindTo(receiver); - var converted = remapper.remapAndRegister(forgeBus, owningClazz, handle, zetaEventClass); + Object convertedMethod = remapper.remapAndRegister(forgeBus, owningClazz, handle, zetaEventClass); //store here so we can unregister later - convertedHandlers.put(new Key(method, receiver, owningClazz), converted); + convertedHandlers.put(new Key(method, receiver, owningClazz), convertedMethod); } @Override @@ -134,29 +144,29 @@ public T fire(@NotNull T event, Class firedAs) { // all these are for bus specific events. The only bus that should have specific stuff is the play one // for generic events - public void registerSubClassWithGeneric(Class baseZetaEventClass, Class forgeZetaEventClass, Class genericClass) { + public void registerWrapperWithGenerics(Class baseZetaEventClass, Class forgeZetaEventClass, Class genericClass) { synchronized (remapper) { - remapper.registerSubClassWithGeneric(baseZetaEventClass, forgeZetaEventClass, genericClass); + remapper.registerWrapperWithGeneric(baseZetaEventClass, forgeZetaEventClass, genericClass); } } - public void registerSubClass(Class baseZetaEventClass, Class forgeZetaEventClass) { + public void registerWrapper(Class baseZetaEventClass, Class forgeZetaEventClass) { synchronized (remapper) { - remapper.registerSubClass(baseZetaEventClass, forgeZetaEventClass, null); + remapper.registerWrapper(baseZetaEventClass, forgeZetaEventClass, null); } } - public void registerSubClassWithGeneric(Class baseZetaEventClass, Class forgeZetaEventClass, + public void registerWrapperWithGenerics(Class baseZetaEventClass, Class forgeZetaEventClass, Function constructor, Class genericClass) { synchronized (remapper) { - remapper.registerSubClassWithGeneric(baseZetaEventClass, forgeZetaEventClass, constructor, genericClass); + remapper.registerWrapperWithGeneric(baseZetaEventClass, forgeZetaEventClass, constructor, genericClass); } } - public void registerSubClass(Class baseZetaEventClass, Class forgeZetaEventClass, - @Nullable Function constructor) { + public void registerWrapper(Class baseZetaEventClass, Class forgeZetaEventClass, + @Nullable Function constructor) { synchronized (remapper) { - remapper.registerSubClass(baseZetaEventClass, forgeZetaEventClass, constructor); + remapper.registerWrapper(baseZetaEventClass, forgeZetaEventClass, constructor); } } @@ -165,114 +175,134 @@ public void registerSubClass(Class baseZetaEven // instances so we don't create multiple as reflections take time and memory private static final ForgeEventsRemapper LOAD_EVENTS_REMAPPER = Util.make(new ForgeEventsRemapper<>(IZetaLoadEvent.class, Event.class), r -> { + //TODO: repace all these with explicit ones + // adds known events subclasses to the bus - r.registerSubClass(ZCommonSetup.class, ForgeZCommonSetup.class); - r.registerSubClass(ZEntityAttributeCreation.class, ForgeZEntityAttributeCreation.class); - r.registerSubClass(ZModulesReady.class, ForgeZModulesReady.class); - r.registerSubClass(ZRegister.class, ForgeZRegister.class); - r.registerSubClass(ZRegister.Post.class, ForgeZRegister.Post.class); - r.registerSubClass(ZConfigChanged.class, ForgeZConfigChange.class); - r.registerSubClass(ZLoadComplete.class, ForgeZLoadComplete.class); + r.registerWrapper(ZCommonSetup.class, FMLCommonSetupEvent.class, + ForgeZCommonSetup::new, ForgeZCommonSetup::e); + r.registerWrapper(ZEntityAttributeCreation.class, EntityAttributeCreationEvent.class, + ForgeZEntityAttributeCreation::new, ForgeZEntityAttributeCreation::e); + r.registerWrapper(ZModulesReady.class, ForgeZModulesReady.class); + r.registerWrapper(ZRegister.class, ForgeZRegister.class); + r.registerWrapper(ZRegister.Post.class, ForgeZRegister.Post.class); + r.registerWrapper(ZConfigChanged.class, ForgeZConfigChange.class); + r.registerWrapper(ZLoadComplete.class, ForgeZLoadComplete.class); //zeta own - r.registerSubClass(ZGatherAdvancementModifiers.class, ForgeZGatherAdvancementModifiers.class); + r.registerWrapper(ZGatherAdvancementModifiers.class, ForgeZGatherAdvancementModifiers.class); // client ones again? if (FMLEnvironment.dist == Dist.DEDICATED_SERVER) return; - r.registerSubClass(ZAddModels.class, ForgeZAddModels.class); - r.registerSubClass(ZAddModelLayers.class, ForgeZAddModelLayers.class); - r.registerSubClass(ZClientSetup.class, ForgeZClientSetup.class); - r.registerSubClass(ZKeyMapping.class, ForgeZKeyMapping.class); - r.registerSubClass(ZModel.RegisterGeometryLoaders.class, ForgeZModel.RegisterGeometryLoaders.class); - r.registerSubClass(ZModel.RegisterAdditional.class, ForgeZModel.RegisterAdditional.class); - r.registerSubClass(ZModel.BakingCompleted.class, ForgeZModel.BakingCompleted.class); - r.registerSubClass(ZModel.ModifyBakingResult.class, ForgeZModel.ModifyBakingResult.class); - r.registerSubClass(ZRegisterLayerDefinitions.class, ForgeZRegisterLayerDefinitions.class); - r.registerSubClass(ZTooltipComponents.class, ForgeZTooltipComponents.class); - r.registerSubClass(ZRegisterClientReloadListener.class, ForgeZRegisterClientReloadListener.class); - r.registerSubClass(ZFirstClientTick.class, ForgeZFirstClientTick.class); - - r.registerSubClass(ZAddBlockColorHandlers.class, ForgeZAddBlockColorHandlers.class); - r.registerSubClass(ZAddItemColorHandlers.class, ForgeZAddItemColorHandlers.class); + r.registerWrapper(ZAddModels.class, ForgeZAddModels.class); + r.registerWrapper(ZAddModelLayers.class, ForgeZAddModelLayers.class); + r.registerWrapper(ZClientSetup.class, ForgeZClientSetup.class); + r.registerWrapper(ZKeyMapping.class, ForgeZKeyMapping.class); + r.registerWrapper(ZModel.RegisterGeometryLoaders.class, ForgeZModel.RegisterGeometryLoaders.class); + r.registerWrapper(ZModel.RegisterAdditional.class, ForgeZModel.RegisterAdditional.class); + r.registerWrapper(ZModel.BakingCompleted.class, ForgeZModel.BakingCompleted.class); + r.registerWrapper(ZModel.ModifyBakingResult.class, ForgeZModel.ModifyBakingResult.class); + r.registerWrapper(ZRegisterLayerDefinitions.class, ForgeZRegisterLayerDefinitions.class); + r.registerWrapper(ZTooltipComponents.class, ForgeZTooltipComponents.class); + r.registerWrapper(ZRegisterClientReloadListener.class, ForgeZRegisterClientReloadListener.class); + r.registerWrapper(ZFirstClientTick.class, ForgeZFirstClientTick.class); + + r.registerWrapper(ZAddBlockColorHandlers.class, ForgeZAddBlockColorHandlers.class); + r.registerWrapper(ZAddItemColorHandlers.class, ForgeZAddItemColorHandlers.class); }); private static final ForgeEventsRemapper PLAY_EVENTS_REMAPPER = Util.make(new ForgeEventsRemapper<>(IZetaPlayEvent.class, Event.class), r -> { - r.registerSubClass(ZAnvilRepair.class, ForgeZAnvilRepair.class); - r.registerSubClass(ZAnvilUpdate.Highest.class, ForgeZAnvilUpdate.Highest.class); - r.registerSubClass(ZAnvilUpdate.Lowest.class, ForgeZAnvilUpdate.Lowest.class); - r.registerSubClass(ZTagsUpdated.class, ForgeZTagsUpdated.class); - r.registerSubClass(ZBabyEntitySpawn.Lowest.class, ForgeZBabyEntitySpawn.Lowest.class); - r.registerSubClass(ZBabyEntitySpawn.class, ForgeZBabyEntitySpawn.class); - r.registerSubClass(ZBlock.Break.class, ForgeZBlock.Break.class); - r.registerSubClass(ZBlock.EntityPlace.class, ForgeZBlock.EntityPlace.class); - r.registerSubClass(ZBlock.BlockToolModification.class, ForgeZBlock.BlockToolModification.class); - r.registerSubClass(ZBonemeal.class, ForgeZBonemeal.class); - r.registerSubClass(ZEntityConstruct.class, ForgeZEntityConstruct.class); - r.registerSubClass(ZEntityInteract.class, ForgeZEntityInteract.class); - r.registerSubClass(ZEntityItemPickup.class, ForgeZEntityItemPickup.class); - r.registerSubClass(ZEntityJoinLevel.class, ForgeZEntityJoinLevel.class); - r.registerSubClass(ZEntityMobGriefing.class, ForgeZEntityMobGriefing.class); - r.registerSubClass(ZEntityTeleport.class, ForgeZEntityTeleport.class); - r.registerSubClass(ZItemTooltip.class, ForgeZItemTooltip.class); - r.registerSubClass(ZLivingChangeTarget.class, ForgeZLivingChangeTarget.class); - r.registerSubClass(ZLivingConversion.class, ForgeZLivingConversion.class); - r.registerSubClass(ZLivingConversion.Pre.class, ForgeZLivingConversion.Pre.class); - r.registerSubClass(ZLivingConversion.Post.class, ForgeZLivingConversion.Post.class); - r.registerSubClass(ZLivingDeath.class, ForgeZLivingDeath.class); - r.registerSubClass(ZLivingDeath.Lowest.class, ForgeZLivingDeath.Lowest.class); - r.registerSubClass(ZLivingDrops.class, ForgeZLivingDrops.class); - r.registerSubClass(ZLivingDrops.Lowest.class, ForgeZLivingDrops.Lowest.class); - r.registerSubClass(ZLivingFall.class, ForgeZLivingFall.class); - r.registerSubClass(ZLivingTick.class, ForgeZLivingTick.class); - r.registerSubClass(ZMobSpawnEvent.class, ForgeZMobSpawnEvent.class); - r.registerSubClass(ZMobSpawnEvent.CheckSpawn.class, ForgeZMobSpawnEvent.FinalizeSpawn.class); - r.registerSubClass(ZMobSpawnEvent.CheckSpawn.Lowest.class, ForgeZMobSpawnEvent.FinalizeSpawn.Lowest.class); - r.registerSubClass(ZPlayNoteBlock.class, ForgeZPlayNoteBlock.class); - r.registerSubClass(ZPlayer.class, ForgeZPlayer.class); - r.registerSubClass(ZPlayer.BreakSpeed.class, ForgeZPlayer.BreakSpeed.class); - r.registerSubClass(ZPlayer.Clone.class, ForgeZPlayer.Clone.class); - r.registerSubClass(ZPlayerDestroyItem.class, ForgeZPlayerDestroyItem.class); - r.registerSubClass(ZPlayer.LoggedIn.class, ForgeZPlayer.LoggedIn.class); - r.registerSubClass(ZPlayer.LoggedOut.class, ForgeZPlayer.LoggedOut.class); - r.registerSubClass(ZPlayerTick.Start.class, ForgeZPlayerTick.Start.class); - r.registerSubClass(ZPlayerTick.End.class, ForgeZPlayerTick.End.class); - r.registerSubClass(ZPlayerInteract.class, ForgeZPlayerInteract.class); - r.registerSubClass(ZPlayerInteract.EntityInteractSpecific.class, ForgeZPlayerInteract.EntityInteractSpecific.class); - r.registerSubClass(ZPlayerInteract.EntityInteract.class, ForgeZPlayerInteract.EntityInteract.class); - r.registerSubClass(ZPlayerInteract.RightClickBlock.class, ForgeZPlayerInteract.RightClickBlock.class); - r.registerSubClass(ZPlayerInteract.RightClickItem.class, ForgeZPlayerInteract.RightClickItem.class); - r.registerSubClass(ZRightClickBlock.class, ForgeZRightClickBlock.class); - r.registerSubClass(ZRightClickBlock.Low.class, ForgeZRightClickBlock.Low.class); - r.registerSubClass(ZRightClickItem.class, ForgeZRightClickItem.class); - r.registerSubClass(ZLootTableLoad.class, ForgeZLootTableLoad.class); - r.registerSubClass(ZVillagerTrades.class, ForgeZVillagerTrades.class); - r.registerSubClass(ZWandererTrades.class, ForgeZWandererTrades.class); - r.registerSubClass(ZFurnaceFuelBurnTime.class, ForgeZFurnaceFuelBurnTime.class); - r.registerSubClass(ZGatherAdditionalFlags.class, ForgeZGatherAdditionalFlags.class); - r.registerSubClass(ZServerTick.Start.class, ForgeZServerTick.Start.class); - r.registerSubClass(ZServerTick.End.class, ForgeZServerTick.End.class); - r.registerSubClass(ZAddReloadListener.class, ForgeZAddReloadListener.class); - r.registerSubClass(ZGatherHints.class, ForgeZGatherHints.class); - r.registerSubClass(ZSleepingLocationCheck.class, ForgeZSleepingLocationCheck.class); - r.registerSubClass(ZAnimalTame.class, ForgeZAnimalTame.class); - r.registerSubClass(ZLevelTick.End.class, ForgeZLevelTick.End.class); - r.registerSubClass(ZLevelTick.Start.class, ForgeZLevelTick.Start.class); + r.registerWrapper(ZAnvilRepair.class, ForgeZAnvilRepair.class); + r.registerWrapper(ZAnvilUpdate.Highest.class, ForgeZAnvilUpdate.Highest.class); + r.registerWrapper(ZAnvilUpdate.Lowest.class, ForgeZAnvilUpdate.Lowest.class); + r.registerWrapper(ZTagsUpdated.class, ForgeZTagsUpdated.class); + r.registerWrapper(ZBabyEntitySpawn.Lowest.class, BabyEntitySpawnEvent.class, + ForgeZBabyEntitySpawn.Lowest::new, a -> a.wrapped); + r.registerWrapper(ZBabyEntitySpawn.class, BabyEntitySpawnEvent.class, + ForgeZBabyEntitySpawn::new, a -> a.wrapped); + r.registerWrapper(ZBlock.Break.class, ForgeZBlock.Break.class); + r.registerWrapper(ZBlock.EntityPlace.class, ForgeZBlock.EntityPlace.class); + r.registerWrapper(ZBlock.BlockToolModification.class, ForgeZBlock.BlockToolModification.class); + r.registerWrapper(ZBonemeal.class, ForgeZBonemeal.class); + r.registerWrapper(ZEntityConstruct.class, ForgeZEntityConstruct.class); + r.registerWrapper(ZEntityInteract.class, PlayerInteractEvent.EntityInteract.class, + ForgeZEntityInteract::new, ForgeZEntityInteract::e); + r.registerWrapper(ZEntityItemPickup.class, ForgeZEntityItemPickup.class); + r.registerWrapper(ZEntityJoinLevel.class, ForgeZEntityJoinLevel.class); + r.registerWrapper(ZEntityMobGriefing.class, ForgeZEntityMobGriefing.class); + r.registerWrapper(ZEntityTeleport.class, ForgeZEntityTeleport.class); + r.registerWrapper(ZItemTooltip.class, ItemTooltipEvent.class, + ForgeZItemTooltip::new, ForgeZItemTooltip::e); + r.registerWrapper(ZLivingChangeTarget.class, LivingChangeTargetEvent.class, + ForgeZLivingChangeTarget::new, ForgeZLivingChangeTarget::e); + r.registerWrapper(ZLivingConversion.class, ForgeZLivingConversion.class); + r.registerWrapper(ZLivingConversion.Pre.class, ForgeZLivingConversion.Pre.class); + r.registerWrapper(ZLivingConversion.Post.class, ForgeZLivingConversion.Post.class); + r.registerWrapper(ZLivingDeath.class, ForgeZLivingDeath.class); + r.registerWrapper(ZLivingDeath.Lowest.class, ForgeZLivingDeath.Lowest.class); + r.registerWrapper(ZLivingDrops.class, LivingDropsEvent.class, + ForgeZLivingDrops::new, w -> w.e); + r.registerWrapper(ZLivingDrops.Lowest.class, LivingDropsEvent.class, + ForgeZLivingDrops.Lowest::new, w -> w.e); + r.registerWrapper(ZLivingFall.class, ForgeZLivingFall.class); + r.registerWrapper(ZLivingTick.class, LivingEvent.LivingTickEvent.class, + ForgeZLivingTick::new, ForgeZLivingTick::e); + r.registerWrapper(ZMobSpawnEvent.class, MobSpawnEvent.class, + ForgeZMobSpawnEvent::new, w -> w.e); + r.registerWrapper(ZMobSpawnEvent.CheckSpawn.class, MobSpawnEvent.FinalizeSpawn.class, + ForgeZMobSpawnEvent.FinalizeSpawn::new, w -> w.e); + r.registerWrapper(ZMobSpawnEvent.CheckSpawn.Lowest.class, MobSpawnEvent.FinalizeSpawn.class, + ForgeZMobSpawnEvent.FinalizeSpawn.Lowest::new, w -> w.e); + r.registerWrapper(ZPlayNoteBlock.class, ForgeZPlayNoteBlock.class); + r.registerWrapper(ZPlayer.BreakSpeed.class, ForgeZPlayer.BreakSpeed.class); + r.registerWrapper(ZPlayer.Clone.class, ForgeZPlayer.Clone.class); + r.registerWrapper(ZPlayerDestroyItem.class, ForgeZPlayerDestroyItem.class); + r.registerWrapper(ZPlayer.LoggedIn.class, ForgeZPlayer.LoggedIn.class); + r.registerWrapper(ZPlayer.LoggedOut.class, ForgeZPlayer.LoggedOut.class); + r.registerWrapper(ZPlayerTick.Start.class, TickEvent.PlayerTickEvent.class, + ForgeZPlayerTick.Start::new, w -> w.e); + r.registerWrapper(ZPlayerTick.End.class, TickEvent.PlayerTickEvent.class, + ForgeZPlayerTick.End::new, w -> w.e); + r.registerWrapper(ZPlayerInteract.class, ForgeZPlayerInteract.class); + r.registerWrapper(ZPlayerInteract.EntityInteractSpecific.class, ForgeZPlayerInteract.EntityInteractSpecific.class); + r.registerWrapper(ZPlayerInteract.EntityInteract.class, ForgeZPlayerInteract.EntityInteract.class); + r.registerWrapper(ZPlayerInteract.RightClickBlock.class, ForgeZPlayerInteract.RightClickBlock.class); + r.registerWrapper(ZPlayerInteract.RightClickItem.class, ForgeZPlayerInteract.RightClickItem.class); + r.registerWrapper(ZRightClickBlock.class, ForgeZRightClickBlock.class); + r.registerWrapper(ZRightClickBlock.Low.class, ForgeZRightClickBlock.Low.class); + r.registerWrapper(ZRightClickItem.class, ForgeZRightClickItem.class); + r.registerWrapper(ZLootTableLoad.class, ForgeZLootTableLoad.class); + r.registerWrapper(ZVillagerTrades.class, ForgeZVillagerTrades.class); + r.registerWrapper(ZWandererTrades.class, ForgeZWandererTrades.class); + r.registerWrapper(ZFurnaceFuelBurnTime.class, ForgeZFurnaceFuelBurnTime.class); + r.registerWrapper(ZGatherAdditionalFlags.class, ForgeZGatherAdditionalFlags.class); + r.registerWrapper(ZServerTick.Start.class, TickEvent.ServerTickEvent.class, + ForgeZServerTick.Start::new, w -> w.e); + r.registerWrapper(ZServerTick.End.class, TickEvent.ServerTickEvent.class, + ForgeZServerTick.End::new, w -> w.e); + r.registerWrapper(ZAddReloadListener.class, ForgeZAddReloadListener.class); + r.registerWrapper(ZGatherHints.class, ForgeZGatherHints.class); + r.registerWrapper(ZSleepingLocationCheck.class, ForgeZSleepingLocationCheck.class); + r.registerWrapper(ZAnimalTame.class, ForgeZAnimalTame.class); + r.registerWrapper(ZLevelTick.End.class, TickEvent.LevelTickEvent.class, + ForgeZLevelTick.End::new, w -> w.e); + r.registerWrapper(ZLevelTick.Start.class, TickEvent.LevelTickEvent.class, + ForgeZLevelTick.Start::new, w -> w.e); //this is ugly. generic events here - r.registerSubClassWithGeneric(ZAttachCapabilities.BlockEntityCaps.class, + r.registerWrapperWithGeneric(ZAttachCapabilities.BlockEntityCaps.class, ForgeZAttachCapabilities.BlockEntityCaps.class, (Function, ForgeZAttachCapabilities.BlockEntityCaps>) inner -> new ForgeZAttachCapabilities.BlockEntityCaps(ForgeCapabilityManager.INSTANCE, inner), BlockEntity.class); - r.registerSubClassWithGeneric(ZAttachCapabilities.ItemStackCaps.class, + r.registerWrapperWithGeneric(ZAttachCapabilities.ItemStackCaps.class, ForgeZAttachCapabilities.ItemStackCaps.class, (Function, ForgeZAttachCapabilities.ItemStackCaps>) inner -> new ForgeZAttachCapabilities.ItemStackCaps(ForgeCapabilityManager.INSTANCE, inner), ItemStack.class); - r.registerSubClassWithGeneric(ZAttachCapabilities.LevelCaps.class, + r.registerWrapperWithGeneric(ZAttachCapabilities.LevelCaps.class, ForgeZAttachCapabilities.LevelCaps.class, (Function, ForgeZAttachCapabilities.LevelCaps>) inner -> new ForgeZAttachCapabilities.LevelCaps(ForgeCapabilityManager.INSTANCE, inner), @@ -280,65 +310,97 @@ public void registerSubClass(Class baseZetaEven // zeta specific ones - r.registerSubClass(ZRecipeCrawl.Digest.class, ForgeZRecipeCrawl.Digest.class); - r.registerSubClass(ZRecipeCrawl.Reset.class, ForgeZRecipeCrawl.Reset.class); - r.registerSubClass(ZRecipeCrawl.Starting.class, ForgeZRecipeCrawl.Starting.class); - r.registerSubClass(ZRecipeCrawl.Visit.Cooking.class, ForgeZRecipeCrawl.Visit.Cooking.class); - r.registerSubClass(ZRecipeCrawl.Visit.Custom.class, ForgeZRecipeCrawl.Visit.Custom.class); - r.registerSubClass(ZRecipeCrawl.Visit.Misc.class, ForgeZRecipeCrawl.Visit.Misc.class); - r.registerSubClass(ZRecipeCrawl.Visit.Shaped.class, ForgeZRecipeCrawl.Visit.Shaped.class); - r.registerSubClass(ZRecipeCrawl.Visit.Shapeless.class, ForgeZRecipeCrawl.Visit.Shapeless.class); - + r.registerWrapper(ZRecipeCrawl.class, ForgeZRecipeCrawl.Digest.class, + ForgeZRecipeCrawl::get, ForgeZRecipeCrawl.Digest::new); + r.registerWrapper(ZRecipeCrawl.Reset.class, ForgeZRecipeCrawl.Reset.class, + ForgeZRecipeCrawl::get, ForgeZRecipeCrawl.Reset::new); + r.registerWrapper(ZRecipeCrawl.Starting.class, ForgeZRecipeCrawl.Starting.class, + ForgeZRecipeCrawl::get, ForgeZRecipeCrawl.Starting::new); + r.registerWrapper(ZRecipeCrawl.Visit.Cooking.class, ForgeZRecipeCrawl.Visit.Cooking.class, + ForgeZRecipeCrawl::get, ForgeZRecipeCrawl.Visit.Cooking::new); + r.registerWrapper(ZRecipeCrawl.Visit.Custom.class, ForgeZRecipeCrawl.Visit.Custom.class, + ForgeZRecipeCrawl::get, ForgeZRecipeCrawl.Visit.Custom::new); + r.registerWrapper(ZRecipeCrawl.Visit.Misc.class, ForgeZRecipeCrawl.Visit.Misc.class, + ForgeZRecipeCrawl::get, ForgeZRecipeCrawl.Visit.Misc::new); + r.registerWrapper(ZRecipeCrawl.Visit.Shaped.class, ForgeZRecipeCrawl.Visit.Shaped.class, + ForgeZRecipeCrawl::get, ForgeZRecipeCrawl.Visit.Shaped::new); + r.registerWrapper(ZRecipeCrawl.Visit.Shapeless.class, ForgeZRecipeCrawl.Visit.Shapeless.class, + ForgeZRecipeCrawl::get, ForgeZRecipeCrawl.Visit.Shapeless::new); //Hmm client events here? maybe i should move them if (FMLEnvironment.dist == Dist.DEDICATED_SERVER) return; - r.registerSubClass(ZClientTick.End.class, ForgeZClientTick.End.class); - r.registerSubClass(ZClientTick.Start.class, ForgeZClientTick.Start.class); - r.registerSubClass(ZEarlyRender.class, ForgeZEarlyRender.class); - r.registerSubClass(ZGatherTooltipComponents.class, ForgeZGatherTooltipComponents.class); - r.registerSubClass(ZHighlightBlock.class, ForgeZHighlightBlock.class); - r.registerSubClass(ZInput.MouseButton.class, ForgeZInput.MouseButton.class); - r.registerSubClass(ZInput.Key.class, ForgeZInput.Key.class); - r.registerSubClass(ZInputUpdate.class, ForgeZInputUpdate.class); - r.registerSubClass(ZRenderContainerScreen.Background.class, ForgeZRenderContainerScreen.Background.class); - r.registerSubClass(ZRenderContainerScreen.Foreground.class, ForgeZRenderContainerScreen.Foreground.class); - r.registerSubClass(ZRenderLiving.PostLowest.class, ForgeZRenderLiving.PostLowest.class); - r.registerSubClass(ZRenderLiving.PreHighest.class, ForgeZRenderLiving.PreHighest.class); - r.registerSubClass(ZRenderPlayer.Post.class, ForgeZRenderPlayer.Post.class); - r.registerSubClass(ZRenderPlayer.Pre.class, ForgeZRenderPlayer.Pre.class); - r.registerSubClass(ZRenderTick.End.class, ForgeZRenderTick.End.class); - r.registerSubClass(ZRenderTick.Start.class, ForgeZRenderTick.Start.class); - r.registerSubClass(ZRenderTooltip.GatherComponents.class, ForgeZRenderTooltip.GatherComponents.class); - r.registerSubClass(ZRenderTooltip.GatherComponents.Low.class, ForgeZRenderTooltip.GatherComponents.Low.class); - r.registerSubClass(ZScreen.Opening.class, ForgeZScreen.Opening.class); - r.registerSubClass(ZScreen.CharacterTyped.Pre.class, ForgeZScreen.CharacterTyped.Pre.class); - r.registerSubClass(ZScreen.CharacterTyped.Post.class, ForgeZScreen.CharacterTyped.Post.class); - r.registerSubClass(ZScreen.Init.Post.class, ForgeZScreen.Init.Post.class); - r.registerSubClass(ZScreen.Init.Pre.class, ForgeZScreen.Init.Pre.class); - r.registerSubClass(ZScreen.KeyPressed.Post.class, ForgeZScreen.KeyPressed.Post.class); - r.registerSubClass(ZScreen.KeyPressed.Pre.class, ForgeZScreen.KeyPressed.Pre.class); - r.registerSubClass(ZScreen.MouseScrolled.Post.class, ForgeZScreen.MouseScrolled.Post.class); - r.registerSubClass(ZScreen.MouseScrolled.Pre.class, ForgeZScreen.MouseScrolled.Pre.class); - r.registerSubClass(ZScreen.MouseButtonPressed.Post.class, ForgeZScreen.MouseButtonPressed.Post.class); - r.registerSubClass(ZScreen.MouseButtonPressed.Pre.class, ForgeZScreen.MouseButtonPressed.Pre.class); - r.registerSubClass(ZScreen.Render.Post.class, ForgeZScreen.Render.Post.class); - r.registerSubClass(ZScreen.Render.Pre.class, ForgeZScreen.Render.Pre.class); - r.registerSubClass(ZRenderGuiOverlay.ArmorLevel.Pre.class, ForgeZRenderGuiOverlay.ArmorLevel.Pre.class); - r.registerSubClass(ZRenderGuiOverlay.ArmorLevel.Post.class, ForgeZRenderGuiOverlay.ArmorLevel.Post.class); - r.registerSubClass(ZRenderGuiOverlay.Crosshair.Post.class, ForgeZRenderGuiOverlay.Crosshair.Post.class); - r.registerSubClass(ZRenderGuiOverlay.Crosshair.Pre.class, ForgeZRenderGuiOverlay.Crosshair.Pre.class); - r.registerSubClass(ZRenderGuiOverlay.DebugText.Pre.class, ForgeZRenderGuiOverlay.DebugText.Pre.class); - r.registerSubClass(ZRenderGuiOverlay.DebugText.Post.class, ForgeZRenderGuiOverlay.DebugText.Post.class); - r.registerSubClass(ZRenderGuiOverlay.Hotbar.Pre.class, ForgeZRenderGuiOverlay.Hotbar.Pre.class); - r.registerSubClass(ZRenderGuiOverlay.Hotbar.Post.class, ForgeZRenderGuiOverlay.Hotbar.Post.class); - r.registerSubClass(ZRenderGuiOverlay.PlayerHealth.Pre.class, ForgeZRenderGuiOverlay.PlayerHealth.Pre.class); - r.registerSubClass(ZRenderGuiOverlay.PlayerHealth.Post.class, ForgeZRenderGuiOverlay.PlayerHealth.Post.class); - r.registerSubClass(ZRenderGuiOverlay.PotionIcons.Pre.class, ForgeZRenderGuiOverlay.PotionIcons.Pre.class); - r.registerSubClass(ZRenderGuiOverlay.PotionIcons.Post.class, ForgeZRenderGuiOverlay.PotionIcons.Post.class); - r.registerSubClass(ZRenderGuiOverlay.ChatPanel.Pre.class, ForgeZRenderGuiOverlay.ChatPanel.Pre.class); - r.registerSubClass(ZRenderGuiOverlay.ChatPanel.Post.class, ForgeZRenderGuiOverlay.ChatPanel.Post.class); - r.registerSubClass(ZScreenshot.class, ForgeZScreenshot.class); + r.registerWrapper(ZClientTick.End.class, TickEvent.ClientTickEvent.class, + ForgeZClientTick.End::new, w -> w.e); + r.registerWrapper(ZClientTick.Start.class, TickEvent.ClientTickEvent.class, + ForgeZClientTick.Start::new, w -> w.e); + r.registerWrapper(ZGatherTooltipComponents.class, ForgeZGatherTooltipComponents.class); + r.registerWrapper(ZHighlightBlock.class, ForgeZHighlightBlock.class); + r.registerWrapper(ZInput.MouseButton.class, ForgeZInput.MouseButton.class); + r.registerWrapper(ZInput.Key.class, ForgeZInput.Key.class); + r.registerWrapper(ZInputUpdate.class, ForgeZInputUpdate.class); + r.registerWrapper(ZRenderContainerScreen.Background.class, ForgeZRenderContainerScreen.Background.class); + r.registerWrapper(ZRenderContainerScreen.Foreground.class, ForgeZRenderContainerScreen.Foreground.class); + r.registerWrapper(ZRenderLiving.PostLowest.class, RenderLivingEvent.Post.class, + ForgeZRenderLiving.PostLowest::new, w -> w.e); + r.registerWrapper(ZRenderLiving.PreHighest.class, RenderLivingEvent.Pre.class, + ForgeZRenderLiving.PreHighest::new, w -> w.e); + r.registerWrapper(ZRenderPlayer.Post.class, RenderPlayerEvent.Post.class, + ForgeZRenderPlayer.Post::new, w -> w.e); + r.registerWrapper(ZRenderPlayer.Pre.class, RenderPlayerEvent.Pre.class, + ForgeZRenderPlayer.Pre::new, w -> w.e); + r.registerWrapper(ZRenderTick.End.class, TickEvent.RenderTickEvent.class, + ForgeZRenderTick.End::new, w -> w.e); + r.registerWrapper(ZRenderTick.Start.class, TickEvent.RenderTickEvent.class, + ForgeZRenderTick.Start::new, w -> w.e); + r.registerWrapper(ZRenderTooltip.GatherComponents.class, ForgeZRenderTooltip.GatherComponents.class); + r.registerWrapper(ZRenderTooltip.GatherComponents.Low.class, ForgeZRenderTooltip.GatherComponents.Low.class); + r.registerWrapper(ZScreen.Opening.class, ForgeZScreen.Opening.class); + r.registerWrapper(ZScreen.CharacterTyped.Pre.class, ForgeZScreen.CharacterTyped.Pre.class); + r.registerWrapper(ZScreen.CharacterTyped.Post.class, ForgeZScreen.CharacterTyped.Post.class); + r.registerWrapper(ZScreen.Init.Post.class, ForgeZScreen.Init.Post.class); + r.registerWrapper(ZScreen.Init.Pre.class, ForgeZScreen.Init.Pre.class); + r.registerWrapper(ZScreen.KeyPressed.Post.class, ForgeZScreen.KeyPressed.Post.class); + r.registerWrapper(ZScreen.KeyPressed.Pre.class, ForgeZScreen.KeyPressed.Pre.class); + r.registerWrapper(ZScreen.MouseScrolled.Post.class, ForgeZScreen.MouseScrolled.Post.class); + r.registerWrapper(ZScreen.MouseScrolled.Pre.class, ForgeZScreen.MouseScrolled.Pre.class); + r.registerWrapper(ZScreen.MouseButtonPressed.Post.class, ForgeZScreen.MouseButtonPressed.Post.class); + r.registerWrapper(ZScreen.MouseButtonPressed.Pre.class, ForgeZScreen.MouseButtonPressed.Pre.class); + r.registerWrapper(ZScreen.Render.Post.class, ScreenEvent.Render.Post.class, + ForgeZScreen.Render.Post::new, w -> w.e); + r.registerWrapper(ZScreen.Render.Pre.class, ScreenEvent.Render.Pre.class, + ForgeZScreen.Render.Pre::new, w -> w.e); + r.registerWrapper(ZRenderGuiOverlay.ArmorLevel.Pre.class, RenderGuiOverlayEvent.Pre.class, + ForgeZRenderGuiOverlay.ArmorLevel.Pre::new, w -> w.e); + r.registerWrapper(ZRenderGuiOverlay.ArmorLevel.Post.class, RenderGuiOverlayEvent.Post.class, + ForgeZRenderGuiOverlay.ArmorLevel.Post::new, w -> w.e); + r.registerWrapper(ZRenderGuiOverlay.Crosshair.Post.class, RenderGuiOverlayEvent.Post.class, + ForgeZRenderGuiOverlay.Crosshair.Post::new, w -> w.e); + r.registerWrapper(ZRenderGuiOverlay.Crosshair.Pre.class, RenderGuiOverlayEvent.Pre.class, + ForgeZRenderGuiOverlay.Crosshair.Pre::new, w -> w.e); + r.registerWrapper(ZRenderGuiOverlay.DebugText.Pre.class, RenderGuiOverlayEvent.Pre.class, + ForgeZRenderGuiOverlay.DebugText.Pre::new, w -> w.e); + r.registerWrapper(ZRenderGuiOverlay.DebugText.Post.class, RenderGuiOverlayEvent.Post.class, + ForgeZRenderGuiOverlay.DebugText.Post::new, w -> w.e); + r.registerWrapper(ZRenderGuiOverlay.Hotbar.Pre.class, RenderGuiOverlayEvent.Pre.class, + ForgeZRenderGuiOverlay.Hotbar.Pre::new, w -> w.e); + r.registerWrapper(ZRenderGuiOverlay.Hotbar.Post.class, RenderGuiOverlayEvent.Post.class, + ForgeZRenderGuiOverlay.Hotbar.Post::new, w -> w.e); + r.registerWrapper(ZRenderGuiOverlay.PlayerHealth.Pre.class, RenderGuiOverlayEvent.Pre.class, + ForgeZRenderGuiOverlay.PlayerHealth.Pre::new, w -> w.e); + r.registerWrapper(ZRenderGuiOverlay.PlayerHealth.Post.class, RenderGuiOverlayEvent.Post.class, + ForgeZRenderGuiOverlay.PlayerHealth.Post::new, w -> w.e); + r.registerWrapper(ZRenderGuiOverlay.PotionIcons.Pre.class, RenderGuiOverlayEvent.Pre.class, + ForgeZRenderGuiOverlay.PotionIcons.Pre::new, w -> w.e); + r.registerWrapper(ZRenderGuiOverlay.PotionIcons.Post.class, RenderGuiOverlayEvent.Post.class, + ForgeZRenderGuiOverlay.PotionIcons.Post::new, w -> w.e); + r.registerWrapper(ZRenderGuiOverlay.ChatPanel.Pre.class, RenderGuiOverlayEvent.Pre.class, + ForgeZRenderGuiOverlay.ChatPanel.Pre::new, w -> w.e); + r.registerWrapper(ZRenderGuiOverlay.ChatPanel.Post.class, RenderGuiOverlayEvent.Post.class, + ForgeZRenderGuiOverlay.ChatPanel.Post::new, w -> w.e); + // zeta own event + r.registerWrapper(ZScreenshot.class, ForgeZScreenshot.class); + r.registerWrapper(ZEarlyRender.class, ForgeZEarlyRender.class); }); diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZEntityAttributeCreation.java b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZEntityAttributeCreation.java index 59851c1..5ca5b69 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZEntityAttributeCreation.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/load/ForgeZEntityAttributeCreation.java @@ -7,12 +7,7 @@ import net.minecraft.world.entity.ai.attributes.AttributeSupplier; import net.minecraftforge.event.entity.EntityAttributeCreationEvent; -public class ForgeZEntityAttributeCreation implements ZEntityAttributeCreation { - private final EntityAttributeCreationEvent e; - - public ForgeZEntityAttributeCreation(EntityAttributeCreationEvent e) { - this.e = e; - } +public record ForgeZEntityAttributeCreation(EntityAttributeCreationEvent e) implements ZEntityAttributeCreation { @Override public void put(EntityType entity, AttributeSupplier map) { diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZItemTooltip.java b/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZItemTooltip.java index 97fd494..0fc33bb 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZItemTooltip.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZItemTooltip.java @@ -12,12 +12,7 @@ import net.minecraft.world.item.TooltipFlag; import net.minecraftforge.event.entity.player.ItemTooltipEvent; -public class ForgeZItemTooltip implements ZItemTooltip { - private final ItemTooltipEvent e; - - public ForgeZItemTooltip(ItemTooltipEvent e) { - this.e = e; - } +public record ForgeZItemTooltip(ItemTooltipEvent e) implements ZItemTooltip { @Override public TooltipFlag getFlags() {return e.getFlags();} diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZLevelTick.java b/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZLevelTick.java index 5064e61..705363b 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZLevelTick.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZLevelTick.java @@ -7,7 +7,7 @@ import net.minecraftforge.event.TickEvent; public class ForgeZLevelTick implements ZLevelTick { - private final TickEvent.LevelTickEvent e; + public final TickEvent.LevelTickEvent e; public ForgeZLevelTick(TickEvent.LevelTickEvent e) { this.e = e; diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZServerTick.java b/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZServerTick.java index 49a13fd..0a39c8f 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZServerTick.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/play/ForgeZServerTick.java @@ -6,7 +6,7 @@ import net.minecraftforge.event.TickEvent; public class ForgeZServerTick implements ZServerTick { - private final TickEvent.ServerTickEvent e; + public final TickEvent.ServerTickEvent e; public ForgeZServerTick(TickEvent.ServerTickEvent e) { this.e = e; diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/ForgeZEntityInteract.java b/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/ForgeZEntityInteract.java index 2a8c9df..8afa861 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/ForgeZEntityInteract.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/ForgeZEntityInteract.java @@ -9,13 +9,7 @@ import net.minecraft.world.level.Level; import net.minecraftforge.event.entity.player.PlayerInteractEvent; -public class ForgeZEntityInteract implements ZEntityInteract { - private final PlayerInteractEvent.EntityInteract e; - - public ForgeZEntityInteract(PlayerInteractEvent.EntityInteract e) { - this.e = e; - } - +public record ForgeZEntityInteract(PlayerInteractEvent.EntityInteract e) implements ZEntityInteract { @Override public Entity getTarget() { return e.getTarget(); diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/living/ForgeZBabyEntitySpawn.java b/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/living/ForgeZBabyEntitySpawn.java index ad93dd3..ef0d4c1 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/living/ForgeZBabyEntitySpawn.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/living/ForgeZBabyEntitySpawn.java @@ -8,40 +8,40 @@ import net.minecraftforge.event.entity.living.BabyEntitySpawnEvent; public class ForgeZBabyEntitySpawn implements ZBabyEntitySpawn { - private final BabyEntitySpawnEvent e; + public final BabyEntitySpawnEvent wrapped; public ForgeZBabyEntitySpawn(BabyEntitySpawnEvent e) { - this.e = e; + this.wrapped = e; } @Override public Mob getParentA() { - return e.getParentA(); + return wrapped.getParentA(); } @Override public Mob getParentB() { - return e.getParentB(); + return wrapped.getParentB(); } @Override public Player getCausedByPlayer() { - return e.getCausedByPlayer(); + return wrapped.getCausedByPlayer(); } @Override public AgeableMob getChild() { - return e.getChild(); + return wrapped.getChild(); } @Override public void setChild(AgeableMob proposedChild) { - e.setChild(proposedChild); + wrapped.setChild(proposedChild); } public static class Lowest extends ForgeZBabyEntitySpawn implements ZBabyEntitySpawn.Lowest { - public Lowest(BabyEntitySpawnEvent e) { - super(e); + public Lowest(BabyEntitySpawnEvent wrapped) { + super(wrapped); } } } diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/living/ForgeZLivingChangeTarget.java b/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/living/ForgeZLivingChangeTarget.java index d6dbfa1..0776f92 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/living/ForgeZLivingChangeTarget.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/living/ForgeZLivingChangeTarget.java @@ -5,12 +5,7 @@ import net.minecraft.world.entity.LivingEntity; import net.minecraftforge.event.entity.living.LivingChangeTargetEvent; -public class ForgeZLivingChangeTarget implements ZLivingChangeTarget { - private final LivingChangeTargetEvent e; - - public ForgeZLivingChangeTarget(LivingChangeTargetEvent e) { - this.e = e; - } +public record ForgeZLivingChangeTarget(LivingChangeTargetEvent e) implements ZLivingChangeTarget { @Override public LivingEntity getEntity() { diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/living/ForgeZLivingDrops.java b/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/living/ForgeZLivingDrops.java index 037328a..8b49305 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/living/ForgeZLivingDrops.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/living/ForgeZLivingDrops.java @@ -10,7 +10,7 @@ import net.minecraftforge.event.entity.living.LivingDropsEvent; public class ForgeZLivingDrops implements ZLivingDrops { - private final LivingDropsEvent e; + public final LivingDropsEvent e; public ForgeZLivingDrops(LivingDropsEvent e) { this.e = e; diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/living/ForgeZMobSpawnEvent.java b/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/living/ForgeZMobSpawnEvent.java index 64f2ec7..fed2b4e 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/living/ForgeZMobSpawnEvent.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/living/ForgeZMobSpawnEvent.java @@ -11,7 +11,7 @@ import net.minecraftforge.event.entity.living.MobSpawnEvent; public class ForgeZMobSpawnEvent implements ZMobSpawnEvent { - private final MobSpawnEvent e; + public final MobSpawnEvent e; public ForgeZMobSpawnEvent(MobSpawnEvent e) { this.e = e; @@ -53,7 +53,7 @@ public void setResult(ZResult value) { } public static class FinalizeSpawn extends ForgeZMobSpawnEvent implements ZMobSpawnEvent.CheckSpawn { - private final MobSpawnEvent.FinalizeSpawn e; + public final MobSpawnEvent.FinalizeSpawn e; public FinalizeSpawn(MobSpawnEvent.FinalizeSpawn e) { super(e); diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/player/ForgeZPlayerTick.java b/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/player/ForgeZPlayerTick.java index 174ebcf..c0c80f6 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/player/ForgeZPlayerTick.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/play/entity/player/ForgeZPlayerTick.java @@ -6,7 +6,7 @@ import net.minecraftforge.event.TickEvent; public abstract class ForgeZPlayerTick implements ZPlayerTick { - private final TickEvent.PlayerTickEvent e; + public final TickEvent.PlayerTickEvent e; protected ForgeZPlayerTick(TickEvent.PlayerTickEvent e) { this.e = e; diff --git a/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModClientProxy.java b/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModClientProxy.java index 37c7708..d097651 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModClientProxy.java +++ b/src/main/java/org/violetmoon/zetaimplforge/mod/ZetaModClientProxy.java @@ -1,80 +1,33 @@ package org.violetmoon.zetaimplforge.mod; -import net.minecraftforge.client.event.RenderGuiOverlayEvent; -import net.minecraftforge.client.gui.overlay.NamedGuiOverlay; -import net.minecraftforge.client.gui.overlay.VanillaGuiOverlay; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.TickEvent; import org.violetmoon.zeta.Zeta; import org.violetmoon.zeta.client.ClientTicker; -import org.violetmoon.zeta.client.event.play.ZRenderGuiOverlay; import org.violetmoon.zeta.util.handler.RequiredModTooltipHandler; import org.violetmoon.zeta.util.zetalist.ZetaList; -import org.violetmoon.zetaimplforge.client.ForgeZetaClient; -import org.violetmoon.zetaimplforge.client.event.play.ForgeZRenderGuiOverlay; import org.violetmoon.zetaimplforge.event.load.ForgeZFirstClientTick; public class ZetaModClientProxy extends ZetaModCommonProxy { - private final ForgeZetaClient clientZeta; + public ZetaModClientProxy(Zeta zeta) { + super(zeta); - public ZetaModClientProxy(Zeta zeta) { - super(zeta); - this.clientZeta = new ForgeZetaClient(zeta); + zeta.playBus + .subscribe(ClientTicker.INSTANCE) + .subscribe(new RequiredModTooltipHandler.Client(zeta)); - zeta.playBus - .subscribe(ClientTicker.INSTANCE) - .subscribe(new RequiredModTooltipHandler.Client(zeta)); + MinecraftForge.EVENT_BUS.addListener(this::clientTick); + } - MinecraftForge.EVENT_BUS.addListener(this::clientTick); + // added once per zeta. Its fine as we then fire it on zeta load bos which is one per zeta too. + boolean clientTicked = false; - MinecraftForge.EVENT_BUS.addListener(this::renderGuiOverlayPre); - MinecraftForge.EVENT_BUS.addListener(this::renderGuiOverlayPost); - } + public void clientTick(TickEvent.ClientTickEvent e) { + if (!clientTicked) { + ZetaList.INSTANCE.fireLoadEvent(new ForgeZFirstClientTick()); + clientTicked = true; + } + } - // added once per zeta. Its fine as we then fire it on zeta load bos which is one per zeta too. - boolean clientTicked = false; - public void clientTick(TickEvent.ClientTickEvent e) { - if(!clientTicked) { - ZetaList.INSTANCE.fireLoadEvent(new ForgeZFirstClientTick()); - clientTicked = true; - } - } - - public void renderGuiOverlayPre(RenderGuiOverlayEvent.Pre e) { - NamedGuiOverlay overlay = e.getOverlay(); - if (overlay == VanillaGuiOverlay.HOTBAR.type()) - clientZeta.playBus.fire(new ForgeZRenderGuiOverlay.Hotbar.Pre(e), ZRenderGuiOverlay.Hotbar.Pre.class); - else if (overlay == VanillaGuiOverlay.CROSSHAIR.type()) - clientZeta.playBus.fire(new ForgeZRenderGuiOverlay.Crosshair.Pre(e), ZRenderGuiOverlay.Crosshair.Pre.class); - else if (overlay == VanillaGuiOverlay.PLAYER_HEALTH.type()) - clientZeta.playBus.fire(new ForgeZRenderGuiOverlay.PlayerHealth.Pre(e), ZRenderGuiOverlay.PlayerHealth.Pre.class); - else if (overlay == VanillaGuiOverlay.ARMOR_LEVEL.type()) - clientZeta.playBus.fire(new ForgeZRenderGuiOverlay.ArmorLevel.Pre(e), ZRenderGuiOverlay.ArmorLevel.Pre.class); - else if (overlay == VanillaGuiOverlay.DEBUG_TEXT.type()) - clientZeta.playBus.fire(new ForgeZRenderGuiOverlay.DebugText.Pre(e), ZRenderGuiOverlay.DebugText.Pre.class); - else if (overlay == VanillaGuiOverlay.POTION_ICONS.type()) - clientZeta.playBus.fire(new ForgeZRenderGuiOverlay.PotionIcons.Pre(e), ZRenderGuiOverlay.PotionIcons.Pre.class); - else if (overlay == VanillaGuiOverlay.CHAT_PANEL.type()) - clientZeta.playBus.fire(new ForgeZRenderGuiOverlay.ChatPanel.Pre(e), ZRenderGuiOverlay.ChatPanel.Pre.class); - } - - public void renderGuiOverlayPost(RenderGuiOverlayEvent.Post e) { - NamedGuiOverlay overlay = e.getOverlay(); - if (overlay == VanillaGuiOverlay.HOTBAR.type()) - clientZeta.playBus.fire(new ForgeZRenderGuiOverlay.Hotbar.Post(e), ZRenderGuiOverlay.Hotbar.Post.class); - else if (overlay == VanillaGuiOverlay.CROSSHAIR.type()) - clientZeta.playBus.fire(new ForgeZRenderGuiOverlay.Crosshair.Post(e), ZRenderGuiOverlay.Crosshair.Post.class); - else if (overlay == VanillaGuiOverlay.PLAYER_HEALTH.type()) - clientZeta.playBus.fire(new ForgeZRenderGuiOverlay.PlayerHealth.Post(e), ZRenderGuiOverlay.PlayerHealth.Post.class); - else if (overlay == VanillaGuiOverlay.ARMOR_LEVEL.type()) - clientZeta.playBus.fire(new ForgeZRenderGuiOverlay.ArmorLevel.Post(e), ZRenderGuiOverlay.ArmorLevel.Post.class); - else if (overlay == VanillaGuiOverlay.DEBUG_TEXT.type()) - clientZeta.playBus.fire(new ForgeZRenderGuiOverlay.DebugText.Post(e), ZRenderGuiOverlay.DebugText.Post.class); - else if (overlay == VanillaGuiOverlay.POTION_ICONS.type()) - clientZeta.playBus.fire(new ForgeZRenderGuiOverlay.PotionIcons.Post(e), ZRenderGuiOverlay.PotionIcons.Post.class); - else if (overlay == VanillaGuiOverlay.CHAT_PANEL.type()) - clientZeta.playBus.fire(new ForgeZRenderGuiOverlay.ChatPanel.Post(e), ZRenderGuiOverlay.ChatPanel.Post.class); - } - } From 195ee933aa39dca571ee79342d7599f92f1a556c Mon Sep 17 00:00:00 2001 From: MehVahdJukaar Date: Sat, 3 Aug 2024 22:52:36 +0200 Subject: [PATCH 20/22] fixed some issues with remapping --- build.properties | 2 +- .../org/violetmoon/zeta/client/ClientTicker.java | 6 ++++++ .../zetaimplforge/event/ForgeEventsRemapper.java | 15 ++++++++++----- .../zetaimplforge/event/ForgeZetaEventBus.java | 2 +- 4 files changed, 18 insertions(+), 7 deletions(-) diff --git a/build.properties b/build.properties index dc36927..a2ce825 100644 --- a/build.properties +++ b/build.properties @@ -5,5 +5,5 @@ mod_name=Zeta mc_version=1.20.1 mapping_channel=official mod_id=zeta -build_number=20-event27 +build_number=20-event29 dir_output=../Build Output/Zeta/ diff --git a/src/main/java/org/violetmoon/zeta/client/ClientTicker.java b/src/main/java/org/violetmoon/zeta/client/ClientTicker.java index 020f277..b3a3d42 100644 --- a/src/main/java/org/violetmoon/zeta/client/ClientTicker.java +++ b/src/main/java/org/violetmoon/zeta/client/ClientTicker.java @@ -3,6 +3,7 @@ import net.minecraft.client.Minecraft; import org.jetbrains.annotations.ApiStatus; import org.violetmoon.zeta.client.event.play.ZClientTick; +import org.violetmoon.zeta.client.event.play.ZRenderGuiOverlay; import org.violetmoon.zeta.client.event.play.ZRenderTick; import org.violetmoon.zeta.event.bus.PlayEvent; @@ -37,4 +38,9 @@ public void onEndClientTick(ZClientTick.End event) { ticksInGame++; } } + + @PlayEvent + public void pre(ZRenderGuiOverlay.ChatPanel.Pre event) { + int aa = 1; + } } diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/ForgeEventsRemapper.java b/src/main/java/org/violetmoon/zetaimplforge/event/ForgeEventsRemapper.java index ca4a939..0dc3525 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/ForgeEventsRemapper.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/ForgeEventsRemapper.java @@ -11,6 +11,7 @@ import org.apache.commons.lang3.text.WordUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.violetmoon.zeta.client.event.play.ZRenderGuiOverlay; import java.lang.invoke.MethodHandle; import java.lang.reflect.Constructor; @@ -20,6 +21,7 @@ import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; +import java.util.regex.Pattern; //@SuppressWarnings({"unchecked","rawtypes"}) public class ForgeEventsRemapper { @@ -94,7 +96,7 @@ private Consumer createForgeConsumer( //special cases fo forge events that are to be sub divided into phases // for gui overlay event - VanillaGuiOverlay overlay = guessGuiOverlayFromClassName(zetaEventBaseClass, forgeEventClass.getSuperclass()); + VanillaGuiOverlay overlay = guessGuiOverlayFromClassName(zetaEventBaseClass, forgeEventClass); if (overlay != null) { //here we know that phase must not be null return event -> { @@ -382,7 +384,7 @@ private enum Phase { NONE, START, END; private static Phase guessFromClassName(Class zetaEventClass, Class forgeClass) { - if (forgeClass.isAssignableFrom(TickEvent.class)) return NONE; + if (!TickEvent.class.isAssignableFrom(forgeClass)) return NONE; String simpleName = zetaEventClass.getSimpleName(); if (simpleName.equals("Start")) { return START; @@ -395,12 +397,15 @@ private static Phase guessFromClassName(Class zetaEventClass, Class forgeC } private static final Map, VanillaGuiOverlay> GUI_OVERLAY_CACHE = new ConcurrentHashMap<>(); + private static final Pattern INNER_CLASS_PATTERN = Pattern.compile("\\$([^$]+)\\$"); @Nullable - private static VanillaGuiOverlay guessGuiOverlayFromClassName(Class zetaEventClass, Class forgeClass) { - if (forgeClass.isAssignableFrom(RenderGuiOverlayEvent.class)) return null; + private static VanillaGuiOverlay guessGuiOverlayFromClassName(Class zetaEventClass, Class forgeEventClass) { + if (!RenderGuiOverlayEvent.class.isAssignableFrom(forgeEventClass)) return null; return GUI_OVERLAY_CACHE.computeIfAbsent(zetaEventClass, zec -> { - String simpleName = zec.getSimpleName(); + var match = INNER_CLASS_PATTERN.matcher(zetaEventClass.getName()); + if (!match.find()) return null; + String simpleName = match.group(1); for (VanillaGuiOverlay overlay : VanillaGuiOverlay.values()) { if (simpleName.toUpperCase().equals(overlay.name().replace("_", ""))) { return overlay; diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/ForgeZetaEventBus.java b/src/main/java/org/violetmoon/zetaimplforge/event/ForgeZetaEventBus.java index 84c807a..0fa6f11 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/ForgeZetaEventBus.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/ForgeZetaEventBus.java @@ -310,7 +310,7 @@ public void registerWrapper(Class baseZetaEvent // zeta specific ones - r.registerWrapper(ZRecipeCrawl.class, ForgeZRecipeCrawl.Digest.class, + r.registerWrapper(ZRecipeCrawl.Digest.class, ForgeZRecipeCrawl.Digest.class, ForgeZRecipeCrawl::get, ForgeZRecipeCrawl.Digest::new); r.registerWrapper(ZRecipeCrawl.Reset.class, ForgeZRecipeCrawl.Reset.class, ForgeZRecipeCrawl::get, ForgeZRecipeCrawl.Reset::new); From 51dfc807ed0d367c9f30fe595110d618e04e41e8 Mon Sep 17 00:00:00 2001 From: MehVahdJukaar Date: Sat, 3 Aug 2024 23:11:08 +0200 Subject: [PATCH 21/22] version --- build.properties | 2 +- src/main/resources/META-INF/mods.toml | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/build.properties b/build.properties index a2ce825..3375784 100644 --- a/build.properties +++ b/build.properties @@ -5,5 +5,5 @@ mod_name=Zeta mc_version=1.20.1 mapping_channel=official mod_id=zeta -build_number=20-event29 +build_number=20 dir_output=../Build Output/Zeta/ diff --git a/src/main/resources/META-INF/mods.toml b/src/main/resources/META-INF/mods.toml index 12adcb4..3ab658a 100644 --- a/src/main/resources/META-INF/mods.toml +++ b/src/main/resources/META-INF/mods.toml @@ -15,4 +15,10 @@ description='''A fully featured Library designed around loading highly configura mandatory=true versionRange="[43.0.8,)" ordering="AFTER" + side="BOTH" + +[[dependencies.zeta]] + modId="quark" + mandatory=false + versionRange="[4.0-460,)" side="BOTH" \ No newline at end of file From df81b4b4af85ccba476b1ac98f8d5ecc9e1df375 Mon Sep 17 00:00:00 2001 From: MehVahdJukaar Date: Sat, 3 Aug 2024 23:12:24 +0200 Subject: [PATCH 22/22] pmd shush --- .../org/violetmoon/zetaimplforge/event/ForgeEventsRemapper.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/violetmoon/zetaimplforge/event/ForgeEventsRemapper.java b/src/main/java/org/violetmoon/zetaimplforge/event/ForgeEventsRemapper.java index 0dc3525..9718cf4 100644 --- a/src/main/java/org/violetmoon/zetaimplforge/event/ForgeEventsRemapper.java +++ b/src/main/java/org/violetmoon/zetaimplforge/event/ForgeEventsRemapper.java @@ -407,7 +407,7 @@ private static VanillaGuiOverlay guessGuiOverlayFromClassName(Class zetaEvent if (!match.find()) return null; String simpleName = match.group(1); for (VanillaGuiOverlay overlay : VanillaGuiOverlay.values()) { - if (simpleName.toUpperCase().equals(overlay.name().replace("_", ""))) { + if (simpleName.equalsIgnoreCase(overlay.name().replace("_", ""))) { return overlay; } }