Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Conditional mods & event bus subscribers #212

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions loader/src/main/java/net/neoforged/fml/common/DependsOn.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/*
* Copyright (c) NeoForged and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/

package net.neoforged.fml.common;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface DependsOn {
/**
* @return the array of mod ids that must be present for this to object to be loaded
*/
String[] value();
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,19 @@
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import net.neoforged.api.distmarker.Dist;
import net.neoforged.bus.api.IEventBus;
import net.neoforged.fml.Bindings;
import net.neoforged.fml.ModContainer;
import net.neoforged.fml.ModList;
import net.neoforged.fml.common.DependsOn;
import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.fml.common.Mod;
import net.neoforged.fml.loading.FMLEnvironment;
import net.neoforged.fml.loading.modscan.ModAnnotation;
import net.neoforged.neoforgespi.language.IModInfo;
import net.neoforged.neoforgespi.language.ModFileScanData;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
Expand All @@ -34,6 +38,7 @@ public class AutomaticEventSubscriber {
private static final Logger LOGGER = LogManager.getLogger();
private static final Type AUTO_SUBSCRIBER = Type.getType(EventBusSubscriber.class);
private static final Type MOD_TYPE = Type.getType(Mod.class);
private static final Type DEPENDS_ON_LIST_TYPE = Type.getType(DependsOn.class);

public static void inject(final ModContainer mod, final ModFileScanData scanData, final Module layer) {
if (scanData == null) return;
Expand All @@ -47,7 +52,19 @@ public static void inject(final ModContainer mod, final ModFileScanData scanData
final String modId = (String) ad.annotationData().getOrDefault("modid", modids.getOrDefault(ad.clazz().getClassName(), mod.getModId()));
final ModAnnotation.EnumHolder busTargetHolder = (ModAnnotation.EnumHolder) ad.annotationData().getOrDefault("bus", new ModAnnotation.EnumHolder(null, EventBusSubscriber.Bus.GAME.name()));
final EventBusSubscriber.Bus busTarget = EventBusSubscriber.Bus.valueOf(busTargetHolder.value());
if (Objects.equals(mod.getModId(), modId) && sides.contains(FMLEnvironment.dist)) {
final List<ModFileScanData.AnnotationData> depData = scanData.getAnnotations().stream()
.filter(annotationData -> DEPENDS_ON_LIST_TYPE.equals(annotationData.annotationType()) && ad.clazz().equals(annotationData.clazz())).toList();

final Set<String> loadedModIds = ModList.get().getMods().stream().map(IModInfo::getModId).collect(Collectors.toSet());

final boolean allDepsPresent;
if (depData.isEmpty()) allDepsPresent = true;
else {
var deps = (String[]) depData.getFirst().annotationData().getOrDefault("value", new DependsOn[0]);
allDepsPresent = loadedModIds.containsAll(List.of(deps));
}

if (Objects.equals(mod.getModId(), modId) && sides.contains(FMLEnvironment.dist) && allDepsPresent) {
try {
IEventBus bus = switch (busTarget) {
case GAME -> Bindings.getGameBus();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@

package net.neoforged.fml.javafmlmod;

import java.lang.annotation.ElementType;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
Expand All @@ -19,9 +21,11 @@
import net.neoforged.bus.api.EventListener;
import net.neoforged.bus.api.IEventBus;
import net.neoforged.fml.ModContainer;
import net.neoforged.fml.ModList;
import net.neoforged.fml.ModLoadingContext;
import net.neoforged.fml.ModLoadingException;
import net.neoforged.fml.ModLoadingIssue;
import net.neoforged.fml.common.DependsOn;
import net.neoforged.fml.event.IModBusEvent;
import net.neoforged.fml.loading.FMLLoader;
import net.neoforged.neoforgespi.language.IModInfo;
Expand Down Expand Up @@ -58,9 +62,23 @@ public FMLModContainer(IModInfo info, List<String> entrypoints, ModFileScanData

for (var entrypoint : entrypoints) {
try {
var cls = Class.forName(layer, entrypoint);
modClasses.add(cls);
LOGGER.trace(LOADING, "Loaded modclass {} with {}", cls.getName(), cls.getClassLoader());
var dependencyData = modFileScanResults.getAnnotatedBy(DependsOn.class, ElementType.TYPE).filter(ad -> ad.clazz().getClassName().equals(entrypoint)).toList();
//ModList is set before containers are constructed
var loadedMods = ModList.get().getMods().stream().map(IModInfo::getModId).collect(Collectors.toSet());
List<String> deps;
if (dependencyData.isEmpty()) {
deps = Collections.emptyList();
} else deps = List.of((String[]) dependencyData.getFirst().annotationData().get("value"));

//Only load entrypoint class if all dependencies are in the ModList
if (loadedMods.containsAll(deps)) {
var cls = Class.forName(layer, entrypoint);
modClasses.add(cls);
LOGGER.trace(LOADING, "Loaded modclass {} with {}", cls.getName(), cls.getClassLoader());
} else {
var missingDeps = deps.stream().filter(dep -> !loadedMods.contains(dep)).toList();
LOGGER.trace(LOADING, "Didn't load modclass with name {} because of missing dependencies {}", entrypoint, missingDeps);
}
} catch (Throwable e) {
LOGGER.error(LOADING, "Failed to load class {}", entrypoint, e);
throw new ModLoadingException(ModLoadingIssue.error("fml.modloadingissue.failedtoloadmodclass").withCause(e).withAffectedMod(info));
Expand Down Expand Up @@ -113,7 +131,6 @@ protected void constructMod() {

// All arguments are found
constructor.newInstance(constructorArgs);

LOGGER.trace(LOADING, "Loaded mod instance {} of type {}", getModId(), modClass.getName());
} catch (Throwable e) {
if (e instanceof InvocationTargetException) e = e.getCause(); // exceptions thrown when a reflected method call throws are wrapped in an InvocationTargetException. However, this isn't useful for the end user who has to dig through the logs to find the actual cause.
Expand Down