mirror of
https://github.com/MinecraftForge/MinecraftForge.git
synced 2026-11-21 20:52:34 +00:00
Update to 1.17
Update to Official classnames Patchwork Make the game compile and run Merge in the new HUD overlay API Merge in the new render properties API PEEL Use Gradle 7.2 snapshot to fix eclipse integration bug in 7.1, Would use 7.0 but FG needs 7.1 for some reason. New FML installer Update to 1.17.1 Co-authored-by: LexManos <[email protected]> Co-authored-by: SizableShrimp <[email protected]> Co-authored-by: cpw <[email protected]> Co-authored-by: Curle <[email protected]> Co-authored-by: Unnoen <[email protected]> Co-authored-by: covers1624 <[email protected]> Co-authored-by: DaemonUmbra <[email protected]> Co-authored-by: gigaherz <[email protected]> Signed-off-by: SizableShrimp <[email protected]>
This commit is contained in:
1 parent
064ae6961b
commit
be5446b91c
1990 files changed
+35661
-37544
No files matched your search
@@ -1,86 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import net.minecraftforge.api.distmarker.Dist;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.forgespi.language.ModFileScanData;
|
||||
import net.minecraftforge.fml.loading.FMLEnvironment;
|
||||
import net.minecraftforge.fml.loading.moddiscovery.ModAnnotation;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.objectweb.asm.Type;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static net.minecraftforge.fml.Logging.LOADING;
|
||||
|
||||
/**
|
||||
* Automatic eventbus subscriber - reads {@link net.minecraftforge.fml.common.Mod.EventBusSubscriber}
|
||||
* annotations and passes the class instances to the {@link net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus}
|
||||
* defined by the annotation. Defaults to {@link MinecraftForge#EVENT_BUS}
|
||||
*/
|
||||
public class AutomaticEventSubscriber
|
||||
{
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
private static final Type AUTO_SUBSCRIBER = Type.getType(Mod.EventBusSubscriber.class);
|
||||
private static final Type MOD_TYPE = Type.getType(Mod.class);
|
||||
public static void inject(final ModContainer mod, final ModFileScanData scanData, final ClassLoader loader)
|
||||
{
|
||||
if (scanData == null) return;
|
||||
LOGGER.debug(LOADING,"Attempting to inject @EventBusSubscriber classes into the eventbus for {}", mod.getModId());
|
||||
List<ModFileScanData.AnnotationData> ebsTargets = scanData.getAnnotations().stream().
|
||||
filter(annotationData -> AUTO_SUBSCRIBER.equals(annotationData.getAnnotationType())).
|
||||
collect(Collectors.toList());
|
||||
Map<String, String> modids = scanData.getAnnotations().stream().
|
||||
filter(annotationData -> MOD_TYPE.equals(annotationData.getAnnotationType())).
|
||||
collect(Collectors.toMap(a -> a.getClassType().getClassName(), a -> (String)a.getAnnotationData().get("value")));
|
||||
|
||||
ebsTargets.forEach(ad -> {
|
||||
@SuppressWarnings("unchecked")
|
||||
final List<ModAnnotation.EnumHolder> sidesValue = (List<ModAnnotation.EnumHolder>)ad.getAnnotationData().
|
||||
getOrDefault("value", Arrays.asList(new ModAnnotation.EnumHolder(null, "CLIENT"), new ModAnnotation.EnumHolder(null, "DEDICATED_SERVER")));
|
||||
final EnumSet<Dist> sides = sidesValue.stream().map(eh -> Dist.valueOf(eh.getValue())).
|
||||
collect(Collectors.toCollection(() -> EnumSet.noneOf(Dist.class)));
|
||||
final String modId = (String)ad.getAnnotationData().getOrDefault("modid", modids.getOrDefault(ad.getClassType().getClassName(), mod.getModId()));
|
||||
final ModAnnotation.EnumHolder busTargetHolder = (ModAnnotation.EnumHolder)ad.getAnnotationData().getOrDefault("bus", new ModAnnotation.EnumHolder(null, "FORGE"));
|
||||
final Mod.EventBusSubscriber.Bus busTarget = Mod.EventBusSubscriber.Bus.valueOf(busTargetHolder.getValue());
|
||||
if (Objects.equals(mod.getModId(), modId) && sides.contains(FMLEnvironment.dist)) {
|
||||
try
|
||||
{
|
||||
LOGGER.debug(LOADING, "Auto-subscribing {} to {}", ad.getClassType().getClassName(), busTarget);
|
||||
busTarget.bus().get().register(Class.forName(ad.getClassType().getClassName(), true, loader));
|
||||
}
|
||||
catch (ClassNotFoundException e)
|
||||
{
|
||||
LOGGER.fatal(LOADING, "Failed to load mod class {} for @EventBusSubscriber annotation", ad.getClassType(), e);
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.Lists;
|
||||
import java.util.List;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import net.minecraft.resources.IResourceManager;
|
||||
import net.minecraft.resources.IResourceManagerReloadListener;
|
||||
import net.minecraftforge.client.ForgeHooksClient;
|
||||
import net.minecraftforge.versions.forge.ForgeVersion;
|
||||
import net.minecraftforge.versions.mcp.MCPVersion;
|
||||
|
||||
|
||||
public class BrandingControl
|
||||
{
|
||||
private static List<String> brandings;
|
||||
private static List<String> brandingsNoMC;
|
||||
private static List<String> overCopyrightBrandings;
|
||||
|
||||
private static void computeBranding()
|
||||
{
|
||||
if (brandings == null)
|
||||
{
|
||||
ImmutableList.Builder<String> brd = ImmutableList.builder();
|
||||
brd.add("Forge " + ForgeVersion.getVersion());
|
||||
brd.add("Minecraft " + MCPVersion.getMCVersion());
|
||||
brd.add("MCP " + MCPVersion.getMCPVersion());
|
||||
int tModCount = ModList.get().size();
|
||||
brd.add(ForgeI18n.parseMessage("fml.menu.loadingmods", tModCount));
|
||||
brandings = brd.build();
|
||||
brandingsNoMC = brandings.subList(1, brandings.size());
|
||||
}
|
||||
}
|
||||
|
||||
private static List<String> getBrandings(boolean includeMC, boolean reverse)
|
||||
{
|
||||
computeBranding();
|
||||
if (includeMC) {
|
||||
return reverse ? Lists.reverse(brandings) : brandings;
|
||||
} else {
|
||||
return reverse ? Lists.reverse(brandingsNoMC) : brandingsNoMC;
|
||||
}
|
||||
}
|
||||
|
||||
private static void computeOverCopyrightBrandings() {
|
||||
if (overCopyrightBrandings == null) {
|
||||
ImmutableList.Builder<String> brd = ImmutableList.builder();
|
||||
if (ForgeHooksClient.forgeStatusLine != null) brd.add(ForgeHooksClient.forgeStatusLine);
|
||||
overCopyrightBrandings = brd.build();
|
||||
}
|
||||
}
|
||||
|
||||
public static void forEachLine(boolean includeMC, boolean reverse, BiConsumer<Integer, String> lineConsumer) {
|
||||
final List<String> brandings = getBrandings(includeMC, reverse);
|
||||
IntStream.range(0, brandings.size()).boxed().forEachOrdered(idx -> lineConsumer.accept(idx, brandings.get(idx)));
|
||||
}
|
||||
|
||||
public static void forEachAboveCopyrightLine(BiConsumer<Integer, String> lineConsumer) {
|
||||
computeOverCopyrightBrandings();
|
||||
IntStream.range(0, overCopyrightBrandings.size()).boxed().forEachOrdered(idx->lineConsumer.accept(idx, overCopyrightBrandings.get(idx)));
|
||||
}
|
||||
|
||||
public static String getClientBranding() {
|
||||
return "forge";
|
||||
}
|
||||
|
||||
public static String getServerBranding() {
|
||||
return "forge";
|
||||
}
|
||||
|
||||
public static IResourceManagerReloadListener resourceManagerReloadListener() {
|
||||
return BrandingControl::onResourceManagerReload;
|
||||
}
|
||||
|
||||
private static void onResourceManagerReload(IResourceManager resourceManager) {
|
||||
brandings = null;
|
||||
brandingsNoMC = null;
|
||||
}
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import cpw.mods.modlauncher.log.TransformingThrowablePatternConverter;
|
||||
import joptsimple.internal.Strings;
|
||||
import net.minecraft.crash.CrashReport;
|
||||
import net.minecraft.crash.CrashReportCategory;
|
||||
import net.minecraftforge.fml.common.ICrashCallable;
|
||||
import net.minecraftforge.fml.loading.moddiscovery.ModFileInfo;
|
||||
import net.minecraftforge.forgespi.language.IModInfo;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import java.io.File;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
public class CrashReportExtender
|
||||
{
|
||||
private static List<ICrashCallable> crashCallables = Collections.synchronizedList(new ArrayList<>());
|
||||
|
||||
public static void enhanceCrashReport(final CrashReport crashReport, final CrashReportCategory category)
|
||||
{
|
||||
for (final ICrashCallable call: crashCallables)
|
||||
{
|
||||
category.setDetail(call.getLabel(), call);
|
||||
}
|
||||
}
|
||||
|
||||
public static void registerCrashCallable(ICrashCallable callable)
|
||||
{
|
||||
crashCallables.add(callable);
|
||||
}
|
||||
|
||||
public static void registerCrashCallable(String headerName, Callable<String> reportGenerator) {
|
||||
registerCrashCallable(new ICrashCallable() {
|
||||
@Override
|
||||
public String getLabel() {
|
||||
return headerName;
|
||||
}
|
||||
@Override
|
||||
public String call() throws Exception {
|
||||
return reportGenerator.call();
|
||||
}
|
||||
});
|
||||
}
|
||||
public static void addCrashReportHeader(StringBuilder stringbuilder, CrashReport crashReport)
|
||||
{
|
||||
}
|
||||
public static String generateEnhancedStackTrace(final Throwable throwable) {
|
||||
return generateEnhancedStackTrace(throwable, true);
|
||||
}
|
||||
|
||||
public static String generateEnhancedStackTrace(final StackTraceElement[] stacktrace) {
|
||||
final Throwable t = new Throwable();
|
||||
t.setStackTrace(stacktrace);
|
||||
return generateEnhancedStackTrace(t, false);
|
||||
}
|
||||
|
||||
public static String generateEnhancedStackTrace(final Throwable throwable, boolean header) {
|
||||
final String s = TransformingThrowablePatternConverter.generateEnhancedStackTrace(throwable);
|
||||
return header ? s : s.substring(s.indexOf(Strings.LINE_SEPARATOR));
|
||||
}
|
||||
|
||||
|
||||
public static File dumpModLoadingCrashReport(final Logger logger, final LoadingFailedException error, final File topLevelDir) {
|
||||
final CrashReport crashReport = CrashReport.forThrowable(new Exception("Mod Loading has failed"), "Mod loading error has occurred");
|
||||
error.getErrors().forEach(mle -> {
|
||||
final Optional<IModInfo> modInfo = Optional.ofNullable(mle.getModInfo());
|
||||
final CrashReportCategory category = crashReport.addCategory(modInfo.map(iModInfo -> "MOD "+iModInfo.getModId()).orElse("NO MOD INFO AVAILABLE"));
|
||||
Throwable cause = mle.getCause();
|
||||
int depth = 0;
|
||||
while (cause != null && cause.getCause() != null && cause.getCause()!=cause) {
|
||||
category.setDetail("Caused by "+(depth++), cause + generateEnhancedStackTrace(cause.getStackTrace()).replaceAll(Strings.LINE_SEPARATOR+"\t", "\n\t\t"));
|
||||
cause = cause.getCause();
|
||||
}
|
||||
if (cause != null)
|
||||
category.applyStackTrace(cause);
|
||||
category.setDetail("Mod File", () -> modInfo.map(IModInfo::getOwningFile).map(t->((ModFileInfo)t).getFile().getFileName()).orElse("NO FILE INFO"));
|
||||
category.setDetail("Failure message", () -> mle.getCleanMessage().replace("\n", "\n\t\t"));
|
||||
category.setDetail("Mod Version", () -> modInfo.map(IModInfo::getVersion).map(Object::toString).orElse("NO MOD INFO AVAILABLE"));
|
||||
category.setDetail("Mod Issue URL", () -> modInfo.map(IModInfo::getOwningFile).map(ModFileInfo.class::cast).flatMap(mfi->mfi.<String>getConfigElement("issueTrackerURL")).orElse("NOT PROVIDED"));
|
||||
category.setDetail("Exception message", Objects.toString(cause, "MISSING EXCEPTION MESSAGE"));
|
||||
});
|
||||
final File file1 = new File(topLevelDir, "crash-reports");
|
||||
final File file2 = new File(file1, "crash-" + (new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss")).format(new Date()) + "-fml.txt");
|
||||
if (crashReport.saveToFile(file2)) {
|
||||
logger.fatal("Crash report saved to {}", file2);
|
||||
} else {
|
||||
logger.fatal("Failed to save crash report");
|
||||
}
|
||||
System.out.print(crashReport.getFriendlyReport());
|
||||
return file2;
|
||||
}
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import java.util.Collections;
|
||||
import net.minecraft.util.registry.Bootstrap;
|
||||
import net.minecraftforge.common.data.ExistingFileHelper;
|
||||
import net.minecraftforge.fml.event.lifecycle.GatherDataEvent;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import java.io.File;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Collection;
|
||||
import java.util.Set;
|
||||
|
||||
public class DatagenModLoader {
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
private static GatherDataEvent.DataGeneratorConfig dataGeneratorConfig;
|
||||
private static ExistingFileHelper existingFileHelper;
|
||||
private static boolean runningDataGen;
|
||||
|
||||
public static boolean isRunningDataGen() {
|
||||
return runningDataGen;
|
||||
}
|
||||
|
||||
@Deprecated //TODO: Remove in 1.17
|
||||
public static void begin(final Set<String> mods, final Path path, final Collection<Path> inputs, Collection<Path> existingPacks, final boolean serverGenerators, final boolean clientGenerators, final boolean devToolGenerators, final boolean reportsGenerator, final boolean structureValidator, final boolean flat) {
|
||||
begin(mods, path, inputs, existingPacks, Collections.emptySet(), serverGenerators, clientGenerators, devToolGenerators, reportsGenerator, structureValidator, flat);
|
||||
}
|
||||
|
||||
@Deprecated //TODO: Remove in 1.17
|
||||
public static void begin(final Set<String> mods, final Path path, final Collection<Path> inputs, Collection<Path> existingPacks, Set<String> existingMods, final boolean serverGenerators, final boolean clientGenerators, final boolean devToolGenerators, final boolean reportsGenerator, final boolean structureValidator, final boolean flat) {
|
||||
begin(mods, path, inputs, existingPacks, existingMods, serverGenerators, clientGenerators, devToolGenerators, reportsGenerator, structureValidator, flat, null, null);
|
||||
}
|
||||
|
||||
public static void begin(final Set<String> mods, final Path path, final Collection<Path> inputs, Collection<Path> existingPacks, Set<String> existingMods, final boolean serverGenerators, final boolean clientGenerators, final boolean devToolGenerators, final boolean reportsGenerator, final boolean structureValidator, final boolean flat, final String assetIndex, final File assetsDir) {
|
||||
if (mods.contains("minecraft") && mods.size() == 1) return;
|
||||
LOGGER.info("Initializing Data Gatherer for mods {}", mods);
|
||||
runningDataGen = true;
|
||||
Bootstrap.bootStrap();
|
||||
dataGeneratorConfig = new GatherDataEvent.DataGeneratorConfig(mods, path, inputs, serverGenerators, clientGenerators, devToolGenerators, reportsGenerator, structureValidator, flat);
|
||||
ModLoader.get().gatherAndInitializeMods(ModWorkManager.syncExecutor(), ModWorkManager.parallelExecutor(), ()->{});
|
||||
if (!mods.contains("forge")) {
|
||||
//If we aren't generating data for forge, automatically add forge as an existing so mods can access forge's data
|
||||
existingMods.add("forge");
|
||||
}
|
||||
existingFileHelper = new ExistingFileHelper(existingPacks, existingMods, structureValidator, assetIndex, assetsDir);
|
||||
ModLoader.get().runEventGenerator(mc->new GatherDataEvent(mc, dataGeneratorConfig.makeGenerator(p->dataGeneratorConfig.isFlat() ? p : p.resolve(mc.getModId()), dataGeneratorConfig.getMods().contains(mc.getModId())), dataGeneratorConfig, existingFileHelper));
|
||||
dataGeneratorConfig.runAll();
|
||||
}
|
||||
}
|
||||
@@ -1,120 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import static net.minecraftforge.fml.Logging.LOADING;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentLinkedDeque;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import net.minecraftforge.fml.event.lifecycle.ParallelDispatchEvent;
|
||||
import org.apache.commons.lang3.time.StopWatch;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import com.google.common.base.Stopwatch;
|
||||
|
||||
import net.minecraftforge.forgespi.language.IModInfo;
|
||||
|
||||
/**
|
||||
* Utility for running code on the main launch thread at the next available
|
||||
* opportunity. There is no guaranteed order that work from various mods will be
|
||||
* run, but your own work will be run sequentially.
|
||||
* <p>
|
||||
* <strong>Use of this class after startup is not possible.</strong> At that
|
||||
* point, {@link IThreadListener} should be used instead.
|
||||
* <p>
|
||||
* Exceptions from tasks will be handled gracefully, causing a mod loading
|
||||
* error. Tasks that take egregiously long times to run will be logged.
|
||||
*/
|
||||
public class DeferredWorkQueue
|
||||
{
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
|
||||
private static Map<Class<? extends ParallelDispatchEvent>, DeferredWorkQueue> workQueues = new HashMap<>();
|
||||
|
||||
private final ModLoadingStage modLoadingStage;
|
||||
private final ConcurrentLinkedDeque<TaskInfo> tasks = new ConcurrentLinkedDeque<>();
|
||||
|
||||
public DeferredWorkQueue(final ModLoadingStage modLoadingStage, Class<? extends ParallelDispatchEvent> eventClass) {
|
||||
this.modLoadingStage = modLoadingStage;
|
||||
workQueues.put(eventClass, this);
|
||||
}
|
||||
|
||||
public static Optional<DeferredWorkQueue> lookup(Optional<Class<? extends ParallelDispatchEvent>> parallelClass) {
|
||||
return Optional.ofNullable(workQueues.get(parallelClass.orElse(null)));
|
||||
}
|
||||
|
||||
void runTasks() {
|
||||
if (tasks.isEmpty()) return;
|
||||
LOGGER.debug(LOADING, "Dispatching synchronous work after {}: {} jobs", modLoadingStage, tasks.size());
|
||||
StopWatch globalTimer = StopWatch.createStarted();
|
||||
tasks.forEach(t->makeRunnable(t, Runnable::run));
|
||||
LOGGER.debug(LOADING, "Synchronous work queue completed in {}", globalTimer);
|
||||
}
|
||||
|
||||
private static void makeRunnable(TaskInfo ti, Executor executor) {
|
||||
executor.execute(() -> {
|
||||
Stopwatch timer = Stopwatch.createStarted();
|
||||
ti.task.run();
|
||||
timer.stop();
|
||||
if (timer.elapsed(TimeUnit.SECONDS) >= 1) {
|
||||
LOGGER.warn(LOADING, "Mod '{}' took {} to run a deferred task.", ti.owner.getModId(), timer);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> enqueueWork(final IModInfo modInfo, final Runnable work) {
|
||||
return CompletableFuture.runAsync(work, r->tasks.add(new TaskInfo(modInfo, r)));
|
||||
}
|
||||
|
||||
public <T> CompletableFuture<T> enqueueWork(final IModInfo modInfo, final Supplier<T> work) {
|
||||
return CompletableFuture.supplyAsync(work, r->tasks.add(new TaskInfo(modInfo, r)));
|
||||
}
|
||||
|
||||
/**
|
||||
* DEPRECATED FOR REMOVAL. Use {@link ParallelDispatchEvent#enqueueWork(Runnable)} or {@link ParallelDispatchEvent#enqueueWork(Supplier)}
|
||||
*
|
||||
* @param workToEnqueue Runnable to execute later
|
||||
* @return a completable future
|
||||
*/
|
||||
@Deprecated
|
||||
public static CompletableFuture<Void> runLater(Runnable workToEnqueue) {
|
||||
return
|
||||
Optional.ofNullable(ModLoadingContext.get().getActiveContainer().modLoadingStage.getDeferredWorkQueue())
|
||||
.map(wq->wq.enqueueWork(ModLoadingContext.get().getActiveContainer().modInfo, workToEnqueue))
|
||||
.orElseGet(()->CompletableFuture.completedFuture(null));
|
||||
}
|
||||
|
||||
static class TaskInfo
|
||||
{
|
||||
public final IModInfo owner;
|
||||
public final Runnable task;
|
||||
|
||||
private TaskInfo(IModInfo owner, Runnable task) {
|
||||
this.owner = owner;
|
||||
this.task = task;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,276 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import net.minecraftforge.api.distmarker.Dist;
|
||||
import net.minecraftforge.fml.loading.FMLEnvironment;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.lang.invoke.SerializedLambda;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* Use to execute code conditionally based on sidedness.
|
||||
* <ul>
|
||||
* <li>When you want to call something on one side and return a result {@link #safeCallWhenOn(Dist, Supplier)}</li>
|
||||
* <li>When you want to call one thing on one side, another thing on the other and return a result {@link #safeRunForDist(Supplier, Supplier)}</li>
|
||||
* <li>When you want to run something on one side {@link #safeRunWhenOn(Dist, Supplier)}</li>
|
||||
* </ul>
|
||||
*/
|
||||
public final class DistExecutor
|
||||
{
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
private DistExecutor() {}
|
||||
|
||||
/**
|
||||
* Run the callable in the supplier only on the specified {@link Side}.
|
||||
* This method is NOT sided-safe and special care needs to be taken in code using this method that implicit class
|
||||
* loading is not triggered by the Callable.
|
||||
*
|
||||
* This method can cause unexpected ClassNotFound exceptions.
|
||||
*
|
||||
* Use {@link #safeCallWhenOn(Dist, Supplier)} where possible.
|
||||
*
|
||||
* @param dist The dist to run on
|
||||
* @param toRun A supplier of the callable to run (Supplier wrapper to ensure classloading only on the appropriate dist)
|
||||
* @param <T> The return type from the callable
|
||||
* @return The callable's result
|
||||
* @deprecated use {@link #safeCallWhenOn(Dist, Supplier)} instead. This remains for advanced use cases.
|
||||
*/
|
||||
@Deprecated
|
||||
public static <T> T callWhenOn(Dist dist, Supplier<Callable<T>> toRun) {
|
||||
return unsafeCallWhenOn(dist, toRun);
|
||||
}
|
||||
|
||||
public static <T> T unsafeCallWhenOn(Dist dist, Supplier<Callable<T>> toRun) {
|
||||
if (dist == FMLEnvironment.dist) {
|
||||
try
|
||||
{
|
||||
return toRun.get().call();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Call the SafeCallable when on the correct {@link Dist}.
|
||||
*
|
||||
* <strong>The lambda supplied here is required to be a method reference to a method defined in
|
||||
* another class, otherwise an invalid SafeReferent error will be thrown</strong>
|
||||
* @param dist the dist which this will run on
|
||||
* @param toRun the SafeCallable to run and return the result from
|
||||
* @param <T> The type of the SafeCallable
|
||||
* @return the result of the SafeCallable or null if on the wrong side
|
||||
*/
|
||||
public static <T> T safeCallWhenOn(Dist dist, Supplier<SafeCallable<T>> toRun) {
|
||||
validateSafeReferent(toRun);
|
||||
return callWhenOn(dist, toRun::get);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the supplied Runnable on the speicified side. Same warnings apply as {@link #callWhenOn(Dist, Supplier)}.
|
||||
*
|
||||
* This method can cause unexpected ClassNotFound exceptions.
|
||||
*
|
||||
* @see #callWhenOn(Dist, Supplier)
|
||||
* @param dist Dist to run this code on
|
||||
* @param toRun The code to run
|
||||
* @deprecated use {@link #safeRunWhenOn(Dist, Supplier)} where possible. Advanced uses only.
|
||||
*/
|
||||
@Deprecated
|
||||
public static void runWhenOn(Dist dist, Supplier<Runnable> toRun) {
|
||||
unsafeRunWhenOn(dist, toRun);
|
||||
}
|
||||
/**
|
||||
* Runs the supplied Runnable on the speicified side. Same warnings apply as {@link #unsafeCallWhenOn(Dist, Supplier)}.
|
||||
*
|
||||
* This method can cause unexpected ClassNotFoundException problems in common scenarios. Understand the pitfalls of
|
||||
* the way the class verifier works to load classes before using this.
|
||||
*
|
||||
* Use {@link #safeRunWhenOn(Dist, Supplier)} if you can.
|
||||
*
|
||||
* @see #unsafeCallWhenOn(Dist, Supplier)
|
||||
* @param dist Dist to run this code on
|
||||
* @param toRun The code to run
|
||||
*/
|
||||
public static void unsafeRunWhenOn(Dist dist, Supplier<Runnable> toRun) {
|
||||
if (dist == FMLEnvironment.dist) {
|
||||
toRun.get().run();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Call the supplied SafeRunnable when on the correct Dist.
|
||||
* @param dist The dist to run on
|
||||
* @param toRun The code to run
|
||||
*/
|
||||
public static void safeRunWhenOn(Dist dist, Supplier<SafeRunnable> toRun) {
|
||||
validateSafeReferent(toRun);
|
||||
if (dist == FMLEnvironment.dist) {
|
||||
toRun.get().run();
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Executes one of the two suppliers, based on which side is active.
|
||||
*
|
||||
* <p>
|
||||
* Example (replacement for old SidedProxy):<br/>
|
||||
* {@code Proxy p = DistExecutor.runForDist(()->ClientProxy::new, ()->ServerProxy::new);}
|
||||
*
|
||||
* NOTE: the double supplier is required to avoid classloading the secondary target.
|
||||
*
|
||||
* @param clientTarget The supplier supplier to run when on the {@link Dist#CLIENT}
|
||||
* @param serverTarget The supplier supplier to run when on the {@link Dist#DEDICATED_SERVER}
|
||||
* @param <T> The common type to return
|
||||
* @return The returned instance
|
||||
* @deprecated Use {@link #safeRunForDist(Supplier, Supplier)}
|
||||
*/
|
||||
@Deprecated
|
||||
public static <T> T runForDist(Supplier<Supplier<T>> clientTarget, Supplier<Supplier<T>> serverTarget) {
|
||||
return unsafeRunForDist(clientTarget, serverTarget);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unsafe version of {@link #safeRunForDist(Supplier, Supplier)}. Use only when you know what you're doing
|
||||
* and understand why the verifier can cause unexpected ClassNotFoundException crashes even when code is apparently
|
||||
* not sided. Ensure you test both sides fully to be confident in using this.
|
||||
*
|
||||
* @param clientTarget The supplier supplier to run when on the {@link Dist#CLIENT}
|
||||
* @param serverTarget The supplier supplier to run when on the {@link Dist#DEDICATED_SERVER}
|
||||
* @param <T> The common type to return
|
||||
* @return The returned instance
|
||||
*/
|
||||
public static <T> T unsafeRunForDist(Supplier<Supplier<T>> clientTarget, Supplier<Supplier<T>> serverTarget) {
|
||||
switch (FMLEnvironment.dist)
|
||||
{
|
||||
case CLIENT:
|
||||
return clientTarget.get().get();
|
||||
case DEDICATED_SERVER:
|
||||
return serverTarget.get().get();
|
||||
default:
|
||||
throw new IllegalArgumentException("UNSIDED?");
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Executes one of the two suppliers, based on which side is active.
|
||||
*
|
||||
* <p>
|
||||
* Example (replacement for old SidedProxy):<br/>
|
||||
* {@code Proxy p = DistExecutor.safeRunForDist(()->ClientProxy::new, ()->ServerProxy::new);}
|
||||
*
|
||||
* NOTE: the double supplier is required to avoid classloading the secondary target.
|
||||
*
|
||||
* @param clientTarget The supplier supplier to run when on the {@link Dist#CLIENT}
|
||||
* @param serverTarget The supplier supplier to run when on the {@link Dist#DEDICATED_SERVER}
|
||||
* @param <T> The common type to return
|
||||
* @return The returned instance
|
||||
*/
|
||||
public static <T> T safeRunForDist(Supplier<SafeSupplier<T>> clientTarget, Supplier<SafeSupplier<T>> serverTarget) {
|
||||
validateSafeReferent(clientTarget);
|
||||
validateSafeReferent(serverTarget);
|
||||
switch (FMLEnvironment.dist)
|
||||
{
|
||||
case CLIENT:
|
||||
return clientTarget.get().get();
|
||||
case DEDICATED_SERVER:
|
||||
return serverTarget.get().get();
|
||||
default:
|
||||
throw new IllegalArgumentException("UNSIDED?");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A safe referent. This will assert that it is being called via a separated class method reference. This will
|
||||
* avoid the common pitfalls of {@link #callWhenOn(Dist, Supplier)} above.
|
||||
*
|
||||
* SafeReferents assert that they are defined as a separate method outside the scope of the calling class.
|
||||
*
|
||||
* <strong>Implementations need to be defined in a separate class to the referring site, with appropriate
|
||||
* visibility to be accessible at the callsite (generally, avoid private methods).</strong>
|
||||
*
|
||||
* <p>
|
||||
* Valid:<br/>
|
||||
*
|
||||
* {@code DistExecutor.safeCallWhenOn(Dist.CLIENT, ()->AnotherClass::clientOnlyMethod);}
|
||||
*
|
||||
* <p>
|
||||
* Invalid:<br/>
|
||||
*
|
||||
* {@code DistExecutor.safeCallWhenOn(Dist.CLIENT, ()->()->Minecraft.getInstance().world);}
|
||||
*/
|
||||
public interface SafeReferent {}
|
||||
|
||||
/**
|
||||
* SafeCallable version of {@link SafeReferent}.
|
||||
* @see SafeReferent
|
||||
* @param <T> The return type of the Callable
|
||||
*/
|
||||
public interface SafeCallable<T> extends SafeReferent, Callable<T>, Serializable {}
|
||||
|
||||
/**
|
||||
* SafeSupplier version of {@link SafeReferent}
|
||||
* @param <T> The return type of the Supplier
|
||||
*/
|
||||
public interface SafeSupplier<T> extends SafeReferent, Supplier<T>, Serializable {}
|
||||
|
||||
/**
|
||||
* SafeRunnable version of {@link SafeReferent}
|
||||
*/
|
||||
public interface SafeRunnable extends SafeReferent, Runnable, Serializable {}
|
||||
|
||||
private static final void validateSafeReferent(Supplier<? extends SafeReferent> safeReferentSupplier) {
|
||||
if (FMLEnvironment.production) return;
|
||||
final SafeReferent setter;
|
||||
try {
|
||||
setter = safeReferentSupplier.get();
|
||||
} catch (Exception e) {
|
||||
// Typically a class cast exception, just return out, expected.
|
||||
return;
|
||||
}
|
||||
|
||||
for (Class<?> cl = setter.getClass(); cl != null; cl = cl.getSuperclass()) {
|
||||
try {
|
||||
Method m = cl.getDeclaredMethod("writeReplace");
|
||||
m.setAccessible(true);
|
||||
Object replacement = m.invoke(setter);
|
||||
if (!(replacement instanceof SerializedLambda))
|
||||
break;// custom interface implementation
|
||||
SerializedLambda l = (SerializedLambda) replacement;
|
||||
if (Objects.equals(l.getCapturingClass(), l.getImplClass())) {
|
||||
LOGGER.fatal("Detected unsafe referent usage, please view the code at {}",Thread.currentThread().getStackTrace()[3]);
|
||||
throw new RuntimeException("Unsafe Referent usage found in safe referent method");
|
||||
}
|
||||
} catch (NoSuchMethodException e) {
|
||||
} catch (IllegalAccessException | InvocationTargetException e) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.BiPredicate;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.screen.Screen;
|
||||
import net.minecraft.resources.IResourcePack;
|
||||
import net.minecraftforge.fml.packs.ModFileResourcePack;
|
||||
|
||||
public class ExtensionPoint<T>
|
||||
{
|
||||
public static final ExtensionPoint<BiFunction<Minecraft, Screen, Screen>> CONFIGGUIFACTORY = new ExtensionPoint<>();
|
||||
public static final ExtensionPoint<BiFunction<Minecraft, ModFileResourcePack, IResourcePack>> RESOURCEPACK = new ExtensionPoint<>();
|
||||
/**
|
||||
* Compatibility display test for the mod.
|
||||
* Used for displaying compatibility with remote servers with the same mod, and on disk saves.
|
||||
*
|
||||
* The supplier provides my "local" version for sending across the network or writing to disk
|
||||
* The predicate tests the version from a remote instance or save for acceptability (Boolean is true for network, false for local save)
|
||||
* and returns true if the version is compatible.
|
||||
*
|
||||
* <p>Return {@link net.minecraftforge.fml.network.FMLNetworkConstants#IGNORESERVERONLY} in the supplier, if you wish to be ignored
|
||||
* as a server side only mod.</p>
|
||||
* <p>Return true in the predicate for all values of the input string (when network boolean is true) if you are client side,
|
||||
* and don't care about matching any potential server version.</p>
|
||||
*
|
||||
* <p>
|
||||
* Examples: A server only mod
|
||||
*
|
||||
* <code><pre>
|
||||
* registerExtensionPoint(DISPLAYTEST, ()->Pair.of(
|
||||
* ()->FMLNetworkConstants.IGNORESERVERONLY, // ignore me, I'm a server only mod
|
||||
* (s,b)->true // i accept anything from the server or the save, if I'm asked
|
||||
* )
|
||||
* </pre></code>
|
||||
* </p>
|
||||
* <p>
|
||||
* Examples: A client only mod
|
||||
* <code><pre>
|
||||
* registerExtensionPoint(DISPLAYTEST, ()->Pair.of(
|
||||
* ()->"anything. i don't care", // if i'm actually on the server, this string is sent but i'm a client only mod, so it won't be
|
||||
* (remoteversionstring,networkbool)->networkbool // i accept anything from the server, by returning true if it's asking about the server
|
||||
* )
|
||||
* </pre></code>
|
||||
* </p>
|
||||
*
|
||||
*/
|
||||
public static final ExtensionPoint<Pair<Supplier<String>, BiPredicate<String, Boolean>>> DISPLAYTEST = new ExtensionPoint<>();
|
||||
|
||||
private Class<T> type;
|
||||
|
||||
private ExtensionPoint() {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,138 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
import com.google.common.collect.Multimap;
|
||||
import net.minecraft.nbt.CompoundNBT;
|
||||
import net.minecraft.nbt.ListNBT;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import net.minecraft.world.storage.IServerConfiguration;
|
||||
import net.minecraft.world.storage.SaveFormat;
|
||||
import net.minecraftforge.registries.ForgeRegistry;
|
||||
import net.minecraftforge.registries.GameData;
|
||||
import net.minecraftforge.registries.RegistryManager;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.apache.logging.log4j.Marker;
|
||||
import org.apache.logging.log4j.MarkerManager;
|
||||
|
||||
/**
|
||||
* @author cpw
|
||||
*
|
||||
*/
|
||||
public final class FMLWorldPersistenceHook implements WorldPersistenceHooks.WorldPersistenceHook
|
||||
{
|
||||
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
private static final Marker WORLDPERSISTENCE = MarkerManager.getMarker("WP");
|
||||
|
||||
@Override
|
||||
public String getModId()
|
||||
{
|
||||
return "fml";
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompoundNBT getDataForWriting(SaveFormat.LevelSave levelSave, IServerConfiguration serverInfo)
|
||||
{
|
||||
CompoundNBT fmlData = new CompoundNBT();
|
||||
ListNBT modList = new ListNBT();
|
||||
ModList.get().getMods().forEach(mi->
|
||||
{
|
||||
final CompoundNBT mod = new CompoundNBT();
|
||||
mod.putString("ModId", mi.getModId());
|
||||
mod.putString("ModVersion", MavenVersionStringHelper.artifactVersionToString(mi.getVersion()));
|
||||
modList.add(mod);
|
||||
});
|
||||
fmlData.put("LoadingModList", modList);
|
||||
|
||||
CompoundNBT registries = new CompoundNBT();
|
||||
fmlData.put("Registries", registries);
|
||||
LOGGER.debug(WORLDPERSISTENCE,"Gathering id map for writing to world save {}", serverInfo.getLevelName());
|
||||
|
||||
for (Map.Entry<ResourceLocation, ForgeRegistry.Snapshot> e : RegistryManager.ACTIVE.takeSnapshot(true).entrySet())
|
||||
{
|
||||
registries.put(e.getKey().toString(), e.getValue().write());
|
||||
}
|
||||
LOGGER.debug(WORLDPERSISTENCE,"ID Map collection complete {}", serverInfo.getLevelName());
|
||||
return fmlData;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void readData(SaveFormat.LevelSave levelSave, IServerConfiguration serverInfo, CompoundNBT tag)
|
||||
{
|
||||
if (tag.contains("LoadingModList"))
|
||||
{
|
||||
ListNBT modList = tag.getList("LoadingModList", (byte)10);
|
||||
for (int i = 0; i < modList.size(); i++)
|
||||
{
|
||||
CompoundNBT mod = modList.getCompound(i);
|
||||
String modId = mod.getString("ModId");
|
||||
if (Objects.equals("minecraft", modId)) {
|
||||
continue;
|
||||
}
|
||||
String modVersion = mod.getString("ModVersion");
|
||||
Optional<? extends ModContainer> container = ModList.get().getModContainerById(modId);
|
||||
if (!container.isPresent())
|
||||
{
|
||||
LOGGER.error(WORLDPERSISTENCE,"This world was saved with mod {} which appears to be missing, things may not work well", modId);
|
||||
continue;
|
||||
}
|
||||
if (!Objects.equals(modVersion, MavenVersionStringHelper.artifactVersionToString(container.get().getModInfo().getVersion())))
|
||||
{
|
||||
LOGGER.warn(WORLDPERSISTENCE,"This world was saved with mod {} version {} and it is now at version {}, things may not work well", modId, modVersion, MavenVersionStringHelper.artifactVersionToString(container.get().getModInfo().getVersion()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Multimap<ResourceLocation, ResourceLocation> failedElements = null;
|
||||
|
||||
if (tag.contains("Registries")) // 1.8, genericed out the 'registries' list
|
||||
{
|
||||
Map<ResourceLocation, ForgeRegistry.Snapshot> snapshot = new HashMap<>();
|
||||
CompoundNBT regs = tag.getCompound("Registries");
|
||||
for (String key : regs.getAllKeys())
|
||||
{
|
||||
snapshot.put(new ResourceLocation(key), ForgeRegistry.Snapshot.read(regs.getCompound(key)));
|
||||
}
|
||||
failedElements = GameData.injectSnapshot(snapshot, true, true);
|
||||
}
|
||||
|
||||
if (failedElements != null && !failedElements.isEmpty())
|
||||
{
|
||||
StringBuilder buf = new StringBuilder();
|
||||
buf.append("Forge Mod Loader could not load this save.\n\n")
|
||||
.append("There are ").append(failedElements.size()).append(" unassigned registry entries in this save.\n")
|
||||
.append("You will not be able to load until they are present again.\n\n");
|
||||
|
||||
failedElements.asMap().forEach((name, entries) ->
|
||||
{
|
||||
buf.append("Missing ").append(name).append(":\n");
|
||||
entries.forEach(rl -> buf.append(" ").append(rl).append("\n"));
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,142 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import com.google.common.base.CharMatcher;
|
||||
import net.minecraftforge.fml.loading.StringUtils;
|
||||
import net.minecraftforge.fml.loading.moddiscovery.ModInfo;
|
||||
import org.apache.commons.lang3.text.ExtendedMessageFormat;
|
||||
import org.apache.commons.lang3.text.FormatFactory;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import java.text.FieldPosition;
|
||||
import java.text.Format;
|
||||
import java.text.ParsePosition;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static net.minecraftforge.fml.Logging.CORE;
|
||||
|
||||
//TODO, this should be re-evaluated now that ITextComponents are passed everywhere instaed of strings.
|
||||
public class ForgeI18n {
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
// From FontRenderer.renderCharAtPos
|
||||
private static final String ALLOWED_CHARS = "\u00c0\u00c1\u00c2\u00c8\u00ca\u00cb\u00cd\u00d3\u00d4\u00d5\u00da\u00df\u00e3\u00f5\u011f\u0130\u0131\u0152\u0153\u015e\u015f\u0174\u0175\u017e\u0207\u0000\u0000\u0000\u0000\u0000\u0000\u0000 !\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u0000\u00c7\u00fc\u00e9\u00e2\u00e4\u00e0\u00e5\u00e7\u00ea\u00eb\u00e8\u00ef\u00ee\u00ec\u00c4\u00c5\u00c9\u00e6\u00c6\u00f4\u00f6\u00f2\u00fb\u00f9\u00ff\u00d6\u00dc\u00f8\u00a3\u00d8\u00d7\u0192\u00e1\u00ed\u00f3\u00fa\u00f1\u00d1\u00aa\u00ba\u00bf\u00ae\u00ac\u00bd\u00bc\u00a1\u00ab\u00bb\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255d\u255c\u255b\u2510\u2514\u2534\u252c\u251c\u2500\u253c\u255e\u255f\u255a\u2554\u2569\u2566\u2560\u2550\u256c\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256b\u256a\u2518\u250c\u2588\u2584\u258c\u2590\u2580\u03b1\u03b2\u0393\u03c0\u03a3\u03c3\u03bc\u03c4\u03a6\u0398\u03a9\u03b4\u221e\u2205\u2208\u2229\u2261\u00b1\u2265\u2264\u2320\u2321\u00f7\u2248\u00b0\u2219\u00b7\u221a\u207f\u00b2\u25a0\u0000";
|
||||
private static final CharMatcher DISALLOWED_CHAR_MATCHER = CharMatcher.anyOf(ALLOWED_CHARS).negate();
|
||||
private static Map<String,String> i18n;
|
||||
private static Map<String,FormatFactory> customFactories;
|
||||
// From StringUtils
|
||||
private static final Pattern PATTERN_CONTROL_CODE = Pattern.compile("(?i)\\u00A7[0-9A-FK-OR]");
|
||||
|
||||
|
||||
|
||||
static {
|
||||
customFactories = new HashMap<>();
|
||||
// {0,modinfo,id} -> modid from ModInfo object; {0,modinfo,name} -> displayname from ModInfo object
|
||||
customFactories.put("modinfo", (name, formatString, locale) -> new CustomReadOnlyFormat((stringBuffer, objectToParse) -> parseModInfo(formatString, stringBuffer, objectToParse)));
|
||||
// {0,lower} -> lowercase supplied string
|
||||
customFactories.put("lower", (name, formatString, locale) -> new CustomReadOnlyFormat((stringBuffer, objectToParse) -> stringBuffer.append(StringUtils.toLowerCase(String.valueOf(objectToParse)))));
|
||||
// {0,upper> -> uppercase supplied string
|
||||
customFactories.put("upper", (name, formatString, locale) -> new CustomReadOnlyFormat((stringBuffer, objectToParse) -> stringBuffer.append(StringUtils.toUpperCase(String.valueOf(objectToParse)))));
|
||||
// {0,exc,cls} -> class of exception; {0,exc,msg} -> message from exception
|
||||
customFactories.put("exc", (name, formatString, locale) -> new CustomReadOnlyFormat((stringBuffer, objectToParse) -> parseException(formatString, stringBuffer, objectToParse)));
|
||||
// {0,vr} -> transform VersionRange into cleartext string using fml.messages.version.restriction.* strings
|
||||
customFactories.put("vr", (name, formatString, locale) -> new CustomReadOnlyFormat(((stringBuffer, o) -> MavenVersionStringHelper.parseVersionRange(formatString, stringBuffer, o))));
|
||||
// {0,i18n,fml.message} -> pass object to i18n string 'fml.message'
|
||||
customFactories.put("i18n", (name, formatString, locale) -> new CustomReadOnlyFormat((stringBuffer, o) -> stringBuffer.append(ForgeI18n.parseMessage(formatString, o))));
|
||||
// {0,ornull,fml.absent} -> append String value of o, or i18n string 'fml.absent' (message format transforms nulls into the string literal "null")
|
||||
customFactories.put("ornull", ((name, formatString, locale) -> new CustomReadOnlyFormat((stringBuffer, o) -> stringBuffer.append(Objects.equals(String.valueOf(o),"null") ? ForgeI18n.parseMessage(formatString) : String.valueOf(o)))));
|
||||
}
|
||||
|
||||
private static void parseException(final String formatString, final StringBuffer stringBuffer, final Object objectToParse) {
|
||||
Throwable t = (Throwable) objectToParse;
|
||||
if (Objects.equals(formatString, "msg")) {
|
||||
stringBuffer.append(t.getClass().getName()).append(": ").append(t.getMessage());
|
||||
} else if (Objects.equals(formatString, "cls")) {
|
||||
stringBuffer.append(t.getClass().getName());
|
||||
}
|
||||
}
|
||||
|
||||
private static void parseModInfo(final String formatString, final StringBuffer stringBuffer, final Object modInfo) {
|
||||
final ModInfo info = (ModInfo) modInfo;
|
||||
if (Objects.equals(formatString, "id")) {
|
||||
stringBuffer.append(info.getModId());
|
||||
} else if (Objects.equals(formatString, "name")) {
|
||||
stringBuffer.append(info.getDisplayName());
|
||||
}
|
||||
}
|
||||
|
||||
public static String getPattern(final String patternName) {
|
||||
return i18n == null ? patternName : i18n.getOrDefault(patternName, patternName);
|
||||
}
|
||||
|
||||
public static void loadLanguageData(final Map<String, String> properties) {
|
||||
LOGGER.debug(CORE,"Loading I18N data entries: {}", properties.size());
|
||||
i18n = properties;
|
||||
}
|
||||
|
||||
public static String parseMessage(final String i18nMessage, Object... args) {
|
||||
final String pattern = getPattern(i18nMessage);
|
||||
try {
|
||||
return parseFormat(pattern, args);
|
||||
} catch (IllegalArgumentException e) {
|
||||
LOGGER.error(CORE,"Illegal format found `{}`", pattern);
|
||||
return pattern;
|
||||
}
|
||||
}
|
||||
|
||||
public static String parseFormat(final String format, final Object... args) {
|
||||
final ExtendedMessageFormat extendedMessageFormat = new ExtendedMessageFormat(format, customFactories);
|
||||
return extendedMessageFormat.format(args);
|
||||
}
|
||||
|
||||
public static String stripSpecialChars(String message)
|
||||
{
|
||||
// We can't handle many unicode points in the splash renderer
|
||||
return DISALLOWED_CHAR_MATCHER.removeFrom(stripControlCodes(message));
|
||||
}
|
||||
|
||||
public static String stripControlCodes(String text) {
|
||||
return PATTERN_CONTROL_CODE.matcher(text).replaceAll("");
|
||||
}
|
||||
|
||||
public static class CustomReadOnlyFormat extends Format {
|
||||
private final BiConsumer<StringBuffer, Object> formatter;
|
||||
|
||||
CustomReadOnlyFormat(final BiConsumer<StringBuffer, Object> formatter) {
|
||||
this.formatter = formatter;
|
||||
}
|
||||
|
||||
@Override
|
||||
public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) {
|
||||
formatter.accept(toAppendTo, obj);
|
||||
return toAppendTo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object parseObject(final String source, final ParsePosition pos) {
|
||||
throw new UnsupportedOperationException("Parsing is not supported");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,182 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.Spliterator;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Stream;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
public class InterModComms
|
||||
{
|
||||
public static final class IMCMessage {
|
||||
private final String modId;
|
||||
private final String method;
|
||||
private final String senderModId;
|
||||
private final Supplier<?> thing;
|
||||
|
||||
IMCMessage(String senderModId, String modId, String method, Supplier<?> thing)
|
||||
{
|
||||
this.senderModId = senderModId;
|
||||
this.modId = modId;
|
||||
this.method = method;
|
||||
this.thing = thing;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return The modid of the sender. This is supplied by the caller, or by the active mod container context.
|
||||
* Consider it unreliable.
|
||||
*/
|
||||
public final String getSenderModId() {
|
||||
return this.senderModId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return The modid being sent to.
|
||||
*/
|
||||
public final String getModId() {
|
||||
return this.modId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return The method being sent to.
|
||||
*/
|
||||
public final String getMethod() {
|
||||
return this.method;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param <T> The type of the message.
|
||||
* @return A {@link Supplier} of the message.
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public final <T> Supplier<T> getMessageSupplier() {
|
||||
return (Supplier<T>)this.thing;
|
||||
}
|
||||
}
|
||||
|
||||
private static ConcurrentMap<String, ConcurrentLinkedQueue<IMCMessage>> containerQueues = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* Send IMC to remote. Sender will default to the active modcontainer, or minecraft if not.
|
||||
*
|
||||
* @param modId the mod id to send to
|
||||
* @param method the method name to send
|
||||
* @param thing the thing associated with the method name
|
||||
* @return true if the message was enqueued for sending (the target modid is loaded)
|
||||
*/
|
||||
public static boolean sendTo(final String modId, final String method, final Supplier<?> thing) {
|
||||
if (!ModList.get().isLoaded(modId)) return false;
|
||||
containerQueues.computeIfAbsent(modId, k->new ConcurrentLinkedQueue<>()).add(new IMCMessage(ModLoadingContext.get().getActiveContainer().getModId(), modId, method, thing));
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send IMC to remote.
|
||||
*
|
||||
* @param senderModId the mod id you are sending from
|
||||
* @param modId the mod id to send to
|
||||
* @param method the method name to send
|
||||
* @param thing the thing associated with the method name
|
||||
* @return true if the message was enqueued for sending (the target modid is loaded)
|
||||
*/
|
||||
public static boolean sendTo(final String senderModId, final String modId, final String method, final Supplier<?> thing) {
|
||||
if (!ModList.get().isLoaded(modId)) return false;
|
||||
containerQueues.computeIfAbsent(modId, k->new ConcurrentLinkedQueue<>()).add(new IMCMessage(senderModId, modId, method, thing));
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve pending messages for your modid. Use the predicate to filter the method name.
|
||||
*
|
||||
* @param modId the modid you are querying for
|
||||
* @param methodMatcher a predicate for the method you are interested in
|
||||
* @return All messages passing the supplied method predicate
|
||||
*/
|
||||
public static Stream<IMCMessage> getMessages(final String modId, final Predicate<String> methodMatcher) {
|
||||
ConcurrentLinkedQueue<IMCMessage> queue = containerQueues.get(modId);
|
||||
if (queue == null) return Stream.empty();
|
||||
return StreamSupport.stream(new QueueFilteringSpliterator(queue, methodMatcher), false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve all message for your modid.
|
||||
*
|
||||
* @param modId the modid you are querying for
|
||||
* @return All messages
|
||||
*/
|
||||
public static Stream<IMCMessage> getMessages(final String modId) {
|
||||
return getMessages(modId, s->Boolean.TRUE);
|
||||
}
|
||||
|
||||
private static class QueueFilteringSpliterator implements Spliterator<IMCMessage>
|
||||
{
|
||||
private final ConcurrentLinkedQueue<IMCMessage> queue;
|
||||
private final Predicate<String> methodFilter;
|
||||
private final Iterator<IMCMessage> iterator;
|
||||
|
||||
public QueueFilteringSpliterator(final ConcurrentLinkedQueue<IMCMessage> queue, final Predicate<String> methodFilter) {
|
||||
this.queue = queue;
|
||||
this.iterator = queue.iterator();
|
||||
this.methodFilter = methodFilter;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int characteristics() {
|
||||
return Spliterator.CONCURRENT | Spliterator.NONNULL | Spliterator.ORDERED;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long estimateSize() {
|
||||
return queue.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean tryAdvance(final Consumer<? super IMCMessage> action)
|
||||
{
|
||||
IMCMessage next;
|
||||
do
|
||||
{
|
||||
if (!iterator.hasNext())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
next = this.iterator.next();
|
||||
}
|
||||
while (!methodFilter.test(next.method));
|
||||
action.accept(next);
|
||||
this.iterator.remove();
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Spliterator<IMCMessage> trySplit() {
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class LoadingFailedException extends RuntimeException {
|
||||
private final List<ModLoadingException> loadingExceptions;
|
||||
|
||||
public LoadingFailedException(final List<ModLoadingException> loadingExceptions) {
|
||||
this.loadingExceptions = loadingExceptions;
|
||||
}
|
||||
|
||||
public List<ModLoadingException> getErrors() {
|
||||
return this.loadingExceptions;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMessage() {
|
||||
return "Loading errors encountered: " + this.loadingExceptions.stream().map(ModLoadingException::getMessage).collect(Collectors.joining(",\n\t", "[\n\t", "\n]"));
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import org.apache.logging.log4j.Marker;
|
||||
import org.apache.logging.log4j.MarkerManager;
|
||||
|
||||
public class Logging
|
||||
{
|
||||
// Lots of markers
|
||||
public static final Marker CORE = MarkerManager.getMarker("CORE");
|
||||
public static final Marker LOADING = MarkerManager.getMarker("LOADING");
|
||||
public static final Marker SCAN = MarkerManager.getMarker("SCAN");
|
||||
public static final Marker SPLASH = MarkerManager.getMarker("SPLASH");
|
||||
public static final Marker CAPABILITIES = MarkerManager.getMarker("CAPABILITIES");
|
||||
public static final Marker MODELLOADING = MarkerManager.getMarker("MODELLOADING");
|
||||
|
||||
// --log CORE:+DEBUG,SCAN:-OFF
|
||||
// forge log debug 5
|
||||
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
public enum LogicalSide
|
||||
{
|
||||
CLIENT, SERVER;
|
||||
|
||||
/**
|
||||
* @return if the logical side is a server.
|
||||
*/
|
||||
public boolean isServer()
|
||||
{
|
||||
return !isClient();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return if the logical side is a client.
|
||||
*/
|
||||
public boolean isClient()
|
||||
{
|
||||
return this == CLIENT;
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.world.World;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public enum LogicalSidedProvider
|
||||
{
|
||||
WORKQUEUE((c)->c.get(), (s)->s.get()),
|
||||
INSTANCE((c)->c.get(), (s)->s.get()),
|
||||
CLIENTWORLD((c)-> Optional.<World>of(c.get().level), (s)->Optional.<World>empty())
|
||||
;
|
||||
private static Supplier<Minecraft> client;
|
||||
private static Supplier<MinecraftServer> server;
|
||||
|
||||
LogicalSidedProvider(Function<Supplier<Minecraft>, ?> clientSide, Function<Supplier<MinecraftServer>, ?> serverSide)
|
||||
{
|
||||
this.clientSide = clientSide;
|
||||
this.serverSide = serverSide;
|
||||
}
|
||||
|
||||
public static void setClient(Supplier<Minecraft> client)
|
||||
{
|
||||
LogicalSidedProvider.client = client;
|
||||
}
|
||||
public static void setServer(Supplier<MinecraftServer> server)
|
||||
{
|
||||
LogicalSidedProvider.server = server;
|
||||
}
|
||||
|
||||
|
||||
private final Function<Supplier<Minecraft>, ?> clientSide;
|
||||
private final Function<Supplier<MinecraftServer>, ?> serverSide;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> T get(final LogicalSide side) {
|
||||
return (T)(side==LogicalSide.CLIENT ? clientSide.apply(client) : serverSide.apply(server));
|
||||
}
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import org.apache.maven.artifact.versioning.ArtifactVersion;
|
||||
import org.apache.maven.artifact.versioning.Restriction;
|
||||
import org.apache.maven.artifact.versioning.VersionRange;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class MavenVersionStringHelper {
|
||||
public static String artifactVersionToString(final ArtifactVersion artifactVersion) {
|
||||
return artifactVersion.toString();
|
||||
}
|
||||
|
||||
public static String versionRangeToString(final VersionRange range) {
|
||||
return range.getRestrictions().stream().map(MavenVersionStringHelper::restrictionToString).collect(Collectors.joining(", "));
|
||||
}
|
||||
|
||||
public static String restrictionToString(final Restriction restriction) {
|
||||
if ( restriction.getLowerBound() == null && restriction.getUpperBound() == null )
|
||||
{
|
||||
return ForgeI18n.parseMessage("fml.messages.version.restriction.any");
|
||||
}
|
||||
else if ( restriction.getLowerBound() != null && restriction.getUpperBound() != null )
|
||||
{
|
||||
if (Objects.equals(artifactVersionToString(restriction.getLowerBound()), artifactVersionToString(restriction.getUpperBound())))
|
||||
{
|
||||
return artifactVersionToString(restriction.getLowerBound());
|
||||
}
|
||||
else
|
||||
{
|
||||
if (restriction.isLowerBoundInclusive() && restriction.isUpperBoundInclusive())
|
||||
{
|
||||
return ForgeI18n.parseMessage("fml.messages.version.restriction.bounded.inclusive", restriction.getLowerBound(), restriction.getUpperBound());
|
||||
}
|
||||
else if (restriction.isLowerBoundInclusive())
|
||||
{
|
||||
return ForgeI18n.parseMessage("fml.messages.version.restriction.bounded.upperexclusive", restriction.getLowerBound(), restriction.getUpperBound());
|
||||
}
|
||||
else if (restriction.isUpperBoundInclusive())
|
||||
{
|
||||
return ForgeI18n.parseMessage("fml.messages.version.restriction.bounded.lowerexclusive", restriction.getLowerBound(), restriction.getUpperBound());
|
||||
}
|
||||
else
|
||||
{
|
||||
return ForgeI18n.parseMessage("fml.messages.version.restriction.bounded.exclusive", restriction.getLowerBound(), restriction.getUpperBound());
|
||||
}
|
||||
}
|
||||
}
|
||||
else if ( restriction.getLowerBound() != null )
|
||||
{
|
||||
if ( restriction.isLowerBoundInclusive() )
|
||||
{
|
||||
return ForgeI18n.parseMessage("fml.messages.version.restriction.lower.inclusive", restriction.getLowerBound());
|
||||
}
|
||||
else
|
||||
{
|
||||
return ForgeI18n.parseMessage("fml.messages.version.restriction.lower.exclusive", restriction.getLowerBound());
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if ( restriction.isUpperBoundInclusive() )
|
||||
{
|
||||
return ForgeI18n.parseMessage("fml.messages.version.restriction.upper.inclusive", restriction.getUpperBound());
|
||||
}
|
||||
else
|
||||
{
|
||||
return ForgeI18n.parseMessage("fml.messages.version.restriction.upper.exclusive", restriction.getUpperBound());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void parseVersionRange(final String formatString, final StringBuffer stringBuffer, final Object range) {
|
||||
stringBuffer.append(versionRangeToString((VersionRange) range));
|
||||
}
|
||||
}
|
||||
@@ -1,173 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import net.minecraftforge.eventbus.api.Event;
|
||||
import net.minecraftforge.fml.config.ModConfig;
|
||||
import net.minecraftforge.fml.event.lifecycle.IModBusEvent;
|
||||
import net.minecraftforge.forgespi.language.IModInfo;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
|
||||
import java.util.EnumMap;
|
||||
import java.util.HashMap;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* The container that wraps around mods in the system.
|
||||
* <p>
|
||||
* The philosophy is that individual mod implementation technologies should not
|
||||
* impact the actual loading and management of mod code. This class provides
|
||||
* a mechanism by which we can wrap actual mod code so that the loader and other
|
||||
* facilities can treat mods at arms length.
|
||||
* </p>
|
||||
*
|
||||
* @author cpw
|
||||
*
|
||||
*/
|
||||
|
||||
public abstract class ModContainer
|
||||
{
|
||||
protected final String modId;
|
||||
protected final String namespace;
|
||||
protected final IModInfo modInfo;
|
||||
protected ModLoadingStage modLoadingStage;
|
||||
protected Supplier<?> contextExtension;
|
||||
protected final Map<ModLoadingStage, Runnable> activityMap = new HashMap<>();
|
||||
protected final Map<ExtensionPoint, Supplier<?>> extensionPoints = new IdentityHashMap<>();
|
||||
protected final EnumMap<ModConfig.Type, ModConfig> configs = new EnumMap<>(ModConfig.Type.class);
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
protected Optional<Consumer<ModConfig.ModConfigEvent>> configHandler = Optional.empty();
|
||||
|
||||
public ModContainer(IModInfo info)
|
||||
{
|
||||
this.modId = info.getModId();
|
||||
// TODO: Currently not reading namespace from configuration..
|
||||
this.namespace = this.modId;
|
||||
this.modInfo = info;
|
||||
this.modLoadingStage = ModLoadingStage.CONSTRUCT;
|
||||
// default displaytest extension checks for version string match
|
||||
registerExtensionPoint(ExtensionPoint.DISPLAYTEST, () -> Pair.of(()->this.modInfo.getVersion().toString(),
|
||||
(incoming, isNetwork)->Objects.equals(incoming, this.modInfo.getVersion().toString())));
|
||||
}
|
||||
|
||||
/**
|
||||
* Errored container state, used for filtering. Does nothing.
|
||||
*/
|
||||
ModContainer()
|
||||
{
|
||||
this.modLoadingStage = ModLoadingStage.ERROR;
|
||||
modId = "BROKEN";
|
||||
namespace = "BROKEN";
|
||||
modInfo = null;
|
||||
}
|
||||
/**
|
||||
* @return the modid for this mod
|
||||
*/
|
||||
public final String getModId()
|
||||
{
|
||||
return modId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the resource prefix for the mod
|
||||
*/
|
||||
public final String getNamespace()
|
||||
{
|
||||
return namespace;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return The current loading stage for this mod
|
||||
*/
|
||||
public ModLoadingStage getCurrentState()
|
||||
{
|
||||
return modLoadingStage;
|
||||
}
|
||||
|
||||
public static <T extends Event & IModBusEvent> CompletableFuture<Void> buildTransitionHandler(
|
||||
final ModContainer target,
|
||||
final ModLoadingStage.EventGenerator<T> eventGenerator,
|
||||
final BiFunction<ModLoadingStage, Throwable, ModLoadingStage> stateChangeHandler,
|
||||
final Executor executor) {
|
||||
return CompletableFuture
|
||||
.runAsync(() -> {
|
||||
ModLoadingContext.get().setActiveContainer(target, target.contextExtension.get());
|
||||
target.activityMap.getOrDefault(target.modLoadingStage, ()->{}).run();
|
||||
target.acceptEvent(eventGenerator.apply(target));
|
||||
}, executor)
|
||||
.whenComplete((mc, exception) -> {
|
||||
target.modLoadingStage = stateChangeHandler.apply(target.modLoadingStage, exception);
|
||||
ModLoadingContext.get().setActiveContainer(null, null);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the modinfo used to create this mod instance
|
||||
*/
|
||||
public IModInfo getModInfo()
|
||||
{
|
||||
return modInfo;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> Optional<T> getCustomExtension(ExtensionPoint<T> point) {
|
||||
return Optional.ofNullable((T)extensionPoints.getOrDefault(point,()-> null).get());
|
||||
}
|
||||
|
||||
public <T> void registerExtensionPoint(ExtensionPoint<T> point, Supplier<T> extension)
|
||||
{
|
||||
extensionPoints.put(point, extension);
|
||||
}
|
||||
|
||||
public void addConfig(final ModConfig modConfig) {
|
||||
configs.put(modConfig.getType(), modConfig);
|
||||
}
|
||||
|
||||
public void dispatchConfigEvent(ModConfig.ModConfigEvent event) {
|
||||
configHandler.ifPresent(configHandler->configHandler.accept(event));
|
||||
}
|
||||
|
||||
/**
|
||||
* Does this mod match the supplied mod?
|
||||
*
|
||||
* @param mod to compare
|
||||
* @return if the mod matches
|
||||
*/
|
||||
public abstract boolean matches(Object mod);
|
||||
|
||||
/**
|
||||
* @return the mod object instance
|
||||
*/
|
||||
public abstract Object getMod();
|
||||
|
||||
/**
|
||||
* Accept an arbitrary event for processing by the mod. Probably posted to an event bus in the lower level container.
|
||||
* @param e Event to accept
|
||||
*/
|
||||
protected <T extends Event & IModBusEvent> void acceptEvent(T e) {}
|
||||
}
|
||||
@@ -1,241 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import net.minecraftforge.eventbus.api.Event;
|
||||
import net.minecraftforge.fml.event.lifecycle.IModBusEvent;
|
||||
import net.minecraftforge.forgespi.language.ModFileScanData;
|
||||
import net.minecraftforge.fml.loading.moddiscovery.ModFile;
|
||||
import net.minecraftforge.fml.loading.moddiscovery.ModFileInfo;
|
||||
import net.minecraftforge.fml.loading.moddiscovery.ModInfo;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import java.util.AbstractMap;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.ForkJoinPool;
|
||||
import java.util.concurrent.ForkJoinWorkerThread;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* Master list of all mods - game-side version. This is classloaded in the game scope and
|
||||
* can dispatch game level events as a result.
|
||||
*/
|
||||
public class ModList
|
||||
{
|
||||
private static Logger LOGGER = LogManager.getLogger();
|
||||
private static ModList INSTANCE;
|
||||
private final List<ModFileInfo> modFiles;
|
||||
private final List<ModInfo> sortedList;
|
||||
private final Map<String, ModFileInfo> fileById;
|
||||
private List<ModContainer> mods;
|
||||
private Map<String, ModContainer> indexedMods;
|
||||
private List<ModFileScanData> modFileScanData;
|
||||
|
||||
private ModList(final List<ModFile> modFiles, final List<ModInfo> sortedList)
|
||||
{
|
||||
this.modFiles = modFiles.stream().map(ModFile::getModFileInfo).map(ModFileInfo.class::cast).collect(Collectors.toList());
|
||||
this.sortedList = sortedList.stream().
|
||||
map(ModInfo.class::cast).
|
||||
collect(Collectors.toList());
|
||||
this.fileById = this.modFiles.stream().map(ModFileInfo::getMods).flatMap(Collection::stream).
|
||||
map(ModInfo.class::cast).
|
||||
collect(Collectors.toMap(ModInfo::getModId, ModInfo::getOwningFile));
|
||||
CrashReportExtender.registerCrashCallable("Mod List", this::crashReport);
|
||||
}
|
||||
|
||||
private String getModContainerState(String modId) {
|
||||
return getModContainerById(modId).map(ModContainer::getCurrentState).map(Object::toString).orElse("NONE");
|
||||
}
|
||||
|
||||
private String fileToLine(ModFile mf) {
|
||||
return String.format("%-50.50s|%-30.30s|%-30.30s|%-20.20s|%-10.10s|Manifest: %s", mf.getFileName(),
|
||||
mf.getModInfos().get(0).getDisplayName(),
|
||||
mf.getModInfos().get(0).getModId(),
|
||||
mf.getModInfos().get(0).getVersion(),
|
||||
getModContainerState(mf.getModInfos().get(0).getModId()),
|
||||
((ModFileInfo)mf.getModFileInfo()).getCodeSigningFingerprint().orElse("NOSIGNATURE"));
|
||||
}
|
||||
private String crashReport() {
|
||||
return "\n"+applyForEachModFile(this::fileToLine).collect(Collectors.joining("\n\t\t", "\t\t", ""));
|
||||
}
|
||||
|
||||
public static ModList of(List<ModFile> modFiles, List<ModInfo> sortedList)
|
||||
{
|
||||
INSTANCE = new ModList(modFiles, sortedList);
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
public static ModList get() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
private static ForkJoinWorkerThread newForkJoinWorkerThread(ForkJoinPool pool) {
|
||||
ForkJoinWorkerThread thread = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool);
|
||||
thread.setName("modloading-worker-" + thread.getPoolIndex());
|
||||
// The default sets it to the SystemClassloader, so copy the current one.
|
||||
thread.setContextClassLoader(Thread.currentThread().getContextClassLoader());
|
||||
return thread;
|
||||
}
|
||||
|
||||
public List<ModFileInfo> getModFiles()
|
||||
{
|
||||
return modFiles;
|
||||
}
|
||||
|
||||
public ModFileInfo getModFileById(String modid)
|
||||
{
|
||||
return this.fileById.get(modid);
|
||||
}
|
||||
|
||||
<T extends Event & IModBusEvent> Function<Executor, CompletableFuture<List<Throwable>>> futureVisitor(
|
||||
final ModLoadingStage.EventGenerator<T> eventGenerator,
|
||||
final BiFunction<ModLoadingStage, Throwable, ModLoadingStage> stateChange) {
|
||||
return executor -> gather(
|
||||
this.mods.stream()
|
||||
.map(mod -> ModContainer.buildTransitionHandler(mod, eventGenerator, stateChange, executor))
|
||||
.collect(Collectors.toList()))
|
||||
.thenComposeAsync(ModList::completableFutureFromExceptionList, executor);
|
||||
}
|
||||
static CompletionStage<List<Throwable>> completableFutureFromExceptionList(List<? extends Map.Entry<?, Throwable>> t) {
|
||||
if (t.stream().noneMatch(e->e.getValue()!=null)) {
|
||||
return CompletableFuture.completedFuture(Collections.emptyList());
|
||||
} else {
|
||||
final List<Throwable> throwables = t.stream().filter(e -> e.getValue() != null).map(Map.Entry::getValue).collect(Collectors.toList());
|
||||
CompletableFuture<List<Throwable>> cf = new CompletableFuture<>();
|
||||
final RuntimeException accumulator = new RuntimeException();
|
||||
cf.completeExceptionally(accumulator);
|
||||
throwables.forEach(exception -> {
|
||||
if (exception instanceof CompletionException) {
|
||||
exception = exception.getCause();
|
||||
}
|
||||
if (exception.getSuppressed().length!=0) {
|
||||
Arrays.stream(exception.getSuppressed()).forEach(accumulator::addSuppressed);
|
||||
} else {
|
||||
accumulator.addSuppressed(exception);
|
||||
}
|
||||
});
|
||||
return cf;
|
||||
}
|
||||
}
|
||||
|
||||
static <V> CompletableFuture<List<Map.Entry<V, Throwable>>> gather(List<? extends CompletableFuture<? extends V>> futures) {
|
||||
List<Map.Entry<V, Throwable>> list = new ArrayList<>(futures.size());
|
||||
CompletableFuture<?>[] results = new CompletableFuture[futures.size()];
|
||||
futures.forEach(future -> {
|
||||
int i = list.size();
|
||||
list.add(null);
|
||||
results[i] = future.whenComplete((result, exception) -> list.set(i, new AbstractMap.SimpleImmutableEntry<>(result, exception)));
|
||||
});
|
||||
return CompletableFuture.allOf(results).handle((r, th)->null).thenApply(res -> list);
|
||||
}
|
||||
|
||||
void setLoadedMods(final List<ModContainer> modContainers)
|
||||
{
|
||||
this.mods = modContainers;
|
||||
this.indexedMods = modContainers.stream().collect(Collectors.toMap(ModContainer::getModId, Function.identity()));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> Optional<T> getModObjectById(String modId)
|
||||
{
|
||||
return getModContainerById(modId).map(ModContainer::getMod).map(o -> (T) o);
|
||||
}
|
||||
|
||||
public Optional<? extends ModContainer> getModContainerById(String modId)
|
||||
{
|
||||
return Optional.ofNullable(this.indexedMods.get(modId));
|
||||
}
|
||||
|
||||
public Optional<? extends ModContainer> getModContainerByObject(Object obj)
|
||||
{
|
||||
return mods.stream().filter(mc -> mc.getMod() == obj).findFirst();
|
||||
}
|
||||
|
||||
public List<ModInfo> getMods()
|
||||
{
|
||||
return this.sortedList;
|
||||
}
|
||||
|
||||
public boolean isLoaded(String modTarget)
|
||||
{
|
||||
return this.indexedMods.containsKey(modTarget);
|
||||
}
|
||||
|
||||
public int size()
|
||||
{
|
||||
return mods.size();
|
||||
}
|
||||
|
||||
public List<ModFileScanData> getAllScanData()
|
||||
{
|
||||
if (modFileScanData == null)
|
||||
{
|
||||
modFileScanData = this.sortedList.stream().
|
||||
map(ModInfo::getOwningFile).
|
||||
filter(Objects::nonNull).
|
||||
map(ModFileInfo::getFile).
|
||||
distinct().
|
||||
map(ModFile::getScanResult).
|
||||
collect(Collectors.toList());
|
||||
}
|
||||
return modFileScanData;
|
||||
|
||||
}
|
||||
|
||||
public void forEachModFile(Consumer<ModFile> fileConsumer)
|
||||
{
|
||||
modFiles.stream().map(ModFileInfo::getFile).forEach(fileConsumer);
|
||||
}
|
||||
|
||||
public <T> Stream<T> applyForEachModFile(Function<ModFile, T> function) {
|
||||
return modFiles.stream().map(ModFileInfo::getFile).map(function);
|
||||
}
|
||||
|
||||
public void forEachModContainer(BiConsumer<String, ModContainer> modContainerConsumer) {
|
||||
indexedMods.forEach(modContainerConsumer);
|
||||
}
|
||||
|
||||
public <T> Stream<T> applyForEachModContainer(Function<ModContainer, T> function) {
|
||||
return indexedMods.values().stream().map(function);
|
||||
}
|
||||
|
||||
private static class UncaughtModLoadingException extends ModLoadingException {
|
||||
public UncaughtModLoadingException(ModLoadingStage stage, Throwable originalException) {
|
||||
super(null, stage, "fml.modloading.uncaughterror", originalException);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,366 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import cpw.mods.modlauncher.TransformingClassLoader;
|
||||
import net.minecraftforge.api.distmarker.Dist;
|
||||
import net.minecraftforge.common.capabilities.CapabilityManager;
|
||||
import net.minecraftforge.eventbus.api.Event;
|
||||
import net.minecraftforge.fml.config.ConfigTracker;
|
||||
import net.minecraftforge.fml.config.ModConfig;
|
||||
import net.minecraftforge.fml.event.lifecycle.IModBusEvent;
|
||||
import net.minecraftforge.fml.loading.FMLLoader;
|
||||
import net.minecraftforge.fml.loading.FMLPaths;
|
||||
import net.minecraftforge.fml.loading.LoadingModList;
|
||||
import net.minecraftforge.fml.loading.moddiscovery.InvalidModIdentifier;
|
||||
import net.minecraftforge.fml.loading.moddiscovery.ModFile;
|
||||
import net.minecraftforge.fml.loading.moddiscovery.ModFileInfo;
|
||||
import net.minecraftforge.fml.loading.moddiscovery.ModInfo;
|
||||
import net.minecraftforge.fml.loading.progress.StartupMessageManager;
|
||||
import net.minecraftforge.fml.network.FMLNetworkConstants;
|
||||
import net.minecraftforge.fml.network.NetworkRegistry;
|
||||
import net.minecraftforge.forgespi.language.IModInfo;
|
||||
import net.minecraftforge.forgespi.language.IModLanguageProvider;
|
||||
import net.minecraftforge.registries.GameData;
|
||||
import net.minecraftforge.registries.ObjectHolderRegistry;
|
||||
import net.minecraftforge.versions.forge.ForgeVersion;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static net.minecraftforge.fml.Logging.CORE;
|
||||
import static net.minecraftforge.fml.Logging.LOADING;
|
||||
|
||||
/**
|
||||
* Loads mods.
|
||||
*
|
||||
* Dispatch cycle is seen in {@link #loadMods()} and {@link #finishMods()}
|
||||
*
|
||||
* Overall sequence for loadMods is:
|
||||
* <dl>
|
||||
* <dt>CONSTRUCT</dt>
|
||||
* <dd>Constructs the mod instance. Mods can typically setup basic environment such as Event listeners
|
||||
* and Configuration specifications here.</dd>
|
||||
* <dt>Automated dispatches</dt>
|
||||
* <dd>Dispatches automated elements : {@link net.minecraftforge.fml.common.Mod.EventBusSubscriber},
|
||||
* {@link net.minecraftforge.event.RegistryEvent}, {@link net.minecraftforge.common.capabilities.CapabilityInject}
|
||||
* and others</dd>
|
||||
* <dt>CONFIG_LOAD</dt>
|
||||
* <dd>Dispatches ConfigLoadEvent to mods</dd>
|
||||
* <dt>COMMON_SETUP</dt>
|
||||
* <dd>Dispatches {@link net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent} to mods</dd>
|
||||
* <dt>SIDED_SETUP</dt>
|
||||
* <dd>Dispatches {@link net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent} or
|
||||
* {@link net.minecraftforge.fml.event.lifecycle.FMLDedicatedServerSetupEvent} to mods</dd>
|
||||
* </dl>
|
||||
*
|
||||
* Overall sequence for finishMods is:
|
||||
* <dl>
|
||||
* <dt>ENQUEUE_IMC</dt>
|
||||
* <dd>Dispatches {@link net.minecraftforge.fml.event.lifecycle.InterModEnqueueEvent} to mods,
|
||||
* for enqueuing {@link InterModComms} messages for other mods to receive subsequently</dd>
|
||||
* <dt>PROCESS_IMC</dt>
|
||||
* <dd>Dispatches {@link net.minecraftforge.fml.event.lifecycle.InterModProcessEvent} to mods,
|
||||
* for processing {@link InterModComms} messages received from other mods prior to this event</dd>
|
||||
* <dt>COMPLETE</dt>
|
||||
* <dd>Dispatches {@link net.minecraftforge.fml.event.lifecycle.FMLLoadCompleteEvent} to mods,
|
||||
* and completes the mod loading sequence.</dd>
|
||||
* </dl>
|
||||
*/
|
||||
public class ModLoader
|
||||
{
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
private static ModLoader INSTANCE;
|
||||
private final TransformingClassLoader launchClassLoader;
|
||||
private final LoadingModList loadingModList;
|
||||
|
||||
private final List<ModLoadingException> loadingExceptions;
|
||||
private final List<ModLoadingWarning> loadingWarnings;
|
||||
private boolean loadingStateValid;
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
private final Optional<Consumer<String>> statusConsumer = StartupMessageManager.modLoaderConsumer();
|
||||
|
||||
private ModLoader()
|
||||
{
|
||||
INSTANCE = this;
|
||||
this.launchClassLoader = FMLLoader.getLaunchClassLoader();
|
||||
this.loadingModList = FMLLoader.getLoadingModList();
|
||||
this.loadingExceptions = FMLLoader.getLoadingModList().
|
||||
getErrors().stream().flatMap(ModLoadingException::fromEarlyException).collect(Collectors.toList());
|
||||
this.loadingWarnings = FMLLoader.getLoadingModList().
|
||||
getBrokenFiles().stream().map(file -> new ModLoadingWarning(null, ModLoadingStage.VALIDATE,
|
||||
InvalidModIdentifier.identifyJarProblem(file.getFilePath()).orElse("fml.modloading.brokenfile"), file.getFileName())).collect(Collectors.toList());
|
||||
FMLLoader.getLoadingModList()
|
||||
.getModFiles().stream().filter(ModFileInfo::missingLicense) //Search for files with missing licenses
|
||||
.filter(modFileInfo -> modFileInfo.getMods().stream().noneMatch(thisModInfo -> this.loadingExceptions.stream().map(ModLoadingException::getModInfo).anyMatch(otherInfo -> otherInfo == thisModInfo))) //Ignore files where any other mod already encountered an error
|
||||
.map(modFileInfo -> new ModLoadingException(null, ModLoadingStage.VALIDATE, "fml.modloading.missinglicense", null, modFileInfo.getFile()))
|
||||
.forEach(this.loadingExceptions::add);
|
||||
LOGGER.debug(CORE, "Loading Network data for FML net version: {}", FMLNetworkConstants.init());
|
||||
CrashReportExtender.registerCrashCallable("ModLauncher", FMLLoader::getLauncherInfo);
|
||||
CrashReportExtender.registerCrashCallable("ModLauncher launch target", FMLLoader::launcherHandlerName);
|
||||
CrashReportExtender.registerCrashCallable("ModLauncher naming", FMLLoader::getNaming);
|
||||
CrashReportExtender.registerCrashCallable("ModLauncher services", this::computeModLauncherServiceList);
|
||||
CrashReportExtender.registerCrashCallable("FML", ForgeVersion::getSpec);
|
||||
CrashReportExtender.registerCrashCallable("Forge", ()->ForgeVersion.getGroup()+":"+ForgeVersion.getVersion());
|
||||
CrashReportExtender.registerCrashCallable("FML Language Providers", this::computeLanguageList);
|
||||
}
|
||||
|
||||
private String computeLanguageList() {
|
||||
return "\n"+FMLLoader.getLanguageLoadingProvider().applyForEach(lp->lp.name() +"@"+ lp.getClass().getPackage().getImplementationVersion()).collect(Collectors.joining("\n\t\t", "\t\t", ""));
|
||||
}
|
||||
|
||||
private String computeModLauncherServiceList() {
|
||||
final List<Map<String, String>> mods = FMLLoader.modLauncherModList();
|
||||
return "\n"+mods.stream().map(mod->mod.getOrDefault("file","nofile")+
|
||||
" "+mod.getOrDefault("name", "missing")+
|
||||
" "+mod.getOrDefault("type","NOTYPE")+
|
||||
" "+mod.getOrDefault("description", "")).
|
||||
collect(Collectors.joining("\n\t\t","\t\t",""));
|
||||
}
|
||||
|
||||
public static ModLoader get()
|
||||
{
|
||||
return INSTANCE == null ? INSTANCE = new ModLoader() : INSTANCE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run on the primary starting thread by ClientModLoader and ServerModLoader
|
||||
* @param syncExecutor An executor to run tasks on the main thread
|
||||
* @param parallelExecutor An executor to run tasks on a parallel loading thread pool
|
||||
* @param periodicTask Optional periodic task to perform on the main thread while other activities run
|
||||
*/
|
||||
public void gatherAndInitializeMods(final ModWorkManager.DrivenExecutor syncExecutor, final Executor parallelExecutor, final Runnable periodicTask) {
|
||||
loadingStateValid = true;
|
||||
statusConsumer.ifPresent(c->c.accept("Waiting for scan to complete"));
|
||||
FMLLoader.backgroundScanHandler.waitForScanToComplete(periodicTask);
|
||||
statusConsumer.ifPresent(c->c.accept("Loading mods"));
|
||||
final ModList modList = ModList.of(loadingModList
|
||||
.getModFiles()
|
||||
.stream()
|
||||
.map(ModFileInfo::getFile)
|
||||
.collect(Collectors.toList()),
|
||||
loadingModList.getMods());
|
||||
if (!this.loadingExceptions.isEmpty()) {
|
||||
LOGGER.fatal(CORE, "Error during pre-loading phase", loadingExceptions.get(0));
|
||||
modList.setLoadedMods(Collections.emptyList());
|
||||
loadingStateValid = false;
|
||||
throw new LoadingFailedException(loadingExceptions);
|
||||
}
|
||||
statusConsumer.ifPresent(c->c.accept("Building Mod List"));
|
||||
final List<ModContainer> modContainers = loadingModList.getModFiles().stream().
|
||||
map(ModFileInfo::getFile).
|
||||
map(mf -> buildMods(mf, launchClassLoader)).
|
||||
flatMap(Collection::stream).
|
||||
collect(Collectors.toList());
|
||||
if (!loadingExceptions.isEmpty()) {
|
||||
LOGGER.fatal(CORE, "Failed to initialize mod containers", loadingExceptions.get(0));
|
||||
modList.setLoadedMods(Collections.emptyList());
|
||||
loadingStateValid = false;
|
||||
throw new LoadingFailedException(loadingExceptions);
|
||||
}
|
||||
modList.setLoadedMods(modContainers);
|
||||
statusConsumer.ifPresent(c->c.accept(String.format("Constructing %d mods", modList.size())));
|
||||
dispatchAndHandleError(ModLoadingStage.CONSTRUCT, syncExecutor, parallelExecutor, periodicTask);
|
||||
statusConsumer.ifPresent(c->c.accept("Creating registries"));
|
||||
dispatchAndHandleError(ModLoadingStage.CREATE_REGISTRIES, syncExecutor, parallelExecutor, periodicTask);
|
||||
ObjectHolderRegistry.findObjectHolders();
|
||||
CapabilityManager.INSTANCE.injectCapabilities(modList.getAllScanData());
|
||||
statusConsumer.ifPresent(c->c.accept("Adding custom tag types"));
|
||||
GameData.setCustomTagTypesFromRegistries();
|
||||
statusConsumer.ifPresent(c->c.accept("Populating registries"));
|
||||
dispatchAndHandleError(ModLoadingStage.LOAD_REGISTRIES, syncExecutor, parallelExecutor, periodicTask);
|
||||
statusConsumer.ifPresent(c->c.accept("Early mod loading complete"));
|
||||
}
|
||||
|
||||
public void loadMods(final ModWorkManager.DrivenExecutor syncExecutor, final Executor parallelExecutor, final Function<Executor, CompletableFuture<Void>> beforeSidedEvent, final Function<Executor, CompletableFuture<Void>> afterSidedEvent, final Runnable periodicTask) {
|
||||
statusConsumer.ifPresent(c->c.accept("Loading mod config"));
|
||||
DistExecutor.unsafeRunWhenOn(Dist.CLIENT, ()->()-> ConfigTracker.INSTANCE.loadConfigs(ModConfig.Type.CLIENT, FMLPaths.CONFIGDIR.get()));
|
||||
ConfigTracker.INSTANCE.loadConfigs(ModConfig.Type.COMMON, FMLPaths.CONFIGDIR.get());
|
||||
statusConsumer.ifPresent(c->c.accept("Mod setup: SETUP"));
|
||||
dispatchAndHandleError(ModLoadingStage.COMMON_SETUP, syncExecutor, parallelExecutor, periodicTask);
|
||||
statusConsumer.ifPresent(c->c.accept("Mod setup: SIDED SETUP"));
|
||||
dispatchAndHandleError(ModLoadingStage.SIDED_SETUP, syncExecutor, parallelExecutor, periodicTask, beforeSidedEvent, afterSidedEvent);
|
||||
statusConsumer.ifPresent(c->c.accept("Mod setup complete"));
|
||||
}
|
||||
|
||||
public void finishMods(final ModWorkManager.DrivenExecutor syncExecutor, final Executor parallelExecutor, final Runnable periodicTask)
|
||||
{
|
||||
statusConsumer.ifPresent(c->c.accept("Mod setup: ENQUEUE IMC"));
|
||||
dispatchAndHandleError(ModLoadingStage.ENQUEUE_IMC, syncExecutor, parallelExecutor, periodicTask);
|
||||
statusConsumer.ifPresent(c->c.accept("Mod setup: PROCESS IMC"));
|
||||
dispatchAndHandleError(ModLoadingStage.PROCESS_IMC, syncExecutor, parallelExecutor, periodicTask);
|
||||
statusConsumer.ifPresent(c->c.accept("Mod setup: Final completion"));
|
||||
dispatchAndHandleError(ModLoadingStage.COMPLETE, syncExecutor, parallelExecutor, periodicTask);
|
||||
statusConsumer.ifPresent(c->c.accept("Freezing data"));
|
||||
GameData.freezeData();
|
||||
NetworkRegistry.lock();
|
||||
statusConsumer.ifPresent(c->c.accept(String.format("Mod loading complete - %d mods loaded", ModList.get().size())));
|
||||
}
|
||||
|
||||
private void dispatchAndHandleError(ModLoadingStage state, ModWorkManager.DrivenExecutor syncExecutor, Executor parallelExecutor, final Runnable ticker) {
|
||||
if (!isLoadingStateValid()) {
|
||||
LOGGER.error("Cowardly refusing to process mod state change request from {}", state);
|
||||
return;
|
||||
}
|
||||
waitForTransition(state, syncExecutor, ticker, state.buildTransition(syncExecutor, parallelExecutor));
|
||||
}
|
||||
|
||||
private void dispatchAndHandleError(ModLoadingStage state, ModWorkManager.DrivenExecutor syncExecutor, Executor parallelExecutor, final Runnable ticker, Function<Executor, CompletableFuture<Void>> preSyncTask, Function<Executor, CompletableFuture<Void>> postSyncTask) {
|
||||
if (!isLoadingStateValid()) {
|
||||
LOGGER.error("Cowardly refusing to process mod state change request from {}", state);
|
||||
return;
|
||||
}
|
||||
waitForTransition(state, syncExecutor, ticker, state.buildTransition(syncExecutor, parallelExecutor, preSyncTask, postSyncTask));
|
||||
}
|
||||
|
||||
private void waitForTransition(final ModLoadingStage state, final ModWorkManager.DrivenExecutor syncExecutor, final Runnable ticker, final CompletableFuture<List<Throwable>> transition) {
|
||||
while (!transition.isDone()) {
|
||||
syncExecutor.drive(ticker);
|
||||
}
|
||||
try {
|
||||
transition.join();
|
||||
} catch (CompletionException e) {
|
||||
loadingStateValid = false;
|
||||
Throwable t = e.getCause();
|
||||
final List<Throwable> notModLoading = Arrays.stream(t.getSuppressed())
|
||||
.filter(obj -> !(obj instanceof ModLoadingException))
|
||||
.collect(Collectors.toList());
|
||||
if (!notModLoading.isEmpty()) {
|
||||
LOGGER.fatal("Encountered non-modloading exceptions!", e);
|
||||
throw e;
|
||||
}
|
||||
|
||||
final List<ModLoadingException> modLoadingExceptions = Arrays.stream(t.getSuppressed())
|
||||
.filter(ModLoadingException.class::isInstance)
|
||||
.map(ModLoadingException.class::cast)
|
||||
.collect(Collectors.toList());
|
||||
LOGGER.fatal(LOADING,"Failed to complete lifecycle event {}, {} errors found", state, modLoadingExceptions.size());
|
||||
throw new LoadingFailedException(modLoadingExceptions);
|
||||
}
|
||||
}
|
||||
|
||||
private List<ModContainer> buildMods(final ModFile modFile, final TransformingClassLoader modClassLoader)
|
||||
{
|
||||
final Map<String, IModInfo> modInfoMap = modFile.getModFileInfo().getMods().stream().collect(Collectors.toMap(IModInfo::getModId, Function.identity()));
|
||||
|
||||
LOGGER.trace(LOADING, "ModContainer is {}", ModContainer.class.getClassLoader());
|
||||
final List<ModContainer> containers = modFile.getScanResult().getTargets()
|
||||
.entrySet()
|
||||
.stream()
|
||||
.map(e -> buildModContainerFromTOML(modFile, modClassLoader, modInfoMap, e))
|
||||
.filter(Objects::nonNull)
|
||||
.collect(Collectors.toList());
|
||||
if (containers.size() != modInfoMap.size()) {
|
||||
LOGGER.fatal(LOADING,"File {} constructed {} mods: {}, but had {} mods specified: {}",
|
||||
modFile.getFilePath(),
|
||||
containers.size(), containers.stream().map(c -> c != null ? c.getModId() : "(null)").sorted().collect(Collectors.toList()),
|
||||
modInfoMap.size(), modInfoMap.values().stream().map(IModInfo::getModId).sorted().collect(Collectors.toList()));
|
||||
loadingExceptions.add(new ModLoadingException(null, ModLoadingStage.CONSTRUCT, "fml.modloading.missingclasses", null, modFile.getFilePath()));
|
||||
}
|
||||
// remove errored mod containers
|
||||
return containers.stream().filter(mc -> mc.modLoadingStage != ModLoadingStage.ERROR).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private ModContainer buildModContainerFromTOML(final ModFile modFile, final TransformingClassLoader modClassLoader, final Map<String, IModInfo> modInfoMap, final Map.Entry<String, ? extends IModLanguageProvider.IModLanguageLoader> idToProviderEntry) {
|
||||
try {
|
||||
final String modId = idToProviderEntry.getKey();
|
||||
final IModLanguageProvider.IModLanguageLoader languageLoader = idToProviderEntry.getValue();
|
||||
IModInfo info = Optional.ofNullable(modInfoMap.get(modId)).
|
||||
// throw a missing metadata error if there is no matching modid in the modInfoMap from the mods.toml file
|
||||
orElseThrow(()->new ModLoadingException(null, ModLoadingStage.CONSTRUCT, "fml.modloading.missingmetadata", null, modId));
|
||||
return languageLoader.loadMod(info, modClassLoader, modFile.getScanResult());
|
||||
} catch (ModLoadingException mle) {
|
||||
// exceptions are caught and added to the error list for later handling
|
||||
loadingExceptions.add(mle);
|
||||
// return an errored container instance here, because we tried and failed building a container.
|
||||
return new ErroredModContainer();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return If the current mod loading state is valid. Use if you interact with vanilla systems directly during loading
|
||||
* and don't want to cause extraneous crashes due to trying to do things that aren't possible in a "broken load"
|
||||
*/
|
||||
public static boolean isLoadingStateValid() {
|
||||
return get().loadingStateValid;
|
||||
}
|
||||
|
||||
public <T extends Event & IModBusEvent> void runEventGenerator(Function<ModContainer, T> generator) {
|
||||
if (!loadingStateValid) {
|
||||
LOGGER.error("Cowardly refusing to send event generator to a broken mod state");
|
||||
return;
|
||||
}
|
||||
ModList.get().forEachModContainer((id, mc) -> mc.acceptEvent(generator.apply(mc)));
|
||||
}
|
||||
|
||||
public <T extends Event & IModBusEvent> void postEvent(T e) {
|
||||
if (!loadingStateValid) {
|
||||
LOGGER.error("Cowardly refusing to send event {} to a broken mod state", e.getClass().getName());
|
||||
return;
|
||||
}
|
||||
ModList.get().forEachModContainer((id, mc) -> mc.acceptEvent(e));
|
||||
}
|
||||
|
||||
public List<ModLoadingWarning> getWarnings()
|
||||
{
|
||||
return ImmutableList.copyOf(this.loadingWarnings);
|
||||
}
|
||||
|
||||
public void addWarning(ModLoadingWarning warning)
|
||||
{
|
||||
this.loadingWarnings.add(warning);
|
||||
}
|
||||
|
||||
private static boolean runningDataGen = false;
|
||||
|
||||
public static boolean isDataGenRunning () {
|
||||
return runningDataGen;
|
||||
}
|
||||
|
||||
private static class ErroredModContainer extends ModContainer {
|
||||
public ErroredModContainer() {
|
||||
super();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean matches(final Object mod) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getMod() {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import net.minecraftforge.common.ForgeConfigSpec;
|
||||
import net.minecraftforge.fml.config.ModConfig;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class ModLoadingContext
|
||||
{
|
||||
private static ThreadLocal<ModLoadingContext> context = ThreadLocal.withInitial(ModLoadingContext::new);
|
||||
private Object languageExtension;
|
||||
private ModLoadingStage stage;
|
||||
|
||||
public static ModLoadingContext get() {
|
||||
return context.get();
|
||||
}
|
||||
|
||||
private ModContainer activeContainer;
|
||||
|
||||
public void setActiveContainer(final ModContainer container, final Object languageExtension) {
|
||||
this.activeContainer = container;
|
||||
this.languageExtension = languageExtension;
|
||||
}
|
||||
|
||||
public ModContainer getActiveContainer() {
|
||||
return activeContainer == null ? ModList.get().getModContainerById("minecraft").orElseThrow(()->new RuntimeException("Where is minecraft???!")) : activeContainer;
|
||||
}
|
||||
|
||||
public String getActiveNamespace() {
|
||||
return activeContainer == null ? "minecraft" : activeContainer.getNamespace();
|
||||
}
|
||||
|
||||
/**
|
||||
* Register an {@link ExtensionPoint} with the mod container.
|
||||
* @param point The extension point to register
|
||||
* @param extension An extension operator
|
||||
* @param <T> The type signature of the extension operator
|
||||
*/
|
||||
public <T> void registerExtensionPoint(ExtensionPoint<T> point, Supplier<T> extension) {
|
||||
getActiveContainer().registerExtensionPoint(point, extension);
|
||||
}
|
||||
|
||||
public void registerConfig(ModConfig.Type type, ForgeConfigSpec spec) {
|
||||
getActiveContainer().addConfig(new ModConfig(type, spec, getActiveContainer()));
|
||||
}
|
||||
|
||||
public void registerConfig(ModConfig.Type type, ForgeConfigSpec spec, String fileName) {
|
||||
getActiveContainer().addConfig(new ModConfig(type, spec, getActiveContainer(), fileName));
|
||||
}
|
||||
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> T extension() {
|
||||
return (T)languageExtension;
|
||||
}
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import com.google.common.collect.Streams;
|
||||
import net.minecraftforge.fml.loading.EarlyLoadingException;
|
||||
import net.minecraftforge.forgespi.language.IModInfo;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* General purpose mod loading error message
|
||||
*/
|
||||
public class ModLoadingException extends RuntimeException
|
||||
{
|
||||
private static final long serialVersionUID = 2048947398536935507L;
|
||||
/**
|
||||
* Mod Info for mod with issue
|
||||
*/
|
||||
private final IModInfo modInfo;
|
||||
/**
|
||||
* The stage where this error was encountered
|
||||
*/
|
||||
private final ModLoadingStage errorStage;
|
||||
|
||||
/**
|
||||
* I18N message to use for display
|
||||
*/
|
||||
private final String i18nMessage;
|
||||
|
||||
/**
|
||||
* Context for message display
|
||||
*/
|
||||
private final List<Object> context;
|
||||
|
||||
public ModLoadingException(final IModInfo modInfo, final ModLoadingStage errorStage, final String i18nMessage, final Throwable originalException, Object... context) {
|
||||
super("Mod Loading Exception", originalException);
|
||||
this.modInfo = modInfo;
|
||||
this.errorStage = errorStage;
|
||||
this.i18nMessage = i18nMessage;
|
||||
this.context = Arrays.asList(context);
|
||||
}
|
||||
|
||||
static Stream<ModLoadingException> fromEarlyException(final EarlyLoadingException e) {
|
||||
return e.getAllData().stream().map(ed->new ModLoadingException(ed.getModInfo(), ModLoadingStage.VALIDATE, ed.getI18message(), e.getCause(), ed.getArgs()));
|
||||
}
|
||||
|
||||
public String getI18NMessage() {
|
||||
return i18nMessage;
|
||||
}
|
||||
|
||||
public Object[] getContext() {
|
||||
return context.toArray();
|
||||
}
|
||||
|
||||
public String formatToString() {
|
||||
return ForgeI18n.parseMessage(i18nMessage, Streams.concat(Stream.of(modInfo, errorStage, getCause()), context.stream()).toArray());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMessage() {
|
||||
return formatToString();
|
||||
}
|
||||
|
||||
public IModInfo getModInfo() {
|
||||
return modInfo;
|
||||
}
|
||||
public String getCleanMessage() {
|
||||
return ForgeI18n.stripControlCodes(formatToString());
|
||||
}
|
||||
}
|
||||
@@ -1,165 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import cpw.mods.modlauncher.api.LamdbaExceptionUtils;
|
||||
import net.minecraftforge.event.RegistryEvent;
|
||||
import net.minecraftforge.eventbus.api.Event;
|
||||
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
|
||||
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
|
||||
import net.minecraftforge.fml.event.lifecycle.FMLConstructModEvent;
|
||||
import net.minecraftforge.fml.event.lifecycle.FMLDedicatedServerSetupEvent;
|
||||
import net.minecraftforge.fml.event.lifecycle.FMLLoadCompleteEvent;
|
||||
import net.minecraftforge.fml.event.lifecycle.IModBusEvent;
|
||||
import net.minecraftforge.fml.event.lifecycle.InterModEnqueueEvent;
|
||||
import net.minecraftforge.fml.event.lifecycle.InterModProcessEvent;
|
||||
import net.minecraftforge.fml.event.lifecycle.ParallelDispatchEvent;
|
||||
import net.minecraftforge.registries.GameData;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.BinaryOperator;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public enum ModLoadingStage
|
||||
{
|
||||
ERROR(),
|
||||
VALIDATE(),
|
||||
CONSTRUCT(FMLConstructModEvent.class),
|
||||
CREATE_REGISTRIES(()->Stream.of(EventGenerator.fromFunction(RegistryEvent.NewRegistry::new))),
|
||||
LOAD_REGISTRIES(GameData::generateRegistryEvents, GameData::preRegistryEventDispatch, GameData::postRegistryEventDispatch, GameData::checkForRevertToVanilla),
|
||||
COMMON_SETUP(FMLCommonSetupEvent.class),
|
||||
SIDED_SETUP(DistExecutor.unsafeRunForDist(()->()->FMLClientSetupEvent.class, ()->()->FMLDedicatedServerSetupEvent.class)),
|
||||
ENQUEUE_IMC(InterModEnqueueEvent.class),
|
||||
PROCESS_IMC(InterModProcessEvent.class),
|
||||
COMPLETE(FMLLoadCompleteEvent.class),
|
||||
DONE();
|
||||
|
||||
private final Supplier<Stream<EventGenerator<?>>> eventFunctionStream;
|
||||
private final Optional<Class<? extends ParallelDispatchEvent>> parallelEventClass;
|
||||
private final ThreadSelector threadSelector;
|
||||
private final BiFunction<Executor, CompletableFuture<List<Throwable>>, CompletableFuture<List<Throwable>>> finalActivityGenerator;
|
||||
private final BiFunction<Executor, ? extends EventGenerator<?>, CompletableFuture<List<Throwable>>> preDispatchHook;
|
||||
private final BiFunction<Executor, ? extends EventGenerator<?>, CompletableFuture<List<Throwable>>> postDispatchHook;
|
||||
private DeferredWorkQueue deferredWorkQueue;
|
||||
|
||||
ModLoadingStage(Class<? extends ParallelDispatchEvent> parallelClass) {
|
||||
final EventGenerator<?> event = EventGenerator.fromFunction(LamdbaExceptionUtils.rethrowFunction((ModContainer mc) -> parallelClass.getConstructor(ModContainer.class).newInstance(mc)));
|
||||
this.eventFunctionStream = ()->Stream.of(event);
|
||||
this.threadSelector = ThreadSelector.PARALLEL;
|
||||
this.parallelEventClass = Optional.of(parallelClass);
|
||||
deferredWorkQueue = new DeferredWorkQueue(this, parallelClass);
|
||||
this.finalActivityGenerator = (e, prev) -> prev.thenApplyAsync((List<Throwable> t) -> {
|
||||
deferredWorkQueue.runTasks();
|
||||
return t;
|
||||
}, e);
|
||||
this.preDispatchHook = (t,f)->CompletableFuture.completedFuture(Collections.emptyList());
|
||||
this.postDispatchHook = (t,f)->CompletableFuture.completedFuture(Collections.emptyList());
|
||||
}
|
||||
|
||||
ModLoadingStage(Supplier<Stream<EventGenerator<?>>> eventStream) {
|
||||
this(eventStream, (t,f)->CompletableFuture.completedFuture(Collections.emptyList()), (t,f)->CompletableFuture.completedFuture(Collections.emptyList()), (e, prev) ->prev.thenApplyAsync(Function.identity(), e));
|
||||
}
|
||||
|
||||
<T extends Event & IModBusEvent> ModLoadingStage(Supplier<Stream<EventGenerator<?>>> eventStream, final BiFunction<Executor, ? extends EventGenerator<T>, CompletableFuture<List<Throwable>>> preDispatchHook, final BiFunction<Executor, ? extends EventGenerator<T>, CompletableFuture<List<Throwable>>> postDispatchHook, final BiFunction<Executor, CompletableFuture<List<Throwable>>, CompletableFuture<List<Throwable>>> finalActivityGenerator) {
|
||||
this.eventFunctionStream = eventStream;
|
||||
this.parallelEventClass = Optional.empty();
|
||||
this.threadSelector = ThreadSelector.SYNC;
|
||||
this.preDispatchHook = preDispatchHook;
|
||||
this.postDispatchHook = postDispatchHook;
|
||||
this.finalActivityGenerator = finalActivityGenerator;
|
||||
}
|
||||
|
||||
ModLoadingStage() {
|
||||
this(ParallelDispatchEvent.class);
|
||||
}
|
||||
|
||||
public <T extends Event & IModBusEvent> CompletableFuture<List<Throwable>> buildTransition(final Executor syncExecutor, final Executor parallelExecutor) {
|
||||
return buildTransition(syncExecutor, parallelExecutor, e->CompletableFuture.runAsync(()->{}, e), e->CompletableFuture.runAsync(()->{}, e));
|
||||
}
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T extends Event & IModBusEvent> CompletableFuture<List<Throwable>> buildTransition(final Executor syncExecutor, final Executor parallelExecutor, Function<Executor, CompletableFuture<Void>> preSyncTask, Function<Executor, CompletableFuture<Void>> postSyncTask) {
|
||||
List<CompletableFuture<List<Throwable>>> cfs = new ArrayList<>();
|
||||
this.eventFunctionStream.get()
|
||||
.map(f->(EventGenerator<T>)f)
|
||||
.reduce((head, tail)-> addCompletableFutureTaskForModDispatch(syncExecutor, parallelExecutor, cfs, head, ModLoadingStage::currentState, tail))
|
||||
.ifPresent(last-> addCompletableFutureTaskForModDispatch(syncExecutor, parallelExecutor, cfs, last, ModLoadingStage::nextState, null));
|
||||
final CompletableFuture<Void> preSyncTaskCF = preSyncTask.apply(syncExecutor);
|
||||
final CompletableFuture<List<Throwable>> eventDispatchCF = ModList.gather(cfs).thenCompose(ModList::completableFutureFromExceptionList);
|
||||
final CompletableFuture<List<Throwable>> postEventDispatchCF = preSyncTaskCF.thenComposeAsync(n -> eventDispatchCF, parallelExecutor).thenApply(r -> {
|
||||
postSyncTask.apply(syncExecutor);
|
||||
return r;
|
||||
});
|
||||
return this.finalActivityGenerator.apply(syncExecutor, postEventDispatchCF);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private <T extends Event & IModBusEvent> EventGenerator<T> addCompletableFutureTaskForModDispatch(final Executor syncExecutor, final Executor parallelExecutor, final List<CompletableFuture<List<Throwable>>> completeableFutures, final EventGenerator<T> eventGenerator, BiFunction<ModLoadingStage, Throwable, ModLoadingStage> nextState, final EventGenerator<T> nextGenerator) {
|
||||
completeableFutures.add(((BiFunction<Executor, EventGenerator<T>, CompletableFuture<List<Throwable>>>)preDispatchHook).apply(threadSelector.apply(syncExecutor, parallelExecutor), eventGenerator));
|
||||
completeableFutures.add(ModList.get().futureVisitor(eventGenerator, nextState).apply(threadSelector.apply(syncExecutor, parallelExecutor)));
|
||||
completeableFutures.add(((BiFunction<Executor, EventGenerator<T>, CompletableFuture<List<Throwable>>>)postDispatchHook).apply(threadSelector.apply(syncExecutor, parallelExecutor), eventGenerator));
|
||||
return nextGenerator;
|
||||
}
|
||||
|
||||
ModLoadingStage nextState(Throwable exception) {
|
||||
return exception != null ? ERROR : values()[this.ordinal()+1];
|
||||
}
|
||||
|
||||
ModLoadingStage currentState(Throwable exception) {
|
||||
return exception != null ? ERROR : this;
|
||||
}
|
||||
|
||||
public Optional<Class<? extends ParallelDispatchEvent>> getParallelEventClass() {
|
||||
return parallelEventClass;
|
||||
}
|
||||
enum ThreadSelector implements BinaryOperator<Executor> {
|
||||
SYNC((sync, parallel)->sync),
|
||||
PARALLEL((sync, parallel)->parallel);
|
||||
|
||||
private final BinaryOperator<Executor> selector;
|
||||
|
||||
ThreadSelector(final BinaryOperator<Executor> selector) {
|
||||
this.selector = selector;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Executor apply(final Executor sync, final Executor parallel) {
|
||||
return this.selector.apply(sync, parallel);
|
||||
}
|
||||
}
|
||||
|
||||
public DeferredWorkQueue getDeferredWorkQueue() {
|
||||
return deferredWorkQueue;
|
||||
}
|
||||
|
||||
public interface EventGenerator<T extends Event & IModBusEvent> extends Function<ModContainer, T> {
|
||||
static <FN extends Event & IModBusEvent> EventGenerator<FN> fromFunction(Function<ModContainer, FN> fn) {
|
||||
return fn::apply;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import com.google.common.collect.Streams;
|
||||
import net.minecraftforge.forgespi.language.IModInfo;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class ModLoadingWarning
|
||||
{
|
||||
/**
|
||||
* Mod Info for mod with warning
|
||||
*/
|
||||
private final IModInfo modInfo;
|
||||
/**
|
||||
* The stage where this warning was encountered
|
||||
*/
|
||||
private final ModLoadingStage warningStage;
|
||||
|
||||
/**
|
||||
* I18N message to use for display
|
||||
*/
|
||||
private final String i18nMessage;
|
||||
|
||||
/**
|
||||
* Context for message display
|
||||
*/
|
||||
private final List<Object> context;
|
||||
|
||||
public ModLoadingWarning(final IModInfo modInfo, final ModLoadingStage warningStage, final String i18nMessage, Object... context) {
|
||||
this.modInfo = modInfo;
|
||||
this.warningStage = warningStage;
|
||||
this.i18nMessage = i18nMessage;
|
||||
this.context = Arrays.asList(context);
|
||||
}
|
||||
|
||||
public String formatToString() {
|
||||
return ForgeI18n.parseMessage(i18nMessage, Streams.concat(Stream.of(modInfo, warningStage), context.stream()).toArray());
|
||||
}
|
||||
}
|
||||
@@ -1,125 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import net.minecraftforge.fml.loading.FMLConfig;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.locks.LockSupport;
|
||||
|
||||
import static net.minecraftforge.fml.Logging.LOADING;
|
||||
|
||||
public class ModWorkManager {
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
private static final long PARK_TIME = TimeUnit.MILLISECONDS.toNanos(1);
|
||||
public interface DrivenExecutor extends Executor {
|
||||
boolean selfDriven();
|
||||
boolean driveOne();
|
||||
|
||||
default void drive(Runnable ticker) {
|
||||
if (!selfDriven()) {
|
||||
while (driveOne()) {
|
||||
ticker.run();
|
||||
}
|
||||
} else {
|
||||
// park for a bit so other threads can schedule
|
||||
LockSupport.parkNanos(PARK_TIME);
|
||||
}
|
||||
}
|
||||
}
|
||||
private static class SyncExecutor implements DrivenExecutor {
|
||||
private ConcurrentLinkedDeque<Runnable> tasks = new ConcurrentLinkedDeque<>();
|
||||
|
||||
@Override
|
||||
public boolean driveOne() {
|
||||
final Runnable task = tasks.pollFirst();
|
||||
if (task != null) {
|
||||
task.run();
|
||||
}
|
||||
return task != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean selfDriven() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(final Runnable command) {
|
||||
tasks.addLast(command);
|
||||
}
|
||||
}
|
||||
|
||||
private static class WrappingExecutor implements DrivenExecutor {
|
||||
private final Executor wrapped;
|
||||
|
||||
public WrappingExecutor(final Executor executor) {
|
||||
this.wrapped = executor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean selfDriven() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean driveOne() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(final Runnable command) {
|
||||
wrapped.execute(command);
|
||||
}
|
||||
}
|
||||
|
||||
private static SyncExecutor syncExecutor;
|
||||
|
||||
public static DrivenExecutor syncExecutor() {
|
||||
if (syncExecutor == null)
|
||||
syncExecutor = new SyncExecutor();
|
||||
return syncExecutor;
|
||||
}
|
||||
|
||||
public static DrivenExecutor wrappedExecutor(Executor executor) {
|
||||
return new WrappingExecutor(executor);
|
||||
}
|
||||
|
||||
private static ForkJoinPool parallelThreadPool;
|
||||
public static Executor parallelExecutor() {
|
||||
if (parallelThreadPool == null) {
|
||||
final int loadingThreadCount = FMLConfig.loadingThreadCount();
|
||||
LOGGER.debug(LOADING, "Using {} threads for parallel mod-loading", loadingThreadCount);
|
||||
parallelThreadPool = new ForkJoinPool(loadingThreadCount, ModWorkManager::newForkJoinWorkerThread, null, false);
|
||||
}
|
||||
return parallelThreadPool;
|
||||
}
|
||||
|
||||
private static ForkJoinWorkerThread newForkJoinWorkerThread(ForkJoinPool pool) {
|
||||
ForkJoinWorkerThread thread = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool);
|
||||
thread.setName("modloading-worker-" + thread.getPoolIndex());
|
||||
// The default sets it to the SystemClassloader, so copy the current one.
|
||||
thread.setContextClassLoader(Thread.currentThread().getContextClassLoader());
|
||||
return thread;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,241 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public final class OptionalMod<T>
|
||||
{
|
||||
private final String modId;
|
||||
private T value;
|
||||
private boolean searched;
|
||||
|
||||
public static <M> OptionalMod<M> of(final String modId) {
|
||||
return new OptionalMod<>(modId);
|
||||
}
|
||||
|
||||
private static OptionalMod<?> EMPTY = new OptionalMod<>(true);
|
||||
private static <T> OptionalMod<T> empty() {
|
||||
@SuppressWarnings("unchecked")
|
||||
OptionalMod<T> t = (OptionalMod<T>) EMPTY;
|
||||
return t;
|
||||
}
|
||||
|
||||
private OptionalMod(boolean searched) {
|
||||
this.searched = searched;
|
||||
this.modId = "";
|
||||
}
|
||||
|
||||
private OptionalMod(String modId)
|
||||
{
|
||||
this.modId = modId;
|
||||
}
|
||||
|
||||
private T getValue()
|
||||
{
|
||||
if (!searched) {
|
||||
this.value = ModList.get().<T>getModObjectById(this.modId).orElse(null);
|
||||
searched = true;
|
||||
}
|
||||
return this.value;
|
||||
}
|
||||
|
||||
/**
|
||||
* If a mod is present in this {@code OptionalMod}, returns the value,
|
||||
* otherwise throws {@code NoSuchElementException}.
|
||||
*
|
||||
* @return the modobject held by this {@code OptionalMod}
|
||||
* @throws NoSuchElementException if there is no modobject present
|
||||
*
|
||||
* @see Optional#isPresent()
|
||||
*/
|
||||
public T get() {
|
||||
if (getValue() == null) {
|
||||
throw new NoSuchElementException("No value present");
|
||||
}
|
||||
return getValue();
|
||||
}
|
||||
|
||||
public String getModId() {
|
||||
return this.modId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return {@code true} if there is a mod object present, otherwise {@code false}.
|
||||
*
|
||||
* @return {@code true} if there is a mod object present, otherwise {@code false}
|
||||
*/
|
||||
public boolean isPresent() {
|
||||
return getValue() != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* If a mod object is present, invoke the specified consumer with the object,
|
||||
* otherwise do nothing.
|
||||
*
|
||||
* @param consumer block to be executed if a mod object is present
|
||||
* @throws NullPointerException if mod object is present and {@code consumer} is
|
||||
* null
|
||||
*/
|
||||
public void ifPresent(Consumer<? super T> consumer) {
|
||||
if (getValue() != null)
|
||||
consumer.accept(getValue());
|
||||
}
|
||||
|
||||
/**
|
||||
* If a mod object is present, and the mod object matches the given predicate,
|
||||
* return an {@code OptionalMod} describing the value, otherwise return an
|
||||
* empty {@code OptionalMod}.
|
||||
*
|
||||
* @param predicate a predicate to apply to the mod object, if present
|
||||
* @return an {@code OptionalMod} describing the value of this {@code OptionalMod}
|
||||
* if a mod object is present and the mod object matches the given predicate,
|
||||
* otherwise an empty {@code OptionalMod}
|
||||
* @throws NullPointerException if the predicate is null
|
||||
*/
|
||||
public OptionalMod<T> filter(Predicate<? super T> predicate) {
|
||||
Objects.requireNonNull(predicate);
|
||||
if (!isPresent())
|
||||
return this;
|
||||
else
|
||||
return predicate.test(getValue()) ? this : empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* If a mod object is present, apply the provided mapping function to it,
|
||||
* and if the result is non-null, return an {@code Optional} describing the
|
||||
* result. Otherwise return an empty {@code Optional}.
|
||||
*
|
||||
* @apiNote This method supports post-processing on optional values, without
|
||||
* the need to explicitly check for a return status.
|
||||
*
|
||||
* @param <U> The type of the result of the mapping function
|
||||
* @param mapper a mapping function to apply to the mod object, if present
|
||||
* @return an {@code Optional} describing the result of applying a mapping
|
||||
* function to the mod object of this {@code OptionalMod}, if a mod object is present,
|
||||
* otherwise an empty {@code Optional}
|
||||
* @throws NullPointerException if the mapping function is null
|
||||
*/
|
||||
public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
|
||||
Objects.requireNonNull(mapper);
|
||||
if (!isPresent())
|
||||
return Optional.empty();
|
||||
else {
|
||||
return Optional.ofNullable(mapper.apply(getValue()));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* If a value is present, apply the provided {@code Optional}-bearing
|
||||
* mapping function to it, return that result, otherwise return an empty
|
||||
* {@code Optional}. This method is similar to {@link #map(Function)},
|
||||
* but the provided mapper is one whose result is already an {@code Optional},
|
||||
* and if invoked, {@code flatMap} does not wrap it with an additional
|
||||
* {@code Optional}.
|
||||
*
|
||||
* @param <U> The type parameter to the {@code Optional} returned by
|
||||
* @param mapper a mapping function to apply to the mod object, if present
|
||||
* the mapping function
|
||||
* @return the result of applying an {@code Optional}-bearing mapping
|
||||
* function to the value of this {@code Optional}, if a value is present,
|
||||
* otherwise an empty {@code Optional}
|
||||
* @throws NullPointerException if the mapping function is null or returns
|
||||
* a null result
|
||||
*/
|
||||
public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) {
|
||||
Objects.requireNonNull(mapper);
|
||||
if (!isPresent())
|
||||
return Optional.empty();
|
||||
else {
|
||||
return Objects.requireNonNull(mapper.apply(getValue()));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the mod object if present, otherwise return {@code other}.
|
||||
*
|
||||
* @param other the mod object to be returned if there is no mod object present, may
|
||||
* be null
|
||||
* @return the mod object, if present, otherwise {@code other}
|
||||
*/
|
||||
public T orElse(T other) {
|
||||
return getValue() != null ? getValue() : other;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the mod object if present, otherwise invoke {@code other} and return
|
||||
* the result of that invocation.
|
||||
*
|
||||
* @param other a {@code Supplier} whose result is returned if no mod object
|
||||
* is present
|
||||
* @return the mod object if present otherwise the result of {@code other.get()}
|
||||
* @throws NullPointerException if mod object is not present and {@code other} is
|
||||
* null
|
||||
*/
|
||||
public T orElseGet(Supplier<? extends T> other) {
|
||||
return getValue() != null ? getValue() : other.get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the contained mod object, if present, otherwise throw an exception
|
||||
* to be created by the provided supplier.
|
||||
*
|
||||
* @apiNote A method reference to the exception constructor with an empty
|
||||
* argument list can be used as the supplier. For example,
|
||||
* {@code IllegalStateException::new}
|
||||
*
|
||||
* @param <X> Type of the exception to be thrown
|
||||
* @param exceptionSupplier The supplier which will return the exception to
|
||||
* be thrown
|
||||
* @return the present mod object
|
||||
* @throws X if there is no mod object present
|
||||
* @throws NullPointerException if no mod object is present and
|
||||
* {@code exceptionSupplier} is null
|
||||
*/
|
||||
public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
|
||||
if (getValue() != null) {
|
||||
return getValue();
|
||||
} else {
|
||||
throw exceptionSupplier.get();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj)
|
||||
{
|
||||
if (this == obj) return true;
|
||||
if (obj instanceof OptionalMod) {
|
||||
return Objects.equals(((OptionalMod)obj).modId, modId);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode()
|
||||
{
|
||||
return Objects.hashCode(modId);
|
||||
}
|
||||
}
|
||||
@@ -1,313 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import net.minecraftforge.registries.IForgeRegistry;
|
||||
import net.minecraftforge.registries.IForgeRegistryEntry;
|
||||
import net.minecraftforge.registries.ObjectHolderRegistry;
|
||||
import net.minecraftforge.registries.RegistryManager;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public final class RegistryObject<T extends IForgeRegistryEntry<? super T>> implements Supplier<T>
|
||||
{
|
||||
private final ResourceLocation name;
|
||||
@Nullable
|
||||
private T value;
|
||||
|
||||
public static <T extends IForgeRegistryEntry<T>, U extends T> RegistryObject<U> of(final ResourceLocation name, Supplier<Class<? super T>> registryType) {
|
||||
return new RegistryObject<>(name, registryType);
|
||||
}
|
||||
|
||||
public static <T extends IForgeRegistryEntry<T>, U extends T> RegistryObject<U> of(final ResourceLocation name, IForgeRegistry<T> registry) {
|
||||
return new RegistryObject<>(name, registry);
|
||||
}
|
||||
|
||||
public static <T extends IForgeRegistryEntry<T>, U extends T> RegistryObject<U> of(final ResourceLocation name, final Class<T> baseType, String modid) {
|
||||
return new RegistryObject<>(name, baseType, modid);
|
||||
}
|
||||
|
||||
private static RegistryObject<?> EMPTY = new RegistryObject<>();
|
||||
|
||||
private static <T extends IForgeRegistryEntry<? super T>> RegistryObject<T> empty() {
|
||||
@SuppressWarnings("unchecked")
|
||||
RegistryObject<T> t = (RegistryObject<T>) EMPTY;
|
||||
return t;
|
||||
}
|
||||
|
||||
private RegistryObject() {
|
||||
this.name = null;
|
||||
}
|
||||
|
||||
private <V extends IForgeRegistryEntry<V>> RegistryObject(ResourceLocation name, Supplier<Class<? super V>> registryType)
|
||||
{
|
||||
this(name, RegistryManager.ACTIVE.<V>getRegistry(registryType.get()));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private <V extends IForgeRegistryEntry<V>> RegistryObject(ResourceLocation name, IForgeRegistry<V> registry)
|
||||
{
|
||||
if (registry == null)
|
||||
throw new IllegalArgumentException("Invalid registry argument, must not be null");
|
||||
this.name = name;
|
||||
ObjectHolderRegistry.addHandler(pred ->
|
||||
{
|
||||
if (pred.test(registry.getRegistryName()))
|
||||
this.value = registry.containsKey(this.name) ? (T)registry.getValue(this.name) : null;
|
||||
});
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private <V extends IForgeRegistryEntry<V>> RegistryObject(final ResourceLocation name, final Class<V> baseType, final String modid)
|
||||
{
|
||||
this.name = name;
|
||||
final Throwable callerStack = new Throwable("Calling Site from mod: " + modid);
|
||||
ObjectHolderRegistry.addHandler(new Consumer<Predicate<ResourceLocation>>()
|
||||
{
|
||||
private IForgeRegistry<V> registry;
|
||||
|
||||
@Override
|
||||
public void accept(Predicate<ResourceLocation> pred)
|
||||
{
|
||||
if (registry == null)
|
||||
{
|
||||
this.registry = RegistryManager.ACTIVE.getRegistry(baseType);
|
||||
if (registry == null)
|
||||
throw new IllegalStateException("Unable to find registry for type " + baseType.getName() + " for mod \"" + modid + "\". Check the 'caused by' to see futher stack.", callerStack);
|
||||
}
|
||||
if (pred.test(registry.getRegistryName()))
|
||||
RegistryObject.this.value = registry.containsKey(RegistryObject.this.name) ? (T)registry.getValue(RegistryObject.this.name) : null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Directly retrieves the wrapped Registry Object. This value will automatically be updated when the backing registry is updated.
|
||||
* Will throw NPE if the value is null, use isPresent to check first. Or use any of the other guarded functions.
|
||||
*/
|
||||
@Override
|
||||
@Nonnull
|
||||
public T get()
|
||||
{
|
||||
T ret = this.value;
|
||||
Objects.requireNonNull(ret, () -> "Registry Object not present: " + this.name);
|
||||
return ret;
|
||||
}
|
||||
|
||||
public void updateReference(IForgeRegistry<? extends T> registry)
|
||||
{
|
||||
this.value = registry.getValue(getId());
|
||||
}
|
||||
|
||||
public ResourceLocation getId()
|
||||
{
|
||||
return this.name;
|
||||
}
|
||||
|
||||
public Stream<T> stream() {
|
||||
return isPresent() ? Stream.of(get()) : Stream.of();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return {@code true} if there is a mod object present, otherwise {@code false}.
|
||||
*
|
||||
* @return {@code true} if there is a mod object present, otherwise {@code false}
|
||||
*/
|
||||
public boolean isPresent() {
|
||||
return this.value != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* If a mod object is present, invoke the specified consumer with the object,
|
||||
* otherwise do nothing.
|
||||
*
|
||||
* @param consumer block to be executed if a mod object is present
|
||||
* @throws NullPointerException if mod object is present and {@code consumer} is
|
||||
* null
|
||||
*/
|
||||
public void ifPresent(Consumer<? super T> consumer) {
|
||||
if (isPresent())
|
||||
consumer.accept(get());
|
||||
}
|
||||
|
||||
/**
|
||||
* If a mod object is present, and the mod object matches the given predicate,
|
||||
* return an {@code RegistryObject} describing the value, otherwise return an
|
||||
* empty {@code RegistryObject}.
|
||||
*
|
||||
* @param predicate a predicate to apply to the mod object, if present
|
||||
* @return an {@code RegistryObject} describing the value of this {@code RegistryObject}
|
||||
* if a mod object is present and the mod object matches the given predicate,
|
||||
* otherwise an empty {@code RegistryObject}
|
||||
* @throws NullPointerException if the predicate is null
|
||||
*/
|
||||
public RegistryObject<T> filter(Predicate<? super T> predicate) {
|
||||
Objects.requireNonNull(predicate);
|
||||
if (!isPresent())
|
||||
return this;
|
||||
else
|
||||
return predicate.test(get()) ? this : empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* If a mod object is present, apply the provided mapping function to it,
|
||||
* and if the result is non-null, return an {@code Optional} describing the
|
||||
* result. Otherwise return an empty {@code Optional}.
|
||||
*
|
||||
* @apiNote This method supports post-processing on optional values, without
|
||||
* the need to explicitly check for a return status.
|
||||
*
|
||||
* @param <U> The type of the result of the mapping function
|
||||
* @param mapper a mapping function to apply to the mod object, if present
|
||||
* @return an {@code Optional} describing the result of applying a mapping
|
||||
* function to the mod object of this {@code RegistryObject}, if a mod object is present,
|
||||
* otherwise an empty {@code Optional}
|
||||
* @throws NullPointerException if the mapping function is null
|
||||
*/
|
||||
public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
|
||||
Objects.requireNonNull(mapper);
|
||||
if (!isPresent())
|
||||
return Optional.empty();
|
||||
else {
|
||||
return Optional.ofNullable(mapper.apply(get()));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* If a value is present, apply the provided {@code Optional}-bearing
|
||||
* mapping function to it, return that result, otherwise return an empty
|
||||
* {@code Optional}. This method is similar to {@link #map(Function)},
|
||||
* but the provided mapper is one whose result is already an {@code Optional},
|
||||
* and if invoked, {@code flatMap} does not wrap it with an additional
|
||||
* {@code Optional}.
|
||||
*
|
||||
* @param <U> The type parameter to the {@code Optional} returned by
|
||||
* @param mapper a mapping function to apply to the mod object, if present
|
||||
* the mapping function
|
||||
* @return the result of applying an {@code Optional}-bearing mapping
|
||||
* function to the value of this {@code Optional}, if a value is present,
|
||||
* otherwise an empty {@code Optional}
|
||||
* @throws NullPointerException if the mapping function is null or returns
|
||||
* a null result
|
||||
*/
|
||||
public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) {
|
||||
Objects.requireNonNull(mapper);
|
||||
if (!isPresent())
|
||||
return Optional.empty();
|
||||
else {
|
||||
return Objects.requireNonNull(mapper.apply(get()));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* If a mod object is present, lazily apply the provided mapping function to it,
|
||||
* returning a supplier for the transformed result. If this object is empty, or the
|
||||
* mapping function returns {@code null}, the supplier will return {@code null}.
|
||||
*
|
||||
* @apiNote This method supports post-processing on optional values, without
|
||||
* the need to explicitly check for a return status.
|
||||
*
|
||||
* @param <U> The type of the result of the mapping function
|
||||
* @param mapper A mapping function to apply to the mod object, if present
|
||||
* @return A {@code Supplier} lazily providing the result of applying a mapping
|
||||
* function to the mod object of this {@code RegistryObject}, if a mod object is present,
|
||||
* otherwise a supplier returning {@code null}
|
||||
* @throws NullPointerException if the mapping function is {@code null}
|
||||
*/
|
||||
public<U> Supplier<U> lazyMap(Function<? super T, ? extends U> mapper) {
|
||||
Objects.requireNonNull(mapper);
|
||||
return () -> isPresent() ? mapper.apply(get()) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the mod object if present, otherwise return {@code other}.
|
||||
*
|
||||
* @param other the mod object to be returned if there is no mod object present, may
|
||||
* be null
|
||||
* @return the mod object, if present, otherwise {@code other}
|
||||
*/
|
||||
public T orElse(T other) {
|
||||
return isPresent() ? get() : other;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the mod object if present, otherwise invoke {@code other} and return
|
||||
* the result of that invocation.
|
||||
*
|
||||
* @param other a {@code Supplier} whose result is returned if no mod object
|
||||
* is present
|
||||
* @return the mod object if present otherwise the result of {@code other.get()}
|
||||
* @throws NullPointerException if mod object is not present and {@code other} is
|
||||
* null
|
||||
*/
|
||||
public T orElseGet(Supplier<? extends T> other) {
|
||||
return isPresent() ? get() : other.get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the contained mod object, if present, otherwise throw an exception
|
||||
* to be created by the provided supplier.
|
||||
*
|
||||
* @apiNote A method reference to the exception constructor with an empty
|
||||
* argument list can be used as the supplier. For example,
|
||||
* {@code IllegalStateException::new}
|
||||
*
|
||||
* @param <X> Type of the exception to be thrown
|
||||
* @param exceptionSupplier The supplier which will return the exception to
|
||||
* be thrown
|
||||
* @return the present mod object
|
||||
* @throws X if there is no mod object present
|
||||
* @throws NullPointerException if no mod object is present and
|
||||
* {@code exceptionSupplier} is null
|
||||
*/
|
||||
public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
|
||||
if (isPresent()) {
|
||||
return get();
|
||||
} else {
|
||||
throw exceptionSupplier.get();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj)
|
||||
{
|
||||
if (this == obj) return true;
|
||||
if (obj instanceof RegistryObject) {
|
||||
return Objects.equals(((RegistryObject<?>)obj).name, name);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode()
|
||||
{
|
||||
return Objects.hashCode(name);
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
public class StartupMessageManager {
|
||||
public static void addModMessage(final String message) {
|
||||
net.minecraftforge.fml.loading.progress.StartupMessageManager.addModMessage(message);
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import net.minecraft.util.text.ITextProperties;
|
||||
import net.minecraft.util.text.StringTextComponent;
|
||||
import net.minecraft.util.text.TranslationTextComponent;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class TextComponentMessageFormatHandler {
|
||||
public static int handle(final TranslationTextComponent parent, final List<ITextProperties> children, final Object[] formatArgs, final String format) {
|
||||
try {
|
||||
StringTextComponent component = new StringTextComponent(ForgeI18n.parseFormat(format, formatArgs));
|
||||
component.getStyle().applyTo(parent.getStyle());
|
||||
children.add(component);
|
||||
return format.length();
|
||||
} catch (IllegalArgumentException ex) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,297 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import com.google.common.io.ByteStreams;
|
||||
import com.google.gson.Gson;
|
||||
import net.minecraftforge.fml.loading.FMLConfig;
|
||||
import net.minecraftforge.fml.loading.moddiscovery.ModInfo;
|
||||
import net.minecraftforge.forgespi.language.IModInfo;
|
||||
import net.minecraftforge.versions.mcp.MCPVersion;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.apache.maven.artifact.versioning.ComparableVersion;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
import static net.minecraftforge.fml.VersionChecker.Status.*;
|
||||
|
||||
public class VersionChecker
|
||||
{
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
private static final int MAX_HTTP_REDIRECTS = Integer.getInteger("http.maxRedirects", 20);
|
||||
|
||||
public enum Status
|
||||
{
|
||||
PENDING(),
|
||||
FAILED(),
|
||||
UP_TO_DATE(),
|
||||
OUTDATED(3, true),
|
||||
AHEAD(),
|
||||
BETA(),
|
||||
BETA_OUTDATED(6, true);
|
||||
|
||||
final int sheetOffset;
|
||||
final boolean draw, animated;
|
||||
|
||||
Status()
|
||||
{
|
||||
this(0, false, false);
|
||||
}
|
||||
|
||||
Status(int sheetOffset)
|
||||
{
|
||||
this(sheetOffset, true, false);
|
||||
}
|
||||
|
||||
Status(int sheetOffset, boolean animated)
|
||||
{
|
||||
this(sheetOffset, true, animated);
|
||||
}
|
||||
|
||||
Status(int sheetOffset, boolean draw, boolean animated)
|
||||
{
|
||||
this.sheetOffset = sheetOffset;
|
||||
this.draw = draw;
|
||||
this.animated = animated;
|
||||
}
|
||||
|
||||
public int getSheetOffset()
|
||||
{
|
||||
return sheetOffset;
|
||||
}
|
||||
|
||||
public boolean shouldDraw()
|
||||
{
|
||||
return draw;
|
||||
}
|
||||
|
||||
public boolean isAnimated()
|
||||
{
|
||||
return animated;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class CheckResult
|
||||
{
|
||||
@Nonnull
|
||||
public final Status status;
|
||||
@Nullable
|
||||
public final ComparableVersion target;
|
||||
@Nullable
|
||||
public final Map<ComparableVersion, String> changes;
|
||||
@Nullable
|
||||
public final String url;
|
||||
|
||||
private CheckResult(@Nonnull Status status, @Nullable ComparableVersion target, @Nullable Map<ComparableVersion, String> changes, @Nullable String url)
|
||||
{
|
||||
this.status = status;
|
||||
this.target = target;
|
||||
this.changes = changes == null ? Collections.<ComparableVersion, String>emptyMap() : Collections.unmodifiableMap(changes);
|
||||
this.url = url;
|
||||
}
|
||||
}
|
||||
|
||||
public static void startVersionCheck()
|
||||
{
|
||||
new Thread("Forge Version Check")
|
||||
{
|
||||
@Override
|
||||
public void run()
|
||||
{
|
||||
if (!FMLConfig.runVersionCheck())
|
||||
{
|
||||
LOGGER.info("Global Forge version check system disabled, no further processing.");
|
||||
return;
|
||||
}
|
||||
|
||||
gatherMods().forEach(this::process);
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens stream for given URL while following redirects
|
||||
*/
|
||||
private InputStream openUrlStream(URL url) throws IOException
|
||||
{
|
||||
URL currentUrl = url;
|
||||
for (int redirects = 0; redirects < MAX_HTTP_REDIRECTS; redirects++)
|
||||
{
|
||||
URLConnection c = currentUrl.openConnection();
|
||||
if (c instanceof HttpURLConnection)
|
||||
{
|
||||
HttpURLConnection huc = (HttpURLConnection) c;
|
||||
huc.setInstanceFollowRedirects(false);
|
||||
int responseCode = huc.getResponseCode();
|
||||
if (responseCode >= 300 && responseCode <= 399)
|
||||
{
|
||||
try
|
||||
{
|
||||
String loc = huc.getHeaderField("Location");
|
||||
currentUrl = new URL(currentUrl, loc);
|
||||
continue;
|
||||
}
|
||||
finally
|
||||
{
|
||||
huc.disconnect();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return c.getInputStream();
|
||||
}
|
||||
throw new IOException("Too many redirects while trying to fetch " + url);
|
||||
}
|
||||
|
||||
private void process(IModInfo mod)
|
||||
{
|
||||
Status status = PENDING;
|
||||
ComparableVersion target = null;
|
||||
Map<ComparableVersion, String> changes = null;
|
||||
String display_url = null;
|
||||
try
|
||||
{
|
||||
URL url = mod.getUpdateURL();
|
||||
LOGGER.info("[{}] Starting version check at {}", mod.getModId(), url.toString());
|
||||
|
||||
InputStream con = openUrlStream(url);
|
||||
String data = new String(ByteStreams.toByteArray(con), StandardCharsets.UTF_8);
|
||||
con.close();
|
||||
|
||||
LOGGER.debug("[{}] Received version check data:\n{}", mod.getModId(), data);
|
||||
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> json = new Gson().fromJson(data, Map.class);
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, String> promos = (Map<String, String>)json.get("promos");
|
||||
display_url = (String)json.get("homepage");
|
||||
|
||||
String mcVersion = MCPVersion.getMCVersion();
|
||||
String rec = promos.get(mcVersion + "-recommended");
|
||||
String lat = promos.get(mcVersion + "-latest");
|
||||
ComparableVersion current = new ComparableVersion(mod.getVersion().toString());
|
||||
|
||||
if (rec != null)
|
||||
{
|
||||
ComparableVersion recommended = new ComparableVersion(rec);
|
||||
int diff = recommended.compareTo(current);
|
||||
|
||||
if (diff == 0)
|
||||
status = UP_TO_DATE;
|
||||
else if (diff < 0)
|
||||
{
|
||||
status = AHEAD;
|
||||
if (lat != null)
|
||||
{
|
||||
ComparableVersion latest = new ComparableVersion(lat);
|
||||
if (current.compareTo(latest) < 0)
|
||||
{
|
||||
status = OUTDATED;
|
||||
target = latest;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
status = OUTDATED;
|
||||
target = recommended;
|
||||
}
|
||||
}
|
||||
else if (lat != null)
|
||||
{
|
||||
ComparableVersion latest = new ComparableVersion(lat);
|
||||
if (current.compareTo(latest) < 0)
|
||||
status = BETA_OUTDATED;
|
||||
else
|
||||
status = BETA;
|
||||
target = latest;
|
||||
}
|
||||
else
|
||||
status = BETA;
|
||||
|
||||
LOGGER.info("[{}] Found status: {} Current: {} Target: {}", mod.getModId(), status, current, target);
|
||||
|
||||
changes = new LinkedHashMap<>();
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, String> tmp = (Map<String, String>)json.get(mcVersion);
|
||||
if (tmp != null)
|
||||
{
|
||||
List<ComparableVersion> ordered = new ArrayList<>();
|
||||
for (String key : tmp.keySet())
|
||||
{
|
||||
ComparableVersion ver = new ComparableVersion(key);
|
||||
if (ver.compareTo(current) > 0 && (target == null || ver.compareTo(target) < 1))
|
||||
{
|
||||
ordered.add(ver);
|
||||
}
|
||||
}
|
||||
Collections.sort(ordered);
|
||||
|
||||
for (ComparableVersion ver : ordered)
|
||||
{
|
||||
changes.put(ver, tmp.get(ver.toString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
LOGGER.warn("Failed to process update information", e);
|
||||
status = FAILED;
|
||||
}
|
||||
results.put(mod, new CheckResult(status, target, changes, display_url));
|
||||
}
|
||||
}.start();
|
||||
}
|
||||
|
||||
// Gather a list of mods that have opted in to this update system by providing a URL.
|
||||
private static List<IModInfo> gatherMods()
|
||||
{
|
||||
List<IModInfo> ret = new LinkedList<>();
|
||||
for (ModInfo info : ModList.get().getMods()) {
|
||||
URL url = info.getUpdateURL();
|
||||
if (url != null)
|
||||
ret.add(info);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
private static Map<IModInfo, CheckResult> results = new ConcurrentHashMap<>();
|
||||
private static final CheckResult PENDING_CHECK = new CheckResult(PENDING, null, null, null);
|
||||
|
||||
public static CheckResult getResult(IModInfo mod)
|
||||
{
|
||||
return results.getOrDefault(mod, PENDING_CHECK);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml;
|
||||
|
||||
import net.minecraft.nbt.CompoundNBT;
|
||||
import net.minecraft.world.storage.IServerConfiguration;
|
||||
import net.minecraft.world.storage.SaveFormat;
|
||||
import net.minecraftforge.fml.common.thread.EffectiveSide;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class WorldPersistenceHooks
|
||||
{
|
||||
private static List<WorldPersistenceHook> worldPersistenceHooks = new ArrayList<>();
|
||||
|
||||
public static void addHook(WorldPersistenceHook hook) {
|
||||
worldPersistenceHooks.add(hook);
|
||||
}
|
||||
|
||||
public static void handleWorldDataSave(final SaveFormat.LevelSave levelSave, final IServerConfiguration serverInfo, final CompoundNBT tagCompound)
|
||||
{
|
||||
worldPersistenceHooks.forEach(wac->tagCompound.put(wac.getModId(), wac.getDataForWriting(levelSave, serverInfo)));
|
||||
}
|
||||
|
||||
public static void handleWorldDataLoad(SaveFormat.LevelSave levelSave, IServerConfiguration serverInfo, CompoundNBT tagCompound)
|
||||
{
|
||||
worldPersistenceHooks.forEach(wac->wac.readData(levelSave, serverInfo, tagCompound.getCompound(wac.getModId())));
|
||||
}
|
||||
|
||||
public interface WorldPersistenceHook
|
||||
{
|
||||
String getModId();
|
||||
CompoundNBT getDataForWriting(SaveFormat.LevelSave levelSave, IServerConfiguration serverInfo);
|
||||
void readData(SaveFormat.LevelSave levelSave, IServerConfiguration serverInfo, CompoundNBT tag);
|
||||
}
|
||||
}
|
||||
@@ -1,322 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.client;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
import com.google.common.collect.HashBasedTable;
|
||||
import com.google.common.collect.HashMultimap;
|
||||
import com.google.common.collect.SetMultimap;
|
||||
import com.google.common.collect.Sets;
|
||||
import com.google.common.collect.Table;
|
||||
import com.mojang.blaze3d.matrix.MatrixStack;
|
||||
import net.minecraft.client.entity.player.ClientPlayerEntity;
|
||||
import net.minecraft.client.gui.AbstractGui;
|
||||
import net.minecraft.client.gui.screen.MultiplayerScreen;
|
||||
import net.minecraft.client.multiplayer.PlayerController;
|
||||
import net.minecraft.util.text.StringTextComponent;
|
||||
import net.minecraftforge.client.event.ClientPlayerNetworkEvent;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.fml.ExtensionPoint;
|
||||
import net.minecraftforge.fml.ForgeI18n;
|
||||
import net.minecraftforge.fml.ModList;
|
||||
import net.minecraftforge.fml.network.FMLNetworkConstants;
|
||||
import net.minecraftforge.fml.network.NetworkRegistry;
|
||||
import net.minecraftforge.versions.forge.ForgeVersion;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.apache.logging.log4j.Marker;
|
||||
import org.apache.logging.log4j.MarkerManager;
|
||||
|
||||
import com.google.common.base.MoreObjects;
|
||||
import com.google.common.base.Strings;
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.multiplayer.ServerData;
|
||||
import net.minecraft.client.world.ClientWorld;
|
||||
import net.minecraft.network.NetworkManager;
|
||||
import net.minecraft.network.ServerStatusResponse;
|
||||
import net.minecraft.resources.ResourcePack;
|
||||
import net.minecraft.resources.FallbackResourceManager;
|
||||
import net.minecraft.resources.IResourcePack;
|
||||
import net.minecraft.resources.SimpleReloadableResourceManager;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import net.minecraftforge.fml.common.ObfuscationReflectionHelper;
|
||||
import net.minecraftforge.forgespi.language.IModInfo;
|
||||
import net.minecraftforge.fml.packs.ModFileResourcePack;
|
||||
import net.minecraftforge.registries.GameData;
|
||||
|
||||
public class ClientHooks
|
||||
{
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
private static final Marker CLIENTHOOKS = MarkerManager.getMarker("CLIENTHOOKS");
|
||||
|
||||
private static final ResourceLocation iconSheet = new ResourceLocation(ForgeVersion.MOD_ID, "textures/gui/icons.png");
|
||||
@Nullable
|
||||
|
||||
public static void processForgeListPingData(ServerStatusResponse packet, ServerData target)
|
||||
{
|
||||
if (packet.getForgeData() != null) {
|
||||
final Map<String, String> mods = packet.getForgeData().getRemoteModData();
|
||||
final Map<ResourceLocation, Pair<String, Boolean>> remoteChannels = packet.getForgeData().getRemoteChannels();
|
||||
final int fmlver = packet.getForgeData().getFMLNetworkVersion();
|
||||
|
||||
boolean fmlNetMatches = fmlver == FMLNetworkConstants.FMLNETVERSION;
|
||||
boolean channelsMatch = NetworkRegistry.checkListPingCompatibilityForClient(remoteChannels);
|
||||
AtomicBoolean result = new AtomicBoolean(true);
|
||||
final List<String> extraClientMods = new ArrayList<>();
|
||||
ModList.get().forEachModContainer((modid, mc) ->
|
||||
mc.getCustomExtension(ExtensionPoint.DISPLAYTEST).ifPresent(ext-> {
|
||||
boolean foundModOnServer = ext.getRight().test(mods.get(modid), true);
|
||||
result.compareAndSet(true, foundModOnServer);
|
||||
if (!foundModOnServer) {
|
||||
extraClientMods.add(modid);
|
||||
}
|
||||
})
|
||||
);
|
||||
boolean modsMatch = result.get();
|
||||
|
||||
final Map<String, String> extraServerMods = mods.entrySet().stream().
|
||||
filter(e -> !Objects.equals(FMLNetworkConstants.IGNORESERVERONLY, e.getValue())).
|
||||
filter(e -> !ModList.get().isLoaded(e.getKey())).
|
||||
collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
|
||||
|
||||
LOGGER.debug(CLIENTHOOKS, "Received FML ping data from server at {}: FMLNETVER={}, mod list is compatible : {}, channel list is compatible: {}, extra server mods: {}", target.ip, fmlver, modsMatch, channelsMatch, extraServerMods);
|
||||
|
||||
String extraReason = null;
|
||||
|
||||
if (!extraServerMods.isEmpty()) {
|
||||
extraReason = "fml.menu.multiplayer.extraservermods";
|
||||
LOGGER.info(CLIENTHOOKS, ForgeI18n.parseMessage(extraReason) + ": {}", extraServerMods.entrySet().stream()
|
||||
.map(e -> e.getKey() + "@" + e.getValue())
|
||||
.collect(Collectors.joining(", ")));
|
||||
}
|
||||
if (!modsMatch) {
|
||||
extraReason = "fml.menu.multiplayer.modsincompatible";
|
||||
LOGGER.info(CLIENTHOOKS, "Client has mods that are missing on server: {}", extraClientMods);
|
||||
}
|
||||
if (!channelsMatch) {
|
||||
extraReason = "fml.menu.multiplayer.networkincompatible";
|
||||
}
|
||||
|
||||
if (fmlver < FMLNetworkConstants.FMLNETVERSION) {
|
||||
extraReason = "fml.menu.multiplayer.serveroutdated";
|
||||
}
|
||||
if (fmlver > FMLNetworkConstants.FMLNETVERSION) {
|
||||
extraReason = "fml.menu.multiplayer.clientoutdated";
|
||||
}
|
||||
target.forgeData = new ExtendedServerListData("FML", extraServerMods.isEmpty() && fmlNetMatches && channelsMatch && modsMatch, mods.size(), extraReason, packet.getForgeData().isTruncated());
|
||||
} else {
|
||||
target.forgeData = new ExtendedServerListData("VANILLA", NetworkRegistry.canConnectToVanillaServer(),0, null);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static void drawForgePingInfo(MultiplayerScreen gui, ServerData target, MatrixStack mStack, int x, int y, int width, int relativeMouseX, int relativeMouseY) {
|
||||
int idx;
|
||||
String tooltip;
|
||||
if (target.forgeData == null)
|
||||
return;
|
||||
switch (target.forgeData.type) {
|
||||
case "FML":
|
||||
if (target.forgeData.isCompatible) {
|
||||
idx = 0;
|
||||
tooltip = ForgeI18n.parseMessage("fml.menu.multiplayer.compatible", target.forgeData.numberOfMods);
|
||||
} else {
|
||||
idx = 16;
|
||||
if(target.forgeData.extraReason != null) {
|
||||
String extraReason = ForgeI18n.parseMessage(target.forgeData.extraReason);
|
||||
tooltip = ForgeI18n.parseMessage("fml.menu.multiplayer.incompatible.extra", extraReason);
|
||||
} else {
|
||||
tooltip = ForgeI18n.parseMessage("fml.menu.multiplayer.incompatible");
|
||||
}
|
||||
}
|
||||
if (target.forgeData.truncated)
|
||||
{
|
||||
tooltip += "\n" + ForgeI18n.parseMessage("fml.menu.multiplayer.truncated");
|
||||
}
|
||||
break;
|
||||
case "VANILLA":
|
||||
if (target.forgeData.isCompatible) {
|
||||
idx = 48;
|
||||
tooltip = ForgeI18n.parseMessage("fml.menu.multiplayer.vanilla");
|
||||
} else {
|
||||
idx = 80;
|
||||
tooltip = ForgeI18n.parseMessage("fml.menu.multiplayer.vanilla.incompatible");
|
||||
}
|
||||
break;
|
||||
default:
|
||||
idx = 64;
|
||||
tooltip = ForgeI18n.parseMessage("fml.menu.multiplayer.unknown", target.forgeData.type);
|
||||
}
|
||||
|
||||
Minecraft.getInstance().getTextureManager().bind(iconSheet);
|
||||
AbstractGui.blit(mStack, x + width - 18, y + 10, 16, 16, 0, idx, 16, 16, 256, 256);
|
||||
|
||||
if(relativeMouseX > width - 15 && relativeMouseX < width && relativeMouseY > 10 && relativeMouseY < 26) {
|
||||
//this is not the most proper way to do it,
|
||||
//but works best here and has the least maintenance overhead
|
||||
gui.setToolTip(Arrays.stream(tooltip.split("\n")).map(StringTextComponent::new).collect(Collectors.toList()));
|
||||
}
|
||||
}
|
||||
|
||||
public static String fixDescription(String description)
|
||||
{
|
||||
return description.endsWith(":NOFML§r") ? description.substring(0, description.length() - 8)+"§r" : description;
|
||||
}
|
||||
|
||||
@SuppressWarnings("resource")
|
||||
static File getSavesDir()
|
||||
{
|
||||
return new File(Minecraft.getInstance().gameDirectory, "saves");
|
||||
}
|
||||
|
||||
private static NetworkManager getClientToServerNetworkManager()
|
||||
{
|
||||
return Minecraft.getInstance().getConnection()!=null ? Minecraft.getInstance().getConnection().getConnection() : null;
|
||||
}
|
||||
|
||||
public static void handleClientWorldClosing(ClientWorld world)
|
||||
{
|
||||
NetworkManager client = getClientToServerNetworkManager();
|
||||
// ONLY revert a non-local connection
|
||||
if (client != null && !client.isMemoryConnection())
|
||||
{
|
||||
GameData.revertToFrozen();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static SetMultimap<String,ResourceLocation> missingTextures = HashMultimap.create();
|
||||
private static Set<String> badTextureDomains = Sets.newHashSet();
|
||||
private static Table<String, String, Set<ResourceLocation>> brokenTextures = HashBasedTable.create();
|
||||
|
||||
public static void trackMissingTexture(ResourceLocation resourceLocation)
|
||||
{
|
||||
badTextureDomains.add(resourceLocation.getNamespace());
|
||||
missingTextures.put(resourceLocation.getNamespace(),resourceLocation);
|
||||
}
|
||||
|
||||
public static void trackBrokenTexture(ResourceLocation resourceLocation, String error)
|
||||
{
|
||||
badTextureDomains.add(resourceLocation.getNamespace());
|
||||
Set<ResourceLocation> badType = brokenTextures.get(resourceLocation.getNamespace(), error);
|
||||
if (badType == null)
|
||||
{
|
||||
badType = Sets.newHashSet();
|
||||
brokenTextures.put(resourceLocation.getNamespace(), MoreObjects.firstNonNull(error, "Unknown error"), badType);
|
||||
}
|
||||
badType.add(resourceLocation);
|
||||
}
|
||||
|
||||
public static void logMissingTextureErrors()
|
||||
{
|
||||
if (missingTextures.isEmpty() && brokenTextures.isEmpty())
|
||||
{
|
||||
return;
|
||||
}
|
||||
Logger logger = LogManager.getLogger("FML.TEXTURE_ERRORS");
|
||||
logger.error(Strings.repeat("+=", 25));
|
||||
logger.error("The following texture errors were found.");
|
||||
Map<String, FallbackResourceManager> resManagers = ObfuscationReflectionHelper.getPrivateValue(SimpleReloadableResourceManager.class, (SimpleReloadableResourceManager)Minecraft.getInstance().getResourceManager(), "field_199014"+"_c");
|
||||
for (String resourceDomain : badTextureDomains)
|
||||
{
|
||||
Set<ResourceLocation> missing = missingTextures.get(resourceDomain);
|
||||
logger.error(Strings.repeat("=", 50));
|
||||
logger.error(" DOMAIN {}", resourceDomain);
|
||||
logger.error(Strings.repeat("-", 50));
|
||||
logger.error(" domain {} is missing {} texture{}",resourceDomain, missing.size(),missing.size()!=1 ? "s" : "");
|
||||
FallbackResourceManager fallbackResourceManager = resManagers.get(resourceDomain);
|
||||
if (fallbackResourceManager == null)
|
||||
{
|
||||
logger.error(" domain {} is missing a resource manager - it is probably a side-effect of automatic texture processing", resourceDomain);
|
||||
}
|
||||
else
|
||||
{
|
||||
List<IResourcePack> resPacks = fallbackResourceManager.fallbacks;
|
||||
logger.error(" domain {} has {} location{}:",resourceDomain, resPacks.size(), resPacks.size() != 1 ? "s" :"");
|
||||
for (IResourcePack resPack : resPacks)
|
||||
{
|
||||
if (resPack instanceof ModFileResourcePack) {
|
||||
ModFileResourcePack modRP = (ModFileResourcePack) resPack;
|
||||
List<IModInfo> mods = modRP.getModFile().getModInfos();
|
||||
logger.error(" mod(s) {} resources at {}", mods.stream().map(IModInfo::getDisplayName).collect(Collectors.toList()), modRP.getModFile().getFilePath());
|
||||
}
|
||||
else if (resPack instanceof ResourcePack)
|
||||
{
|
||||
logger.error(" resource pack at path {}", ((ResourcePack)resPack).file.getPath());
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.error(" unknown resourcepack type {} : {}", resPack.getClass().getName(), resPack.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
logger.error(Strings.repeat("-", 25));
|
||||
if (missingTextures.containsKey(resourceDomain)) {
|
||||
logger.error(" The missing resources for domain {} are:", resourceDomain);
|
||||
for (ResourceLocation rl : missing) {
|
||||
logger.error(" {}", rl.getPath());
|
||||
}
|
||||
logger.error(Strings.repeat("-", 25));
|
||||
}
|
||||
if (!brokenTextures.containsRow(resourceDomain))
|
||||
{
|
||||
logger.error(" No other errors exist for domain {}", resourceDomain);
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.error(" The following other errors were reported for domain {}:",resourceDomain);
|
||||
Map<String, Set<ResourceLocation>> resourceErrs = brokenTextures.row(resourceDomain);
|
||||
for (String error: resourceErrs.keySet())
|
||||
{
|
||||
logger.error(Strings.repeat("-", 25));
|
||||
logger.error(" Problem: {}", error);
|
||||
for (ResourceLocation rl : resourceErrs.get(error))
|
||||
{
|
||||
logger.error(" {}",rl.getPath());
|
||||
}
|
||||
}
|
||||
}
|
||||
logger.error(Strings.repeat("=", 50));
|
||||
}
|
||||
logger.error(Strings.repeat("+=", 25));
|
||||
}
|
||||
|
||||
public static void firePlayerLogin(PlayerController pc, ClientPlayerEntity player, NetworkManager networkManager) {
|
||||
MinecraftForge.EVENT_BUS.post(new ClientPlayerNetworkEvent.LoggedInEvent(pc, player, networkManager));
|
||||
}
|
||||
|
||||
public static void firePlayerLogout(PlayerController pc, ClientPlayerEntity player) {
|
||||
MinecraftForge.EVENT_BUS.post(new ClientPlayerNetworkEvent.LoggedOutEvent(pc, player, player != null ? player.connection != null ? player.connection.getConnection() : null : null));
|
||||
}
|
||||
|
||||
public static void firePlayerRespawn(PlayerController pc, ClientPlayerEntity oldPlayer, ClientPlayerEntity newPlayer, NetworkManager networkManager) {
|
||||
MinecraftForge.EVENT_BUS.post(new ClientPlayerNetworkEvent.RespawnEvent(pc, oldPlayer, newPlayer, networkManager));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,237 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.client;
|
||||
|
||||
import static net.minecraftforge.fml.Logging.CORE;
|
||||
import static net.minecraftforge.fml.loading.LogMarkers.LOADING;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.*;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import net.minecraft.resources.IFutureReloadListener;
|
||||
import net.minecraft.resources.IPackNameDecorator;
|
||||
import net.minecraft.resources.IReloadableResourceManager;
|
||||
import net.minecraft.resources.IResourceManager;
|
||||
import net.minecraft.resources.ResourcePackInfo;
|
||||
import net.minecraft.resources.ResourcePackList;
|
||||
import net.minecraft.util.datafix.codec.DatapackCodec;
|
||||
import net.minecraftforge.fml.*;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import com.mojang.blaze3d.systems.RenderSystem;
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.resources.DownloadingPackFinder;
|
||||
import net.minecraft.profiler.IProfiler;
|
||||
import net.minecraft.resources.data.PackMetadataSection;
|
||||
import net.minecraft.util.text.TranslationTextComponent;
|
||||
import net.minecraftforge.api.distmarker.Dist;
|
||||
import net.minecraftforge.api.distmarker.OnlyIn;
|
||||
import net.minecraftforge.client.model.ModelLoaderRegistry;
|
||||
import net.minecraftforge.common.ForgeConfig;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.fml.client.gui.screen.LoadingErrorScreen;
|
||||
import net.minecraftforge.fml.client.registry.RenderingRegistry;
|
||||
import net.minecraftforge.fml.loading.moddiscovery.ModFile;
|
||||
import net.minecraftforge.fml.packs.DelegatingResourcePack;
|
||||
import net.minecraftforge.fml.packs.ModFileResourcePack;
|
||||
import net.minecraftforge.fml.packs.ResourcePackLoader;
|
||||
import net.minecraftforge.fml.server.LanguageHook;
|
||||
import net.minecraftforge.forgespi.language.IModInfo;
|
||||
|
||||
@OnlyIn(Dist.CLIENT)
|
||||
public class ClientModLoader
|
||||
{
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
private static boolean loading;
|
||||
private static Minecraft mc;
|
||||
private static boolean loadingComplete;
|
||||
private static LoadingFailedException error;
|
||||
private static EarlyLoaderGUI earlyLoaderGUI;
|
||||
|
||||
private static class SpacedRunnable implements Runnable {
|
||||
static final long NANO_SLEEP_TIME = TimeUnit.MILLISECONDS.toNanos(50);
|
||||
private final Runnable wrapped;
|
||||
private long lastRun;
|
||||
|
||||
private SpacedRunnable(final Runnable wrapped) {
|
||||
this.wrapped = wrapped;
|
||||
this.lastRun = System.nanoTime() - NANO_SLEEP_TIME;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
if (System.nanoTime() - this.lastRun > NANO_SLEEP_TIME) {
|
||||
wrapped.run();
|
||||
this.lastRun = System.nanoTime();
|
||||
}
|
||||
}
|
||||
}
|
||||
public static void begin(final Minecraft minecraft, final ResourcePackList defaultResourcePacks, final IReloadableResourceManager mcResourceManager, DownloadingPackFinder metadataSerializer)
|
||||
{
|
||||
// force log4j to shutdown logging in a shutdown hook. This is because we disable default shutdown hook so the server properly logs it's shutdown
|
||||
Runtime.getRuntime().addShutdownHook(new Thread(LogManager::shutdown));
|
||||
loading = true;
|
||||
ClientModLoader.mc = minecraft;
|
||||
LogicalSidedProvider.setClient(()->minecraft);
|
||||
LanguageHook.loadForgeAndMCLangs();
|
||||
earlyLoaderGUI = new EarlyLoaderGUI(minecraft.getWindow());
|
||||
createRunnableWithCatch(()->ModLoader.get().gatherAndInitializeMods(ModWorkManager.syncExecutor(), ModWorkManager.parallelExecutor(), new SpacedRunnable(earlyLoaderGUI::renderTick))).run();
|
||||
if (error == null) {
|
||||
ResourcePackLoader.loadResourcePacks(defaultResourcePacks, ClientModLoader::buildPackFinder);
|
||||
DatapackCodec.DEFAULT.addModPacks(ResourcePackLoader.getPackNames());
|
||||
mcResourceManager.registerReloadListener(ClientModLoader::onResourceReload);
|
||||
mcResourceManager.registerReloadListener(BrandingControl.resourceManagerReloadListener());
|
||||
ModelLoaderRegistry.init();
|
||||
}
|
||||
}
|
||||
|
||||
private static CompletableFuture<Void> onResourceReload(final IFutureReloadListener.IStage stage, final IResourceManager resourceManager, final IProfiler prepareProfiler, final IProfiler executeProfiler, final Executor asyncExecutor, final Executor syncExecutor) {
|
||||
return CompletableFuture.runAsync(createRunnableWithCatch(() -> startModLoading(ModWorkManager.wrappedExecutor(syncExecutor), asyncExecutor)), ModWorkManager.parallelExecutor())
|
||||
.thenCompose(stage::wait)
|
||||
.thenRunAsync(() -> finishModLoading(ModWorkManager.wrappedExecutor(syncExecutor), asyncExecutor), ModWorkManager.parallelExecutor());
|
||||
}
|
||||
|
||||
private static Runnable createRunnableWithCatch(Runnable r) {
|
||||
return ()-> {
|
||||
if (loadingComplete) return;
|
||||
try {
|
||||
r.run();
|
||||
} catch (LoadingFailedException e) {
|
||||
if (error == null) error = e;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static void startModLoading(ModWorkManager.DrivenExecutor syncExecutor, Executor parallelExecutor) {
|
||||
earlyLoaderGUI.handleElsewhere();
|
||||
createRunnableWithCatch(() -> ModLoader.get().loadMods(syncExecutor, parallelExecutor, executor -> CompletableFuture.runAsync(ClientModLoader::preSidedRunnable, executor), executor -> CompletableFuture.runAsync(ClientModLoader::postSidedRunnable, executor), new SpacedRunnable(earlyLoaderGUI::renderTick))).run();
|
||||
}
|
||||
|
||||
private static void postSidedRunnable() {
|
||||
LOGGER.debug(LOADING, "Running post client event work");
|
||||
RenderingRegistry.loadEntityRenderers(mc.getEntityRenderDispatcher());
|
||||
}
|
||||
|
||||
private static void preSidedRunnable() {
|
||||
LOGGER.debug(LOADING, "Running pre client event work");
|
||||
}
|
||||
|
||||
private static void finishModLoading(ModWorkManager.DrivenExecutor syncExecutor, Executor parallelExecutor)
|
||||
{
|
||||
createRunnableWithCatch(() -> ModLoader.get().finishMods(syncExecutor, parallelExecutor, new SpacedRunnable(earlyLoaderGUI::renderTick))).run();
|
||||
loading = false;
|
||||
loadingComplete = true;
|
||||
// reload game settings on main thread
|
||||
syncExecutor.execute(()->mc.options.load());
|
||||
}
|
||||
|
||||
public static VersionChecker.Status checkForUpdates()
|
||||
{
|
||||
boolean anyOutdated = ModList.get().getMods().stream()
|
||||
.map(VersionChecker::getResult)
|
||||
.map(result -> result.status)
|
||||
.anyMatch(status -> status == VersionChecker.Status.OUTDATED || status == VersionChecker.Status.BETA_OUTDATED);
|
||||
return anyOutdated ? VersionChecker.Status.OUTDATED : null;
|
||||
}
|
||||
|
||||
public static boolean completeModLoading()
|
||||
{
|
||||
RenderSystem.disableTexture();
|
||||
RenderSystem.enableTexture();
|
||||
List<ModLoadingWarning> warnings = ModLoader.get().getWarnings();
|
||||
boolean showWarnings = true;
|
||||
try {
|
||||
showWarnings = ForgeConfig.CLIENT.showLoadWarnings.get();
|
||||
} catch (NullPointerException e) {
|
||||
// We're in an early error state, config is not available. Assume true.
|
||||
}
|
||||
if (!showWarnings) {
|
||||
//User disabled warning screen, as least log them
|
||||
if (!warnings.isEmpty()) {
|
||||
LOGGER.warn(LOADING, "Mods loaded with {} warning(s)", warnings.size());
|
||||
warnings.forEach(warning -> LOGGER.warn(LOADING, warning.formatToString()));
|
||||
}
|
||||
warnings = Collections.emptyList(); //Clear warnings, as the user does not want to see them
|
||||
}
|
||||
File dumpedLocation = null;
|
||||
if (error == null) {
|
||||
// We can finally start the forge eventbus up
|
||||
MinecraftForge.EVENT_BUS.start();
|
||||
} else {
|
||||
// Double check we have the langs loaded for forge
|
||||
LanguageHook.loadForgeAndMCLangs();
|
||||
dumpedLocation = CrashReportExtender.dumpModLoadingCrashReport(LOGGER, error, mc.gameDirectory);
|
||||
}
|
||||
if (error != null || !warnings.isEmpty()) {
|
||||
mc.setScreen(new LoadingErrorScreen(error, warnings, dumpedLocation));
|
||||
return true;
|
||||
} else {
|
||||
ClientHooks.logMissingTextureErrors();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static void renderProgressText() {
|
||||
earlyLoaderGUI.renderFromGUI();
|
||||
}
|
||||
public static boolean isLoading()
|
||||
{
|
||||
return loading;
|
||||
}
|
||||
|
||||
private static ResourcePackLoader.IPackInfoFinder buildPackFinder(Map<ModFile, ? extends ModFileResourcePack> modResourcePacks, BiConsumer<? super ModFileResourcePack, ResourcePackInfo> packSetter) {
|
||||
return (packList, factory) -> clientPackFinder(modResourcePacks, packSetter, packList, factory);
|
||||
}
|
||||
|
||||
private static void clientPackFinder(Map<ModFile, ? extends ModFileResourcePack> modResourcePacks, BiConsumer<? super ModFileResourcePack, ResourcePackInfo> packSetter, Consumer<ResourcePackInfo> consumer, ResourcePackInfo.IFactory factory) {
|
||||
List<ModFileResourcePack> hiddenPacks = new ArrayList<>();
|
||||
for (Entry<ModFile, ? extends ModFileResourcePack> e : modResourcePacks.entrySet())
|
||||
{
|
||||
IModInfo mod = e.getKey().getModInfos().get(0);
|
||||
if (Objects.equals(mod.getModId(), "minecraft")) continue; // skip the minecraft "mod"
|
||||
final String name = "mod:" + mod.getModId();
|
||||
final ResourcePackInfo packInfo = ResourcePackInfo.create(name, false, e::getValue, factory, ResourcePackInfo.Priority.BOTTOM, IPackNameDecorator.DEFAULT);
|
||||
if (packInfo == null) {
|
||||
// Vanilla only logs an error, instead of propagating, so handle null and warn that something went wrong
|
||||
ModLoader.get().addWarning(new ModLoadingWarning(mod, ModLoadingStage.ERROR, "fml.modloading.brokenresources", e.getKey()));
|
||||
continue;
|
||||
}
|
||||
packSetter.accept(e.getValue(), packInfo);
|
||||
LOGGER.debug(CORE, "Generating PackInfo named {} for mod file {}", name, e.getKey().getFilePath());
|
||||
if (mod.getOwningFile().showAsResourcePack()) {
|
||||
consumer.accept(packInfo);
|
||||
} else {
|
||||
hiddenPacks.add(e.getValue());
|
||||
}
|
||||
}
|
||||
final ResourcePackInfo packInfo = ResourcePackInfo.create("mod_resources", true, () -> new DelegatingResourcePack("mod_resources", "Mod Resources",
|
||||
new PackMetadataSection(new TranslationTextComponent("fml.resources.modresources", hiddenPacks.size()), 6),
|
||||
hiddenPacks), factory, ResourcePackInfo.Priority.BOTTOM, IPackNameDecorator.DEFAULT);
|
||||
consumer.accept(packInfo);
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.client;
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.screen.Screen;
|
||||
import net.minecraftforge.fml.ModList;
|
||||
import net.minecraftforge.fml.ExtensionPoint;
|
||||
import net.minecraftforge.fml.loading.moddiscovery.ModInfo;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.function.BiFunction;
|
||||
|
||||
public class ConfigGuiHandler
|
||||
{
|
||||
public static Optional<BiFunction<Minecraft, Screen, Screen>> getGuiFactoryFor(ModInfo selectedMod)
|
||||
{
|
||||
return ModList.get().getModContainerById(selectedMod.getModId()).
|
||||
flatMap(mc -> mc.getCustomExtension(ExtensionPoint.CONFIGGUIFACTORY));
|
||||
}
|
||||
}
|
||||
@@ -1,146 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.client;
|
||||
|
||||
import com.mojang.blaze3d.platform.GlStateManager;
|
||||
import com.mojang.blaze3d.systems.RenderSystem;
|
||||
|
||||
import net.minecraft.client.MainWindow;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.util.math.MathHelper;
|
||||
import net.minecraftforge.fml.loading.progress.StartupMessageManager;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
import org.lwjgl.opengl.GL14;
|
||||
import org.lwjgl.stb.STBEasyFont;
|
||||
import org.lwjgl.system.MemoryUtil;
|
||||
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.lang.management.MemoryUsage;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.List;
|
||||
|
||||
public class EarlyLoaderGUI {
|
||||
private final MainWindow window;
|
||||
private boolean handledElsewhere;
|
||||
|
||||
public EarlyLoaderGUI(final MainWindow window) {
|
||||
this.window = window;
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
private void setupMatrix() {
|
||||
RenderSystem.clear(256, Minecraft.ON_OSX);
|
||||
RenderSystem.matrixMode(5889);
|
||||
RenderSystem.loadIdentity();
|
||||
RenderSystem.ortho(0.0D, window.getWidth() / window.getGuiScale(), window.getHeight() / window.getGuiScale(), 0.0D, 1000.0D, 3000.0D);
|
||||
RenderSystem.matrixMode(5888);
|
||||
RenderSystem.loadIdentity();
|
||||
RenderSystem.translatef(0.0F, 0.0F, -2000.0F);
|
||||
}
|
||||
|
||||
public void handleElsewhere() {
|
||||
this.handledElsewhere = true;
|
||||
}
|
||||
|
||||
void renderFromGUI() {
|
||||
renderMessages();
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
void renderTick() {
|
||||
if (handledElsewhere) return;
|
||||
int guiScale = window.calculateScale(0, false);
|
||||
window.setGuiScale(guiScale);
|
||||
|
||||
RenderSystem.clearColor(1.0f, 1.0f, 1.0f, 1.0f);
|
||||
RenderSystem.clear(GL11.GL_COLOR_BUFFER_BIT, Minecraft.ON_OSX);
|
||||
RenderSystem.pushMatrix();
|
||||
setupMatrix();
|
||||
renderBackground();
|
||||
renderMessages();
|
||||
window.updateDisplay();
|
||||
RenderSystem.popMatrix();
|
||||
}
|
||||
|
||||
private void renderBackground() {
|
||||
GL11.glBegin(GL11.GL_QUADS);
|
||||
GL11.glColor4f(239F / 255F, 50F / 255F, 61F / 255F, 255F / 255F); //Color from ResourceLoadProgressGui
|
||||
GL11.glVertex3f(0, 0, -10);
|
||||
GL11.glVertex3f(0, window.getGuiScaledHeight(), -10);
|
||||
GL11.glVertex3f(window.getGuiScaledWidth(), window.getGuiScaledHeight(), -10);
|
||||
GL11.glVertex3f(window.getGuiScaledWidth(), 0, -10);
|
||||
GL11.glEnd();
|
||||
}
|
||||
|
||||
private void renderMessages() {
|
||||
List<Pair<Integer, StartupMessageManager.Message>> messages = StartupMessageManager.getMessages();
|
||||
for (int i = 0; i < messages.size(); i++) {
|
||||
boolean nofade = i == 0;
|
||||
final Pair<Integer, StartupMessageManager.Message> pair = messages.get(i);
|
||||
final float fade = MathHelper.clamp((4000.0f - (float) pair.getLeft() - ( i - 4 ) * 1000.0f) / 5000.0f, 0.0f, 1.0f);
|
||||
if (fade <0.01f && !nofade) continue;
|
||||
StartupMessageManager.Message msg = pair.getRight();
|
||||
renderMessage(msg.getText(), msg.getTypeColour(), ((window.getGuiScaledHeight() - 15) / 10) - i + 1, nofade ? 1.0f : fade);
|
||||
}
|
||||
renderMemoryInfo();
|
||||
}
|
||||
|
||||
private static final float[] memorycolour = new float[] { 0.0f, 0.0f, 0.0f};
|
||||
|
||||
private void renderMemoryInfo() {
|
||||
final MemoryUsage heapusage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
|
||||
final MemoryUsage offheapusage = ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage();
|
||||
final float pctmemory = (float) heapusage.getUsed() / heapusage.getMax();
|
||||
String memory = String.format("Memory Heap: %d / %d MB (%.1f%%) OffHeap: %d MB", heapusage.getUsed() >> 20, heapusage.getMax() >> 20, pctmemory * 100.0, offheapusage.getUsed() >> 20);
|
||||
|
||||
final int i = MathHelper.hsvToRgb((1.0f - (float)Math.pow(pctmemory, 1.5f)) / 3f, 1.0f, 0.5f);
|
||||
memorycolour[2] = ((i) & 0xFF) / 255.0f;
|
||||
memorycolour[1] = ((i >> 8 ) & 0xFF) / 255.0f;
|
||||
memorycolour[0] = ((i >> 16 ) & 0xFF) / 255.0f;
|
||||
renderMessage(memory, memorycolour, 1, 1.0f);
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
void renderMessage(final String message, final float[] colour, int line, float alpha) {
|
||||
GlStateManager._enableClientState(GL11.GL_VERTEX_ARRAY);
|
||||
ByteBuffer charBuffer = MemoryUtil.memAlloc(message.length() * 270);
|
||||
int quads = STBEasyFont.stb_easy_font_print(0, 0, message, null, charBuffer);
|
||||
GL14.glVertexPointer(2, GL11.GL_FLOAT, 16, charBuffer);
|
||||
|
||||
RenderSystem.enableBlend();
|
||||
RenderSystem.disableTexture();
|
||||
// STBEasyFont's quads are in reverse order or what OGGL expects, so it gets culled for facing the wrong way.
|
||||
// So Disable culling https://github.com/MinecraftForge/MinecraftForge/pull/6824
|
||||
RenderSystem.disableCull();
|
||||
GL14.glBlendColor(0,0,0, alpha);
|
||||
RenderSystem.blendFunc(GlStateManager.SourceFactor.CONSTANT_ALPHA, GlStateManager.DestFactor.ONE_MINUS_CONSTANT_ALPHA);
|
||||
RenderSystem.color3f(colour[0],colour[1],colour[2]);
|
||||
RenderSystem.pushMatrix();
|
||||
RenderSystem.translatef(10, line * 10, 0);
|
||||
RenderSystem.scalef(1, 1, 0);
|
||||
RenderSystem.drawArrays(GL11.GL_QUADS, 0, quads * 4);
|
||||
RenderSystem.popMatrix();
|
||||
|
||||
RenderSystem.enableCull();
|
||||
GlStateManager._disableClientState(GL11.GL_VERTEX_ARRAY);
|
||||
MemoryUtil.memFree(charBuffer);
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.client;
|
||||
|
||||
public class ExtendedServerListData {
|
||||
public final String type;
|
||||
public final boolean isCompatible;
|
||||
public int numberOfMods;
|
||||
public String extraReason;
|
||||
public final boolean truncated;
|
||||
|
||||
public ExtendedServerListData(String type, boolean isCompatible, int num, String extraReason)
|
||||
{
|
||||
this(type, isCompatible, num, extraReason, false);
|
||||
}
|
||||
|
||||
public ExtendedServerListData(String type, boolean isCompatible, int num, String extraReason, boolean truncated)
|
||||
{
|
||||
this.type = type;
|
||||
this.isCompatible = isCompatible;
|
||||
this.numberOfMods = num;
|
||||
this.extraReason = extraReason;
|
||||
this.truncated = truncated;
|
||||
}
|
||||
}
|
||||
@@ -1,643 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.client.gui;
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.AbstractGui;
|
||||
import net.minecraft.client.gui.FontRenderer;
|
||||
import net.minecraft.client.renderer.IRenderTypeBuffer;
|
||||
import net.minecraft.client.renderer.Tessellator;
|
||||
import net.minecraft.client.renderer.BufferBuilder;
|
||||
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import net.minecraft.util.math.vector.Matrix4f;
|
||||
import net.minecraft.util.text.ITextProperties;
|
||||
import net.minecraft.util.text.LanguageMap;
|
||||
import net.minecraft.util.text.Style;
|
||||
import net.minecraftforge.client.event.RenderTooltipEvent;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
|
||||
import org.lwjgl.opengl.GL11;
|
||||
|
||||
import com.mojang.blaze3d.matrix.MatrixStack;
|
||||
import com.mojang.blaze3d.systems.RenderSystem;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* This class provides several methods and constants used by the Config GUI classes.
|
||||
*
|
||||
* @author bspkrs
|
||||
*/
|
||||
public class GuiUtils
|
||||
{
|
||||
public static final int DEFAULT_BACKGROUND_COLOR = 0xF0100010;
|
||||
public static final int DEFAULT_BORDER_COLOR_START = 0x505000FF;
|
||||
public static final int DEFAULT_BORDER_COLOR_END = (DEFAULT_BORDER_COLOR_START & 0xFEFEFE) >> 1 | DEFAULT_BORDER_COLOR_START & 0xFF000000;
|
||||
public static final String UNDO_CHAR = "\u21B6";
|
||||
public static final String RESET_CHAR = "\u2604";
|
||||
public static final String VALID = "\u2714";
|
||||
public static final String INVALID = "\u2715";
|
||||
|
||||
public static int[] colorCodes = new int[] { 0, 170, 43520, 43690, 11141120, 11141290, 16755200, 11184810, 5592405, 5592575, 5635925, 5636095, 16733525, 16733695, 16777045, 16777215,
|
||||
0, 42, 10752, 10794, 2752512, 2752554, 2763264, 2763306, 1381653, 1381695, 1392405, 1392447, 4134165, 4134207, 4144917, 4144959 };
|
||||
|
||||
public static int getColorCode(char c, boolean isLighter)
|
||||
{
|
||||
return colorCodes[isLighter ? "0123456789abcdef".indexOf(c) : "0123456789abcdef".indexOf(c) + 16];
|
||||
}
|
||||
/**
|
||||
* Draws a textured box of any size (smallest size is borderSize * 2 square) based on a fixed size textured box with continuous borders
|
||||
* and filler. It is assumed that the desired texture ResourceLocation object has been bound using
|
||||
* Minecraft.getMinecraft().getTextureManager().bindTexture(resourceLocation).
|
||||
*
|
||||
* @param x x axis offset
|
||||
* @param y y axis offset
|
||||
* @param u bound resource location image x offset
|
||||
* @param v bound resource location image y offset
|
||||
* @param width the desired box width
|
||||
* @param height the desired box height
|
||||
* @param textureWidth the width of the box texture in the resource location image
|
||||
* @param textureHeight the height of the box texture in the resource location image
|
||||
* @param borderSize the size of the box's borders
|
||||
* @param zLevel the zLevel to draw at
|
||||
*/
|
||||
@Deprecated //Use matrix stack version TODO remove 1.17
|
||||
public static void drawContinuousTexturedBox(int x, int y, int u, int v, int width, int height, int textureWidth, int textureHeight,
|
||||
int borderSize, float zLevel)
|
||||
{
|
||||
drawContinuousTexturedBox(x, y, u, v, width, height, textureWidth, textureHeight, borderSize, borderSize, borderSize, borderSize, zLevel);
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws a textured box of any size (smallest size is borderSize * 2 square) based on a fixed size textured box with continuous borders
|
||||
* and filler. The provided ResourceLocation object will be bound using
|
||||
* Minecraft.getMinecraft().getTextureManager().bindTexture(resourceLocation).
|
||||
*
|
||||
* @param res the ResourceLocation object that contains the desired image
|
||||
* @param x x axis offset
|
||||
* @param y y axis offset
|
||||
* @param u bound resource location image x offset
|
||||
* @param v bound resource location image y offset
|
||||
* @param width the desired box width
|
||||
* @param height the desired box height
|
||||
* @param textureWidth the width of the box texture in the resource location image
|
||||
* @param textureHeight the height of the box texture in the resource location image
|
||||
* @param borderSize the size of the box's borders
|
||||
* @param zLevel the zLevel to draw at
|
||||
*/
|
||||
@Deprecated //Use matrix stack version TODO remove 1.17
|
||||
public static void drawContinuousTexturedBox(ResourceLocation res, int x, int y, int u, int v, int width, int height, int textureWidth, int textureHeight,
|
||||
int borderSize, float zLevel)
|
||||
{
|
||||
drawContinuousTexturedBox(res, x, y, u, v, width, height, textureWidth, textureHeight, borderSize, borderSize, borderSize, borderSize, zLevel);
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws a textured box of any size (smallest size is borderSize * 2 square) based on a fixed size textured box with continuous borders
|
||||
* and filler. The provided ResourceLocation object will be bound using
|
||||
* Minecraft.getMinecraft().getTextureManager().bindTexture(resourceLocation).
|
||||
*
|
||||
* @param res the ResourceLocation object that contains the desired image
|
||||
* @param x x axis offset
|
||||
* @param y y axis offset
|
||||
* @param u bound resource location image x offset
|
||||
* @param v bound resource location image y offset
|
||||
* @param width the desired box width
|
||||
* @param height the desired box height
|
||||
* @param textureWidth the width of the box texture in the resource location image
|
||||
* @param textureHeight the height of the box texture in the resource location image
|
||||
* @param topBorder the size of the box's top border
|
||||
* @param bottomBorder the size of the box's bottom border
|
||||
* @param leftBorder the size of the box's left border
|
||||
* @param rightBorder the size of the box's right border
|
||||
* @param zLevel the zLevel to draw at
|
||||
*/
|
||||
@Deprecated //Use matrix stack version TODO remove 1.17
|
||||
public static void drawContinuousTexturedBox(ResourceLocation res, int x, int y, int u, int v, int width, int height, int textureWidth, int textureHeight,
|
||||
int topBorder, int bottomBorder, int leftBorder, int rightBorder, float zLevel)
|
||||
{
|
||||
Minecraft.getInstance().getTextureManager().bind(res);
|
||||
drawContinuousTexturedBox(x, y, u, v, width, height, textureWidth, textureHeight, topBorder, bottomBorder, leftBorder, rightBorder, zLevel);
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws a textured box of any size (smallest size is borderSize * 2 square) based on a fixed size textured box with continuous borders
|
||||
* and filler. It is assumed that the desired texture ResourceLocation object has been bound using
|
||||
* Minecraft.getMinecraft().getTextureManager().bindTexture(resourceLocation).
|
||||
*
|
||||
* @param x x axis offset
|
||||
* @param y y axis offset
|
||||
* @param u bound resource location image x offset
|
||||
* @param v bound resource location image y offset
|
||||
* @param width the desired box width
|
||||
* @param height the desired box height
|
||||
* @param textureWidth the width of the box texture in the resource location image
|
||||
* @param textureHeight the height of the box texture in the resource location image
|
||||
* @param topBorder the size of the box's top border
|
||||
* @param bottomBorder the size of the box's bottom border
|
||||
* @param leftBorder the size of the box's left border
|
||||
* @param rightBorder the size of the box's right border
|
||||
* @param zLevel the zLevel to draw at
|
||||
*/
|
||||
@Deprecated //Use matrix stack version TODO remove 1.17
|
||||
public static void drawContinuousTexturedBox(int x, int y, int u, int v, int width, int height, int textureWidth, int textureHeight,
|
||||
int topBorder, int bottomBorder, int leftBorder, int rightBorder, float zLevel)
|
||||
{
|
||||
RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F);
|
||||
RenderSystem.enableBlend();
|
||||
RenderSystem.blendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, 1, 0);
|
||||
|
||||
int fillerWidth = textureWidth - leftBorder - rightBorder;
|
||||
int fillerHeight = textureHeight - topBorder - bottomBorder;
|
||||
int canvasWidth = width - leftBorder - rightBorder;
|
||||
int canvasHeight = height - topBorder - bottomBorder;
|
||||
int xPasses = canvasWidth / fillerWidth;
|
||||
int remainderWidth = canvasWidth % fillerWidth;
|
||||
int yPasses = canvasHeight / fillerHeight;
|
||||
int remainderHeight = canvasHeight % fillerHeight;
|
||||
|
||||
// Draw Border
|
||||
// Top Left
|
||||
drawTexturedModalRect(x, y, u, v, leftBorder, topBorder, zLevel);
|
||||
// Top Right
|
||||
drawTexturedModalRect(x + leftBorder + canvasWidth, y, u + leftBorder + fillerWidth, v, rightBorder, topBorder, zLevel);
|
||||
// Bottom Left
|
||||
drawTexturedModalRect(x, y + topBorder + canvasHeight, u, v + topBorder + fillerHeight, leftBorder, bottomBorder, zLevel);
|
||||
// Bottom Right
|
||||
drawTexturedModalRect(x + leftBorder + canvasWidth, y + topBorder + canvasHeight, u + leftBorder + fillerWidth, v + topBorder + fillerHeight, rightBorder, bottomBorder, zLevel);
|
||||
|
||||
for (int i = 0; i < xPasses + (remainderWidth > 0 ? 1 : 0); i++)
|
||||
{
|
||||
// Top Border
|
||||
drawTexturedModalRect(x + leftBorder + (i * fillerWidth), y, u + leftBorder, v, (i == xPasses ? remainderWidth : fillerWidth), topBorder, zLevel);
|
||||
// Bottom Border
|
||||
drawTexturedModalRect(x + leftBorder + (i * fillerWidth), y + topBorder + canvasHeight, u + leftBorder, v + topBorder + fillerHeight, (i == xPasses ? remainderWidth : fillerWidth), bottomBorder, zLevel);
|
||||
|
||||
// Throw in some filler for good measure
|
||||
for (int j = 0; j < yPasses + (remainderHeight > 0 ? 1 : 0); j++)
|
||||
drawTexturedModalRect(x + leftBorder + (i * fillerWidth), y + topBorder + (j * fillerHeight), u + leftBorder, v + topBorder, (i == xPasses ? remainderWidth : fillerWidth), (j == yPasses ? remainderHeight : fillerHeight), zLevel);
|
||||
}
|
||||
|
||||
// Side Borders
|
||||
for (int j = 0; j < yPasses + (remainderHeight > 0 ? 1 : 0); j++)
|
||||
{
|
||||
// Left Border
|
||||
drawTexturedModalRect(x, y + topBorder + (j * fillerHeight), u, v + topBorder, leftBorder, (j == yPasses ? remainderHeight : fillerHeight), zLevel);
|
||||
// Right Border
|
||||
drawTexturedModalRect(x + leftBorder + canvasWidth, y + topBorder + (j * fillerHeight), u + leftBorder + fillerWidth, v + topBorder, rightBorder, (j == yPasses ? remainderHeight : fillerHeight), zLevel);
|
||||
}
|
||||
}
|
||||
|
||||
@Deprecated //Use matrix stack version TODO remove 1.17
|
||||
public static void drawTexturedModalRect(int x, int y, int u, int v, int width, int height, float zLevel)
|
||||
{
|
||||
final float uScale = 1f / 0x100;
|
||||
final float vScale = 1f / 0x100;
|
||||
|
||||
Tessellator tessellator = Tessellator.getInstance();
|
||||
BufferBuilder wr = tessellator.getBuilder();
|
||||
wr.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX);
|
||||
wr.vertex(x , y + height, zLevel).uv( u * uScale, ((v + height) * vScale)).endVertex();
|
||||
wr.vertex(x + width, y + height, zLevel).uv((u + width) * uScale, ((v + height) * vScale)).endVertex();
|
||||
wr.vertex(x + width, y , zLevel).uv((u + width) * uScale, ( v * vScale)).endVertex();
|
||||
wr.vertex(x , y , zLevel).uv( u * uScale, ( v * vScale)).endVertex();
|
||||
tessellator.end();
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws a textured box of any size (smallest size is borderSize * 2 square) based on a fixed size textured box with continuous borders
|
||||
* and filler. It is assumed that the desired texture ResourceLocation object has been bound using
|
||||
* Minecraft.getMinecraft().getTextureManager().bindTexture(resourceLocation).
|
||||
*
|
||||
* @param matrixStack the gui matrix stack
|
||||
* @param x x axis offset
|
||||
* @param y y axis offset
|
||||
* @param u bound resource location image x offset
|
||||
* @param v bound resource location image y offset
|
||||
* @param width the desired box width
|
||||
* @param height the desired box height
|
||||
* @param textureWidth the width of the box texture in the resource location image
|
||||
* @param textureHeight the height of the box texture in the resource location image
|
||||
* @param borderSize the size of the box's borders
|
||||
* @param zLevel the zLevel to draw at
|
||||
*/
|
||||
public static void drawContinuousTexturedBox(MatrixStack matrixStack, int x, int y, int u, int v, int width, int height, int textureWidth, int textureHeight,
|
||||
int borderSize, float zLevel)
|
||||
{
|
||||
drawContinuousTexturedBox(matrixStack, x, y, u, v, width, height, textureWidth, textureHeight, borderSize, borderSize, borderSize, borderSize, zLevel);
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws a textured box of any size (smallest size is borderSize * 2 square) based on a fixed size textured box with continuous borders
|
||||
* and filler. The provided ResourceLocation object will be bound using
|
||||
* Minecraft.getMinecraft().getTextureManager().bindTexture(resourceLocation).
|
||||
*
|
||||
* @param matrixStack the gui matrix stack
|
||||
* @param res the ResourceLocation object that contains the desired image
|
||||
* @param x x axis offset
|
||||
* @param y y axis offset
|
||||
* @param u bound resource location image x offset
|
||||
* @param v bound resource location image y offset
|
||||
* @param width the desired box width
|
||||
* @param height the desired box height
|
||||
* @param textureWidth the width of the box texture in the resource location image
|
||||
* @param textureHeight the height of the box texture in the resource location image
|
||||
* @param borderSize the size of the box's borders
|
||||
* @param zLevel the zLevel to draw at
|
||||
*/
|
||||
public static void drawContinuousTexturedBox(MatrixStack matrixStack, ResourceLocation res, int x, int y, int u, int v, int width, int height, int textureWidth, int textureHeight,
|
||||
int borderSize, float zLevel)
|
||||
{
|
||||
drawContinuousTexturedBox(matrixStack, res, x, y, u, v, width, height, textureWidth, textureHeight, borderSize, borderSize, borderSize, borderSize, zLevel);
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws a textured box of any size (smallest size is borderSize * 2 square) based on a fixed size textured box with continuous borders
|
||||
* and filler. The provided ResourceLocation object will be bound using
|
||||
* Minecraft.getMinecraft().getTextureManager().bindTexture(resourceLocation).
|
||||
*
|
||||
* @param matrixStack the gui matrix stack
|
||||
* @param res the ResourceLocation object that contains the desired image
|
||||
* @param x x axis offset
|
||||
* @param y y axis offset
|
||||
* @param u bound resource location image x offset
|
||||
* @param v bound resource location image y offset
|
||||
* @param width the desired box width
|
||||
* @param height the desired box height
|
||||
* @param textureWidth the width of the box texture in the resource location image
|
||||
* @param textureHeight the height of the box texture in the resource location image
|
||||
* @param topBorder the size of the box's top border
|
||||
* @param bottomBorder the size of the box's bottom border
|
||||
* @param leftBorder the size of the box's left border
|
||||
* @param rightBorder the size of the box's right border
|
||||
* @param zLevel the zLevel to draw at
|
||||
*/
|
||||
public static void drawContinuousTexturedBox(MatrixStack matrixStack, ResourceLocation res, int x, int y, int u, int v, int width, int height, int textureWidth, int textureHeight,
|
||||
int topBorder, int bottomBorder, int leftBorder, int rightBorder, float zLevel)
|
||||
{
|
||||
Minecraft.getInstance().getTextureManager().bind(res);
|
||||
drawContinuousTexturedBox(matrixStack, x, y, u, v, width, height, textureWidth, textureHeight, topBorder, bottomBorder, leftBorder, rightBorder, zLevel);
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws a textured box of any size (smallest size is borderSize * 2 square) based on a fixed size textured box with continuous borders
|
||||
* and filler. It is assumed that the desired texture ResourceLocation object has been bound using
|
||||
* Minecraft.getMinecraft().getTextureManager().bindTexture(resourceLocation).
|
||||
*
|
||||
* @param matrixStack the gui matrix stack
|
||||
* @param x x axis offset
|
||||
* @param y y axis offset
|
||||
* @param u bound resource location image x offset
|
||||
* @param v bound resource location image y offset
|
||||
* @param width the desired box width
|
||||
* @param height the desired box height
|
||||
* @param textureWidth the width of the box texture in the resource location image
|
||||
* @param textureHeight the height of the box texture in the resource location image
|
||||
* @param topBorder the size of the box's top border
|
||||
* @param bottomBorder the size of the box's bottom border
|
||||
* @param leftBorder the size of the box's left border
|
||||
* @param rightBorder the size of the box's right border
|
||||
* @param zLevel the zLevel to draw at
|
||||
*/
|
||||
@SuppressWarnings("deprecation")
|
||||
public static void drawContinuousTexturedBox(MatrixStack matrixStack, int x, int y, int u, int v, int width, int height, int textureWidth, int textureHeight,
|
||||
int topBorder, int bottomBorder, int leftBorder, int rightBorder, float zLevel)
|
||||
{
|
||||
RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F);
|
||||
RenderSystem.enableBlend();
|
||||
RenderSystem.blendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, 1, 0);
|
||||
|
||||
int fillerWidth = textureWidth - leftBorder - rightBorder;
|
||||
int fillerHeight = textureHeight - topBorder - bottomBorder;
|
||||
int canvasWidth = width - leftBorder - rightBorder;
|
||||
int canvasHeight = height - topBorder - bottomBorder;
|
||||
int xPasses = canvasWidth / fillerWidth;
|
||||
int remainderWidth = canvasWidth % fillerWidth;
|
||||
int yPasses = canvasHeight / fillerHeight;
|
||||
int remainderHeight = canvasHeight % fillerHeight;
|
||||
|
||||
// Draw Border
|
||||
// Top Left
|
||||
drawTexturedModalRect(matrixStack, x, y, u, v, leftBorder, topBorder, zLevel);
|
||||
// Top Right
|
||||
drawTexturedModalRect(matrixStack, x + leftBorder + canvasWidth, y, u + leftBorder + fillerWidth, v, rightBorder, topBorder, zLevel);
|
||||
// Bottom Left
|
||||
drawTexturedModalRect(matrixStack, x, y + topBorder + canvasHeight, u, v + topBorder + fillerHeight, leftBorder, bottomBorder, zLevel);
|
||||
// Bottom Right
|
||||
drawTexturedModalRect(matrixStack, x + leftBorder + canvasWidth, y + topBorder + canvasHeight, u + leftBorder + fillerWidth, v + topBorder + fillerHeight, rightBorder, bottomBorder, zLevel);
|
||||
|
||||
for (int i = 0; i < xPasses + (remainderWidth > 0 ? 1 : 0); i++)
|
||||
{
|
||||
// Top Border
|
||||
drawTexturedModalRect(matrixStack, x + leftBorder + (i * fillerWidth), y, u + leftBorder, v, (i == xPasses ? remainderWidth : fillerWidth), topBorder, zLevel);
|
||||
// Bottom Border
|
||||
drawTexturedModalRect(matrixStack, x + leftBorder + (i * fillerWidth), y + topBorder + canvasHeight, u + leftBorder, v + topBorder + fillerHeight, (i == xPasses ? remainderWidth : fillerWidth), bottomBorder, zLevel);
|
||||
|
||||
// Throw in some filler for good measure
|
||||
for (int j = 0; j < yPasses + (remainderHeight > 0 ? 1 : 0); j++)
|
||||
drawTexturedModalRect(matrixStack, x + leftBorder + (i * fillerWidth), y + topBorder + (j * fillerHeight), u + leftBorder, v + topBorder, (i == xPasses ? remainderWidth : fillerWidth), (j == yPasses ? remainderHeight : fillerHeight), zLevel);
|
||||
}
|
||||
|
||||
// Side Borders
|
||||
for (int j = 0; j < yPasses + (remainderHeight > 0 ? 1 : 0); j++)
|
||||
{
|
||||
// Left Border
|
||||
drawTexturedModalRect(matrixStack, x, y + topBorder + (j * fillerHeight), u, v + topBorder, leftBorder, (j == yPasses ? remainderHeight : fillerHeight), zLevel);
|
||||
// Right Border
|
||||
drawTexturedModalRect(matrixStack, x + leftBorder + canvasWidth, y + topBorder + (j * fillerHeight), u + leftBorder + fillerWidth, v + topBorder, rightBorder, (j == yPasses ? remainderHeight : fillerHeight), zLevel);
|
||||
}
|
||||
}
|
||||
|
||||
public static void drawTexturedModalRect(MatrixStack matrixStack, int x, int y, int u, int v, int width, int height, float zLevel)
|
||||
{
|
||||
final float uScale = 1f / 0x100;
|
||||
final float vScale = 1f / 0x100;
|
||||
|
||||
Tessellator tessellator = Tessellator.getInstance();
|
||||
BufferBuilder wr = tessellator.getBuilder();
|
||||
wr.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX);
|
||||
Matrix4f matrix = matrixStack.last().pose();
|
||||
wr.vertex(matrix, x , y + height, zLevel).uv( u * uScale, ((v + height) * vScale)).endVertex();
|
||||
wr.vertex(matrix, x + width, y + height, zLevel).uv((u + width) * uScale, ((v + height) * vScale)).endVertex();
|
||||
wr.vertex(matrix, x + width, y , zLevel).uv((u + width) * uScale, ( v * vScale)).endVertex();
|
||||
wr.vertex(matrix, x , y , zLevel).uv( u * uScale, ( v * vScale)).endVertex();
|
||||
tessellator.end();
|
||||
}
|
||||
|
||||
@Nonnull
|
||||
private static ItemStack cachedTooltipStack = ItemStack.EMPTY;
|
||||
|
||||
/**
|
||||
* Must be called from {@code GuiScreen.renderToolTip} before {@code GuiScreen.drawHoveringText} is called.
|
||||
*
|
||||
* @param stack The stack for which a tooltip is about to be drawn.
|
||||
*/
|
||||
public static void preItemToolTip(@Nonnull ItemStack stack)
|
||||
{
|
||||
cachedTooltipStack = stack;
|
||||
}
|
||||
|
||||
/**
|
||||
* Must be called from {@code GuiScreen.renderToolTip} after {@code GuiScreen.drawHoveringText} is called.
|
||||
*/
|
||||
public static void postItemToolTip()
|
||||
{
|
||||
cachedTooltipStack = ItemStack.EMPTY;
|
||||
}
|
||||
|
||||
public static void drawHoveringText(MatrixStack mStack, List<? extends ITextProperties> textLines, int mouseX, int mouseY, int screenWidth, int screenHeight, int maxTextWidth, FontRenderer font)
|
||||
{
|
||||
drawHoveringText(mStack, textLines, mouseX, mouseY, screenWidth, screenHeight, maxTextWidth, DEFAULT_BACKGROUND_COLOR, DEFAULT_BORDER_COLOR_START, DEFAULT_BORDER_COLOR_END, font);
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws a tooltip box on the screen with text in it.
|
||||
* Automatically positions the box relative to the mouse to match Mojang's implementation.
|
||||
* Automatically wraps text when there is not enough space on the screen to display the text without wrapping.
|
||||
* Can have a maximum width set to avoid creating very wide tooltips.
|
||||
*
|
||||
* @param textLines the lines of text to be drawn in a hovering tooltip box.
|
||||
* @param mouseX the mouse X position
|
||||
* @param mouseY the mouse Y position
|
||||
* @param screenWidth the available screen width for the tooltip to drawn in
|
||||
* @param screenHeight the available screen height for the tooltip to drawn in
|
||||
* @param maxTextWidth the maximum width of the text in the tooltip box.
|
||||
* Set to a negative number to have no max width.
|
||||
* @param backgroundColor The background color of the box
|
||||
* @param borderColorStart The starting color of the box border
|
||||
* @param borderColorEnd The ending color of the box border. The border color will be smoothly interpolated
|
||||
* between the start and end values.
|
||||
* @param font the font for drawing the text in the tooltip box
|
||||
*/
|
||||
public static void drawHoveringText(MatrixStack mStack, List<? extends ITextProperties> textLines, int mouseX, int mouseY, int screenWidth, int screenHeight,
|
||||
int maxTextWidth, int backgroundColor, int borderColorStart, int borderColorEnd, FontRenderer font)
|
||||
{
|
||||
drawHoveringText(cachedTooltipStack, mStack, textLines, mouseX, mouseY, screenWidth, screenHeight, maxTextWidth, backgroundColor, borderColorStart, borderColorEnd, font);
|
||||
}
|
||||
|
||||
public static void drawHoveringText(@Nonnull final ItemStack stack, MatrixStack mStack, List<? extends ITextProperties> textLines, int mouseX, int mouseY, int screenWidth, int screenHeight, int maxTextWidth, FontRenderer font)
|
||||
{
|
||||
drawHoveringText(stack, mStack, textLines, mouseX, mouseY, screenWidth, screenHeight, maxTextWidth, DEFAULT_BACKGROUND_COLOR, DEFAULT_BORDER_COLOR_START, DEFAULT_BORDER_COLOR_END, font);
|
||||
}
|
||||
|
||||
/**
|
||||
* Use this version if calling from somewhere where ItemStack context is available.
|
||||
*
|
||||
* @see #drawHoveringText(MatrixStack, List, int, int, int, int, int, int, int, int, FontRenderer)
|
||||
*/
|
||||
//TODO, Validate rendering is the same as the original
|
||||
public static void drawHoveringText(@Nonnull final ItemStack stack, MatrixStack mStack, List<? extends ITextProperties> textLines, int mouseX, int mouseY,
|
||||
int screenWidth, int screenHeight, int maxTextWidth,
|
||||
int backgroundColor, int borderColorStart, int borderColorEnd, FontRenderer font)
|
||||
{
|
||||
if (!textLines.isEmpty())
|
||||
{
|
||||
RenderTooltipEvent.Pre event = new RenderTooltipEvent.Pre(stack, textLines, mStack, mouseX, mouseY, screenWidth, screenHeight, maxTextWidth, font);
|
||||
if (MinecraftForge.EVENT_BUS.post(event))
|
||||
return;
|
||||
mouseX = event.getX();
|
||||
mouseY = event.getY();
|
||||
screenWidth = event.getScreenWidth();
|
||||
screenHeight = event.getScreenHeight();
|
||||
maxTextWidth = event.getMaxWidth();
|
||||
font = event.getFontRenderer();
|
||||
|
||||
RenderSystem.disableRescaleNormal();
|
||||
RenderSystem.disableDepthTest();
|
||||
int tooltipTextWidth = 0;
|
||||
|
||||
for (ITextProperties textLine : textLines)
|
||||
{
|
||||
int textLineWidth = font.width(textLine);
|
||||
if (textLineWidth > tooltipTextWidth)
|
||||
tooltipTextWidth = textLineWidth;
|
||||
}
|
||||
|
||||
boolean needsWrap = false;
|
||||
|
||||
int titleLinesCount = 1;
|
||||
int tooltipX = mouseX + 12;
|
||||
if (tooltipX + tooltipTextWidth + 4 > screenWidth)
|
||||
{
|
||||
tooltipX = mouseX - 16 - tooltipTextWidth;
|
||||
if (tooltipX < 4) // if the tooltip doesn't fit on the screen
|
||||
{
|
||||
if (mouseX > screenWidth / 2)
|
||||
tooltipTextWidth = mouseX - 12 - 8;
|
||||
else
|
||||
tooltipTextWidth = screenWidth - 16 - mouseX;
|
||||
needsWrap = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (maxTextWidth > 0 && tooltipTextWidth > maxTextWidth)
|
||||
{
|
||||
tooltipTextWidth = maxTextWidth;
|
||||
needsWrap = true;
|
||||
}
|
||||
|
||||
if (needsWrap)
|
||||
{
|
||||
int wrappedTooltipWidth = 0;
|
||||
List<ITextProperties> wrappedTextLines = new ArrayList<>();
|
||||
for (int i = 0; i < textLines.size(); i++)
|
||||
{
|
||||
ITextProperties textLine = textLines.get(i);
|
||||
List<ITextProperties> wrappedLine = font.getSplitter().splitLines(textLine, tooltipTextWidth, Style.EMPTY);
|
||||
if (i == 0)
|
||||
titleLinesCount = wrappedLine.size();
|
||||
|
||||
for (ITextProperties line : wrappedLine)
|
||||
{
|
||||
int lineWidth = font.width(line);
|
||||
if (lineWidth > wrappedTooltipWidth)
|
||||
wrappedTooltipWidth = lineWidth;
|
||||
wrappedTextLines.add(line);
|
||||
}
|
||||
}
|
||||
tooltipTextWidth = wrappedTooltipWidth;
|
||||
textLines = wrappedTextLines;
|
||||
|
||||
if (mouseX > screenWidth / 2)
|
||||
tooltipX = mouseX - 16 - tooltipTextWidth;
|
||||
else
|
||||
tooltipX = mouseX + 12;
|
||||
}
|
||||
|
||||
int tooltipY = mouseY - 12;
|
||||
int tooltipHeight = 8;
|
||||
|
||||
if (textLines.size() > 1)
|
||||
{
|
||||
tooltipHeight += (textLines.size() - 1) * 10;
|
||||
if (textLines.size() > titleLinesCount)
|
||||
tooltipHeight += 2; // gap between title lines and next lines
|
||||
}
|
||||
|
||||
if (tooltipY < 4)
|
||||
tooltipY = 4;
|
||||
else if (tooltipY + tooltipHeight + 4 > screenHeight)
|
||||
tooltipY = screenHeight - tooltipHeight - 4;
|
||||
|
||||
final int zLevel = 400;
|
||||
RenderTooltipEvent.Color colorEvent = new RenderTooltipEvent.Color(stack, textLines, mStack, tooltipX, tooltipY, font, backgroundColor, borderColorStart, borderColorEnd);
|
||||
MinecraftForge.EVENT_BUS.post(colorEvent);
|
||||
backgroundColor = colorEvent.getBackground();
|
||||
borderColorStart = colorEvent.getBorderStart();
|
||||
borderColorEnd = colorEvent.getBorderEnd();
|
||||
|
||||
mStack.pushPose();
|
||||
Matrix4f mat = mStack.last().pose();
|
||||
//TODO, lots of unnessesary GL calls here, we can buffer all these together.
|
||||
drawGradientRect(mat, zLevel, tooltipX - 3, tooltipY - 4, tooltipX + tooltipTextWidth + 3, tooltipY - 3, backgroundColor, backgroundColor);
|
||||
drawGradientRect(mat, zLevel, tooltipX - 3, tooltipY + tooltipHeight + 3, tooltipX + tooltipTextWidth + 3, tooltipY + tooltipHeight + 4, backgroundColor, backgroundColor);
|
||||
drawGradientRect(mat, zLevel, tooltipX - 3, tooltipY - 3, tooltipX + tooltipTextWidth + 3, tooltipY + tooltipHeight + 3, backgroundColor, backgroundColor);
|
||||
drawGradientRect(mat, zLevel, tooltipX - 4, tooltipY - 3, tooltipX - 3, tooltipY + tooltipHeight + 3, backgroundColor, backgroundColor);
|
||||
drawGradientRect(mat, zLevel, tooltipX + tooltipTextWidth + 3, tooltipY - 3, tooltipX + tooltipTextWidth + 4, tooltipY + tooltipHeight + 3, backgroundColor, backgroundColor);
|
||||
drawGradientRect(mat, zLevel, tooltipX - 3, tooltipY - 3 + 1, tooltipX - 3 + 1, tooltipY + tooltipHeight + 3 - 1, borderColorStart, borderColorEnd);
|
||||
drawGradientRect(mat, zLevel, tooltipX + tooltipTextWidth + 2, tooltipY - 3 + 1, tooltipX + tooltipTextWidth + 3, tooltipY + tooltipHeight + 3 - 1, borderColorStart, borderColorEnd);
|
||||
drawGradientRect(mat, zLevel, tooltipX - 3, tooltipY - 3, tooltipX + tooltipTextWidth + 3, tooltipY - 3 + 1, borderColorStart, borderColorStart);
|
||||
drawGradientRect(mat, zLevel, tooltipX - 3, tooltipY + tooltipHeight + 2, tooltipX + tooltipTextWidth + 3, tooltipY + tooltipHeight + 3, borderColorEnd, borderColorEnd);
|
||||
|
||||
MinecraftForge.EVENT_BUS.post(new RenderTooltipEvent.PostBackground(stack, textLines, mStack, tooltipX, tooltipY, font, tooltipTextWidth, tooltipHeight));
|
||||
|
||||
IRenderTypeBuffer.Impl renderType = IRenderTypeBuffer.immediate(Tessellator.getInstance().getBuilder());
|
||||
mStack.translate(0.0D, 0.0D, zLevel);
|
||||
|
||||
int tooltipTop = tooltipY;
|
||||
|
||||
for (int lineNumber = 0; lineNumber < textLines.size(); ++lineNumber)
|
||||
{
|
||||
ITextProperties line = textLines.get(lineNumber);
|
||||
if (line != null)
|
||||
font.drawInBatch(LanguageMap.getInstance().getVisualOrder(line), (float)tooltipX, (float)tooltipY, -1, true, mat, renderType, false, 0, 15728880);
|
||||
|
||||
if (lineNumber + 1 == titleLinesCount)
|
||||
tooltipY += 2;
|
||||
|
||||
tooltipY += 10;
|
||||
}
|
||||
|
||||
renderType.endBatch();
|
||||
mStack.popPose();
|
||||
|
||||
MinecraftForge.EVENT_BUS.post(new RenderTooltipEvent.PostText(stack, textLines, mStack, tooltipX, tooltipTop, font, tooltipTextWidth, tooltipHeight));
|
||||
|
||||
RenderSystem.enableDepthTest();
|
||||
RenderSystem.enableRescaleNormal();
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public static void drawGradientRect(Matrix4f mat, int zLevel, int left, int top, int right, int bottom, int startColor, int endColor)
|
||||
{
|
||||
float startAlpha = (float)(startColor >> 24 & 255) / 255.0F;
|
||||
float startRed = (float)(startColor >> 16 & 255) / 255.0F;
|
||||
float startGreen = (float)(startColor >> 8 & 255) / 255.0F;
|
||||
float startBlue = (float)(startColor & 255) / 255.0F;
|
||||
float endAlpha = (float)(endColor >> 24 & 255) / 255.0F;
|
||||
float endRed = (float)(endColor >> 16 & 255) / 255.0F;
|
||||
float endGreen = (float)(endColor >> 8 & 255) / 255.0F;
|
||||
float endBlue = (float)(endColor & 255) / 255.0F;
|
||||
|
||||
RenderSystem.enableDepthTest();
|
||||
RenderSystem.disableTexture();
|
||||
RenderSystem.enableBlend();
|
||||
RenderSystem.defaultBlendFunc();
|
||||
RenderSystem.shadeModel(GL11.GL_SMOOTH);
|
||||
|
||||
Tessellator tessellator = Tessellator.getInstance();
|
||||
BufferBuilder buffer = tessellator.getBuilder();
|
||||
buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_COLOR);
|
||||
buffer.vertex(mat, right, top, zLevel).color(startRed, startGreen, startBlue, startAlpha).endVertex();
|
||||
buffer.vertex(mat, left, top, zLevel).color(startRed, startGreen, startBlue, startAlpha).endVertex();
|
||||
buffer.vertex(mat, left, bottom, zLevel).color( endRed, endGreen, endBlue, endAlpha).endVertex();
|
||||
buffer.vertex(mat, right, bottom, zLevel).color( endRed, endGreen, endBlue, endAlpha).endVertex();
|
||||
tessellator.end();
|
||||
|
||||
RenderSystem.shadeModel(GL11.GL_FLAT);
|
||||
RenderSystem.disableBlend();
|
||||
RenderSystem.enableTexture();
|
||||
}
|
||||
|
||||
public static void drawInscribedRect(MatrixStack mStack, int x, int y, int boundsWidth, int boundsHeight, int rectWidth, int rectHeight)
|
||||
{
|
||||
drawInscribedRect(mStack, x, y, boundsWidth, boundsHeight, rectWidth, rectHeight, true, true);
|
||||
}
|
||||
|
||||
public static void drawInscribedRect(MatrixStack mStack, int x, int y, int boundsWidth, int boundsHeight, int rectWidth, int rectHeight, boolean centerX, boolean centerY)
|
||||
{
|
||||
if (rectWidth * boundsHeight > rectHeight * boundsWidth) {
|
||||
int h = boundsHeight;
|
||||
boundsHeight = (int) (boundsWidth * ((double) rectHeight / rectWidth));
|
||||
if (centerY) y += (h - boundsHeight) / 2;
|
||||
} else {
|
||||
int w = boundsWidth;
|
||||
boundsWidth = (int) (boundsHeight * ((double) rectWidth / rectHeight));
|
||||
if (centerX) x += (w - boundsWidth) / 2;
|
||||
}
|
||||
|
||||
AbstractGui.blit(mStack, x, y, boundsWidth, boundsHeight, 0.0f,0.0f, rectWidth, rectHeight, rectWidth, rectHeight);
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
/*
|
||||
package net.minecraftforge.fml.client.gui.screen;
|
||||
import net.minecraft.client.gui.widget.button.Button;
|
||||
import net.minecraft.util.text.StringTextComponent;
|
||||
import net.minecraft.util.text.TranslationTextComponent;
|
||||
import net.minecraftforge.fml.ForgeI18n;
|
||||
import net.minecraftforge.fml.StartupQuery;
|
||||
|
||||
public class ConfirmationScreen extends NotificationScreen
|
||||
{
|
||||
public ConfirmationScreen(StartupQuery query)
|
||||
{
|
||||
super(query);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void addConfirmationButtons()
|
||||
{
|
||||
this.addButton(new Button(this.width / 2 - 104, this.height - PADDING - 20, 100, 20, new StringTextComponent(ForgeI18n.parseMessage("gui.yes")), b ->
|
||||
{
|
||||
ConfirmationScreen.this.minecraft.currentScreen = null;
|
||||
query.setResult(true);
|
||||
query.finish();
|
||||
}
|
||||
));
|
||||
this.addButton(new Button(this.width / 2 + 4, this.height - PADDING - 20, 100, 20, new StringTextComponent(ForgeI18n.parseMessage("gui.no")), b ->
|
||||
{
|
||||
ConfirmationScreen.this.minecraft.currentScreen = null;
|
||||
query.setResult(false);
|
||||
query.finish();
|
||||
}
|
||||
));
|
||||
}
|
||||
}
|
||||
*/
|
||||
@@ -1,170 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.client.gui.screen;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import com.mojang.blaze3d.matrix.MatrixStack;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.FontRenderer;
|
||||
import net.minecraft.client.gui.screen.ErrorScreen;
|
||||
import net.minecraft.client.gui.widget.list.ExtendedList;
|
||||
import net.minecraft.util.IReorderingProcessor;
|
||||
import net.minecraft.util.Util;
|
||||
import net.minecraft.util.text.ITextComponent;
|
||||
import net.minecraft.util.text.ITextProperties;
|
||||
import net.minecraft.util.text.StringTextComponent;
|
||||
import net.minecraft.util.text.TextFormatting;
|
||||
import net.minecraftforge.fml.ForgeI18n;
|
||||
import net.minecraftforge.fml.LoadingFailedException;
|
||||
import net.minecraftforge.fml.ModLoadingException;
|
||||
import net.minecraftforge.fml.ModLoadingWarning;
|
||||
import net.minecraftforge.fml.client.ClientHooks;
|
||||
import net.minecraftforge.fml.client.gui.widget.ExtendedButton;
|
||||
import net.minecraftforge.fml.loading.FMLPaths;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import java.io.File;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
public class LoadingErrorScreen extends ErrorScreen {
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
private final Path modsDir;
|
||||
private final Path logFile;
|
||||
private final List<ModLoadingException> modLoadErrors;
|
||||
private final List<ModLoadingWarning> modLoadWarnings;
|
||||
private final Path dumpedLocation;
|
||||
private LoadingEntryList entryList;
|
||||
private ITextComponent errorHeader;
|
||||
private ITextComponent warningHeader;
|
||||
|
||||
public LoadingErrorScreen(LoadingFailedException loadingException, List<ModLoadingWarning> warnings, final File dumpedLocation)
|
||||
{
|
||||
super(new StringTextComponent("Loading Error"), null);
|
||||
this.modLoadWarnings = warnings;
|
||||
this.modLoadErrors = loadingException == null ? Collections.emptyList() : loadingException.getErrors();
|
||||
this.modsDir = FMLPaths.MODSDIR.get();
|
||||
this.logFile = FMLPaths.GAMEDIR.get().resolve(Paths.get("logs","latest.log"));
|
||||
this.dumpedLocation = dumpedLocation != null ? dumpedLocation.toPath() : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init()
|
||||
{
|
||||
super.init();
|
||||
this.buttons.clear();
|
||||
this.children.clear();
|
||||
|
||||
this.errorHeader = new StringTextComponent(TextFormatting.RED + ForgeI18n.parseMessage("fml.loadingerrorscreen.errorheader", this.modLoadErrors.size()) + TextFormatting.RESET);
|
||||
this.warningHeader = new StringTextComponent(TextFormatting.YELLOW + ForgeI18n.parseMessage("fml.loadingerrorscreen.warningheader", this.modLoadErrors.size()) + TextFormatting.RESET);
|
||||
|
||||
int yOffset = 46;
|
||||
this.addButton(new ExtendedButton(50, this.height - yOffset, this.width / 2 - 55, 20, new StringTextComponent(ForgeI18n.parseMessage("fml.button.open.mods.folder")), b -> Util.getPlatform().openFile(modsDir.toFile())));
|
||||
this.addButton(new ExtendedButton(this.width / 2 + 5, this.height - yOffset, this.width / 2 - 55, 20, new StringTextComponent(ForgeI18n.parseMessage("fml.button.open.file", logFile.getFileName())), b -> Util.getPlatform().openFile(logFile.toFile())));
|
||||
if (this.modLoadErrors.isEmpty()) {
|
||||
this.addButton(new ExtendedButton(this.width / 4, this.height - 24, this.width / 2, 20, new StringTextComponent(ForgeI18n.parseMessage("fml.button.continue.launch")), b -> {
|
||||
ClientHooks.logMissingTextureErrors();
|
||||
this.minecraft.setScreen(null);
|
||||
}));
|
||||
} else {
|
||||
this.addButton(new ExtendedButton(this.width / 4, this.height - 24, this.width / 2, 20, new StringTextComponent(ForgeI18n.parseMessage("fml.button.open.file", dumpedLocation.getFileName())), b -> Util.getPlatform().openFile(dumpedLocation.toFile())));
|
||||
}
|
||||
|
||||
this.entryList = new LoadingEntryList(this, this.modLoadErrors, this.modLoadWarnings);
|
||||
this.children.add(this.entryList);
|
||||
this.setFocused(this.entryList);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void render(MatrixStack mStack, int mouseX, int mouseY, float partialTicks)
|
||||
{
|
||||
this.renderBackground(mStack);
|
||||
this.entryList.render(mStack, mouseX, mouseY, partialTicks);
|
||||
drawMultiLineCenteredString(mStack, font, this.modLoadErrors.isEmpty() ? warningHeader : errorHeader, this.width / 2, 10);
|
||||
this.buttons.forEach(button -> button.render(mStack, mouseX, mouseY, partialTicks));
|
||||
}
|
||||
|
||||
private void drawMultiLineCenteredString(MatrixStack mStack, FontRenderer fr, ITextComponent str, int x, int y) {
|
||||
for (IReorderingProcessor s : fr.split(str, this.width)) {
|
||||
fr.drawShadow(mStack, s, (float) (x - fr.width(s) / 2.0), y, 0xFFFFFF);
|
||||
y+=fr.lineHeight;
|
||||
}
|
||||
}
|
||||
public static class LoadingEntryList extends ExtendedList<LoadingEntryList.LoadingMessageEntry> {
|
||||
LoadingEntryList(final LoadingErrorScreen parent, final List<ModLoadingException> errors, final List<ModLoadingWarning> warnings) {
|
||||
super(parent.minecraft, parent.width, parent.height, 35, parent.height - 50, 2 * parent.minecraft.font.lineHeight + 8);
|
||||
boolean both = !errors.isEmpty() && !warnings.isEmpty();
|
||||
if (both)
|
||||
addEntry(new LoadingMessageEntry(parent.errorHeader, true));
|
||||
errors.forEach(e->addEntry(new LoadingMessageEntry(new StringTextComponent(e.formatToString()))));
|
||||
if (both) {
|
||||
int maxChars = (this.width - 10) / parent.minecraft.font.width("-");
|
||||
addEntry(new LoadingMessageEntry(new StringTextComponent("\n" + Strings.repeat("-", maxChars) + "\n")));
|
||||
addEntry(new LoadingMessageEntry(parent.warningHeader, true));
|
||||
}
|
||||
warnings.forEach(w->addEntry(new LoadingMessageEntry(new StringTextComponent(w.formatToString()))));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int getScrollbarPosition()
|
||||
{
|
||||
return this.getRight() - 6;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getRowWidth()
|
||||
{
|
||||
return this.width;
|
||||
}
|
||||
|
||||
public class LoadingMessageEntry extends ExtendedList.AbstractListEntry<LoadingMessageEntry> {
|
||||
private final ITextComponent message;
|
||||
private final boolean center;
|
||||
|
||||
LoadingMessageEntry(final ITextComponent message) {
|
||||
this(message, false);
|
||||
}
|
||||
|
||||
LoadingMessageEntry(final ITextComponent message, final boolean center) {
|
||||
this.message = Objects.requireNonNull(message);
|
||||
this.center = center;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void render(MatrixStack mStack, int entryIdx, int top, int left, final int entryWidth, final int entryHeight, final int mouseX, final int mouseY, final boolean p_194999_5_, final float partialTicks) {
|
||||
FontRenderer font = Minecraft.getInstance().font;
|
||||
final List<IReorderingProcessor> strings = font.split(message, LoadingEntryList.this.width);
|
||||
int y = top + 2;
|
||||
for (int i = 0; i < Math.min(strings.size(), 2); i++) {
|
||||
if (center)
|
||||
font.draw(mStack, strings.get(i), left + (width) - font.width(strings.get(i)) / 2F, y, 0xFFFFFF);
|
||||
else
|
||||
font.draw(mStack, strings.get(i), left + 5, y, 0xFFFFFF);
|
||||
y += font.lineHeight;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,512 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.client.gui.screen;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import com.mojang.blaze3d.matrix.MatrixStack;
|
||||
import cpw.mods.modlauncher.Environment;
|
||||
import net.minecraft.util.text.*;
|
||||
import net.minecraftforge.fml.loading.FMLEnvironment;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.apache.maven.artifact.versioning.ComparableVersion;
|
||||
|
||||
import com.mojang.blaze3d.systems.RenderSystem;
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.FontRenderer;
|
||||
import net.minecraft.client.gui.screen.Screen;
|
||||
import net.minecraft.client.gui.widget.TextFieldWidget;
|
||||
import net.minecraft.client.gui.widget.button.Button;
|
||||
import net.minecraft.client.gui.widget.list.ExtendedList;
|
||||
import net.minecraft.client.renderer.Tessellator;
|
||||
import net.minecraft.client.renderer.texture.DynamicTexture;
|
||||
import net.minecraft.client.renderer.texture.NativeImage;
|
||||
import net.minecraft.client.renderer.texture.TextureManager;
|
||||
import net.minecraft.util.IReorderingProcessor;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import net.minecraft.util.Util;
|
||||
import net.minecraftforge.client.gui.ScrollPanel;
|
||||
import net.minecraftforge.common.ForgeHooks;
|
||||
import net.minecraftforge.common.util.Size2i;
|
||||
import net.minecraftforge.fml.ForgeI18n;
|
||||
import net.minecraftforge.fml.MavenVersionStringHelper;
|
||||
import net.minecraftforge.fml.ModContainer;
|
||||
import net.minecraftforge.fml.ModList;
|
||||
import net.minecraftforge.fml.VersionChecker;
|
||||
import net.minecraftforge.fml.client.ConfigGuiHandler;
|
||||
import net.minecraftforge.fml.client.gui.GuiUtils;
|
||||
import net.minecraftforge.fml.client.gui.widget.ModListWidget;
|
||||
import net.minecraftforge.fml.loading.FMLPaths;
|
||||
import net.minecraftforge.fml.loading.StringUtils;
|
||||
import net.minecraftforge.fml.loading.moddiscovery.ModInfo;
|
||||
import net.minecraftforge.fml.packs.ModFileResourcePack;
|
||||
import net.minecraftforge.fml.packs.ResourcePackLoader;
|
||||
import net.minecraftforge.forgespi.language.IModInfo;
|
||||
|
||||
public class ModListScreen extends Screen
|
||||
{
|
||||
private static String stripControlCodes(String value) { return net.minecraft.util.StringUtils.stripColor(value); }
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
private enum SortType implements Comparator<ModInfo>
|
||||
{
|
||||
NORMAL,
|
||||
A_TO_Z{ @Override protected int compare(String name1, String name2){ return name1.compareTo(name2); }},
|
||||
Z_TO_A{ @Override protected int compare(String name1, String name2){ return name2.compareTo(name1); }};
|
||||
|
||||
Button button;
|
||||
protected int compare(String name1, String name2){ return 0; }
|
||||
@Override
|
||||
public int compare(ModInfo o1, ModInfo o2) {
|
||||
String name1 = StringUtils.toLowerCase(stripControlCodes(o1.getDisplayName()));
|
||||
String name2 = StringUtils.toLowerCase(stripControlCodes(o2.getDisplayName()));
|
||||
return compare(name1, name2);
|
||||
}
|
||||
|
||||
ITextComponent getButtonText() {
|
||||
return new TranslationTextComponent("fml.menu.mods." + StringUtils.toLowerCase(name()));
|
||||
}
|
||||
}
|
||||
|
||||
private static final int PADDING = 6;
|
||||
|
||||
private Screen parentScreen;
|
||||
|
||||
private ModListWidget modList;
|
||||
private InfoPanel modInfo;
|
||||
private ModListWidget.ModEntry selected = null;
|
||||
private int listWidth;
|
||||
private List<ModInfo> mods;
|
||||
private final List<ModInfo> unsortedMods;
|
||||
private Button configButton, openModsFolderButton;
|
||||
|
||||
private int buttonMargin = 1;
|
||||
private int numButtons = SortType.values().length;
|
||||
private String lastFilterText = "";
|
||||
|
||||
private TextFieldWidget search;
|
||||
|
||||
private boolean sorted = false;
|
||||
private SortType sortType = SortType.NORMAL;
|
||||
|
||||
/**
|
||||
* @param parentScreen
|
||||
*/
|
||||
public ModListScreen(Screen parentScreen)
|
||||
{
|
||||
super(new TranslationTextComponent("fml.menu.mods.title"));
|
||||
this.parentScreen = parentScreen;
|
||||
this.mods = Collections.unmodifiableList(ModList.get().getMods());
|
||||
this.unsortedMods = Collections.unmodifiableList(this.mods);
|
||||
}
|
||||
|
||||
class InfoPanel extends ScrollPanel {
|
||||
private ResourceLocation logoPath;
|
||||
private Size2i logoDims = new Size2i(0, 0);
|
||||
private List<IReorderingProcessor> lines = Collections.emptyList();
|
||||
|
||||
InfoPanel(Minecraft mcIn, int widthIn, int heightIn, int topIn)
|
||||
{
|
||||
super(mcIn, widthIn, heightIn, topIn, modList.getRight() + PADDING);
|
||||
}
|
||||
|
||||
void setInfo(List<String> lines, ResourceLocation logoPath, Size2i logoDims)
|
||||
{
|
||||
this.logoPath = logoPath;
|
||||
this.logoDims = logoDims;
|
||||
this.lines = resizeContent(lines);
|
||||
}
|
||||
|
||||
void clearInfo()
|
||||
{
|
||||
this.logoPath = null;
|
||||
this.logoDims = new Size2i(0, 0);
|
||||
this.lines = Collections.emptyList();
|
||||
}
|
||||
|
||||
private List<IReorderingProcessor> resizeContent(List<String> lines)
|
||||
{
|
||||
List<IReorderingProcessor> ret = new ArrayList<>();
|
||||
for (String line : lines)
|
||||
{
|
||||
if (line == null)
|
||||
{
|
||||
ret.add(null);
|
||||
continue;
|
||||
}
|
||||
|
||||
ITextComponent chat = ForgeHooks.newChatWithLinks(line, false);
|
||||
int maxTextLength = this.width - 12;
|
||||
if (maxTextLength >= 0)
|
||||
{
|
||||
ret.addAll(LanguageMap.getInstance().getVisualOrder(font.getSplitter().splitLines(chat, maxTextLength, Style.EMPTY)));
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getContentHeight()
|
||||
{
|
||||
int height = 50;
|
||||
height += (lines.size() * font.lineHeight);
|
||||
if (height < this.bottom - this.top - 8)
|
||||
height = this.bottom - this.top - 8;
|
||||
return height;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int getScrollAmount()
|
||||
{
|
||||
return font.lineHeight * 3;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void drawPanel(MatrixStack mStack, int entryRight, int relativeY, Tessellator tess, int mouseX, int mouseY)
|
||||
{
|
||||
if (logoPath != null) {
|
||||
Minecraft.getInstance().getTextureManager().bind(logoPath);
|
||||
RenderSystem.enableBlend();
|
||||
RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F);
|
||||
// Draw the logo image inscribed in a rectangle with width entryWidth (minus some padding) and height 50
|
||||
int headerHeight = 50;
|
||||
GuiUtils.drawInscribedRect(mStack, left + PADDING, relativeY, width - (PADDING * 2), headerHeight, logoDims.width, logoDims.height, false, true);
|
||||
relativeY += headerHeight + PADDING;
|
||||
}
|
||||
|
||||
for (IReorderingProcessor line : lines)
|
||||
{
|
||||
if (line != null)
|
||||
{
|
||||
RenderSystem.enableBlend();
|
||||
ModListScreen.this.font.drawShadow(mStack, line, left + PADDING, relativeY, 0xFFFFFF);
|
||||
RenderSystem.disableAlphaTest();
|
||||
RenderSystem.disableBlend();
|
||||
}
|
||||
relativeY += font.lineHeight;
|
||||
}
|
||||
|
||||
final Style component = findTextLine(mouseX, mouseY);
|
||||
if (component!=null) {
|
||||
ModListScreen.this.renderComponentHoverEffect(mStack, component, mouseX, mouseY);
|
||||
}
|
||||
}
|
||||
|
||||
private Style findTextLine(final int mouseX, final int mouseY) {
|
||||
double offset = (mouseY - top) + border + scrollDistance + 1;
|
||||
if (logoPath != null) {
|
||||
offset -= 50;
|
||||
}
|
||||
if (offset <= 0)
|
||||
return null;
|
||||
|
||||
int lineIdx = (int) (offset / font.lineHeight);
|
||||
if (lineIdx >= lines.size() || lineIdx < 1)
|
||||
return null;
|
||||
|
||||
IReorderingProcessor line = lines.get(lineIdx-1);
|
||||
if (line != null)
|
||||
{
|
||||
return font.getSplitter().componentStyleAtWidth(line, mouseX - left - border);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean mouseClicked(final double mouseX, final double mouseY, final int button) {
|
||||
final Style component = findTextLine((int) mouseX, (int) mouseY);
|
||||
if (component != null) {
|
||||
ModListScreen.this.handleComponentClicked(component);
|
||||
return true;
|
||||
}
|
||||
return super.mouseClicked(mouseX, mouseY, button);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void drawBackground() {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init()
|
||||
{
|
||||
for (ModInfo mod : mods)
|
||||
{
|
||||
listWidth = Math.max(listWidth,getFontRenderer().width(mod.getDisplayName()) + 10);
|
||||
listWidth = Math.max(listWidth,getFontRenderer().width(MavenVersionStringHelper.artifactVersionToString(mod.getVersion())) + 5);
|
||||
}
|
||||
listWidth = Math.max(Math.min(listWidth, width/3), 100);
|
||||
listWidth += listWidth % numButtons != 0 ? (numButtons - listWidth % numButtons) : 0;
|
||||
|
||||
int modInfoWidth = this.width - this.listWidth - (PADDING * 3);
|
||||
int doneButtonWidth = Math.min(modInfoWidth, 200);
|
||||
int y = this.height - 20 - PADDING;
|
||||
this.addButton(new Button(((listWidth + PADDING + this.width - doneButtonWidth) / 2), y, doneButtonWidth, 20,
|
||||
new TranslationTextComponent("gui.done"), b -> ModListScreen.this.onClose()));
|
||||
this.addButton(this.openModsFolderButton = new Button(6, y, this.listWidth, 20,
|
||||
new TranslationTextComponent("fml.menu.mods.openmodsfolder"), b -> Util.getPlatform().openFile(FMLPaths.MODSDIR.get().toFile())));
|
||||
y -= 20 + PADDING;
|
||||
this.addButton(this.configButton = new Button(6, y, this.listWidth, 20,
|
||||
new TranslationTextComponent("fml.menu.mods.config"), b -> ModListScreen.this.displayModConfig()));
|
||||
this.configButton.active = false;
|
||||
|
||||
y -= 14 + PADDING + 1;
|
||||
search = new TextFieldWidget(getFontRenderer(), PADDING + 1, y, listWidth - 2, 14, new TranslationTextComponent("fml.menu.mods.search"));
|
||||
|
||||
int fullButtonHeight = PADDING + 20 + PADDING;
|
||||
this.modList = new ModListWidget(this, listWidth, fullButtonHeight, search.y - getFontRenderer().lineHeight - PADDING);
|
||||
this.modList.setLeftPos(6);
|
||||
|
||||
this.modInfo = new InfoPanel(this.minecraft, modInfoWidth, this.height - PADDING - fullButtonHeight, PADDING);
|
||||
|
||||
children.add(search);
|
||||
children.add(modList);
|
||||
children.add(modInfo);
|
||||
search.setFocus(false);
|
||||
search.setCanLoseFocus(true);
|
||||
|
||||
final int width = listWidth / numButtons;
|
||||
int x = PADDING;
|
||||
addButton(SortType.NORMAL.button = new Button(x, PADDING, width - buttonMargin, 20, SortType.NORMAL.getButtonText(), b -> resortMods(SortType.NORMAL)));
|
||||
x += width + buttonMargin;
|
||||
addButton(SortType.A_TO_Z.button = new Button(x, PADDING, width - buttonMargin, 20, SortType.A_TO_Z.getButtonText(), b -> resortMods(SortType.A_TO_Z)));
|
||||
x += width + buttonMargin;
|
||||
addButton(SortType.Z_TO_A.button = new Button(x, PADDING, width - buttonMargin, 20, SortType.Z_TO_A.getButtonText(), b -> resortMods(SortType.Z_TO_A)));
|
||||
resortMods(SortType.NORMAL);
|
||||
updateCache();
|
||||
}
|
||||
|
||||
private void displayModConfig()
|
||||
{
|
||||
if (selected == null) return;
|
||||
try
|
||||
{
|
||||
ConfigGuiHandler.getGuiFactoryFor(selected.getInfo()).map(f->f.apply(this.minecraft, this)).ifPresent(newScreen -> this.minecraft.setScreen(newScreen));
|
||||
}
|
||||
catch (final Exception e)
|
||||
{
|
||||
LOGGER.error("There was a critical issue trying to build the config GUI for {}", selected.getInfo().getModId(), e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void tick()
|
||||
{
|
||||
search.tick();
|
||||
modList.setSelected(selected);
|
||||
|
||||
if (!search.getValue().equals(lastFilterText))
|
||||
{
|
||||
reloadMods();
|
||||
sorted = false;
|
||||
}
|
||||
|
||||
if (!sorted)
|
||||
{
|
||||
reloadMods();
|
||||
mods.sort(sortType);
|
||||
modList.refreshList();
|
||||
if (selected != null)
|
||||
{
|
||||
selected = modList.children().stream().filter(e -> e.getInfo() == selected.getInfo()).findFirst().orElse(null);
|
||||
updateCache();
|
||||
}
|
||||
sorted = true;
|
||||
}
|
||||
}
|
||||
|
||||
public <T extends ExtendedList.AbstractListEntry<T>> void buildModList(Consumer<T> modListViewConsumer, Function<ModInfo, T> newEntry)
|
||||
{
|
||||
mods.forEach(mod->modListViewConsumer.accept(newEntry.apply(mod)));
|
||||
}
|
||||
|
||||
private void reloadMods()
|
||||
{
|
||||
this.mods = this.unsortedMods.stream().
|
||||
filter(mi->StringUtils.toLowerCase(stripControlCodes(mi.getDisplayName())).contains(StringUtils.toLowerCase(search.getValue()))).collect(Collectors.toList());
|
||||
lastFilterText = search.getValue();
|
||||
}
|
||||
|
||||
private void resortMods(SortType newSort)
|
||||
{
|
||||
this.sortType = newSort;
|
||||
|
||||
for (SortType sort : SortType.values())
|
||||
{
|
||||
if (sort.button != null)
|
||||
sort.button.active = sortType != sort;
|
||||
}
|
||||
sorted = false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void render(MatrixStack mStack, int mouseX, int mouseY, float partialTicks)
|
||||
{
|
||||
this.modList.render(mStack, mouseX, mouseY, partialTicks);
|
||||
if (this.modInfo != null)
|
||||
this.modInfo.render(mStack, mouseX, mouseY, partialTicks);
|
||||
|
||||
ITextComponent text = new TranslationTextComponent("fml.menu.mods.search");
|
||||
int x = modList.getLeft() + ((modList.getRight() - modList.getLeft()) / 2) - (getFontRenderer().width(text) / 2);
|
||||
getFontRenderer().draw(mStack, text.getVisualOrderText(), x, search.y - getFontRenderer().lineHeight, 0xFFFFFF);
|
||||
this.search.render(mStack, mouseX , mouseY, partialTicks);
|
||||
super.render(mStack, mouseX, mouseY, partialTicks);
|
||||
}
|
||||
|
||||
public Minecraft getMinecraftInstance()
|
||||
{
|
||||
return minecraft;
|
||||
}
|
||||
|
||||
public FontRenderer getFontRenderer()
|
||||
{
|
||||
return font;
|
||||
}
|
||||
|
||||
public void setSelected(ModListWidget.ModEntry entry)
|
||||
{
|
||||
this.selected = entry == this.selected ? null : entry;
|
||||
updateCache();
|
||||
}
|
||||
|
||||
private void updateCache()
|
||||
{
|
||||
if (selected == null) {
|
||||
this.configButton.active = false;
|
||||
this.modInfo.clearInfo();
|
||||
return;
|
||||
}
|
||||
ModInfo selectedMod = selected.getInfo();
|
||||
this.configButton.active = ConfigGuiHandler.getGuiFactoryFor(selectedMod).isPresent();
|
||||
List<String> lines = new ArrayList<>();
|
||||
VersionChecker.CheckResult vercheck = VersionChecker.getResult(selectedMod);
|
||||
|
||||
@SuppressWarnings("resource")
|
||||
Pair<ResourceLocation, Size2i> logoData = selectedMod.getLogoFile().map(logoFile->
|
||||
{
|
||||
TextureManager tm = this.minecraft.getTextureManager();
|
||||
final ModFileResourcePack resourcePack = ResourcePackLoader.getResourcePackFor(selectedMod.getModId())
|
||||
.orElse(ResourcePackLoader.getResourcePackFor("forge").
|
||||
orElseThrow(()->new RuntimeException("Can't find forge, WHAT!")));
|
||||
try
|
||||
{
|
||||
NativeImage logo = null;
|
||||
InputStream logoResource = resourcePack.getRootResource(logoFile);
|
||||
if (logoResource != null)
|
||||
logo = NativeImage.read(logoResource);
|
||||
if (logo != null)
|
||||
{
|
||||
|
||||
return Pair.of(tm.register("modlogo", new DynamicTexture(logo) {
|
||||
|
||||
@Override
|
||||
public void upload() {
|
||||
this.bind();
|
||||
NativeImage td = this.getPixels();
|
||||
// Use custom "blur" value which controls texture filtering (nearest-neighbor vs linear)
|
||||
this.getPixels().upload(0, 0, 0, 0, 0, td.getWidth(), td.getHeight(), selectedMod.getLogoBlur(), false, false, false);
|
||||
}
|
||||
}), new Size2i(logo.getWidth(), logo.getHeight()));
|
||||
}
|
||||
}
|
||||
catch (IOException e) { }
|
||||
return Pair.<ResourceLocation, Size2i>of(null, new Size2i(0, 0));
|
||||
}).orElse(Pair.of(null, new Size2i(0, 0)));
|
||||
|
||||
lines.add(selectedMod.getDisplayName());
|
||||
lines.add(ForgeI18n.parseMessage("fml.menu.mods.info.version", MavenVersionStringHelper.artifactVersionToString(selectedMod.getVersion())));
|
||||
lines.add(ForgeI18n.parseMessage("fml.menu.mods.info.idstate", selectedMod.getModId(), ModList.get().getModContainerById(selectedMod.getModId()).
|
||||
map(ModContainer::getCurrentState).map(Object::toString).orElse("NONE")));
|
||||
|
||||
selectedMod.getConfigElement("credits").ifPresent(credits->
|
||||
lines.add(ForgeI18n.parseMessage("fml.menu.mods.info.credits", credits)));
|
||||
selectedMod.getConfigElement("authors").ifPresent(authors ->
|
||||
lines.add(ForgeI18n.parseMessage("fml.menu.mods.info.authors", authors)));
|
||||
selectedMod.getConfigElement("displayURL").ifPresent(displayURL ->
|
||||
lines.add(ForgeI18n.parseMessage("fml.menu.mods.info.displayurl", displayURL)));
|
||||
if (selectedMod.getOwningFile() == null || selectedMod.getOwningFile().getMods().size()==1)
|
||||
lines.add(ForgeI18n.parseMessage("fml.menu.mods.info.nochildmods"));
|
||||
else
|
||||
lines.add(ForgeI18n.parseMessage("fml.menu.mods.info.childmods", selectedMod.getOwningFile().getMods().stream().map(IModInfo::getDisplayName).collect(Collectors.joining(","))));
|
||||
|
||||
if (vercheck.status == VersionChecker.Status.OUTDATED || vercheck.status == VersionChecker.Status.BETA_OUTDATED)
|
||||
lines.add(ForgeI18n.parseMessage("fml.menu.mods.info.updateavailable", vercheck.url == null ? "" : vercheck.url));
|
||||
lines.add(ForgeI18n.parseMessage("fml.menu.mods.info.license", selectedMod.getOwningFile().getLicense()));
|
||||
lines.add(null);
|
||||
lines.add(selectedMod.getDescription());
|
||||
|
||||
/* Removed because people bitched that this information was misleading.
|
||||
lines.add(null);
|
||||
if (FMLEnvironment.secureJarsEnabled) {
|
||||
lines.add(ForgeI18n.parseMessage("fml.menu.mods.info.signature", selectedMod.getOwningFile().getCodeSigningFingerprint().orElse(ForgeI18n.parseMessage("fml.menu.mods.info.signature.unsigned"))));
|
||||
lines.add(ForgeI18n.parseMessage("fml.menu.mods.info.trust", selectedMod.getOwningFile().getTrustData().orElse(ForgeI18n.parseMessage("fml.menu.mods.info.trust.noauthority"))));
|
||||
} else {
|
||||
lines.add(ForgeI18n.parseMessage("fml.menu.mods.info.securejardisabled"));
|
||||
}
|
||||
*/
|
||||
|
||||
if ((vercheck.status == VersionChecker.Status.OUTDATED || vercheck.status == VersionChecker.Status.BETA_OUTDATED) && vercheck.changes.size() > 0)
|
||||
{
|
||||
lines.add(null);
|
||||
lines.add(ForgeI18n.parseMessage("fml.menu.mods.info.changelogheader"));
|
||||
for (Entry<ComparableVersion, String> entry : vercheck.changes.entrySet())
|
||||
{
|
||||
lines.add(" " + entry.getKey() + ":");
|
||||
lines.add(entry.getValue());
|
||||
lines.add(null);
|
||||
}
|
||||
}
|
||||
|
||||
modInfo.setInfo(lines, logoData.getLeft(), logoData.getRight());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void resize(Minecraft mc, int width, int height)
|
||||
{
|
||||
String s = this.search.getValue();
|
||||
SortType sort = this.sortType;
|
||||
ModListWidget.ModEntry selected = this.selected;
|
||||
this.init(mc, width, height);
|
||||
this.search.setValue(s);
|
||||
this.selected = selected;
|
||||
if (!this.search.getValue().isEmpty())
|
||||
reloadMods();
|
||||
if (sort != SortType.NORMAL)
|
||||
resortMods(sort);
|
||||
updateCache();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClose()
|
||||
{
|
||||
this.minecraft.setScreen(this.parentScreen);
|
||||
}
|
||||
}
|
||||
@@ -1,133 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
/*
|
||||
package net.minecraftforge.fml.client.gui.screen;
|
||||
|
||||
import com.mojang.blaze3d.matrix.MatrixStack;
|
||||
import net.minecraft.client.gui.widget.button.Button;
|
||||
import net.minecraft.client.renderer.Tessellator;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.screen.Screen;
|
||||
import net.minecraft.util.text.TranslationTextComponent;
|
||||
import net.minecraftforge.client.gui.ScrollPanel;
|
||||
|
||||
public class NotificationScreen extends Screen
|
||||
{
|
||||
private class TextPanel extends ScrollPanel
|
||||
{
|
||||
TextPanel(Minecraft client, int width, int height, int top, int left)
|
||||
{
|
||||
super(client, width, height, top, left);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int getContentHeight()
|
||||
{
|
||||
int height = 0;
|
||||
height += (textLines.length * font.FONT_HEIGHT) + 4;
|
||||
if (height < this.height - 50)
|
||||
height = this.height - 50;
|
||||
return height;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void drawPanel(MatrixStack mStack, int entryRight, int relativeY, Tessellator tess, int mouseX, int mouseY)
|
||||
{
|
||||
drawCenteredLines(mStack, relativeY, textLines);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int getScrollAmount()
|
||||
{
|
||||
return font.FONT_HEIGHT * 3;
|
||||
}
|
||||
}
|
||||
|
||||
protected static final int PADDING = 6;
|
||||
|
||||
protected final StartupQuery query;
|
||||
|
||||
private final String[] headerLines;
|
||||
private final String[] textLines;
|
||||
private final String action;
|
||||
|
||||
private ScrollPanel textPanel;
|
||||
|
||||
public NotificationScreen(StartupQuery query)
|
||||
{
|
||||
super(new TranslationTextComponent("fml.menu.notification.title"));
|
||||
this.query = query;
|
||||
this.headerLines = query.getHeader().isEmpty() ? new String[0] : query.getHeader().split("\n");
|
||||
this.textLines = query.getText().split("\n");
|
||||
this.action = query.getAction();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init()
|
||||
{
|
||||
super.init();
|
||||
int panelY = PADDING + headerLines.length * font.FONT_HEIGHT + PADDING;
|
||||
int panelHeight = this.height - PADDING - 20 - panelY;
|
||||
if (!action.isEmpty()) {
|
||||
panelHeight = panelHeight - font.FONT_HEIGHT - PADDING;
|
||||
}
|
||||
textPanel = new TextPanel(this.minecraft, this.width - (PADDING * 2), panelHeight, panelY, PADDING);
|
||||
this.children.add(textPanel);
|
||||
addConfirmationButtons();
|
||||
}
|
||||
|
||||
protected void addConfirmationButtons() {
|
||||
this.buttons.add(new Button(this.width / 2 - 100, this.height - PADDING - 20, 200, 20, new TranslationTextComponent("gui.done"), b -> {
|
||||
NotificationScreen.this.minecraft.displayGuiScreen(null);
|
||||
query.finish();
|
||||
}));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void render(MatrixStack mStack, int mouseX, int mouseY, float partialTicks)
|
||||
{
|
||||
this.renderBackground(mStack);
|
||||
|
||||
drawCenteredLines(mStack, PADDING, headerLines);
|
||||
|
||||
if (textPanel != null)
|
||||
{
|
||||
textPanel.render(mStack, mouseX, mouseY, partialTicks);
|
||||
}
|
||||
|
||||
if (!action.isEmpty())
|
||||
{
|
||||
drawCenteredString(mStack, font, action, this.width / 2, this.height - PADDING - 20 - font.FONT_HEIGHT, -1);
|
||||
}
|
||||
|
||||
super.render(mStack, mouseX, mouseY, partialTicks);
|
||||
}
|
||||
|
||||
protected void drawCenteredLines(MatrixStack mStack, int yStart, String... lines)
|
||||
{
|
||||
for (String line : lines)
|
||||
{
|
||||
if (!line.isEmpty())
|
||||
this.drawCenteredString(mStack, font, line, this.width / 2, yStart, 0xFFFFFF);
|
||||
yStart += font.FONT_HEIGHT;
|
||||
}
|
||||
}
|
||||
}
|
||||
*/
|
||||
@@ -1,73 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.client.gui.widget;
|
||||
|
||||
import com.mojang.blaze3d.matrix.MatrixStack;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.widget.button.Button;
|
||||
import net.minecraft.util.text.ITextComponent;
|
||||
import net.minecraft.util.text.StringTextComponent;
|
||||
import net.minecraftforge.fml.client.gui.GuiUtils;
|
||||
|
||||
import net.minecraft.client.gui.widget.button.Button.IPressable;
|
||||
|
||||
/**
|
||||
* This class provides a button that fixes several bugs present in the vanilla GuiButton drawing code.
|
||||
* The gist of it is that it allows buttons of any size without gaps in the graphics and with the
|
||||
* borders drawn properly. It also prevents button text from extending out of the sides of the button by
|
||||
* trimming the end of the string and adding an ellipsis.<br/><br/>
|
||||
*
|
||||
* The code that handles drawing the button is in GuiUtils.
|
||||
*
|
||||
* @author bspkrs
|
||||
*/
|
||||
public class ExtendedButton extends Button
|
||||
{
|
||||
public ExtendedButton(int xPos, int yPos, int width, int height, ITextComponent displayString, IPressable handler)
|
||||
{
|
||||
super(xPos, yPos, width, height, displayString, handler);
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws this button to the screen.
|
||||
*/
|
||||
@Override
|
||||
public void renderButton(MatrixStack mStack, int mouseX, int mouseY, float partial)
|
||||
{
|
||||
if (this.visible)
|
||||
{
|
||||
Minecraft mc = Minecraft.getInstance();
|
||||
this.isHovered = mouseX >= this.x && mouseY >= this.y && mouseX < this.x + this.width && mouseY < this.y + this.height;
|
||||
int k = this.getYImage(this.isHovered());
|
||||
GuiUtils.drawContinuousTexturedBox(mStack, WIDGETS_LOCATION, this.x, this.y, 0, 46 + k * 20, this.width, this.height, 200, 20, 2, 3, 2, 2, this.getBlitOffset());
|
||||
this.renderBg(mStack, mc, mouseX, mouseY);
|
||||
|
||||
ITextComponent buttonText = this.getMessage();
|
||||
int strWidth = mc.font.width(buttonText);
|
||||
int ellipsisWidth = mc.font.width("...");
|
||||
|
||||
if (strWidth > width - 6 && strWidth > ellipsisWidth)
|
||||
//TODO, srg names make it hard to figure out how to append to an ITextProperties from this trim operation, wraping this in StringTextComponent is kinda dirty.
|
||||
buttonText = new StringTextComponent(mc.font.substrByWidth(buttonText, width - 6 - ellipsisWidth).getString() + "...");
|
||||
|
||||
drawCenteredString(mStack, mc.font, buttonText, this.x + this.width / 2, this.y + (this.height - 8) / 2, getFGColor());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.client.gui.widget;
|
||||
|
||||
import com.mojang.blaze3d.matrix.MatrixStack;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.FontRenderer;
|
||||
import net.minecraft.client.gui.AbstractGui;
|
||||
import net.minecraft.client.gui.widget.list.ExtendedList;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import net.minecraft.util.text.ITextComponent;
|
||||
import net.minecraft.util.text.ITextProperties;
|
||||
import net.minecraft.util.text.LanguageMap;
|
||||
import net.minecraft.util.text.StringTextComponent;
|
||||
import net.minecraftforge.fml.client.gui.screen.ModListScreen;
|
||||
import net.minecraftforge.versions.forge.ForgeVersion;
|
||||
import net.minecraftforge.fml.MavenVersionStringHelper;
|
||||
import net.minecraftforge.fml.VersionChecker;
|
||||
import net.minecraftforge.fml.loading.moddiscovery.ModInfo;
|
||||
|
||||
import com.mojang.blaze3d.systems.RenderSystem;
|
||||
|
||||
public class ModListWidget extends ExtendedList<ModListWidget.ModEntry>
|
||||
{
|
||||
private static String stripControlCodes(String value) { return net.minecraft.util.StringUtils.stripColor(value); }
|
||||
private static final ResourceLocation VERSION_CHECK_ICONS = new ResourceLocation(ForgeVersion.MOD_ID, "textures/gui/version_check_icons.png");
|
||||
private final int listWidth;
|
||||
|
||||
private ModListScreen parent;
|
||||
|
||||
public ModListWidget(ModListScreen parent, int listWidth, int top, int bottom)
|
||||
{
|
||||
super(parent.getMinecraftInstance(), listWidth, parent.height, top, bottom, parent.getFontRenderer().lineHeight * 2 + 8);
|
||||
this.parent = parent;
|
||||
this.listWidth = listWidth;
|
||||
this.refreshList();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int getScrollbarPosition()
|
||||
{
|
||||
return this.listWidth;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getRowWidth()
|
||||
{
|
||||
return this.listWidth;
|
||||
}
|
||||
|
||||
public void refreshList() {
|
||||
this.clearEntries();
|
||||
parent.buildModList(this::addEntry, mod->new ModEntry(mod, this.parent));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void renderBackground(MatrixStack mStack)
|
||||
{
|
||||
this.parent.renderBackground(mStack);
|
||||
}
|
||||
|
||||
public class ModEntry extends ExtendedList.AbstractListEntry<ModEntry> {
|
||||
private final ModInfo modInfo;
|
||||
private final ModListScreen parent;
|
||||
|
||||
ModEntry(ModInfo info, ModListScreen parent) {
|
||||
this.modInfo = info;
|
||||
this.parent = parent;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void render(MatrixStack mStack, int entryIdx, int top, int left, int entryWidth, int entryHeight, int mouseX, int mouseY, boolean p_194999_5_, float partialTicks)
|
||||
{
|
||||
ITextComponent name = new StringTextComponent(stripControlCodes(modInfo.getDisplayName()));
|
||||
ITextComponent version = new StringTextComponent(stripControlCodes(MavenVersionStringHelper.artifactVersionToString(modInfo.getVersion())));
|
||||
VersionChecker.CheckResult vercheck = VersionChecker.getResult(modInfo);
|
||||
FontRenderer font = this.parent.getFontRenderer();
|
||||
font.draw(mStack, LanguageMap.getInstance().getVisualOrder(ITextProperties.composite(font.substrByWidth(name, listWidth))), left + 3, top + 2, 0xFFFFFF);
|
||||
font.draw(mStack, LanguageMap.getInstance().getVisualOrder(ITextProperties.composite(font.substrByWidth(version, listWidth))), left + 3, top + 2 + font.lineHeight, 0xCCCCCC);
|
||||
if (vercheck.status.shouldDraw())
|
||||
{
|
||||
//TODO: Consider adding more icons for visualization
|
||||
Minecraft.getInstance().getTextureManager().bind(VERSION_CHECK_ICONS);
|
||||
RenderSystem.color4f(1, 1, 1, 1);
|
||||
RenderSystem.pushMatrix();
|
||||
AbstractGui.blit(mStack, getLeft() + width - 12, top + entryHeight / 4, vercheck.status.getSheetOffset() * 8, (vercheck.status.isAnimated() && ((System.currentTimeMillis() / 800 & 1)) == 1) ? 8 : 0, 8, 8, 64, 16);
|
||||
RenderSystem.popMatrix();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean mouseClicked(double p_mouseClicked_1_, double p_mouseClicked_3_, int p_mouseClicked_5_)
|
||||
{
|
||||
parent.setSelected(this);
|
||||
ModListWidget.this.setSelected(this);
|
||||
return false;
|
||||
}
|
||||
|
||||
public ModInfo getInfo()
|
||||
{
|
||||
return modInfo;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,218 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.client.gui.widget;
|
||||
|
||||
import com.mojang.blaze3d.matrix.MatrixStack;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.util.text.ITextComponent;
|
||||
import net.minecraft.util.text.StringTextComponent;
|
||||
import net.minecraftforge.fml.client.gui.GuiUtils;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
import net.minecraft.client.gui.widget.button.Button.IPressable;
|
||||
|
||||
/**
|
||||
* This class is blatantly stolen from iChunUtils with permission.
|
||||
*
|
||||
* @author iChun
|
||||
*/
|
||||
public class Slider extends ExtendedButton
|
||||
{
|
||||
/** The value of this slider control. */
|
||||
public double sliderValue = 1.0F;
|
||||
|
||||
public ITextComponent dispString;
|
||||
|
||||
/** Is this slider control being dragged. */
|
||||
public boolean dragging = false;
|
||||
public boolean showDecimal = true;
|
||||
|
||||
public double minValue = 0.0D;
|
||||
public double maxValue = 5.0D;
|
||||
public int precision = 1;
|
||||
|
||||
@Nullable
|
||||
public ISlider parent = null;
|
||||
|
||||
public ITextComponent suffix;
|
||||
|
||||
public boolean drawString = true;
|
||||
|
||||
public Slider(int xPos, int yPos, int width, int height, ITextComponent prefix, ITextComponent suf, double minVal, double maxVal, double currentVal, boolean showDec, boolean drawStr, IPressable handler)
|
||||
{
|
||||
this(xPos, yPos, width, height, prefix, suf, minVal, maxVal, currentVal, showDec, drawStr, handler, null);
|
||||
}
|
||||
|
||||
public Slider(int xPos, int yPos, int width, int height, ITextComponent prefix, ITextComponent suf, double minVal, double maxVal, double currentVal, boolean showDec, boolean drawStr, IPressable handler, @Nullable ISlider par)
|
||||
{
|
||||
super(xPos, yPos, width, height, prefix, handler);
|
||||
minValue = minVal;
|
||||
maxValue = maxVal;
|
||||
sliderValue = (currentVal - minValue) / (maxValue - minValue);
|
||||
dispString = prefix;
|
||||
parent = par;
|
||||
suffix = suf;
|
||||
showDecimal = showDec;
|
||||
String val;
|
||||
|
||||
if (showDecimal)
|
||||
{
|
||||
val = Double.toString(sliderValue * (maxValue - minValue) + minValue);
|
||||
precision = Math.min(val.substring(val.indexOf(".") + 1).length(), 4);
|
||||
}
|
||||
else
|
||||
{
|
||||
val = Integer.toString((int)Math.round(sliderValue * (maxValue - minValue) + minValue));
|
||||
precision = 0;
|
||||
}
|
||||
|
||||
setMessage(new StringTextComponent("").append(dispString).append(val).append(suffix));
|
||||
|
||||
drawString = drawStr;
|
||||
if(!drawString)
|
||||
setMessage(new StringTextComponent(""));
|
||||
}
|
||||
|
||||
public Slider(int xPos, int yPos, ITextComponent displayStr, double minVal, double maxVal, double currentVal, IPressable handler, ISlider par)
|
||||
{
|
||||
this(xPos, yPos, 150, 20, displayStr, new StringTextComponent(""), minVal, maxVal, currentVal, true, true, handler, par);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns 0 if the button is disabled, 1 if the mouse is NOT hovering over this button and 2 if it IS hovering over
|
||||
* this button.
|
||||
*/
|
||||
@Override
|
||||
public int getYImage(boolean par1)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fired when the mouse button is dragged. Equivalent of MouseListener.mouseDragged(MouseEvent e).
|
||||
*/
|
||||
@Override
|
||||
protected void renderBg(MatrixStack mStack, Minecraft par1Minecraft, int par2, int par3)
|
||||
{
|
||||
if (this.visible)
|
||||
{
|
||||
if (this.dragging)
|
||||
{
|
||||
this.sliderValue = (par2 - (this.x + 4)) / (float)(this.width - 8);
|
||||
updateSlider();
|
||||
}
|
||||
|
||||
GuiUtils.drawContinuousTexturedBox(mStack, WIDGETS_LOCATION, this.x + (int)(this.sliderValue * (float)(this.width - 8)), this.y, 0, 66, 8, this.height, 200, 20, 2, 3, 2, 2, this.getBlitOffset());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the mouse has been pressed on this control. Equivalent of MouseListener.mousePressed(MouseEvent
|
||||
* e).
|
||||
*/
|
||||
@Override
|
||||
public void onClick(double mouseX, double mouseY)
|
||||
{
|
||||
this.sliderValue = (mouseX - (this.x + 4)) / (this.width - 8);
|
||||
updateSlider();
|
||||
this.dragging = true;
|
||||
}
|
||||
|
||||
public void updateSlider()
|
||||
{
|
||||
if (this.sliderValue < 0.0F)
|
||||
{
|
||||
this.sliderValue = 0.0F;
|
||||
}
|
||||
|
||||
if (this.sliderValue > 1.0F)
|
||||
{
|
||||
this.sliderValue = 1.0F;
|
||||
}
|
||||
|
||||
String val;
|
||||
|
||||
if (showDecimal)
|
||||
{
|
||||
val = Double.toString(sliderValue * (maxValue - minValue) + minValue);
|
||||
|
||||
if (val.substring(val.indexOf(".") + 1).length() > precision)
|
||||
{
|
||||
val = val.substring(0, val.indexOf(".") + precision + 1);
|
||||
|
||||
if (val.endsWith("."))
|
||||
{
|
||||
val = val.substring(0, val.indexOf(".") + precision);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
while (val.substring(val.indexOf(".") + 1).length() < precision)
|
||||
{
|
||||
val = val + "0";
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
val = Integer.toString((int)Math.round(sliderValue * (maxValue - minValue) + minValue));
|
||||
}
|
||||
|
||||
if(drawString)
|
||||
{
|
||||
setMessage(new StringTextComponent("").append(dispString).append(val).append(suffix));
|
||||
}
|
||||
|
||||
if (parent != null)
|
||||
{
|
||||
parent.onChangeSliderValue(this);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fired when the mouse button is released. Equivalent of MouseListener.mouseReleased(MouseEvent e).
|
||||
*/
|
||||
@Override
|
||||
public void onRelease(double mouseX, double mouseY)
|
||||
{
|
||||
this.dragging = false;
|
||||
}
|
||||
|
||||
public int getValueInt()
|
||||
{
|
||||
return (int)Math.round(sliderValue * (maxValue - minValue) + minValue);
|
||||
}
|
||||
|
||||
public double getValue()
|
||||
{
|
||||
return sliderValue * (maxValue - minValue) + minValue;
|
||||
}
|
||||
|
||||
public void setValue(double d)
|
||||
{
|
||||
this.sliderValue = (d - minValue) / (maxValue - minValue);
|
||||
}
|
||||
|
||||
public static interface ISlider
|
||||
{
|
||||
void onChangeSliderValue(Slider slider);
|
||||
}
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.client.gui.widget;
|
||||
|
||||
import com.mojang.blaze3d.matrix.MatrixStack;
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.widget.button.Button;
|
||||
import net.minecraft.util.text.ITextComponent;
|
||||
import net.minecraft.util.text.StringTextComponent;
|
||||
import net.minecraftforge.fml.client.gui.GuiUtils;
|
||||
|
||||
import net.minecraft.client.gui.widget.button.Button.IPressable;
|
||||
|
||||
/**
|
||||
* This class provides a button that shows a string glyph at the beginning. The glyph can be scaled using the glyphScale parameter.
|
||||
*
|
||||
* @author bspkrs
|
||||
*/
|
||||
public class UnicodeGlyphButton extends ExtendedButton
|
||||
{
|
||||
public String glyph;
|
||||
public float glyphScale;
|
||||
|
||||
public UnicodeGlyphButton(int xPos, int yPos, int width, int height, ITextComponent displayString, String glyph, float glyphScale, IPressable handler)
|
||||
{
|
||||
super(xPos, yPos, width, height, displayString, handler);
|
||||
this.glyph = glyph;
|
||||
this.glyphScale = glyphScale;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void render(MatrixStack mStack, int mouseX, int mouseY, float partial)
|
||||
{
|
||||
if (this.visible)
|
||||
{
|
||||
Minecraft mc = Minecraft.getInstance();
|
||||
this.isHovered = mouseX >= this.x && mouseY >= this.y && mouseX < this.x + this.width && mouseY < this.y + this.height;
|
||||
int k = this.getYImage(this.isHovered);
|
||||
GuiUtils.drawContinuousTexturedBox(mStack, Button.WIDGETS_LOCATION, this.x, this.y, 0, 46 + k * 20, this.width, this.height, 200, 20, 2, 3, 2, 2, this.getBlitOffset());
|
||||
this.renderBg(mStack, mc, mouseX, mouseY);
|
||||
|
||||
ITextComponent buttonText = this.createNarrationMessage();
|
||||
int glyphWidth = (int) (mc.font.width(glyph) * glyphScale);
|
||||
int strWidth = mc.font.width(buttonText);
|
||||
int ellipsisWidth = mc.font.width("...");
|
||||
int totalWidth = strWidth + glyphWidth;
|
||||
|
||||
if (totalWidth > width - 6 && totalWidth > ellipsisWidth)
|
||||
buttonText = new StringTextComponent(mc.font.substrByWidth(buttonText, width - 6 - ellipsisWidth).getString().trim() + "...") ;
|
||||
|
||||
strWidth = mc.font.width(buttonText);
|
||||
totalWidth = glyphWidth + strWidth;
|
||||
|
||||
mStack.pushPose();
|
||||
mStack.scale(glyphScale, glyphScale, 1.0F);
|
||||
this.drawCenteredString(mStack, mc.font, new StringTextComponent(glyph),
|
||||
(int) (((this.x + (this.width / 2) - (strWidth / 2)) / glyphScale) - (glyphWidth / (2 * glyphScale)) + 2),
|
||||
(int) (((this.y + ((this.height - 8) / glyphScale) / 2) - 1) / glyphScale), getFGColor());
|
||||
mStack.popPose();
|
||||
|
||||
this.drawCenteredString(mStack, mc.font, buttonText, (int) (this.x + (this.width / 2) + (glyphWidth / glyphScale)),
|
||||
this.y + (this.height - 8) / 2, getFGColor());
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.client.registry;
|
||||
|
||||
import net.minecraft.client.renderer.tileentity.TileEntityRenderer;
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.tileentity.TileEntityType;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher;
|
||||
import net.minecraft.client.settings.KeyBinding;
|
||||
import net.minecraft.tileentity.TileEntity;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Function;
|
||||
|
||||
public class ClientRegistry
|
||||
{
|
||||
private static Map<Class<? extends Entity>, ResourceLocation> entityShaderMap = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* Registers a Tile Entity renderer.
|
||||
* Call this during {@link net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent}.
|
||||
* This method is safe to call during parallel mod loading.
|
||||
*/
|
||||
public static synchronized <T extends TileEntity> void bindTileEntityRenderer(TileEntityType<T> tileEntityType,
|
||||
Function<? super TileEntityRendererDispatcher, ? extends TileEntityRenderer<? super T>> rendererFactory)
|
||||
{
|
||||
TileEntityRendererDispatcher.instance.setSpecialRendererInternal(tileEntityType, rendererFactory.apply(TileEntityRendererDispatcher.instance));
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a KeyBinding.
|
||||
* Call this during {@link net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent}.
|
||||
* This method is safe to call during parallel mod loading.
|
||||
*/
|
||||
public static synchronized void registerKeyBinding(KeyBinding key)
|
||||
{
|
||||
Minecraft.getInstance().options.keyMappings = ArrayUtils.add(Minecraft.getInstance().options.keyMappings, key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a shader for an entity. This shader gets activated when a spectator begins spectating an entity.
|
||||
* Vanilla examples of this are the green effect for creepers and the invert effect for endermen.
|
||||
* Call this during {@link net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent}.
|
||||
* This method is safe to call during parallel mod loading.
|
||||
*/
|
||||
public static void registerEntityShader(Class<? extends Entity> entityClass, ResourceLocation shader)
|
||||
{
|
||||
entityShaderMap.put(entityClass, shader);
|
||||
}
|
||||
|
||||
public static ResourceLocation getEntityShader(Class<? extends Entity> entityClass)
|
||||
{
|
||||
return entityShaderMap.get(entityClass);
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.client.registry;
|
||||
|
||||
import net.minecraft.client.renderer.entity.EntityRenderer;
|
||||
import net.minecraft.client.renderer.entity.EntityRendererManager;
|
||||
import net.minecraft.entity.Entity;
|
||||
|
||||
public interface IRenderFactory<T extends Entity>
|
||||
{
|
||||
EntityRenderer<? super T> createRenderFor(EntityRendererManager manager);
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.client.registry;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import net.minecraft.client.renderer.entity.EntityRenderer;
|
||||
import net.minecraft.client.renderer.entity.EntityRendererManager;
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.entity.EntityType;
|
||||
|
||||
public class RenderingRegistry
|
||||
{
|
||||
private static final RenderingRegistry INSTANCE = new RenderingRegistry();
|
||||
|
||||
private final Map<EntityType<? extends Entity>, IRenderFactory<? extends Entity>> entityRenderers = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* Register an entity rendering handler. This will, after mod initialization, be inserted into the main
|
||||
* render map for entities.
|
||||
* Call this during {@link net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent}.
|
||||
* This method is safe to call during parallel mod loading.
|
||||
*/
|
||||
public static <T extends Entity> void registerEntityRenderingHandler(EntityType<T> entityClass, IRenderFactory<? super T> renderFactory)
|
||||
{
|
||||
INSTANCE.entityRenderers.put(entityClass, renderFactory);
|
||||
}
|
||||
|
||||
public static void loadEntityRenderers(EntityRendererManager manager)
|
||||
{
|
||||
INSTANCE.entityRenderers.forEach((key, value) -> register(manager, key, value));
|
||||
manager.validateRendererExistence();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static <T extends Entity> void register(EntityRendererManager manager, EntityType<T> entityType, IRenderFactory<?> renderFactory)
|
||||
{
|
||||
manager.register(entityType, ((IRenderFactory<T>)renderFactory).createRenderFor(manager));
|
||||
}
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.common;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.cert.Certificate;
|
||||
|
||||
public class CertificateHelper {
|
||||
|
||||
private static final String HEXES = "0123456789abcdef";
|
||||
|
||||
public static ImmutableList<String> getFingerprints(Certificate[] certificates)
|
||||
{
|
||||
int len = 0;
|
||||
if (certificates != null)
|
||||
{
|
||||
len = certificates.length;
|
||||
}
|
||||
ImmutableList.Builder<String> certBuilder = ImmutableList.builder();
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
certBuilder.add(CertificateHelper.getFingerprint(certificates[i]));
|
||||
}
|
||||
return certBuilder.build();
|
||||
}
|
||||
|
||||
public static String getFingerprint(Certificate certificate)
|
||||
{
|
||||
if (certificate == null)
|
||||
{
|
||||
return "NO VALID CERTIFICATE FOUND";
|
||||
}
|
||||
try
|
||||
{
|
||||
MessageDigest md = MessageDigest.getInstance("SHA-1");
|
||||
byte[] der = certificate.getEncoded();
|
||||
md.update(der);
|
||||
byte[] digest = md.digest();
|
||||
return hexify(digest);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return "CERTIFICATE FINGERPRINT EXCEPTION";
|
||||
}
|
||||
}
|
||||
|
||||
public static String getFingerprint(ByteBuffer buffer)
|
||||
{
|
||||
try
|
||||
{
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-1");
|
||||
digest.update(buffer);
|
||||
byte[] chksum = digest.digest();
|
||||
return hexify(chksum);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return "CERTIFICATE FINGERPRINT EXCEPTION";
|
||||
}
|
||||
}
|
||||
|
||||
private static String hexify(byte[] chksum)
|
||||
{
|
||||
final StringBuilder hex = new StringBuilder( 2 * chksum.length );
|
||||
for ( final byte b : chksum ) {
|
||||
hex.append(HEXES.charAt((b & 0xF0) >> 4))
|
||||
.append(HEXES.charAt((b & 0x0F)));
|
||||
}
|
||||
return hex.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.common;
|
||||
|
||||
import java.io.PrintStream;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
|
||||
/**
|
||||
* RuntimeException that gives subclasses the simple opportunity to write extra data when printing the stack trace.
|
||||
* Mainly a helper class as printsStackTrace has multiple signatures.
|
||||
*/
|
||||
public abstract class EnhancedRuntimeException extends RuntimeException
|
||||
{
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public EnhancedRuntimeException() { super(); }
|
||||
public EnhancedRuntimeException(String message) { super(message); }
|
||||
public EnhancedRuntimeException(String message, Throwable cause) { super(message, cause); }
|
||||
public EnhancedRuntimeException(Throwable cause) { super(cause); }
|
||||
|
||||
@Override
|
||||
public String getMessage()
|
||||
{
|
||||
StackTraceElement[] stack = Thread.currentThread().getStackTrace();
|
||||
if (stack.length > 2 && stack[2].getClassName().startsWith("org.apache.logging.log4j."))
|
||||
{
|
||||
// This is a bit of a hack to force ourselves to be able to give a extended description when log4j prints this out.
|
||||
// Sadly this text is displayed AFTER the initial exception line, and before the stack trace. But as the intention
|
||||
// is to print this to the end user this is what we need to do.
|
||||
final StringWriter buf = new StringWriter();
|
||||
|
||||
String msg = super.getMessage();
|
||||
if (msg != null)
|
||||
buf.append(msg);
|
||||
|
||||
buf.append('\n');
|
||||
this.printStackTrace(new WrappedPrintStream()
|
||||
{
|
||||
@Override
|
||||
public void println(String line)
|
||||
{
|
||||
buf.append(line).append('\n');
|
||||
}
|
||||
});
|
||||
return buf.toString();
|
||||
}
|
||||
return super.getMessage();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void printStackTrace(final PrintWriter s)
|
||||
{
|
||||
printStackTrace(new WrappedPrintStream()
|
||||
{
|
||||
@Override
|
||||
public void println(String line)
|
||||
{
|
||||
s.println(line);
|
||||
}
|
||||
});
|
||||
super.printStackTrace(s);
|
||||
}
|
||||
@Override
|
||||
public void printStackTrace(final PrintStream s)
|
||||
{
|
||||
printStackTrace(new WrappedPrintStream()
|
||||
{
|
||||
@Override
|
||||
public void println(String line)
|
||||
{
|
||||
s.println(line);
|
||||
}
|
||||
});
|
||||
super.printStackTrace(s);
|
||||
}
|
||||
|
||||
protected abstract void printStackTrace(WrappedPrintStream stream);
|
||||
|
||||
public static abstract class WrappedPrintStream
|
||||
{
|
||||
public abstract void println(String line);
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.common;
|
||||
|
||||
import net.minecraft.crash.ICrashReportDetail;
|
||||
|
||||
public interface ICrashCallable extends ICrashReportDetail<String>
|
||||
{
|
||||
String getLabel();
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.common;
|
||||
import net.minecraftforge.fml.common.EnhancedRuntimeException.WrappedPrintStream;
|
||||
|
||||
|
||||
public class LoaderException extends EnhancedRuntimeException
|
||||
{
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = -5675297950958861378L;
|
||||
|
||||
public LoaderException(Throwable wrapped)
|
||||
{
|
||||
super(wrapped);
|
||||
}
|
||||
|
||||
public LoaderException()
|
||||
{
|
||||
}
|
||||
public LoaderException(String message)
|
||||
{
|
||||
super(message);
|
||||
}
|
||||
public LoaderException(String message, Throwable cause)
|
||||
{
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
@Override protected void printStackTrace(WrappedPrintStream stream){}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.common;
|
||||
|
||||
/**
|
||||
* Prevent LoaderException from adding its own stack trace to the wrapped throwable's stack trace.
|
||||
*/
|
||||
public class LoaderExceptionModCrash extends LoaderException
|
||||
{
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public LoaderExceptionModCrash(String message, Throwable cause)
|
||||
{
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized Throwable fillInStackTrace()
|
||||
{
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.common;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import net.minecraftforge.api.distmarker.Dist;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.fml.event.lifecycle.ModLifecycleEvent;
|
||||
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
|
||||
|
||||
/**
|
||||
* This defines a Mod to FML.
|
||||
* Any class found with this annotation applied will be loaded as a Mod. The instance that is loaded will
|
||||
* represent the mod to other Mods in the system. It will be sent various subclasses of {@link ModLifecycleEvent}
|
||||
* at pre-defined times during the loading of the game.
|
||||
*/
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.TYPE)
|
||||
public @interface Mod
|
||||
{
|
||||
/**
|
||||
* The unique mod identifier for this mod.
|
||||
* <b>Required to be lowercased in the english locale for compatibility. Will be truncated to 64 characters long.</b>
|
||||
*
|
||||
* This will be used to identify your mod for third parties (other mods), it will be used to identify your mod for registries such as block and item registries.
|
||||
* By default, you will have a resource domain that matches the modid. All these uses require that constraints are imposed on the format of the modid.
|
||||
*/
|
||||
String value();
|
||||
|
||||
/**
|
||||
* Annotate a class which will be subscribed to an Event Bus at mod construction time.
|
||||
* Defaults to subscribing the current modid to the {@link MinecraftForge#EVENT_BUS}
|
||||
* on both sides.
|
||||
*
|
||||
* @see Bus
|
||||
*/
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.TYPE)
|
||||
@interface EventBusSubscriber {
|
||||
/**
|
||||
* Specify targets to load this event subscriber on. Can be used to avoid loading Client specific events
|
||||
* on a dedicated server, for example.
|
||||
*
|
||||
* @return an array of Dist to load this event subscriber on
|
||||
*/
|
||||
Dist[] value() default { Dist.CLIENT, Dist.DEDICATED_SERVER };
|
||||
|
||||
/**
|
||||
* Optional value, only necessary if this annotation is not on the same class that has a @Mod annotation.
|
||||
* Needed to prevent early classloading of classes not owned by your mod.
|
||||
* @return a modid
|
||||
*/
|
||||
String modid() default "";
|
||||
|
||||
/**
|
||||
* Specify an alternative bus to listen to
|
||||
*
|
||||
* @return the bus you wish to listen to
|
||||
*/
|
||||
Bus bus() default Bus.FORGE;
|
||||
|
||||
enum Bus {
|
||||
/**
|
||||
* The main Forge Event Bus.
|
||||
* @see MinecraftForge#EVENT_BUS
|
||||
*/
|
||||
FORGE(()-> MinecraftForge.EVENT_BUS),
|
||||
/**
|
||||
* The mod specific Event bus.
|
||||
* @see FMLJavaModLoadingContext#getModEventBus()
|
||||
*/
|
||||
MOD(()-> FMLJavaModLoadingContext.get().getModEventBus());
|
||||
|
||||
private final Supplier<IEventBus> busSupplier;
|
||||
|
||||
Bus(final Supplier<IEventBus> eventBusSupplier) {
|
||||
this.busSupplier = eventBusSupplier;
|
||||
}
|
||||
|
||||
public Supplier<IEventBus> bus() {
|
||||
return busSupplier;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,277 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.common;
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.StringJoiner;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
import cpw.mods.modlauncher.api.INameMappingService;
|
||||
import net.minecraftforge.fml.loading.FMLLoader;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.apache.logging.log4j.Marker;
|
||||
import org.apache.logging.log4j.MarkerManager;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
|
||||
/**
|
||||
* Some reflection helper code.
|
||||
* This may not work properly in Java 9 with its new, more restrictive, reflection management.
|
||||
* As such, if issues are encountered, please report them and we can see what we can do to expand
|
||||
* the compatibility.
|
||||
*
|
||||
* In other cases, AccessTransformers may be used.
|
||||
*
|
||||
* All field and method names should be passed in as SRG names, and this will automatically resolve if MCP mappings are detected.
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings({"serial", "unchecked", "unused", "WeakerAccess"})
|
||||
public class ObfuscationReflectionHelper
|
||||
{
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
private static final Marker REFLECTION = MarkerManager.getMarker("REFLECTION");
|
||||
|
||||
/**
|
||||
* Remaps a name using the SRG naming function
|
||||
* @param domain The {@link INameMappingService.Domain} to use to remap the name.
|
||||
* @param name The name to try and remap.
|
||||
* @return The remapped name, or the original name if it couldn't be remapped.
|
||||
*/
|
||||
@Nonnull
|
||||
public static String remapName(INameMappingService.Domain domain, String name)
|
||||
{
|
||||
return FMLLoader.getNameFunction("srg").map(f->f.apply(domain, name)).orElse(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value a field with the specified name in the given class.
|
||||
* Note: For performance, use {@link #findField(Class, String)} if you are getting the value more than once.
|
||||
* <p>
|
||||
* Throws an exception if the field is not found or the value of the field cannot be gotten.
|
||||
*
|
||||
* @param classToAccess The class to find the field on.
|
||||
* @param instance The instance of the {@code classToAccess}.
|
||||
* @param fieldName The SRG (unmapped) name of the field to find (e.g. "field_181725_a").
|
||||
* @param <T> The type of the value.
|
||||
* @param <E> The type of the {@code classToAccess}.
|
||||
* @return The value of the field with the specified name in the {@code classToAccess}.
|
||||
* @throws UnableToAccessFieldException If there was a problem getting the field.
|
||||
* @throws UnableToAccessFieldException If there was a problem getting the value.
|
||||
*/
|
||||
@Nullable
|
||||
public static <T, E> T getPrivateValue(Class<? super E> classToAccess, E instance, String fieldName)
|
||||
{
|
||||
try
|
||||
{
|
||||
return (T) findField(classToAccess, fieldName).get(instance);
|
||||
}
|
||||
catch (UnableToFindFieldException e)
|
||||
{
|
||||
LOGGER.error(REFLECTION,"Unable to locate field {} ({}) on type {}", fieldName, remapName(INameMappingService.Domain.FIELD, fieldName), classToAccess.getName(), e);
|
||||
throw e;
|
||||
}
|
||||
catch (IllegalAccessException e)
|
||||
{
|
||||
LOGGER.error(REFLECTION,"Unable to access field {} ({}) on type {}", fieldName, remapName(INameMappingService.Domain.FIELD, fieldName), classToAccess.getName(), e);
|
||||
throw new UnableToAccessFieldException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value a field with the specified name in the given class.
|
||||
* Note: For performance, use {@link #findField(Class, String)} if you are setting the value more than once.
|
||||
* <p>
|
||||
* Throws an exception if the field is not found or the value of the field cannot be set.
|
||||
*
|
||||
* @param classToAccess The class to find the field on.
|
||||
* @param instance The instance of the {@code classToAccess}.
|
||||
* @param value The new value for the field
|
||||
* @param fieldName The name of the field in the {@code classToAccess}.
|
||||
* @param <T> The type of the value.
|
||||
* @param <E> The type of the {@code classToAccess}.
|
||||
* @throws UnableToFindFieldException If there was a problem getting the field.
|
||||
* @throws UnableToAccessFieldException If there was a problem setting the value of the field.
|
||||
*/
|
||||
public static <T, E> void setPrivateValue(@Nonnull final Class<? super T> classToAccess, @Nonnull final T instance, @Nullable final E value, @Nonnull final String fieldName)
|
||||
{
|
||||
try
|
||||
{
|
||||
findField(classToAccess, fieldName).set(instance, value);
|
||||
}
|
||||
catch (UnableToFindFieldException e)
|
||||
{
|
||||
LOGGER.error("Unable to locate any field {} on type {}", fieldName, classToAccess.getName(), e);
|
||||
throw e;
|
||||
}
|
||||
catch (IllegalAccessException e)
|
||||
{
|
||||
LOGGER.error("Unable to set any field {} on type {}", fieldName, classToAccess.getName(), e);
|
||||
throw new UnableToAccessFieldException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds a method with the specified name and parameters in the given class and makes it accessible.
|
||||
* Note: For performance, store the returned value and avoid calling this repeatedly.
|
||||
* <p>
|
||||
* Throws an exception if the method is not found.
|
||||
*
|
||||
* @param clazz The class to find the method on.
|
||||
* @param methodName The SRG (unmapped) name of the method to find (e.g. "func_12820_D").
|
||||
* @param parameterTypes The parameter types of the method to find.
|
||||
* @return The method with the specified name and parameters in the given class.
|
||||
* @throws NullPointerException If {@code clazz} is null.
|
||||
* @throws NullPointerException If {@code methodName} is null.
|
||||
* @throws IllegalArgumentException If {@code methodName} is empty.
|
||||
* @throws NullPointerException If {@code parameterTypes} is null.
|
||||
* @throws UnableToFindMethodException If the method could not be found.
|
||||
*/
|
||||
@Nonnull
|
||||
public static Method findMethod(@Nonnull final Class<?> clazz, @Nonnull final String methodName, @Nonnull final Class<?>... parameterTypes)
|
||||
{
|
||||
Preconditions.checkNotNull(clazz, "Class to find method on cannot be null.");
|
||||
Preconditions.checkNotNull(methodName, "Name of method to find cannot be null.");
|
||||
Preconditions.checkArgument(!methodName.isEmpty(), "Name of method to find cannot be empty.");
|
||||
Preconditions.checkNotNull(parameterTypes, "Parameter types of method to find cannot be null.");
|
||||
|
||||
try
|
||||
{
|
||||
Method m = clazz.getDeclaredMethod(remapName(INameMappingService.Domain.METHOD, methodName), parameterTypes);
|
||||
m.setAccessible(true);
|
||||
return m;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
throw new UnableToFindMethodException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds a constructor with the specified parameter types in the given class and makes it accessible.
|
||||
* Note: For performance, store the returned value and avoid calling this repeatedly.
|
||||
* <p>
|
||||
* Throws an exception if the constructor is not found.
|
||||
*
|
||||
* @param clazz The class to find the constructor in.
|
||||
* @param parameterTypes The parameter types of the constructor.
|
||||
* @param <T> The type.
|
||||
* @return The constructor with the specified parameters in the given class.
|
||||
* @throws NullPointerException If {@code clazz} is null.
|
||||
* @throws NullPointerException If {@code parameterTypes} is null.
|
||||
* @throws UnknownConstructorException If the constructor could not be found.
|
||||
*/
|
||||
@Nonnull
|
||||
public static <T> Constructor<T> findConstructor(@Nonnull final Class<T> clazz, @Nonnull final Class<?>... parameterTypes)
|
||||
{
|
||||
Preconditions.checkNotNull(clazz, "Class to find constructor on cannot be null.");
|
||||
Preconditions.checkNotNull(parameterTypes, "Parameter types of constructor to find cannot be null.");
|
||||
|
||||
try
|
||||
{
|
||||
Constructor<T> constructor = clazz.getDeclaredConstructor(parameterTypes);
|
||||
constructor.setAccessible(true);
|
||||
return constructor;
|
||||
}
|
||||
catch (final NoSuchMethodException e)
|
||||
{
|
||||
final StringBuilder desc = new StringBuilder();
|
||||
desc.append(clazz.getSimpleName());
|
||||
|
||||
StringJoiner joiner = new StringJoiner(", ", "(", ")");
|
||||
for (Class<?> type : parameterTypes)
|
||||
{
|
||||
joiner.add(type.getSimpleName());
|
||||
}
|
||||
desc.append(joiner);
|
||||
|
||||
throw new UnknownConstructorException("Could not find constructor '" + desc.toString() + "' in " + clazz);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds a field with the specified name in the given class and makes it accessible.
|
||||
* Note: For performance, store the returned value and avoid calling this repeatedly.
|
||||
* <p>
|
||||
* Throws an exception if the field is not found.
|
||||
*
|
||||
* @param clazz The class to find the field on.
|
||||
* @param fieldName The SRG (unmapped) name of the field to find (e.g. "field_181725_a").
|
||||
* @param <T> The type.
|
||||
* @return The constructor with the specified parameters in the given class.
|
||||
* @throws NullPointerException If {@code clazz} is null.
|
||||
* @throws NullPointerException If {@code fieldName} is null.
|
||||
* @throws IllegalArgumentException If {@code fieldName} is empty.
|
||||
* @throws UnableToFindFieldException If the field could not be found.
|
||||
*/
|
||||
@Nonnull
|
||||
public static <T> Field findField(@Nonnull final Class<? super T> clazz, @Nonnull final String fieldName)
|
||||
{
|
||||
Preconditions.checkNotNull(clazz, "Class to find field on cannot be null.");
|
||||
Preconditions.checkNotNull(fieldName, "Name of field to find cannot be null.");
|
||||
Preconditions.checkArgument(!fieldName.isEmpty(), "Name of field to find cannot be empty.");
|
||||
|
||||
try
|
||||
{
|
||||
Field f = clazz.getDeclaredField(remapName(INameMappingService.Domain.FIELD, fieldName));
|
||||
f.setAccessible(true);
|
||||
return f;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
throw new UnableToFindFieldException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static class UnableToAccessFieldException extends RuntimeException
|
||||
{
|
||||
private UnableToAccessFieldException(Exception e)
|
||||
{
|
||||
super(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static class UnableToFindFieldException extends RuntimeException
|
||||
{
|
||||
private UnableToFindFieldException(Exception e)
|
||||
{
|
||||
super(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static class UnableToFindMethodException extends RuntimeException
|
||||
{
|
||||
public UnableToFindMethodException(Throwable failed)
|
||||
{
|
||||
super(failed);
|
||||
}
|
||||
}
|
||||
|
||||
public static class UnknownConstructorException extends RuntimeException
|
||||
{
|
||||
public UnknownConstructorException(final String message)
|
||||
{
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.common.network;
|
||||
|
||||
import io.netty.buffer.ByteBuf;
|
||||
|
||||
/**
|
||||
* Utilities for interacting with {@link ByteBuf}.
|
||||
* @author cpw
|
||||
*
|
||||
*/
|
||||
public class ByteBufUtils {
|
||||
|
||||
public static String getContentDump(ByteBuf buffer)
|
||||
{
|
||||
int currentLength = buffer.readableBytes();
|
||||
StringBuffer returnString = new StringBuffer((currentLength * 3) + // The
|
||||
// hex
|
||||
(currentLength) + // The ascii
|
||||
(currentLength / 4) + // The tabs/\n's
|
||||
30); // The text
|
||||
|
||||
// returnString.append("Buffer contents:\n");
|
||||
int i, j; // Loop variables
|
||||
for (i = 0; i < currentLength; i++)
|
||||
{
|
||||
if ((i != 0) && (i % 16 == 0))
|
||||
{
|
||||
// If it's a multiple of 16 and i isn't null, show the ascii
|
||||
returnString.append('\t');
|
||||
for (j = i - 16; j < i; j++)
|
||||
{
|
||||
if (buffer.getByte(j) < 0x20 || buffer.getByte(j) > 0x7F)
|
||||
returnString.append('.');
|
||||
else
|
||||
returnString.append((char) buffer.getByte(j));
|
||||
}
|
||||
// Add a linefeed after the string
|
||||
returnString.append("\n");
|
||||
}
|
||||
|
||||
returnString.append(Integer.toString((buffer.getByte(i) & 0xF0) >> 4, 16) + Integer.toString((buffer.getByte(i) & 0x0F) >> 0, 16));
|
||||
returnString.append(' ');
|
||||
}
|
||||
|
||||
// Add padding spaces if it's not a multiple of 16
|
||||
if (i != 0 && i % 16 != 0)
|
||||
{
|
||||
for (j = 0; j < ((16 - (i % 16)) * 3); j++)
|
||||
{
|
||||
returnString.append(' ');
|
||||
}
|
||||
}
|
||||
// Add the tab for alignment
|
||||
returnString.append('\t');
|
||||
|
||||
// Add final characters at right, after padding
|
||||
|
||||
// If it was at the end of a line, print out the full line
|
||||
if (i > 0 && (i % 16) == 0)
|
||||
{
|
||||
j = i - 16;
|
||||
} else
|
||||
{
|
||||
j = (i - (i % 16));
|
||||
}
|
||||
|
||||
for (; i >= 0 && j < i; j++)
|
||||
{
|
||||
if (buffer.getByte(j) < 0x20 || buffer.getByte(j) > 0x7F)
|
||||
returnString.append('.');
|
||||
else
|
||||
returnString.append((char) buffer.getByte(j));
|
||||
}
|
||||
|
||||
// Finally, tidy it all up with a newline
|
||||
returnString.append('\n');
|
||||
returnString.append("Length: " + currentLength);
|
||||
|
||||
return returnString.toString();
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.common.network;
|
||||
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelOutboundHandlerAdapter;
|
||||
import io.netty.channel.ChannelPipeline;
|
||||
import io.netty.channel.ChannelPromise;
|
||||
import io.netty.channel.SimpleChannelInboundHandler;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
import net.minecraft.network.PacketDirection;
|
||||
import net.minecraft.network.NettyVarint21FrameDecoder;
|
||||
import net.minecraft.network.NettyVarint21FrameEncoder;
|
||||
import net.minecraft.network.NetworkManager;
|
||||
import net.minecraft.network.IPacket;
|
||||
import net.minecraft.network.PacketBuffer;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
public class PacketLoggingHandler
|
||||
{
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
public static void register(NetworkManager manager)
|
||||
{
|
||||
ChannelPipeline pipeline = manager.channel().pipeline();
|
||||
final PacketDirection direction = manager.getDirection();
|
||||
if (manager.isMemoryConnection())
|
||||
{
|
||||
pipeline.addBefore("packet_handler", "splitter", new SimpleChannelInboundHandler<IPacket<?>>()
|
||||
{
|
||||
String prefix = (direction == PacketDirection.SERVERBOUND ? "SERVER: C->S" : "CLIENT: S->C");
|
||||
@Override
|
||||
protected void channelRead0(ChannelHandlerContext ctx, IPacket<?> msg) throws Exception
|
||||
{
|
||||
PacketBuffer buf = new PacketBuffer(Unpooled.buffer());
|
||||
msg.write(buf);
|
||||
LOGGER.debug("{} {}:\n{}", prefix, msg.getClass().getSimpleName(), ByteBufUtils.getContentDump(buf));
|
||||
ctx.fireChannelRead(msg);
|
||||
}
|
||||
});
|
||||
pipeline.addBefore("splitter", "prepender", new ChannelOutboundHandlerAdapter()
|
||||
{
|
||||
String prefix = (direction == PacketDirection.SERVERBOUND ? "SERVER: S->C" : "CLIENT: C->S");
|
||||
@Override
|
||||
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception
|
||||
{
|
||||
if (msg instanceof IPacket<?>)
|
||||
{
|
||||
PacketBuffer buf = new PacketBuffer(Unpooled.buffer());
|
||||
((IPacket<?>)msg).write(buf);
|
||||
LOGGER.debug("{} {}:\n{}", prefix, msg.getClass().getSimpleName(), ByteBufUtils.getContentDump(buf));
|
||||
}
|
||||
ctx.write(msg, promise);
|
||||
}
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
pipeline.replace("splitter", "splitter", new NettyVarint21FrameDecoder()
|
||||
{
|
||||
String prefix = (direction == PacketDirection.SERVERBOUND ? "SERVER: C->S" : "CLIENT: S->C");
|
||||
@Override
|
||||
protected void decode(ChannelHandlerContext context, ByteBuf input, List<Object> output) throws Exception
|
||||
{
|
||||
super.decode(context, input, output);
|
||||
Iterator<Object> itr = output.iterator();
|
||||
while (itr.hasNext())
|
||||
{
|
||||
ByteBuf pkt = (ByteBuf)itr.next();
|
||||
pkt.markReaderIndex();
|
||||
LOGGER.debug("{}:\n{}", prefix, ByteBufUtils.getContentDump(pkt));
|
||||
pkt.resetReaderIndex();
|
||||
}
|
||||
}
|
||||
});
|
||||
pipeline.replace("prepender", "prepender", new NettyVarint21FrameEncoder()
|
||||
{
|
||||
String prefix = (direction == PacketDirection.SERVERBOUND ? "SERVER: S->C" : "CLIENT: C->S");
|
||||
@Override
|
||||
protected void encode(ChannelHandlerContext context, ByteBuf input, ByteBuf output) throws Exception
|
||||
{
|
||||
input.markReaderIndex();
|
||||
LOGGER.debug("{}:\n{}", prefix, ByteBufUtils.getContentDump(input));
|
||||
input.resetReaderIndex();
|
||||
super.encode(context, input, output);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.common.registry;
|
||||
|
||||
import net.minecraftforge.registries.IForgeRegistry;
|
||||
import net.minecraftforge.registries.IForgeRegistryEntry;
|
||||
import net.minecraftforge.registries.RegistryManager;
|
||||
|
||||
|
||||
public class GameRegistry
|
||||
{
|
||||
/**
|
||||
* Retrieves the registry associated with this super class type.
|
||||
* If the return is non-null it is HIGHLY recommended that modders cache this
|
||||
* value as the return will never change for a given type in a single run of Minecraft once set.
|
||||
*
|
||||
* @param registryType The base class of items in this registry.
|
||||
* @return The registry, Null if none is registered.
|
||||
*/
|
||||
public static <K extends IForgeRegistryEntry<K>> IForgeRegistry<K> findRegistry(Class<K> registryType)
|
||||
{
|
||||
return RegistryManager.ACTIVE.getRegistry(registryType);
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.common.registry;
|
||||
|
||||
import net.minecraft.network.PacketBuffer;
|
||||
|
||||
/**
|
||||
* A interface for Entities that need extra information to be communicated
|
||||
* between the server and client when they are spawned.
|
||||
*/
|
||||
public interface IEntityAdditionalSpawnData
|
||||
{
|
||||
/**
|
||||
* Called by the server when constructing the spawn packet.
|
||||
* Data should be added to the provided stream.
|
||||
*
|
||||
* @param buffer The packet data stream
|
||||
*/
|
||||
void writeSpawnData(PacketBuffer buffer);
|
||||
|
||||
/**
|
||||
* Called by the client when it receives a Entity spawn packet.
|
||||
* Data should be read out of the stream in the same way as it was written.
|
||||
*
|
||||
* @param additionalData The packet data stream
|
||||
*/
|
||||
void readSpawnData(PacketBuffer additionalData);
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.common.thread;
|
||||
|
||||
import net.minecraftforge.fml.LogicalSide;
|
||||
|
||||
public class EffectiveSide
|
||||
{
|
||||
public static LogicalSide get() {
|
||||
final ThreadGroup group = Thread.currentThread().getThreadGroup();
|
||||
return group instanceof SidedThreadGroup ? ((SidedThreadGroup) group).getSide() : LogicalSide.CLIENT;
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.common.thread;
|
||||
|
||||
import net.minecraftforge.fml.LogicalSide;
|
||||
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
|
||||
/**
|
||||
* A thread group and factory combination which belongs to a {@link LogicalSide}.
|
||||
*/
|
||||
public final class SidedThreadGroup extends ThreadGroup implements ThreadFactory
|
||||
{
|
||||
private final LogicalSide side;
|
||||
|
||||
SidedThreadGroup(final LogicalSide side)
|
||||
{
|
||||
super(side.name());
|
||||
this.side = side;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the side this sided thread group belongs to.
|
||||
*
|
||||
* @return the side
|
||||
*/
|
||||
public LogicalSide getSide()
|
||||
{
|
||||
return this.side;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Thread newThread(@Nonnull final Runnable runnable)
|
||||
{
|
||||
return new Thread(this, runnable);
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.common.thread;
|
||||
|
||||
import net.minecraftforge.fml.LogicalSide;
|
||||
|
||||
public final class SidedThreadGroups
|
||||
{
|
||||
public static final SidedThreadGroup CLIENT = new SidedThreadGroup(LogicalSide.CLIENT);
|
||||
public static final SidedThreadGroup SERVER = new SidedThreadGroup(LogicalSide.SERVER);
|
||||
|
||||
private SidedThreadGroups() {
|
||||
}
|
||||
}
|
||||
@@ -1,172 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.config;
|
||||
|
||||
import com.electronwill.nightconfig.core.ConfigFormat;
|
||||
import com.electronwill.nightconfig.core.file.CommentedFileConfig;
|
||||
import com.electronwill.nightconfig.core.file.FileWatcher;
|
||||
import com.electronwill.nightconfig.core.io.ParsingException;
|
||||
import com.electronwill.nightconfig.core.io.WritingMode;
|
||||
import net.minecraftforge.fml.loading.FMLConfig;
|
||||
import net.minecraftforge.fml.loading.FMLPaths;
|
||||
import org.apache.commons.io.FilenameUtils;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.function.Function;
|
||||
|
||||
import static net.minecraftforge.fml.config.ConfigTracker.CONFIG;
|
||||
|
||||
public class ConfigFileTypeHandler {
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
static ConfigFileTypeHandler TOML = new ConfigFileTypeHandler();
|
||||
private static final Path defaultConfigPath = FMLPaths.GAMEDIR.get().resolve(FMLConfig.defaultConfigPath());
|
||||
|
||||
public Function<ModConfig, CommentedFileConfig> reader(Path configBasePath) {
|
||||
return (c) -> {
|
||||
final Path configPath = configBasePath.resolve(c.getFileName());
|
||||
final CommentedFileConfig configData = CommentedFileConfig.builder(configPath).sync().
|
||||
preserveInsertionOrder().
|
||||
autosave().
|
||||
onFileNotFound((newfile, configFormat)-> setupConfigFile(c, newfile, configFormat)).
|
||||
writingMode(WritingMode.REPLACE).
|
||||
build();
|
||||
LOGGER.debug(CONFIG, "Built TOML config for {}", configPath.toString());
|
||||
try
|
||||
{
|
||||
configData.load();
|
||||
}
|
||||
catch (ParsingException ex)
|
||||
{
|
||||
throw new ConfigLoadingException(c, ex);
|
||||
}
|
||||
LOGGER.debug(CONFIG, "Loaded TOML config file {}", configPath.toString());
|
||||
try {
|
||||
FileWatcher.defaultInstance().addWatch(configPath, new ConfigWatcher(c, configData, Thread.currentThread().getContextClassLoader()));
|
||||
LOGGER.debug(CONFIG, "Watching TOML config file {} for changes", configPath.toString());
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Couldn't watch config file", e);
|
||||
}
|
||||
return configData;
|
||||
};
|
||||
}
|
||||
|
||||
public void unload(Path configBasePath, ModConfig config) {
|
||||
Path configPath = configBasePath.resolve(config.getFileName());
|
||||
try {
|
||||
FileWatcher.defaultInstance().removeWatch(configBasePath.resolve(config.getFileName()));
|
||||
} catch (RuntimeException e) {
|
||||
LOGGER.error("Failed to remove config {} from tracker!", configPath.toString(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean setupConfigFile(final ModConfig modConfig, final Path file, final ConfigFormat<?> conf) throws IOException {
|
||||
Path p = defaultConfigPath.resolve(modConfig.getFileName());
|
||||
if (Files.exists(p)) {
|
||||
LOGGER.info(CONFIG, "Loading default config file from path {}", p);
|
||||
Files.copy(p, file);
|
||||
} else {
|
||||
Files.createFile(file);
|
||||
conf.initEmptyFile(file);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void backUpConfig(final CommentedFileConfig commentedFileConfig)
|
||||
{
|
||||
backUpConfig(commentedFileConfig, 5); //TODO: Think of a way for mods to set their own preference (include a sanity check as well, no disk stuffing)
|
||||
}
|
||||
|
||||
public static void backUpConfig(final CommentedFileConfig commentedFileConfig, final int maxBackups)
|
||||
{
|
||||
Path bakFileLocation = commentedFileConfig.getNioPath().getParent();
|
||||
String bakFileName = FilenameUtils.removeExtension(commentedFileConfig.getFile().getName());
|
||||
String bakFileExtension = FilenameUtils.getExtension(commentedFileConfig.getFile().getName()) + ".bak";
|
||||
Path bakFile = bakFileLocation.resolve(bakFileName + "-1" + "." + bakFileExtension);
|
||||
try
|
||||
{
|
||||
for(int i = maxBackups; i > 0; i--)
|
||||
{
|
||||
Path oldBak = bakFileLocation.resolve(bakFileName + "-" + i + "." + bakFileExtension);
|
||||
if(Files.exists(oldBak))
|
||||
{
|
||||
if(i >= maxBackups)
|
||||
Files.delete(oldBak);
|
||||
else
|
||||
Files.move(oldBak, bakFileLocation.resolve(bakFileName + "-" + (i + 1) + "." + bakFileExtension));
|
||||
}
|
||||
}
|
||||
Files.copy(commentedFileConfig.getNioPath(), bakFile);
|
||||
}
|
||||
catch (IOException exception)
|
||||
{
|
||||
LOGGER.warn(CONFIG, "Failed to back up config file {}", commentedFileConfig.getNioPath(), exception);
|
||||
}
|
||||
}
|
||||
|
||||
private static class ConfigWatcher implements Runnable {
|
||||
private final ModConfig modConfig;
|
||||
private final CommentedFileConfig commentedFileConfig;
|
||||
private final ClassLoader realClassLoader;
|
||||
|
||||
ConfigWatcher(final ModConfig modConfig, final CommentedFileConfig commentedFileConfig, final ClassLoader classLoader) {
|
||||
this.modConfig = modConfig;
|
||||
this.commentedFileConfig = commentedFileConfig;
|
||||
this.realClassLoader = classLoader;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
// Force the regular classloader onto the special thread
|
||||
Thread.currentThread().setContextClassLoader(realClassLoader);
|
||||
if (!this.modConfig.getSpec().isCorrecting()) {
|
||||
try
|
||||
{
|
||||
this.commentedFileConfig.load();
|
||||
if(!this.modConfig.getSpec().isCorrect(commentedFileConfig))
|
||||
{
|
||||
LOGGER.warn(CONFIG, "Configuration file {} is not correct. Correcting", commentedFileConfig.getFile().getAbsolutePath());
|
||||
ConfigFileTypeHandler.backUpConfig(commentedFileConfig);
|
||||
this.modConfig.getSpec().correct(commentedFileConfig);
|
||||
commentedFileConfig.save();
|
||||
}
|
||||
}
|
||||
catch (ParsingException ex)
|
||||
{
|
||||
throw new ConfigLoadingException(modConfig, ex);
|
||||
}
|
||||
LOGGER.debug(CONFIG, "Config file {} changed, sending notifies", this.modConfig.getFileName());
|
||||
this.modConfig.getSpec().afterReload();
|
||||
this.modConfig.fireEvent(new ModConfig.Reloading(this.modConfig));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class ConfigLoadingException extends RuntimeException
|
||||
{
|
||||
public ConfigLoadingException(ModConfig config, Exception cause)
|
||||
{
|
||||
super("Failed loading config file " + config.getFileName() + " of type " + config.getType() + " for modid " + config.getModId(), cause);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,141 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.config;
|
||||
|
||||
import com.electronwill.nightconfig.core.CommentedConfig;
|
||||
import com.electronwill.nightconfig.core.file.CommentedFileConfig;
|
||||
import com.electronwill.nightconfig.toml.TomlFormat;
|
||||
import it.unimi.dsi.fastutil.bytes.Byte2ByteOpenCustomHashMap;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraftforge.fml.network.FMLHandshakeMessages;
|
||||
import net.minecraftforge.fml.network.NetworkEvent;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.apache.logging.log4j.Marker;
|
||||
import org.apache.logging.log4j.MarkerManager;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Collections;
|
||||
import java.util.EnumMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static cpw.mods.modlauncher.api.LamdbaExceptionUtils.rethrowFunction;
|
||||
|
||||
public class ConfigTracker {
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
static final Marker CONFIG = MarkerManager.getMarker("CONFIG");
|
||||
public static final ConfigTracker INSTANCE = new ConfigTracker();
|
||||
private final ConcurrentHashMap<String, ModConfig> fileMap;
|
||||
private final EnumMap<ModConfig.Type, Set<ModConfig>> configSets;
|
||||
private ConcurrentHashMap<String, Map<ModConfig.Type, ModConfig>> configsByMod;
|
||||
|
||||
private ConfigTracker() {
|
||||
this.fileMap = new ConcurrentHashMap<>();
|
||||
this.configSets = new EnumMap<>(ModConfig.Type.class);
|
||||
this.configsByMod = new ConcurrentHashMap<>();
|
||||
this.configSets.put(ModConfig.Type.CLIENT, Collections.synchronizedSet(new LinkedHashSet<>()));
|
||||
this.configSets.put(ModConfig.Type.COMMON, Collections.synchronizedSet(new LinkedHashSet<>()));
|
||||
// this.configSets.put(ModConfig.Type.PLAYER, new ConcurrentSkipListSet<>());
|
||||
this.configSets.put(ModConfig.Type.SERVER, Collections.synchronizedSet(new LinkedHashSet<>()));
|
||||
}
|
||||
|
||||
void trackConfig(final ModConfig config) {
|
||||
if (this.fileMap.containsKey(config.getFileName())) {
|
||||
LOGGER.error(CONFIG,"Detected config file conflict {} between {} and {}", config.getFileName(), this.fileMap.get(config.getFileName()).getModId(), config.getModId());
|
||||
throw new RuntimeException("Config conflict detected!");
|
||||
}
|
||||
this.fileMap.put(config.getFileName(), config);
|
||||
this.configSets.get(config.getType()).add(config);
|
||||
this.configsByMod.computeIfAbsent(config.getModId(), (k)->new EnumMap<>(ModConfig.Type.class)).put(config.getType(), config);
|
||||
LOGGER.debug(CONFIG, "Config file {} for {} tracking", config.getFileName(), config.getModId());
|
||||
}
|
||||
|
||||
public void loadConfigs(ModConfig.Type type, Path configBasePath) {
|
||||
LOGGER.debug(CONFIG, "Loading configs type {}", type);
|
||||
this.configSets.get(type).forEach(config -> openConfig(config, configBasePath));
|
||||
}
|
||||
|
||||
public void unloadConfigs(ModConfig.Type type, Path configBasePath) {
|
||||
LOGGER.debug(CONFIG, "Unloading configs type {}", type);
|
||||
this.configSets.get(type).forEach(config -> closeConfig(config, configBasePath));
|
||||
}
|
||||
|
||||
public List<Pair<String, FMLHandshakeMessages.S2CConfigData>> syncConfigs(boolean isLocal) {
|
||||
final Map<String, byte[]> configData = configSets.get(ModConfig.Type.SERVER).stream().collect(Collectors.toMap(ModConfig::getFileName, mc -> { //TODO: Test cpw's LambdaExceptionUtils on Oracle javac.
|
||||
try {
|
||||
return Files.readAllBytes(mc.getFullPath());
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}));
|
||||
return configData.entrySet().stream().map(e->Pair.of("Config "+e.getKey(), new FMLHandshakeMessages.S2CConfigData(e.getKey(), e.getValue()))).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private void openConfig(final ModConfig config, final Path configBasePath) {
|
||||
LOGGER.trace(CONFIG, "Loading config file type {} at {} for {}", config.getType(), config.getFileName(), config.getModId());
|
||||
final CommentedFileConfig configData = config.getHandler().reader(configBasePath).apply(config);
|
||||
config.setConfigData(configData);
|
||||
config.fireEvent(new ModConfig.Loading(config));
|
||||
config.save();
|
||||
}
|
||||
|
||||
private void closeConfig(final ModConfig config, final Path configBasePath) {
|
||||
if (config.getConfigData() != null) {
|
||||
LOGGER.trace(CONFIG, "Closing config file type {} at {} for {}", config.getType(), config.getFileName(), config.getModId());
|
||||
config.save();
|
||||
config.getHandler().unload(configBasePath, config);
|
||||
config.setConfigData(null);
|
||||
}
|
||||
}
|
||||
|
||||
public void receiveSyncedConfig(final FMLHandshakeMessages.S2CConfigData s2CConfigData, final Supplier<NetworkEvent.Context> contextSupplier) {
|
||||
if (!Minecraft.getInstance().isLocalServer()) {
|
||||
Optional.ofNullable(fileMap.get(s2CConfigData.getFileName())).ifPresent(mc-> {
|
||||
mc.setConfigData(TomlFormat.instance().createParser().parse(new ByteArrayInputStream(s2CConfigData.getBytes())));
|
||||
mc.fireEvent(new ModConfig.Reloading(mc));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public void loadDefaultServerConfigs() {
|
||||
configSets.get(ModConfig.Type.SERVER).forEach(modConfig -> {
|
||||
final CommentedConfig commentedConfig = CommentedConfig.inMemory();
|
||||
modConfig.getSpec().correct(commentedConfig);
|
||||
modConfig.setConfigData(commentedConfig);
|
||||
modConfig.fireEvent(new ModConfig.Loading(modConfig));
|
||||
});
|
||||
}
|
||||
|
||||
public String getConfigFileName(String modId, ModConfig.Type type) {
|
||||
return Optional.ofNullable(configsByMod.getOrDefault(modId, Collections.emptyMap()).getOrDefault(type, null)).
|
||||
map(ModConfig::getFullPath).map(Object::toString).orElse(null);
|
||||
}
|
||||
}
|
||||
@@ -1,160 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.config;
|
||||
|
||||
import com.electronwill.nightconfig.core.CommentedConfig;
|
||||
import com.electronwill.nightconfig.core.file.CommentedFileConfig;
|
||||
import net.minecraftforge.common.ForgeConfigSpec;
|
||||
import net.minecraftforge.eventbus.api.Event;
|
||||
import net.minecraftforge.fml.ModContainer;
|
||||
import net.minecraftforge.fml.event.lifecycle.IModBusEvent;
|
||||
import net.minecraftforge.fml.loading.StringUtils;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
public class ModConfig
|
||||
{
|
||||
private final Type type;
|
||||
private final ForgeConfigSpec spec;
|
||||
private final String fileName;
|
||||
private final ModContainer container;
|
||||
private final ConfigFileTypeHandler configHandler;
|
||||
private CommentedConfig configData;
|
||||
private Callable<Void> saveHandler;
|
||||
|
||||
public ModConfig(final Type type, final ForgeConfigSpec spec, final ModContainer container, final String fileName) {
|
||||
this.type = type;
|
||||
this.spec = spec;
|
||||
this.fileName = fileName;
|
||||
this.container = container;
|
||||
this.configHandler = ConfigFileTypeHandler.TOML;
|
||||
ConfigTracker.INSTANCE.trackConfig(this);
|
||||
}
|
||||
|
||||
public ModConfig(final Type type, final ForgeConfigSpec spec, final ModContainer activeContainer) {
|
||||
this(type, spec, activeContainer, defaultConfigName(type, activeContainer.getModId()));
|
||||
}
|
||||
|
||||
private static String defaultConfigName(Type type, String modId) {
|
||||
// config file name would be "forge-client.toml" and "forge-server.toml"
|
||||
return String.format("%s-%s.toml", modId, type.extension());
|
||||
}
|
||||
public Type getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public String getFileName() {
|
||||
return fileName;
|
||||
}
|
||||
|
||||
public ConfigFileTypeHandler getHandler() {
|
||||
return configHandler;
|
||||
}
|
||||
|
||||
public ForgeConfigSpec getSpec() {
|
||||
return spec;
|
||||
}
|
||||
|
||||
public String getModId() {
|
||||
return container.getModId();
|
||||
}
|
||||
|
||||
public CommentedConfig getConfigData() {
|
||||
return this.configData;
|
||||
}
|
||||
|
||||
void setConfigData(final CommentedConfig configData) {
|
||||
this.configData = configData;
|
||||
this.spec.setConfig(this.configData);
|
||||
}
|
||||
|
||||
void fireEvent(final ModConfigEvent configEvent) {
|
||||
this.container.dispatchConfigEvent(configEvent);
|
||||
}
|
||||
|
||||
public void save() {
|
||||
((CommentedFileConfig)this.configData).save();
|
||||
}
|
||||
|
||||
public Path getFullPath() {
|
||||
return ((CommentedFileConfig)this.configData).getNioPath();
|
||||
}
|
||||
|
||||
public enum Type {
|
||||
/**
|
||||
* Common mod config for configuration that needs to be loaded on both environments.
|
||||
* Loaded on both servers and clients.
|
||||
* Stored in the global config directory.
|
||||
* Not synced.
|
||||
* Suffix is "-common" by default.
|
||||
*/
|
||||
COMMON,
|
||||
/**
|
||||
* Client config is for configuration affecting the ONLY client state such as graphical options.
|
||||
* Only loaded on the client side.
|
||||
* Stored in the global config directory.
|
||||
* Not synced.
|
||||
* Suffix is "-client" by default.
|
||||
*/
|
||||
CLIENT,
|
||||
// /**
|
||||
// * Player type config is configuration that is associated with a player.
|
||||
// * Preferences around machine states, for example.
|
||||
// */
|
||||
// PLAYER,
|
||||
/**
|
||||
* Server type config is configuration that is associated with a server instance.
|
||||
* Only loaded during server startup.
|
||||
* Stored in a server/save specific "serverconfig" directory.
|
||||
* Synced to clients during connection.
|
||||
* Suffix is "-server" by default.
|
||||
*/
|
||||
SERVER;
|
||||
|
||||
public String extension() {
|
||||
return StringUtils.toLowerCase(name());
|
||||
}
|
||||
}
|
||||
|
||||
public static class ModConfigEvent extends Event implements IModBusEvent {
|
||||
private final ModConfig config;
|
||||
|
||||
ModConfigEvent(final ModConfig config) {
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
public ModConfig getConfig() {
|
||||
return config;
|
||||
}
|
||||
}
|
||||
|
||||
public static class Loading extends ModConfigEvent {
|
||||
Loading(final ModConfig config) {
|
||||
super(config);
|
||||
}
|
||||
}
|
||||
|
||||
public static class Reloading extends ModConfigEvent {
|
||||
Reloading(final ModConfig config) {
|
||||
super(config);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.event.lifecycle;
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraftforge.fml.ModContainer;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* This is the second of four commonly called events during mod lifecycle startup.
|
||||
*
|
||||
* Called before {@link InterModEnqueueEvent}
|
||||
* Called after {@link FMLCommonSetupEvent}
|
||||
*
|
||||
* Called on {@link net.minecraftforge.api.distmarker.Dist#CLIENT} - the game client.
|
||||
*
|
||||
* Alternative to {@link FMLDedicatedServerSetupEvent}.
|
||||
*
|
||||
* Do client only setup with this event, such as KeyBindings.
|
||||
*
|
||||
* This is a parallel dispatch event.
|
||||
*/
|
||||
public class FMLClientSetupEvent extends ParallelDispatchEvent
|
||||
{
|
||||
private final Supplier<Minecraft> minecraftSupplier;
|
||||
|
||||
public FMLClientSetupEvent(ModContainer container)
|
||||
{
|
||||
super(container);
|
||||
minecraftSupplier = Minecraft::getInstance;
|
||||
}
|
||||
|
||||
public Supplier<Minecraft> getMinecraftSupplier()
|
||||
{
|
||||
return minecraftSupplier;
|
||||
}
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.event.lifecycle;
|
||||
|
||||
import net.minecraftforge.fml.ModContainer;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* This is the first of four commonly called events during mod initialization.
|
||||
*
|
||||
* Called before {@link FMLClientSetupEvent} or {@link FMLDedicatedServerSetupEvent} during mod startup.
|
||||
*
|
||||
* Called after {@link net.minecraftforge.event.RegistryEvent.Register} events have been fired.
|
||||
*
|
||||
* Either register your listener using {@link net.minecraftforge.fml.AutomaticEventSubscriber} and
|
||||
* {@link net.minecraftforge.eventbus.api.SubscribeEvent} or
|
||||
* {@link net.minecraftforge.eventbus.api.IEventBus#addListener(Consumer)} in your constructor.
|
||||
*
|
||||
* Most non-specific mod setup will be performed here. Note that this is a parallel dispatched event - you cannot
|
||||
* interact with game state in this event.
|
||||
*
|
||||
* @see net.minecraftforge.fml.DeferredWorkQueue to enqueue work to run on the main game thread after this event has
|
||||
* completed dispatch
|
||||
*/
|
||||
public class FMLCommonSetupEvent extends ParallelDispatchEvent
|
||||
{
|
||||
public FMLCommonSetupEvent(final ModContainer container)
|
||||
{
|
||||
super(container);
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.event.lifecycle;
|
||||
|
||||
import net.minecraftforge.fml.ModContainer;
|
||||
|
||||
public class FMLConstructModEvent extends ParallelDispatchEvent {
|
||||
public FMLConstructModEvent(final ModContainer container) {
|
||||
super(container);
|
||||
}
|
||||
}
|
||||
-51
@@ -1,51 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.event.lifecycle;
|
||||
|
||||
import net.minecraft.server.dedicated.DedicatedServer;
|
||||
import net.minecraftforge.fml.ModContainer;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* This is the second of four commonly called events during mod lifecycle startup.
|
||||
*
|
||||
* Called before {@link InterModEnqueueEvent}
|
||||
* Called after {@link FMLCommonSetupEvent}
|
||||
*
|
||||
* Called on {@link net.minecraftforge.api.distmarker.Dist#DEDICATED_SERVER} - the dedicated game server.
|
||||
*
|
||||
* Alternative to {@link FMLClientSetupEvent}.
|
||||
*
|
||||
* Do dedicated server specific activities with this event.
|
||||
*
|
||||
* <em>This event is fired before construction of the dedicated server. Use {@link net.minecraftforge.fml.event.server.FMLServerAboutToStartEvent}
|
||||
* or {@link net.minecraftforge.fml.event.server.FMLServerStartingEvent} to do stuff with the server, in both dedicated
|
||||
* and integrated server contexts</em>
|
||||
*
|
||||
* This is a parallel dispatch event.
|
||||
*/
|
||||
public class FMLDedicatedServerSetupEvent extends ParallelDispatchEvent
|
||||
{
|
||||
public FMLDedicatedServerSetupEvent(ModContainer container)
|
||||
{
|
||||
super(container);
|
||||
}
|
||||
}
|
||||
-57
@@ -1,57 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.event.lifecycle;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Set;
|
||||
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
|
||||
|
||||
/**
|
||||
* DEPRECATED WITHOUT REPLACEMENT. REMOVE FROM YOUR CODE!!!
|
||||
* IT HAS NEVER BEEN FIRED IN 1.13+ AND WILL NEVER FIRE AGAIN!!!
|
||||
* FIRE.JPG FIRE.JPG FIRE.JPG
|
||||
* DELET THIS
|
||||
*/
|
||||
@Deprecated
|
||||
public class FMLFingerprintViolationEvent extends ModLifecycleEvent
|
||||
{
|
||||
|
||||
private final boolean isDirectory;
|
||||
private final Set<String> fingerprints;
|
||||
private final File source;
|
||||
private final String expectedFingerprint;
|
||||
|
||||
public FMLFingerprintViolationEvent(boolean isDirectory, File source, ImmutableSet<String> fingerprints, String expectedFingerprint)
|
||||
{
|
||||
super(null);
|
||||
this.isDirectory = isDirectory;
|
||||
this.source = source;
|
||||
this.fingerprints = fingerprints;
|
||||
this.expectedFingerprint = expectedFingerprint;
|
||||
}
|
||||
|
||||
public boolean isDirectory() { return isDirectory; }
|
||||
public Set<String> getFingerprints() { return fingerprints; }
|
||||
public File getSource() { return source; }
|
||||
public String getExpectedFingerprint() { return expectedFingerprint; }
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.event.lifecycle;
|
||||
|
||||
import net.minecraftforge.fml.ModContainer;
|
||||
|
||||
/**
|
||||
* This is a mostly internal event fired to mod containers that indicates that loading is complete. Mods should not
|
||||
* in general override or otherwise attempt to implement this event.
|
||||
*
|
||||
* @author cpw
|
||||
*/
|
||||
public class FMLLoadCompleteEvent extends ParallelDispatchEvent
|
||||
{
|
||||
public FMLLoadCompleteEvent(final ModContainer container)
|
||||
{
|
||||
super(container);
|
||||
}
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.event.lifecycle;
|
||||
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Maps;
|
||||
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
|
||||
/**
|
||||
* Called whenever the ID mapping might have changed. If you register for this event, you
|
||||
* will be called back whenever the client or server loads an ID set. This includes both
|
||||
* when the ID maps are loaded from disk, as well as when the ID maps revert to the initial
|
||||
* state.
|
||||
*
|
||||
* Note: you cannot change the IDs that have been allocated, but you might want to use
|
||||
* this event to update caches or other in-mod artifacts that might be impacted by an ID
|
||||
* change.
|
||||
*
|
||||
* Fired on the {@link net.minecraftforge.common.MinecraftForge#EVENT_BUS}
|
||||
*/
|
||||
public class FMLModIdMappingEvent extends ModLifecycleEvent
|
||||
{
|
||||
public class ModRemapping
|
||||
{
|
||||
public final ResourceLocation registry;
|
||||
public final ResourceLocation key;
|
||||
public final int oldId;
|
||||
public final int newId;
|
||||
|
||||
private ModRemapping(ResourceLocation registry, ResourceLocation key, int oldId, int newId)
|
||||
{
|
||||
this.registry = registry;
|
||||
this.key = key;
|
||||
this.oldId = oldId;
|
||||
this.newId = newId;
|
||||
}
|
||||
}
|
||||
|
||||
private final Map<ResourceLocation, ImmutableList<ModRemapping>> remaps;
|
||||
private final ImmutableSet<ResourceLocation> keys;
|
||||
|
||||
public final boolean isFrozen;
|
||||
public FMLModIdMappingEvent(Map<ResourceLocation, Map<ResourceLocation, Integer[]>> remaps, boolean isFrozen)
|
||||
{
|
||||
super(null);
|
||||
this.isFrozen = isFrozen;
|
||||
this.remaps = Maps.newHashMap();
|
||||
remaps.forEach((name, rm) ->
|
||||
{
|
||||
List<ModRemapping> tmp = Lists.newArrayList();
|
||||
rm.forEach((key, value) -> tmp.add(new ModRemapping(name, key, value[0], value[1])));
|
||||
tmp.sort(Comparator.comparingInt(o -> o.newId));
|
||||
this.remaps.put(name, ImmutableList.copyOf(tmp));
|
||||
});
|
||||
this.keys = ImmutableSet.copyOf(this.remaps.keySet());
|
||||
}
|
||||
|
||||
public ImmutableSet<ResourceLocation> getRegistries()
|
||||
{
|
||||
return this.keys;
|
||||
}
|
||||
|
||||
public ImmutableList<ModRemapping> getRemaps(ResourceLocation registry)
|
||||
{
|
||||
return this.remaps.get(registry);
|
||||
}
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.event.lifecycle;
|
||||
|
||||
import cpw.mods.modlauncher.api.LamdbaExceptionUtils;
|
||||
import net.minecraft.data.DataGenerator;
|
||||
import net.minecraftforge.common.data.ExistingFileHelper;
|
||||
import net.minecraftforge.eventbus.api.Event;
|
||||
import net.minecraftforge.fml.ModContainer;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class GatherDataEvent extends Event implements IModBusEvent
|
||||
{
|
||||
private final DataGenerator dataGenerator;
|
||||
private final DataGeneratorConfig config;
|
||||
private final ExistingFileHelper existingFileHelper;
|
||||
private final ModContainer modContainer;
|
||||
|
||||
public GatherDataEvent(final ModContainer mc, final DataGenerator dataGenerator, final DataGeneratorConfig dataGeneratorConfig, ExistingFileHelper existingFileHelper)
|
||||
{
|
||||
this.modContainer = mc;
|
||||
this.dataGenerator = dataGenerator;
|
||||
this.config = dataGeneratorConfig;
|
||||
this.existingFileHelper = existingFileHelper;
|
||||
}
|
||||
|
||||
public ModContainer getModContainer() {
|
||||
return this.modContainer;
|
||||
}
|
||||
|
||||
public DataGenerator getGenerator() { return this.dataGenerator; }
|
||||
public ExistingFileHelper getExistingFileHelper() { return existingFileHelper; }
|
||||
public boolean includeServer() { return this.config.server; }
|
||||
public boolean includeClient() { return this.config.client; }
|
||||
public boolean includeDev() { return this.config.dev; }
|
||||
public boolean includeReports() { return this.config.reports; }
|
||||
public boolean validate() { return this.config.validate; }
|
||||
|
||||
public static class DataGeneratorConfig {
|
||||
private final Set<String> mods;
|
||||
private final Path path;
|
||||
private final Collection<Path> inputs;
|
||||
private final boolean server;
|
||||
private final boolean client;
|
||||
private final boolean dev;
|
||||
private final boolean reports;
|
||||
private final boolean validate;
|
||||
private final boolean flat;
|
||||
private List<DataGenerator> generators = new ArrayList<>();
|
||||
|
||||
public DataGeneratorConfig(final Set<String> mods, final Path path, final Collection<Path> inputs, final boolean server, final boolean client, final boolean dev, final boolean reports, final boolean validate, final boolean flat) {
|
||||
this.mods = mods;
|
||||
this.path = path;
|
||||
this.inputs = inputs;
|
||||
this.server = server;
|
||||
this.client = client;
|
||||
this.dev = dev;
|
||||
this.reports = reports;
|
||||
this.validate = validate;
|
||||
this.flat = flat;
|
||||
|
||||
}
|
||||
|
||||
public Set<String> getMods() {
|
||||
return mods;
|
||||
}
|
||||
|
||||
public boolean isFlat() {
|
||||
return flat || getMods().size() == 1;
|
||||
}
|
||||
|
||||
public DataGenerator makeGenerator(final Function<Path,Path> pathEnhancer, final boolean shouldExecute) {
|
||||
final DataGenerator generator = new DataGenerator(pathEnhancer.apply(path), inputs);
|
||||
if (shouldExecute)
|
||||
generators.add(generator);
|
||||
return generator;
|
||||
}
|
||||
|
||||
public void runAll() {
|
||||
Map<Path, List<DataGenerator>> paths = generators.stream().collect(Collectors.groupingBy(DataGenerator::getOutputFolder));
|
||||
|
||||
paths.values().forEach(LamdbaExceptionUtils.rethrowConsumer(lst -> {
|
||||
DataGenerator parent = lst.get(0);
|
||||
for (int x = 1; x < lst.size(); x++)
|
||||
lst.get(x).getProviders().forEach(parent::addProvider);
|
||||
parent.run();
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.event.lifecycle;
|
||||
|
||||
/**
|
||||
* Marker interface for events dispatched on the ModLifecycle event bus instead of the primary event bus
|
||||
*/
|
||||
public interface IModBusEvent {
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.event.lifecycle;
|
||||
|
||||
import net.minecraftforge.fml.ModContainer;
|
||||
|
||||
/**
|
||||
* This is the third of four commonly called events during mod lifecycle startup.
|
||||
*
|
||||
* Called before {@link InterModProcessEvent}
|
||||
* Called after {@link FMLClientSetupEvent} or {@link FMLDedicatedServerSetupEvent}
|
||||
*
|
||||
*
|
||||
* Enqueue {@link net.minecraftforge.fml.InterModComms} messages to other mods with this event.
|
||||
*
|
||||
* This is a parallel dispatch event.
|
||||
*/
|
||||
public class InterModEnqueueEvent extends ParallelDispatchEvent
|
||||
{
|
||||
|
||||
public InterModEnqueueEvent(final ModContainer container)
|
||||
{
|
||||
super(container);
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.event.lifecycle;
|
||||
|
||||
import net.minecraftforge.fml.ModContainer;
|
||||
|
||||
import java.util.function.Predicate;
|
||||
|
||||
/**
|
||||
* This is the fourth of four commonly called events during mod lifecycle startup.
|
||||
*
|
||||
* Called after {@link InterModEnqueueEvent}
|
||||
*
|
||||
* Retrieve {@link net.minecraftforge.fml.InterModComms} {@link net.minecraftforge.fml.InterModComms.IMCMessage} suppliers
|
||||
* and process them as you wish with this event.
|
||||
*
|
||||
* This is a parallel dispatch event.
|
||||
*
|
||||
* @see #getIMCStream()
|
||||
* @see #getIMCStream(Predicate)
|
||||
*/
|
||||
public class InterModProcessEvent extends ParallelDispatchEvent
|
||||
{
|
||||
public InterModProcessEvent(final ModContainer container)
|
||||
{
|
||||
super(container);
|
||||
}
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.event.lifecycle;
|
||||
|
||||
import net.minecraftforge.eventbus.api.Event;
|
||||
import net.minecraftforge.fml.InterModComms;
|
||||
import net.minecraftforge.fml.ModContainer;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* Parent type to all ModLifecycle events. This is based on Forge EventBus. They fire through the
|
||||
* ModContainer's eventbus instance.
|
||||
*/
|
||||
public class ModLifecycleEvent extends Event implements IModBusEvent
|
||||
{
|
||||
private final ModContainer container;
|
||||
|
||||
public ModLifecycleEvent(ModContainer container)
|
||||
{
|
||||
this.container = container;
|
||||
}
|
||||
|
||||
public final String description()
|
||||
{
|
||||
String cn = getClass().getName();
|
||||
return cn.substring(cn.lastIndexOf('.')+1);
|
||||
}
|
||||
|
||||
public Stream<InterModComms.IMCMessage> getIMCStream() {
|
||||
return InterModComms.getMessages(this.container.getModId());
|
||||
}
|
||||
|
||||
public Stream<InterModComms.IMCMessage> getIMCStream(Predicate<String> methodFilter) {
|
||||
return InterModComms.getMessages(this.container.getModId(), methodFilter);
|
||||
}
|
||||
|
||||
ModContainer getContainer() {
|
||||
return this.container;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return description();
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.event.lifecycle;
|
||||
|
||||
import net.minecraftforge.fml.DeferredWorkQueue;
|
||||
import net.minecraftforge.fml.ModContainer;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class ParallelDispatchEvent extends ModLifecycleEvent {
|
||||
public ParallelDispatchEvent(final ModContainer container) {
|
||||
super(container);
|
||||
}
|
||||
|
||||
private Optional<DeferredWorkQueue> getQueue() {
|
||||
return DeferredWorkQueue.lookup(Optional.of(getClass()));
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> enqueueWork(Runnable work) {
|
||||
return getQueue().map(q->q.enqueueWork(getContainer().getModInfo(), work)).orElseThrow(()->new RuntimeException("No work queue found!"));
|
||||
}
|
||||
|
||||
public <T> CompletableFuture<T> enqueueWork(Supplier<T> work) {
|
||||
return getQueue().map(q->q.enqueueWork(getContainer().getModInfo(), work)).orElseThrow(()->new RuntimeException("No work queue found!"));
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.event.server;
|
||||
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraftforge.fml.event.lifecycle.InterModProcessEvent;
|
||||
|
||||
/**
|
||||
* Called before the server begins loading anything. Called after {@link InterModProcessEvent} on the dedicated
|
||||
* server, and after the player has hit "Play Selected World" in the client. Called before {@link FMLServerStartingEvent}.
|
||||
*
|
||||
* You can obtain a reference to the server with this event.
|
||||
* @author cpw
|
||||
*/
|
||||
public class FMLServerAboutToStartEvent extends ServerLifecycleEvent {
|
||||
|
||||
public FMLServerAboutToStartEvent(MinecraftServer server)
|
||||
{
|
||||
super(server);
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.event.server;
|
||||
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
|
||||
/**
|
||||
* Called after {@link FMLServerStartingEvent} when the server is available and ready to play.
|
||||
*
|
||||
* @author cpw
|
||||
*/
|
||||
public class FMLServerStartedEvent extends ServerLifecycleEvent
|
||||
{
|
||||
|
||||
public FMLServerStartedEvent(final MinecraftServer server)
|
||||
{
|
||||
super(server);
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.event.server;
|
||||
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
|
||||
/**
|
||||
* Called after {@link FMLServerAboutToStartEvent} and before {@link FMLServerStartedEvent}.
|
||||
* This event allows for customizations of the server.
|
||||
*
|
||||
* If you need to add commands use {@link net.minecraftforge.event.RegisterCommandsEvent}.
|
||||
*
|
||||
* @author cpw
|
||||
*/
|
||||
public class FMLServerStartingEvent extends ServerLifecycleEvent
|
||||
{
|
||||
public FMLServerStartingEvent(final MinecraftServer server)
|
||||
{
|
||||
super(server);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.event.server;
|
||||
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
|
||||
/**
|
||||
* Called after {@link FMLServerStoppingEvent} when the server has completely shut down.
|
||||
* Called immediately before shutting down, on the dedicated server, and before returning
|
||||
* to the main menu on the client.
|
||||
*
|
||||
* @author cpw
|
||||
*/
|
||||
public class FMLServerStoppedEvent extends ServerLifecycleEvent {
|
||||
public FMLServerStoppedEvent(MinecraftServer server)
|
||||
{
|
||||
super(server);
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.event.server;
|
||||
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
|
||||
/**
|
||||
* Called when the server begins an orderly shutdown, before {@link FMLServerStoppedEvent}.
|
||||
*
|
||||
* @author cpw
|
||||
*/
|
||||
public class FMLServerStoppingEvent extends ServerLifecycleEvent
|
||||
{
|
||||
public FMLServerStoppingEvent(MinecraftServer server)
|
||||
{
|
||||
super(server);
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.event.server;
|
||||
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraftforge.eventbus.api.Event;
|
||||
|
||||
public class ServerLifecycleEvent extends Event
|
||||
{
|
||||
|
||||
protected final MinecraftServer server;
|
||||
|
||||
public ServerLifecycleEvent(MinecraftServer server)
|
||||
{
|
||||
this.server = server;
|
||||
}
|
||||
|
||||
public MinecraftServer getServer()
|
||||
{
|
||||
return server;
|
||||
}
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.hooks;
|
||||
|
||||
import net.minecraft.entity.item.ItemEntity;
|
||||
import net.minecraft.entity.player.PlayerEntity;
|
||||
import net.minecraft.inventory.IInventory;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.util.RegistryKey;
|
||||
import net.minecraft.world.World;
|
||||
import net.minecraftforge.client.model.animation.Animation;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.event.entity.player.PlayerEvent;
|
||||
import net.minecraftforge.fml.LogicalSide;
|
||||
import net.minecraftforge.event.TickEvent;
|
||||
|
||||
public class BasicEventHooks
|
||||
{
|
||||
|
||||
public static void firePlayerChangedDimensionEvent(PlayerEntity player, RegistryKey<World> fromDim, RegistryKey<World> toDim)
|
||||
{
|
||||
MinecraftForge.EVENT_BUS.post(new PlayerEvent.PlayerChangedDimensionEvent(player, fromDim, toDim));
|
||||
}
|
||||
|
||||
public static void firePlayerLoggedIn(PlayerEntity player)
|
||||
{
|
||||
MinecraftForge.EVENT_BUS.post(new PlayerEvent.PlayerLoggedInEvent(player));
|
||||
}
|
||||
|
||||
public static void firePlayerLoggedOut(PlayerEntity player)
|
||||
{
|
||||
MinecraftForge.EVENT_BUS.post(new PlayerEvent.PlayerLoggedOutEvent(player));
|
||||
}
|
||||
|
||||
public static void firePlayerRespawnEvent(PlayerEntity player, boolean endConquered)
|
||||
{
|
||||
MinecraftForge.EVENT_BUS.post(new PlayerEvent.PlayerRespawnEvent(player, endConquered));
|
||||
}
|
||||
|
||||
public static void firePlayerItemPickupEvent(PlayerEntity player, ItemEntity item, ItemStack clone)
|
||||
{
|
||||
MinecraftForge.EVENT_BUS.post(new PlayerEvent.ItemPickupEvent(player, item, clone));
|
||||
}
|
||||
|
||||
public static void firePlayerCraftingEvent(PlayerEntity player, ItemStack crafted, IInventory craftMatrix)
|
||||
{
|
||||
MinecraftForge.EVENT_BUS.post(new PlayerEvent.ItemCraftedEvent(player, crafted, craftMatrix));
|
||||
}
|
||||
|
||||
public static void firePlayerSmeltedEvent(PlayerEntity player, ItemStack smelted)
|
||||
{
|
||||
MinecraftForge.EVENT_BUS.post(new PlayerEvent.ItemSmeltedEvent(player, smelted));
|
||||
}
|
||||
|
||||
public static void onRenderTickStart(float timer)
|
||||
{
|
||||
Animation.setClientPartialTickTime(timer);
|
||||
MinecraftForge.EVENT_BUS.post(new TickEvent.RenderTickEvent(TickEvent.Phase.START, timer));
|
||||
}
|
||||
|
||||
public static void onRenderTickEnd(float timer)
|
||||
{
|
||||
MinecraftForge.EVENT_BUS.post(new TickEvent.RenderTickEvent(TickEvent.Phase.END, timer));
|
||||
}
|
||||
|
||||
public static void onPlayerPreTick(PlayerEntity player)
|
||||
{
|
||||
MinecraftForge.EVENT_BUS.post(new TickEvent.PlayerTickEvent(TickEvent.Phase.START, player));
|
||||
}
|
||||
|
||||
public static void onPlayerPostTick(PlayerEntity player)
|
||||
{
|
||||
MinecraftForge.EVENT_BUS.post(new TickEvent.PlayerTickEvent(TickEvent.Phase.END, player));
|
||||
}
|
||||
|
||||
public static void onPreWorldTick(World world)
|
||||
{
|
||||
MinecraftForge.EVENT_BUS.post(new TickEvent.WorldTickEvent(LogicalSide.SERVER, TickEvent.Phase.START, world));
|
||||
}
|
||||
|
||||
public static void onPostWorldTick(World world)
|
||||
{
|
||||
MinecraftForge.EVENT_BUS.post(new TickEvent.WorldTickEvent(LogicalSide.SERVER, TickEvent.Phase.END, world));
|
||||
}
|
||||
|
||||
public static void onPreClientTick()
|
||||
{
|
||||
MinecraftForge.EVENT_BUS.post(new TickEvent.ClientTickEvent(TickEvent.Phase.START));
|
||||
}
|
||||
|
||||
public static void onPostClientTick()
|
||||
{
|
||||
MinecraftForge.EVENT_BUS.post(new TickEvent.ClientTickEvent(TickEvent.Phase.END));
|
||||
}
|
||||
|
||||
public static void onPreServerTick()
|
||||
{
|
||||
MinecraftForge.EVENT_BUS.post(new TickEvent.ServerTickEvent(TickEvent.Phase.START));
|
||||
}
|
||||
|
||||
public static void onPostServerTick()
|
||||
{
|
||||
MinecraftForge.EVENT_BUS.post(new TickEvent.ServerTickEvent(TickEvent.Phase.END));
|
||||
}
|
||||
}
|
||||
@@ -1,124 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.javafmlmod;
|
||||
|
||||
import cpw.mods.modlauncher.api.LamdbaExceptionUtils;
|
||||
import net.minecraftforge.fml.ModLoadingException;
|
||||
import net.minecraftforge.fml.ModLoadingStage;
|
||||
import net.minecraftforge.fml.common.Mod;
|
||||
import net.minecraftforge.forgespi.language.ILifecycleEvent;
|
||||
import net.minecraftforge.forgespi.language.IModLanguageProvider;
|
||||
import net.minecraftforge.forgespi.language.IModInfo;
|
||||
import net.minecraftforge.forgespi.language.ModFileScanData;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.objectweb.asm.Type;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.util.Map;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static net.minecraftforge.fml.Logging.*;
|
||||
|
||||
public class FMLJavaModLanguageProvider implements IModLanguageProvider
|
||||
{
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
|
||||
private static class FMLModTarget implements IModLanguageProvider.IModLanguageLoader {
|
||||
private static final Logger LOGGER = FMLJavaModLanguageProvider.LOGGER;
|
||||
private final String className;
|
||||
private final String modId;
|
||||
|
||||
private FMLModTarget(String className, String modId)
|
||||
{
|
||||
this.className = className;
|
||||
this.modId = modId;
|
||||
}
|
||||
|
||||
public String getModId()
|
||||
{
|
||||
return modId;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public <T> T loadMod(final IModInfo info, final ClassLoader modClassLoader, final ModFileScanData modFileScanResults)
|
||||
{
|
||||
// This language class is loaded in the system level classloader - before the game even starts
|
||||
// So we must treat container construction as an arms length operation, and load the container
|
||||
// in the classloader of the game - the context classloader is appropriate here.
|
||||
try
|
||||
{
|
||||
final Class<?> fmlContainer = Class.forName("net.minecraftforge.fml.javafmlmod.FMLModContainer", true, Thread.currentThread().getContextClassLoader());
|
||||
LOGGER.debug(LOADING, "Loading FMLModContainer from classloader {} - got {}", Thread.currentThread().getContextClassLoader(), fmlContainer.getClassLoader());
|
||||
final Constructor<?> constructor = fmlContainer.getConstructor(IModInfo.class, String.class, ClassLoader.class, ModFileScanData.class);
|
||||
return (T)constructor.newInstance(info, className, modClassLoader, modFileScanResults);
|
||||
}
|
||||
// ALL exception handling has to be done through the classloader, because we're loaded in the wrong context, so any classes we just blind load will be in the wrong
|
||||
// class loading context. Funky but works.
|
||||
catch (InvocationTargetException e) {
|
||||
LOGGER.fatal(LOADING, "Failed to build mod", e);
|
||||
final Class<RuntimeException> mle = (Class<RuntimeException>)LamdbaExceptionUtils.uncheck(()->Class.forName("net.minecraftforge.fml.ModLoadingException", true, Thread.currentThread().getContextClassLoader()));
|
||||
if (mle.isInstance(e.getTargetException())) {
|
||||
throw mle.cast(e.getTargetException());
|
||||
} else {
|
||||
final Class<ModLoadingStage> mls = (Class<ModLoadingStage>) LamdbaExceptionUtils.uncheck(()->Class.forName("net.minecraftforge.fml.ModLoadingStage", true, Thread.currentThread().getContextClassLoader()));
|
||||
throw LamdbaExceptionUtils.uncheck(()->LamdbaExceptionUtils.uncheck(()->mle.getConstructor(IModInfo.class, mls, String.class, Throwable.class)).newInstance(info, Enum.valueOf(mls, "CONSTRUCT"), "fml.modloading.failedtoloadmodclass", e));
|
||||
}
|
||||
}
|
||||
catch (NoSuchMethodException | ClassNotFoundException | InstantiationException | IllegalAccessException e)
|
||||
{
|
||||
LOGGER.fatal(LOADING,"Unable to load FMLModContainer, wut?", e);
|
||||
final Class<RuntimeException> mle = (Class<RuntimeException>)LamdbaExceptionUtils.uncheck(()->Class.forName("net.minecraftforge.fml.ModLoadingException", true, Thread.currentThread().getContextClassLoader()));
|
||||
final Class<ModLoadingStage> mls = (Class<ModLoadingStage>) LamdbaExceptionUtils.uncheck(()->Class.forName("net.minecraftforge.fml.ModLoadingStage", true, Thread.currentThread().getContextClassLoader()));
|
||||
throw LamdbaExceptionUtils.uncheck(()->LamdbaExceptionUtils.uncheck(()->mle.getConstructor(IModInfo.class, mls, String.class, Throwable.class)).newInstance(info, Enum.valueOf(mls, "CONSTRUCT"), "fml.modloading.failedtoloadmodclass", e));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static final Type MODANNOTATION = Type.getType("Lnet/minecraftforge/fml/common/Mod;");
|
||||
|
||||
@Override
|
||||
public String name()
|
||||
{
|
||||
return "javafml";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Consumer<ModFileScanData> getFileVisitor() {
|
||||
return scanResult -> {
|
||||
final Map<String, FMLModTarget> modTargetMap = scanResult.getAnnotations().stream()
|
||||
.filter(ad -> ad.getAnnotationType().equals(MODANNOTATION))
|
||||
.peek(ad -> LOGGER.debug(SCAN, "Found @Mod class {} with id {}", ad.getClassType().getClassName(), ad.getAnnotationData().get("value")))
|
||||
.map(ad -> new FMLModTarget(ad.getClassType().getClassName(), (String)ad.getAnnotationData().get("value")))
|
||||
.collect(Collectors.toMap(FMLModTarget::getModId, Function.identity(), (a,b)->a));
|
||||
scanResult.addLanguageLoader(modTargetMap);
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public <R extends ILifecycleEvent<R>> void consumeLifecycleEvent(final Supplier<R> consumeEvent) {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.javafmlmod;
|
||||
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.fml.ModLoadingContext;
|
||||
|
||||
public class FMLJavaModLoadingContext
|
||||
{
|
||||
private final FMLModContainer container;
|
||||
|
||||
FMLJavaModLoadingContext(FMLModContainer container) {
|
||||
this.container = container;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return The mod's event bus, to allow subscription to Mod specific events
|
||||
*/
|
||||
public IEventBus getModEventBus()
|
||||
{
|
||||
return container.getEventBus();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Helper to get the right instance from the {@link ModLoadingContext} correctly.
|
||||
* @return The FMLJavaMod language specific extension from the ModLoadingContext
|
||||
*/
|
||||
public static FMLJavaModLoadingContext get() {
|
||||
return ModLoadingContext.get().extension();
|
||||
}
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.javafmlmod;
|
||||
|
||||
import net.minecraftforge.eventbus.EventBusErrorMessage;
|
||||
import net.minecraftforge.eventbus.api.BusBuilder;
|
||||
import net.minecraftforge.eventbus.api.Event;
|
||||
import net.minecraftforge.eventbus.api.IEventBus;
|
||||
import net.minecraftforge.eventbus.api.IEventListener;
|
||||
import net.minecraftforge.fml.AutomaticEventSubscriber;
|
||||
import net.minecraftforge.fml.ModContainer;
|
||||
import net.minecraftforge.fml.ModLoadingException;
|
||||
import net.minecraftforge.fml.ModLoadingStage;
|
||||
import net.minecraftforge.fml.event.lifecycle.IModBusEvent;
|
||||
import net.minecraftforge.forgespi.language.IModInfo;
|
||||
import net.minecraftforge.forgespi.language.ModFileScanData;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static net.minecraftforge.fml.Logging.LOADING;
|
||||
|
||||
public class FMLModContainer extends ModContainer
|
||||
{
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
private final ModFileScanData scanResults;
|
||||
private final IEventBus eventBus;
|
||||
private Object modInstance;
|
||||
private final Class<?> modClass;
|
||||
|
||||
public FMLModContainer(IModInfo info, String className, ClassLoader modClassLoader, ModFileScanData modFileScanResults)
|
||||
{
|
||||
super(info);
|
||||
LOGGER.debug(LOADING,"Creating FMLModContainer instance for {} with classLoader {} & {}", className, modClassLoader, getClass().getClassLoader());
|
||||
this.scanResults = modFileScanResults;
|
||||
activityMap.put(ModLoadingStage.CONSTRUCT, this::constructMod);
|
||||
this.eventBus = BusBuilder.builder().setExceptionHandler(this::onEventFailed).setTrackPhases(false).markerType(IModBusEvent.class).build();
|
||||
this.configHandler = Optional.of(this.eventBus::post);
|
||||
final FMLJavaModLoadingContext contextExtension = new FMLJavaModLoadingContext(this);
|
||||
this.contextExtension = () -> contextExtension;
|
||||
try
|
||||
{
|
||||
modClass = Class.forName(className, true, modClassLoader);
|
||||
LOGGER.trace(LOADING,"Loaded modclass {} with {}", modClass.getName(), modClass.getClassLoader());
|
||||
}
|
||||
catch (Throwable e)
|
||||
{
|
||||
LOGGER.error(LOADING, "Failed to load class {}", className, e);
|
||||
throw new ModLoadingException(info, ModLoadingStage.CONSTRUCT, "fml.modloading.failedtoloadmodclass", e);
|
||||
}
|
||||
}
|
||||
|
||||
private void onEventFailed(IEventBus iEventBus, Event event, IEventListener[] iEventListeners, int i, Throwable throwable)
|
||||
{
|
||||
LOGGER.error(new EventBusErrorMessage(event, i, iEventListeners, throwable));
|
||||
}
|
||||
|
||||
private void constructMod()
|
||||
{
|
||||
try
|
||||
{
|
||||
LOGGER.trace(LOADING, "Loading mod instance {} of type {}", getModId(), modClass.getName());
|
||||
this.modInstance = modClass.newInstance();
|
||||
LOGGER.trace(LOADING, "Loaded mod instance {} of type {}", getModId(), modClass.getName());
|
||||
}
|
||||
catch (Throwable e)
|
||||
{
|
||||
LOGGER.error(LOADING,"Failed to create mod instance. ModID: {}, class {}", getModId(), modClass.getName(), e);
|
||||
throw new ModLoadingException(modInfo, ModLoadingStage.CONSTRUCT, "fml.modloading.failedtoloadmod", e, modClass);
|
||||
}
|
||||
try {
|
||||
LOGGER.trace(LOADING, "Injecting Automatic event subscribers for {}", getModId());
|
||||
AutomaticEventSubscriber.inject(this, this.scanResults, this.modClass.getClassLoader());
|
||||
LOGGER.trace(LOADING, "Completed Automatic event subscribers for {}", getModId());
|
||||
} catch (Throwable e) {
|
||||
LOGGER.error(LOADING,"Failed to register automatic subscribers. ModID: {}, class {}", getModId(), modClass.getName(), e);
|
||||
throw new ModLoadingException(modInfo, ModLoadingStage.CONSTRUCT, "fml.modloading.failedtoloadmod", e, modClass);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean matches(Object mod)
|
||||
{
|
||||
return mod == modInstance;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getMod()
|
||||
{
|
||||
return modInstance;
|
||||
}
|
||||
|
||||
public IEventBus getEventBus()
|
||||
{
|
||||
return this.eventBus;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected <T extends Event & IModBusEvent> void acceptEvent(final T e) {
|
||||
try {
|
||||
LOGGER.trace(LOADING, "Firing event for modid {} : {}", this.getModId(), e);
|
||||
this.eventBus.post(e);
|
||||
LOGGER.trace(LOADING, "Fired event for modid {} : {}", this.getModId(), e);
|
||||
} catch (Throwable t) {
|
||||
LOGGER.error(LOADING,"Caught exception during event {} dispatch for modid {}", e, this.getModId(), t);
|
||||
throw new ModLoadingException(modInfo, modLoadingStage, "fml.modloading.errorduringevent", t);
|
||||
}
|
||||
}
|
||||
}
|
||||
-88
@@ -1,88 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.mclanguageprovider;
|
||||
|
||||
import net.minecraftforge.fml.ModContainer;
|
||||
import net.minecraftforge.forgespi.language.ILifecycleEvent;
|
||||
import net.minecraftforge.forgespi.language.IModInfo;
|
||||
import net.minecraftforge.forgespi.language.IModLanguageProvider;
|
||||
import net.minecraftforge.forgespi.language.ModFileScanData;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.util.Collections;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import static net.minecraftforge.fml.Logging.LOADING;
|
||||
|
||||
import net.minecraftforge.forgespi.language.IModLanguageProvider.IModLanguageLoader;
|
||||
|
||||
public class MinecraftModLanguageProvider implements IModLanguageProvider {
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
@Override
|
||||
public String name() {
|
||||
return "minecraft";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Consumer<ModFileScanData> getFileVisitor() {
|
||||
return (sd)->sd.addLanguageLoader(Collections.singletonMap("minecraft", new MinecraftModTarget()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public <R extends ILifecycleEvent<R>> void consumeLifecycleEvent(final Supplier<R> consumeEvent) {
|
||||
|
||||
}
|
||||
|
||||
public static class MinecraftModTarget implements IModLanguageLoader {
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public <T> T loadMod(final IModInfo info, final ClassLoader modClassLoader, final ModFileScanData modFileScanResults) {
|
||||
try {
|
||||
final Class<?> mcModClass = Class.forName("net.minecraftforge.fml.mclanguageprovider.MinecraftModLanguageProvider$MinecraftModContainer", true, modClassLoader);
|
||||
return (T)mcModClass.getConstructor(IModInfo.class).newInstance(info);
|
||||
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | NoSuchMethodException | InvocationTargetException e) {
|
||||
LOGGER.fatal(LOADING,"Unable to load MinecraftModContainer, wut?", e);
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
public static class MinecraftModContainer extends ModContainer {
|
||||
private static final String MCMODINSTANCE = "minecraft, the mod";
|
||||
|
||||
public MinecraftModContainer(final IModInfo info) {
|
||||
super(info);
|
||||
contextExtension = ()->null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean matches(final Object mod) {
|
||||
return Objects.equals(mod, MCMODINSTANCE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getMod() {
|
||||
return MCMODINSTANCE;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.network;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
public enum ConnectionType
|
||||
{
|
||||
MODDED(s->Integer.valueOf(s.substring(FMLNetworkConstants.FMLNETMARKER.length()))), VANILLA(s->0);
|
||||
|
||||
private final Function<String, Integer> versionExtractor;
|
||||
|
||||
ConnectionType(Function<String, Integer> versionExtractor)
|
||||
{
|
||||
this.versionExtractor = versionExtractor;
|
||||
}
|
||||
|
||||
public static ConnectionType forVersionFlag(String vers)
|
||||
{
|
||||
return vers.startsWith(FMLNetworkConstants.FMLNETMARKER) ? MODDED : VANILLA;
|
||||
}
|
||||
|
||||
public int getFMLVersionNumber(final String fmlVersion)
|
||||
{
|
||||
return versionExtractor.apply(fmlVersion);
|
||||
}
|
||||
|
||||
public boolean isVanilla()
|
||||
{
|
||||
return this == VANILLA;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.network;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class FMLConnectionData
|
||||
{
|
||||
private ImmutableList<String> modList;
|
||||
private ImmutableMap<ResourceLocation, String> channels;
|
||||
|
||||
/* package private */ FMLConnectionData(List<String> modList, Map<ResourceLocation, String> channels)
|
||||
{
|
||||
this.modList = ImmutableList.copyOf(modList);
|
||||
this.channels = ImmutableMap.copyOf(channels);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the list of mods present in the remote.
|
||||
* <b>WARNING: This list is not authoritative.
|
||||
* A mod missing from the list does not mean the mod isn't there,
|
||||
* and similarly a mod present in the list does not mean it is there.
|
||||
* People using hacked clients WILL hack the mod lists to make them look correct.
|
||||
* Do not use this as an anti-cheat feature!
|
||||
* </b>
|
||||
* @return An immutable list of MODIDs
|
||||
*/
|
||||
public ImmutableList<String> getModList()
|
||||
{
|
||||
return modList;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the list of network channels present in the remote.
|
||||
* <b>WARNING: This list is not authoritative.
|
||||
* A channel missing from the list does not mean the remote won't accept packets with that channel ID,
|
||||
* and similarly a channel present in the list does not mean the remote won't ignore it.
|
||||
* People using hacked clients WILL hack the channel list to make it look correct.
|
||||
* Do not use this as an anti-cheat feature!
|
||||
* </b>
|
||||
* @return An immutable map of channel IDs and their respective protocol versions.
|
||||
*/
|
||||
public ImmutableMap<ResourceLocation, String> getChannels()
|
||||
{
|
||||
return channels;
|
||||
}
|
||||
}
|
||||
@@ -1,309 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.network;
|
||||
|
||||
import net.minecraft.network.login.ServerLoginNetHandler;
|
||||
import com.google.common.collect.Multimap;
|
||||
import net.minecraft.network.NetworkManager;
|
||||
import net.minecraft.network.PacketBuffer;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import net.minecraft.util.text.StringTextComponent;
|
||||
import net.minecraftforge.fml.config.ConfigTracker;
|
||||
import net.minecraftforge.fml.loading.AdvancedLogMessageAdapter;
|
||||
import net.minecraftforge.fml.network.simple.SimpleChannel;
|
||||
import net.minecraftforge.fml.util.ThreeConsumer;
|
||||
import net.minecraftforge.registries.ForgeRegistry;
|
||||
import net.minecraftforge.registries.GameData;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.apache.logging.log4j.Marker;
|
||||
import org.apache.logging.log4j.MarkerManager;
|
||||
|
||||
import com.google.common.collect.Maps;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.IntSupplier;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import static net.minecraftforge.registries.ForgeRegistry.REGISTRIES;
|
||||
|
||||
/**
|
||||
* Instance responsible for handling the overall FML network handshake.
|
||||
*
|
||||
* <p>An instance is created during {@link net.minecraft.network.handshake.client.CHandshakePacket} handling, and attached
|
||||
* to the {@link NetworkManager#channel} via {@link FMLNetworkConstants#FML_HANDSHAKE_HANDLER}.
|
||||
*
|
||||
* <p>The {@link FMLNetworkConstants#handshakeChannel} is a {@link SimpleChannel} with standard messages flowing in both directions.
|
||||
*
|
||||
* <p>The {@link #loginWrapper} transforms these messages into {@link net.minecraft.network.login.client.CCustomPayloadLoginPacket}
|
||||
* and {@link net.minecraft.network.login.server.SCustomPayloadLoginPacket} compatible messages, by means of wrapping.
|
||||
*
|
||||
* <p>The handshake is ticked {@link #tickLogin(NetworkManager)} from the {@link ServerLoginNetHandler#update()} method,
|
||||
* utilizing the {@link ServerLoginNetHandler.State#NEGOTIATING} state, which is otherwise unused in vanilla code.
|
||||
*
|
||||
* <p>During client to server initiation, on the <em>server</em>, the {@link NetworkEvent.GatherLoginPayloadsEvent} is fired,
|
||||
* which solicits all registered channels at the {@link NetworkRegistry} for any
|
||||
* {@link net.minecraftforge.fml.network.NetworkRegistry.LoginPayload} they wish to supply.
|
||||
*
|
||||
* <p>The collected {@link net.minecraftforge.fml.network.NetworkRegistry.LoginPayload} are sent, one per tick, via
|
||||
* the {@link FMLLoginWrapper#wrapPacket(ResourceLocation, PacketBuffer)} mechanism to the incoming client connection. Each
|
||||
* packet is indexed via {@link net.minecraft.network.login.client.CCustomPayloadLoginPacket#transaction}, which is
|
||||
* the only mechanism available for tracking request/response pairs.
|
||||
*
|
||||
* <p>Each packet sent from the server should be replied by the client, though not necessarily in sent order. The reply
|
||||
* should contain the index of the server's packet it is replying to. The {@link FMLLoginWrapper} class handles indexing
|
||||
* replies correctly automatically.
|
||||
*
|
||||
* <p>Once all packets have been dispatched, we wait for all replies to be received. Once all replies are received, the
|
||||
* final login phase will commence.
|
||||
*/
|
||||
public class FMLHandshakeHandler {
|
||||
static final Marker FMLHSMARKER = MarkerManager.getMarker("FMLHANDSHAKE").setParents(FMLNetworkConstants.NETWORK);
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
|
||||
private static final FMLLoginWrapper loginWrapper = new FMLLoginWrapper();
|
||||
|
||||
static {
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new handshake instance. Called when connection is first created during the {@link net.minecraft.network.handshake.client.CHandshakePacket}
|
||||
* handling.
|
||||
*
|
||||
* @param manager The network manager for this connection
|
||||
* @param direction The {@link NetworkDirection} for this connection: {@link NetworkDirection#LOGIN_TO_SERVER} or {@link NetworkDirection#LOGIN_TO_CLIENT}
|
||||
*/
|
||||
static void registerHandshake(NetworkManager manager, NetworkDirection direction) {
|
||||
manager.channel().attr(FMLNetworkConstants.FML_HANDSHAKE_HANDLER).compareAndSet(null, new FMLHandshakeHandler(manager, direction));
|
||||
}
|
||||
|
||||
static boolean tickLogin(NetworkManager networkManager)
|
||||
{
|
||||
return networkManager.channel().attr(FMLNetworkConstants.FML_HANDSHAKE_HANDLER).get().tickServer();
|
||||
}
|
||||
|
||||
private List<NetworkRegistry.LoginPayload> messageList;
|
||||
|
||||
private List<Integer> sentMessages = new ArrayList<>();
|
||||
|
||||
private final NetworkDirection direction;
|
||||
private final NetworkManager manager;
|
||||
private int packetPosition;
|
||||
private Map<ResourceLocation, ForgeRegistry.Snapshot> registrySnapshots;
|
||||
private Set<ResourceLocation> registriesToReceive;
|
||||
private Map<ResourceLocation, String> registryHashes;
|
||||
|
||||
private FMLHandshakeHandler(NetworkManager networkManager, NetworkDirection side)
|
||||
{
|
||||
this.direction = side;
|
||||
this.manager = networkManager;
|
||||
if (networkManager.isMemoryConnection()) {
|
||||
this.messageList = NetworkRegistry.gatherLoginPayloads(this.direction, true);
|
||||
LOGGER.debug(FMLHSMARKER, "Starting local connection.");
|
||||
} else if (NetworkHooks.getConnectionType(()->this.manager)==ConnectionType.VANILLA) {
|
||||
this.messageList = Collections.emptyList();
|
||||
LOGGER.debug(FMLHSMARKER, "Starting new vanilla network connection.");
|
||||
} else {
|
||||
this.messageList = NetworkRegistry.gatherLoginPayloads(this.direction, false);
|
||||
LOGGER.debug(FMLHSMARKER, "Starting new modded network connection. Found {} messages to dispatch.", this.messageList.size());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Transforms a two-argument instance method reference into a {@link BiConsumer} based on the {@link #getHandshake(Supplier)} function.
|
||||
*
|
||||
* This should only be used for login message types.
|
||||
*
|
||||
* @param consumer A two argument instance method reference
|
||||
* @param <MSG> message type
|
||||
* @return A {@link BiConsumer} for use in message handling
|
||||
*/
|
||||
public static <MSG extends IntSupplier> BiConsumer<MSG, Supplier<NetworkEvent.Context>> biConsumerFor(ThreeConsumer<FMLHandshakeHandler, ? super MSG, ? super Supplier<NetworkEvent.Context>> consumer)
|
||||
{
|
||||
return (m, c) -> ThreeConsumer.bindArgs(consumer, m, c).accept(getHandshake(c));
|
||||
}
|
||||
|
||||
/**
|
||||
* Transforms a two-argument instance method reference into a {@link BiConsumer} {@link #biConsumerFor(ThreeConsumer)}, first calling the {@link #handleIndexedMessage(FMLHandshakeMessages.LoginIndexedMessage, Supplier)}
|
||||
* method to handle index tracking. Used for client to server replies.
|
||||
*
|
||||
* This should only be used for login messages.
|
||||
*
|
||||
* @param next The method reference to call after index handling
|
||||
* @param <MSG> message type
|
||||
* @return A {@link BiConsumer} for use in message handling
|
||||
*/
|
||||
public static <MSG extends IntSupplier> BiConsumer<MSG, Supplier<NetworkEvent.Context>> indexFirst(ThreeConsumer<FMLHandshakeHandler, MSG, Supplier<NetworkEvent.Context>> next)
|
||||
{
|
||||
final BiConsumer<MSG, Supplier<NetworkEvent.Context>> loginIndexedMessageSupplierBiConsumer = biConsumerFor(FMLHandshakeHandler::handleIndexedMessage);
|
||||
return loginIndexedMessageSupplierBiConsumer.andThen(biConsumerFor(next));
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the handshake from the {@link NetworkEvent.Context}
|
||||
*
|
||||
* @param contextSupplier the {@link NetworkEvent.Context}
|
||||
* @return The handshake handler for the connection
|
||||
*/
|
||||
private static FMLHandshakeHandler getHandshake(Supplier<NetworkEvent.Context> contextSupplier) {
|
||||
return contextSupplier.get().attr(FMLNetworkConstants.FML_HANDSHAKE_HANDLER).get();
|
||||
}
|
||||
|
||||
void handleServerModListOnClient(FMLHandshakeMessages.S2CModList serverModList, Supplier<NetworkEvent.Context> c)
|
||||
{
|
||||
LOGGER.debug(FMLHSMARKER, "Logging into server with mod list [{}]", String.join(", ", serverModList.getModList()));
|
||||
boolean accepted = NetworkRegistry.validateClientChannels(serverModList.getChannels());
|
||||
c.get().setPacketHandled(true);
|
||||
if (!accepted) {
|
||||
LOGGER.error(FMLHSMARKER, "Terminating connection with server, mismatched mod list");
|
||||
c.get().getNetworkManager().disconnect(new StringTextComponent("Connection closed - mismatched mod channel list"));
|
||||
return;
|
||||
}
|
||||
FMLNetworkConstants.handshakeChannel.reply(new FMLHandshakeMessages.C2SModListReply(), c.get());
|
||||
|
||||
LOGGER.debug(FMLHSMARKER, "Accepted server connection");
|
||||
// Set the modded marker on the channel so we know we got packets
|
||||
c.get().getNetworkManager().channel().attr(FMLNetworkConstants.FML_NETVERSION).set(FMLNetworkConstants.NETVERSION);
|
||||
c.get().getNetworkManager().channel().attr(FMLNetworkConstants.FML_CONNECTION_DATA)
|
||||
.set(new FMLConnectionData(serverModList.getModList(), serverModList.getChannels()));
|
||||
|
||||
this.registriesToReceive = new HashSet<>(serverModList.getRegistries());
|
||||
this.registrySnapshots = Maps.newHashMap();
|
||||
LOGGER.debug(REGISTRIES, "Expecting {} registries: {}", ()->this.registriesToReceive.size(), ()->this.registriesToReceive);
|
||||
}
|
||||
|
||||
<MSG extends IntSupplier> void handleIndexedMessage(MSG message, Supplier<NetworkEvent.Context> c)
|
||||
{
|
||||
LOGGER.debug(FMLHSMARKER, "Received client indexed reply {} of type {}", message.getAsInt(), message.getClass().getName());
|
||||
boolean removed = this.sentMessages.removeIf(i-> i == message.getAsInt());
|
||||
if (!removed) {
|
||||
LOGGER.error(FMLHSMARKER, "Recieved unexpected index {} in client reply", message.getAsInt());
|
||||
}
|
||||
}
|
||||
|
||||
void handleClientModListOnServer(FMLHandshakeMessages.C2SModListReply clientModList, Supplier<NetworkEvent.Context> c)
|
||||
{
|
||||
LOGGER.debug(FMLHSMARKER, "Received client connection with modlist [{}]", String.join(", ", clientModList.getModList()));
|
||||
boolean accepted = NetworkRegistry.validateServerChannels(clientModList.getChannels());
|
||||
c.get().getNetworkManager().channel().attr(FMLNetworkConstants.FML_CONNECTION_DATA)
|
||||
.set(new FMLConnectionData(clientModList.getModList(), clientModList.getChannels()));
|
||||
c.get().setPacketHandled(true);
|
||||
if (!accepted) {
|
||||
LOGGER.error(FMLHSMARKER, "Terminating connection with client, mismatched mod list");
|
||||
c.get().getNetworkManager().disconnect(new StringTextComponent("Connection closed - mismatched mod channel list"));
|
||||
return;
|
||||
}
|
||||
LOGGER.debug(FMLHSMARKER, "Accepted client connection mod list");
|
||||
}
|
||||
|
||||
void handleRegistryMessage(final FMLHandshakeMessages.S2CRegistry registryPacket, final Supplier<NetworkEvent.Context> contextSupplier){
|
||||
LOGGER.debug(FMLHSMARKER,"Received registry packet for {}", registryPacket.getRegistryName());
|
||||
this.registriesToReceive.remove(registryPacket.getRegistryName());
|
||||
this.registrySnapshots.put(registryPacket.getRegistryName(), registryPacket.getSnapshot());
|
||||
|
||||
boolean continueHandshake = true;
|
||||
if (this.registriesToReceive.isEmpty()) {
|
||||
continueHandshake = handleRegistryLoading(contextSupplier);
|
||||
}
|
||||
// The handshake reply isn't sent until we have processed the message
|
||||
contextSupplier.get().setPacketHandled(true);
|
||||
if (!continueHandshake) {
|
||||
LOGGER.error(FMLHSMARKER, "Connection closed, not continuing handshake");
|
||||
} else {
|
||||
FMLNetworkConstants.handshakeChannel.reply(new FMLHandshakeMessages.C2SAcknowledge(), contextSupplier.get());
|
||||
}
|
||||
}
|
||||
|
||||
private boolean handleRegistryLoading(final Supplier<NetworkEvent.Context> contextSupplier) {
|
||||
// We use a countdown latch to suspend the network thread pending the client thread processing the registry data
|
||||
AtomicBoolean successfulConnection = new AtomicBoolean(false);
|
||||
CountDownLatch block = new CountDownLatch(1);
|
||||
contextSupplier.get().enqueueWork(() -> {
|
||||
LOGGER.debug(FMLHSMARKER, "Injecting registry snapshot from server.");
|
||||
final Multimap<ResourceLocation, ResourceLocation> missingData = GameData.injectSnapshot(registrySnapshots, false, false);
|
||||
LOGGER.debug(FMLHSMARKER, "Snapshot injected.");
|
||||
if (!missingData.isEmpty()) {
|
||||
LOGGER.error(FMLHSMARKER, "Missing registry data for network connection:\n{}", new AdvancedLogMessageAdapter(sb->
|
||||
missingData.forEach((reg, entry)-> sb.append("\t").append(reg).append(": ").append(entry).append('\n'))));
|
||||
}
|
||||
successfulConnection.set(missingData.isEmpty());
|
||||
block.countDown();
|
||||
});
|
||||
LOGGER.debug(FMLHSMARKER, "Waiting for registries to load.");
|
||||
try {
|
||||
block.await();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.interrupted();
|
||||
}
|
||||
if (successfulConnection.get()) {
|
||||
LOGGER.debug(FMLHSMARKER, "Registry load complete, continuing handshake.");
|
||||
} else {
|
||||
LOGGER.error(FMLHSMARKER, "Failed to load registry, closing connection.");
|
||||
this.manager.disconnect(new StringTextComponent("Failed to synchronize registry data from server, closing connection"));
|
||||
}
|
||||
return successfulConnection.get();
|
||||
}
|
||||
|
||||
void handleClientAck(final FMLHandshakeMessages.C2SAcknowledge msg, final Supplier<NetworkEvent.Context> contextSupplier) {
|
||||
LOGGER.debug(FMLHSMARKER, "Received acknowledgement from client");
|
||||
contextSupplier.get().setPacketHandled(true);
|
||||
}
|
||||
|
||||
void handleConfigSync(final FMLHandshakeMessages.S2CConfigData msg, final Supplier<NetworkEvent.Context> contextSupplier) {
|
||||
LOGGER.debug(FMLHSMARKER, "Received config sync from server");
|
||||
ConfigTracker.INSTANCE.receiveSyncedConfig(msg, contextSupplier);
|
||||
contextSupplier.get().setPacketHandled(true);
|
||||
FMLNetworkConstants.handshakeChannel.reply(new FMLHandshakeMessages.C2SAcknowledge(), contextSupplier.get());
|
||||
}
|
||||
/**
|
||||
* FML will send packets, from Server to Client, from the messages queue until the queue is drained. Each message
|
||||
* will be indexed, and placed into the "pending acknowledgement" queue.
|
||||
*
|
||||
* As indexed packets are received at the server, they will be removed from the "pending acknowledgement" queue.
|
||||
*
|
||||
* Once the pending queue is drained, this method returns true - indicating that login processing can proceed to
|
||||
* the next step.
|
||||
*
|
||||
* @return true if there is no more need to tick this login connection.
|
||||
*/
|
||||
public boolean tickServer()
|
||||
{
|
||||
if (packetPosition < messageList.size()) {
|
||||
NetworkRegistry.LoginPayload message = messageList.get(packetPosition);
|
||||
|
||||
LOGGER.debug(FMLHSMARKER, "Sending ticking packet info '{}' to '{}' sequence {}", message.getMessageContext(), message.getChannelName(), packetPosition);
|
||||
sentMessages.add(packetPosition);
|
||||
loginWrapper.sendServerToClientLoginPacket(message.getChannelName(), message.getData(), packetPosition, this.manager);
|
||||
packetPosition++;
|
||||
}
|
||||
|
||||
// we're done when sentMessages is empty
|
||||
if (sentMessages.isEmpty() && packetPosition >= messageList.size()-1) {
|
||||
// clear ourselves - we're done!
|
||||
this.manager.channel().attr(FMLNetworkConstants.FML_HANDSHAKE_HANDLER).set(null);
|
||||
LOGGER.debug(FMLHSMARKER, "Handshake complete!");
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1,278 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.network;
|
||||
|
||||
import net.minecraft.network.PacketBuffer;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import net.minecraftforge.fml.ModList;
|
||||
import net.minecraftforge.fml.loading.moddiscovery.ModInfo;
|
||||
import net.minecraftforge.registries.ForgeRegistry;
|
||||
import net.minecraftforge.registries.RegistryManager;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.IntSupplier;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
import com.google.common.collect.Maps;
|
||||
|
||||
public class FMLHandshakeMessages
|
||||
{
|
||||
static class LoginIndexedMessage implements IntSupplier
|
||||
{
|
||||
private int loginIndex;
|
||||
|
||||
void setLoginIndex(final int loginIndex) {
|
||||
this.loginIndex = loginIndex;
|
||||
}
|
||||
|
||||
int getLoginIndex() {
|
||||
return loginIndex;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getAsInt() {
|
||||
return getLoginIndex();
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Server to client "list of mods". Always first handshake message.
|
||||
*/
|
||||
public static class S2CModList extends LoginIndexedMessage
|
||||
{
|
||||
private List<String> mods;
|
||||
private Map<ResourceLocation, String> channels;
|
||||
private List<ResourceLocation> registries;
|
||||
|
||||
public S2CModList()
|
||||
{
|
||||
this.mods = ModList.get().getMods().stream().map(ModInfo::getModId).collect(Collectors.toList());
|
||||
this.channels = NetworkRegistry.buildChannelVersions();
|
||||
this.registries = RegistryManager.getRegistryNamesForSyncToClient();
|
||||
}
|
||||
|
||||
private S2CModList(List<String> mods, Map<ResourceLocation, String> channels, List<ResourceLocation> registries)
|
||||
{
|
||||
this.mods = mods;
|
||||
this.channels = channels;
|
||||
this.registries = registries;
|
||||
}
|
||||
|
||||
public static S2CModList decode(PacketBuffer input)
|
||||
{
|
||||
List<String> mods = new ArrayList<>();
|
||||
int len = input.readVarInt();
|
||||
for (int x = 0; x < len; x++)
|
||||
mods.add(input.readUtf(0x100));
|
||||
|
||||
Map<ResourceLocation, String> channels = new HashMap<>();
|
||||
len = input.readVarInt();
|
||||
for (int x = 0; x < len; x++)
|
||||
channels.put(input.readResourceLocation(), input.readUtf(0x100));
|
||||
|
||||
List<ResourceLocation> registries = new ArrayList<>();
|
||||
len = input.readVarInt();
|
||||
for (int x = 0; x < len; x++)
|
||||
registries.add(input.readResourceLocation());
|
||||
|
||||
return new S2CModList(mods, channels, registries);
|
||||
}
|
||||
|
||||
public void encode(PacketBuffer output)
|
||||
{
|
||||
output.writeVarInt(mods.size());
|
||||
mods.forEach(m -> output.writeUtf(m, 0x100));
|
||||
|
||||
output.writeVarInt(channels.size());
|
||||
channels.forEach((k, v) -> {
|
||||
output.writeResourceLocation(k);
|
||||
output.writeUtf(v, 0x100);
|
||||
});
|
||||
|
||||
output.writeVarInt(registries.size());
|
||||
registries.forEach(output::writeResourceLocation);
|
||||
}
|
||||
|
||||
public List<String> getModList() {
|
||||
return mods;
|
||||
}
|
||||
|
||||
public List<ResourceLocation> getRegistries() {
|
||||
return this.registries;
|
||||
}
|
||||
|
||||
public Map<ResourceLocation, String> getChannels() {
|
||||
return this.channels;
|
||||
}
|
||||
}
|
||||
|
||||
public static class C2SModListReply extends LoginIndexedMessage
|
||||
{
|
||||
private List<String> mods;
|
||||
private Map<ResourceLocation, String> channels;
|
||||
private Map<ResourceLocation, String> registries;
|
||||
|
||||
public C2SModListReply()
|
||||
{
|
||||
this.mods = ModList.get().getMods().stream().map(ModInfo::getModId).collect(Collectors.toList());
|
||||
this.channels = NetworkRegistry.buildChannelVersions();
|
||||
this.registries = Maps.newHashMap(); //TODO: Fill with known hashes, which requires keeping a file cache
|
||||
}
|
||||
|
||||
private C2SModListReply(List<String> mods, Map<ResourceLocation, String> channels, Map<ResourceLocation, String> registries)
|
||||
{
|
||||
this.mods = mods;
|
||||
this.channels = channels;
|
||||
this.registries = registries;
|
||||
}
|
||||
|
||||
public static C2SModListReply decode(PacketBuffer input)
|
||||
{
|
||||
List<String> mods = new ArrayList<>();
|
||||
int len = input.readVarInt();
|
||||
for (int x = 0; x < len; x++)
|
||||
mods.add(input.readUtf(0x100));
|
||||
|
||||
Map<ResourceLocation, String> channels = new HashMap<>();
|
||||
len = input.readVarInt();
|
||||
for (int x = 0; x < len; x++)
|
||||
channels.put(input.readResourceLocation(), input.readUtf(0x100));
|
||||
|
||||
Map<ResourceLocation, String> registries = new HashMap<>();
|
||||
len = input.readVarInt();
|
||||
for (int x = 0; x < len; x++)
|
||||
registries.put(input.readResourceLocation(), input.readUtf(0x100));
|
||||
|
||||
return new C2SModListReply(mods, channels, registries);
|
||||
}
|
||||
|
||||
public void encode(PacketBuffer output)
|
||||
{
|
||||
output.writeVarInt(mods.size());
|
||||
mods.forEach(m -> output.writeUtf(m, 0x100));
|
||||
|
||||
output.writeVarInt(channels.size());
|
||||
channels.forEach((k, v) -> {
|
||||
output.writeResourceLocation(k);
|
||||
output.writeUtf(v, 0x100);
|
||||
});
|
||||
|
||||
output.writeVarInt(registries.size());
|
||||
registries.forEach((k, v) -> {
|
||||
output.writeResourceLocation(k);
|
||||
output.writeUtf(v, 0x100);
|
||||
});
|
||||
}
|
||||
|
||||
public List<String> getModList() {
|
||||
return mods;
|
||||
}
|
||||
|
||||
public Map<ResourceLocation, String> getRegistries() {
|
||||
return this.registries;
|
||||
}
|
||||
|
||||
public Map<ResourceLocation, String> getChannels() {
|
||||
return this.channels;
|
||||
}
|
||||
}
|
||||
|
||||
public static class C2SAcknowledge extends LoginIndexedMessage {
|
||||
public void encode(PacketBuffer buf) {
|
||||
|
||||
}
|
||||
|
||||
public static C2SAcknowledge decode(PacketBuffer buf) {
|
||||
return new C2SAcknowledge();
|
||||
}
|
||||
}
|
||||
|
||||
public static class S2CRegistry extends LoginIndexedMessage {
|
||||
private ResourceLocation registryName;
|
||||
@Nullable
|
||||
private ForgeRegistry.Snapshot snapshot;
|
||||
|
||||
public S2CRegistry(final ResourceLocation name, @Nullable ForgeRegistry.Snapshot snapshot) {
|
||||
this.registryName = name;
|
||||
this.snapshot = snapshot;
|
||||
}
|
||||
|
||||
void encode(final PacketBuffer buffer) {
|
||||
buffer.writeResourceLocation(registryName);
|
||||
buffer.writeBoolean(hasSnapshot());
|
||||
if (hasSnapshot())
|
||||
buffer.writeBytes(snapshot.getPacketData());
|
||||
}
|
||||
|
||||
public static S2CRegistry decode(final PacketBuffer buffer) {
|
||||
ResourceLocation name = buffer.readResourceLocation();
|
||||
ForgeRegistry.Snapshot snapshot = null;
|
||||
if (buffer.readBoolean())
|
||||
snapshot = ForgeRegistry.Snapshot.read(buffer);
|
||||
return new S2CRegistry(name, snapshot);
|
||||
}
|
||||
|
||||
public ResourceLocation getRegistryName() {
|
||||
return registryName;
|
||||
}
|
||||
|
||||
public boolean hasSnapshot() {
|
||||
return snapshot != null;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public ForgeRegistry.Snapshot getSnapshot() {
|
||||
return snapshot;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static class S2CConfigData extends LoginIndexedMessage {
|
||||
private final String fileName;
|
||||
private final byte[] fileData;
|
||||
|
||||
public S2CConfigData(final String configFileName, final byte[] configFileData) {
|
||||
this.fileName = configFileName;
|
||||
this.fileData = configFileData;
|
||||
}
|
||||
|
||||
void encode(final PacketBuffer buffer) {
|
||||
buffer.writeUtf(this.fileName);
|
||||
buffer.writeByteArray(this.fileData);
|
||||
}
|
||||
|
||||
public static S2CConfigData decode(final PacketBuffer buffer) {
|
||||
return new S2CConfigData(buffer.readUtf(32767), buffer.readByteArray());
|
||||
}
|
||||
|
||||
public String getFileName() {
|
||||
return fileName;
|
||||
}
|
||||
|
||||
public byte[] getBytes() {
|
||||
return fileData;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.network;
|
||||
|
||||
import io.netty.buffer.Unpooled;
|
||||
import net.minecraft.network.NetworkManager;
|
||||
import net.minecraft.network.PacketBuffer;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import net.minecraftforge.fml.network.event.EventNetworkChannel;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
/**
|
||||
* Wrapper for custom login packets. Transforms unnamed login channel messages into channels dispatched the same
|
||||
* as regular custom packets.
|
||||
*/
|
||||
public class FMLLoginWrapper {
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
static final ResourceLocation WRAPPER = new ResourceLocation("fml:loginwrapper");
|
||||
private EventNetworkChannel wrapperChannel;
|
||||
|
||||
FMLLoginWrapper() {
|
||||
wrapperChannel = NetworkRegistry.ChannelBuilder.named(FMLLoginWrapper.WRAPPER).
|
||||
clientAcceptedVersions(a->true).
|
||||
serverAcceptedVersions(a->true).
|
||||
networkProtocolVersion(()-> FMLNetworkConstants.NETVERSION)
|
||||
.eventNetworkChannel();
|
||||
wrapperChannel.addListener(this::wrapperReceived);
|
||||
}
|
||||
|
||||
private <T extends NetworkEvent> void wrapperReceived(final T packet) {
|
||||
// we don't care about channel registration change events on this channel
|
||||
if (packet instanceof NetworkEvent.ChannelRegistrationChangeEvent) return;
|
||||
final NetworkEvent.Context wrappedContext = packet.getSource().get();
|
||||
final PacketBuffer payload = packet.getPayload();
|
||||
ResourceLocation targetNetworkReceiver = FMLNetworkConstants.FML_HANDSHAKE_RESOURCE;
|
||||
PacketBuffer data = null;
|
||||
if (payload != null) {
|
||||
targetNetworkReceiver = payload.readResourceLocation();
|
||||
final int payloadLength = payload.readVarInt();
|
||||
data = new PacketBuffer(payload.readBytes(payloadLength));
|
||||
}
|
||||
final int loginSequence = packet.getLoginIndex();
|
||||
LOGGER.debug(FMLHandshakeHandler.FMLHSMARKER, "Recieved login wrapper packet event for channel {} with index {}", targetNetworkReceiver, loginSequence);
|
||||
final NetworkEvent.Context context = new NetworkEvent.Context(wrappedContext.getNetworkManager(), wrappedContext.getDirection(), new PacketDispatcher((rl, buf) -> {
|
||||
LOGGER.debug(FMLHandshakeHandler.FMLHSMARKER, "Dispatching wrapped packet reply for channel {} with index {}", rl, loginSequence);
|
||||
wrappedContext.getPacketDispatcher().sendPacket(WRAPPER, this.wrapPacket(rl, buf));
|
||||
}));
|
||||
final NetworkEvent.LoginPayloadEvent loginPayloadEvent = new NetworkEvent.LoginPayloadEvent(data, () -> context, loginSequence);
|
||||
NetworkRegistry.findTarget(targetNetworkReceiver).ifPresent(ni -> {
|
||||
ni.dispatchLoginPacket(loginPayloadEvent);
|
||||
wrappedContext.setPacketHandled(context.getPacketHandled());
|
||||
});
|
||||
}
|
||||
|
||||
private PacketBuffer wrapPacket(final ResourceLocation rl, final PacketBuffer buf) {
|
||||
PacketBuffer pb = new PacketBuffer(Unpooled.buffer(buf.capacity()));
|
||||
pb.writeResourceLocation(rl);
|
||||
pb.writeVarInt(buf.readableBytes());
|
||||
pb.writeBytes(buf);
|
||||
return pb;
|
||||
}
|
||||
|
||||
void sendServerToClientLoginPacket(final ResourceLocation resourceLocation, final PacketBuffer buffer, final int index, final NetworkManager manager) {
|
||||
PacketBuffer pb = wrapPacket(resourceLocation, buffer);
|
||||
manager.send(NetworkDirection.LOGIN_TO_CLIENT.buildPacket(Pair.of(pb, index), WRAPPER).getThis());
|
||||
}
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.network;
|
||||
|
||||
import io.netty.buffer.Unpooled;
|
||||
import io.netty.util.Attribute;
|
||||
import net.minecraft.network.IPacket;
|
||||
import net.minecraft.network.NetworkManager;
|
||||
import net.minecraft.network.PacketBuffer;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashSet;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class FMLMCRegisterPacketHandler {
|
||||
public static final FMLMCRegisterPacketHandler INSTANCE = new FMLMCRegisterPacketHandler();
|
||||
|
||||
public static class ChannelList {
|
||||
private Set<ResourceLocation> locations = new HashSet<>();
|
||||
|
||||
public void updateFrom(final Supplier<NetworkEvent.Context> source, PacketBuffer buffer, final NetworkEvent.RegistrationChangeType changeType) {
|
||||
byte[] data = new byte[Math.max(buffer.readableBytes(), 0)];
|
||||
buffer.readBytes(data);
|
||||
Set<ResourceLocation> oldLocations = this.locations;
|
||||
this.locations = bytesToResLocation(data);
|
||||
// ensure all locations receive updates, old and new.
|
||||
oldLocations.addAll(this.locations);
|
||||
oldLocations.stream()
|
||||
.map(NetworkRegistry::findTarget)
|
||||
.filter(Optional::isPresent)
|
||||
.map(Optional::get)
|
||||
.forEach(t->t.dispatchEvent(new NetworkEvent.ChannelRegistrationChangeEvent(source, changeType)));
|
||||
}
|
||||
|
||||
byte[] toByteArray() {
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
for (ResourceLocation rl : locations) {
|
||||
try {
|
||||
bos.write(rl.toString().getBytes(StandardCharsets.UTF_8));
|
||||
bos.write(0);
|
||||
} catch (IOException e) {
|
||||
// fake IOE
|
||||
}
|
||||
}
|
||||
return bos.toByteArray();
|
||||
}
|
||||
|
||||
private Set<ResourceLocation> bytesToResLocation(byte[] all) {
|
||||
HashSet<ResourceLocation> rl = new HashSet<>();
|
||||
int last = 0;
|
||||
for (int cur = 0; cur < all.length; cur++) {
|
||||
if (all[cur] == '\0') {
|
||||
String s = new String(all, last, cur - last, StandardCharsets.UTF_8);
|
||||
rl.add(new ResourceLocation(s));
|
||||
last = cur + 1;
|
||||
}
|
||||
}
|
||||
return rl;
|
||||
}
|
||||
}
|
||||
|
||||
public void addChannels(Set<ResourceLocation> locations, NetworkManager manager) {
|
||||
getFrom(manager).locations.addAll(locations);
|
||||
}
|
||||
|
||||
void registerListener(NetworkEvent evt) {
|
||||
final ChannelList channelList = getFrom(evt);
|
||||
channelList.updateFrom(evt.getSource(), evt.getPayload(), NetworkEvent.RegistrationChangeType.REGISTER);
|
||||
evt.getSource().get().setPacketHandled(true);
|
||||
}
|
||||
|
||||
void unregisterListener(NetworkEvent evt) {
|
||||
final ChannelList channelList = getFrom(evt);
|
||||
channelList.updateFrom(evt.getSource(), evt.getPayload(), NetworkEvent.RegistrationChangeType.UNREGISTER);
|
||||
evt.getSource().get().setPacketHandled(true);
|
||||
}
|
||||
|
||||
private static ChannelList getFrom(NetworkManager manager) {
|
||||
return fromAttr(manager.channel().attr(FMLNetworkConstants.FML_MC_REGISTRY));
|
||||
}
|
||||
|
||||
private static ChannelList getFrom(NetworkEvent event) {
|
||||
return fromAttr(event.getSource().get().attr(FMLNetworkConstants.FML_MC_REGISTRY));
|
||||
}
|
||||
|
||||
private static ChannelList fromAttr(Attribute<ChannelList> attr) {
|
||||
attr.setIfAbsent(new ChannelList());
|
||||
return attr.get();
|
||||
}
|
||||
|
||||
public void sendRegistry(NetworkManager manager, final NetworkDirection dir) {
|
||||
PacketBuffer pb = new PacketBuffer(Unpooled.buffer());
|
||||
pb.writeBytes(getFrom(manager).toByteArray());
|
||||
final ICustomPacket<IPacket<?>> iPacketICustomPacket = dir.buildPacket(Pair.of(pb, 0), FMLNetworkConstants.MC_REGISTER_RESOURCE);
|
||||
manager.send(iPacketICustomPacket.getThis());
|
||||
}
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.network;
|
||||
|
||||
import io.netty.util.AttributeKey;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import net.minecraftforge.fml.network.event.EventNetworkChannel;
|
||||
import net.minecraftforge.fml.network.simple.SimpleChannel;
|
||||
import org.apache.logging.log4j.Marker;
|
||||
import org.apache.logging.log4j.MarkerManager;
|
||||
|
||||
import java.util.List;
|
||||
/**
|
||||
* Constants related to networking
|
||||
*/
|
||||
public class FMLNetworkConstants
|
||||
{
|
||||
public static final String FMLNETMARKER = "FML";
|
||||
public static final int FMLNETVERSION = 2;
|
||||
public static final String NETVERSION = FMLNETMARKER + FMLNETVERSION;
|
||||
public static final String NOVERSION = "NONE";
|
||||
|
||||
static final Marker NETWORK = MarkerManager.getMarker("FMLNETWORK");
|
||||
static final AttributeKey<String> FML_NETVERSION = AttributeKey.valueOf("fml:netversion");
|
||||
static final AttributeKey<FMLHandshakeHandler> FML_HANDSHAKE_HANDLER = AttributeKey.valueOf("fml:handshake");
|
||||
static final AttributeKey<FMLMCRegisterPacketHandler.ChannelList> FML_MC_REGISTRY = AttributeKey.valueOf("minecraft:netregistry");
|
||||
static final AttributeKey<FMLConnectionData> FML_CONNECTION_DATA = AttributeKey.valueOf("fml:conndata");
|
||||
static final ResourceLocation FML_HANDSHAKE_RESOURCE = new ResourceLocation("fml:handshake");
|
||||
static final ResourceLocation FML_PLAY_RESOURCE = new ResourceLocation("fml:play");
|
||||
static final ResourceLocation MC_REGISTER_RESOURCE = new ResourceLocation("minecraft:register");
|
||||
static final ResourceLocation MC_UNREGISTER_RESOURCE = new ResourceLocation("minecraft:unregister");
|
||||
static final SimpleChannel handshakeChannel = NetworkInitialization.getHandshakeChannel();
|
||||
static final SimpleChannel playChannel = NetworkInitialization.getPlayChannel();
|
||||
static final List<EventNetworkChannel> mcRegChannels = NetworkInitialization.buildMCRegistrationChannels();
|
||||
/**
|
||||
* Return this value in your {@link net.minecraftforge.fml.ExtensionPoint#DISPLAYTEST} function to be ignored.
|
||||
*/
|
||||
public static final String IGNORESERVERONLY = "OHNOES\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31\uD83D\uDE31";
|
||||
|
||||
public static String init() {
|
||||
return FMLNetworkConstants.NETVERSION;
|
||||
}
|
||||
}
|
||||
@@ -1,437 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.network;
|
||||
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.collect.Maps;
|
||||
import com.google.common.collect.Multimap;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.IHasContainer;
|
||||
import net.minecraft.client.gui.ScreenManager;
|
||||
import net.minecraft.client.gui.screen.Screen;
|
||||
import net.minecraft.client.world.ClientWorld;
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.entity.EntityType;
|
||||
import net.minecraft.inventory.container.Container;
|
||||
import net.minecraft.inventory.container.ContainerType;
|
||||
import net.minecraft.network.PacketBuffer;
|
||||
import net.minecraft.tags.ITag;
|
||||
import net.minecraft.tags.ITagCollection;
|
||||
import net.minecraft.tags.ITagCollectionSupplier;
|
||||
import net.minecraft.tags.TagRegistryManager;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import net.minecraft.util.math.MathHelper;
|
||||
import net.minecraft.util.math.vector.Vector3d;
|
||||
import net.minecraft.util.text.TranslationTextComponent;
|
||||
import net.minecraft.world.World;
|
||||
import net.minecraftforge.common.ForgeTagHandler;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.event.TagsUpdatedEvent;
|
||||
import net.minecraftforge.fml.LogicalSidedProvider;
|
||||
import net.minecraft.util.registry.Registry;
|
||||
import net.minecraft.util.text.ITextComponent;
|
||||
import net.minecraftforge.fml.common.registry.IEntityAdditionalSpawnData;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Supplier;
|
||||
import net.minecraftforge.registries.IForgeRegistry;
|
||||
import net.minecraftforge.registries.IForgeRegistryEntry;
|
||||
import net.minecraftforge.registries.RegistryManager;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
public class FMLPlayMessages
|
||||
{
|
||||
/**
|
||||
* Used to spawn a custom entity without the same restrictions as
|
||||
* {@link net.minecraft.network.play.server.SSpawnObjectPacket} or {@link net.minecraft.network.play.server.SSpawnMobPacket}
|
||||
*
|
||||
* To customize how your entity is created clientside (instead of using the default factory provided to the {@link EntityType})
|
||||
* see {@link EntityType.Builder#setCustomClientFactory}.
|
||||
*/
|
||||
public static class SpawnEntity
|
||||
{
|
||||
private final Entity entity;
|
||||
private final int typeId;
|
||||
private final int entityId;
|
||||
private final UUID uuid;
|
||||
private final double posX, posY, posZ;
|
||||
private final byte pitch, yaw, headYaw;
|
||||
private final int velX, velY, velZ;
|
||||
private final PacketBuffer buf;
|
||||
|
||||
SpawnEntity(Entity e)
|
||||
{
|
||||
this.entity = e;
|
||||
this.typeId = Registry.ENTITY_TYPE.getId(e.getType()); //TODO: Codecs
|
||||
this.entityId = e.getId();
|
||||
this.uuid = e.getUUID();
|
||||
this.posX = e.getX();
|
||||
this.posY = e.getY();
|
||||
this.posZ = e.getZ();
|
||||
this.pitch = (byte) MathHelper.floor(e.xRot * 256.0F / 360.0F);
|
||||
this.yaw = (byte) MathHelper.floor(e.yRot * 256.0F / 360.0F);
|
||||
this.headYaw = (byte) (e.getYHeadRot() * 256.0F / 360.0F);
|
||||
Vector3d vec3d = e.getDeltaMovement();
|
||||
double d1 = MathHelper.clamp(vec3d.x, -3.9D, 3.9D);
|
||||
double d2 = MathHelper.clamp(vec3d.y, -3.9D, 3.9D);
|
||||
double d3 = MathHelper.clamp(vec3d.z, -3.9D, 3.9D);
|
||||
this.velX = (int)(d1 * 8000.0D);
|
||||
this.velY = (int)(d2 * 8000.0D);
|
||||
this.velZ = (int)(d3 * 8000.0D);
|
||||
this.buf = null;
|
||||
}
|
||||
|
||||
private SpawnEntity(int typeId, int entityId, UUID uuid, double posX, double posY, double posZ,
|
||||
byte pitch, byte yaw, byte headYaw, int velX, int velY, int velZ, PacketBuffer buf)
|
||||
{
|
||||
this.entity = null;
|
||||
this.typeId = typeId;
|
||||
this.entityId = entityId;
|
||||
this.uuid = uuid;
|
||||
this.posX = posX;
|
||||
this.posY = posY;
|
||||
this.posZ = posZ;
|
||||
this.pitch = pitch;
|
||||
this.yaw = yaw;
|
||||
this.headYaw = headYaw;
|
||||
this.velX = velX;
|
||||
this.velY = velY;
|
||||
this.velZ = velZ;
|
||||
this.buf = buf;
|
||||
}
|
||||
|
||||
public static void encode(SpawnEntity msg, PacketBuffer buf)
|
||||
{
|
||||
buf.writeVarInt(msg.typeId);
|
||||
buf.writeInt(msg.entityId);
|
||||
buf.writeLong(msg.uuid.getMostSignificantBits());
|
||||
buf.writeLong(msg.uuid.getLeastSignificantBits());
|
||||
buf.writeDouble(msg.posX);
|
||||
buf.writeDouble(msg.posY);
|
||||
buf.writeDouble(msg.posZ);
|
||||
buf.writeByte(msg.pitch);
|
||||
buf.writeByte(msg.yaw);
|
||||
buf.writeByte(msg.headYaw);
|
||||
buf.writeShort(msg.velX);
|
||||
buf.writeShort(msg.velY);
|
||||
buf.writeShort(msg.velZ);
|
||||
if (msg.entity instanceof IEntityAdditionalSpawnData)
|
||||
{
|
||||
((IEntityAdditionalSpawnData) msg.entity).writeSpawnData(buf);
|
||||
}
|
||||
}
|
||||
|
||||
public static SpawnEntity decode(PacketBuffer buf)
|
||||
{
|
||||
return new SpawnEntity(
|
||||
buf.readVarInt(),
|
||||
buf.readInt(),
|
||||
new UUID(buf.readLong(), buf.readLong()),
|
||||
buf.readDouble(), buf.readDouble(), buf.readDouble(),
|
||||
buf.readByte(), buf.readByte(), buf.readByte(),
|
||||
buf.readShort(), buf.readShort(), buf.readShort(),
|
||||
buf
|
||||
);
|
||||
}
|
||||
|
||||
public static void handle(SpawnEntity msg, Supplier<NetworkEvent.Context> ctx)
|
||||
{
|
||||
ctx.get().enqueueWork(() -> {
|
||||
EntityType<?> type = Registry.ENTITY_TYPE.byId(msg.typeId);
|
||||
if (type == null)
|
||||
{
|
||||
throw new RuntimeException(String.format("Could not spawn entity (id %d) with unknown type at (%f, %f, %f)", msg.entityId, msg.posX, msg.posY, msg.posZ));
|
||||
}
|
||||
|
||||
Optional<World> world = LogicalSidedProvider.CLIENTWORLD.get(ctx.get().getDirection().getReceptionSide());
|
||||
Entity e = world.map(w->type.customClientSpawn(msg, w)).orElse(null);
|
||||
if (e == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
e.setPacketCoordinates(msg.posX, msg.posY, msg.posZ);
|
||||
e.absMoveTo(msg.posX, msg.posY, msg.posZ, (msg.yaw * 360) / 256.0F, (msg.pitch * 360) / 256.0F);
|
||||
e.setYHeadRot((msg.headYaw * 360) / 256.0F);
|
||||
e.setYBodyRot((msg.headYaw * 360) / 256.0F);
|
||||
|
||||
e.setId(msg.entityId);
|
||||
e.setUUID(msg.uuid);
|
||||
world.filter(ClientWorld.class::isInstance).ifPresent(w->((ClientWorld)w).putNonPlayerEntity(msg.entityId, e));
|
||||
e.lerpMotion(msg.velX / 8000.0, msg.velY / 8000.0, msg.velZ / 8000.0);
|
||||
if (e instanceof IEntityAdditionalSpawnData)
|
||||
{
|
||||
((IEntityAdditionalSpawnData) e).readSpawnData(msg.buf);
|
||||
}
|
||||
});
|
||||
ctx.get().setPacketHandled(true);
|
||||
}
|
||||
|
||||
public Entity getEntity()
|
||||
{
|
||||
return entity;
|
||||
}
|
||||
|
||||
public int getTypeId()
|
||||
{
|
||||
return typeId;
|
||||
}
|
||||
|
||||
public int getEntityId()
|
||||
{
|
||||
return entityId;
|
||||
}
|
||||
|
||||
public UUID getUuid()
|
||||
{
|
||||
return uuid;
|
||||
}
|
||||
|
||||
public double getPosX()
|
||||
{
|
||||
return posX;
|
||||
}
|
||||
|
||||
public double getPosY()
|
||||
{
|
||||
return posY;
|
||||
}
|
||||
|
||||
public double getPosZ()
|
||||
{
|
||||
return posZ;
|
||||
}
|
||||
|
||||
public byte getPitch()
|
||||
{
|
||||
return pitch;
|
||||
}
|
||||
|
||||
public byte getYaw()
|
||||
{
|
||||
return yaw;
|
||||
}
|
||||
|
||||
public byte getHeadYaw()
|
||||
{
|
||||
return headYaw;
|
||||
}
|
||||
|
||||
public int getVelX()
|
||||
{
|
||||
return velX;
|
||||
}
|
||||
|
||||
public int getVelY()
|
||||
{
|
||||
return velY;
|
||||
}
|
||||
|
||||
public int getVelZ()
|
||||
{
|
||||
return velZ;
|
||||
}
|
||||
|
||||
public PacketBuffer getAdditionalData()
|
||||
{
|
||||
return buf;
|
||||
}
|
||||
}
|
||||
|
||||
public static class OpenContainer
|
||||
{
|
||||
private final int id;
|
||||
private final int windowId;
|
||||
private final ITextComponent name;
|
||||
private final PacketBuffer additionalData;
|
||||
|
||||
OpenContainer(ContainerType<?> id, int windowId, ITextComponent name, PacketBuffer additionalData)
|
||||
{
|
||||
this(Registry.MENU.getId(id), windowId, name, additionalData);
|
||||
}
|
||||
|
||||
private OpenContainer(int id, int windowId, ITextComponent name, PacketBuffer additionalData)
|
||||
{
|
||||
this.id = id;
|
||||
this.windowId = windowId;
|
||||
this.name = name;
|
||||
this.additionalData = additionalData;
|
||||
}
|
||||
|
||||
public static void encode(OpenContainer msg, PacketBuffer buf)
|
||||
{
|
||||
buf.writeVarInt(msg.id);
|
||||
buf.writeVarInt(msg.windowId);
|
||||
buf.writeComponent(msg.name);
|
||||
buf.writeByteArray(msg.additionalData.readByteArray());
|
||||
}
|
||||
|
||||
public static OpenContainer decode(PacketBuffer buf)
|
||||
{
|
||||
return new OpenContainer(buf.readVarInt(), buf.readVarInt(), buf.readComponent(), new PacketBuffer(Unpooled.wrappedBuffer(buf.readByteArray(32600))));
|
||||
}
|
||||
|
||||
public static void handle(OpenContainer msg, Supplier<NetworkEvent.Context> ctx)
|
||||
{
|
||||
ctx.get().enqueueWork(() -> {
|
||||
ScreenManager.getScreenFactory(msg.getType(), Minecraft.getInstance(), msg.getWindowId(), msg.getName())
|
||||
.ifPresent(f -> {
|
||||
Container c = msg.getType().create(msg.getWindowId(), Minecraft.getInstance().player.inventory, msg.getAdditionalData());
|
||||
@SuppressWarnings("unchecked")
|
||||
Screen s = ((ScreenManager.IScreenFactory<Container, ?>)f).create(c, Minecraft.getInstance().player.inventory, msg.getName());
|
||||
Minecraft.getInstance().player.containerMenu = ((IHasContainer<?>)s).getMenu();
|
||||
Minecraft.getInstance().setScreen(s);
|
||||
});
|
||||
});
|
||||
ctx.get().setPacketHandled(true);
|
||||
}
|
||||
|
||||
public final ContainerType<?> getType() {
|
||||
return Registry.MENU.byId(this.id);
|
||||
}
|
||||
|
||||
public int getWindowId() {
|
||||
return windowId;
|
||||
}
|
||||
|
||||
public ITextComponent getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public PacketBuffer getAdditionalData() {
|
||||
return additionalData;
|
||||
}
|
||||
}
|
||||
|
||||
public static class SyncCustomTagTypes
|
||||
{
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
private final Map<ResourceLocation, ITagCollection<?>> customTagTypeCollections;
|
||||
|
||||
SyncCustomTagTypes(Map<ResourceLocation, ITagCollection<?>> customTagTypeCollections)
|
||||
{
|
||||
this.customTagTypeCollections = customTagTypeCollections;
|
||||
}
|
||||
|
||||
public Map<ResourceLocation, ITagCollection<?>> getCustomTagTypes()
|
||||
{
|
||||
return customTagTypeCollections;
|
||||
}
|
||||
|
||||
public static void encode(SyncCustomTagTypes msg, PacketBuffer buf)
|
||||
{
|
||||
buf.writeVarInt(msg.customTagTypeCollections.size());
|
||||
msg.customTagTypeCollections.forEach((registryName, modded) -> forgeTagCollectionWrite(buf, registryName, modded.getAllTags()));
|
||||
}
|
||||
|
||||
private static <T> void forgeTagCollectionWrite(PacketBuffer buf, ResourceLocation registryName, Map<ResourceLocation, ITag<T>> tags)
|
||||
{
|
||||
buf.writeResourceLocation(registryName);
|
||||
buf.writeVarInt(tags.size());
|
||||
tags.forEach((name, tag) -> {
|
||||
buf.writeResourceLocation(name);
|
||||
List<T> elements = tag.getValues();
|
||||
buf.writeVarInt(elements.size());
|
||||
for (T element : elements)
|
||||
{
|
||||
buf.writeResourceLocation(((IForgeRegistryEntry<?>) element).getRegistryName());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static SyncCustomTagTypes decode(PacketBuffer buf)
|
||||
{
|
||||
ImmutableMap.Builder<ResourceLocation, ITagCollection<?>> builder = ImmutableMap.builder();
|
||||
int size = buf.readVarInt();
|
||||
for (int i = 0; i < size; i++)
|
||||
{
|
||||
ResourceLocation regName = buf.readResourceLocation();
|
||||
IForgeRegistry<?> registry = RegistryManager.ACTIVE.getRegistry(regName);
|
||||
if (registry != null)
|
||||
{
|
||||
builder.put(regName, readTagCollection(buf, registry));
|
||||
}
|
||||
}
|
||||
return new SyncCustomTagTypes(builder.build());
|
||||
}
|
||||
|
||||
private static <T extends IForgeRegistryEntry<T>> ITagCollection<T> readTagCollection(PacketBuffer buf, IForgeRegistry<T> registry)
|
||||
{
|
||||
Map<ResourceLocation, ITag<T>> tags = Maps.newHashMap();
|
||||
int totalTags = buf.readVarInt();
|
||||
for (int i = 0; i < totalTags; i++)
|
||||
{
|
||||
ImmutableSet.Builder<T> elementBuilder = ImmutableSet.builder();
|
||||
ResourceLocation name = buf.readResourceLocation();
|
||||
int totalElements = buf.readVarInt();
|
||||
for (int j = 0; j < totalElements; j++)
|
||||
{
|
||||
T element = registry.getValue(buf.readResourceLocation());
|
||||
if (element != null)
|
||||
{
|
||||
elementBuilder.add(element);
|
||||
}
|
||||
}
|
||||
tags.put(name, ITag.fromSet(elementBuilder.build()));
|
||||
}
|
||||
return ITagCollection.of(tags);
|
||||
}
|
||||
|
||||
public static void handle(SyncCustomTagTypes msg, Supplier<NetworkEvent.Context> ctx)
|
||||
{
|
||||
ctx.get().enqueueWork(() -> {
|
||||
if (Minecraft.getInstance().level != null)
|
||||
{
|
||||
ITagCollectionSupplier tagCollectionSupplier = Minecraft.getInstance().level.getTagManager();
|
||||
//Validate that all the tags exist using the tag type collections from the packet
|
||||
// We mimic vanilla in that we validate before updating the actual stored tags so that it can gracefully fallback
|
||||
// to the last working set of tags
|
||||
//Note: We gracefully ignore any tag types the server may have that we don't as they won't be in our tag registry
|
||||
// so they won't be validated
|
||||
//Override and use the tags from the packet to test for validation before we actually set them
|
||||
Multimap<ResourceLocation, ResourceLocation> missingTags = TagRegistryManager.getAllMissingTags(ForgeTagHandler.withSpecificCustom(tagCollectionSupplier, msg.customTagTypeCollections));
|
||||
if (missingTags.isEmpty())
|
||||
{
|
||||
//If we have no missing tags, update the custom tag types
|
||||
ForgeTagHandler.updateCustomTagTypes(msg);
|
||||
if (!ctx.get().getNetworkManager().isMemoryConnection())
|
||||
{
|
||||
//And if everything hasn't already been set due to being in single player
|
||||
// Fetch and update the custom tag types. We skip vanilla tag types as they have already been fetched
|
||||
// And fire an event that the custom tag types have been updated
|
||||
TagRegistryManager.fetchCustomTagTypes(tagCollectionSupplier);
|
||||
MinecraftForge.EVENT_BUS.post(new TagsUpdatedEvent.CustomTagTypes(tagCollectionSupplier));
|
||||
}
|
||||
} else {
|
||||
LOGGER.warn("Incomplete server tags, disconnecting. Missing: {}", missingTags);
|
||||
ctx.get().getNetworkManager().disconnect(new TranslationTextComponent("multiplayer.disconnect.missing_tags"));
|
||||
}
|
||||
}
|
||||
});
|
||||
ctx.get().setPacketHandled(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,169 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.network;
|
||||
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonDeserializationContext;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonSerializationContext;
|
||||
import com.google.gson.JsonSyntaxException;
|
||||
import net.minecraft.util.JSONUtils;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import net.minecraftforge.fml.ExtensionPoint;
|
||||
import net.minecraftforge.fml.ModList;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import static net.minecraftforge.fml.network.FMLNetworkConstants.NETWORK;
|
||||
|
||||
/**
|
||||
* {
|
||||
* "fmlNetworkVersion" : FMLNETVERSION,
|
||||
* "channels": [
|
||||
* {
|
||||
* "res": "fml:handshake",
|
||||
* "version": "1.2.3.4",
|
||||
* "required": true
|
||||
* }
|
||||
* ],
|
||||
* "mods": [
|
||||
* {
|
||||
* "modid": "modid",
|
||||
* "modmarker": "<somestring>"
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
*
|
||||
*/
|
||||
public class FMLStatusPing {
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
private static final int CHANNEL_TRUNCATE_LIMIT = 150;
|
||||
private static final int MOD_TRUNCATE_LIMIT = 150;
|
||||
private static volatile boolean warnedAboutTruncation = false;
|
||||
|
||||
private transient Map<ResourceLocation, Pair<String, Boolean>> channels;
|
||||
private transient Map<String, String> mods;
|
||||
private transient int fmlNetworkVer;
|
||||
private transient boolean truncated;
|
||||
|
||||
public FMLStatusPing() {
|
||||
this.channels = NetworkRegistry.buildChannelVersionsForListPing();
|
||||
this.mods = new HashMap<>();
|
||||
ModList.get().forEachModContainer((modid, mc) ->
|
||||
mods.put(modid, mc.getCustomExtension(ExtensionPoint.DISPLAYTEST).
|
||||
map(Pair::getLeft).map(Supplier::get).orElse(FMLNetworkConstants.IGNORESERVERONLY)));
|
||||
this.fmlNetworkVer = FMLNetworkConstants.FMLNETVERSION;
|
||||
this.truncated = false;
|
||||
}
|
||||
|
||||
private FMLStatusPing(Map<ResourceLocation, Pair<String, Boolean>> deserialized, Map<String,String> modMarkers, int fmlNetVer, boolean truncated) {
|
||||
this.channels = ImmutableMap.copyOf(deserialized);
|
||||
this.mods = modMarkers;
|
||||
this.fmlNetworkVer = fmlNetVer;
|
||||
this.truncated = truncated;
|
||||
}
|
||||
|
||||
public static class Serializer {
|
||||
public static FMLStatusPing deserialize(JsonObject forgeData, JsonDeserializationContext ctx) {
|
||||
try {
|
||||
final Map<ResourceLocation, Pair<String, Boolean>> channels = StreamSupport.stream(JSONUtils.getAsJsonArray(forgeData, "channels").spliterator(), false).
|
||||
map(JsonElement::getAsJsonObject).
|
||||
collect(Collectors.toMap(jo -> new ResourceLocation(JSONUtils.getAsString(jo, "res")),
|
||||
jo -> Pair.of(JSONUtils.getAsString(jo, "version"), JSONUtils.getAsBoolean(jo, "required")))
|
||||
);
|
||||
|
||||
final Map<String, String> mods = StreamSupport.stream(JSONUtils.getAsJsonArray(forgeData, "mods").spliterator(), false).
|
||||
map(JsonElement::getAsJsonObject).
|
||||
collect(Collectors.toMap(jo -> JSONUtils.getAsString(jo, "modId"), jo->JSONUtils.getAsString(jo, "modmarker")));
|
||||
|
||||
final int remoteFMLVersion = JSONUtils.getAsInt(forgeData, "fmlNetworkVersion");
|
||||
final boolean truncated = JSONUtils.getAsBoolean(forgeData, "truncated", false);
|
||||
return new FMLStatusPing(channels, mods, remoteFMLVersion, truncated);
|
||||
} catch (JsonSyntaxException e) {
|
||||
LOGGER.debug(NETWORK, "Encountered an error parsing status ping data", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static JsonObject serialize(FMLStatusPing forgeData, JsonSerializationContext ctx) {
|
||||
JsonObject obj = new JsonObject();
|
||||
JsonArray channels = new JsonArray();
|
||||
boolean truncated = forgeData.channels.size() > CHANNEL_TRUNCATE_LIMIT || forgeData.mods.size() > MOD_TRUNCATE_LIMIT;
|
||||
if (truncated && !warnedAboutTruncation)
|
||||
{
|
||||
warnedAboutTruncation = true;
|
||||
LOGGER.warn("Heuristically truncating mod and/or network channel list in server status ping packet. Compatibility report " +
|
||||
"in the multiplayer screen may be inaccurate.");
|
||||
}
|
||||
|
||||
forgeData.channels.entrySet().stream().limit(CHANNEL_TRUNCATE_LIMIT).forEach(entry -> {
|
||||
ResourceLocation namespace = entry.getKey();
|
||||
Pair<String, Boolean> version = entry.getValue();
|
||||
JsonObject mi = new JsonObject();
|
||||
mi.addProperty("res", namespace.toString());
|
||||
mi.addProperty("version", version.getLeft());
|
||||
mi.addProperty("required", version.getRight());
|
||||
channels.add(mi);
|
||||
});
|
||||
|
||||
obj.add("channels", channels);
|
||||
|
||||
JsonArray modTestValues = new JsonArray();
|
||||
forgeData.mods.entrySet().stream().limit(MOD_TRUNCATE_LIMIT).forEach(entry -> {
|
||||
String modId = entry.getKey();
|
||||
String value = entry.getValue();
|
||||
JsonObject mi = new JsonObject();
|
||||
mi.addProperty("modId", modId);
|
||||
mi.addProperty("modmarker", value);
|
||||
modTestValues.add(mi);
|
||||
});
|
||||
obj.add("mods", modTestValues);
|
||||
obj.addProperty("fmlNetworkVersion", forgeData.fmlNetworkVer);
|
||||
obj.addProperty("truncated", truncated);
|
||||
return obj;
|
||||
}
|
||||
}
|
||||
|
||||
public Map<ResourceLocation, Pair<String, Boolean>> getRemoteChannels() {
|
||||
return this.channels;
|
||||
}
|
||||
|
||||
public Map<String,String> getRemoteModData() {
|
||||
return mods;
|
||||
}
|
||||
|
||||
public int getFMLNetworkVersion() {
|
||||
return fmlNetworkVer;
|
||||
}
|
||||
|
||||
public boolean isTruncated()
|
||||
{
|
||||
return truncated;
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.network;
|
||||
|
||||
import net.minecraft.entity.player.PlayerInventory;
|
||||
import net.minecraft.inventory.container.Container;
|
||||
import net.minecraft.inventory.container.ContainerType;
|
||||
import net.minecraft.network.PacketBuffer;
|
||||
|
||||
public interface IContainerFactory<T extends Container> extends ContainerType.IFactory<T>
|
||||
{
|
||||
T create(int windowId, PlayerInventory inv, PacketBuffer data);
|
||||
|
||||
@Override
|
||||
default T create(int p_create_1_, PlayerInventory p_create_2_)
|
||||
{
|
||||
return create(p_create_1_, p_create_2_, null);
|
||||
}
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.network;
|
||||
|
||||
import it.unimi.dsi.fastutil.objects.Reference2ReferenceArrayMap;
|
||||
import net.minecraft.network.IPacket;
|
||||
import net.minecraft.network.PacketBuffer;
|
||||
import net.minecraft.network.login.client.CCustomPayloadLoginPacket;
|
||||
import net.minecraft.network.login.server.SCustomPayloadLoginPacket;
|
||||
import net.minecraft.network.play.client.CCustomPayloadPacket;
|
||||
import net.minecraft.network.play.server.SCustomPayloadPlayPacket;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import net.minecraftforge.fml.unsafe.UnsafeHacks;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.Arrays;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public interface ICustomPacket<T extends IPacket<?>> {
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
enum Fields {
|
||||
CPACKETCUSTOMPAYLOAD(CCustomPayloadPacket.class),
|
||||
SPACKETCUSTOMPAYLOAD(SCustomPayloadPlayPacket.class),
|
||||
CPACKETCUSTOMLOGIN(CCustomPayloadLoginPacket.class),
|
||||
SPACKETCUSTOMLOGIN(SCustomPayloadLoginPacket.class),
|
||||
;
|
||||
|
||||
static final Reference2ReferenceArrayMap<Class<?>, Fields> lookup;
|
||||
static {
|
||||
lookup = Stream.of(values()).
|
||||
collect(Collectors.toMap(Fields::getClazz, Function.identity(), (m1, m2)->m1, Reference2ReferenceArrayMap::new));
|
||||
}
|
||||
|
||||
private final Class<?> clazz;
|
||||
|
||||
final Optional<Field> data;
|
||||
final Optional<Field> channel;
|
||||
final Optional<Field> index;
|
||||
|
||||
Fields(Class<?> customPacketClass)
|
||||
{
|
||||
this.clazz = customPacketClass;
|
||||
Field[] fields = customPacketClass.getDeclaredFields();
|
||||
data = Arrays.stream(fields).filter(f-> !Modifier.isStatic(f.getModifiers()) && f.getType() == PacketBuffer.class).findFirst();
|
||||
channel = Arrays.stream(fields).filter(f->!Modifier.isStatic(f.getModifiers()) && f.getType() == ResourceLocation.class).findFirst();
|
||||
index = Arrays.stream(fields).filter(f->!Modifier.isStatic(f.getModifiers()) && f.getType() == int.class).findFirst();
|
||||
}
|
||||
|
||||
private Class<?> getClazz()
|
||||
{
|
||||
return clazz;
|
||||
}
|
||||
}
|
||||
|
||||
default PacketBuffer getInternalData() {
|
||||
return Fields.lookup.get(this.getClass()).data.map(f->UnsafeHacks.<PacketBuffer>getField(f, this)).orElse(null);
|
||||
}
|
||||
|
||||
default ResourceLocation getName() {
|
||||
return Fields.lookup.get(this.getClass()).channel.map(f->UnsafeHacks.<ResourceLocation>getField(f, this)).orElse(FMLLoginWrapper.WRAPPER);
|
||||
}
|
||||
|
||||
default int getIndex() {
|
||||
return Fields.lookup.get(this.getClass()).index.map(f->UnsafeHacks.getIntField(f, this)).orElse(Integer.MIN_VALUE);
|
||||
}
|
||||
|
||||
default void setData(PacketBuffer buffer) {
|
||||
Fields.lookup.get(this.getClass()).data.ifPresent(f->UnsafeHacks.setField(f, this, buffer));
|
||||
}
|
||||
|
||||
default void setName(ResourceLocation channelName) {
|
||||
Fields.lookup.get(this.getClass()).channel.ifPresent(f->UnsafeHacks.setField(f, this, channelName));
|
||||
}
|
||||
|
||||
default void setIndex(int index) {
|
||||
Fields.lookup.get(this.getClass()).index.ifPresent(f->UnsafeHacks.setIntField(f, this, index));
|
||||
}
|
||||
|
||||
default NetworkDirection getDirection() {
|
||||
return NetworkDirection.directionFor(this.getClass());
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
default T getThis() {
|
||||
return (T)this;
|
||||
}
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.network;
|
||||
|
||||
import it.unimi.dsi.fastutil.objects.Reference2ReferenceArrayMap;
|
||||
import net.minecraft.network.IPacket;
|
||||
import net.minecraft.network.PacketBuffer;
|
||||
import net.minecraft.network.login.client.CCustomPayloadLoginPacket;
|
||||
import net.minecraft.network.login.server.SCustomPayloadLoginPacket;
|
||||
import net.minecraft.network.play.client.CCustomPayloadPacket;
|
||||
import net.minecraft.network.play.server.SCustomPayloadPlayPacket;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import net.minecraftforge.fml.LogicalSide;
|
||||
import net.minecraftforge.fml.unsafe.UnsafeHacks;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public enum NetworkDirection
|
||||
{
|
||||
PLAY_TO_SERVER(NetworkEvent.ClientCustomPayloadEvent::new, LogicalSide.CLIENT, CCustomPayloadPacket.class, 1),
|
||||
PLAY_TO_CLIENT(NetworkEvent.ServerCustomPayloadEvent::new, LogicalSide.SERVER, SCustomPayloadPlayPacket.class, 0),
|
||||
LOGIN_TO_SERVER(NetworkEvent.ClientCustomPayloadLoginEvent::new, LogicalSide.CLIENT, CCustomPayloadLoginPacket.class, 3),
|
||||
LOGIN_TO_CLIENT(NetworkEvent.ServerCustomPayloadLoginEvent::new, LogicalSide.SERVER, SCustomPayloadLoginPacket.class, 2);
|
||||
|
||||
private final BiFunction<ICustomPacket<?>, Supplier<NetworkEvent.Context>, NetworkEvent> eventSupplier;
|
||||
private final LogicalSide logicalSide;
|
||||
private final Class<? extends IPacket> packetClass;
|
||||
private final int otherWay;
|
||||
|
||||
private static final Reference2ReferenceArrayMap<Class<? extends IPacket>, NetworkDirection> packetLookup;
|
||||
|
||||
static {
|
||||
packetLookup = Stream.of(values()).
|
||||
collect(Collectors.toMap(NetworkDirection::getPacketClass, Function.identity(), (m1,m2)->m1, Reference2ReferenceArrayMap::new));
|
||||
}
|
||||
|
||||
NetworkDirection(BiFunction<ICustomPacket<?>, Supplier<NetworkEvent.Context>, NetworkEvent> eventSupplier, LogicalSide logicalSide, Class<? extends IPacket> clazz, int i)
|
||||
{
|
||||
this.eventSupplier = eventSupplier;
|
||||
this.logicalSide = logicalSide;
|
||||
this.packetClass = clazz;
|
||||
this.otherWay = i;
|
||||
}
|
||||
|
||||
private Class<? extends IPacket> getPacketClass() {
|
||||
return packetClass;
|
||||
}
|
||||
public static <T extends ICustomPacket<?>> NetworkDirection directionFor(Class<T> customPacket)
|
||||
{
|
||||
return packetLookup.get(customPacket);
|
||||
}
|
||||
|
||||
public NetworkDirection reply() {
|
||||
return NetworkDirection.values()[this.otherWay];
|
||||
}
|
||||
public NetworkEvent getEvent(final ICustomPacket<?> buffer, final Supplier<NetworkEvent.Context> manager) {
|
||||
return this.eventSupplier.apply(buffer, manager);
|
||||
}
|
||||
|
||||
public LogicalSide getOriginationSide()
|
||||
{
|
||||
return logicalSide;
|
||||
}
|
||||
|
||||
public LogicalSide getReceptionSide() { return reply().logicalSide; };
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T extends IPacket<?>> ICustomPacket<T> buildPacket(Pair<PacketBuffer,Integer> packetData, ResourceLocation channelName)
|
||||
{
|
||||
ICustomPacket<T> packet = (ICustomPacket<T>)UnsafeHacks.newInstance(getPacketClass());
|
||||
packet.setName(channelName);
|
||||
packet.setData(packetData.getLeft());
|
||||
packet.setIndex(packetData.getRight());
|
||||
return packet;
|
||||
}
|
||||
}
|
||||
@@ -1,239 +0,0 @@
|
||||
/*
|
||||
* Minecraft Forge
|
||||
* Copyright (c) 2016-2021.
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation version 2.1
|
||||
* of the License.
|
||||
*
|
||||
* This library is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public
|
||||
* License along with this library; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
package net.minecraftforge.fml.network;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
import io.netty.util.Attribute;
|
||||
import io.netty.util.AttributeKey;
|
||||
|
||||
import net.minecraft.entity.player.ServerPlayerEntity;
|
||||
import net.minecraft.network.INetHandler;
|
||||
import net.minecraft.network.play.ServerPlayNetHandler;
|
||||
import net.minecraft.network.NetworkManager;
|
||||
import net.minecraft.network.PacketBuffer;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import net.minecraft.util.concurrent.ThreadTaskExecutor;
|
||||
import net.minecraftforge.eventbus.api.Event;
|
||||
import net.minecraftforge.fml.LogicalSidedProvider;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class NetworkEvent extends Event
|
||||
{
|
||||
private final PacketBuffer payload;
|
||||
private final Supplier<Context> source;
|
||||
private final int loginIndex;
|
||||
|
||||
private NetworkEvent(final ICustomPacket<?> payload, final Supplier<Context> source)
|
||||
{
|
||||
this.payload = payload.getInternalData();
|
||||
this.source = source;
|
||||
this.loginIndex = payload.getIndex();
|
||||
}
|
||||
|
||||
private NetworkEvent(final PacketBuffer payload, final Supplier<Context> source, final int loginIndex)
|
||||
{
|
||||
this.payload = payload;
|
||||
this.source = source;
|
||||
this.loginIndex = loginIndex;
|
||||
}
|
||||
|
||||
public NetworkEvent(final Supplier<Context> source) {
|
||||
this.source = source;
|
||||
this.payload = null;
|
||||
this.loginIndex = -1;
|
||||
}
|
||||
|
||||
public PacketBuffer getPayload()
|
||||
{
|
||||
return payload;
|
||||
}
|
||||
|
||||
public Supplier<Context> getSource()
|
||||
{
|
||||
return source;
|
||||
}
|
||||
|
||||
public int getLoginIndex()
|
||||
{
|
||||
return loginIndex;
|
||||
}
|
||||
|
||||
public static class ServerCustomPayloadEvent extends NetworkEvent
|
||||
{
|
||||
ServerCustomPayloadEvent(final ICustomPacket<?> payload, final Supplier<Context> source) {
|
||||
super(payload, source);
|
||||
}
|
||||
}
|
||||
public static class ClientCustomPayloadEvent extends NetworkEvent
|
||||
{
|
||||
ClientCustomPayloadEvent(final ICustomPacket<?> payload, final Supplier<Context> source) {
|
||||
super(payload, source);
|
||||
}
|
||||
}
|
||||
public static class ServerCustomPayloadLoginEvent extends ServerCustomPayloadEvent {
|
||||
ServerCustomPayloadLoginEvent(ICustomPacket<?> payload, Supplier<Context> source)
|
||||
{
|
||||
super(payload, source);
|
||||
}
|
||||
}
|
||||
|
||||
public static class ClientCustomPayloadLoginEvent extends ClientCustomPayloadEvent {
|
||||
ClientCustomPayloadLoginEvent(ICustomPacket<?> payload, Supplier<Context> source)
|
||||
{
|
||||
super(payload, source);
|
||||
}
|
||||
}
|
||||
|
||||
public static class GatherLoginPayloadsEvent extends Event {
|
||||
private final List<NetworkRegistry.LoginPayload> collected;
|
||||
private final boolean isLocal;
|
||||
|
||||
public GatherLoginPayloadsEvent(final List<NetworkRegistry.LoginPayload> loginPayloadList, boolean isLocal) {
|
||||
this.collected = loginPayloadList;
|
||||
this.isLocal = isLocal;
|
||||
}
|
||||
|
||||
public void add(PacketBuffer buffer, ResourceLocation channelName, String context) {
|
||||
collected.add(new NetworkRegistry.LoginPayload(buffer, channelName, context));
|
||||
}
|
||||
|
||||
public boolean isLocal() {
|
||||
return isLocal;
|
||||
}
|
||||
}
|
||||
|
||||
public static class LoginPayloadEvent extends NetworkEvent {
|
||||
LoginPayloadEvent(final PacketBuffer payload, final Supplier<Context> source, final int loginIndex) {
|
||||
super(payload, source, loginIndex);
|
||||
}
|
||||
}
|
||||
|
||||
public enum RegistrationChangeType {
|
||||
REGISTER, UNREGISTER;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fired when the channel registration (see minecraft custom channel documentation) changes. Note the payload
|
||||
* is not exposed. This fires to the resource location that owns the channel, when it's registration changes state.
|
||||
*
|
||||
* It seems plausible that this will fire multiple times for the same state, depending on what the server is doing.
|
||||
* It just directly dispatches upon receipt.
|
||||
*/
|
||||
public static class ChannelRegistrationChangeEvent extends NetworkEvent {
|
||||
private final RegistrationChangeType changeType;
|
||||
|
||||
ChannelRegistrationChangeEvent(final Supplier<Context> source, RegistrationChangeType changeType) {
|
||||
super(source);
|
||||
this.changeType = changeType;
|
||||
}
|
||||
|
||||
public RegistrationChangeType getRegistrationChangeType() {
|
||||
return this.changeType;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Context for {@link NetworkEvent}
|
||||
*/
|
||||
public static class Context
|
||||
{
|
||||
/**
|
||||
* The {@link NetworkManager} for this message.
|
||||
*/
|
||||
private final NetworkManager networkManager;
|
||||
|
||||
/**
|
||||
* The {@link NetworkDirection} this message has been received on.
|
||||
*/
|
||||
private final NetworkDirection networkDirection;
|
||||
|
||||
/**
|
||||
* The packet dispatcher for this event. Sends back to the origin.
|
||||
*/
|
||||
private final PacketDispatcher packetDispatcher;
|
||||
private boolean packetHandled;
|
||||
|
||||
Context(NetworkManager netHandler, NetworkDirection networkDirection, int index)
|
||||
{
|
||||
this(netHandler, networkDirection, new PacketDispatcher.NetworkManagerDispatcher(netHandler, index, networkDirection.reply()::buildPacket));
|
||||
}
|
||||
|
||||
Context(NetworkManager networkManager, NetworkDirection networkDirection, PacketDispatcher dispatcher) {
|
||||
this.networkManager = networkManager;
|
||||
this.networkDirection = networkDirection;
|
||||
this.packetDispatcher = dispatcher;
|
||||
}
|
||||
|
||||
public NetworkDirection getDirection() {
|
||||
return networkDirection;
|
||||
}
|
||||
|
||||
public PacketDispatcher getPacketDispatcher() {
|
||||
return packetDispatcher;
|
||||
}
|
||||
|
||||
public <T> Attribute<T> attr(AttributeKey<T> key) {
|
||||
return networkManager.channel().attr(key);
|
||||
}
|
||||
|
||||
public void setPacketHandled(boolean packetHandled) {
|
||||
this.packetHandled = packetHandled;
|
||||
}
|
||||
|
||||
public boolean getPacketHandled()
|
||||
{
|
||||
return packetHandled;
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> enqueueWork(Runnable runnable) {
|
||||
ThreadTaskExecutor<?> executor = LogicalSidedProvider.WORKQUEUE.get(getDirection().getReceptionSide());
|
||||
// Must check ourselves as Minecraft will sometimes delay tasks even when they are received on the client thread
|
||||
// Same logic as ThreadTaskExecutor#runImmediately without the join
|
||||
if (!executor.isSameThread()) {
|
||||
return executor.submitAsync(runnable); // Use the internal method so thread check isn't done twice
|
||||
} else {
|
||||
runnable.run();
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* When available, gets the sender for packets that are sent from a client to the server.
|
||||
*/
|
||||
@Nullable
|
||||
public ServerPlayerEntity getSender()
|
||||
{
|
||||
INetHandler netHandler = networkManager.getPacketListener();
|
||||
if (netHandler instanceof ServerPlayNetHandler)
|
||||
{
|
||||
ServerPlayNetHandler netHandlerPlayServer = (ServerPlayNetHandler) netHandler;
|
||||
return netHandlerPlayServer.player;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public NetworkManager getNetworkManager() {
|
||||
return networkManager;
|
||||
}
|
||||
}
|
||||
}
|
||||
Loaded 100 of 1990 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user