diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashClassLoader.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashClassLoader.java new file mode 100644 index 000000000..890e6295b --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashClassLoader.java @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.cleanroom.splash.pre; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.ArrayList; +import java.util.List; + +/** + * Motivation is to keep pre splash's untransformed classes out of the game's loader. + * + *

Note: Only applied to {@link PreSplashScreenContainer.SdlRenderer}.

+ */ +final class PreSplashClassLoader extends URLClassLoader { + + PreSplashClassLoader(ClassLoader parent) { + super(nativeLibraryPaths(), parent); + } + + private static URL[] nativeLibraryPaths() { + List paths = new ArrayList<>(); + for (String property : List.of("org.lwjgl.librarypath", "java.library.path")) { + String value = System.getProperty(property); + if (value == null || value.isEmpty()) { + continue; + } + for (String directory : value.split(File.pathSeparator)) { + if (directory.isEmpty()) { + continue; + } + try { + paths.add(new File(directory).toURI().toURL()); + } catch (MalformedURLException e) { + throw new IllegalStateException("Invalid native library directory: " + directory, e); + } + } + } + return paths.toArray(URL[]::new); + } + + private static boolean isIsolated(String name) { + return name.startsWith("org.lwjgl.") + || name.startsWith("com.cleanroommc.kirino.") + || name.startsWith("com.cleanroommc.mcttf.") + || name.startsWith("com.cleanroommc.cleanroom.splash.pre.PreSplashScreenContainer$") + || name.startsWith("com.cleanroommc.cleanroom.splash.pre.renderer."); + } + + @Override + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + if (!isIsolated(name)) { + return super.loadClass(name, resolve); + } + + synchronized (getClassLoadingLock(name)) { + Class loaded = findLoadedClass(name); + + if (loaded == null) { + String resource = name.replace('.', '/') + ".class"; + try (InputStream input = getParent().getResourceAsStream(resource)) { + if (input == null) { + throw new ClassNotFoundException(name); + } + + byte[] bytes = input.readAllBytes(); + loaded = defineClass(name, bytes, 0, bytes.length); + } catch (IOException e) { + throw new ClassNotFoundException(name, e); + } + } + + if (resolve) { + resolveClass(loaded); + } + + return loaded; + } + } +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashManager.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashManager.java new file mode 100644 index 000000000..e2a19a047 --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashManager.java @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.cleanroom.splash.pre; + +import com.google.common.base.Preconditions; +import org.jetbrains.annotations.ApiStatus; +import org.jspecify.annotations.Nullable; + +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; + +/** + * This is not a client-side only class, but it's only intended to work for client-side bootstrapping. + */ +public final class PreSplashManager { + + public static final PreSplashManager INSTANCE = new PreSplashManager(); + + private final PreSplashPhaseFSM fsm = new PreSplashPhaseFSM(); + private final Queue states = new ConcurrentLinkedQueue<>(); + private volatile @Nullable PreSplashPhase currentPhase = null; + + private PreSplashManager() { + } + + private static String title() { + return "Cleanroom"; + } + + private static String phaseMsg(PreSplashPhase phase) { + return switch (phase) { + case FML_SETUP -> "Preparing Forge Mod Loader"; + case INITIAL_MOD_SCAN -> "Discovering mods"; + case CORE_MOD_LAUNCH -> "Loading core mods"; + case MINECRAFT_INIT -> "Initializing Minecraft"; + case RIGHT_BEFORE_SPLASH -> "Starting mod loading"; + }; + } + + /** + * Thread-safe. + * + * @param phase The next observed phase + */ + @ApiStatus.Internal + public synchronized void notifyPhase(PreSplashPhase phase) { + Preconditions.checkNotNull(phase); + Preconditions.checkState(phase == fsm.getState(), + "Expected pre splash phase: %s; Observed: %s", fsm.getState(), phase); + + fsm.next(); + + states.add(new PreSplashState(title(), phaseMsg(phase), "")); + currentPhase = phase; + } + + /** + * Thread-safe. Must be called after the first {@link #notifyPhase(PreSplashPhase)}. + * + * @param phase The current phase that owns this detail update (acts like a filter) + */ + @SuppressWarnings("DataFlowIssue") + @ApiStatus.Internal + public synchronized void notifyDetails(PreSplashPhase phase, String details) { + Preconditions.checkNotNull(phase); + Preconditions.checkNotNull(details); + Preconditions.checkNotNull(currentPhase); + + if (currentPhase == phase) { + states.add(new PreSplashState(title(), phaseMsg(currentPhase), details)); + } + } + + /** + * Thread-safe. Only intended to be read after the first phase has been published. + */ + @ApiStatus.Internal + PreSplashPhase readPhase() { + return Preconditions.checkNotNull(currentPhase); + } + + /** + * Thread-safe. + */ + @Nullable + PreSplashState peek() { + return states.peek(); + } + + /** + * Thread-safe. + */ + @Nullable + PreSplashState poll() { + return states.poll(); + } +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashPhase.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashPhase.java new file mode 100644 index 000000000..15494cd3a --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashPhase.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.cleanroom.splash.pre; + +import com.cleanroommc.discovery.CleanroomModDiscoverer; + +import net.minecraft.client.Minecraft; +import net.minecraft.launchwrapper.LaunchClassLoader; +import net.minecraftforge.fml.common.launcher.FMLTweaker; +import net.minecraftforge.fml.relauncher.CoreModManager; + +import java.io.File; + +public enum PreSplashPhase { + + /** + * @see FMLTweaker#injectIntoClassLoader(LaunchClassLoader) + */ + FML_SETUP, + + /** + * @see CleanroomModDiscoverer#CleanroomModDiscoverer() + */ + INITIAL_MOD_SCAN, + + /** + * @see CoreModManager#handleLaunch(File, LaunchClassLoader, FMLTweaker) + */ + CORE_MOD_LAUNCH, + + /** + * @see Minecraft#init() + */ + MINECRAFT_INIT, + + /** + * @see Minecraft#init() + */ + RIGHT_BEFORE_SPLASH +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashPhaseFSM.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashPhaseFSM.java new file mode 100644 index 000000000..4a5604c71 --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashPhaseFSM.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.cleanroom.splash.pre; + +import com.cleanroommc.kirino.schemata.fsm.FiniteStateMachine; + +import com.google.common.base.Preconditions; + +final class PreSplashPhaseFSM { + + private final FiniteStateMachine fsm; + + private boolean finished = false; + + PreSplashPhaseFSM() { + fsm = FiniteStateMachine.BuilderImpl + .enumIntStateMachine(PreSplashPhase.class, 0, 0) + .initialState(PreSplashPhase.FML_SETUP) + .addTransition(PreSplashPhase.FML_SETUP, 0, PreSplashPhase.INITIAL_MOD_SCAN) + .addTransition(PreSplashPhase.INITIAL_MOD_SCAN, 0, PreSplashPhase.CORE_MOD_LAUNCH) + .addTransition(PreSplashPhase.CORE_MOD_LAUNCH, 0, PreSplashPhase.MINECRAFT_INIT) + .addTransition(PreSplashPhase.MINECRAFT_INIT, 0, PreSplashPhase.RIGHT_BEFORE_SPLASH) + .error((state, input) -> { + throw new RuntimeException(String.format( + "An error occurred inside PreSplashPhaseFSM. The input=%d leads to a non-existent route. Current state=%s.", input, state)); + }) + .validate() + .build(); + } + + public PreSplashPhase getState() { + return fsm.state(); + } + + public void next() { + Preconditions.checkState(!finished); + + if (fsm.state() == PreSplashPhase.RIGHT_BEFORE_SPLASH) { + finished = true; + } else { + fsm.accept(0); + } + } +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashPresentation.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashPresentation.java new file mode 100644 index 000000000..9057b104b --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashPresentation.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.cleanroom.splash.pre; + +import com.google.common.base.Preconditions; +import org.jspecify.annotations.Nullable; + +public final class PreSplashPresentation { + + private final PreSplashManager manager; + private PreSplashState current; + + public PreSplashPresentation(PreSplashManager manager) { + this.manager = manager; + current = Preconditions.checkNotNull(manager.peek(), + "The initial pre splash frame must be published."); + } + + public boolean isFinished() { + return manager.readPhase() == PreSplashPhase.RIGHT_BEFORE_SPLASH; + } + + @Nullable + public PreSplashState peek() { + return manager.peek(); + } + + @Nullable + public PreSplashState poll() { + PreSplashState next = manager.poll(); + if (next != null) { + current = next; + } + return next; + } + + public PreSplashState nextFrame() { + if (peek() != null) { + poll(); + } + return current; + } +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java new file mode 100644 index 000000000..e689fc745 --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java @@ -0,0 +1,1094 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.cleanroom.splash.pre; + +import com.cleanroommc.anone.reveal.ReflectiveInvocation; +import com.cleanroommc.cleanroom.splash.pre.renderer.PreSplashLayout; +import com.cleanroommc.cleanroom.splash.pre.renderer.PreSplashLogger; +import com.cleanroommc.cleanroom.splash.pre.renderer.SdlSplashRenderer; +import com.cleanroommc.cleanroom.splash.pre.renderer.SwingSplashRenderer; +import com.cleanroommc.cleanroom.splash.pre.renderer.WindowsAppRegistration; + +import com.google.common.base.Preconditions; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import net.minecraft.client.Minecraft; +import net.minecraft.client.resources.IReloadableResourceManager; +import net.minecraft.client.resources.data.MetadataSerializer; +import net.minecraft.launchwrapper.LaunchClassLoader; +import net.minecraftforge.fml.common.launcher.FMLTweaker; +import net.minecraftforge.fml.client.FMLClientHandler; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.ApiStatus; +import org.jspecify.annotations.Nullable; + +import org.lwjgl.opengl.GL; +import org.lwjgl.opengl.GL11; +import org.lwjgl.sdl.SDLError; +import org.lwjgl.sdl.SDLEvents; +import org.lwjgl.sdl.SDLInit; +import org.lwjgl.sdl.SDLVideo; +import org.lwjgl.sdl.SDL_Event; +import org.lwjgl.sdl.SDL_EventFilter; +import org.lwjgl.sdl.SDL_Rect; +import org.lwjgl.system.Configuration; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.system.Platform; +import org.lwjgl.system.ThreadLocalUtil; + +import javax.swing.JDialog; +import javax.swing.SwingUtilities; +import javax.swing.Timer; +import javax.swing.WindowConstants; +import java.awt.Frame; +import java.awt.GraphicsEnvironment; +import java.awt.Rectangle; +import java.awt.Window; +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.nio.IntBuffer; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.LockSupport; +import java.util.function.BiConsumer; +import java.util.function.BooleanSupplier; +import java.util.function.Supplier; +import java.util.jar.JarEntry; +import java.util.jar.JarOutputStream; + +/** + * It owns the renderer lifecycle, SDL window OR Swing process. + */ +public final class PreSplashScreenContainer { + + private static @Nullable PreSplashScreenContainer instance; + + public static final Logger LOGGER = LogManager.getLogger("Pre Splash Screen"); + + private static final int THREAD_START_TIMEOUT_SECOND = 45; + private static final int THREAD_STOP_TIMEOUT_SECOND = 10; + + private final Thread gameThread; + private final Thread thread; + private final Thread shutdownHook; + private final PreSplashPresentation presentation; + + private final CountDownLatch startupReady = new CountDownLatch(1); + + private final Path gameDirectory; + private final File assetsDirectory; + private final @Nullable String assetIndex; + + private volatile boolean running = true; + + /** + * Must be called on the game thread. + * + * @see #start(Path, File, String) + */ + private PreSplashScreenContainer(Path gameDirectory, File assetsDirectory, @Nullable String assetIndex) { + Preconditions.checkNotNull(gameDirectory); + Preconditions.checkNotNull(assetsDirectory); + + gameThread = Thread.currentThread(); + presentation = new PreSplashPresentation(PreSplashManager.INSTANCE); + this.gameDirectory = gameDirectory; + this.assetsDirectory = assetsDirectory; + this.assetIndex = assetIndex; + thread = new Thread(this::run, "Pre Splash Renderer"); + thread.setDaemon(true); + shutdownHook = new Thread(this::stopAndWait, "Pre Splash Shutdown"); + } + + /** + * Called only from the client tweaker, right after publishing {@link PreSplashPhase#FML_SETUP}. + * + * @see FMLTweaker#injectIntoClassLoader(LaunchClassLoader) + */ + @ApiStatus.Internal + public static void start(Path gameDirectory, File assetsDirectory, @Nullable String assetIndex) { + Preconditions.checkNotNull(gameDirectory); + Preconditions.checkNotNull(assetsDirectory); + + PreSplashScreenContainer screen; + synchronized (PreSplashScreenContainer.class) { + Preconditions.checkState(instance == null, "Pre splash has already started."); + screen = new PreSplashScreenContainer(gameDirectory, assetsDirectory, assetIndex); + instance = screen; + + Runtime.getRuntime().addShutdownHook(screen.shutdownHook); + screen.thread.start(); // this::run + } + + // wait until the renderer releases game startup + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(THREAD_START_TIMEOUT_SECOND); + boolean interrupted = false; + while (true) { + try { + if (!screen.startupReady.await(deadline - System.nanoTime(), TimeUnit.NANOSECONDS)) { + LOGGER.warn("Pre splash renderer did not become ready within {} seconds.", THREAD_START_TIMEOUT_SECOND); + screen.stopAndWait(); + } + break; + } catch (InterruptedException e) { + interrupted = true; + } + } + + if (interrupted) { + Thread.currentThread().interrupt(); + } + } + + /** + * Called only from the client handler, right after publishing {@link PreSplashPhase#RIGHT_BEFORE_SPLASH}. + * + * @see FMLClientHandler#beginMinecraftLoading(Minecraft, List, IReloadableResourceManager, MetadataSerializer) + */ + @ApiStatus.Internal + public static void finish() { + PreSplashScreenContainer screen; + synchronized (PreSplashScreenContainer.class) { + if (instance == null) { + return; + } + + screen = instance; + } + + screen.stopAndWait(); + } + + private void stopAndWait() { + running = false; + LockSupport.unpark(thread); + if (Thread.currentThread() == thread) { + return; + } + + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(THREAD_STOP_TIMEOUT_SECOND); + boolean interrupted = false; + while (thread.isAlive()) { + long remaining = deadline - System.nanoTime(); + if (remaining <= 0) { + LOGGER.warn("Pre splash renderer did not stop within {} seconds.", THREAD_STOP_TIMEOUT_SECOND); + break; + } + try { + TimeUnit.NANOSECONDS.timedJoin(thread, remaining); + } catch (InterruptedException e) { + interrupted = true; + } + } + + // only if the renderer has not signaled yet + startupReady.countDown(); + + if (interrupted) { + Thread.currentThread().interrupt(); + } + } + + private boolean isRunning() { + return running && gameThread.isAlive() && !presentation.isFinished(); + } + + private void run() { + try { + LOGGER.info("Starting pre splash screen."); + if (!isRunning()) { + return; + } + boolean mac = System.getProperty("os.name", "").toLowerCase(Locale.ROOT).startsWith("mac"); + if (mac || !runSdl()) { + if (isRunning()) { + runSwing(); + } + } + } catch (Throwable failure) { + LOGGER.warn("Pre splash unavailable. Continue normal startup.", failure); + } finally { + running = false; + startupReady.countDown(); + try { + Runtime.getRuntime().removeShutdownHook(shutdownHook); + } catch (IllegalStateException ignored) { + // if shutdown has already begun + } + LOGGER.info("Pre splash screen stopped."); + } + } + + // + private boolean runSdl() { + Thread renderThread = Thread.currentThread(); + ClassLoader previousContextLoader = renderThread.getContextClassLoader(); + boolean[] unavailable = { false }; + + try (PreSplashClassLoader loader = new PreSplashClassLoader(PreSplashScreenContainer.class.getClassLoader())) { + renderThread.setContextClassLoader(loader); + + Class renderer = Class.forName(PreSplashScreenContainer.class.getName() + "$SdlRenderer", true, loader); + Runnable render = (Runnable) renderer.getConstructor( + Path.class, + File.class, + String.class, + BooleanSupplier.class, + Supplier.class, + Runnable.class, + Runnable.class, + Runnable.class).newInstance( + gameDirectory, + assetsDirectory, + assetIndex, + (BooleanSupplier) this::isRunning, + (Supplier) presentation::nextFrame, + (Runnable) () -> running = false, + (Runnable) startupReady::countDown, + (Runnable) () -> unavailable[0] = true); + + // SDL ENTRYPOINT + render.run(); + + } catch (Throwable failure) { + LOGGER.warn("SDL pre splash unavailable. Falling back to Swing.", failure); + return false; + } finally { + renderThread.setContextClassLoader(previousContextLoader); + } + + return !unavailable[0]; + } + + private void runSwing() throws IOException { + // SWING ENTRYPOINT + new SwingRenderer( + this::isRunning, + presentation::nextFrame, + startupReady::countDown).run(); + } + // + + // + @ApiStatus.Internal + public static String createWindowTitle() { + String title = "Cleanroom Pre Splash"; + return System.getenv("NIRI_SOCKET") == null ? title : title + " [" + UUID.randomUUID() + "]"; + } + + private static final class NiriWindowPlacement { + + private NiriWindowPlacement() { + } + + private static @Nullable JsonElement niriMessage(String... arguments) { + List command = new ArrayList<>(List.of("niri", "msg", "--json")); + command.addAll(List.of(arguments)); + + Process message = null; + try { + message = new ProcessBuilder(command).redirectError(ProcessBuilder.Redirect.DISCARD).start(); + if (message.waitFor(1, TimeUnit.SECONDS) && message.exitValue() == 0) { + try (InputStream input = message.getInputStream()) { + return JsonParser.parseString(new String(input.readAllBytes(), StandardCharsets.UTF_8)); + } + } + } catch (IOException | RuntimeException failure) { + LOGGER.debug("Could not communicate with niri for pre splash positioning.", failure); + } catch (InterruptedException ignored) { + Thread.currentThread().interrupt(); + } finally { + if (message != null && message.isAlive()) { + message.destroyForcibly(); + } + } + return null; + } + + public static boolean centerWindowOnNiri(String windowTitle) { + if (System.getenv("NIRI_SOCKET") == null) { + return true; + } + + try { + JsonElement windows = niriMessage("windows"); + if (windows == null) { + return false; + } + + JsonObject splash = null; + for (JsonElement element : windows.getAsJsonArray()) { + JsonObject window = element.getAsJsonObject(); + JsonElement title = window.get("title"); + if (title != null + && title.isJsonPrimitive() + && windowTitle.equals(title.getAsString()) + && window.get("is_floating").getAsBoolean()) { + if (splash != null) { + return false; + } + + splash = window; + } + } + + if (splash == null) { + return false; + } + + JsonElement workspaces = niriMessage("workspaces"); + JsonElement outputs = niriMessage("outputs"); + if (workspaces == null || outputs == null) { + return false; + } + + for (JsonElement element : workspaces.getAsJsonArray()) { + JsonObject workspace = element.getAsJsonObject(); + if (!workspace.get("id").equals(splash.get("workspace_id")) || workspace.get("output").isJsonNull()) { + continue; + } + + JsonObject output = outputs.getAsJsonObject().getAsJsonObject(workspace.get("output").getAsString()); + JsonObject logical = output.getAsJsonObject("logical"); + JsonObject layout = splash.getAsJsonObject("layout"); + var size = layout.getAsJsonArray("tile_size"); + var position = layout.getAsJsonArray("tile_pos_in_workspace_view"); + double x = (logical.get("width").getAsDouble() - size.get(0).getAsDouble()) / 2; + double y = (logical.get("height").getAsDouble() - size.get(1).getAsDouble()) / 2; + + niriMessage( + "action", + "move-floating-window", + "--id", splash.get("id").getAsString(), + "--x=" + String.format(Locale.ROOT, "%+.3f", x - position.get(0).getAsDouble()), + "--y=" + String.format(Locale.ROOT, "%+.3f", y - position.get(1).getAsDouble())); + + return true; + } + } catch (RuntimeException failure) { + LOGGER.debug("Could not center pre splash through niri.", failure); + } + return false; + } + } + + /** + * @see PreSplashScreenContainer#runSdl() + */ + @ApiStatus.Internal + public static final class SdlRenderer implements Runnable { + + private final Path gameDirectory; + private final File assetsDirectory; + private final @Nullable String assetIndex; + private final BooleanSupplier running; + private final Supplier state; + private final Runnable stop; + private final Runnable startupReady; + private final Runnable unavailable; + + @ReflectiveInvocation + public SdlRenderer( + Path gameDirectory, + File assetsDirectory, + @Nullable String assetIndex, + BooleanSupplier running, + Supplier state, + Runnable stop, + Runnable startupReady, + Runnable unavailable) { + + Preconditions.checkNotNull(gameDirectory); + Preconditions.checkNotNull(assetsDirectory); + Preconditions.checkNotNull(running); + Preconditions.checkNotNull(state); + Preconditions.checkNotNull(stop); + Preconditions.checkNotNull(startupReady); + Preconditions.checkNotNull(unavailable); + + this.gameDirectory = gameDirectory; + this.assetsDirectory = assetsDirectory; + this.assetIndex = assetIndex; + this.running = running; + this.state = state; + this.stop = stop; + this.startupReady = startupReady; + this.unavailable = unavailable; + } + + @Override + public void run() { + try (Window window = Window.open(stop)) { + if (running.getAsBoolean()) { + try (SdlSplashRenderer renderer = new SdlSplashRenderer(gameDirectory, assetsDirectory, assetIndex, startupReady)) { + window.runLoop(running, (width, height) -> { + renderer.update(state.get()); + renderer.render(width, height); + }); + } + } + } catch (Throwable failure) { + LOGGER.warn("SDL pre splash unavailable. Falling back to Swing.", failure); + unavailable.run(); + } + } + + static final class Window implements AutoCloseable { + + private static final int TARGET_FRAME_RATE = 60; + + private final @Nullable String originalLibraryPath = System.getProperty("org.lwjgl.librarypath"); + private final String windowTitle = createWindowTitle(); + private long window; + private long context; + private boolean videoInitialized; + private boolean initialized; + private boolean glInitialized; + private @Nullable WindowsAppRegistration windowsAppRegistration; + private @Nullable SDL_EventFilter watch; + + static Window open(Runnable stop) { + Window window = new Window(); + try { + window.initialize(stop); + return window; + } catch (RuntimeException | Error failure) { + try { + window.close(); + } catch (Throwable cleanup) { + failure.addSuppressed(cleanup); + } + throw failure; + } + } + + private static void checkSDL(boolean success, String operation) { + Preconditions.checkState(success, "%s: %s", operation, SDLError.SDL_GetError()); + } + + private void initialize(Runnable stop) { + // configure this loader's (PreSplashClassLoader) LWJGL copy + Configuration.LIBRARY_PATH.set(null); + Configuration.SHARED_LIBRARY_EXTRACT_PATH.set(null); + Configuration.SHARED_LIBRARY_EXTRACT_DIRECTORY.set("cleanroom-pre-splash"); + Configuration.SHARED_LIBRARY_EXTRACT_FORCE.set(true); + Configuration.OPENGL_EXPLICIT_INIT.set(true); + + if (Platform.get() == Platform.WINDOWS) { + windowsAppRegistration = WindowsAppRegistration.register(); + } + + checkSDL(SDLInit.SDL_InitSubSystem(SDLInit.SDL_INIT_VIDEO | SDLInit.SDL_INIT_EVENTS), "SDL_InitSubSystem"); + + videoInitialized = true; + // on non-Apple platforms, the video initializing thread is SDL's main thread + Preconditions.checkState(SDLInit.SDL_IsMainThread(), "Pre splash must run on its SDL video thread."); + + String videoDriver = SDLVideo.SDL_GetCurrentVideoDriver(); + Preconditions.checkState(videoDriver != null, "SDL video driver is not initialized."); + + SDLVideo.SDL_GL_ResetAttributes(); + checkSDL(SDLVideo.SDL_GL_SetAttribute(SDLVideo.SDL_GL_CONTEXT_MAJOR_VERSION, 4), "GL major version"); + checkSDL(SDLVideo.SDL_GL_SetAttribute(SDLVideo.SDL_GL_CONTEXT_MINOR_VERSION, 6), "GL minor version"); + checkSDL(SDLVideo.SDL_GL_SetAttribute(SDLVideo.SDL_GL_CONTEXT_PROFILE_MASK, SDLVideo.SDL_GL_CONTEXT_PROFILE_COMPATIBILITY), "GL profile"); + checkSDL(SDLVideo.SDL_GL_SetAttribute(SDLVideo.SDL_GL_DOUBLEBUFFER, 1), "GL double buffering"); + + int display = SDLVideo.SDL_GetPrimaryDisplay(); + Preconditions.checkState(display != 0, "SDL_GetPrimaryDisplay: %s", SDLError.SDL_GetError()); + + try (MemoryStack stack = MemoryStack.stackPush()) { + SDL_Rect bounds = SDL_Rect.malloc(stack); + checkSDL(SDLVideo.SDL_GetDisplayBounds(display, bounds), "SDL_GetDisplayBounds"); + + float scale = Math.min((float) bounds.w() / PreSplashLayout.WIDTH, (float) bounds.h() / PreSplashLayout.HEIGHT) * PreSplashLayout.SCREEN_PERCENTAGE; + int windowWidth = Math.max(1, Math.round(PreSplashLayout.WIDTH * scale)); + int windowHeight = Math.max(1, Math.round(PreSplashLayout.HEIGHT * scale)); + + window = SDLVideo.SDL_CreateWindow(windowTitle, windowWidth, windowHeight, + SDLVideo.SDL_WINDOW_OPENGL + | SDLVideo.SDL_WINDOW_HIGH_PIXEL_DENSITY + | SDLVideo.SDL_WINDOW_HIDDEN + | SDLVideo.SDL_WINDOW_UTILITY + | SDLVideo.SDL_WINDOW_NOT_FOCUSABLE + | SDLVideo.SDL_WINDOW_ALWAYS_ON_TOP); + + Preconditions.checkState(window != 0, "SDL_CreateWindow: %s", SDLError.SDL_GetError()); + + // fixed size window + checkSDL(SDLVideo.SDL_SetWindowMinimumSize(window, windowWidth, windowHeight), "SDL_SetWindowMinimumSize"); + checkSDL(SDLVideo.SDL_SetWindowMaximumSize(window, windowWidth, windowHeight), "SDL_SetWindowMaximumSize"); + } + + // Wayland does not support explicit positioning + if (!"wayland".equals(videoDriver)) { + int centered = SDLVideo.SDL_WINDOWPOS_CENTERED_DISPLAY(display); + if (!SDLVideo.SDL_SetWindowPosition(window, centered, centered)) { + LOGGER.debug("Could not center pre splash window: {}", SDLError.SDL_GetError()); + } + } + + context = SDLVideo.SDL_GL_CreateContext(window); + Preconditions.checkState(context != 0, "SDL_GL_CreateContext: %s", SDLError.SDL_GetError()); + checkSDL(SDLVideo.SDL_GL_MakeCurrent(window, context), "SDL_GL_MakeCurrent"); + + GL.create(SDLVideo::SDL_GL_GetProcAddress); + + glInitialized = true; + boolean gl46 = GL.createCapabilities().OpenGL46; + + // release LWJGL's global table so the game's LWJGL can initialize + ThreadLocalUtil.setFunctionMissingAddresses(0); + + Preconditions.checkState(gl46, "Pre splash requires OpenGL 4.6."); + LOGGER.info("Pre splash GL context created.\nVideo Driver: {}\nGL Vendor: {}\nRenderer: {}\nVersion: {}", + videoDriver, + GL11.glGetString(GL11.GL_VENDOR), + GL11.glGetString(GL11.GL_RENDERER), + GL11.glGetString(GL11.GL_VERSION)); + + if (!SDLVideo.SDL_GL_SetSwapInterval(0)) { + LOGGER.debug("Could not disable pre splash VSync: {}", SDLError.SDL_GetError()); + } + + SDLVideo.SDL_GL_ResetAttributes(); + + int windowId = SDLVideo.SDL_GetWindowID(window); + checkSDL(windowId != 0, "SDL_GetWindowID"); + + watch = SDL_EventFilter.create((_, address) -> { + // borrowed. must not close + SDL_Event event = SDL_Event.create(address); + if (event.type() == SDLEvents.SDL_EVENT_QUIT + || (event.type() == SDLEvents.SDL_EVENT_WINDOW_CLOSE_REQUESTED && event.window().windowID() == windowId)) { + stop.run(); + } + return true; + }); + checkSDL(SDLEvents.SDL_AddEventWatch(watch, 0), "SDL_AddEventWatch"); + + if (originalLibraryPath == null) { + System.clearProperty("org.lwjgl.librarypath"); + } else { + System.setProperty("org.lwjgl.librarypath", originalLibraryPath); + } + + initialized = true; + } + + void runLoop(BooleanSupplier running, BiConsumer draw) { + checkSDL(SDLVideo.SDL_ShowWindow(window), "SDL_ShowWindow"); + + boolean centerPending = System.getenv("NIRI_SOCKET") != null; + long centerDeadline = 0; + + try (MemoryStack stack = MemoryStack.stackPush()) { + IntBuffer width = stack.mallocInt(1); + IntBuffer height = stack.mallocInt(1); + while (running.getAsBoolean()) { + long frameStart = System.nanoTime(); + SDLEvents.SDL_PumpEvents(); + checkSDL(SDLVideo.SDL_GetWindowSizeInPixels(window, width, height), "SDL_GetWindowSizeInPixels"); + if (width.get(0) <= 0 || height.get(0) <= 0) { + LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(100)); + continue; + } + + draw.accept(width.get(0), height.get(0)); + checkSDL(SDLVideo.SDL_GL_SwapWindow(window), "SDL_GL_SwapWindow"); + + if (centerPending) { + if (centerDeadline == 0) { + centerDeadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(1); + } + centerPending = System.nanoTime() < centerDeadline && !NiriWindowPlacement.centerWindowOnNiri(windowTitle); + } + + long remaining = TimeUnit.SECONDS.toNanos(1) / TARGET_FRAME_RATE - (System.nanoTime() - frameStart); + if (remaining > 0) { + LockSupport.parkNanos(remaining); + } + } + } + } + + @Override + public void close() { + try { + if (watch != null) { + SDLEvents.SDL_RemoveEventWatch(watch, 0); + watch.free(); + } + if (glInitialized) { + GL.setCapabilities(null); + if (!initialized) { + ThreadLocalUtil.setFunctionMissingAddresses(0); + } + } + if (context != 0) { + if (!SDLVideo.SDL_GL_MakeCurrent(window, 0)) { + LOGGER.warn("Could not detach pre splash GL context: {}", SDLError.SDL_GetError()); + } + if (!SDLVideo.SDL_GL_DestroyContext(context)) { + LOGGER.warn("Could not destroy pre splash GL context: {}", SDLError.SDL_GetError()); + } + } + } finally { + try { + if (glInitialized) { + GL.destroy(); + } + } finally { + try { + if (window != 0) { + SDLVideo.SDL_DestroyWindow(window); + } + } finally { + try { + if (videoInitialized) { + if (!initialized) { + SDLVideo.SDL_GL_ResetAttributes(); + } + SDLInit.SDL_QuitSubSystem(SDLInit.SDL_INIT_VIDEO | SDLInit.SDL_INIT_EVENTS); + } + } finally { + try { + if (windowsAppRegistration != null) { + windowsAppRegistration.close(); + windowsAppRegistration = null; + } + } finally { + if (!initialized) { + if (originalLibraryPath == null) { + System.clearProperty("org.lwjgl.librarypath"); + } else { + System.setProperty("org.lwjgl.librarypath", originalLibraryPath); + } + } + } + } + } + } + } + } + } + } + + /** + * @see PreSplashScreenContainer#runSwing() + */ + @ApiStatus.Internal + public static final class SwingRenderer { + + private static final int HELPER_STOP_TIMEOUT_SECOND = 2; + + private final BooleanSupplier running; + private final Supplier state; + private final Runnable startupReady; + + private SwingRenderer(BooleanSupplier running, Supplier state, Runnable startupReady) { + this.running = running; + this.state = state; + this.startupReady = startupReady; + } + + private void run() throws IOException { + new HelperProcess(running, state, startupReady).run(); + } + + static final class Protocol { + + private static final int STATE = 1; + private static final int CLOSE = 2; + private static final int READY = 3; + private static final int LOG = 4; + private static final int MAX_LOG_BYTES = 1024 * 1024; + + private Protocol() { + } + + static void writeState(DataOutputStream output, PreSplashState state) throws IOException { + output.writeByte(STATE); + output.writeUTF(state.title()); + output.writeUTF(state.message()); + output.writeUTF(state.details()); + output.flush(); + } + + @Nullable + static PreSplashState readState(DataInputStream input) throws IOException { + int command; + try { + command = input.readUnsignedByte(); + } catch (IOException ignored) { + return null; + } + if (command == CLOSE) { + return null; + } + if (command != STATE) { + throw new IOException("Invalid pre splash command: " + command); + } + return new PreSplashState(input.readUTF(), input.readUTF(), input.readUTF()); + } + + static void close(DataOutputStream output) throws IOException { + output.writeByte(CLOSE); + output.flush(); + } + + static void ready(DataOutputStream output) throws IOException { + synchronized (output) { + output.writeByte(READY); + output.flush(); + } + } + + static void log(DataOutputStream output, PreSplashLogger.Level level, String message, @Nullable Throwable failure) throws IOException { + if (failure != null) { + StringWriter stack = new StringWriter(); + failure.printStackTrace(new PrintWriter(stack)); + message += "\n" + stack; + } + + byte[] bytes = message.getBytes(StandardCharsets.UTF_8); + if (bytes.length > MAX_LOG_BYTES) { + throw new IOException("Pre splash log message is too large."); + } + + synchronized (output) { + output.writeByte(LOG); + output.writeByte(level.ordinal()); + output.writeInt(bytes.length); + output.write(bytes); + output.flush(); + } + } + + private static final class ReplyReader { + + private final DataInputStream input; + private byte @Nullable [] bytes; + private int level; + private int offset; + + private ReplyReader(DataInputStream input) { + this.input = input; + } + + private int poll() throws IOException { + if (bytes == null) { + if (input.available() == 0) { + return 0; + } + input.mark(6); + int reply = input.readUnsignedByte(); + if (reply == READY) { + return READY; + } + if (reply != LOG) { + throw new IOException("Invalid pre splash reply: " + reply); + } + if (input.available() < 5) { + input.reset(); + return 0; + } + level = input.readUnsignedByte(); + int length = input.readInt(); + if (level >= PreSplashLogger.Level.values().length || length < 0 || length > MAX_LOG_BYTES) { + throw new IOException("Invalid pre splash log message."); + } + bytes = new byte[length]; + offset = 0; + } + + int available = Math.min(input.available(), bytes.length - offset); + input.readFully(bytes, offset, available); + offset += available; + if (offset < bytes.length) { + return 0; + } + + PreSplashLogger.LOGGER.log(PreSplashLogger.Level.values()[level], new String(bytes, StandardCharsets.UTF_8)); + bytes = null; + return LOG; + } + } + } + + private record HelperProcess(BooleanSupplier running, Supplier state, Runnable startupReady) { + + private static void writeHelperClass(JarOutputStream output, Class type, Set entries) throws IOException { + String resource = type.getName().replace('.', '/') + ".class"; + if (!entries.add(resource)) { + return; + } + + try (InputStream input = PreSplashScreenContainer.class.getResourceAsStream("/" + resource)) { + Preconditions.checkNotNull(input, "Missing Swing pre splash class: %s", type.getName()); + output.putNextEntry(new JarEntry(resource)); + input.transferTo(output); + output.closeEntry(); + } + + for (Class nested : type.getDeclaredClasses()) { + writeHelperClass(output, nested, entries); + } + } + + private void run() throws IOException { + String renderer = SwingRenderer.class.getName() + "$Helper"; + String windowTitle = createWindowTitle(); + Path helperJar = Files.createTempFile("cleanroom-pre-splash-", ".jar"); + Process helper = null; + + try { + try (JarOutputStream output = new JarOutputStream(Files.newOutputStream(helperJar))) { + Set entries = new HashSet<>(); + for (Class type : List.of(Protocol.class, Helper.class, PreSplashState.class, SwingSplashRenderer.class, PreSplashLayout.class, PreSplashLogger.class)) { + writeHelperClass(output, type, entries); + } + } + + boolean windows = System.getProperty("os.name", "").toLowerCase(Locale.ROOT).startsWith("windows"); + Path java = Path.of(System.getProperty("java.home"), "bin", windows ? "java.exe" : "java"); + + ProcessBuilder builder = new ProcessBuilder( + java.toString(), + "-Dapple.awt.UIElement=true", + "-cp", helperJar.toString(), + renderer, + Long.toString(ProcessHandle.current().pid()), + windowTitle); + + builder.environment().remove("JDK_JAVA_OPTIONS"); + builder.environment().remove("JAVA_TOOL_OPTIONS"); + builder.environment().remove("_JAVA_OPTIONS"); + builder.redirectError(ProcessBuilder.Redirect.INHERIT); + + helper = builder.start(); + + try (DataOutputStream commands = new DataOutputStream(new BufferedOutputStream(helper.getOutputStream())); + DataInputStream replies = new DataInputStream(new BufferedInputStream(helper.getInputStream()))) { + + PreSplashState previous = null; + boolean ready = false; + Protocol.ReplyReader reader = new Protocol.ReplyReader(replies); + + while (running.getAsBoolean()) { + PreSplashState current = state.get(); + boolean alive = helper.isAlive(); + + if (alive && current != previous) { + Protocol.writeState(commands, current); + previous = current; + } + + int reply; + while (running.getAsBoolean() && (reply = reader.poll()) != 0) { + if (reply == Protocol.READY && !ready) { + NiriWindowPlacement.centerWindowOnNiri(windowTitle); + ready = true; + startupReady.run(); + } + } + + if (!alive) { + LOGGER.warn("Swing pre splash helper exited with code {}.", helper.exitValue()); + break; + } + + LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(50)); + } + + if (helper.isAlive()) { + Protocol.close(commands); + } + } + } finally { + try { + if (helper != null) { + stopHelper(helper); + } + } finally { + Files.deleteIfExists(helperJar); + } + } + } + + private static void stopHelper(Process helper) { + boolean interrupted = false; + try { + if (!helper.waitFor(HELPER_STOP_TIMEOUT_SECOND, TimeUnit.SECONDS)) { + helper.destroy(); + helper.waitFor(HELPER_STOP_TIMEOUT_SECOND, TimeUnit.SECONDS); + } + } catch (InterruptedException ignored) { + interrupted = true; + } finally { + if (helper.isAlive()) { + helper.destroyForcibly(); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(HELPER_STOP_TIMEOUT_SECOND); + while (helper.isAlive()) { + long remaining = deadline - System.nanoTime(); + if (remaining <= 0) { + break; + } + try { + helper.waitFor(remaining, TimeUnit.NANOSECONDS); + } catch (InterruptedException ignored) { + interrupted = true; + } + } + } + if (interrupted) { + Thread.currentThread().interrupt(); + } + } + } + } + + /** + * This is the entry point in the helper JVM. + */ + public static final class Helper { + + private static final int TARGET_FRAME_RATE = 60; + + private static final DataOutputStream REPLIES = new DataOutputStream(System.out); + + private final SwingSplashRenderer renderer = new SwingSplashRenderer(Helper::signalStartupReady); + + private @Nullable JDialog window; + private @Nullable Timer timer; + + public static void main(String[] args) { + try { + PreSplashLogger.setSink(Helper::log); + ProcessHandle parent = ProcessHandle.of(Long.parseLong(args[0])).orElse(null); + if (parent == null) { + return; + } + + parent.onExit().thenRun(() -> System.exit(0)); + + try (DataInputStream commands = new DataInputStream(new BufferedInputStream(System.in))) { + PreSplashState initial = Protocol.readState(commands); + if (initial == null) { + return; + } + + Helper[] screen = new Helper[1]; + SwingUtilities.invokeAndWait(() -> { + Helper helper = new Helper(); + screen[0] = helper; + helper.renderer.update(initial); + helper.open(args[1]); + }); + + Helper helper = screen[0]; + + PreSplashState state; + while ((state = Protocol.readState(commands)) != null) { + PreSplashState update = state; + SwingUtilities.invokeLater(() -> helper.renderer.update(update)); + } + + SwingUtilities.invokeLater(helper::close); + } + } catch (Throwable failure) { + failure.printStackTrace(System.err); + System.exit(1); + } + } + + private void open(String windowTitle) { + var configuration = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration(); + Rectangle bounds = configuration.getBounds(); + float scale = Math.min((float) bounds.width / PreSplashLayout.WIDTH, (float) bounds.height / PreSplashLayout.HEIGHT) * PreSplashLayout.SCREEN_PERCENTAGE; + int width = Math.max(1, Math.round(PreSplashLayout.WIDTH * scale)); + int height = Math.max(1, Math.round(PreSplashLayout.HEIGHT * scale)); + + window = new JDialog((Frame) null, windowTitle, false, configuration); + window.setType(Window.Type.UTILITY); + window.setUndecorated(true); + window.setResizable(false); + window.setFocusableWindowState(false); + window.setAutoRequestFocus(false); + window.setAlwaysOnTop(true); + window.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); + window.setContentPane(renderer); + window.setSize(width, height); + window.setLocation(bounds.x + (bounds.width - width) / 2, bounds.y + (bounds.height - height) / 2); + window.setVisible(true); + + timer = new Timer(1000 / TARGET_FRAME_RATE, _ -> { + if (!window.isDisplayable()) { + close(); + return; + } + renderer.repaint(); + }); + + timer.start(); + } + + private static void signalStartupReady() { + try { + Protocol.ready(REPLIES); + } catch (IOException failure) { + failure.printStackTrace(System.err); + System.exit(1); + } + } + + private static void log(PreSplashLogger.Level level, String message, @Nullable Throwable failure) { + try { + Protocol.log(REPLIES, level, message, failure); + } catch (IOException error) { + System.err.println("[" + level + "] [Pre Splash Renderer]: " + message); + if (failure != null) { + failure.printStackTrace(System.err); + } + error.printStackTrace(System.err); + } + } + + private void close() { + if (timer != null) { + timer.stop(); + } + if (window != null) { + window.dispose(); + } + System.exit(0); + } + } + } + // +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashState.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashState.java new file mode 100644 index 000000000..9b0873476 --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashState.java @@ -0,0 +1,14 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.cleanroom.splash.pre; + +public record PreSplashState(String title, String message, String details) { +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/package-info.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/package-info.java new file mode 100644 index 000000000..b62fbed75 --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/package-info.java @@ -0,0 +1,14 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +@NullMarked +package com.cleanroommc.cleanroom.splash.pre; + +import org.jspecify.annotations.NullMarked; diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/AsyncFontLoader.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/AsyncFontLoader.java new file mode 100644 index 000000000..6d277cc49 --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/AsyncFontLoader.java @@ -0,0 +1,203 @@ +package com.cleanroommc.cleanroom.splash.pre.renderer; + +import com.cleanroommc.kirino.ui.font.McTtfFontData; +import com.cleanroommc.mcttf.extract.AssetSource; +import com.google.common.base.Preconditions; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import org.apache.commons.lang3.time.StopWatch; +import org.jspecify.annotations.Nullable; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; + +import static com.cleanroommc.cleanroom.splash.pre.renderer.PreSplashLogger.LOGGER; + +/** + * FreeType & GL agnostic async Minecraft font loader. + * + *

Note: Only used by {@link SdlSplashRenderer}.

+ */ +final class AsyncFontLoader implements AutoCloseable { + + private static final class Assets implements AssetSource { + + private static final Pattern HASH = Pattern.compile("[0-9a-f]{40}"); + + private final Path directory; + private final @Nullable Map index; + + private Assets(Path directory, @Nullable String assetIndex) { + this.directory = directory; + if (assetIndex == null) { + index = null; + return; + } + + index = new HashMap<>(); + Path file = directory.resolve("indexes").resolve(assetIndex + ".json"); + try (var reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) { + JsonObject objects = JsonParser.parseReader(reader).getAsJsonObject().getAsJsonObject("objects"); + if (objects != null) { + for (var entry : objects.entrySet()) { + String hash = entry.getValue().getAsJsonObject().get("hash").getAsString(); + if (!HASH.matcher(hash).matches()) { + throw new IOException("Invalid asset hash: " + hash); + } + + index.put(entry.getKey(), directory.resolve("objects").resolve(hash.substring(0, 2)).resolve(hash)); + } + } + } catch (Throwable failure) { + index.clear(); + LOGGER.warn("Could not read pre splash asset index {}.", file, failure); + } + } + + @Nullable + private Path find(String path) { + Preconditions.checkArgument(path.startsWith("assets/"), "Invalid asset path: %s", path); + + String name = path.substring("assets/".length()); + Path file = index == null ? directory.resolve(name) : index.get(name); + return file != null && Files.isRegularFile(file) ? file : null; + } + + @Override + public boolean exists(String path) { + return find(path) != null || SdlSplashRenderer.class.getResource("/" + path) != null; + } + + @Override + public InputStream open(String path) throws IOException { + Path file = find(path); + if (file != null) { + return Files.newInputStream(file); + } + InputStream input = SdlSplashRenderer.class.getResourceAsStream("/" + path); + if (input == null) { + throw new FileNotFoundException(path); + } + return input; + } + + @Override + public void close() { + // NO OP + } + } + + private static final int LOAD_TIMEOUT_SECOND = 30; + private static final int THREAD_STOP_TIMEOUT_SECOND = 2; + + final Thread thread; + private final long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(LOAD_TIMEOUT_SECOND); + private byte @Nullable [] data; + private boolean finished; + private boolean closed; + + AsyncFontLoader(File assetsDirectory, @Nullable String assetIndex) { + thread = new Thread(() -> load(assetsDirectory, assetIndex), "Pre Splash Font Loader"); + thread.setDaemon(true); + } + + synchronized boolean isFinished() { + if (!finished && deadline - System.nanoTime() <= 0) { + LOGGER.warn("Pre splash Minecraft font loading timed out after {} seconds.", LOAD_TIMEOUT_SECOND); + cancel(); + } + + return finished; + } + + @SuppressWarnings("DataFlowIssue") + synchronized byte @Nullable [] take() { + byte[] data = this.data; + this.data = null; + return data; + } + + @SuppressWarnings("DataFlowIssue") + private void load(File assetsDirectory, @Nullable String assetIndex) { + StopWatch stopWatch = StopWatch.createStarted(); + byte[] data = null; + + try { + synchronized (this) { + if (closed || isFinished()) { + return; + } + } + + Assets source = new Assets(assetsDirectory.toPath(), assetIndex); + + synchronized (this) { + if (closed || isFinished()) { + source.close(); + return; + } + } + + data = McTtfFontData.loadDefault(source, "pre_splash"); + } catch (Throwable failure) { + LOGGER.warn("Could not prepare the pre splash Minecraft font.", failure); + } finally { + stopWatch.stop(); + synchronized (this) { + if (!closed && !isFinished()) { + this.data = data; + if (data != null) { + LOGGER.info("Pre splash Minecraft font loaded in {} ms.", stopWatch.getTime(TimeUnit.MILLISECONDS)); + } + } + finished = true; + } + } + } + + private void cancel() { + synchronized (this) { + closed = true; + finished = true; + data = null; + } + + thread.interrupt(); + } + + @Override + public void close() { + cancel(); + if (Thread.currentThread() == thread) { + return; + } + + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(THREAD_STOP_TIMEOUT_SECOND); + boolean interrupted = false; + while (thread.isAlive()) { + long remaining = deadline - System.nanoTime(); + if (remaining <= 0) { + LOGGER.warn("Pre splash font loader did not stop within {} seconds.", THREAD_STOP_TIMEOUT_SECOND); + break; + } + try { + TimeUnit.NANOSECONDS.timedJoin(thread, remaining); + } catch (InterruptedException e) { + interrupted = true; + } + } + + if (interrupted) { + Thread.currentThread().interrupt(); + } + } +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/IconDrawer.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/IconDrawer.java new file mode 100644 index 000000000..654a6efee --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/IconDrawer.java @@ -0,0 +1,209 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.cleanroom.splash.pre.renderer; + +import com.cleanroommc.kirino.engine.render.core.shader.ImmediateShaderAccess; +import com.cleanroommc.kirino.gl.shader.Shader; +import com.cleanroommc.kirino.gl.shader.ShaderProgram; +import com.cleanroommc.kirino.gl.texture.GLTexture; +import com.cleanroommc.kirino.gl.texture.accessor.Texture2DAccessor; +import com.cleanroommc.kirino.gl.texture.meta.FilterMode; +import com.cleanroommc.kirino.gl.texture.meta.WrapMode; +import com.cleanroommc.kirino.gl.vao.VAO; +import com.cleanroommc.kirino.utils.MinecraftResourceUtils; +import com.cleanroommc.kirino.utils.ResourceLocation; +import com.google.common.base.Preconditions; +import org.apache.commons.lang3.time.StopWatch; +import org.jspecify.annotations.Nullable; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL45; +import org.lwjgl.stb.STBImage; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.system.MemoryUtil; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import static com.cleanroommc.cleanroom.splash.pre.renderer.PreSplashLogger.LOGGER; + +/** + *

Note: Only used by {@link SdlSplashRenderer}.

+ */ +final class IconDrawer implements AutoCloseable { + + private static final ResourceLocation VERTEX_SHADER = new ResourceLocation("cleanroom:shaders/icon.vert"); + private static final ResourceLocation FRAGMENT_SHADER = new ResourceLocation("cleanroom:shaders/icon.frag"); + private static final ResourceLocation LOGO = new ResourceLocation("cleanroom:icon.png"); + + private final StopWatch stopWatch = new StopWatch(); + private final VAO dummyVao; // borrowed + private final @Nullable Shader vertexShader; + private final @Nullable Shader fragmentShader; + private final @Nullable ShaderProgram program; + private final @Nullable Texture2DAccessor icon; + + IconDrawer(ImmediateShaderAccess shaders, VAO dummyVao, Path gameDirectory) throws IOException { + Preconditions.checkNotNull(shaders); + Preconditions.checkNotNull(gameDirectory); + Preconditions.checkNotNull(dummyVao); + + this.dummyVao = dummyVao; + + try { + vertexShader = shaders.makeShader(VERTEX_SHADER); + fragmentShader = shaders.makeShader(FRAGMENT_SHADER); + shaders.submitToGL(vertexShader, fragmentShader); + program = shaders.makeProgram(true, vertexShader, fragmentShader); + + for (String uniform : List.of( + "resolution", + "progress", + "logoTexture", + "logoCenter", + "logoScale", + "background", + "glow", + "time", + "enableGlow")) { + Preconditions.checkState(program.uniformLocation(uniform) >= 0, "Missing uniform: %s", uniform); + } + + program.uniform1i("logoTexture", 0); + program.uniform2f("resolution", PreSplashLayout.WIDTH, PreSplashLayout.HEIGHT); + program.uniform3f("background", + ((PreSplashLayout.BACKGROUND >> 16) & 255) / 255f, + ((PreSplashLayout.BACKGROUND >> 8) & 255) / 255f, + (PreSplashLayout.BACKGROUND & 255) / 255f); + program.uniform3f("glow", + ((PreSplashLayout.GLOW_COLOR >> 16) & 255) / 255f, + ((PreSplashLayout.GLOW_COLOR >> 8) & 255) / 255f, + (PreSplashLayout.GLOW_COLOR & 255) / 255f); + program.uniform1b("enableGlow", PreSplashLayout.ENABLE_GLOW); + + icon = loadIcon(gameDirectory); + } catch (Throwable failure) { + try { + close(); + } catch (Throwable cleanup) { + failure.addSuppressed(cleanup); + } + throw failure; + } + } + + private static Texture2DAccessor loadIcon(Path gameDirectory) throws IOException { + Path customIcon = gameDirectory.resolve("config").resolve("cleanroom_pre_splash_icon.png"); + + if (Files.isRegularFile(customIcon)) { + try { + return loadIcon(Files.readAllBytes(customIcon)); + } catch (IOException failure) { + LOGGER.warn("Could not load custom pre splash icon {}.", customIcon, failure); + } + } + + try (var input = MinecraftResourceUtils.getEarlyInputStream(LOGO)) { + return loadIcon(input.readAllBytes()); + } + } + + private static Texture2DAccessor loadIcon(byte[] bytes) throws IOException { + ByteBuffer encoded = MemoryUtil.memAlloc(bytes.length); + ByteBuffer pixels = null; + GLTexture texture = null; + try (MemoryStack stack = MemoryStack.stackPush()) { + encoded.put(bytes).flip(); + var width = stack.mallocInt(1); + var height = stack.mallocInt(1); + var channels = stack.mallocInt(1); + pixels = STBImage.stbi_load_from_memory(encoded, width, height, channels, STBImage.STBI_rgb_alpha); + if (pixels == null) { + throw new IOException("Could not decode pre splash icon: " + STBImage.stbi_failure_reason()); + } + + texture = GLTexture.newDsaTex2D(width.get(0), height.get(0)); + Texture2DAccessor accessor = new Texture2DAccessor(true, texture); + accessor.highlevel().alloc(false, pixels); + accessor.setCommonParams(FilterMode.LINEAR, FilterMode.LINEAR, WrapMode.CLAMP_TO_EDGE, WrapMode.CLAMP_TO_EDGE); + return accessor; + } catch (Throwable failure) { + if (texture != null) { + try { + texture.disposeManually(); + } catch (Throwable cleanup) { + failure.addSuppressed(cleanup); + } + } + throw failure; + } finally { + if (pixels != null) { + STBImage.stbi_image_free(pixels); + } + MemoryUtil.memFree(encoded); + } + } + + void render(float x, float y, float width, float height) { + Preconditions.checkNotNull(program); + Preconditions.checkNotNull(icon); + Preconditions.checkArgument(width > 0 && height > 0); + + long elapsedMillis = stopWatch.getTime(TimeUnit.MILLISECONDS); + float progress = Math.min(1f, elapsedMillis / (float) SdlSplashRenderer.ICON_ANIM_DURATION_MILLIS); + + program.uniform2f("logoCenter", (x + width / 2f) / PreSplashLayout.WIDTH, 1f - (y + height / 2f) / PreSplashLayout.HEIGHT); + program.uniform2f("logoScale", width / PreSplashLayout.WIDTH, height / PreSplashLayout.HEIGHT); + program.uniform1f("progress", progress); + program.uniform1f("time", elapsedMillis / 1000f); + icon.bindUnit(0); + dummyVao.bind(); + + program.use(); + GL11.glDrawArrays(GL11.GL_TRIANGLES, 0, 3); + program.use0(); + + VAO.bind(0); + GL45.glBindTextureUnit(0, 0); + + if (!stopWatch.isStarted()) { + stopWatch.start(); + } + } + + @Override + public void close() { + try { + if (icon != null) { + icon.texture.disposeManually(); + } + } finally { + try { + if (program != null) { + program.disposeManually(); + } + } finally { + try { + if (fragmentShader != null && fragmentShader.getShaderID() != 0) { + fragmentShader.disposeManually(); + } + } finally { + if (vertexShader != null && vertexShader.getShaderID() != 0) { + vertexShader.disposeManually(); + } + } + } + } + } +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/LogoAnimationDrawer.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/LogoAnimationDrawer.java new file mode 100644 index 000000000..ac080cd60 --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/LogoAnimationDrawer.java @@ -0,0 +1,174 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.cleanroom.splash.pre.renderer; + +import com.cleanroommc.kirino.engine.render.core.shader.ImmediateShaderAccess; +import com.cleanroommc.kirino.gl.shader.Shader; +import com.cleanroommc.kirino.gl.shader.ShaderProgram; +import com.cleanroommc.kirino.gl.texture.GLTexture; +import com.cleanroommc.kirino.gl.texture.accessor.Texture2DAccessor; +import com.cleanroommc.kirino.gl.texture.meta.FilterMode; +import com.cleanroommc.kirino.gl.texture.meta.WrapMode; +import com.cleanroommc.kirino.gl.vao.VAO; +import com.cleanroommc.kirino.utils.MinecraftResourceUtils; +import com.cleanroommc.kirino.utils.ResourceLocation; +import com.google.common.base.Preconditions; +import org.apache.commons.lang3.time.StopWatch; +import org.jspecify.annotations.Nullable; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL45; +import org.lwjgl.stb.STBImage; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.system.MemoryUtil; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.List; +import java.util.concurrent.TimeUnit; + +/** + *

Note: Only used by {@link SdlSplashRenderer}.

+ */ +final class LogoAnimationDrawer implements AutoCloseable { + + private static final ResourceLocation VERTEX_SHADER = new ResourceLocation("cleanroom:shaders/logo_animation.vert"); + private static final ResourceLocation FRAGMENT_SHADER = new ResourceLocation("cleanroom:shaders/logo_animation.frag"); + private static final ResourceLocation LOGO = new ResourceLocation("cleanroom:icon.png"); + + private final StopWatch stopWatch = new StopWatch(); + private final VAO dummyVao; // borrowed + private final @Nullable Shader vertexShader; + private final @Nullable Shader fragmentShader; + private final @Nullable ShaderProgram program; + private final @Nullable Texture2DAccessor logo; + + public LogoAnimationDrawer(ImmediateShaderAccess shaders, VAO dummyVao) throws IOException { + Preconditions.checkNotNull(shaders); + Preconditions.checkNotNull(dummyVao); + + this.dummyVao = dummyVao; + + try { + vertexShader = shaders.makeShader(VERTEX_SHADER); + fragmentShader = shaders.makeShader(FRAGMENT_SHADER); + shaders.submitToGL(vertexShader, fragmentShader); + program = shaders.makeProgram(true, vertexShader, fragmentShader); + + for (String uniform : List.of("resolution", "progress", "logoTexture", "background")) { + Preconditions.checkState(program.uniformLocation(uniform) >= 0, "Missing uniform: %s", uniform); + } + + program.uniform1i("logoTexture", 0); + program.uniform3f("background", + ((PreSplashLayout.BACKGROUND >> 16) & 255) / 255f, + ((PreSplashLayout.BACKGROUND >> 8) & 255) / 255f, + (PreSplashLayout.BACKGROUND & 255) / 255f); + + logo = loadLogo(); + } catch (Throwable failure) { + try { + close(); + } catch (Throwable cleanup) { + failure.addSuppressed(cleanup); + } + throw failure; + } + } + + private static Texture2DAccessor loadLogo() throws IOException { + byte[] bytes; + try (var input = MinecraftResourceUtils.getEarlyInputStream(LOGO)) { + bytes = input.readAllBytes(); + } + + ByteBuffer encoded = MemoryUtil.memAlloc(bytes.length); + ByteBuffer pixels = null; + GLTexture texture = null; + try (MemoryStack stack = MemoryStack.stackPush()) { + encoded.put(bytes).flip(); + var width = stack.mallocInt(1); + var height = stack.mallocInt(1); + var channels = stack.mallocInt(1); + pixels = STBImage.stbi_load_from_memory(encoded, width, height, channels, STBImage.STBI_rgb_alpha); + if (pixels == null) { + throw new IOException("Could not decode pre splash logo: " + STBImage.stbi_failure_reason()); + } + + texture = GLTexture.newDsaTex2D(width.get(0), height.get(0)); + Texture2DAccessor accessor = new Texture2DAccessor(true, texture); + accessor.highlevel().alloc(false, pixels); + accessor.setCommonParams(FilterMode.LINEAR, FilterMode.LINEAR, WrapMode.CLAMP_TO_EDGE, WrapMode.CLAMP_TO_EDGE); + return accessor; + } catch (Throwable failure) { + if (texture != null) { + try { + texture.disposeManually(); + } catch (Throwable cleanup) { + failure.addSuppressed(cleanup); + } + } + throw failure; + } finally { + if (pixels != null) { + STBImage.stbi_image_free(pixels); + } + MemoryUtil.memFree(encoded); + } + } + + public void render(int width, int height) { + Preconditions.checkNotNull(program); + Preconditions.checkNotNull(logo); + + float progress = Math.min(1f, stopWatch.getTime(TimeUnit.MILLISECONDS) / (float) SdlSplashRenderer.LOGO_ANIM_DURATION_MILLIS); + + program.uniform2f("resolution", width, height); + program.uniform1f("progress", progress); + logo.bindUnit(0); + dummyVao.bind(); + + program.use(); + GL11.glDrawArrays(GL11.GL_TRIANGLES, 0, 3); + program.use0(); + + VAO.bind(0); + GL45.glBindTextureUnit(0, 0); + + if (!stopWatch.isStarted()) { + stopWatch.start(); + } + } + + @Override + public void close() { + try { + if (logo != null) { + logo.texture.disposeManually(); + } + } finally { + try { + if (program != null) { + program.disposeManually(); + } + } finally { + try { + if (fragmentShader != null && fragmentShader.getShaderID() != 0) { + fragmentShader.disposeManually(); + } + } finally { + if (vertexShader != null && vertexShader.getShaderID() != 0) { + vertexShader.disposeManually(); + } + } + } + } + } +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/PreSplashLayout.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/PreSplashLayout.java new file mode 100644 index 000000000..69227fee4 --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/PreSplashLayout.java @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.cleanroom.splash.pre.renderer; + +public final class PreSplashLayout { + + public static final int WIDTH = 720; + public static final int HEIGHT = 360; + public static final float SCREEN_PERCENTAGE = 0.35f; + public static final int BACKGROUND = 0xFF0E1116; + public static final int GLOW_COLOR = 0xFF455D74; + public static final boolean ENABLE_GLOW = false; + + private PreSplashLayout() { + } +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/PreSplashLogger.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/PreSplashLogger.java new file mode 100644 index 000000000..33e518577 --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/PreSplashLogger.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.cleanroom.splash.pre.renderer; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.jspecify.annotations.Nullable; + +import java.util.Objects; + +public final class PreSplashLogger { + + public enum Level { + TRACE, + DEBUG, + INFO, + WARN, + ERROR + } + + @FunctionalInterface + public interface Sink { + + void log(Level level, String message, @Nullable Throwable failure); + } + + private static final class Log4j { + + private static final Logger LOGGER = LogManager.getLogger("Pre Splash Renderer"); + + private static void log(Level level, String message, @Nullable Throwable failure) { + LOGGER.log(org.apache.logging.log4j.Level.valueOf(level.name()), message, failure); + } + } + + public static final PreSplashLogger LOGGER = new PreSplashLogger(); + + private static volatile @Nullable Sink sink; + + private PreSplashLogger() { + } + + public static void setSink(Sink sink) { + PreSplashLogger.sink = Objects.requireNonNull(sink); + } + + public void trace(String message, Object... arguments) { + log(Level.TRACE, message, arguments); + } + + public void debug(String message, Object... arguments) { + log(Level.DEBUG, message, arguments); + } + + public void info(String message, Object... arguments) { + log(Level.INFO, message, arguments); + } + + public void warn(String message, Object... arguments) { + log(Level.WARN, message, arguments); + } + + public void error(String message, Object... arguments) { + log(Level.ERROR, message, arguments); + } + + /** + * Supports {} placeholders and an optional Throwable. + */ + public void log(Level level, String message, Object... arguments) { + Throwable failure = arguments.length > 0 && arguments[arguments.length - 1] instanceof Throwable cause ? cause : null; + int count = arguments.length - (failure == null ? 0 : 1); + + if (count > 0) { + StringBuilder formatted = new StringBuilder(); + int offset = 0; + for (int i = 0; i < count; i++) { + int placeholder = message.indexOf("{}", offset); + if (placeholder < 0) { + break; + } + formatted.append(message, offset, placeholder).append(arguments[i]); + offset = placeholder + 2; + } + message = formatted.append(message, offset, message.length()).toString(); + } + + Sink sink = PreSplashLogger.sink; + if (sink == null) { + Log4j.log(level, message, failure); + } else { + sink.log(level, message, failure); + } + } +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SdlSplashRenderer.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SdlSplashRenderer.java new file mode 100644 index 000000000..51e3de369 --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SdlSplashRenderer.java @@ -0,0 +1,597 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.cleanroom.splash.pre.renderer; + +import com.cleanroommc.cleanroom.splash.pre.PreSplashState; +import com.cleanroommc.kirino.engine.render.core.shader.ImmediateShaderAccess; +import com.cleanroommc.kirino.gl.GLResourceManager; +import com.cleanroommc.kirino.gl.buffer.view.VBOView; +import com.cleanroommc.kirino.gl.vao.VAO; +import com.cleanroommc.kirino.gl.vao.attribute.AttributeLayout; +import com.cleanroommc.kirino.gl.vao.attribute.Stride; +import com.cleanroommc.kirino.ui.simplegui.SimpleGuiRuntime; +import com.cleanroommc.kirino.ui.simpletext.ST_Config; +import com.cleanroommc.kirino.ui.simpletext.ST_FontBackendType; +import com.cleanroommc.kirino.ui.simpletext.SimpleTextRuntime; +import com.cleanroommc.kirino.ui.simpletext.atlas.Tex2DArrayGlyphAtlas; +import com.cleanroommc.kirino.ui.simpletext.backend.DefaultTextProducer; +import com.cleanroommc.kirino.ui.simpletext.backend.DefaultTextRenderer; +import com.cleanroommc.kirino.ui.simpletext.backend.FreeTypeFontHandle; +import com.cleanroommc.kirino.ui.simpletext.backend.freetype.FreeTypeManager; +import com.cleanroommc.kirino.ui.simpletext.text.StyledText; +import com.cleanroommc.kirino.utils.MinecraftResourceUtils; +import com.cleanroommc.kirino.utils.ResourceLocation; +import com.cleanroommc.mcttf.glyph.GlyphBuilder; + +import com.google.common.base.Preconditions; +import org.apache.commons.lang3.time.StopWatch; +import org.jspecify.annotations.Nullable; + +import org.lwjgl.opengl.GL11; +import org.lwjgl.system.MemoryUtil; +import org.lwjgl.util.freetype.FT_Face; +import org.lwjgl.util.freetype.FreeType; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.concurrent.TimeUnit; + +import static com.cleanroommc.cleanroom.splash.pre.renderer.PreSplashLogger.LOGGER; + +public final class SdlSplashRenderer implements AutoCloseable { + + private static final ResourceLocation FALLBACK_FONT = new ResourceLocation("kirino:fonts/jetbrains/jetbrains_mono_nl_regular.ttf"); + private static final String ENGLISH_CHARACTERS = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; + + private static final long EARLY_TITLE_IN_ANIM_MILLIS = 200; // for "Warming Up" + private static final long EARLY_TITLE_CHAR_TYPE_MILLIS = 40; // for "Cleanroom" + private static final long EARLY_TITLE_CHAR_FADE_IN_MILLIS = 180; // for "Cleanroom" + private static final long EARLY_TITLE_HOLD_MILLIS = 650; // for "Cleanroom" + private static final long INTRO_FADE_OUT_ANIM_MILLIS = 200; + private static final long POST_INTRO_MASK_FADE_OUT_MILLIS = 150; + private static final long POST_INTRO_LOADING_BAR_CYCLE_MILLIS = 1600; + private static final long MAX_TRANSITION_FRAME_MILLIS = 33; + private static final long LOADING_BAR_CYCLE_MILLIS = 1400; + private static final long LOADING_BAR_FADE_OUT_MILLIS = 200; + static final long LOGO_ANIM_DURATION_MILLIS = 1200; + static final long ICON_ANIM_DURATION_MILLIS = 480; + + private final Runnable startupReady; + + private final GLResourceManager.ResourceScope scope; + private final AsyncFontLoader fontLoader; + private final ImmediateShaderAccess shaders; + private final VAO dummyVao; + private final @Nullable SimpleGuiRuntime gui; + private final @Nullable LogoAnimationDrawer logoAnimation; + private final @Nullable IconDrawer icon; + private final @Nullable FreeTypeManager freeType; + + private final StopWatch mainStopWatch = new StopWatch(); + private final StopWatch earlyTitleStopWatch = new StopWatch(); + private final StopWatch titleHoldStopWatch = new StopWatch(); + private final StopWatch loadingBarFadeOutStopWatch = new StopWatch(); + private final StopWatch introFadeOutStopWatch = new StopWatch(); + private final StopWatch postIntroMaskStopWatch = new StopWatch(); + private long introFadeOutFrameMillis; + private long introFadeOutElapsedMillis; + private long postIntroMaskFrameMillis; + private long postIntroMaskElapsedMillis; + + private @Nullable ByteBuffer mcFontData; + private @Nullable PreSplashState state; + private @Nullable SimpleTextRuntime text; + private @Nullable SimpleTextRuntime introText; + + private enum IntroStage { + LOGO, + TITLE_WARMUP, + TITLE_FADE_IN, + TITLE_HOLD, + FONT_LOADING, + BAR_FADE_OUT, + ENGLISH_WARMUP, + FADE_OUT, + FINISHED + } + + // states + private boolean fontResolved; + private boolean fontResolveFailed = true; + private boolean earlyTitleFallback; + private boolean fontLoadingAtEntry; + private boolean englishWarmedUp; + private IntroStage introStage = IntroStage.LOGO; + + private boolean startupSignaled; + + public SdlSplashRenderer(Path gameDirectory, File assetsDirectory, @Nullable String assetIndex, Runnable startupReady) throws Exception { + LOGGER.info("Pre Splash Screen Backend: SDL + GL46"); + + Preconditions.checkNotNull(gameDirectory); + Preconditions.checkNotNull(assetsDirectory); + Preconditions.checkNotNull(startupReady); + + this.startupReady = startupReady; + + fontLoader = new AsyncFontLoader(assetsDirectory, assetIndex); + scope = GLResourceManager.openScope(); + + try { + fontLoader.thread.start(); + + shaders = ImmediateShaderAccess.fromSourceLoader(rl -> { + try (InputStream input = MinecraftResourceUtils.getEarlyInputStream(rl)) { + return new String(input.readAllBytes(), StandardCharsets.UTF_8); + } catch (IOException e) { + throw new IllegalStateException("Could not load pre splash shader " + rl, e); + } + }); + + AttributeLayout layout = new AttributeLayout(); + layout.push(new Stride(0)); + dummyVao = new VAO(layout, null, (VBOView @Nullable []) null); + + gui = new SimpleGuiRuntime(shaders, dummyVao, PreSplashLayout.WIDTH, PreSplashLayout.HEIGHT); + + logoAnimation = new LogoAnimationDrawer(shaders, dummyVao); + icon = new IconDrawer(shaders, dummyVao, gameDirectory); + + var constructor = FreeTypeManager.class.getDeclaredConstructor(); + constructor.setAccessible(true); + FreeTypeManager freeType = constructor.newInstance(); + freeType.loggerName = "pre_splash"; + freeType.init(); + this.freeType = freeType; + text = createText(freeType.load(FALLBACK_FONT, 0, 48), false); + + GL11.glDisable(GL11.GL_DEPTH_TEST); + GL11.glDisable(GL11.GL_CULL_FACE); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + } catch (Throwable failure) { + try { + close(); + } catch (Throwable cleanup) { + failure.addSuppressed(cleanup); + } + throw failure; + } + } + + /** + * Loads Minecraft font into {@link #text}. + * + * @return Whether Minecraft font is ready + */ + @SuppressWarnings("DataFlowIssue") + private boolean resolveFont() { + if (fontResolved) { + return !fontResolveFailed; + } + if (!fontLoader.isFinished()) { + return false; + } + + fontResolved = true; + byte[] bytes = fontLoader.take(); + if (bytes == null) { + LOGGER.warn("Could not load the pre splash Minecraft font."); + return false; + } + + Preconditions.checkNotNull(freeType); + + ByteBuffer data = null; + SimpleTextRuntime replacement; + try { + data = MemoryUtil.memAlloc(bytes.length); + data.put(bytes).flip(); + replacement = createText(freeType.load(data, 0, 48), true); + } catch (Throwable failure) { + if (data != null) { + try { + freeType.unload(data); + } catch (Throwable cleanup) { + failure.addSuppressed(cleanup); + } finally { + MemoryUtil.memFree(data); + } + } + LOGGER.warn("Could not initialize pre splash Minecraft text.", failure); + return false; + } + + SimpleTextRuntime previous = Preconditions.checkNotNull(text); + text = replacement; + mcFontData = data; + fontResolveFailed = false; + + if (previous != introText) { + try { + previous.close(); + } catch (Throwable failure) { + LOGGER.warn("Could not dispose the previous pre splash text runtime.", failure); + } finally { + freeType.unload(FALLBACK_FONT); + } + } + + return true; + } + + private SimpleTextRuntime createText(FT_Face face, boolean minecraftFont) { + ST_Config config = new ST_Config( + ST_FontBackendType.FREE_TYPE, + 48, + 16, + 12, + FreeType.FT_LOAD_RENDER | FreeType.FT_LOAD_NO_HINTING); + + SimpleGuiRuntime underline = null; + SimpleGuiRuntime strikethrough = null; + + try { + underline = new SimpleGuiRuntime(shaders, dummyVao, PreSplashLayout.WIDTH, PreSplashLayout.HEIGHT); + strikethrough = new SimpleGuiRuntime(shaders, dummyVao, PreSplashLayout.WIDTH, PreSplashLayout.HEIGHT); + return new SimpleTextRuntime( + _ -> new FreeTypeFontHandle(face), + runtime -> { + DefaultTextRenderer renderer = new DefaultTextRenderer(runtime, new Tex2DArrayGlyphAtlas(1024, 1024), shaders, 256, PreSplashLayout.WIDTH, PreSplashLayout.HEIGHT); + renderer.loggerName = "pre_splash"; + return renderer; + }, + runtime -> { + int layoutPixelSize = config.pixelSize(); + if (!minecraftFont) { + int capHeight = runtime.getGlyphMetrics(runtime.getFont().getGlyphIndex('A')).getGlyphHeight(); + layoutPixelSize = Math.round(capHeight * GlyphBuilder.LINE_HEIGHT_PIXELS / (float) GlyphBuilder.MC_LINE_TOP_PIXELS); + } + return new DefaultTextProducer(runtime, layoutPixelSize, GlyphBuilder.LINE_HEIGHT_PIXELS); + }, + shaders, + underline, + strikethrough, + config); + } catch (Throwable failure) { + try { + if (strikethrough != null) { + strikethrough.close(); + } + } catch (Throwable cleanup) { + failure.addSuppressed(cleanup); + } + try { + if (underline != null) { + underline.close(); + } + } catch (Throwable cleanup) { + failure.addSuppressed(cleanup); + } + throw failure; + } + } + + public void update(PreSplashState state) { + if (this.state == state) { + return; + } + + this.state = state; + } + + private static float easeInOut(float t) { + t = Math.clamp(t, 0f, 1f); + return t * t * (3f - 2f * t); + } + + public void render(int width, int height) { + if (state == null) { + return; + } + + float scale = Math.min((float) width / PreSplashLayout.WIDTH, (float) height / PreSplashLayout.HEIGHT); + int viewportWidth = Math.round(PreSplashLayout.WIDTH * scale); + int viewportHeight = Math.round(PreSplashLayout.HEIGHT * scale); + GL11.glViewport((width - viewportWidth) / 2, (height - viewportHeight) / 2, viewportWidth, viewportHeight); + + GL11.glClearColor( + ((PreSplashLayout.BACKGROUND >> 16) & 255) / 255f, + ((PreSplashLayout.BACKGROUND >> 8) & 255) / 255f, + (PreSplashLayout.BACKGROUND & 255) / 255f, + 1); + GL11.glClear(GL11.GL_COLOR_BUFFER_BIT); + + Preconditions.checkNotNull(logoAnimation); + Preconditions.checkNotNull(text); + Preconditions.checkNotNull(gui); + + // + if (!mainStopWatch.isStarted()) { + mainStopWatch.start(); + } + + if (introStage == IntroStage.LOGO && mainStopWatch.getTime(TimeUnit.MILLISECONDS) >= LOGO_ANIM_DURATION_MILLIS) { + fontLoadingAtEntry = !fontLoader.isFinished(); + earlyTitleFallback = fontLoadingAtEntry || !resolveFont(); + introText = text; + introStage = IntroStage.TITLE_WARMUP; + } + + if (introStage == IntroStage.TITLE_HOLD) { + if (!titleHoldStopWatch.isStarted()) { + titleHoldStopWatch.start(); + } + if (!englishWarmedUp) { + introStage = IntroStage.ENGLISH_WARMUP; + } else if (titleHoldStopWatch.getTime(TimeUnit.MILLISECONDS) >= EARLY_TITLE_HOLD_MILLIS) { + introStage = IntroStage.FADE_OUT; + introFadeOutStopWatch.start(); + } + } + + if (introStage == IntroStage.FONT_LOADING && fontLoader.isFinished()) { + introStage = IntroStage.BAR_FADE_OUT; + loadingBarFadeOutStopWatch.start(); + } + + if (introStage == IntroStage.ENGLISH_WARMUP) { + if (fontLoadingAtEntry) { + resolveFont(); + } + + text.begin(); + text.append(ENGLISH_CHARACTERS, 0, 0, 40, 0x00FFFFFF); + text.endDraw(); + GL11.glFinish(); + englishWarmedUp = true; + + if (fontLoadingAtEntry || titleHoldStopWatch.getTime(TimeUnit.MILLISECONDS) >= EARLY_TITLE_HOLD_MILLIS) { + introStage = IntroStage.FADE_OUT; + introFadeOutStopWatch.start(); + } else { + introStage = IntroStage.TITLE_HOLD; + } + } + + if (introStage != IntroStage.FINISHED) { + logoAnimation.render(viewportWidth, viewportHeight); + } + + if (introStage != IntroStage.LOGO && introStage != IntroStage.FINISHED) { + Preconditions.checkNotNull(introText); + + long titleTime = earlyTitleStopWatch.getTime(TimeUnit.MILLISECONDS); + String title = fontLoadingAtEntry ? "Warming Up" : "Cleanroom"; + long titleFadeDuration = fontLoadingAtEntry + ? EARLY_TITLE_IN_ANIM_MILLIS + : EARLY_TITLE_CHAR_FADE_IN_MILLIS + (title.length() - 1) * EARLY_TITLE_CHAR_TYPE_MILLIS; + float progress = switch (introStage) { + case TITLE_WARMUP -> 0; + case TITLE_FADE_IN -> easeInOut(titleTime / (float) titleFadeDuration); + default -> 1; + }; + + int titleFontSize = earlyTitleFallback ? 30 : 40; + var lineInfo = introText.simulate(title, 0, 0, titleFontSize); + String styledTitle; + if (!fontLoadingAtEntry && introStage == IntroStage.TITLE_FADE_IN) { + StringBuilder characters = new StringBuilder(); + for (int i = 0; i < title.length(); i++) { + float characterProgress = easeInOut((titleTime - i * EARLY_TITLE_CHAR_TYPE_MILLIS) / (float) EARLY_TITLE_CHAR_FADE_IN_MILLIS); + characters.append("§c=rgba(255;255;255;").append((int) (characterProgress * 255)).append(")[").append(title.charAt(i)).append("]§"); + } + styledTitle = characters.toString(); + } else { + styledTitle = String.format("§c=rgba(255;255;255;%d)[%s]§", (int) (progress * 255), title); + } + + introText.begin(); + introText.appendStyled( + new StyledText(styledTitle), + 4 + (PreSplashLayout.WIDTH - lineInfo.getLineWidth()) / 2f, + PreSplashLayout.HEIGHT * 0.74f, + titleFontSize); + introText.endDraw(); + + boolean showLoadingBar = fontLoadingAtEntry && (introStage == IntroStage.TITLE_WARMUP + || introStage == IntroStage.TITLE_FADE_IN + || introStage == IntroStage.FONT_LOADING + || introStage == IntroStage.BAR_FADE_OUT); + + float barFadeOut = easeInOut(loadingBarFadeOutStopWatch.getTime(TimeUnit.MILLISECONDS) / (float) LOADING_BAR_FADE_OUT_MILLIS); + float barProgress = progress * (1f - barFadeOut); + long fadeOutTime = introFadeOutStopWatch.getTime(TimeUnit.MILLISECONDS); + introFadeOutElapsedMillis += Math.min(fadeOutTime - introFadeOutFrameMillis, MAX_TRANSITION_FRAME_MILLIS); + introFadeOutFrameMillis = fadeOutTime; + float fadeOut = easeInOut(introFadeOutElapsedMillis / (float) INTRO_FADE_OUT_ANIM_MILLIS); + + gui.begin(); + gui.append(stream -> { + if (showLoadingBar) { + float barHeight = 5; + float barWidth = 180; + float segmentWidth = 50; + float barX = (PreSplashLayout.WIDTH - barWidth) / 2f; + float barY = PreSplashLayout.HEIGHT * 0.83f; + float cycle = (titleTime % LOADING_BAR_CYCLE_MILLIS) / (float) LOADING_BAR_CYCLE_MILLIS; + float position = easeInOut(1f - Math.abs(cycle * 2f - 1f)); + stream.rectEx(barX, barY, barWidth, barHeight, (int) (barProgress * 40) << 24 | 0xFFFFFF) + .radius(barHeight / 2f, 1) + .emit(); + stream.rectEx(barX + position * (barWidth - segmentWidth), barY, segmentWidth, barHeight, (int) (barProgress * 255) << 24 | 0xB9C7DB) + .radius(barHeight / 2f, 1) + .emit(); + } + + stream.rect( + 0, + 0, + PreSplashLayout.WIDTH, + PreSplashLayout.HEIGHT, + (int) (fadeOut * 255) << 24 | (PreSplashLayout.BACKGROUND & 0xFFFFFF)); + }); + gui.endDraw(); + + if (introStage == IntroStage.TITLE_WARMUP) { + GL11.glFinish(); + introStage = IntroStage.TITLE_FADE_IN; + earlyTitleStopWatch.start(); + } else if (introStage == IntroStage.TITLE_FADE_IN && progress >= 1) { + introStage = fontLoadingAtEntry ? IntroStage.FONT_LOADING : IntroStage.TITLE_HOLD; + } else if (introStage == IntroStage.BAR_FADE_OUT && barFadeOut >= 1) { + introStage = IntroStage.ENGLISH_WARMUP; + } + + if (introStage == IntroStage.FADE_OUT && !startupSignaled) { + startupSignaled = true; + startupReady.run(); + } + if (introStage == IntroStage.FADE_OUT && fadeOut >= 1) { + introStage = IntroStage.FINISHED; + } + } + // + + if (introStage == IntroStage.FINISHED) { + Preconditions.checkNotNull(icon); + + int iconWidth = 120; + int iconHeight = 120; + icon.render((PreSplashLayout.WIDTH - iconWidth) / 2f, PreSplashLayout.HEIGHT * 0.15f, iconWidth, iconHeight); + + text.begin(); + var lineInfo = text.simulate(state.title(), 0, 0, 40); + text.append(state.title(), (PreSplashLayout.WIDTH - lineInfo.getLineWidth()) / 2f, 200, 40, 0xFFF1F4FA); + lineInfo = text.simulate(state.message(), 0, 0, 25); + text.append(state.message(), (PreSplashLayout.WIDTH - lineInfo.getLineWidth()) / 2f, 240, 25, 0xFFB9C7DB); + if (!state.details().isEmpty()) { + lineInfo = text.simulate(state.details(), 0, 0, 25); + text.append(state.details(), (PreSplashLayout.WIDTH - lineInfo.getLineWidth()) / 2f, 292, 25, 0xFF8998AE); + } + text.endDraw(); + + gui.begin(); + gui.append(stream -> { + float barHeight = 7; + float barWidth = 300; + float segmentWidth = 80; + float barX = (PreSplashLayout.WIDTH - barWidth) / 2f; + float cycle = (mainStopWatch.getTime(TimeUnit.MILLISECONDS) % POST_INTRO_LOADING_BAR_CYCLE_MILLIS) / (float) POST_INTRO_LOADING_BAR_CYCLE_MILLIS; + float position = easeInOut(1f - Math.abs(cycle * 2f - 1f)); + stream.rectEx(barX, 273, barWidth, barHeight, 0xFF263448) + .radius(barHeight / 2f, 1) + .emit(); + stream.rectEx(barX + position * (barWidth - segmentWidth), 273, segmentWidth, barHeight, 0xFF8AB9E8) + .radius(barHeight / 2f, 1) + .emit(); + }); + gui.endDraw(); + + long maskTime = postIntroMaskStopWatch.getTime(TimeUnit.MILLISECONDS); + boolean maskFinished = postIntroMaskElapsedMillis >= POST_INTRO_MASK_FADE_OUT_MILLIS; + if (!maskFinished) { + postIntroMaskElapsedMillis += Math.min(maskTime - postIntroMaskFrameMillis, MAX_TRANSITION_FRAME_MILLIS); + postIntroMaskFrameMillis = maskTime; + float opacity = 1f - easeInOut(postIntroMaskElapsedMillis / (float) POST_INTRO_MASK_FADE_OUT_MILLIS); + + gui.begin(); + gui.append(stream -> stream.rect( + 0, + 0, + PreSplashLayout.WIDTH, + PreSplashLayout.HEIGHT, + (int) (opacity * 255) << 24 | (PreSplashLayout.BACKGROUND & 0xFFFFFF))); + gui.endDraw(); + + if (!postIntroMaskStopWatch.isStarted()) { + postIntroMaskStopWatch.start(); + } + } + + if (maskFinished && introText != null) { + SimpleTextRuntime previous = introText; + introText = null; + if (previous != text) { + Preconditions.checkNotNull(freeType); + + try { + previous.close(); + } catch (Throwable failure) { + LOGGER.warn("Could not dispose the pre splash intro text runtime.", failure); + } finally { + freeType.unload(FALLBACK_FONT); + } + } + } + } + } + + @Override + public void close() throws Exception { + if (mainStopWatch.isStarted()) { + mainStopWatch.stop(); + LOGGER.info("Pre splash renderer finished in {}ms.", mainStopWatch.getTime(TimeUnit.MILLISECONDS)); + } + + try { + fontLoader.close(); + } finally { + try { + if (introText != null && introText != text) { + introText.close(); + } + } finally { + try { + if (text != null) { + text.close(); + } + } finally { + try { + if (icon != null) { + icon.close(); + } + } finally { + try { + if (logoAnimation != null) { + logoAnimation.close(); + } + } finally { + try { + if (gui != null) { + gui.close(); + } + } finally { + try { + if (freeType != null) { + freeType.destroy(); + } + } finally { + try { + if (mcFontData != null) { + MemoryUtil.memFree(mcFontData); + } + } finally { + scope.close(); + } + } + } + } + } + } + } + } + } +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SwingSplashRenderer.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SwingSplashRenderer.java new file mode 100644 index 000000000..18683a955 --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SwingSplashRenderer.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.cleanroom.splash.pre.renderer; + +import com.cleanroommc.cleanroom.splash.pre.PreSplashState; + +import org.jspecify.annotations.Nullable; + +import javax.swing.JPanel; +import java.awt.Color; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; + +import static com.cleanroommc.cleanroom.splash.pre.renderer.PreSplashLogger.LOGGER; + +public final class SwingSplashRenderer extends JPanel { + + private final Runnable startupReady; + + private @Nullable PreSplashState state; + private boolean startupSignaled; + + public SwingSplashRenderer(Runnable startupReady) { + LOGGER.info("Pre Splash Screen Backend: Swing"); + + this.startupReady = startupReady; + } + + public void update(PreSplashState state) { + if (this.state == state) { + return; + } + + this.state = state; + repaint(); + } + + @Override + protected void paintComponent(Graphics graphics) { + if (state == null) { + return; + } + + Graphics2D draw = (Graphics2D) graphics.create(); + try { + draw.setColor(new Color(PreSplashLayout.BACKGROUND, true)); + draw.fillRect(0, 0, getWidth(), getHeight()); + double scale = Math.min((double) getWidth() / PreSplashLayout.WIDTH, (double) getHeight() / PreSplashLayout.HEIGHT); + draw.translate((getWidth() - PreSplashLayout.WIDTH * scale) / 2, (getHeight() - PreSplashLayout.HEIGHT * scale) / 2); + draw.scale(scale, scale); + draw.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + draw.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + drawText(draw, state.title(), 48, 106, 32, 0xFFF1F4FA); + drawText(draw, state.message(), 48, 190, 16, 0xFFB9C7DB); + drawText(draw, state.details(), 48, 286, 16, 0xFF8998AE); + } finally { + draw.dispose(); + } + + if (!startupSignaled) { + startupSignaled = true; + startupReady.run(); + } + } + + private static void drawText(Graphics2D draw, String value, float x, float y, float size, int color) { + draw.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 1).deriveFont(size)); + draw.setColor(new Color(color, true)); + draw.drawString(value, x, y); + } +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/WindowsAppRegistration.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/WindowsAppRegistration.java new file mode 100644 index 000000000..dece72966 --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/WindowsAppRegistration.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.cleanroom.splash.pre.renderer; + +import com.google.common.base.Preconditions; +import org.lwjgl.sdl.SDL; +import org.lwjgl.sdl.SDLError; +import org.lwjgl.system.APIUtil; +import org.lwjgl.system.JNI; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.system.MemoryUtil; +import org.lwjgl.system.windows.User32; + +import java.util.UUID; + +public final class WindowsAppRegistration implements AutoCloseable { + + private long unregister; + + private WindowsAppRegistration(long unregister) { + this.unregister = unregister; + } + + public static WindowsAppRegistration register() { + // LWJGL 3.4.3's SDLBinding.kt adds SDL_ automatically, generating nonexistent SDL_SDL_* exports + + long register = APIUtil.apiGetFunctionAddress(SDL.getLibrary(), "SDL_RegisterApp"); + long unregister = APIUtil.apiGetFunctionAddress(SDL.getLibrary(), "SDL_UnregisterApp"); + try (MemoryStack stack = MemoryStack.stackPush()) { + // pre splash and game otherwise register SDL_app for the same process HINSTANCE + long name = MemoryUtil.memAddress(stack.UTF8("Cleanroom_PreSplash_" + UUID.randomUUID())); + + Preconditions.checkState(JNI.invokePPZ(name, User32.CS_BYTEALIGNCLIENT | User32.CS_OWNDC, 0L, register), + "SDL_RegisterApp: %s", SDLError.SDL_GetError()); + } + + return new WindowsAppRegistration(unregister); + } + + @Override + public void close() { + if (unregister != 0L) { + JNI.invokeV(unregister); + unregister = 0L; + } + } +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/package-info.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/package-info.java new file mode 100644 index 000000000..579d326e4 --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/package-info.java @@ -0,0 +1,14 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +@NullMarked +package com.cleanroommc.cleanroom.splash.pre.renderer; + +import org.jspecify.annotations.NullMarked; diff --git a/module/cleanroom/src/main/java/com/cleanroommc/discovery/CleanroomModDiscoverer.java b/module/cleanroom/src/main/java/com/cleanroommc/discovery/CleanroomModDiscoverer.java index 662fd4c1c..a2bead98c 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/discovery/CleanroomModDiscoverer.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/discovery/CleanroomModDiscoverer.java @@ -12,6 +12,8 @@ import com.cleanroommc.cleanmix.CleanMixModContainer; import com.cleanroommc.cleanmix.MixinConfiguration; +import com.cleanroommc.cleanroom.splash.pre.PreSplashManager; +import com.cleanroommc.cleanroom.splash.pre.PreSplashPhase; import com.cleanroommc.common.CleanroomContainer; import com.cleanroommc.common.CleanroomEnvironment; import com.cleanroommc.common.ConfigAnytimeContainer; @@ -160,6 +162,10 @@ public final class CleanroomModDiscoverer extends ModDiscoverer { private File fileDirector; private CleanroomModDiscoverer() { + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyPhase(PreSplashPhase.INITIAL_MOD_SCAN); + } + Map files = new LinkedHashMap<>(); for (File candidate : LibraryManager.getCandidates()) { files.putIfAbsent(normalize(candidate), false); @@ -172,7 +178,13 @@ private CleanroomModDiscoverer() { } } catch (URISyntaxException ignored) { } } + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.INITIAL_MOD_SCAN, "Scanning mods"); + } this.discover(files); + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.INITIAL_MOD_SCAN, "Finished discovering mods"); + } } public static CleanroomModDiscoverer instance() { @@ -422,6 +434,9 @@ public void discoverMixinMods() { if (!mod.hasMixinManifestAttributes()) { continue; } + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.CORE_MOD_LAUNCH, "Loading mixins: " + mod.file().getName()); + } if (mod.coremod() == null) { try { Launch.classLoader.addURL(mod.file().toURI().toURL()); @@ -447,6 +462,9 @@ public void discoverCoreMods(File minecraftDirectory, LaunchClassLoader classLoa File modsDir = setupCoreModDir(minecraftDirectory); findDerpMods(modsDir); if (fileDirector != null) { + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.CORE_MOD_LAUNCH, "Installing mods with File Director"); + } discoverFileDirectorMods(minecraftDirectory, classLoader); } @@ -580,7 +598,13 @@ private void discoverFileDirectorMods(File gameDir, LaunchClassLoader classLoade return true; }); if (!installed.isEmpty()) { + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.CORE_MOD_LAUNCH, "Scanning installed mods"); + } discover(installed); + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.CORE_MOD_LAUNCH, "Finished discovering installed mods"); + } } } @@ -734,6 +758,9 @@ private void discoverCoreMod( if (containNonMods) { addContainedDepsToClasspath(classLoader, attributes, containedDepsDir); } + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.CORE_MOD_LAUNCH, "Loading launch plugin: " + file.getName()); + } CleanroomLog.get().info("Cascading tweaker {} from {}", discoveredMod.tweaker(), file.getName()); Integer sortOrder = Ints.tryParse(Strings.nullToEmpty(attributes.getValue("TweakOrder"))); CoreModManager.injectDiscoveredCascadingTweaker( diff --git a/module/cleanroom/src/main/resources/assets/cleanroom/shaders/icon.frag b/module/cleanroom/src/main/resources/assets/cleanroom/shaders/icon.frag new file mode 100644 index 000000000..ddfde822b --- /dev/null +++ b/module/cleanroom/src/main/resources/assets/cleanroom/shaders/icon.frag @@ -0,0 +1,97 @@ +#version 460 core + +in vec2 ViewportUV; +out vec4 Color; + +uniform vec2 resolution; +uniform float progress; +uniform sampler2D logoTexture; +uniform vec2 logoCenter; +uniform vec2 logoScale; +uniform vec3 background; +uniform vec3 glow; +uniform float time; +uniform bool enableGlow; + +const float INITIAL_SCALE = 0.94; +const float INITIAL_BLUR = 4.0; +const float INITIAL_OFFSET_Y = 7.0; +const float GLOW_SPEED = 0.85; +const float GLOW_INTENSITY = 0.06; + +vec3 sampleBackground(vec2 uv) +{ + if (!enableGlow) return background; + + float glowTime = time * GLOW_SPEED; + float aspectRatio = resolution.x / max(resolution.y, 1.0); + float widthMix = 0.65 * smoothstep(1.3, 4.5, aspectRatio); + float materialWidth = mix(resolution.y, resolution.x, widthMix); + vec2 p = (uv - 0.5) * resolution * vec2(1.0, -1.0); + vec2 materialPos = p / max(vec2(materialWidth, resolution.y), vec2(1.0)); + + float centerGlow = 1.0 - smoothstep(0.05, 0.85, length(materialPos)); + vec3 color = background * (0.96 + centerGlow * 0.04); + + vec2 glowCenterA = vec2(0.42 * cos(glowTime), 0.23 * sin(glowTime * 2.0)); + vec2 deltaA = materialPos - glowCenterA; + float glowA = exp(-dot(deltaA, deltaA) * 4.5); + + vec2 glowCenterB = vec2(-0.34 * cos(glowTime * 2.0), 0.18 * sin(glowTime)); + vec2 deltaB = materialPos - glowCenterB; + float glowB = exp(-dot(deltaB, deltaB) * 7.0); + + float flowCoordinate = dot(materialPos, normalize(vec2(0.82, -0.57))); + float flowPosition = 0.55 * sin(glowTime); + float flowDelta = flowCoordinate - flowPosition; + float flowingBand = exp(-flowDelta * flowDelta * 5.5); + + float interiorLight = glowA * 0.55 + glowB * 0.28 + flowingBand * 0.42; + return color + glow * interiorLight * GLOW_INTENSITY; +} + +vec4 sampleLogo(vec2 uv) +{ + if (any(lessThan(uv, vec2(0.0))) || any(greaterThan(uv, vec2(1.0)))) return vec4(0.0); + vec4 color = texture(logoTexture, vec2(uv.x, 1.0 - uv.y)); + return vec4(color.rgb * color.a, color.a); +} + +void main() +{ + float t = clamp(progress, 0.0, 1.0); + float eased = 1.0 - pow(1.0 - t, 3.0); + vec3 backgroundColor = mix(background, sampleBackground(ViewportUV), eased); + float opacity = smoothstep(0.0, 0.72, t); + vec2 scale = logoScale * mix(INITIAL_SCALE, 1.0, eased); + vec2 center = logoCenter - vec2(0.0, INITIAL_OFFSET_Y / resolution.y) * (1.0 - eased); + vec2 uv = (ViewportUV - center) / scale + 0.5; + vec2 blurStep = INITIAL_BLUR * (1.0 - eased) / resolution / scale; + vec2 extent = blurStep * 2.0; + + if (opacity == 0.0 || any(lessThan(uv, -extent)) || any(greaterThan(uv, 1.0 + extent))) + { + Color = vec4(backgroundColor, 1.0); + return; + } + + vec4 logo; + if (t == 1.0) + { + logo = sampleLogo(uv); + } + else + { + const float weights[5] = float[5](1.0, 4.0, 6.0, 4.0, 1.0); + logo = vec4(0.0); + for (int y = -2; y <= 2; y++) + { + for (int x = -2; x <= 2; x++) + { + logo += sampleLogo(uv + vec2(x, y) * blurStep) * weights[x + 2] * weights[y + 2] / 256.0; + } + } + } + + Color = vec4(backgroundColor * (1.0 - logo.a * opacity) + logo.rgb * opacity, 1.0); +} diff --git a/module/cleanroom/src/main/resources/assets/cleanroom/shaders/icon.vert b/module/cleanroom/src/main/resources/assets/cleanroom/shaders/icon.vert new file mode 100644 index 000000000..d0ba5f721 --- /dev/null +++ b/module/cleanroom/src/main/resources/assets/cleanroom/shaders/icon.vert @@ -0,0 +1,10 @@ +#version 460 core + +out vec2 ViewportUV; + +void main() +{ + vec2 position = vec2((gl_VertexID << 1) & 2, gl_VertexID & 2); + ViewportUV = position; + gl_Position = vec4(position * 2.0 - 1.0, 0.0, 1.0); +} diff --git a/module/cleanroom/src/main/resources/assets/cleanroom/shaders/logo_animation.frag b/module/cleanroom/src/main/resources/assets/cleanroom/shaders/logo_animation.frag new file mode 100644 index 000000000..085878f20 --- /dev/null +++ b/module/cleanroom/src/main/resources/assets/cleanroom/shaders/logo_animation.frag @@ -0,0 +1,168 @@ +#version 460 core + +uniform vec2 resolution; +uniform float progress; +uniform sampler2D logoTexture; +uniform vec3 background; + +in vec2 ViewportUV; +out vec4 Color; + +const vec2 LOGO_CENTER = vec2(0.5, 0.548); +const float FACE_DURATION = 0.607; +const float SETTLE_START = 0.836; +const float SETTLE_END = 1.0; +const float GLOW_FADE_START = 0.541; +const float GLOW_FADE_END = SETTLE_END; + +vec2 faceE1(int face) +{ + if (face == 0) return vec2(0.437, 0.226); + if (face == 1) return vec2(-0.437, 0.226); + return vec2(0.0, -0.548); +} + +vec2 faceE2(int face) +{ + if (face == 0) return vec2(-0.437, 0.226); + if (face == 1) return vec2(0.0, -0.548); + return vec2(0.437, 0.226); +} + +vec2 faceLocalUV(vec2 logoUV, int face) +{ + vec2 a = faceE1(face); + vec2 b = faceE2(face); + vec2 p = logoUV - LOGO_CENTER; + float det = a.x * b.y - a.y * b.x; + return vec2((p.x * b.y - p.y * b.x), (a.x * p.y - a.y * p.x)) / det; +} + +float faceCoverage(vec2 logoUV, int face) +{ + vec2 q = faceLocalUV(logoUV, face); + vec2 w = max(fwidth(q), vec2(0.001)); + vec2 lo = smoothstep(-w, w, q); + vec2 hi = vec2(1.0) - smoothstep(vec2(1.0) - w, vec2(1.0) + w, q); + return clamp(lo.x * lo.y * hi.x * hi.y, 0.0, 1.0); +} + +vec4 sampleLogo(vec2 uv) +{ + if (any(lessThan(uv, vec2(0.0))) || any(greaterThan(uv, vec2(1.0)))) return vec4(0.0); + return texture(logoTexture, vec2(uv.x, 1.0 - uv.y)); +} + +vec2 rotate2D(vec2 p, float angle) +{ + float c = cos(angle), s = sin(angle); + return mat2(c, s, -s, c) * p; +} + +float ease(float x) +{ + x = clamp(x, 0.0, 1.0); + return x * x * (3.0 - 2.0 * x); +} + +float easeOut(float x) +{ + x = clamp(x, 0.0, 1.0); + return 1.0 - pow(1.0 - x, 3.0); +} + +vec2 entryOffset(int face) +{ + if (face == 0) return vec2(0.0, 0.105); + if (face == 1) return vec2(-0.115, -0.05); + return vec2(0.115, -0.05); +} + +float entryAngle(int face) +{ + if (face == 0) return -0.18; + if (face == 1) return -0.22; + return 0.22; +} + +float startProgress(int face) +{ + if (face == 0) return 0.033; + if (face == 1) return 0.115; + return 0.197; +} + +vec4 animateFace(vec2 screenLogoUV, int face, float t) +{ + float prog = clamp((t - startProgress(face)) / FACE_DURATION, 0.0, 1.0); + float approach = easeOut(clamp(prog * 1.16, 0.0, 1.0)); + + vec2 translation = entryOffset(face) * (1.0 - approach); + float rotation = entryAngle(face) * (1.0 - approach); + vec2 canonicalUV = rotate2D(screenLogoUV - LOGO_CENTER - translation, -rotation) + LOGO_CENTER; + + vec4 texel = sampleLogo(canonicalUV); + float region = faceCoverage(canonicalUV, face); + vec2 local = faceLocalUV(canonicalUV, face); + + float path = clamp(0.5 * local.x + 0.5 * local.y, 0.0, 1.0); + if (face == 1) path = clamp(1.0 - (0.6 * local.x + 0.4 * local.y), 0.0, 1.0); + if (face == 2) path = clamp(0.35 * local.x + 0.65 * local.y, 0.0, 1.0); + float front = ease(clamp((prog * 1.15 - path + 0.05) / 0.12, 0.0, 1.0)); + + float inside = min(min(local.x, local.y), min(1.0 - local.x, 1.0 - local.y)); + float edgeBand = 1.0 - smoothstep(0.045, 0.1, inside); + float fillIn = ease(clamp((prog - 0.37) / 0.52, 0.0, 1.0)); + float visibility = region * texel.a * max(edgeBand * front, fillIn); + + float light = (1.0 - fillIn) * edgeBand * front * 0.74; + vec3 rgb = mix(texel.rgb, vec3(0.96, 0.97, 1.0), light); + return vec4(rgb * visibility, visibility); +} + +float faceGlow(vec2 screenLogoUV, int face, float t) +{ + float prog = clamp((t - startProgress(face)) / FACE_DURATION, 0.0, 1.0); + if (prog <= 0.001) return 0.0; + float approach = easeOut(clamp(prog * 1.16, 0.0, 1.0)); + vec2 q = rotate2D(screenLogoUV - LOGO_CENTER - entryOffset(face) * (1.0 - approach), -entryAngle(face) * (1.0 - approach)) + LOGO_CENTER; + vec2 v = faceLocalUV(q, face); + float edge = min(min(v.x, v.y), min(1.0 - v.x, 1.0 - v.y)); + float front = clamp(prog * 1.5, 0.0, 1.0); + return (0.12 * exp(-18.0 * abs(edge)) + 0.06 * exp(-7.0 * abs(edge))) * front; +} + +void main() +{ + float scale = resolution.y * 0.4; + vec2 logoUV = (ViewportUV - 0.5) * resolution / scale + 0.5; + float t = clamp(progress, 0.0, 1.0); + + vec4 texel = sampleLogo(logoUV); + vec4 original = vec4(texel.rgb * texel.a, texel.a); + + vec4 logo = original; + float glow = 0.0; + + if (t < SETTLE_END) + { + vec4 assembled = vec4(0.0); + for (int i = 0; i < 3; ++i) + { + vec4 piece = animateFace(logoUV, i, t); + assembled.rgb += (1.0 - assembled.a) * piece.rgb; + assembled.a += (1.0 - assembled.a) * piece.a; + glow += faceGlow(logoUV, i, t); + } + + float settle = ease((t - SETTLE_START) / (SETTLE_END - SETTLE_START)); + logo = mix(assembled, original, settle); + + float glowStrength = 1.0 - ease((t - GLOW_FADE_START) / (GLOW_FADE_END - GLOW_FADE_START)); + glow *= glowStrength; + } + + vec3 rgb = background * (1.0 - logo.a) + logo.rgb; + rgb += glow * vec3(0.57, 0.74, 1.0); + Color = vec4(rgb, 1.0); +} diff --git a/module/cleanroom/src/main/resources/assets/cleanroom/shaders/logo_animation.vert b/module/cleanroom/src/main/resources/assets/cleanroom/shaders/logo_animation.vert new file mode 100644 index 000000000..d0ba5f721 --- /dev/null +++ b/module/cleanroom/src/main/resources/assets/cleanroom/shaders/logo_animation.vert @@ -0,0 +1,10 @@ +#version 460 core + +out vec2 ViewportUV; + +void main() +{ + vec2 position = vec2((gl_VertexID << 1) & 2, gl_VertexID & 2); + ViewportUV = position; + gl_Position = vec4(position * 2.0 - 1.0, 0.0, 1.0); +} diff --git a/module/forge/src/main/java/net/minecraftforge/fml/client/FMLClientHandler.java b/module/forge/src/main/java/net/minecraftforge/fml/client/FMLClientHandler.java index fb57c59d7..0ea650af1 100644 --- a/module/forge/src/main/java/net/minecraftforge/fml/client/FMLClientHandler.java +++ b/module/forge/src/main/java/net/minecraftforge/fml/client/FMLClientHandler.java @@ -35,6 +35,7 @@ import java.util.concurrent.TimeUnit; import java.util.function.Predicate; +import com.cleanroommc.cleanroom.splash.pre.PreSplashScreenContainer; import com.cleanroommc.client.modlist.ModListConfig; import com.cleanroommc.client.modlist.screen.ModListScreen; import com.cleanroommc.common.PatchModPresentChecker; @@ -218,6 +219,8 @@ public class FMLClientHandler implements IFMLSidedHandler */ public void beginMinecraftLoading(Minecraft minecraft, List resourcePackList, IReloadableResourceManager resourceManager, MetadataSerializer metaSerializer) { + PreSplashScreenContainer.finish(); + detectOptifine(); SplashProgress.start(); client = minecraft; diff --git a/module/forge/src/main/java/net/minecraftforge/fml/common/launcher/FMLDeobfTweaker.java b/module/forge/src/main/java/net/minecraftforge/fml/common/launcher/FMLDeobfTweaker.java index 806dedf1d..f3193836c 100644 --- a/module/forge/src/main/java/net/minecraftforge/fml/common/launcher/FMLDeobfTweaker.java +++ b/module/forge/src/main/java/net/minecraftforge/fml/common/launcher/FMLDeobfTweaker.java @@ -22,7 +22,10 @@ import java.io.File; import java.util.List; +import com.cleanroommc.cleanroom.splash.pre.PreSplashManager; +import com.cleanroommc.cleanroom.splash.pre.PreSplashPhase; import com.cleanroommc.cleanmix.service.CleanMixService; +import com.cleanroommc.common.CleanroomEnvironment; import net.minecraft.launchwrapper.ITweaker; import net.minecraft.launchwrapper.LaunchClassLoader; import net.minecraftforge.fml.common.FMLLog; @@ -42,6 +45,10 @@ public void acceptOptions(List args, File gameDir, File assetsDir, Strin @Override public void injectIntoClassLoader(LaunchClassLoader classLoader) { + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.CORE_MOD_LAUNCH, "Preparing class transformers"); + } + // Deobfuscation transformer, always last, and the access transformer tweaker as well TransformerDelegate.registerRenameTransformer(new DeobfuscationTransformer()); // Add all the access transformers now as well @@ -55,10 +62,18 @@ public void injectIntoClassLoader(LaunchClassLoader classLoader) classLoader.registerTransformer("net.minecraftforge.fml.common.asm.transformers.ItemBlockSpecialTransformer"); classLoader.registerTransformer("net.minecraftforge.fml.common.asm.transformers.PotionEffectTransformer"); + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.CORE_MOD_LAUNCH, "Initializing mixins"); + } + ((CleanMixService) MixinService.getService()).transitionToInit(); try { + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.CORE_MOD_LAUNCH, "Preparing Minecraft classes"); + } + FMLLog.log.debug("Validating minecraft"); Loader.injectData(FMLInjectionData.data()); Loader.instance(); diff --git a/module/forge/src/main/java/net/minecraftforge/fml/common/launcher/FMLTweaker.java b/module/forge/src/main/java/net/minecraftforge/fml/common/launcher/FMLTweaker.java index faf27b031..24b7d8f86 100644 --- a/module/forge/src/main/java/net/minecraftforge/fml/common/launcher/FMLTweaker.java +++ b/module/forge/src/main/java/net/minecraftforge/fml/common/launcher/FMLTweaker.java @@ -19,6 +19,9 @@ package net.minecraftforge.fml.common.launcher; +import com.cleanroommc.cleanroom.splash.pre.PreSplashManager; +import com.cleanroommc.cleanroom.splash.pre.PreSplashPhase; +import com.cleanroommc.cleanroom.splash.pre.PreSplashScreenContainer; import com.cleanroommc.common.CleanroomEnvironment; import com.google.common.collect.Lists; import com.google.common.collect.Maps; @@ -144,6 +147,10 @@ else if (arg.contains("=")) @Override public void injectIntoClassLoader(LaunchClassLoader classLoader) { + PreSplashManager.INSTANCE.notifyPhase(PreSplashPhase.FML_SETUP); + String assets = launchArgs.get("--assetsDir"); + PreSplashScreenContainer.start(gameDir.toPath(), assets == null ? new File(gameDir, "assets") : new File(assets), launchArgs.get("--assetIndex")); + FMLLaunchHandler.configureForClientLaunch(classLoader, this); FMLLaunchHandler.appendCoreMods(); } diff --git a/module/forge/src/main/java/net/minecraftforge/fml/relauncher/CoreModManager.java b/module/forge/src/main/java/net/minecraftforge/fml/relauncher/CoreModManager.java index 04b9a3a47..211af3aff 100644 --- a/module/forge/src/main/java/net/minecraftforge/fml/relauncher/CoreModManager.java +++ b/module/forge/src/main/java/net/minecraftforge/fml/relauncher/CoreModManager.java @@ -20,6 +20,8 @@ package net.minecraftforge.fml.relauncher; import com.cleanroommc.cleanmix.CleanMixHooks; +import com.cleanroommc.cleanroom.splash.pre.PreSplashManager; +import com.cleanroommc.cleanroom.splash.pre.PreSplashPhase; import com.google.common.base.Strings; import com.google.common.collect.*; import com.google.common.primitives.Ints; @@ -103,6 +105,10 @@ public void acceptOptions(List args, File gameDir, File assetsDir, Strin @Override public void injectIntoClassLoader(LaunchClassLoader classLoader) { + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.CORE_MOD_LAUNCH, "Registering transformers: " + name); + } + FMLLog.log.debug("Injecting coremod {} \\{{}\\} class transformers", name, coreModInstance.getClass().getName()); List ts = Lists.newArrayList(); String[] asmTransformerClass = coreModInstance.getASMTransformerClass(); @@ -121,6 +127,10 @@ public void injectIntoClassLoader(LaunchClassLoader classLoader) } FMLLog.log.debug("Injection complete"); + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.CORE_MOD_LAUNCH, "Initializing core mod: " + name); + } + FMLLog.log.debug("Running coremod plugin for {} {{}}", name, coreModInstance.getClass().getName()); Map data = new HashMap<>(); data.put("mcLocation", mcDir); @@ -132,6 +142,10 @@ public void injectIntoClassLoader(LaunchClassLoader classLoader) String setupClass = coreModInstance.getSetupClass(); if (setupClass != null) { + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.CORE_MOD_LAUNCH, "Running setup: " + name); + } + try { IFMLCallHook call = (IFMLCallHook) Class.forName(setupClass, true, classLoader).getConstructor().newInstance(); @@ -222,7 +236,7 @@ public static void handleLaunch(File mcDir, LaunchClassLoader classLoader, FMLTw { for (String path : System.getProperty("crl.dev.extrapath").split(File.pathSeparator)) { - try + try { Launch.classLoader.addURL(new File(path).getAbsoluteFile().toURI().toURL()); FMLLog.log.debug("Adding extra path {} to class path", path); @@ -244,8 +258,19 @@ public static void handleLaunch(File mcDir, LaunchClassLoader classLoader, FMLTw FMLLog.log.info("Found a command line coremod : {}", coreModClassName); loadCoreMod(classLoader, coreModClassName, null); } + + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyPhase(PreSplashPhase.CORE_MOD_LAUNCH); + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.CORE_MOD_LAUNCH, "Discovering core mods"); + } + // Coremods CleanroomModDiscoverer.instance().discoverCoreMods(mcDir, classLoader, tweaker); + + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.CORE_MOD_LAUNCH, "Discovering mixin mods"); + } + // Mixin Mods CleanroomModDiscoverer.instance().discoverMixinMods(); } @@ -290,7 +315,7 @@ public static boolean isCoreModLoaded(String coreModClass) private static FMLPluginWrapper loadCoreMod(LaunchClassLoader classLoader, String coreModClass, File location) { - if (loadedPlugins.contains(coreModClass)) + if (loadedPlugins.contains(coreModClass)) { return null; } @@ -403,6 +428,10 @@ else if (deobfuscatedEnvironment && location == null) // This is probably a mod public static boolean loadCoreModFromDiscoveredJar(LaunchClassLoader classLoader, String coreModClass, File location) { + if (CleanroomEnvironment.side().isClient() && !loadedPlugins.contains(coreModClass)) { + String coreModName = coreModClass.substring(coreModClass.lastIndexOf('.') + 1); + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.CORE_MOD_LAUNCH, "Loading core mod: " + coreModName); + } return loadCoreMod(classLoader, coreModClass, location) != null; } @@ -420,8 +449,18 @@ public static void injectCoreModTweaks(FMLInjectionAndSortingTweaker fmlInjectio List tweakers = (List) Launch.blackboard.get("Tweaks"); // Add the sorting tweaker first- it'll appear twice in the list tweakers.addFirst(fmlInjectionAndSortingTweaker); + + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.CORE_MOD_LAUNCH, "Loading additional core mods"); + } + // Load rescued (ForceLoadAsMod) coremods CleanroomModDiscoverer.instance().rescueDroppedCoremods(); + + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.CORE_MOD_LAUNCH, "Loading early mixins"); + } + // Early Mixin Loaders Instantiation CleanMixHooks.loadMixinBooterEarlyMixins(loadPlugins); // Add loadPlugins (including rescued coremods) @@ -432,6 +471,10 @@ public static void injectCoreModTweaks(FMLInjectionAndSortingTweaker fmlInjectio public static void sortTweakList() { + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.CORE_MOD_LAUNCH, "Sorting launch plugins"); + } + @SuppressWarnings("unchecked") List tweakers = (List) Launch.blackboard.get("Tweaks"); // Basically a copy of Collections.sort pre 8u20, optimized as we know we're an array list. diff --git a/module/kirino b/module/kirino index 9d446db2d..73939d44b 160000 --- a/module/kirino +++ b/module/kirino @@ -1 +1 @@ -Subproject commit 9d446db2deaa505d5dd66b488a1af8c385ff27de +Subproject commit 73939d44b5228bca30c0c2a2e8638a6f92390f70 diff --git a/module/minecraft/patches/net/minecraft/client/Minecraft.java.patch b/module/minecraft/patches/net/minecraft/client/Minecraft.java.patch index fd5afa422..1d51573fc 100644 --- a/module/minecraft/patches/net/minecraft/client/Minecraft.java.patch +++ b/module/minecraft/patches/net/minecraft/client/Minecraft.java.patch @@ -67,34 +67,47 @@ this.isDemo = gameConfig.gameInfo.isDemo; this.displayWidth = gameConfig.displayInfo.width > 0 ? gameConfig.displayInfo.width : 1; this.displayHeight = gameConfig.displayInfo.height > 0 ? gameConfig.displayInfo.height : 1; -@@ -447,6 +436,7 @@ +@@ -447,6 +436,10 @@ /** Starts the game: initializes the canvas, the title, the settings, etcetera. */ private void init() throws IOException, LWJGLException { ++ com.cleanroommc.cleanroom.splash.pre.PreSplashManager.INSTANCE.notifyPhase(com.cleanroommc.cleanroom.splash.pre.PreSplashPhase.MINECRAFT_INIT); ++ com.cleanroommc.cleanroom.splash.pre.PreSplashManager.INSTANCE.notifyDetails(com.cleanroommc.cleanroom.splash.pre.PreSplashPhase.MINECRAFT_INIT, "Initializing video"); + com.cleanroommc.client.sdl.SDL.ensureVideo(); ++ com.cleanroommc.cleanroom.splash.pre.PreSplashManager.INSTANCE.notifyDetails(com.cleanroommc.cleanroom.splash.pre.PreSplashPhase.MINECRAFT_INIT, "Loading game settings"); this.gameSettings = new GameSettings(this, this.gameDir); this.creativeSettings = new CreativeSettings(this, this.gameDir); this.defaultResourcePacks.add(this.defaultResourcePack); -@@ -455,8 +445,9 @@ +@@ -455,25 +448,33 @@ this.displayWidth = this.gameSettings.overrideWidth; this.displayHeight = this.gameSettings.overrideHeight; } - - LOGGER.info("LWJGL Version: {}", Sys.getVersion()); ++ com.cleanroommc.cleanroom.splash.pre.PreSplashManager.INSTANCE.notifyDetails(com.cleanroommc.cleanroom.splash.pre.PreSplashPhase.MINECRAFT_INIT, "Creating game window"); + com.cleanroommc.client.sdl.Window window = com.cleanroommc.client.sdl.SDL.createWindow().title("Cleanroom").size(this.displayWidth, this.displayHeight).resizable().vsync(this.gameSettings.enableVsync).openGL().build(); + com.cleanroommc.client.sdl.CleanroomWindowBridge.install(window); + LOGGER.info("LWJGL Version: {}", org.lwjgl.Version.getVersion()); this.setWindowIcon(); this.setInitialDisplayMode(); ++ com.cleanroommc.cleanroom.splash.pre.PreSplashManager.INSTANCE.notifyDetails(com.cleanroommc.cleanroom.splash.pre.PreSplashPhase.MINECRAFT_INIT, "Initializing native resources"); this.createDisplay(); -@@ -468,12 +459,13 @@ + OpenGlHelper.initializeTextures(); + this.framebuffer = new Framebuffer(this.displayWidth, this.displayHeight, true); + this.framebuffer.setFramebufferColor(0.0F, 0.0F, 0.0F, 0.0F); ++ com.cleanroommc.cleanroom.splash.pre.PreSplashManager.INSTANCE.notifyDetails(com.cleanroommc.cleanroom.splash.pre.PreSplashPhase.MINECRAFT_INIT, "Initializing resource manager"); + this.registerMetadataSerializers(); + this.resourcePackRepository = new ResourcePackRepository( this.fileResourcepacks, new File(this.gameDir, "server-resource-packs"), this.defaultResourcePack, this.metadataSerializer, this.gameSettings ); this.resourceManager = new SimpleReloadableResourceManager(this.metadataSerializer); ++ com.cleanroommc.cleanroom.splash.pre.PreSplashManager.INSTANCE.notifyDetails(com.cleanroommc.cleanroom.splash.pre.PreSplashPhase.MINECRAFT_INIT, "Initializing immediate client services"); + com.cleanroommc.kirino.ImmediateClientServices.initAndWarmUp(this.resourceManager); ++ com.cleanroommc.cleanroom.splash.pre.PreSplashManager.INSTANCE.notifyDetails(com.cleanroommc.cleanroom.splash.pre.PreSplashPhase.MINECRAFT_INIT, "Loading languages"); this.languageManager = new LanguageManager(this.metadataSerializer, this.gameSettings.language); this.resourceManager.registerReloadListener(this.languageManager); - this.refreshResources(); ++ com.cleanroommc.cleanroom.splash.pre.PreSplashManager.INSTANCE.notifyPhase(com.cleanroommc.cleanroom.splash.pre.PreSplashPhase.RIGHT_BEFORE_SPLASH); + net.minecraftforge.fml.client.FMLClientHandler.instance().beginMinecraftLoading(this, this.defaultResourcePacks, this.resourceManager, this.metadataSerializer); this.renderEngine = new TextureManager(this.resourceManager); this.resourceManager.registerReloadListener(this.renderEngine); @@ -103,7 +116,7 @@ this.skinManager = new SkinManager(this.renderEngine, new File(this.fileAssets, "skins"), this.sessionService); this.saveLoader = new AnvilSaveConverter(new File(this.gameDir, "saves"), this.dataFixer); this.soundHandler = new SoundHandler(this.resourceManager, this.gameSettings); -@@ -491,6 +483,8 @@ +@@ -491,6 +492,8 @@ this.resourceManager.registerReloadListener(new GrassColorReloadListener()); this.resourceManager.registerReloadListener(new FoliageColorReloadListener()); this.mouseHelper = new MouseHelper(); @@ -112,7 +125,7 @@ this.checkGLError("Pre startup"); GlStateManager.enableTexture2D(); GlStateManager.shadeModel(7425); -@@ -504,19 +498,24 @@ +@@ -504,19 +507,24 @@ GlStateManager.loadIdentity(); GlStateManager.matrixMode(5888); this.checkGLError("Startup"); @@ -137,7 +150,7 @@ this.entityRenderer = new EntityRenderer(this, this.resourceManager); this.resourceManager.registerReloadListener(this.entityRenderer); this.blockRenderDispatcher = new BlockRendererDispatcher(this.modelManager.getBlockModelShapes(), this.blockColors); -@@ -527,18 +526,26 @@ +@@ -527,18 +535,26 @@ this.resourceManager.registerReloadListener(this.searchTreeManager); GlStateManager.viewport(0, 0, this.displayWidth, this.displayHeight); this.effectRenderer = new ParticleManager(this.world, this.renderEngine); @@ -167,7 +180,7 @@ if (this.gameSettings.fullScreen && !this.fullscreen) { this.toggleFullscreen(); } -@@ -599,34 +606,22 @@ +@@ -599,34 +615,22 @@ private void createDisplay() throws LWJGLException { Display.setResizable(true); @@ -213,7 +226,7 @@ } } -@@ -640,7 +635,7 @@ +@@ -640,7 +644,7 @@ inputstream = this.defaultResourcePack.getInputStreamAssets(new ResourceLocation("icons/icon_16x16.png")); inputstream1 = this.defaultResourcePack.getInputStreamAssets(new ResourceLocation("icons/icon_32x32.png")); if (inputstream != null && inputstream1 != null) { @@ -222,7 +235,7 @@ } } catch (IOException ioexception) { LOGGER.error("Couldn't set icon", ioexception); -@@ -679,6 +674,7 @@ +@@ -679,6 +683,7 @@ } private void startTimerHackThread() { @@ -230,7 +243,7 @@ Thread thread = new Thread("Timer hack thread") { @Override public void run() { -@@ -691,6 +687,7 @@ +@@ -691,6 +696,7 @@ } }; thread.setDaemon(true); @@ -238,7 +251,7 @@ thread.start(); } -@@ -704,22 +701,26 @@ +@@ -704,22 +710,26 @@ File file1 = new File(getMinecraft().gameDir, "crash-reports"); File file2 = new File(file1, "crash-" + new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss").format(new Date()) + "-client.txt"); Bootstrap.printToSYSOUT(crashReportIn.getCompleteReport()); @@ -268,7 +281,7 @@ public void refreshResources() { List list = Lists.newArrayList(this.defaultResourcePacks); if (this.integratedServer != null) { -@@ -902,16 +903,22 @@ +@@ -902,16 +912,22 @@ * @param guiScreenIn The {@link GuiScreen} to display. If it is {@code null}, any open GUI will be closed. */ public void displayGuiScreen(@Nullable GuiScreen guiScreenIn) { @@ -295,7 +308,7 @@ if (guiScreenIn instanceof GuiMainMenu || guiScreenIn instanceof GuiMultiplayer) { this.gameSettings.showDebugInfo = false; this.ingameGUI.getChatGUI().clearChatMessages(true); -@@ -962,7 +969,8 @@ +@@ -962,7 +978,8 @@ this.soundHandler.unloadSounds(); } finally { @@ -305,7 +318,7 @@ if (!this.hasCrashed) { System.exit(0); } -@@ -980,6 +988,8 @@ +@@ -980,6 +997,8 @@ } this.timer.updateTimer(); @@ -314,7 +327,7 @@ this.profiler.startSection("scheduledExecutables"); synchronized (this.scheduledTasks) { while (!this.scheduledTasks.isEmpty()) { -@@ -999,7 +1009,7 @@ +@@ -999,7 +1018,7 @@ long i1 = System.nanoTime() - l; this.checkGLError("Pre render"); this.profiler.endStartSection("sound"); @@ -323,7 +336,7 @@ this.profiler.endSection(); this.profiler.startSection("render"); GlStateManager.pushMatrix(); -@@ -1009,11 +1019,13 @@ +@@ -1009,11 +1028,13 @@ GlStateManager.enableTexture2D(); this.profiler.endSection(); if (!this.skipRenderWorld) { @@ -337,7 +350,7 @@ } this.profiler.endSection(); -@@ -1096,7 +1108,7 @@ +@@ -1096,7 +1117,7 @@ } protected void checkWindowResize() { @@ -346,7 +359,7 @@ int i = this.displayWidth; int j = this.displayHeight; this.displayWidth = Display.getWidth(); -@@ -1308,9 +1320,9 @@ +@@ -1308,9 +1329,9 @@ if (this.leftClickCounter <= 0 && !this.player.isHandActive()) { if (leftClick && this.objectMouseOver != null && this.objectMouseOver.typeOfHit == RayTraceResult.Type.BLOCK) { BlockPos blockpos = this.objectMouseOver.getBlockPos(); @@ -359,7 +372,7 @@ this.player.swingArm(EnumHand.MAIN_HAND); } } else { -@@ -1333,7 +1345,8 @@ +@@ -1333,7 +1354,8 @@ break; case BLOCK: BlockPos blockpos = this.objectMouseOver.getBlockPos(); @@ -369,7 +382,7 @@ this.playerController.clickBlock(blockpos, this.objectMouseOver.sideHit); break; } -@@ -1343,6 +1356,7 @@ +@@ -1343,6 +1365,7 @@ } this.player.resetCooldown(); @@ -377,7 +390,7 @@ } this.player.swingArm(EnumHand.MAIN_HAND); -@@ -1399,6 +1413,7 @@ +@@ -1399,6 +1422,7 @@ } } @@ -385,7 +398,7 @@ if (!itemstack.isEmpty() && this.playerController.processRightClick(this.player, this.world, enumhand) == EnumActionResult.SUCCESS) { this.entityRenderer.itemRenderer.resetEquippedProgress(enumhand); -@@ -1414,7 +1429,12 @@ +@@ -1414,7 +1438,12 @@ try { this.fullscreen = !this.fullscreen; this.gameSettings.fullScreen = this.fullscreen; @@ -399,7 +412,7 @@ this.updateDisplayMode(); this.displayWidth = Display.getDisplayMode().getWidth(); this.displayHeight = Display.getDisplayMode().getHeight(); -@@ -1444,7 +1464,17 @@ +@@ -1444,7 +1473,17 @@ this.updateFramebufferSize(); } @@ -418,7 +431,7 @@ Display.setVSyncEnabled(this.gameSettings.enableVsync); this.updateDisplay(); } catch (Exception exception) { -@@ -1483,6 +1513,8 @@ +@@ -1483,6 +1522,8 @@ this.rightClickDelayTimer--; } @@ -427,7 +440,7 @@ this.profiler.startSection("gui"); if (!this.isGamePaused) { this.ingameGUI.updateTick(); -@@ -1632,6 +1664,7 @@ +@@ -1632,6 +1673,7 @@ } this.profiler.endSection(); @@ -435,7 +448,7 @@ this.systemTime = getSystemTime(); } -@@ -1705,6 +1738,7 @@ +@@ -1705,6 +1747,7 @@ } } } @@ -443,7 +456,7 @@ } this.processKeyBinds(); -@@ -1896,6 +1930,8 @@ +@@ -1896,6 +1939,8 @@ private void runTickMouse() throws IOException { while (Mouse.next()) { @@ -452,7 +465,7 @@ int i = Mouse.getEventButton(); KeyBinding.setKeyBindState(i - 100, Mouse.getEventButtonState()); if (Mouse.getEventButtonState()) { -@@ -1931,6 +1967,7 @@ +@@ -1931,6 +1976,7 @@ this.currentScreen.handleMouseInput(); } } @@ -460,7 +473,7 @@ } } -@@ -1949,6 +1986,7 @@ +@@ -1949,6 +1995,7 @@ /** Arguments: World foldername, World ingame name, WorldSettings */ public void launchIntegratedServer(String folderName, String worldName, @Nullable WorldSettings worldSettingsIn) { @@ -468,7 +481,7 @@ this.loadWorld(null); System.gc(); ISaveHandler isavehandler = this.saveLoader.getSaveLoader(folderName, false); -@@ -1990,6 +2028,11 @@ +@@ -1990,6 +2037,11 @@ this.loadingScreen.displaySavingString(I18n.format("menu.loadingLevel")); while (!this.integratedServer.serverIsInRunLoop()) { @@ -480,7 +493,7 @@ String s = this.integratedServer.getUserMessage(); if (s != null) { this.loadingScreen.displayLoadingString(I18n.format(s)); -@@ -2007,8 +2050,13 @@ +@@ -2007,8 +2059,13 @@ SocketAddress socketaddress = this.integratedServer.getNetworkSystem().addLocalEndpoint(); NetworkManager networkmanager = NetworkManager.provideLocalClient(socketaddress); networkmanager.setNetHandler(new NetHandlerLoginClient(networkmanager, this, null)); @@ -496,7 +509,7 @@ this.networkManager = networkmanager; } -@@ -2019,6 +2067,8 @@ +@@ -2019,6 +2076,8 @@ /** par2Str is displayed on the loading screen to the user unloads the current world first */ public void loadWorld(@Nullable WorldClient worldClientIn, String loadingMessage) { @@ -505,7 +518,7 @@ if (worldClientIn == null) { NetHandlerPlayClient nethandlerplayclient = this.getConnection(); if (nethandlerplayclient != null) { -@@ -2027,6 +2077,14 @@ +@@ -2027,6 +2086,14 @@ if (this.integratedServer != null && this.integratedServer.isAnvilFileSet()) { this.integratedServer.initiateShutdown(); @@ -520,7 +533,7 @@ } this.integratedServer = null; -@@ -2047,6 +2105,7 @@ +@@ -2047,6 +2114,7 @@ this.ingameGUI.resetPlayersOverlayFooterHeader(); this.setServerData(null); this.integratedServerIsRunning = false; @@ -528,7 +541,7 @@ } this.soundHandler.stopSounds(); -@@ -2060,6 +2119,8 @@ +@@ -2060,6 +2128,8 @@ } TileEntityRendererDispatcher.instance.setWorld(worldClientIn); @@ -537,7 +550,7 @@ if (worldClientIn != null) { if (!this.integratedServerIsRunning) { AuthenticationService authenticationservice = new YggdrasilAuthenticationService(this.proxy, UUID.randomUUID().toString()); -@@ -2112,6 +2173,7 @@ +@@ -2112,6 +2182,7 @@ this.player == null ? new RecipeBook() : this.player.getRecipeBook() ); this.player.getDataManager().setEntryValues(entityplayersp.getDataManager().getAll()); @@ -545,7 +558,7 @@ this.player.dimension = dimension; this.renderViewEntity = this.player; this.player.preparePlayerToSpawn(); -@@ -2153,110 +2215,8 @@ +@@ -2153,110 +2224,8 @@ /** Called when user clicked he's mouse middle button (pick block) */ private void middleClickMouse() { if (this.objectMouseOver != null && this.objectMouseOver.typeOfHit != RayTraceResult.Type.MISS) { @@ -658,7 +671,7 @@ } } -@@ -2288,12 +2248,16 @@ +@@ -2288,12 +2257,16 @@ }); theCrash.getCategory().addDetail("LWJGL", new ICrashReportDetail() { public String call() throws Exception { @@ -677,7 +690,7 @@ } }); theCrash.getCategory().addDetail("GL Caps", new ICrashReportDetail() { -@@ -2372,6 +2336,7 @@ +@@ -2372,6 +2345,7 @@ return instance; } @@ -685,7 +698,7 @@ public ListenableFuture scheduleResourcesRefresh() { return this.addScheduledTask(new Runnable() { @Override -@@ -2536,15 +2501,8 @@ +@@ -2536,15 +2510,8 @@ /** Used in the usage snooper. */ public static int getGLMaximumTextureSize() { @@ -703,7 +716,7 @@ } /** Returns whether snooping is enabled or not. */ -@@ -2658,6 +2616,9 @@ +@@ -2658,6 +2625,9 @@ } if (this.player != null) { @@ -713,7 +726,7 @@ if (this.player.world.provider instanceof WorldProviderHell) { return MusicTicker.MusicType.NETHER; } else if (this.player.world.provider instanceof WorldProviderEnd) { -@@ -2677,9 +2638,9 @@ +@@ -2677,9 +2647,9 @@ if (i != 0 && !Keyboard.isRepeatEvent()) { if (!(this.currentScreen instanceof GuiControls) || ((GuiControls)this.currentScreen).time <= getSystemTime() - 20L) { if (Keyboard.getEventKeyState()) { @@ -725,7 +738,7 @@ this.ingameGUI .getChatGUI() .printChatMessage(ScreenShotHelper.saveScreenshot(this.gameDir, this.displayWidth, this.displayHeight, this.framebuffer)); -@@ -2691,7 +2652,7 @@ +@@ -2691,7 +2661,7 @@ ((ScreenChatOptions)this.currentScreen).updateNarratorButton(); } } @@ -734,7 +747,7 @@ } } } -@@ -2720,7 +2681,7 @@ +@@ -2720,7 +2690,7 @@ try { return Futures.immediateFuture(callableToSchedule.call()); } catch (Exception exception) { @@ -743,7 +756,7 @@ } } else { ListenableFutureTask listenablefuturetask = ListenableFutureTask.create(callableToSchedule); -@@ -2798,11 +2759,24 @@ +@@ -2798,11 +2768,24 @@ return this.timer.elapsedPartialTicks; } @@ -769,7 +782,7 @@ public boolean isReducedDebug() { return this.player != null && this.player.hasReducedDebug() || this.gameSettings.reducedDebugInfo; } -@@ -2814,4 +2788,8 @@ +@@ -2814,4 +2797,8 @@ public Tutorial getTutorial() { return this.tutorial; }