more-shader-refactors #11

Merged
embeddedt merged 9 commits from mitchej123/celeritas:more-shader-refactors into stonecutter 2025-04-26 16:37:18 -04:00
150 changed files with 2754 additions and 1866 deletions

No files matched your search

+2
View File
@@ -35,6 +35,8 @@ dependencies {
compileOnly("org.ow2.asm:asm:9.6") compileOnly("org.ow2.asm:asm:9.6")
compileOnly("org.ow2.asm:asm-tree:9.6") compileOnly("org.ow2.asm:asm-tree:9.6")
implementation("org.apache.commons:commons-compress:1.26.0") implementation("org.apache.commons:commons-compress:1.26.0")
implementation("com.google.code.gson:gson:2.10.1")
implementation("commons-codec:commons-codec:1.17.0")
def glslTransformLib = "org.taumc:glsl-transformation-lib:${glsl_transformation_lib_version}:fat" def glslTransformLib = "org.taumc:glsl-transformation-lib:${glsl_transformation_lib_version}:fat"
def jcpp = "org.anarres:jcpp:1.4.14" def jcpp = "org.anarres:jcpp:1.4.14"
@@ -1,12 +1,146 @@
package net.irisshaders.iris; package net.irisshaders.iris;
import java.nio.file.Path; import com.google.common.base.Throwables;
import lombok.Getter;
import net.irisshaders.iris.config.IrisConfig;
import net.irisshaders.iris.gl.shader.StandardMacros;
import net.irisshaders.iris.helpers.OptionalBoolean;
import net.irisshaders.iris.pipeline.PipelineManager;
import net.irisshaders.iris.shaderpack.DimensionId;
import net.irisshaders.iris.shaderpack.ShaderPack;
import net.irisshaders.iris.shaderpack.materialmap.NamespacedId;
import net.irisshaders.iris.shaderpack.option.OptionSet;
import net.irisshaders.iris.shaderpack.option.Profile;
import net.irisshaders.iris.shaderpack.option.values.MutableOptionValues;
import net.irisshaders.iris.shaderpack.option.values.OptionValues;
import org.jetbrains.annotations.NotNull;
import org.taumc.celeritas.CeleritasShaderVersionService;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.stream.Stream;
import java.util.zip.ZipError;
import java.util.zip.ZipException;
import static net.irisshaders.iris.IrisLogging.IRIS_LOGGER;
import static org.embeddedt.embeddium.compat.mc.PlatformUtilService.PLATFORM_UTIL; import static org.embeddedt.embeddium.compat.mc.PlatformUtilService.PLATFORM_UTIL;
public class IrisCommon { public class IrisCommon {
public static final float DEGREES_TO_RADIANS = (float)Math.PI / 180.0F; public static final float DEGREES_TO_RADIANS = (float)Math.PI / 180.0F;
private static Path shaderpacksDirectory; private static Path shaderpacksDirectory;
private static final Map<String, String> shaderPackOptionQueue = new HashMap<>();
@Getter private static IrisConfig irisConfig;
private static ShaderPack currentPack;
private static boolean initialized;
private static boolean renderSystemInit = false;
public static NamespacedId lastDimension = null;
private static PipelineManager pipelineManager;
private static Optional<Exception> storedError = Optional.empty();
private static boolean loadPackWhenPossible = false;
public static void loadShaderpackWhenPossible() {
loadPackWhenPossible = true;
}
public static Optional<Exception> getStoredError() {
return storedError;
}
public static void setStoredError(Optional<Exception> error) {
storedError = error;
}
public static boolean isFallback() {
return fallback;
}
public static void setFallback(boolean fallback) {
IrisCommon.fallback = fallback;
}
// Flag variable used when reloading
// Used in favor of queueDefaultShaderPackOptionValues() for resetting as the
// behavior is more concrete and therefore is more likely to repair a user's issues
private static boolean resetShaderPackOptions = false;
static FileSystem zipFileSystem;
static boolean fallback;
static String currentPackName;
/**
* Called once RenderSystem#initRenderer has completed. This means that we can safely access OpenGL.
*/
public static void onRenderSystemInit() {
if (!initialized) {
IRIS_LOGGER.warn("Iris::onRenderSystemInit was called, but Iris::onEarlyInitialize was not called." +
" Trying to avoid a crash but this is an odd state.");
return;
}
renderSystemInit = true;
CeleritasShaderVersionService.INSTANCE.onRenderSystemInit();
}
/**
* Called very early on in Minecraft initialization. At this point we *cannot* safely access OpenGL, but we can do
* some very basic setup, config loading, and environment checks.
*
* <p>This is roughly equivalent to Fabric Loader's ClientModInitializer#onInitializeClient entrypoint, except
* it's entirely cross platform & we get to decide its exact semantics.</p>
*
* <p>This is called right before options are loaded, so we can add key bindings here.</p>
*/
public static void onEarlyInitialize() {
try {
if (!Files.exists(IrisCommon.getShaderpacksDirectory())) {
Files.createDirectories(IrisCommon.getShaderpacksDirectory());
}
} catch (IOException e) {
IRIS_LOGGER.warn("Failed to create the shaderpacks directory!");
IRIS_LOGGER.warn("", e);
}
irisConfig = new IrisConfig(PLATFORM_UTIL.getConfigDir().resolve(IrisConstants.MODID + "-shaders.properties"));
try {
IrisCommon.getIrisConfig().initialize();
} catch (IOException e) {
IRIS_LOGGER.error("Failed to initialize Iris configuration, default values will be used instead");
IRIS_LOGGER.error("", e);
}
initialized = true;
CeleritasShaderVersionService.INSTANCE.onEarlyInitialize();
}
public static void onLoadingComplete() {
if (!initialized) {
IRIS_LOGGER.warn("Iris::onLoadingComplete was called, but Iris::onEarlyInitialize was not called." +
" Trying to avoid a crash but this is an odd state.");
return;
}
// Initialize the pipeline now so that we don't increase world loading time. Just going to guess that
// the player is in the overworld.
// See: https://github.com/IrisShaders/Iris/issues/323
lastDimension = DimensionId.OVERWORLD;
CeleritasShaderVersionService.INSTANCE.onLoadingComplete();
}
public static Path getShaderpacksDirectory() { public static Path getShaderpacksDirectory() {
if (shaderpacksDirectory == null) { if (shaderpacksDirectory == null) {
@@ -15,4 +149,351 @@ public class IrisCommon {
return shaderpacksDirectory; return shaderpacksDirectory;
} }
public static boolean isValidShaderpack(Path pack) {
if (Files.isDirectory(pack)) {
// Sometimes the shaderpack directory itself can be
// identified as a shader pack due to it containing
// folders which contain "shaders" folders, this is
// necessary to check against that
if (pack.equals(getShaderpacksDirectory())) {
return false;
}
try (Stream<Path> stream = Files.walk(pack)) {
return stream
.filter(Files::isDirectory)
// Prevent a pack simply named "shaders" from being
// identified as a valid pack
.filter(path -> !path.equals(pack))
.anyMatch(path -> path.endsWith("shaders"));
} catch (IOException ignored) {
// ignored, not a valid shader pack.
return false;
}
}
if (pack.toString().endsWith(".zip")) {
try (FileSystem zipSystem = FileSystems.newFileSystem(pack, IrisCommon.class.getClassLoader())) {
Path root = zipSystem.getRootDirectories().iterator().next();
try (Stream<Path> stream = Files.walk(root)) {
return stream
.filter(Files::isDirectory)
.anyMatch(path -> path.endsWith("shaders"));
}
} catch (ZipError zipError) {
// Java 8 seems to throw a ZipError instead of a subclass of IOException
IRIS_LOGGER.warn("The ZIP at " + pack + " is corrupt");
} catch (IOException ignored) {
// ignored, not a valid shader pack.
}
}
return false;
}
public static Map<String, String> getShaderPackOptionQueue() {
return shaderPackOptionQueue;
}
public static void queueShaderPackOptionsFromProfile(Profile profile) {
getShaderPackOptionQueue().putAll(profile.optionValues);
}
public static void queueShaderPackOptionsFromProperties(Properties properties) {
queueDefaultShaderPackOptionValues();
properties.stringPropertyNames().forEach(key ->
getShaderPackOptionQueue().put(key, properties.getProperty(key)));
}
// Used in favor of resetShaderPackOptions as the aforementioned requires the pack to be reloaded
public static void queueDefaultShaderPackOptionValues() {
clearShaderPackOptionQueue();
getCurrentPack().ifPresent(pack -> {
OptionSet options = pack.getShaderPackOptions().getOptionSet();
OptionValues values = pack.getShaderPackOptions().getOptionValues();
options.getStringOptions().forEach((key, mOpt) -> {
if (values.getStringValue(key).isPresent()) {
getShaderPackOptionQueue().put(key, mOpt.getOption().getDefaultValue());
}
});
options.getBooleanOptions().forEach((key, mOpt) -> {
if (values.getBooleanValue(key) != OptionalBoolean.DEFAULT) {
getShaderPackOptionQueue().put(key, Boolean.toString(mOpt.getOption().getDefaultValue()));
}
});
});
}
public static void clearShaderPackOptionQueue() {
getShaderPackOptionQueue().clear();
}
public static void resetShaderPackOptionsOnNextReload() {
resetShaderPackOptions = true;
}
public static void clearResetShaderPackOptions() {
resetShaderPackOptions = false;
}
public static boolean shouldResetShaderPackOptionsOnNextReload() {
return resetShaderPackOptions;
}
@NotNull
public static Optional<ShaderPack> getCurrentPack() {
return Optional.ofNullable(currentPack);
}
static Optional<Path> loadExternalZipShaderpack(Path shaderpackPath) throws IOException {
FileSystem zipSystem = FileSystems.newFileSystem(shaderpackPath, IrisCommon.class.getClassLoader());
IrisCommon.zipFileSystem = zipSystem;
// Should only be one root directory for a zip shaderpack
Path root = zipSystem.getRootDirectories().iterator().next();
Path potentialShaderDir = zipSystem.getPath("shaders");
// If the shaders dir was immediately found return it
// Otherwise, manually search through each directory path until it ends with "shaders"
if (Files.exists(potentialShaderDir)) {
return Optional.of(potentialShaderDir);
}
// Sometimes shaderpacks have their shaders directory within another folder in the shaderpack
// For example Sildurs-Vibrant-Shaders.zip/shaders
// While other packs have Trippy-Shaderpack-master.zip/Trippy-Shaderpack-master/shaders
// This makes it hard to determine what is the actual shaders dir
try (Stream<Path> stream = Files.walk(root)) {
return stream
.filter(Files::isDirectory)
.filter(path -> path.endsWith("shaders"))
.findFirst();
}
}
static Optional<Properties> tryReadConfigProperties(Path path) {
Properties properties = new Properties();
if (Files.exists(path)) {
try (InputStream is = Files.newInputStream(path)) {
// NB: config properties are specified to be encoded with ISO-8859-1 by OptiFine,
// so we don't need to do the UTF-8 workaround here.
properties.load(is);
} catch (IOException e) {
// TODO: Better error handling
return Optional.empty();
}
}
return Optional.of(properties);
}
static void tryUpdateConfigPropertiesFile(Path path, Properties properties) {
try {
if (properties.isEmpty()) {
// Delete the file or don't create it if there are no changed configs
if (Files.exists(path)) {
Files.delete(path);
}
return;
}
try (OutputStream out = Files.newOutputStream(path)) {
properties.store(out, null);
}
} catch (IOException e) {
// TODO: Better error handling
}
}
public static void loadShaderpack() {
if (getIrisConfig() == null) {
if (!initialized) {
throw new IllegalStateException("Iris::loadShaderpack was called, but Iris::onInitializeClient wasn't" +
" called yet. How did this happen?");
} else {
throw new NullPointerException("Iris.irisConfig was null unexpectedly");
}
}
if (!getIrisConfig().areShadersEnabled()) {
IRIS_LOGGER.info("Shaders are disabled because enableShaders is set to false in iris.properties");
setShadersDisabled();
return;
}
// Attempt to load an external shaderpack if it is available
Optional<String> externalName = getIrisConfig().getShaderPackName();
if (externalName.isEmpty()) {
IRIS_LOGGER.info("Shaders are disabled because no valid shaderpack is selected");
setShadersDisabled();
return;
}
if (!loadExternalShaderpack(externalName.get())) {
IRIS_LOGGER.warn("Falling back to normal rendering without shaders because the shaderpack could not be loaded");
setShadersDisabled();
fallback = true;
}
}
static void setShadersDisabled() {
currentPack = null;
fallback = false;
currentPackName = "(off)";
IRIS_LOGGER.info("Shaders are disabled");
}
@SuppressWarnings("unchecked")
private static boolean loadExternalShaderpack(String name) {
Path shaderPackRoot;
Path shaderPackConfigTxt;
try {
shaderPackRoot = getShaderpacksDirectory().resolve(name);
shaderPackConfigTxt = getShaderpacksDirectory().resolve(name + ".txt");
} catch (InvalidPathException e) {
IRIS_LOGGER.error("Failed to load the shaderpack \"{}\" because it contains invalid characters in its path", name);
return false;
}
if (!isValidShaderpack(shaderPackRoot)) {
IRIS_LOGGER.error("Pack \"{}\" is not valid! Can't load it.", name);
return false;
}
Path shaderPackPath;
if (!Files.isDirectory(shaderPackRoot) && shaderPackRoot.toString().endsWith(".zip")) {
Optional<Path> optionalPath;
try {
optionalPath = loadExternalZipShaderpack(shaderPackRoot);
} catch (FileSystemNotFoundException | NoSuchFileException e) {
IRIS_LOGGER.error("Failed to load the shaderpack \"{}\" because it does not exist in your shaderpacks folder!", name);
return false;
} catch (ZipException e) {
IRIS_LOGGER.error("The shaderpack \"{}\" appears to be corrupted, please try downloading it again!", name);
return false;
} catch (IOException e) {
IRIS_LOGGER.error("Failed to load the shaderpack \"{}\"!", name);
IRIS_LOGGER.error("", e);
return false;
}
if (optionalPath.isPresent()) {
shaderPackPath = optionalPath.get();
} else {
IRIS_LOGGER.error("Could not load the shaderpack \"{}\" because it appears to lack a \"shaders\" directory", name);
return false;
}
} else {
if (!Files.exists(shaderPackRoot)) {
IRIS_LOGGER.error("Failed to load the shaderpack \"{}\" because it does not exist!", name);
return false;
}
// If it's a folder-based shaderpack, just use the shaders subdirectory
shaderPackPath = shaderPackRoot.resolve("shaders");
}
if (!Files.exists(shaderPackPath)) {
IRIS_LOGGER.error("Could not load the shaderpack \"{}\" because it appears to lack a \"shaders\" directory", name);
return false;
}
Map<String, String> changedConfigs = tryReadConfigProperties(shaderPackConfigTxt)
.map(properties -> (Map<String, String>) (Object) properties)
.orElse(new HashMap<>());
changedConfigs.putAll(getShaderPackOptionQueue());
clearShaderPackOptionQueue();
if (shouldResetShaderPackOptionsOnNextReload()) {
changedConfigs.clear();
}
clearResetShaderPackOptions();
try {
currentPack = new ShaderPack(shaderPackPath, changedConfigs, StandardMacros.createStandardEnvironmentDefines());
MutableOptionValues changedConfigsValues = currentPack.getShaderPackOptions().getOptionValues().mutableCopy();
// Store changed values from those currently in use by the shader pack
Properties configsToSave = new Properties();
changedConfigsValues.getBooleanValues().forEach((k, v) -> configsToSave.setProperty(k, Boolean.toString(v)));
changedConfigsValues.getStringValues().forEach(configsToSave::setProperty);
tryUpdateConfigPropertiesFile(shaderPackConfigTxt, configsToSave);
} catch (Exception e) {
IRIS_LOGGER.error("Failed to load the shaderpack \"{}\"!", name);
IRIS_LOGGER.error("", e);
return false;
}
fallback = false;
currentPackName = name;
IRIS_LOGGER.info("Using shaderpack: " + name);
return true;
}
/**
* Destroys and deallocates all created OpenGL resources. Useful as part of a reload.
*/
static void destroyEverything() {
currentPack = null;
CeleritasShaderVersionService.INSTANCE.destroyEverything();
// Close the zip filesystem that the shaderpack was loaded from
//
// This prevents a FileSystemAlreadyExistsException when reloading shaderpacks.
if (zipFileSystem != null) {
try {
zipFileSystem.close();
} catch (NoSuchFileException e) {
IRIS_LOGGER.warn("Failed to close the shaderpack zip when reloading because it was deleted, proceeding anyways.");
} catch (IOException e) {
IRIS_LOGGER.error("Failed to close zip file system?", e);
}
}
}
@NotNull
public static PipelineManager getPipelineManager() {
if (pipelineManager == null) {
pipelineManager = new PipelineManager(CeleritasShaderVersionService.INSTANCE::createPipeline);
}
if (loadPackWhenPossible && renderSystemInit) {
loadPackWhenPossible = false;
CeleritasShaderVersionService.INSTANCE.reload();
}
return pipelineManager;
}
public static NamespacedId getLastDimension() {
return lastDimension;
}
} }
@@ -1,18 +1,19 @@
package net.irisshaders.iris.compat.dh; package net.irisshaders.iris.compat.dh;
import net.irisshaders.iris.Iris;
import net.irisshaders.iris.gl.shader.ShaderCompileException; import net.irisshaders.iris.gl.shader.ShaderCompileException;
import net.irisshaders.iris.pipeline.IrisRenderingPipeline; import net.irisshaders.iris.pipeline.IrisRenderingPipeline;
import net.irisshaders.iris.uniforms.CapturedRenderingState; import net.irisshaders.iris.uniforms.CapturedRenderingState;
import net.minecraft.client.Minecraft;
import org.embeddedt.embeddium.impl.loader.common.EarlyLoaderServices;
import org.joml.Matrix4f; import org.joml.Matrix4f;
import org.taumc.celeritas.CeleritasShaderVersionService;
import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType; import java.lang.invoke.MethodType;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import static net.irisshaders.iris.IrisLogging.IRIS_LOGGER;
import static org.embeddedt.embeddium.compat.mc.MinecraftVersionShimService.MINECRAFT_SHIM;
public class DHCompat { public class DHCompat {
private static boolean dhPresent = true; private static boolean dhPresent = true;
private static boolean lastIncompatible; private static boolean lastIncompatible;
@@ -29,7 +30,7 @@ public class DHCompat {
public DHCompat(IrisRenderingPipeline pipeline, boolean renderDHShadow) { public DHCompat(IrisRenderingPipeline pipeline, boolean renderDHShadow) {
try { try {
if (dhPresent) { if (dhPresent) {
compatInternalInstance = Class.forName("net.irisshaders.iris.compat.dh.DHCompatInternal").getDeclaredConstructor(pipeline.getClass(), boolean.class).newInstance(pipeline, renderDHShadow); compatInternalInstance = CeleritasShaderVersionService.INSTANCE.getDHCompatInstance(pipeline, renderDHShadow);
lastIncompatible = (boolean) incompatible.invoke(compatInternalInstance); lastIncompatible = (boolean) incompatible.invoke(compatInternalInstance);
} }
} catch (Throwable e) { } catch (Throwable e) {
@@ -56,7 +57,7 @@ public class DHCompat {
public static void run() { public static void run() {
try { try {
if (EarlyLoaderServices.INSTANCE.isModLoaded("distanthorizons")) { if (MINECRAFT_SHIM.isDHPresent()) {
deletePipeline = MethodHandles.lookup().findVirtual(Class.forName("net.irisshaders.iris.compat.dh.DHCompatInternal"), "clear", MethodType.methodType(void.class)); deletePipeline = MethodHandles.lookup().findVirtual(Class.forName("net.irisshaders.iris.compat.dh.DHCompatInternal"), "clear", MethodType.methodType(void.class));
MethodHandle setupEventHandlers = MethodHandles.lookup().findStatic(Class.forName("net.irisshaders.iris.compat.dh.LodRendererEvents"), "setupEventHandlers", MethodType.methodType(void.class)); MethodHandle setupEventHandlers = MethodHandles.lookup().findStatic(Class.forName("net.irisshaders.iris.compat.dh.LodRendererEvents"), "setupEventHandlers", MethodType.methodType(void.class));
getDepthTex = MethodHandles.lookup().findVirtual(Class.forName("net.irisshaders.iris.compat.dh.DHCompatInternal"), "getStoredDepthTex", MethodType.methodType(int.class)); getDepthTex = MethodHandles.lookup().findVirtual(Class.forName("net.irisshaders.iris.compat.dh.DHCompatInternal"), "getStoredDepthTex", MethodType.methodType(int.class));
@@ -74,14 +75,14 @@ public class DHCompat {
} catch (Throwable e) { } catch (Throwable e) {
dhPresent = false; dhPresent = false;
if (EarlyLoaderServices.INSTANCE.isModLoaded("distanthorizons")) { if (MINECRAFT_SHIM.isDHPresent()) {
if (e instanceof ExceptionInInitializerError eiie) { if (e instanceof ExceptionInInitializerError eiie) {
throw new RuntimeException("Failure loading DH compat.", eiie.getCause()); throw new RuntimeException("Failure loading DH compat.", eiie.getCause());
} else { } else {
throw new RuntimeException("DH found, but one or more API methods are missing. Iris requires DH [2.0.4] or DH API version [1.1.0] or newer. Please make sure you are on the latest version of DH and Iris.", e); throw new RuntimeException("DH found, but one or more API methods are missing. Iris requires DH [2.0.4] or DH API version [1.1.0] or newer. Please make sure you are on the latest version of DH and Iris.", e);
} }
} else { } else {
Iris.logger.info("DH not found, and classes not found."); IRIS_LOGGER.info("DH not found, and classes not found.");
} }
} }
} }
@@ -111,7 +112,7 @@ public class DHCompat {
} }
public static int getRenderDistance() { public static int getRenderDistance() {
if (!dhPresent) return Minecraft.getInstance().options.getEffectiveRenderDistance(); if (!dhPresent) return MINECRAFT_SHIM.getEffectiveRenderDistance();
try { try {
return (int) getRenderDistance.invoke(); return (int) getRenderDistance.invoke();
@@ -10,6 +10,7 @@ import org.joml.Vector2f;
import org.joml.Vector3i; import org.joml.Vector3i;
import org.lwjgl.opengl.GL43C; import org.lwjgl.opengl.GL43C;
import org.lwjgl.opengl.GL46C; import org.lwjgl.opengl.GL46C;
import org.taumc.celeritas.CeleritasShaderVersionService;
public final class ComputeProgram extends GlResource { public final class ComputeProgram extends GlResource {
private final ProgramUniforms uniforms; private final ProgramUniforms uniforms;
@@ -72,7 +73,7 @@ public final class ComputeProgram extends GlResource {
} }
public void dispatch(float width, float height) { public void dispatch(float width, float height) {
if (!MINECRAFT_SHIM.irisAllowConcurrentUpdate()) { if (!CeleritasShaderVersionService.INSTANCE.irisAllowConcurrentUpdate()) {
IrisRenderSystem.memoryBarrier(GL43C.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL43C.GL_TEXTURE_FETCH_BARRIER_BIT | GL43C.GL_SHADER_STORAGE_BARRIER_BIT); IrisRenderSystem.memoryBarrier(GL43C.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL43C.GL_TEXTURE_FETCH_BARRIER_BIT | GL43C.GL_SHADER_STORAGE_BARRIER_BIT);
} }
@@ -6,18 +6,16 @@ import java.util.regex.Pattern;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static com.mitchej123.glsm.GLStateManagerService.GL_STATE_MANAGER; import static com.mitchej123.glsm.GLStateManagerService.GL_STATE_MANAGER;
import static net.irisshaders.iris.IrisLogging.IRIS_LOGGER;
import static org.embeddedt.embeddium.compat.mc.MinecraftVersionShimService.MINECRAFT_SHIM; import static org.embeddedt.embeddium.compat.mc.MinecraftVersionShimService.MINECRAFT_SHIM;
import static org.embeddedt.embeddium.compat.dh.DHCompatService.DH_COMPAT; import static org.embeddedt.embeddium.compat.dh.DHCompatService.DH_COMPAT;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.mojang.blaze3d.platform.GlUtil;
import net.irisshaders.iris.Iris;
import net.irisshaders.iris.IrisConstants; import net.irisshaders.iris.IrisConstants;
import net.irisshaders.iris.helpers.StringPair; import net.irisshaders.iris.helpers.StringPair;
import net.irisshaders.iris.pipeline.WorldRenderingPhase; import net.irisshaders.iris.pipeline.WorldRenderingPhase;
import net.irisshaders.iris.texture.format.TextureFormat; import net.irisshaders.iris.texture.format.TextureFormat;
import net.irisshaders.iris.texture.format.TextureFormatLoader; import net.irisshaders.iris.texture.format.TextureFormatLoader;
import net.minecraft.Util;
import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL20C; import org.lwjgl.opengl.GL20C;
import org.lwjgl.opengl.GL30C; import org.lwjgl.opengl.GL30C;
@@ -102,7 +100,7 @@ public class StandardMacros {
* @see <a href="https://github.com/sp614x/optifine/blob/9c6a5b5326558ccc57c6490b66b3be3b2dc8cbef/OptiFineDoc/doc/shaders.txt#L696-L699">Optifine Doc</a> * @see <a href="https://github.com/sp614x/optifine/blob/9c6a5b5326558ccc57c6490b66b3be3b2dc8cbef/OptiFineDoc/doc/shaders.txt#L696-L699">Optifine Doc</a>
*/ */
public static String getMcVersion() { public static String getMcVersion() {
String version = Iris.getReleaseTarget(); String version = MINECRAFT_SHIM.getMcVersion();
if (version == null) { if (version == null) {
throw new IllegalStateException("Could not get the current minecraft version!"); throw new IllegalStateException("Could not get the current minecraft version!");
@@ -111,8 +109,8 @@ public class StandardMacros {
String[] splitVersion = version.split("\\."); String[] splitVersion = version.split("\\.");
if (splitVersion.length < 2) { if (splitVersion.length < 2) {
Iris.logger.error("Could not parse game version \"" + version + "\""); IRIS_LOGGER.error("Could not parse game version \"" + version + "\"");
splitVersion = Iris.getBackupVersionNumber().split("\\."); splitVersion = MINECRAFT_SHIM.getBackupVersionNumber().split("\\.");
} }
String major = splitVersion[0]; String major = splitVersion[0];
@@ -191,13 +189,7 @@ public class StandardMacros {
* @see <a href="https://github.com/sp614x/optifine/blob/9c6a5b5326558ccc57c6490b66b3be3b2dc8cbef/OptiFineDoc/doc/shaders.txt#L709-L714">Optifine Doc</a> * @see <a href="https://github.com/sp614x/optifine/blob/9c6a5b5326558ccc57c6490b66b3be3b2dc8cbef/OptiFineDoc/doc/shaders.txt#L709-L714">Optifine Doc</a>
*/ */
public static String getOsString() { public static String getOsString() {
return switch (Util.getPlatform()) { return MINECRAFT_SHIM.getOsString();
case OSX -> "MC_OS_MAC";
case LINUX -> "MC_OS_LINUX";
case WINDOWS ->
"MC_OS_WINDOWS"; // Note: Optifine doesn't have a macro for Solaris. https://github.com/sp614x/optifine/blob/9c6a5b5326558ccc57c6490b66b3be3b2dc8cbef/OptiFineDoc/doc/shaders.txt#L709-L714
default -> "MC_OS_UNKNOWN";
};
} }
/** /**
@@ -207,7 +199,7 @@ public class StandardMacros {
* @see <a href="https://github.com/sp614x/optifine/blob/9c6a5b5326558ccc57c6490b66b3be3b2dc8cbef/OptiFineDoc/doc/shaders.txt#L716-L723">Optifine Doc</a> * @see <a href="https://github.com/sp614x/optifine/blob/9c6a5b5326558ccc57c6490b66b3be3b2dc8cbef/OptiFineDoc/doc/shaders.txt#L716-L723">Optifine Doc</a>
*/ */
public static String getVendor() { public static String getVendor() {
String vendor = Objects.requireNonNull(GlUtil.getVendor()).toLowerCase(Locale.ROOT); String vendor = Objects.requireNonNull(GL_STATE_MANAGER.glGetString(GL11.GL_VENDOR).toLowerCase(Locale.ROOT));
if (vendor.startsWith("ati")) { if (vendor.startsWith("ati")) {
return "MC_GL_VENDOR_ATI"; return "MC_GL_VENDOR_ATI";
} else if (vendor.startsWith("intel")) { } else if (vendor.startsWith("intel")) {
@@ -229,7 +221,7 @@ public class StandardMacros {
* @see <a href="https://github.com/sp614x/optifine/blob/9c6a5b5326558ccc57c6490b66b3be3b2dc8cbef/OptiFineDoc/doc/shaders.txt#L725-L733">Optifine Doc</a> * @see <a href="https://github.com/sp614x/optifine/blob/9c6a5b5326558ccc57c6490b66b3be3b2dc8cbef/OptiFineDoc/doc/shaders.txt#L725-L733">Optifine Doc</a>
*/ */
public static String getRenderer() { public static String getRenderer() {
String renderer = Objects.requireNonNull(GlUtil.getRenderer()).toLowerCase(Locale.ROOT); String renderer = Objects.requireNonNull(GL_STATE_MANAGER.glGetString(GL11.GL_RENDERER)).toLowerCase(Locale.ROOT);
if (renderer.startsWith("amd")) { if (renderer.startsWith("amd")) {
return "MC_GL_RENDERER_RADEON"; return "MC_GL_RENDERER_RADEON";
} else if (renderer.startsWith("ati")) { } else if (renderer.startsWith("ati")) {
@@ -1,8 +1,5 @@
package net.irisshaders.iris.gl.state; package net.irisshaders.iris.gl.state;
import com.mojang.blaze3d.vertex.DefaultVertexFormat;
import com.mojang.blaze3d.vertex.VertexFormat;
public class ShaderAttributeInputs { public class ShaderAttributeInputs {
private boolean color; private boolean color;
private boolean tex; private boolean tex;
@@ -14,45 +11,28 @@ public class ShaderAttributeInputs {
private boolean text; private boolean text;
// WARNING: adding new fields requires updating hashCode and equals methods! // WARNING: adding new fields requires updating hashCode and equals methods!
public ShaderAttributeInputs(VertexFormat format, boolean isFullbright, boolean isLines, boolean glint, boolean text) {
if (format == DefaultVertexFormat.POSITION_COLOR_NORMAL && !isLines) {
newLines = true;
}
this.text = text;
this.glint = glint;
format.getElementAttributeNames().forEach(name -> {
if ("Color".equals(name)) {
color = true;
}
if ("UV0".equals(name)) {
tex = true;
}
if ("UV1".equals(name)) {
overlay = true;
}
if ("UV2".equals(name) && !isFullbright) {
light = true;
}
if ("Normal".equals(name)) {
normal = true;
}
});
}
public ShaderAttributeInputs(boolean color, boolean tex, boolean overlay, boolean light, boolean normal) { public ShaderAttributeInputs(boolean color, boolean tex, boolean overlay, boolean light, boolean normal) {
this.color = color; this.color = color;
this.tex = tex; this.tex = tex;
this.overlay = overlay; this.overlay = overlay;
this.light = light; this.light = light;
this.normal = normal; this.normal = normal;
this.newLines = false;
this.glint = false;
this.text = false;
} }
public ShaderAttributeInputs(boolean color, boolean tex, boolean overlay, boolean light, boolean normal, boolean newLines, boolean glint, boolean text) {
this.color = color;
this.tex = tex;
this.overlay = overlay;
this.light = light;
this.normal = normal;
this.newLines = newLines;
this.glint = glint;
this.text = text;
}
public boolean hasColor() { public boolean hasColor() {
return color; return color;
} }
@@ -1,6 +1,6 @@
package net.irisshaders.iris.layer; package net.irisshaders.iris.layer;
import net.irisshaders.iris.Iris; import net.irisshaders.iris.IrisCommon;
import net.irisshaders.iris.gl.state.StateUpdateNotifiers; import net.irisshaders.iris.gl.state.StateUpdateNotifiers;
import net.irisshaders.iris.pipeline.WorldRenderingPhase; import net.irisshaders.iris.pipeline.WorldRenderingPhase;
import net.irisshaders.iris.pipeline.WorldRenderingPipeline; import net.irisshaders.iris.pipeline.WorldRenderingPipeline;
@@ -70,7 +70,7 @@ public class GbufferPrograms {
} }
public static WorldRenderingPhase getCurrentPhase() { public static WorldRenderingPhase getCurrentPhase() {
WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable(); WorldRenderingPipeline pipeline = IrisCommon.getPipelineManager().getPipelineNullable();
if (pipeline != null) { if (pipeline != null) {
return pipeline.getPhase(); return pipeline.getPhase();
@@ -80,7 +80,7 @@ public class GbufferPrograms {
} }
private static void setPhase(WorldRenderingPhase phase) { private static void setPhase(WorldRenderingPhase phase) {
WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable(); WorldRenderingPipeline pipeline = IrisCommon.getPipelineManager().getPipelineNullable();
if (pipeline != null) { if (pipeline != null) {
pipeline.setPhase(phase); pipeline.setPhase(phase);
@@ -88,7 +88,7 @@ public class GbufferPrograms {
} }
public static void setOverridePhase(WorldRenderingPhase phase) { public static void setOverridePhase(WorldRenderingPhase phase) {
WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable(); WorldRenderingPipeline pipeline = IrisCommon.getPipelineManager().getPipelineNullable();
if (pipeline != null) { if (pipeline != null) {
pipeline.setOverridePhase(phase); pipeline.setOverridePhase(phase);
@@ -0,0 +1,6 @@
package net.irisshaders.iris.pipeline;
import net.irisshaders.iris.targets.RenderTargetStateListener;
public interface IrisRenderingPipeline extends WorldRenderingPipeline, RenderTargetStateListener {
}
@@ -6,18 +6,19 @@ import java.util.Optional;
import java.util.function.Function; import java.util.function.Function;
import static com.mitchej123.glsm.GLStateManagerService.GL_STATE_MANAGER; import static com.mitchej123.glsm.GLStateManagerService.GL_STATE_MANAGER;
import static net.irisshaders.iris.IrisLogging.IRIS_LOGGER;
import net.irisshaders.iris.Iris;
import net.irisshaders.iris.shaderpack.materialmap.NamespacedId; import net.irisshaders.iris.shaderpack.materialmap.NamespacedId;
import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings;
import net.irisshaders.iris.uniforms.SystemTimeUniforms; import net.irisshaders.iris.uniforms.SystemTimeUniforms;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.lwjgl.opengl.GL20C; import org.lwjgl.opengl.GL20C;
import org.taumc.celeritas.CeleritasShaderVersionService;
public class PipelineManager { public class PipelineManager {
private final Function<NamespacedId, WorldRenderingPipeline> pipelineFactory; private final Function<NamespacedId, WorldRenderingPipeline> pipelineFactory;
private final Map<NamespacedId, WorldRenderingPipeline> pipelinesPerDimension = new HashMap<>(); private final Map<NamespacedId, WorldRenderingPipeline> pipelinesPerDimension = new HashMap<>();
private WorldRenderingPipeline pipeline = new VanillaRenderingPipeline(); private WorldRenderingPipeline pipeline = CeleritasShaderVersionService.INSTANCE.createVanillaRenderingPipeline();
private int versionCounterForSodiumShaderReload = 0; private int versionCounterForSodiumShaderReload = 0;
public PipelineManager(Function<NamespacedId, WorldRenderingPipeline> pipelineFactory) { public PipelineManager(Function<NamespacedId, WorldRenderingPipeline> pipelineFactory) {
@@ -29,7 +30,7 @@ public class PipelineManager {
SystemTimeUniforms.COUNTER.reset(); SystemTimeUniforms.COUNTER.reset();
SystemTimeUniforms.TIMER.reset(); SystemTimeUniforms.TIMER.reset();
Iris.logger.info("Creating pipeline for dimension {}", currentDimension); IRIS_LOGGER.info("Creating pipeline for dimension {}", currentDimension);
pipeline = pipelineFactory.apply(currentDimension); pipeline = pipelineFactory.apply(currentDimension);
pipelinesPerDimension.put(currentDimension, pipeline); pipelinesPerDimension.put(currentDimension, pipeline);
@@ -76,7 +77,7 @@ public class PipelineManager {
*/ */
public void destroyPipeline() { public void destroyPipeline() {
pipelinesPerDimension.forEach((dimensionId, pipeline) -> { pipelinesPerDimension.forEach((dimensionId, pipeline) -> {
Iris.logger.info("Destroying pipeline {}", dimensionId); IRIS_LOGGER.info("Destroying pipeline {}", dimensionId);
resetTextureState(); resetTextureState();
pipeline.destroy(); pipeline.destroy();
}); });
@@ -2,6 +2,7 @@ package net.irisshaders.iris.pipeline;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.primitives.Ints; import com.google.common.primitives.Ints;
import org.embeddedt.embeddium.compat.mc.IResourceLocation;
import org.embeddedt.embeddium.impl.render.chunk.RenderPassConfiguration; import org.embeddedt.embeddium.impl.render.chunk.RenderPassConfiguration;
import net.irisshaders.iris.gl.blending.AlphaTest; import net.irisshaders.iris.gl.blending.AlphaTest;
import net.irisshaders.iris.gl.blending.AlphaTests; import net.irisshaders.iris.gl.blending.AlphaTests;
@@ -23,8 +24,6 @@ import net.irisshaders.iris.targets.RenderTargets;
import net.irisshaders.iris.uniforms.CommonUniforms; import net.irisshaders.iris.uniforms.CommonUniforms;
import net.irisshaders.iris.uniforms.builtin.BuiltinReplacementUniforms; import net.irisshaders.iris.uniforms.builtin.BuiltinReplacementUniforms;
import net.irisshaders.iris.uniforms.custom.CustomUniforms; import net.irisshaders.iris.uniforms.custom.CustomUniforms;
import net.minecraft.resources.ResourceLocation;
import org.embeddedt.embeddium.impl.util.ResourceLocationUtil;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
@@ -296,7 +295,7 @@ public class SodiumTerrainPipeline {
String namespace = matcher.group("namespace"); String namespace = matcher.group("namespace");
String path = matcher.group("path"); String path = matcher.group("path");
ResourceLocation identifier = ResourceLocationUtil.make(namespace, path); IResourceLocation identifier = MINECRAFT_SHIM.makeResourceLocation(namespace, path);
return ""; return "";
} }
@@ -4,6 +4,7 @@ import java.util.List;
import java.util.OptionalInt; import java.util.OptionalInt;
import static com.mitchej123.glsm.GLStateManagerService.GL_STATE_MANAGER; import static com.mitchej123.glsm.GLStateManagerService.GL_STATE_MANAGER;
import static org.embeddedt.embeddium.compat.mc.MinecraftVersionShimService.MINECRAFT_SHIM;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap; import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectMaps; import it.unimi.dsi.fastutil.objects.Object2ObjectMaps;
@@ -11,17 +12,16 @@ import net.irisshaders.iris.compat.dh.DHCompat;
import net.irisshaders.iris.features.FeatureFlags; import net.irisshaders.iris.features.FeatureFlags;
import net.irisshaders.iris.gl.texture.TextureType; import net.irisshaders.iris.gl.texture.TextureType;
import net.irisshaders.iris.helpers.Tri; import net.irisshaders.iris.helpers.Tri;
import net.irisshaders.iris.mixin.LevelRendererAccessor;
import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings;
import net.irisshaders.iris.shaderpack.properties.CloudSetting; import net.irisshaders.iris.shaderpack.properties.CloudSetting;
import net.irisshaders.iris.shaderpack.properties.ParticleRenderingSettings;
import net.irisshaders.iris.shaderpack.texture.TextureStage; import net.irisshaders.iris.shaderpack.texture.TextureStage;
import net.irisshaders.iris.targets.RenderTargetStateListener; import net.irisshaders.iris.targets.RenderTargetStateListener;
import net.irisshaders.iris.uniforms.FrameUpdateNotifier; import net.irisshaders.iris.uniforms.FrameUpdateNotifier;
import net.minecraft.client.Camera;
import net.minecraft.client.Minecraft;
public class VanillaRenderingPipeline implements WorldRenderingPipeline { import org.embeddedt.embeddium.compat.mc.ICamera;
import org.embeddedt.embeddium.compat.mc.ILevelRenderer;
public abstract class VanillaRenderingPipeline implements WorldRenderingPipeline {
public VanillaRenderingPipeline() { public VanillaRenderingPipeline() {
WorldRenderingSettings.INSTANCE.setDisableDirectionalShading(shouldDisableDirectionalShading()); WorldRenderingSettings.INSTANCE.setDisableDirectionalShading(shouldDisableDirectionalShading());
WorldRenderingSettings.INSTANCE.setUseSeparateAo(false); WorldRenderingSettings.INSTANCE.setUseSeparateAo(false);
@@ -29,19 +29,18 @@ public class VanillaRenderingPipeline implements WorldRenderingPipeline {
WorldRenderingSettings.INSTANCE.setAmbientOcclusionLevel(1.0f); WorldRenderingSettings.INSTANCE.setAmbientOcclusionLevel(1.0f);
WorldRenderingSettings.INSTANCE.setUseExtendedVertexFormat(false); WorldRenderingSettings.INSTANCE.setUseExtendedVertexFormat(false);
WorldRenderingSettings.INSTANCE.setVoxelizeLightBlocks(false); WorldRenderingSettings.INSTANCE.setVoxelizeLightBlocks(false);
WorldRenderingSettings.INSTANCE.setBlockTypeIds(null);
WorldRenderingSettings.INSTANCE.setFallbackTextureMaterialMapping(null);
} }
@Override @Override
public void beginLevelRendering() { public void beginLevelRendering() {
// Use the default Minecraft framebuffer and ensure that no programs are in use // Use the default Minecraft framebuffer and ensure that no programs are in use
Minecraft.getInstance().getMainRenderTarget().bindWrite(true); MINECRAFT_SHIM.bindFramebuffer();
GL_STATE_MANAGER.glUseProgram(0); GL_STATE_MANAGER.glUseProgram(0);
} }
@Override @Override
public void renderShadows(LevelRendererAccessor worldRenderer, Camera camera) { public void renderShadows(ILevelRenderer worldRenderer, ICamera camera) {
// stub: nothing to do here // stub: nothing to do here
} }
@@ -182,11 +181,6 @@ public class VanillaRenderingPipeline implements WorldRenderingPipeline {
return false; return false;
} }
@Override
public ParticleRenderingSettings getParticleRenderingSettings() {
return Minecraft.useShaderTransparency() ? ParticleRenderingSettings.AFTER : ParticleRenderingSettings.MIXED;
}
@Override @Override
public boolean allowConcurrentCompute() { public boolean allowConcurrentCompute() {
return false; return false;
@@ -0,0 +1,29 @@
package net.irisshaders.iris.pipeline;
public enum WorldRenderingPhase {
NONE,
SKY,
SUNSET,
CUSTOM_SKY,
SUN,
MOON,
STARS,
VOID,
TERRAIN_SOLID,
TERRAIN_CUTOUT_MIPPED,
TERRAIN_CUTOUT,
ENTITIES,
BLOCK_ENTITIES,
DESTROY,
OUTLINE,
DEBUG,
HAND_SOLID,
TERRAIN_TRANSLUCENT,
TRIPWIRE,
PARTICLES,
CLOUDS,
RAIN_SNOW,
WORLD_BORDER,
HAND_TRANSLUCENT;
}
@@ -5,13 +5,13 @@ import net.irisshaders.iris.compat.dh.DHCompat;
import net.irisshaders.iris.features.FeatureFlags; import net.irisshaders.iris.features.FeatureFlags;
import net.irisshaders.iris.gl.texture.TextureType; import net.irisshaders.iris.gl.texture.TextureType;
import net.irisshaders.iris.helpers.Tri; import net.irisshaders.iris.helpers.Tri;
import net.irisshaders.iris.mixin.LevelRendererAccessor;
import net.irisshaders.iris.shaderpack.properties.CloudSetting; import net.irisshaders.iris.shaderpack.properties.CloudSetting;
import net.irisshaders.iris.shaderpack.properties.ParticleRenderingSettings; import net.irisshaders.iris.shaderpack.properties.ParticleRenderingSettings;
import net.irisshaders.iris.shaderpack.texture.TextureStage; import net.irisshaders.iris.shaderpack.texture.TextureStage;
import net.irisshaders.iris.targets.RenderTargetStateListener; import net.irisshaders.iris.targets.RenderTargetStateListener;
import net.irisshaders.iris.uniforms.FrameUpdateNotifier; import net.irisshaders.iris.uniforms.FrameUpdateNotifier;
import net.minecraft.client.Camera; import org.embeddedt.embeddium.compat.mc.ICamera;
import org.embeddedt.embeddium.compat.mc.ILevelRenderer;
import java.util.List; import java.util.List;
import java.util.OptionalInt; import java.util.OptionalInt;
@@ -19,7 +19,7 @@ import java.util.OptionalInt;
public interface WorldRenderingPipeline { public interface WorldRenderingPipeline {
void beginLevelRendering(); void beginLevelRendering();
void renderShadows(LevelRendererAccessor worldRenderer, Camera camera); void renderShadows(ILevelRenderer worldRenderer, ICamera camera);
void addDebugText(List<String> messages); void addDebugText(List<String> messages);
@@ -4,7 +4,6 @@ import net.irisshaders.iris.gl.shader.ShaderType;
import net.irisshaders.iris.pipeline.transform.PatchShaderType; import net.irisshaders.iris.pipeline.transform.PatchShaderType;
import net.irisshaders.iris.pipeline.transform.parameter.Parameters; import net.irisshaders.iris.pipeline.transform.parameter.Parameters;
import org.taumc.glsl.Transformer; import org.taumc.glsl.Transformer;
import org.taumc.glsl.Util;
import org.taumc.glsl.grammar.GLSLLexer; import org.taumc.glsl.grammar.GLSLLexer;
import org.taumc.glsl.grammar.GLSLParser; import org.taumc.glsl.grammar.GLSLParser;
@@ -3,8 +3,6 @@ package net.irisshaders.iris.pipeline.foss_transform;
import net.irisshaders.iris.gl.shader.ShaderType; import net.irisshaders.iris.gl.shader.ShaderType;
import net.irisshaders.iris.pipeline.transform.parameter.VanillaParameters; import net.irisshaders.iris.pipeline.transform.parameter.VanillaParameters;
import org.taumc.glsl.Transformer; import org.taumc.glsl.Transformer;
import org.taumc.glsl.Util;
import org.taumc.glsl.grammar.GLSLParser;
public class EntityPatcherNew { public class EntityPatcherNew {
public static void patchOverlayColor(Transformer translationUnit, VanillaParameters parameters) { public static void patchOverlayColor(Transformer translationUnit, VanillaParameters parameters) {
@@ -2,7 +2,6 @@ package net.irisshaders.iris.pipeline.foss_transform;
import com.google.common.reflect.TypeToken; import com.google.common.reflect.TypeToken;
import com.google.gson.Gson; import com.google.gson.Gson;
import net.irisshaders.iris.Iris;
import net.irisshaders.iris.pipeline.transform.PatchShaderType; import net.irisshaders.iris.pipeline.transform.PatchShaderType;
import org.apache.commons.codec.binary.Hex; import org.apache.commons.codec.binary.Hex;
@@ -25,6 +24,7 @@ import java.util.function.Supplier;
import java.util.zip.DeflaterOutputStream; import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream; import java.util.zip.InflaterInputStream;
import static net.irisshaders.iris.IrisLogging.IRIS_LOGGER;
import static org.embeddedt.embeddium.compat.mc.PlatformUtilService.PLATFORM_UTIL; import static org.embeddedt.embeddium.compat.mc.PlatformUtilService.PLATFORM_UTIL;
public class ShaderTransformationDiskCache { public class ShaderTransformationDiskCache {
@@ -61,12 +61,12 @@ public class ShaderTransformationDiskCache {
if(map != null && !map.isEmpty()) { if(map != null && !map.isEmpty()) {
return map; return map;
} else { } else {
Iris.logger.error("Cache data is corrupt"); IRIS_LOGGER.error("Cache data is corrupt");
Files.deleteIfExists(path); Files.deleteIfExists(path);
} }
} catch(FileNotFoundException | NoSuchFileException ignored) { } catch(FileNotFoundException | NoSuchFileException ignored) {
} catch(IOException e) { } catch(IOException e) {
Iris.logger.error("Error loading transformed shader, will re-transform now", e); IRIS_LOGGER.error("Error loading transformed shader, will re-transform now", e);
} }
Map<PatchShaderType, String> results = transformFn.get(); Map<PatchShaderType, String> results = transformFn.get();
@@ -77,7 +77,7 @@ public class ShaderTransformationDiskCache {
writer.write(new Gson().toJson(results, typeToken.getType())); writer.write(new Gson().toJson(results, typeToken.getType()));
} }
} catch(IOException e) { } catch(IOException e) {
Iris.logger.error("Error writing transformed shader to disk", e); IRIS_LOGGER.error("Error writing transformed shader to disk", e);
} }
return results; return results;
@@ -5,8 +5,6 @@ import net.irisshaders.iris.pipeline.transform.PatchShaderType;
import net.irisshaders.iris.pipeline.transform.parameter.SodiumParameters; import net.irisshaders.iris.pipeline.transform.parameter.SodiumParameters;
import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings;
import org.taumc.glsl.Transformer; import org.taumc.glsl.Transformer;
import org.taumc.glsl.Util;
import org.taumc.glsl.grammar.GLSLParser;
import static net.irisshaders.iris.pipeline.foss_transform.ShaderTransformer.*; import static net.irisshaders.iris.pipeline.foss_transform.ShaderTransformer.*;
@@ -1,7 +1,6 @@
package net.irisshaders.iris.pipeline.foss_transform; package net.irisshaders.iris.pipeline.foss_transform;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap; import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import net.irisshaders.iris.Iris;
import net.irisshaders.iris.gl.blending.AlphaTest; import net.irisshaders.iris.gl.blending.AlphaTest;
import net.irisshaders.iris.gl.state.ShaderAttributeInputs; import net.irisshaders.iris.gl.state.ShaderAttributeInputs;
import net.irisshaders.iris.gl.texture.TextureType; import net.irisshaders.iris.gl.texture.TextureType;
@@ -19,6 +18,8 @@ import net.irisshaders.iris.shaderpack.texture.TextureStage;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.Map; import java.util.Map;
import static net.irisshaders.iris.IrisLogging.IRIS_LOGGER;
public class TransformPatcherBridge { public class TransformPatcherBridge {
private static final boolean USE_GLSL_TRANSFORMER; private static final boolean USE_GLSL_TRANSFORMER;
@@ -35,7 +36,7 @@ public class TransformPatcherBridge {
} }
if(useGlslTransformer && transform == null) { if(useGlslTransformer && transform == null) {
Iris.logger.warn("glsl-transformer is requested, but is not available in this jar"); IRIS_LOGGER.warn("glsl-transformer is requested, but is not available in this jar");
useGlslTransformer = false; useGlslTransformer = false;
} }
@@ -8,16 +8,18 @@ import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2IntMaps; import it.unimi.dsi.fastutil.objects.Object2IntMaps;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap; import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap;
import net.irisshaders.iris.Iris; import net.irisshaders.iris.IrisCommon;
import net.irisshaders.iris.helpers.StringPair; import net.irisshaders.iris.helpers.StringPair;
import net.irisshaders.iris.pipeline.transform.ShaderPrinter; import net.irisshaders.iris.pipeline.transform.ShaderPrinter;
import net.irisshaders.iris.shaderpack.materialmap.BlockEntry;
import net.irisshaders.iris.shaderpack.materialmap.BlockRenderType; import net.irisshaders.iris.shaderpack.materialmap.BlockRenderType;
import net.irisshaders.iris.shaderpack.materialmap.LegacyIdMap; import net.irisshaders.iris.shaderpack.materialmap.LegacyIdMap;
import net.irisshaders.iris.shaderpack.materialmap.NamespacedId; import net.irisshaders.iris.shaderpack.materialmap.NamespacedId;
import net.irisshaders.iris.shaderpack.option.OrderBackedProperties; import net.irisshaders.iris.shaderpack.option.OrderBackedProperties;
import net.irisshaders.iris.shaderpack.option.ShaderPackOptions; import net.irisshaders.iris.shaderpack.option.ShaderPackOptions;
import net.irisshaders.iris.shaderpack.preprocessor.PropertiesPreprocessor; import net.irisshaders.iris.shaderpack.preprocessor.PropertiesPreprocessor;
import org.embeddedt.embeddium.compat.iris.IBlockEntry;
import org.taumc.celeritas.CeleritasShaderVersionService;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
@@ -29,6 +31,7 @@ import java.nio.file.NoSuchFileException;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.*; import java.util.*;
import static net.irisshaders.iris.IrisLogging.IRIS_LOGGER;
import static org.embeddedt.embeddium.compat.mc.PlatformUtilService.PLATFORM_UTIL; import static org.embeddedt.embeddium.compat.mc.PlatformUtilService.PLATFORM_UTIL;
/** /**
@@ -48,7 +51,7 @@ public class IdMap {
/** /**
* Maps block states to block ids defined in block.properties * Maps block states to block ids defined in block.properties
*/ */
private Int2ObjectMap<List<BlockEntry>> blockPropertiesMap; private Int2ObjectMap<List<IBlockEntry>> blockPropertiesMap;
/** /**
* A set of render type overrides for specific blocks. Allows shader packs to move blocks to different render types. * A set of render type overrides for specific blocks. Allows shader packs to move blocks to different render types.
@@ -102,12 +105,12 @@ public class IdMap {
try { try {
properties.load(propertiesReader); properties.load(propertiesReader);
} catch (IOException e) { } catch (IOException e) {
Iris.logger.error("Error loading " + name + " at " + shaderPath, e); IRIS_LOGGER.error("Error loading " + name + " at " + shaderPath, e);
return Optional.empty(); return Optional.empty();
} }
if (Iris.getIrisConfig().areDebugOptionsEnabled()) { if (IrisCommon.getIrisConfig().areDebugOptionsEnabled()) {
ShaderPrinter.deleteIfClearing(); ShaderPrinter.deleteIfClearing();
try (OutputStream os = Files.newOutputStream(PLATFORM_UTIL.getGameDir().resolve("patched_shaders").resolve(name))) { try (OutputStream os = Files.newOutputStream(PLATFORM_UTIL.getGameDir().resolve("patched_shaders").resolve(name))) {
properties.store(new OutputStreamWriter(os, StandardCharsets.UTF_8), "Patched version of properties"); properties.store(new OutputStreamWriter(os, StandardCharsets.UTF_8), "Patched version of properties");
@@ -124,11 +127,11 @@ public class IdMap {
// ID maps should be encoded in ISO_8859_1. // ID maps should be encoded in ISO_8859_1.
return Files.readString(shaderPath.resolve(name), StandardCharsets.ISO_8859_1); return Files.readString(shaderPath.resolve(name), StandardCharsets.ISO_8859_1);
} catch (NoSuchFileException e) { } catch (NoSuchFileException e) {
Iris.logger.debug("An " + name + " file was not found in the current shaderpack"); IRIS_LOGGER.debug("An " + name + " file was not found in the current shaderpack");
return null; return null;
} catch (IOException e) { } catch (IOException e) {
Iris.logger.error("An IOException occurred reading " + name + " from the current shaderpack", e); IRIS_LOGGER.error("An IOException occurred reading " + name + " from the current shaderpack", e);
return null; return null;
} }
@@ -164,7 +167,7 @@ public class IdMap {
intId = Integer.parseInt(key.substring(keyPrefix.length())); intId = Integer.parseInt(key.substring(keyPrefix.length()));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
// Not a valid property line // Not a valid property line
Iris.logger.warn("Failed to parse line in " + fileName + ": invalid key " + key); IRIS_LOGGER.warn("Failed to parse line in " + fileName + ": invalid key " + key);
return; return;
} }
@@ -172,7 +175,7 @@ public class IdMap {
for (String part : value.split("\\s+")) { for (String part : value.split("\\s+")) {
if (part.contains("=")) { if (part.contains("=")) {
// Avoid tons of logspam for now // Avoid tons of logspam for now
Iris.logger.warn("Failed to parse an ResourceLocation in " + fileName + " for the key " + key + ": state properties are currently not supported: " + part); IRIS_LOGGER.warn("Failed to parse an ResourceLocation in " + fileName + " for the key " + key + ": state properties are currently not supported: " + part);
continue; continue;
} }
@@ -185,8 +188,8 @@ public class IdMap {
return Object2IntMaps.unmodifiable(idMap); return Object2IntMaps.unmodifiable(idMap);
} }
private static Int2ObjectMap<List<BlockEntry>> parseBlockMap(Properties properties, String keyPrefix, String fileName) { private static Int2ObjectMap<List<IBlockEntry>> parseBlockMap(Properties properties, String keyPrefix, String fileName) {
Int2ObjectMap<List<BlockEntry>> entriesById = new Int2ObjectOpenHashMap<>(); Int2ObjectMap<List<IBlockEntry>> entriesById = new Int2ObjectOpenHashMap<>();
properties.forEach((keyObject, valueObject) -> { properties.forEach((keyObject, valueObject) -> {
String key = (String) keyObject; String key = (String) keyObject;
@@ -203,11 +206,11 @@ public class IdMap {
intId = Integer.parseInt(key.substring(keyPrefix.length())); intId = Integer.parseInt(key.substring(keyPrefix.length()));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
// Not a valid property line // Not a valid property line
Iris.logger.warn("Failed to parse line in " + fileName + ": invalid key " + key); IRIS_LOGGER.warn("Failed to parse line in " + fileName + ": invalid key " + key);
return; return;
} }
List<BlockEntry> entries = new ArrayList<>(); List<IBlockEntry> entries = new ArrayList<>();
// Split on whitespace groups, not just single spaces // Split on whitespace groups, not just single spaces
for (String part : value.split("\\s+")) { for (String part : value.split("\\s+")) {
@@ -216,9 +219,9 @@ public class IdMap {
} }
try { try {
entries.add(BlockEntry.parse(part)); entries.add(CeleritasShaderVersionService.INSTANCE.parseBlockEntry(part));
} catch (Exception e) { } catch (Exception e) {
Iris.logger.warn("Unexpected error while parsing an entry from " + fileName + " for the key " + key + ":", e); IRIS_LOGGER.warn("Unexpected error while parsing an entry from " + fileName + " for the key " + key + ":", e);
} }
} }
@@ -254,7 +257,7 @@ public class IdMap {
BlockRenderType renderType = BlockRenderType.fromString(keyWithoutPrefix).orElse(null); BlockRenderType renderType = BlockRenderType.fromString(keyWithoutPrefix).orElse(null);
if (renderType == null) { if (renderType == null) {
Iris.logger.warn("Failed to parse line in " + fileName + ": invalid block render type: " + key); IRIS_LOGGER.warn("Failed to parse line in " + fileName + ": invalid block render type: " + key);
return; return;
} }
@@ -291,7 +294,7 @@ public class IdMap {
return overrides; return overrides;
} }
public Int2ObjectMap<List<BlockEntry>> getBlockProperties() { public Int2ObjectMap<List<IBlockEntry>> getBlockProperties() {
return blockPropertiesMap; return blockPropertiesMap;
} }
@@ -4,7 +4,8 @@ import com.google.common.collect.ImmutableList;
import net.irisshaders.iris.gl.shader.StandardMacros; import net.irisshaders.iris.gl.shader.StandardMacros;
import net.irisshaders.iris.helpers.StringPair; import net.irisshaders.iris.helpers.StringPair;
import net.irisshaders.iris.parsing.BiomeCategories; import net.irisshaders.iris.parsing.BiomeCategories;
import net.irisshaders.iris.uniforms.BiomeUniforms; import org.taumc.celeritas.CeleritasShaderVersionService;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@@ -25,7 +26,7 @@ public class IrisDefines {
public static ImmutableList<StringPair> createIrisReplacements() { public static ImmutableList<StringPair> createIrisReplacements() {
ArrayList<StringPair> s = new ArrayList<>(StandardMacros.createStandardEnvironmentDefines()); ArrayList<StringPair> s = new ArrayList<>(StandardMacros.createStandardEnvironmentDefines());
BiomeUniforms.getBiomeMap().forEach((biome, id) -> define(s, "BIOME_" + biome.location().getPath().toUpperCase(Locale.ROOT), String.valueOf(id))); CeleritasShaderVersionService.INSTANCE.processBiomeMap((key, value) -> define(s, key, value));
BiomeCategories[] categories = BiomeCategories.values(); BiomeCategories[] categories = BiomeCategories.values();
for (int i = 0; i < categories.length; i++) { for (int i = 0; i < categories.length; i++) {
@@ -1,7 +1,6 @@
package net.irisshaders.iris.shaderpack; package net.irisshaders.iris.shaderpack;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import net.irisshaders.iris.Iris;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
@@ -11,6 +10,8 @@ import java.nio.file.Path;
import java.util.*; import java.util.*;
import java.util.stream.Stream; import java.util.stream.Stream;
import static net.irisshaders.iris.IrisLogging.IRIS_LOGGER;
public class LanguageMap { public class LanguageMap {
private final Map<String, Map<String, String>> translationMaps; private final Map<String, Map<String, String>> translationMaps;
@@ -46,7 +47,7 @@ public class LanguageMap {
try (InputStreamReader isr = new InputStreamReader(Files.newInputStream(path), StandardCharsets.UTF_8)) { try (InputStreamReader isr = new InputStreamReader(Files.newInputStream(path), StandardCharsets.UTF_8)) {
properties.load(isr); properties.load(isr);
} catch (IOException e) { } catch (IOException e) {
Iris.logger.error("Failed to parse shader pack language file " + path, e); IRIS_LOGGER.error("Failed to parse shader pack language file " + path, e);
} }
ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
@@ -8,11 +8,8 @@ import com.google.gson.stream.JsonReader;
import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap; import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap; import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import net.irisshaders.iris.api.v0.IrisApi;
import net.irisshaders.iris.features.FeatureFlags; import net.irisshaders.iris.features.FeatureFlags;
import net.irisshaders.iris.gl.texture.TextureDefinition; import net.irisshaders.iris.gl.texture.TextureDefinition;
import net.irisshaders.iris.gui.FeatureMissingErrorScreen;
import net.irisshaders.iris.gui.screen.ShaderPackScreen;
import net.irisshaders.iris.helpers.StringPair; import net.irisshaders.iris.helpers.StringPair;
import net.irisshaders.iris.pathways.colorspace.ColorSpace; import net.irisshaders.iris.pathways.colorspace.ColorSpace;
import net.irisshaders.iris.shaderpack.include.AbsolutePackPath; import net.irisshaders.iris.shaderpack.include.AbsolutePackPath;
@@ -20,10 +17,10 @@ import net.irisshaders.iris.shaderpack.include.IncludeGraph;
import net.irisshaders.iris.shaderpack.include.IncludeProcessor; import net.irisshaders.iris.shaderpack.include.IncludeProcessor;
import net.irisshaders.iris.shaderpack.include.ShaderPackSourceNames; import net.irisshaders.iris.shaderpack.include.ShaderPackSourceNames;
import net.irisshaders.iris.shaderpack.materialmap.NamespacedId; import net.irisshaders.iris.shaderpack.materialmap.NamespacedId;
import net.irisshaders.iris.shaderpack.option.menu.OptionMenuContainer;
import net.irisshaders.iris.shaderpack.option.OrderBackedProperties; import net.irisshaders.iris.shaderpack.option.OrderBackedProperties;
import net.irisshaders.iris.shaderpack.option.ProfileSet; import net.irisshaders.iris.shaderpack.option.ProfileSet;
import net.irisshaders.iris.shaderpack.option.ShaderPackOptions; import net.irisshaders.iris.shaderpack.option.ShaderPackOptions;
import net.irisshaders.iris.shaderpack.option.menu.OptionMenuContainer;
import net.irisshaders.iris.shaderpack.option.values.MutableOptionValues; import net.irisshaders.iris.shaderpack.option.values.MutableOptionValues;
import net.irisshaders.iris.shaderpack.option.values.OptionValues; import net.irisshaders.iris.shaderpack.option.values.OptionValues;
import net.irisshaders.iris.shaderpack.preprocessor.JcppProcessor; import net.irisshaders.iris.shaderpack.preprocessor.JcppProcessor;
@@ -35,11 +32,9 @@ import net.irisshaders.iris.shaderpack.texture.CustomTextureData;
import net.irisshaders.iris.shaderpack.texture.TextureFilteringData; import net.irisshaders.iris.shaderpack.texture.TextureFilteringData;
import net.irisshaders.iris.shaderpack.texture.TextureStage; import net.irisshaders.iris.shaderpack.texture.TextureStage;
import net.irisshaders.iris.uniforms.custom.CustomUniforms; import net.irisshaders.iris.uniforms.custom.CustomUniforms;
import net.minecraft.client.Minecraft;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import org.apache.commons.lang3.SystemUtils;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.taumc.celeritas.CeleritasShaderVersionService;
import org.taumc.celeritas.api.v0.CeleritasShadersApi;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
@@ -197,15 +192,8 @@ public class ShaderPack {
List<String> invalidFeatureFlags = invalidFlagList.stream().map(FeatureFlags::getHumanReadableName).toList(); List<String> invalidFeatureFlags = invalidFlagList.stream().map(FeatureFlags::getHumanReadableName).toList();
if (!invalidFeatureFlags.isEmpty()) { if (!invalidFeatureFlags.isEmpty()) {
if (Minecraft.getInstance().screen instanceof ShaderPackScreen) { CeleritasShaderVersionService.INSTANCE.handleUnsupportedFeatureFlags(invalidFlagList, invalidFeatureFlags);
MutableComponent component = Component.translatable("iris.unsupported.pack.description", FeatureFlags.getInvalidStatus(invalidFlagList), invalidFeatureFlags.stream() CeleritasShadersApi.getInstance().getConfig().setShadersEnabledAndApply(false);
.collect(Collectors.joining(", ", ": ", ".")));
if (SystemUtils.IS_OS_MAC) {
component = component.append(Component.translatable("iris.unsupported.pack.macos"));
}
Minecraft.getInstance().setScreen(new FeatureMissingErrorScreen(Minecraft.getInstance().screen, Component.translatable("iris.unsupported.pack"), component));
}
IrisApi.getInstance().getConfig().setShadersEnabledAndApply(false);
} }
List<StringPair> newEnvDefines = new ArrayList<>(environmentDefines); List<StringPair> newEnvDefines = new ArrayList<>(environmentDefines);
@@ -3,10 +3,12 @@ package net.irisshaders.iris.shaderpack.materialmap;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import it.unimi.dsi.fastutil.Function; import it.unimi.dsi.fastutil.Function;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import org.embeddedt.embeddium.compat.iris.IBlockEntry;
import org.taumc.celeritas.CeleritasShaderVersionService;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections;
import java.util.List; import java.util.List;
public class LegacyIdMap { public class LegacyIdMap {
@@ -17,7 +19,7 @@ public class LegacyIdMap {
private static final ImmutableList<String> WOOD_TYPES = private static final ImmutableList<String> WOOD_TYPES =
ImmutableList.of("oak", "birch", "jungle", "spruce", "acacia", "dark_oak"); ImmutableList.of("oak", "birch", "jungle", "spruce", "acacia", "dark_oak");
public static void addLegacyValues(Int2ObjectMap<List<BlockEntry>> blockIdMap) { public static void addLegacyValues(Int2ObjectMap<List<IBlockEntry>> blockIdMap) {
add(blockIdMap, 1, block("stone"), block("granite"), block("diorite"), block("andesite")); add(blockIdMap, 1, block("stone"), block("granite"), block("diorite"), block("andesite"));
add(blockIdMap, 2, block("grass_block")); add(blockIdMap, 2, block("grass_block"));
add(blockIdMap, 4, block("cobblestone")); add(blockIdMap, 4, block("cobblestone"));
@@ -76,12 +78,12 @@ public class LegacyIdMap {
// TODO: 76 -> redstone_torch (on) // TODO: 76 -> redstone_torch (on)
} }
private static BlockEntry block(String name) { private static IBlockEntry block(String name) {
return new BlockEntry(new NamespacedId("minecraft", name), Collections.emptyMap(), false); return CeleritasShaderVersionService.INSTANCE.createBlockEntry(new NamespacedId("minecraft", name));
} }
private static void addMany(Int2ObjectMap<List<BlockEntry>> blockIdMap, int id, List<String> prefixes, Function<String, BlockEntry> toId) { private static void addMany(Int2ObjectMap<List<IBlockEntry>> blockIdMap, int id, List<String> prefixes, Function<String, IBlockEntry> toId) {
List<BlockEntry> entries = new ArrayList<>(); List<IBlockEntry> entries = new ArrayList<>();
for (String prefix : prefixes) { for (String prefix : prefixes) {
entries.add(toId.apply(prefix)); entries.add(toId.apply(prefix));
@@ -90,7 +92,7 @@ public class LegacyIdMap {
blockIdMap.put(id, entries); blockIdMap.put(id, entries);
} }
private static void add(Int2ObjectMap<List<BlockEntry>> blockIdMap, int id, BlockEntry... entries) { private static void add(Int2ObjectMap<List<IBlockEntry>> blockIdMap, int id, IBlockEntry... entries) {
blockIdMap.put(id, Arrays.asList(entries)); blockIdMap.put(id, Arrays.asList(entries));
} }
} }
@@ -1,23 +1,15 @@
package net.irisshaders.iris.shaderpack.materialmap; package net.irisshaders.iris.shaderpack.materialmap;
import it.unimi.dsi.fastutil.objects.Object2IntFunction; import it.unimi.dsi.fastutil.objects.Object2IntFunction;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.Map; import static org.embeddedt.embeddium.compat.mc.MinecraftVersionShimService.MINECRAFT_SHIM;
import java.util.Objects;
public class WorldRenderingSettings { public class WorldRenderingSettings {
public static final WorldRenderingSettings INSTANCE = new WorldRenderingSettings(); public static final WorldRenderingSettings INSTANCE = new WorldRenderingSettings();
private boolean reloadRequired; private boolean reloadRequired;
private Object2IntMap<BlockState> blockStateIds;
private FallbackTextureMaterials fallbackTextureMaterialMapping;
private Map<Block, RenderType> blockTypeIds;
private Object2IntFunction<NamespacedId> entityIds; private Object2IntFunction<NamespacedId> entityIds;
private Object2IntFunction<NamespacedId> itemIds; private Object2IntFunction<NamespacedId> itemIds;
private float ambientOcclusionLevel; private float ambientOcclusionLevel;
@@ -30,8 +22,6 @@ public class WorldRenderingSettings {
public WorldRenderingSettings() { public WorldRenderingSettings() {
reloadRequired = false; reloadRequired = false;
blockStateIds = null;
blockTypeIds = null;
ambientOcclusionLevel = 1.0F; ambientOcclusionLevel = 1.0F;
disableDirectionalShading = false; disableDirectionalShading = false;
useSeparateAo = false; useSeparateAo = false;
@@ -51,56 +41,11 @@ public class WorldRenderingSettings {
public void reloadRendererIfRequired() { public void reloadRendererIfRequired() {
if (isReloadRequired()) { if (isReloadRequired()) {
if (Minecraft.getInstance().levelRenderer != null) { MINECRAFT_SHIM.markRendererReloadRequired();
Minecraft.getInstance().levelRenderer.allChanged();
}
clearReloadRequired(); clearReloadRequired();
} }
} }
@Nullable
public Object2IntMap<BlockState> getBlockStateIds() {
return blockStateIds;
}
public void setBlockStateIds(Object2IntMap<BlockState> blockStateIds) {
if (Objects.equals(this.blockStateIds, blockStateIds)) {
return;
}
this.reloadRequired = true;
this.blockStateIds = blockStateIds;
}
@Nullable
public FallbackTextureMaterials getFallbackTextureMaterialMapping() {
return fallbackTextureMaterialMapping;
}
public void setFallbackTextureMaterialMapping(FallbackTextureMaterials fallbackTextureMaterialMapping) {
if (Objects.equals(this.fallbackTextureMaterialMapping, fallbackTextureMaterialMapping)) {
return;
}
this.reloadRequired = true;
this.fallbackTextureMaterialMapping = fallbackTextureMaterialMapping;
}
@Nullable
public Map<Block, RenderType> getBlockTypeIds() {
return blockTypeIds;
}
public void setBlockTypeIds(Map<Block, RenderType> blockTypeIds) {
if (Objects.equals(this.blockTypeIds, blockTypeIds)) {
return;
}
this.reloadRequired = true;
this.blockTypeIds = blockTypeIds;
}
@Nullable @Nullable
public Object2IntFunction<NamespacedId> getEntityIds() { public Object2IntFunction<NamespacedId> getEntityIds() {
@@ -199,4 +144,8 @@ public class WorldRenderingSettings {
public boolean hasVillagerConversionId() { public boolean hasVillagerConversionId() {
return hasVillagerConversionId; return hasVillagerConversionId;
} }
public void setReloadRequired() {
reloadRequired = true;
}
} }
@@ -1,7 +1,6 @@
package net.irisshaders.iris.shaderpack.option.menu; package net.irisshaders.iris.shaderpack.option.menu;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import net.irisshaders.iris.Iris;
import net.irisshaders.iris.shaderpack.option.ProfileSet; import net.irisshaders.iris.shaderpack.option.ProfileSet;
import net.irisshaders.iris.shaderpack.option.ShaderPackOptions; import net.irisshaders.iris.shaderpack.option.ShaderPackOptions;
import net.irisshaders.iris.shaderpack.properties.ShaderProperties; import net.irisshaders.iris.shaderpack.properties.ShaderProperties;
@@ -13,6 +12,8 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import static net.irisshaders.iris.IrisLogging.IRIS_LOGGER;
public class OptionMenuContainer { public class OptionMenuContainer {
public final OptionMenuElementScreen mainScreen; public final OptionMenuElementScreen mainScreen;
public final Map<String, OptionMenuElementScreen> subScreens = new HashMap<>(); public final Map<String, OptionMenuElementScreen> subScreens = new HashMap<>();
@@ -58,7 +59,7 @@ public class OptionMenuContainer {
} }
} }
} catch (IllegalArgumentException error) { } catch (IllegalArgumentException error) {
Iris.logger.warn(error); IRIS_LOGGER.warn(error);
elementsToInsert.add(OptionMenuElement.EMPTY); elementsToInsert.add(OptionMenuElement.EMPTY);
} }
@@ -1,6 +1,5 @@
package net.irisshaders.iris.shaderpack.option.menu; package net.irisshaders.iris.shaderpack.option.menu;
import net.irisshaders.iris.Iris;
import net.irisshaders.iris.shaderpack.option.ShaderPackOptions; import net.irisshaders.iris.shaderpack.option.ShaderPackOptions;
import net.irisshaders.iris.shaderpack.properties.ShaderProperties; import net.irisshaders.iris.shaderpack.properties.ShaderProperties;
@@ -8,6 +7,8 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import static net.irisshaders.iris.IrisLogging.IRIS_LOGGER;
public class OptionMenuElementScreen { public class OptionMenuElementScreen {
public final List<OptionMenuElement> elements = new ArrayList<>(); public final List<OptionMenuElement> elements = new ArrayList<>();
@@ -34,7 +35,7 @@ public class OptionMenuElementScreen {
} }
} }
} catch (IllegalArgumentException error) { } catch (IllegalArgumentException error) {
Iris.logger.warn(error.getMessage()); IRIS_LOGGER.warn(error.getMessage());
this.elements.add(OptionMenuElement.EMPTY); this.elements.add(OptionMenuElement.EMPTY);
} }
@@ -1,6 +1,6 @@
package net.irisshaders.iris.shaderpack.option.menu; package net.irisshaders.iris.shaderpack.option.menu;
import net.irisshaders.iris.Iris; import net.irisshaders.iris.IrisCommon;
import net.irisshaders.iris.shaderpack.option.values.MutableOptionValues; import net.irisshaders.iris.shaderpack.option.values.MutableOptionValues;
import net.irisshaders.iris.shaderpack.option.values.OptionValues; import net.irisshaders.iris.shaderpack.option.values.OptionValues;
import net.irisshaders.iris.shaderpack.properties.ShaderProperties; import net.irisshaders.iris.shaderpack.properties.ShaderProperties;
@@ -32,7 +32,7 @@ public abstract class OptionMenuOptionElement extends OptionMenuElement {
*/ */
public OptionValues getPendingOptionValues() { public OptionValues getPendingOptionValues() {
MutableOptionValues values = getAppliedOptionValues().mutableCopy(); MutableOptionValues values = getAppliedOptionValues().mutableCopy();
values.addAll(Iris.getShaderPackOptionQueue()); values.addAll(IrisCommon.getShaderPackOptionQueue());
return values; return values;
} }
@@ -1,6 +1,6 @@
package net.irisshaders.iris.shaderpack.option.menu; package net.irisshaders.iris.shaderpack.option.menu;
import net.irisshaders.iris.Iris; import net.irisshaders.iris.IrisCommon;
import net.irisshaders.iris.shaderpack.option.OptionSet; import net.irisshaders.iris.shaderpack.option.OptionSet;
import net.irisshaders.iris.shaderpack.option.ProfileSet; import net.irisshaders.iris.shaderpack.option.ProfileSet;
import net.irisshaders.iris.shaderpack.option.values.MutableOptionValues; import net.irisshaders.iris.shaderpack.option.values.MutableOptionValues;
@@ -24,7 +24,7 @@ public class OptionMenuProfileElement extends OptionMenuElement {
*/ */
public OptionValues getPendingOptionValues() { public OptionValues getPendingOptionValues() {
MutableOptionValues values = packAppliedValues.mutableCopy(); MutableOptionValues values = packAppliedValues.mutableCopy();
values.addAll(Iris.getShaderPackOptionQueue()); values.addAll(IrisCommon.getShaderPackOptionQueue());
return values; return values;
} }
@@ -1,20 +1,21 @@
package net.irisshaders.iris.shaderpack.parsing; package net.irisshaders.iris.shaderpack.parsing;
import net.irisshaders.iris.Iris;
import net.irisshaders.iris.shaderpack.programs.ComputeSource; import net.irisshaders.iris.shaderpack.programs.ComputeSource;
import org.joml.Vector2f; import org.joml.Vector2f;
import org.joml.Vector3i; import org.joml.Vector3i;
import static net.irisshaders.iris.IrisLogging.IRIS_LOGGER;
public class ComputeDirectiveParser { public class ComputeDirectiveParser {
public static void setComputeWorkGroups(ComputeSource source, ConstDirectiveParser.ConstDirective directive) { public static void setComputeWorkGroups(ComputeSource source, ConstDirectiveParser.ConstDirective directive) {
if (!directive.getValue().startsWith("ivec3")) { if (!directive.getValue().startsWith("ivec3")) {
Iris.logger.error("Failed to process " + directive + ": value was not a valid ivec3 constructor"); IRIS_LOGGER.error("Failed to process " + directive + ": value was not a valid ivec3 constructor");
} }
String ivec3Args = directive.getValue().substring("ivec3".length()).trim(); String ivec3Args = directive.getValue().substring("ivec3".length()).trim();
if (!ivec3Args.startsWith("(") || !ivec3Args.endsWith(")")) { if (!ivec3Args.startsWith("(") || !ivec3Args.endsWith(")")) {
Iris.logger.error("Failed to process " + directive + ": value was not a valid ivec3 constructor"); IRIS_LOGGER.error("Failed to process " + directive + ": value was not a valid ivec3 constructor");
} }
ivec3Args = ivec3Args.substring(1, ivec3Args.length() - 1); ivec3Args = ivec3Args.substring(1, ivec3Args.length() - 1);
@@ -26,7 +27,7 @@ public class ComputeDirectiveParser {
} }
if (parts.length != 3) { if (parts.length != 3) {
Iris.logger.error("Failed to process " + directive + IRIS_LOGGER.error("Failed to process " + directive +
": expected 3 arguments to a ivec3 constructor, got " + parts.length); ": expected 3 arguments to a ivec3 constructor, got " + parts.length);
} }
@@ -36,19 +37,19 @@ public class ComputeDirectiveParser {
Integer.parseInt(parts[1]), Integer.parseInt(parts[1]),
Integer.parseInt(parts[2]))); Integer.parseInt(parts[2])));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
Iris.logger.error("Failed to process " + directive, e); IRIS_LOGGER.error("Failed to process " + directive, e);
} }
} }
public static void setComputeWorkGroupsRelative(ComputeSource source, ConstDirectiveParser.ConstDirective directive) { public static void setComputeWorkGroupsRelative(ComputeSource source, ConstDirectiveParser.ConstDirective directive) {
if (!directive.getValue().startsWith("vec2")) { if (!directive.getValue().startsWith("vec2")) {
Iris.logger.error("Failed to process " + directive + ": value was not a valid vec2 constructor"); IRIS_LOGGER.error("Failed to process " + directive + ": value was not a valid vec2 constructor");
} }
String vec2Args = directive.getValue().substring("vec2".length()).trim(); String vec2Args = directive.getValue().substring("vec2".length()).trim();
if (!vec2Args.startsWith("(") || !vec2Args.endsWith(")")) { if (!vec2Args.startsWith("(") || !vec2Args.endsWith(")")) {
Iris.logger.error("Failed to process " + directive + ": value was not a valid vec2 constructor"); IRIS_LOGGER.error("Failed to process " + directive + ": value was not a valid vec2 constructor");
} }
vec2Args = vec2Args.substring(1, vec2Args.length() - 1); vec2Args = vec2Args.substring(1, vec2Args.length() - 1);
@@ -60,7 +61,7 @@ public class ComputeDirectiveParser {
} }
if (parts.length != 2) { if (parts.length != 2) {
Iris.logger.error("Failed to process " + directive + IRIS_LOGGER.error("Failed to process " + directive +
": expected 2 arguments to a vec2 constructor, got " + parts.length); ": expected 2 arguments to a vec2 constructor, got " + parts.length);
} }
@@ -70,7 +71,7 @@ public class ComputeDirectiveParser {
Float.parseFloat(parts[1]) Float.parseFloat(parts[1])
)); ));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
Iris.logger.error("Failed to process " + directive, e); IRIS_LOGGER.error("Failed to process " + directive, e);
} }
} }
} }
@@ -1,6 +1,5 @@
package net.irisshaders.iris.shaderpack.programs; package net.irisshaders.iris.shaderpack.programs;
import net.irisshaders.iris.Iris;
import net.irisshaders.iris.features.FeatureFlags; import net.irisshaders.iris.features.FeatureFlags;
import net.irisshaders.iris.gl.blending.BlendModeOverride; import net.irisshaders.iris.gl.blending.BlendModeOverride;
import net.irisshaders.iris.shaderpack.ShaderPack; import net.irisshaders.iris.shaderpack.ShaderPack;
@@ -20,6 +19,8 @@ import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.function.Function; import java.util.function.Function;
import static net.irisshaders.iris.IrisLogging.IRIS_LOGGER;
public class ProgramSet implements ProgramSetInterface { public class ProgramSet implements ProgramSetInterface {
private final PackDirectives packDirectives; private final PackDirectives packDirectives;
@@ -202,7 +203,7 @@ public class ProgramSet implements ProgramSetInterface {
if (vertexSource == null && fragmentSource != null) { if (vertexSource == null && fragmentSource != null) {
// This is for really old packs that do not use a vertex shader. // This is for really old packs that do not use a vertex shader.
Iris.logger.warn("Found a program (" + program + ") that has a fragment shader but no vertex shader? This is very legacy behavior and might not work right."); IRIS_LOGGER.warn("Found a program (" + program + ") that has a fragment shader but no vertex shader? This is very legacy behavior and might not work right.");
vertexSource = """ vertexSource = """
#version 120 #version 120
@@ -364,7 +365,7 @@ public class ProgramSet implements ProgramSetInterface {
} }
packDirectives.getRenderTargetDirectives().getRenderTargetSettings().forEach((index, settings) -> packDirectives.getRenderTargetDirectives().getRenderTargetSettings().forEach((index, settings) ->
Iris.logger.debug("Render target settings for colortex" + index + ": " + settings)); IRIS_LOGGER.debug("Render target settings for colortex" + index + ": " + settings));
} }
public Optional<ProgramSource> getShadow() { public Optional<ProgramSource> getShadow() {
@@ -2,12 +2,12 @@ package net.irisshaders.iris.texture;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import net.irisshaders.iris.Iris; import net.irisshaders.iris.IrisCommon;
import net.irisshaders.iris.gl.IrisRenderSystem; import net.irisshaders.iris.gl.IrisRenderSystem;
import net.irisshaders.iris.gl.state.StateUpdateNotifiers; import net.irisshaders.iris.gl.state.StateUpdateNotifiers;
import net.irisshaders.iris.gl.texture.TextureType; import net.irisshaders.iris.gl.texture.TextureType;
import net.irisshaders.iris.pipeline.WorldRenderingPipeline; import net.irisshaders.iris.pipeline.WorldRenderingPipeline;
import net.minecraft.client.renderer.texture.AbstractTexture; import org.embeddedt.embeddium.compat.mc.MCAbstractTexture;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
public class TextureTracker { public class TextureTracker {
@@ -19,19 +19,19 @@ public class TextureTracker {
StateUpdateNotifiers.bindTextureNotifier = listener -> bindTextureListener = listener; StateUpdateNotifiers.bindTextureNotifier = listener -> bindTextureListener = listener;
} }
private final Int2ObjectMap<AbstractTexture> textures = new Int2ObjectOpenHashMap<>(); private final Int2ObjectMap<MCAbstractTexture> textures = new Int2ObjectOpenHashMap<>();
private boolean lockBindCallback; private boolean lockBindCallback;
private TextureTracker() { private TextureTracker() {
} }
public void trackTexture(int id, AbstractTexture texture) { public void trackTexture(int id, MCAbstractTexture texture) {
textures.put(id, texture); textures.put(id, texture);
} }
@Nullable @Nullable
public AbstractTexture getTexture(int id) { public MCAbstractTexture getTexture(int id) {
return textures.get(id); return textures.get(id);
} }
@@ -44,7 +44,7 @@ public class TextureTracker {
if (bindTextureListener != null) { if (bindTextureListener != null) {
bindTextureListener.run(); bindTextureListener.run();
} }
WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable(); WorldRenderingPipeline pipeline = IrisCommon.getPipelineManager().getPipelineNullable();
if (pipeline != null) { if (pipeline != null) {
pipeline.onSetShaderTexture(id); pipeline.onSetShaderTexture(id);
} }
@@ -4,6 +4,7 @@ import org.embeddedt.embeddium.compat.mc.IResource;
import org.embeddedt.embeddium.compat.mc.IResourceLocation; import org.embeddedt.embeddium.compat.mc.IResourceLocation;
import org.embeddedt.embeddium.compat.mc.IResourceProvider; import org.embeddedt.embeddium.compat.mc.IResourceProvider;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.taumc.celeritas.CeleritasShaderVersionService;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
@@ -71,7 +72,7 @@ public class TextureFormatLoader {
private static void onFormatChange() { private static void onFormatChange() {
try { try {
MINECRAFT_SHIM.reloadIris(); CeleritasShaderVersionService.INSTANCE.reloadIris();
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@@ -1,9 +1,9 @@
package net.irisshaders.iris.texture.util; package net.irisshaders.iris.texture.util;
import static com.mitchej123.glsm.GLStateManagerService.GL_STATE_MANAGER; import static com.mitchej123.glsm.GLStateManagerService.GL_STATE_MANAGER;
import static org.embeddedt.embeddium.compat.mc.MinecraftVersionShimService.MINECRAFT_SHIM;
import net.irisshaders.iris.gl.IrisRenderSystem; import net.irisshaders.iris.gl.IrisRenderSystem;
import net.minecraft.client.Minecraft;
import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL30; import org.lwjgl.opengl.GL30;
@@ -35,7 +35,7 @@ public class TextureManipulationUtil {
int height = GL_STATE_MANAGER.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, level, GL11.GL_TEXTURE_HEIGHT); int height = GL_STATE_MANAGER.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, level, GL11.GL_TEXTURE_HEIGHT);
GL_STATE_MANAGER.glViewport(0, 0, width, height); GL_STATE_MANAGER.glViewport(0, 0, width, height);
GL_STATE_MANAGER.glFramebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_COLOR_ATTACHMENT0, GL11.GL_TEXTURE_2D, textureId, level); GL_STATE_MANAGER.glFramebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_COLOR_ATTACHMENT0, GL11.GL_TEXTURE_2D, textureId, level);
GL_STATE_MANAGER.clear(GL11.GL_COLOR_BUFFER_BIT, Minecraft.ON_OSX); GL_STATE_MANAGER.clear(GL11.GL_COLOR_BUFFER_BIT, MINECRAFT_SHIM.isOnOSX());
GL_STATE_MANAGER.glFramebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_COLOR_ATTACHMENT0, GL11.GL_TEXTURE_2D, 0, level); GL_STATE_MANAGER.glFramebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_COLOR_ATTACHMENT0, GL11.GL_TEXTURE_2D, 0, level);
} }
@@ -0,0 +1,11 @@
package net.irisshaders.iris.uniforms;
import net.irisshaders.iris.gl.uniform.UniformHolder;
import java.util.ServiceLoader;
public interface BiomeUniforms {
BiomeUniforms BIOME_UNIFORMS = ServiceLoader.load(BiomeUniforms.class).findFirst().orElseThrow();
void addBiomeUniforms(UniformHolder uniforms);
}
@@ -0,0 +1,125 @@
package net.irisshaders.iris.uniforms;
import static com.mitchej123.glsm.GLStateManagerService.GL_STATE_MANAGER;
import static net.irisshaders.iris.gl.uniform.UniformUpdateFrequency.*;
import static net.irisshaders.iris.uniforms.IdMapUniforms.ID_MAP_UNIFORMS;
import static org.embeddedt.embeddium.compat.mc.MinecraftVersionShimService.MINECRAFT_SHIM;
import net.irisshaders.iris.compat.dh.DHCompat;
import net.irisshaders.iris.gl.blending.BlendMode;
import net.irisshaders.iris.gl.state.FogMode;
import net.irisshaders.iris.gl.state.StateUpdateNotifiers;
import net.irisshaders.iris.gl.uniform.DynamicUniformHolder;
import net.irisshaders.iris.gl.uniform.UniformHolder;
import net.irisshaders.iris.layer.GbufferPrograms;
import net.irisshaders.iris.shaderpack.IdMap;
import net.irisshaders.iris.shaderpack.properties.PackDirectives;
import net.irisshaders.iris.uniforms.transforms.SmoothedFloat;
import net.irisshaders.iris.uniforms.transforms.SmoothedVec2f;
import org.joml.*;
import org.joml.Math;
public final class CommonUniforms {
private static final Vector4i ZERO_VECTOR_4i = new Vector4i(0, 0, 0, 0);
static {
GbufferPrograms.init();
}
private CommonUniforms() {
// no construction allowed
}
// Needs to use a LocationalUniformHolder as we need it for the common uniforms
public static void addDynamicUniforms(DynamicUniformHolder uniforms, FogMode fogMode) {
ExternallyManagedUniforms.addExternallyManagedUniforms117(uniforms);
FogUniforms.addFogUniforms(uniforms, fogMode);
IrisInternalUniforms.addFogUniforms(uniforms, fogMode);
// This is a fallback for when entityId via attributes cannot be used. (lightning)
uniforms.uniform1i( "entityId", CapturedRenderingState.INSTANCE::getCurrentRenderedEntity, StateUpdateNotifiers.fallbackEntityNotifier);
// TODO: OptiFine doesn't think that atlasSize is a "dynamic" uniform,
// but we do. How will custom uniforms depending on atlasSize work?
//
// Note: on 1.17+ we don't need to reset this when textures are bound, since
// the shader will always be setup (and therefore uniforms will be re-uploaded)
// after the texture is changed and before rendering starts.
uniforms.uniform2i("atlasSize", MINECRAFT_SHIM::getAtlasSize, listener -> {});
uniforms.uniform2i("gtextureSize", MINECRAFT_SHIM::getTextureSize, StateUpdateNotifiers.bindTextureNotifier);
uniforms.uniform4i("blendFunc", () -> {
if (GL_STATE_MANAGER.isBlendEnabled()) {
final BlendMode blend = GL_STATE_MANAGER.getBlendMode();
return new Vector4i(blend.srcRgb(), blend.dstRgb(), blend.srcAlpha(), blend.dstAlpha());
} else {
return ZERO_VECTOR_4i;
}
}, StateUpdateNotifiers.blendFuncNotifier);
uniforms.uniform1i("renderStage", () -> GbufferPrograms.getCurrentPhase().ordinal(), StateUpdateNotifiers.phaseChangeNotifier);
}
public static void addCommonUniforms(DynamicUniformHolder uniforms, IdMap idMap, PackDirectives directives, FrameUpdateNotifier updateNotifier, FogMode fogMode) {
CommonUniforms.addNonDynamicUniforms(uniforms, idMap, directives, updateNotifier);
CommonUniforms.addDynamicUniforms(uniforms, fogMode);
}
public static void addNonDynamicUniforms(UniformHolder uniforms, IdMap idMap, PackDirectives directives, FrameUpdateNotifier updateNotifier) {
CameraUniforms.addCameraUniforms(uniforms, updateNotifier);
ViewportUniforms.addViewportUniforms(uniforms);
WorldTimeUniforms.addWorldTimeUniforms(uniforms);
SystemTimeUniforms.addSystemTimeUniforms(uniforms);
BiomeUniforms.BIOME_UNIFORMS.addBiomeUniforms(uniforms);
new CelestialUniforms(directives.getSunPathRotation()).addCelestialUniforms(uniforms);
IrisExclusiveUniforms.addIrisExclusiveUniforms(uniforms);
IrisTimeUniforms.addTimeUniforms(uniforms);
MatrixUniforms.addMatrixUniforms(uniforms, directives);
ID_MAP_UNIFORMS.addIdMapUniforms(updateNotifier, uniforms, idMap, directives.isOldHandLight());
CommonUniforms.generalCommonUniforms(uniforms, updateNotifier, directives);
}
public static void generalCommonUniforms(UniformHolder uniforms, FrameUpdateNotifier updateNotifier, PackDirectives directives) {
ExternallyManagedUniforms.addExternallyManagedUniforms117(uniforms);
SmoothedVec2f eyeBrightnessSmooth = new SmoothedVec2f(directives.getEyeBrightnessHalfLife(), directives.getEyeBrightnessHalfLife(), MINECRAFT_SHIM::getEyeBrightness, updateNotifier);
uniforms
.uniform1b(PER_FRAME, "hideGUI", MINECRAFT_SHIM::hideGui)
.uniform1b(PER_FRAME, "isRightHanded", MINECRAFT_SHIM::isRightHanded)
.uniform1i(PER_FRAME, "isEyeInWater", MINECRAFT_SHIM::isEyeInWater)
.uniform1f(PER_FRAME, "blindness", MINECRAFT_SHIM::getBlindness)
.uniform1f(PER_FRAME, "darknessFactor", MINECRAFT_SHIM::getDarknessFactor)
.uniform1f(PER_FRAME, "darknessLightFactor", CapturedRenderingState.INSTANCE::getDarknessLightFactor)
.uniform1f(PER_FRAME, "nightVision", MINECRAFT_SHIM::getNightVision)
.uniform1b(PER_FRAME, "is_sneaking", MINECRAFT_SHIM::isSneaking)
.uniform1b(PER_FRAME, "is_sprinting", MINECRAFT_SHIM::isSprinting)
.uniform1b(PER_FRAME, "is_hurt", MINECRAFT_SHIM::isHurt)
.uniform1b(PER_FRAME, "is_invisible", MINECRAFT_SHIM::isInvisible)
.uniform1b(PER_FRAME, "is_burning", MINECRAFT_SHIM::isBurning)
.uniform1b(PER_FRAME, "is_on_ground", MINECRAFT_SHIM::isOnGround)
// TODO: Do we need to clamp this to avoid fullbright breaking shaders? Or should shaders be able to detect
// that the player is trying to turn on fullbright?
.uniform1f(PER_FRAME, "screenBrightness", MINECRAFT_SHIM::getScreenBrightness)
// just a dummy value for shaders where entityColor isn't supplied through a vertex attribute (and thus is
// not available) - suppresses warnings. See AttributeShaderTransformer for the actual entityColor code.
.uniform4f(ONCE, "entityColor", () -> new Vector4f(0, 0, 0, 0))
.uniform1i(ONCE, "blockEntityId", () -> -1)
.uniform1i(ONCE, "currentRenderedItemId", () -> -1)
.uniform1f(ONCE, "pi", () -> Math.PI)
.uniform1f(PER_TICK, "playerMood", MINECRAFT_SHIM::getPlayerMood)
.uniform2i(PER_FRAME, "eyeBrightness", MINECRAFT_SHIM::getEyeBrightness)
.uniform2i(PER_FRAME, "eyeBrightnessSmooth", () -> {
Vector2f smoothed = eyeBrightnessSmooth.get();
return new Vector2i((int) smoothed.x(), (int) smoothed.y());
})
.uniform1f(PER_TICK, "rainStrength", MINECRAFT_SHIM::getRainStrength)
.uniform1f(PER_TICK, "wetness", new SmoothedFloat(directives.getWetnessHalfLife(), directives.getDrynessHalfLife(), MINECRAFT_SHIM::getRainStrength, updateNotifier))
.uniform3d(PER_FRAME, "skyColor", MINECRAFT_SHIM::getSkyColor)
.uniform1f(PER_FRAME, "dhFarPlane", DHCompat::getFarPlane)
.uniform1f(PER_FRAME, "dhNearPlane", DHCompat::getNearPlane)
.uniform1i(PER_FRAME, "dhRenderDistance", DHCompat::getRenderDistance);
}
}
@@ -0,0 +1,12 @@
package net.irisshaders.iris.uniforms;
import net.irisshaders.iris.gl.uniform.UniformHolder;
import net.irisshaders.iris.shaderpack.IdMap;
import java.util.ServiceLoader;
public interface IdMapUniforms {
IdMapUniforms ID_MAP_UNIFORMS = ServiceLoader.load(IdMapUniforms.class).findFirst().orElseThrow();
void addIdMapUniforms(FrameUpdateNotifier notifier, UniformHolder uniforms, IdMap idMap, boolean isOldHandLight);
}
@@ -3,13 +3,12 @@ package net.irisshaders.iris.uniforms;
import net.irisshaders.iris.compat.dh.DHCompat; import net.irisshaders.iris.compat.dh.DHCompat;
import net.irisshaders.iris.gl.uniform.UniformHolder; import net.irisshaders.iris.gl.uniform.UniformHolder;
import net.irisshaders.iris.shaderpack.properties.PackDirectives; import net.irisshaders.iris.shaderpack.properties.PackDirectives;
import net.irisshaders.iris.shadows.ShadowMatrices;
import net.irisshaders.iris.shadows.ShadowRenderer;
import org.joml.Matrix4f; import org.joml.Matrix4f;
import java.util.function.Supplier; import java.util.function.Supplier;
import static net.irisshaders.iris.gl.uniform.UniformUpdateFrequency.PER_FRAME; import static net.irisshaders.iris.gl.uniform.UniformUpdateFrequency.PER_FRAME;
import static org.embeddedt.embeddium.compat.mc.MinecraftVersionShimService.MINECRAFT_SHIM;
public final class MatrixUniforms { public final class MatrixUniforms {
private MatrixUniforms() { private MatrixUniforms() {
@@ -19,9 +18,8 @@ public final class MatrixUniforms {
addMatrix(uniforms, "ModelView", CapturedRenderingState.INSTANCE::getGbufferModelView); addMatrix(uniforms, "ModelView", CapturedRenderingState.INSTANCE::getGbufferModelView);
addMatrix(uniforms, "Projection", CapturedRenderingState.INSTANCE::getGbufferProjection); addMatrix(uniforms, "Projection", CapturedRenderingState.INSTANCE::getGbufferProjection);
addDHMatrix(uniforms, "Projection", DHCompat::getProjection); addDHMatrix(uniforms, "Projection", DHCompat::getProjection);
addShadowMatrix(uniforms, "ModelView", () -> addShadowMatrix(uniforms, "ModelView", () -> MINECRAFT_SHIM.getShadowModelView(directives.getSunPathRotation(), directives.getShadowDirectives().getIntervalSize()));
new Matrix4f(ShadowRenderer.createShadowModelView(directives.getSunPathRotation(), directives.getShadowDirectives().getIntervalSize()).last().pose())); addShadowMatrix(uniforms, "Projection", () -> MINECRAFT_SHIM.getShadowProjection(directives.getShadowDirectives().getDistance(),
addShadowMatrix(uniforms, "Projection", () -> ShadowMatrices.createOrthoMatrix(directives.getShadowDirectives().getDistance(),
directives.getShadowDirectives().getNearPlane() < 0 ? -DHCompat.getRenderDistance() : directives.getShadowDirectives().getNearPlane(), directives.getShadowDirectives().getNearPlane() < 0 ? -DHCompat.getRenderDistance() : directives.getShadowDirectives().getNearPlane(),
directives.getShadowDirectives().getFarPlane() < 0 ? DHCompat.getRenderDistance() : directives.getShadowDirectives().getFarPlane())); directives.getShadowDirectives().getFarPlane() < 0 ? DHCompat.getRenderDistance() : directives.getShadowDirectives().getFarPlane()));
} }
@@ -14,8 +14,8 @@ public class BuiltinReplacementUniforms {
public static void addBuiltinReplacementUniforms(UniformHolder uniforms) { public static void addBuiltinReplacementUniforms(UniformHolder uniforms) {
uniforms.uniformMatrix(UniformUpdateFrequency.ONCE, "iris_LightmapTextureMatrix", () -> { uniforms.uniformMatrix(UniformUpdateFrequency.ONCE, "iris_LightmapTextureMatrix", () -> {
//Iris.logger.warn("A shader appears to require the lightmap texture matrix even after transformations have occurred"); //IRIS_LOGGER.warn("A shader appears to require the lightmap texture matrix even after transformations have occurred");
//Iris.logger.warn("Iris handles this correctly but it indicates that the shader is doing weird things with lightmap coordinates"); //IRIS_LOGGER.warn("Iris handles this correctly but it indicates that the shader is doing weird things with lightmap coordinates");
return lightmapTextureMatrix; return lightmapTextureMatrix;
}); });
@@ -0,0 +1,12 @@
package org.embeddedt.embeddium.compat.iris;
import net.irisshaders.iris.shaderpack.materialmap.NamespacedId;
import java.util.Map;
public interface IBlockEntry {
Iterable<IBlockEntry> expandEntries();
NamespacedId id();
boolean isTag();
Map<String, String> propertyPredicates();
}
@@ -0,0 +1,4 @@
package org.embeddedt.embeddium.compat.mc;
public interface ICamera {
}
@@ -0,0 +1,4 @@
package org.embeddedt.embeddium.compat.mc;
public interface ILevelRenderer {
}
@@ -1,10 +1,10 @@
package org.embeddedt.embeddium.compat.mc; package org.embeddedt.embeddium.compat.mc;
import org.joml.Matrix4f; import org.joml.Matrix4f;
import org.joml.Vector2i;
import org.joml.Vector3d; import org.joml.Vector3d;
import org.joml.Vector4f; import org.joml.Vector4f;
import java.io.IOException;
import java.util.ServiceLoader; import java.util.ServiceLoader;
/** /**
@@ -12,6 +12,7 @@ import java.util.ServiceLoader;
*/ */
public interface MinecraftVersionShimService { public interface MinecraftVersionShimService {
MinecraftVersionShimService MINECRAFT_SHIM = ServiceLoader.load(MinecraftVersionShimService.class).findFirst().orElseThrow(); MinecraftVersionShimService MINECRAFT_SHIM = ServiceLoader.load(MinecraftVersionShimService.class).findFirst().orElseThrow();
Vector2i ZERO2I = new Vector2i();
Vector3d ZERO3D = new Vector3d(0); Vector3d ZERO3D = new Vector3d(0);
Vector4f ZERO4F = new Vector4f(0); Vector4f ZERO4F = new Vector4f(0);
@@ -38,6 +39,7 @@ public interface MinecraftVersionShimService {
boolean isLevelLoaded(); boolean isLevelLoaded();
int getRenderDistanceInBlocks(); int getRenderDistanceInBlocks();
int getEffectiveRenderDistance();
Vector3d getUnshiftedCameraPosition(); Vector3d getUnshiftedCameraPosition();
float getSkyAngle(); float getSkyAngle();
void applyRotationYP(Matrix4f preCelestial, float degrees); void applyRotationYP(Matrix4f preCelestial, float degrees);
@@ -74,6 +76,25 @@ public interface MinecraftVersionShimService {
boolean isFirstPersonCamera(); boolean isFirstPersonCamera();
boolean isSpectator(); boolean isSpectator();
Vector3d getEyePosition(); Vector3d getEyePosition();
boolean isOnGround();
boolean isHurt();
boolean isInvisible();
boolean isBurning();
boolean isSneaking();
boolean isSprinting();
Vector3d getSkyColor();
float getBlindness();
float getDarknessFactor();
float getPlayerMood();
float getRainStrength();
Vector2i getEyeBrightness();
float getNightVision();
int isEyeInWater();
boolean hideGui();
boolean isRightHanded();
float getScreenBrightness();
Vector2i getAtlasSize();
Vector2i getTextureSize();
MCNativeImage createNativeImage(int width, int height, boolean useCalloc); MCNativeImage createNativeImage(int width, int height, boolean useCalloc);
MCNativeImage[] createNativeImageArray(int size); MCNativeImage[] createNativeImageArray(int size);
@@ -81,7 +102,18 @@ public interface MinecraftVersionShimService {
IResourceLocation makeResourceLocation(String namespace, String path); IResourceLocation makeResourceLocation(String namespace, String path);
IResourceLocation makeResourceLocation(String str); IResourceLocation makeResourceLocation(String str);
// TODO(mitchej123): Does this belong here? String getOsString();
void reloadIris() throws IOException;
boolean irisAllowConcurrentUpdate(); String getMcVersion();
String getBackupVersionNumber();
void markRendererReloadRequired();
boolean isDHPresent();
Matrix4f getShadowModelView(float sunPathRotation, float intervalSize);
Matrix4f getShadowProjection(float shadowDistance, float nearPlane, float farPlane);
void bindFramebuffer();
} }
@@ -0,0 +1,58 @@
package org.taumc.celeritas;
import net.irisshaders.iris.features.FeatureFlags;
import net.irisshaders.iris.pipeline.IrisRenderingPipeline;
import net.irisshaders.iris.pipeline.WorldRenderingPipeline;
import net.irisshaders.iris.shaderpack.materialmap.NamespacedId;
import org.embeddedt.embeddium.compat.iris.IBlockEntry;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.ServiceLoader;
import java.util.function.BiConsumer;
public interface CeleritasShaderVersionService {
CeleritasShaderVersionService INSTANCE = ServiceLoader.load(CeleritasShaderVersionService.class).findFirst().orElseThrow();
/**
* Reload the Iris
* @throws IOException
*/
void reloadIris() throws IOException;
/**
* Checks whether Iris allows concurrent updates to the shader pack.
*
* @return true if Iris allows concurrent updates, false otherwise.
*/
boolean irisAllowConcurrentUpdate();
void handleUnsupportedFeatureFlags(List<FeatureFlags> invalidFlagList, List<String> invalidFeatureFlags);
void processBiomeMap(BiConsumer<String, String> define);
/**
* Parses a block ID entry.
*
* @param entry The string representation of the entry. Must not be empty.
*/
IBlockEntry parseBlockEntry(@NotNull String entry);
IBlockEntry createBlockEntry(NamespacedId id);
void onEarlyInitialize();
void onRenderSystemInit();
void onLoadingComplete();
void destroyEverything();
WorldRenderingPipeline createPipeline(NamespacedId dimensionId);
WorldRenderingPipeline createVanillaRenderingPipeline();
void reload();
Object getDHCompatInstance(IrisRenderingPipeline pipeline, boolean renderDHShadow) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException;
}
@@ -1,7 +1,6 @@
package org.taumc.celeritas.api.v0; package org.taumc.celeritas.api.v0;
import net.irisshaders.iris.api.v0.IrisApiConfig; import net.irisshaders.iris.api.v0.IrisApiConfig;
import java.util.ServiceLoader; import java.util.ServiceLoader;
public interface CeleritasShadersApi { public interface CeleritasShadersApi {
@@ -0,0 +1,16 @@
package org.taumc.celeritas.compat;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
public enum InteractionHand {
MAIN_HAND,
OFF_HAND;
InteractionHand() {
}
public ItemStack getItemInHand(EntityPlayer player){
return player.getHeldItem();
}
}
@@ -12,3 +12,5 @@ private-f net.minecraft.client.renderer.EntityRenderer field_78504_Q # lightmapC
public net.minecraft.world.WorldSettings$GameType public net.minecraft.world.WorldSettings$GameType
public net.minecraft.world.WorldSettings.GameType public net.minecraft.world.WorldSettings.GameType
public net.minecraft.client.multiplayer.PlayerControllerMP currentGameType # currentGameType public net.minecraft.client.multiplayer.PlayerControllerMP currentGameType # currentGameType
public net.minecraft.entity.Entity fire # fire
public net.minecraft.client.renderer.EntityRenderer getNightVisionBrightness(Lnet/minecraft/entity/player/EntityPlayer;F)F # getNightVisionBrightness
@@ -1,53 +0,0 @@
package net.irisshaders.iris;
import net.irisshaders.iris.config.IrisConfig;
import java.io.IOException;
import java.nio.file.Files;
import static org.embeddedt.embeddium.compat.mc.PlatformUtilService.PLATFORM_UTIL;
public class Iris {
public static final IrisLogging logger = IrisLogging.IRIS_LOGGER;
private static boolean initialized;
private static IrisConfig irisConfig;
/**
* Called very early on in Minecraft initialization. At this point we *cannot* safely access OpenGL, but we can do
* some very basic setup, config loading, and environment checks.
*
* <p>This is roughly equivalent to Fabric Loader's ClientModInitializer#onInitializeClient entrypoint, except
* it's entirely cross platform & we get to decide its exact semantics.</p>
*
* <p>This is called right before options are loaded, so we can add key bindings here.</p>
*/
public static void onEarlyInitialize() {
// reloadKeybind = new KeyMapping("iris.keybind.reload", InputConstants.Type.KEYSYM, GLFW.GLFW_KEY_R, "iris.keybinds");
// toggleShadersKeybind = new KeyMapping("iris.keybind.toggleShaders", InputConstants.Type.KEYSYM, GLFW.GLFW_KEY_K, "iris.keybinds");
// shaderpackScreenKeybind = new KeyMapping("iris.keybind.shaderPackSelection", InputConstants.Type.KEYSYM, GLFW.GLFW_KEY_O, "iris.keybinds");
// wireframeKeybind = new KeyMapping("iris.keybind.wireframe", InputConstants.Type.KEYSYM, InputConstants.UNKNOWN.getValue(), "iris.keybinds");
// DHCompat.run();
try {
if (!Files.exists(IrisCommon.getShaderpacksDirectory())) {
Files.createDirectories(IrisCommon.getShaderpacksDirectory());
}
} catch (IOException e) {
logger.warn("Failed to create the shaderpacks directory!");
logger.warn("", e);
}
irisConfig = new IrisConfig(PLATFORM_UTIL.getConfigDir().resolve(IrisConstants.MODID + "-shaders.properties"));
try {
irisConfig.initialize();
} catch (IOException e) {
logger.error("Failed to initialize Iris configuration, default values will be used instead");
logger.error("", e);
}
initialized = true;
}
}
@@ -0,0 +1,189 @@
package net.irisshaders.iris;
import net.irisshaders.iris.features.FeatureFlags;
import net.irisshaders.iris.pipeline.IrisRenderingPipeline;
import net.irisshaders.iris.pipeline.WorldRenderingPipeline;
import net.irisshaders.iris.shaderpack.materialmap.BlockEntry;
import net.irisshaders.iris.shaderpack.materialmap.NamespacedId;
import org.apache.commons.lang3.StringUtils;
import org.embeddedt.embeddium.compat.iris.IBlockEntry;
import org.jetbrains.annotations.NotNull;
import org.taumc.celeritas.CeleritasShaderVersionService;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import static net.irisshaders.iris.IrisLogging.IRIS_LOGGER;
public class IrisArchaic implements CeleritasShaderVersionService {
@Override
public void reloadIris() throws IOException {
}
@Override
public boolean irisAllowConcurrentUpdate() {
return false;
}
@Override
public void handleUnsupportedFeatureFlags(List<FeatureFlags> invalidFlagList, List<String> invalidFeatureFlags) {
// TODO: Implement this method to handle unsupported feature flags on 1.7.10
/*
if (Minecraft.getInstance().screen instanceof ShaderPackScreen) {
MutableComponent component = Component.translatable("iris.unsupported.pack.description", FeatureFlags.getInvalidStatus(invalidFlagList), invalidFeatureFlags.stream()
.collect(Collectors.joining(", ", ": ", ".")));
if (SystemUtils.IS_OS_MAC) {
component = component.append(Component.translatable("iris.unsupported.pack.macos"));
}
Minecraft.getInstance().setScreen(new FeatureMissingErrorScreen(Minecraft.getInstance().screen, Component.translatable("iris.unsupported.pack"), component));
}
*/
}
@Override
public void processBiomeMap(BiConsumer<String, String> define) {
}
@Override
public IBlockEntry parseBlockEntry(@NotNull String entry) {
if (entry.isEmpty()) {
throw new IllegalArgumentException("Called BlockEntry::parse with an empty string");
}
// We can assume that this array is of at least array length because the input string is non-empty.
final String[] splitStates = entry.split(":");
// Trivial case: no states, no namespace
if (splitStates.length == 1) {
return new BlockEntry(new NamespacedId("minecraft", entry), Collections.emptySet());
}
// Examples of what we'll accept
// stone
// stone:0
// minecraft:stone:0
// minecraft:stone:0,1,2 # Theoretically valid, but I haven't seen any examples in actual shaders
// Examples of what we don't (Yet?) accept - Seems to be from MC 1.8+
// minecraft:farmland:moisture=0
// minecraft:farmland:moisture=1
// minecraft:double_plant:half=lower
// minecraft:double_plant:half=upper
// minecraft:grass:snowy=true
// minecraft:unpowered_comparator:powered=false
// Less trivial case: no metas involved, just a namespace
//
// The first term MUST be a valid ResourceLocation component
// The second term, if it is not numeric, must be a valid ResourceLocation component.
if (splitStates.length == 2 && !StringUtils.isNumeric(splitStates[1].substring(0, 1))) {
return new BlockEntry(new NamespacedId(splitStates[0], splitStates[1]), Collections.emptySet());
}
// Complex case: One or more states involved...
final int statesStart;
final NamespacedId id;
if (StringUtils.isNumeric(splitStates[1].substring(0, 1))) {
// We have an entry of the form "stone:0"
statesStart = 1;
id = new NamespacedId("minecraft", splitStates[0]);
} else {
// We have an entry of the form "minecraft:stone:0"
statesStart = 2;
id = new NamespacedId(splitStates[0], splitStates[1]);
}
final Set<Integer> metas = new HashSet<>();
for (int index = statesStart; index < splitStates.length; index++) {
// Parse out one or more metadata ids
final String[] metaParts = splitStates[index].split(", ");
for (String metaPart : metaParts) {
try {
metas.add(Integer.parseInt(metaPart));
} catch (NumberFormatException e) {
IRIS_LOGGER.warn("Warning: the block ID map entry \"" + entry + "\" could not be fully parsed:");
IRIS_LOGGER.warn("- Metadata ids must be a comma separated list of one or more integers, but "+ splitStates[index] + " is not of that form!");
}
}
}
return new BlockEntry(id, metas);
}
@Override
public IBlockEntry createBlockEntry(NamespacedId id) {
return new BlockEntry(id, Set.of());
}
@Override
public void onEarlyInitialize() {
// reloadKeybind = new KeyMapping("iris.keybind.reload", InputConstants.Type.KEYSYM, GLFW.GLFW_KEY_R, "iris.keybinds");
// toggleShadersKeybind = new KeyMapping("iris.keybind.toggleShaders", InputConstants.Type.KEYSYM, GLFW.GLFW_KEY_K, "iris.keybinds");
// shaderpackScreenKeybind = new KeyMapping("iris.keybind.shaderPackSelection", InputConstants.Type.KEYSYM, GLFW.GLFW_KEY_O, "iris.keybinds");
// wireframeKeybind = new KeyMapping("iris.keybind.wireframe", InputConstants.Type.KEYSYM, InputConstants.UNKNOWN.getValue(), "iris.keybinds");
// DHCompat.run();
}
@Override
public void onRenderSystemInit() {
}
@Override
public void onLoadingComplete() {
}
@Override
public void destroyEverything() {
IrisCommon.getPipelineManager().destroyPipeline();
}
@Override
public WorldRenderingPipeline createPipeline(NamespacedId dimensionId) {
if (IrisCommon.getCurrentPack().isEmpty()) {
// Completely disables shader-based rendering
return createVanillaRenderingPipeline();
}
IRIS_LOGGER.error("Not Implemented");
// TODO: This should be reverted if a dimension change causes shaders to compile again
IrisCommon.setFallback(true);
return createVanillaRenderingPipeline();
}
@Override
public WorldRenderingPipeline createVanillaRenderingPipeline() {
// TODO
return null;
}
@Override
public void reload() {
}
@Override
public Object getDHCompatInstance(IrisRenderingPipeline pipeline, boolean renderDHShadow)
throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
// TODO
return null;
}
}
@@ -0,0 +1,23 @@
package net.irisshaders.iris.api.v0.item;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import org.joml.Vector3f;
public interface IrisItemLightProvider {
Vector3f DEFAULT_LIGHT_COLOR = new Vector3f(1, 1, 1);
default int getLightEmission(EntityPlayer player, ItemStack stack) {
if (stack.getItem() instanceof ItemBlock item) {
return item.blockInstance.getLightValue();
}
return 0;
}
default Vector3f getLightColor(EntityPlayer player, ItemStack stack) {
return DEFAULT_LIGHT_COLOR;
}
}
@@ -3,7 +3,7 @@ package net.irisshaders.iris.apiimpl;
import net.irisshaders.iris.api.v0.IrisApiConfig; import net.irisshaders.iris.api.v0.IrisApiConfig;
import org.taumc.celeritas.api.v0.CeleritasShadersApi; import org.taumc.celeritas.api.v0.CeleritasShadersApi;
public class IrisApiV0Impl implements CeleritasShadersApi { public class IrisApiV0ImplArchaic implements CeleritasShadersApi {
@Override @Override
public boolean isShaderPackInUse() { public boolean isShaderPackInUse() {
return false; return false;
@@ -48,4 +48,6 @@ public class IrisApiV0Impl implements CeleritasShadersApi {
public float getSunPathRotation() { public float getSunPathRotation() {
return 0; return 0;
} }
} }
@@ -0,0 +1,26 @@
package net.irisshaders.iris.shaderpack.materialmap;
import org.embeddedt.embeddium.compat.iris.IBlockEntry;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
public record BlockEntry(NamespacedId id, Set<Integer> ids) implements IBlockEntry {
@Override
public Iterable<IBlockEntry> expandEntries() {
return Collections.singletonList(this);
}
@Override
public boolean isTag() {
return false;
}
@Override
public Map<String, String> propertyPredicates() {
return Map.of();
}
}
@@ -0,0 +1,56 @@
package net.irisshaders.iris.uniforms;
import net.irisshaders.iris.gl.uniform.FloatSupplier;
import net.irisshaders.iris.gl.uniform.UniformHolder;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import java.util.function.IntSupplier;
import java.util.function.ToIntFunction;
public class ArchaicBiomeUniforms implements BiomeUniforms {
@Override
public void addBiomeUniforms(UniformHolder uniforms) {
// All based on player's location
// "biome", int, BiomeID
// "biome_category", int, BiomeCategory - BiomeDictionary.Type should be usable
// "biome_precipitation", int, Current Precipitation -- seems enableSnow helps with this
// "rainfall", float, rainfall
// "temperature", float, temperature
}
static IntSupplier playerI(ToIntFunction<EntityPlayer> function) {
return () -> {
EntityPlayer player = Minecraft.getMinecraft().thePlayer;
if (player == null) {
return 0; // TODO: I'm not sure what I'm supposed to do here?
} else {
return function.applyAsInt(player);
}
};
}
static FloatSupplier playerF(ToFloatFunction<EntityPlayer> function) {
return () -> {
EntityPlayer player = Minecraft.getMinecraft().thePlayer;
if (player == null) {
return 0.0f; // TODO: I'm not sure what I'm supposed to do here?
} else {
return function.applyAsFloat(player);
}
};
}
@FunctionalInterface
public interface ToFloatFunction<T> {
/**
* Applies this function to the given argument.
*
* @param value the function argument
* @return the function result
*/
float applyAsFloat(T value);
}
}
@@ -0,0 +1,130 @@
package net.irisshaders.iris.uniforms;
import it.unimi.dsi.fastutil.objects.Object2IntFunction;
import net.irisshaders.iris.api.v0.item.IrisItemLightProvider;
import net.irisshaders.iris.gl.uniform.UniformHolder;
import net.irisshaders.iris.shaderpack.IdMap;
import net.irisshaders.iris.shaderpack.materialmap.NamespacedId;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import org.jetbrains.annotations.NotNull;
import org.joml.Vector3f;
import org.taumc.celeritas.compat.InteractionHand;
import static net.irisshaders.iris.gl.uniform.UniformUpdateFrequency.PER_FRAME;
public class ArchaicIdMapUniforms implements IdMapUniforms {
public void addIdMapUniforms(FrameUpdateNotifier notifier, UniformHolder uniforms, IdMap idMap, boolean isOldHandLight) {
HeldItemSupplier mainHandSupplier = new HeldItemSupplier(InteractionHand.MAIN_HAND, idMap.getItemIdMap(), isOldHandLight);
HeldItemSupplier offHandSupplier = new HeldItemSupplier(InteractionHand.OFF_HAND, idMap.getItemIdMap(), false);
notifier.addListener(mainHandSupplier::update);
notifier.addListener(offHandSupplier::update);
uniforms
.uniform1i(PER_FRAME, "heldItemId", mainHandSupplier::getIntID)
.uniform1i(PER_FRAME, "heldItemId2", offHandSupplier::getIntID)
.uniform1i(PER_FRAME, "heldBlockLightValue", mainHandSupplier::getLightValue)
.uniform1i(PER_FRAME, "heldBlockLightValue2", offHandSupplier::getLightValue)
.uniform3f(PER_FRAME, "heldBlockLightColor", mainHandSupplier::getLightColor)
.uniform3f(PER_FRAME, "heldBlockLightColor2", offHandSupplier::getLightColor);
}
/**
* Provides the currently held item, and it's light value, in the given hand as a uniform. Uses the item.properties ID map to map the item
* to an integer, and the old hand light value to map offhand to main hand.
*/
private static class HeldItemSupplier {
private final InteractionHand hand;
private final Object2IntFunction<NamespacedId> itemIdMap;
private final boolean applyOldHandLight;
private int intID;
private int lightValue;
private Vector3f lightColor;
HeldItemSupplier(InteractionHand hand, Object2IntFunction<NamespacedId> itemIdMap, boolean shouldApplyOldHandLight) {
this.hand = hand;
this.itemIdMap = itemIdMap;
this.applyOldHandLight = shouldApplyOldHandLight && hand == InteractionHand.MAIN_HAND;
}
private void invalidate() {
intID = -1;
lightValue = 0;
lightColor = IrisItemLightProvider.DEFAULT_LIGHT_COLOR;
}
public void update() {
EntityPlayer player = Minecraft.getMinecraft().thePlayer;
if (player == null) {
// Not valid when the player doesn't exist
invalidate();
return;
}
ItemStack heldStack = hand.getItemInHand(player);
if (heldStack == null) {
invalidate();
return;
}
Item heldItem = heldStack.getItem();
if (heldItem == null) {
invalidate();
return;
}
ResourceLocation heldItemId = new ResourceLocation(Item.itemRegistry.getNameForObject(heldItem));
intID = itemIdMap.applyAsInt(new NamespacedId(heldItemId.getResourceDomain(), heldItemId.getResourcePath()));
IrisItemLightProvider lightProvider = (IrisItemLightProvider) heldItem;
lightValue = lightProvider.getLightEmission(Minecraft.getMinecraft().thePlayer, heldStack);
if (applyOldHandLight) {
lightProvider = applyOldHandLighting(player, lightProvider);
}
}
private IrisItemLightProvider applyOldHandLighting(@NotNull EntityPlayer player, IrisItemLightProvider existing) {
ItemStack offHandStack = InteractionHand.OFF_HAND.getItemInHand(player);
if (offHandStack == null) {
return existing;
}
Item offHandItem = offHandStack.getItem();
if (offHandItem == null) {
return existing;
}
IrisItemLightProvider lightProvider = (IrisItemLightProvider) offHandItem;
int newEmission = lightProvider.getLightEmission(Minecraft.getMinecraft().thePlayer, offHandStack);
if (lightValue < newEmission) {
lightValue = newEmission;
return lightProvider;
}
return existing;
}
public int getIntID() {
return intID;
}
public int getLightValue() {
return lightValue;
}
public Vector3f getLightColor() {
return lightColor;
}
}
}
@@ -6,25 +6,30 @@ import net.irisshaders.iris.uniforms.CapturedRenderingState;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.client.resources.I18n; import net.minecraft.client.resources.I18n;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.launchwrapper.Launch; import net.minecraft.launchwrapper.Launch;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.ResourceLocation; import net.minecraft.util.ResourceLocation;
import net.minecraft.util.Vec3;
import net.minecraft.world.WorldProviderEnd; import net.minecraft.world.WorldProviderEnd;
import net.minecraft.world.WorldProviderHell; import net.minecraft.world.WorldProviderHell;
import org.embeddedt.embeddium.compat.mc.IResourceLocation; import org.embeddedt.embeddium.compat.mc.IResourceLocation;
import org.embeddedt.embeddium.compat.mc.MCNativeImage; import org.embeddedt.embeddium.compat.mc.MCNativeImage;
import org.embeddedt.embeddium.compat.mc.MinecraftVersionShimService; import org.embeddedt.embeddium.compat.mc.MinecraftVersionShimService;
import org.embeddedt.embeddium.compat.mc.PlatformUtilService; import org.embeddedt.embeddium.compat.mc.PlatformUtilService;
import org.joml.*;
import org.joml.Math; import org.joml.Math;
import org.joml.Matrix4f; import org.lwjgl.system.Platform;
import org.joml.Vector3d;
import org.joml.Vector4f;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Path; import java.nio.file.Path;
public class MinecraftArchaicVersionShimImpl implements MinecraftVersionShimService, PlatformUtilService { public class MinecraftArchaicVersionShimImpl implements MinecraftVersionShimService, PlatformUtilService {
private static final Minecraft client = Minecraft.getMinecraft();
private static final boolean isDevelopmentEnvironment = (boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment"); private static final boolean isDevelopmentEnvironment = (boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment");
@@ -62,6 +67,11 @@ public class MinecraftArchaicVersionShimImpl implements MinecraftVersionShimServ
return Minecraft.getMinecraft().gameSettings.renderDistanceChunks * 16; return Minecraft.getMinecraft().gameSettings.renderDistanceChunks * 16;
} }
@Override
public int getEffectiveRenderDistance() {
return Minecraft.getMinecraft().gameSettings.renderDistanceChunks;
}
@Override @Override
public Vector3d getUnshiftedCameraPosition() { public Vector3d getUnshiftedCameraPosition() {
// TODO: Needs to be captured in 1.7.10 via mixins // TODO: Needs to be captured in 1.7.10 via mixins
@@ -267,6 +277,149 @@ public class MinecraftArchaicVersionShimImpl implements MinecraftVersionShimServ
return eyePosition.set(eye.posX, eye.posY, eye.posZ); return eyePosition.set(eye.posX, eye.posY, eye.posZ);
} }
@Override
public boolean isOnGround() {
return client.thePlayer != null && client.thePlayer.onGround;
}
@Override
public boolean isHurt() {
// Do not use isHurt, that's not what we want!
return (client.thePlayer != null && client.thePlayer.hurtTime > 0);
}
@Override
public boolean isInvisible() {
return (client.thePlayer != null && client.thePlayer.isInvisible());
}
@Override
public boolean isBurning() {
return client.thePlayer != null && client.thePlayer.fire > 0 && !client.thePlayer.isImmuneToFire();
}
@Override
public boolean isSneaking() {
return (client.thePlayer != null && client.thePlayer.isSneaking());
}
@Override
public boolean isSprinting() {
return (client.thePlayer != null && client.thePlayer.isSprinting());
}
@Override
public Vector3d getSkyColor() {
if (client.theWorld == null || client.renderViewEntity == null) {
return ZERO3D;
}
final Vec3 skyColor = client.theWorld.getSkyColor(client.renderViewEntity, CapturedRenderingState.INSTANCE.getTickDelta());
return new Vector3d(skyColor.xCoord, skyColor.yCoord, skyColor.zCoord);
}
@Override
public float getBlindness() {
final EntityLivingBase cameraEntity = client.renderViewEntity;
if (cameraEntity instanceof EntityLiving livingEntity && livingEntity.isPotionActive(Potion.blindness)) {
final PotionEffect blindness = livingEntity.getActivePotionEffect(Potion.blindness);
if (blindness != null) {
// Guessing that this is what OF uses, based on how vanilla calculates the fog value in BackgroundRenderer
// TODO: Add this to ShaderDoc
return Math.clamp(0.0F, 1.0F, blindness.getDuration() / 20.0F);
}
}
return 0.0F;
}
@Override
public float getDarknessFactor() {
// TODO: What should this be?
return 0.0F;
}
@Override
public float getPlayerMood() {
// TODO: What should this be?
return 0.0F;
}
@Override
public float getRainStrength() {
if (client.theWorld == null) {
return 0f;
}
// Note: Ensure this is in the range of 0 to 1 - some custom servers send out of range values.
return Math.clamp(0.0F, 1.0F, client.theWorld.getRainStrength(CapturedRenderingState.INSTANCE.getTickDelta()));
}
@Override
public Vector2i getEyeBrightness() {
if (client.renderViewEntity == null || client.theWorld == null) {
return ZERO2I;
}
// This is what ShadersMod did in 1.7.10
final int eyeBrightness = client.renderViewEntity.getBrightnessForRender(CapturedRenderingState.INSTANCE.getTickDelta());
return new Vector2i((eyeBrightness & 0xffff), (eyeBrightness >> 16));
}
@Override
public float getNightVision() {
Entity cameraEntity = client.renderViewEntity;
if (cameraEntity instanceof EntityPlayer entityPlayer) {
if (!entityPlayer.isPotionActive(Potion.nightVision)) {
return 0.0F;
}
float nightVisionStrength = client.entityRenderer.getNightVisionBrightness(entityPlayer, CapturedRenderingState.INSTANCE.getTickDelta());
try {
if (nightVisionStrength > 0) {
// Just protecting against potential weird mod behavior
return Math.clamp(0.0F, 1.0F, nightVisionStrength);
}
} catch (NullPointerException e) {
return 0.0F;
}
}
return 0.0F;
}
@Override
public int isEyeInWater() {
return 0;
}
@Override
public boolean hideGui() {
return false;
}
@Override
public boolean isRightHanded() {
return false;
}
@Override
public float getScreenBrightness() {
return 0;
}
@Override
public Vector2i getAtlasSize() {
return null;
}
@Override
public Vector2i getTextureSize() {
return null;
}
@Override @Override
public MCNativeImage createNativeImage(int width, int height, boolean useCalloc) { public MCNativeImage createNativeImage(int width, int height, boolean useCalloc) {
// TODO // TODO
@@ -290,16 +443,50 @@ public class MinecraftArchaicVersionShimImpl implements MinecraftVersionShimServ
} }
@Override @Override
public void reloadIris() throws IOException { public String getOsString() {
return switch (Platform.get()) {
case Platform.MACOSX -> "MC_OS_MAC";
case Platform.LINUX -> "MC_OS_LINUX";
case Platform.WINDOWS -> "MC_OS_WINDOWS";
};
}
@Override
public String getMcVersion() {
return Loader.MC_VERSION;
}
@Override
public String getBackupVersionNumber() {
return "1.7.10";
}
@Override
public void markRendererReloadRequired() {
// TODO // TODO
} }
@Override @Override
public boolean irisAllowConcurrentUpdate() { public boolean isDHPresent() {
// TODO
return false; return false;
} }
@Override
public Matrix4f getShadowModelView(float sunPathRotation, float intervalSize) {
// TODO
return null;
}
@Override
public Matrix4f getShadowProjection(float shadowDistance, float nearPlane, float farPlane) {
return null;
}
@Override
public void bindFramebuffer() {
Minecraft.getMinecraft().getFramebuffer().bindFramebuffer(true);
}
@Override @Override
public boolean isLoadValid() { public boolean isLoadValid() {
return true; return true;
@@ -1,6 +1,6 @@
package org.taumc.celeritas.mixin.shaders; package org.taumc.celeritas.mixin.shaders.startup;
import net.irisshaders.iris.Iris; import net.irisshaders.iris.IrisCommon;
import net.minecraft.client.settings.GameSettings; import net.minecraft.client.settings.GameSettings;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.Unique;
@@ -20,7 +20,7 @@ public class MixinGameSettings {
} }
iris$initialized = true; iris$initialized = true;
Iris.onEarlyInitialize(); IrisCommon.onEarlyInitialize();
} }
} }
@@ -0,0 +1,16 @@
package org.taumc.celeritas.mixin.shaders.startup;
import net.irisshaders.iris.IrisCommon;
import net.minecraft.client.renderer.OpenGlHelper;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(OpenGlHelper.class)
public class MixinInitRenderer {
@Inject(method = "initializeTextures", at = @At("RETURN"))
private static void angelica$initializeRenderer(CallbackInfo ci) {
IrisCommon.onRenderSystemInit();
}
}
@@ -0,0 +1 @@
net.irisshaders.iris.uniforms.ArchaicBiomeUniforms
@@ -0,0 +1 @@
net.irisshaders.iris.uniforms.ArchaicIdMapUniforms
@@ -0,0 +1 @@
net.irisshaders.iris.IrisArchaic
@@ -1 +1 @@
net.irisshaders.iris.apiimpl.IrisApiV0Impl net.irisshaders.iris.apiimpl.IrisApiV0ImplArchaic
@@ -25,7 +25,7 @@ public abstract class MixinDebugScreenOverlay {
DrawCallTrackingRenderBuffers drawTracker = (DrawCallTrackingRenderBuffers) Minecraft.getInstance().renderBuffers(); DrawCallTrackingRenderBuffers drawTracker = (DrawCallTrackingRenderBuffers) Minecraft.getInstance().renderBuffers();
// blank line separator // blank line separator
if (true) { // TODO Iris.getIrisConfig().areDebugOptionsEnabled()) { if (true) { // TODO IrisCommon.getIrisConfig().areDebugOptionsEnabled()) {
messages.add(""); messages.add("");
messages.add("[Entity Batching] " + BatchingDebugMessageHelper.getDebugMessage(drawTracker)); messages.add("[Entity Batching] " + BatchingDebugMessageHelper.getDebugMessage(drawTracker));
} }
@@ -0,0 +1,68 @@
package net.irisshaders.iris.shaderpack.materialmap;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.world.level.block.Block;
import org.jetbrains.annotations.Nullable;
import java.util.Map;
import java.util.Objects;
public class ModernWorldRenderingSettings {
public static final ModernWorldRenderingSettings INSTANCE = new ModernWorldRenderingSettings();
private Object2IntMap<BlockState> blockStateIds;
private FallbackTextureMaterials fallbackTextureMaterialMapping;
private Map<Block, RenderType> blockTypeIds;
public ModernWorldRenderingSettings() {
this.blockStateIds = null;
this.fallbackTextureMaterialMapping = null;
this.blockTypeIds = null;
}
@Nullable
public Object2IntMap<BlockState> getBlockStateIds() {
return blockStateIds;
}
public void setBlockStateIds(Object2IntMap<BlockState> blockStateIds) {
if (Objects.equals(this.blockStateIds, blockStateIds)) {
return;
}
WorldRenderingSettings.INSTANCE.setReloadRequired();
this.blockStateIds = blockStateIds;
}
@Nullable
public FallbackTextureMaterials getFallbackTextureMaterialMapping() {
return fallbackTextureMaterialMapping;
}
public void setFallbackTextureMaterialMapping(FallbackTextureMaterials fallbackTextureMaterialMapping) {
if (Objects.equals(this.fallbackTextureMaterialMapping, fallbackTextureMaterialMapping)) {
return;
}
WorldRenderingSettings.INSTANCE.setReloadRequired();
this.fallbackTextureMaterialMapping = fallbackTextureMaterialMapping;
}
@Nullable
public Map<Block, RenderType> getBlockTypeIds() {
return blockTypeIds;
}
public void setBlockTypeIds(Map<Block, RenderType> blockTypeIds) {
if (Objects.equals(this.blockTypeIds, blockTypeIds)) {
return;
}
WorldRenderingSettings.INSTANCE.setReloadRequired();
this.blockTypeIds = blockTypeIds;
}
}
@@ -115,10 +115,10 @@ public class Celeritas /*? if fabric {*/ /*implements ClientModInitializer *//*?
// TODO remove // TODO remove
//? if shaders { //? if shaders {
modEventBus.addListener((RegisterKeyMappingsEvent ev) -> { modEventBus.addListener((RegisterKeyMappingsEvent ev) -> {
ev.register(net.irisshaders.iris.Iris.reloadKeybind); ev.register(net.irisshaders.iris.IrisModern.reloadKeybind);
ev.register(net.irisshaders.iris.Iris.shaderpackScreenKeybind); ev.register(net.irisshaders.iris.IrisModern.shaderpackScreenKeybind);
ev.register(net.irisshaders.iris.Iris.toggleShadersKeybind); ev.register(net.irisshaders.iris.IrisModern.toggleShadersKeybind);
ev.register(net.irisshaders.iris.Iris.wireframeKeybind); ev.register(net.irisshaders.iris.IrisModern.wireframeKeybind);
}); });
//?} //?}
} }
@@ -1,6 +1,7 @@
package org.embeddedt.embeddium.impl.modern.render.chunk.compile.pipeline; package org.embeddedt.embeddium.impl.modern.render.chunk.compile.pipeline;
import lombok.Getter; import lombok.Getter;
import net.irisshaders.iris.shaderpack.materialmap.ModernWorldRenderingSettings;
import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.FluidState; import net.minecraft.world.level.material.FluidState;
@@ -50,7 +51,7 @@ public class BlockRenderCache {
var colorRegistry = new ColorProviderRegistry(client.getBlockColors()); var colorRegistry = new ColorProviderRegistry(client.getBlockColors());
this.blockRenderer = new BlockRenderer(colorRegistry, lightPipelineProvider, WorldRenderingSettings.INSTANCE.getBlockTypeIds()); this.blockRenderer = new BlockRenderer(colorRegistry, lightPipelineProvider, ModernWorldRenderingSettings.INSTANCE.getBlockTypeIds());
this.fluidRenderer = new FluidRenderer(colorRegistry, lightPipelineProvider); this.fluidRenderer = new FluidRenderer(colorRegistry, lightPipelineProvider);
this.lightPipelineProvider = lightPipelineProvider; this.lightPipelineProvider = lightPipelineProvider;
this.specialBlockRenderer = new SpecialBlockRenderer(); this.specialBlockRenderer = new SpecialBlockRenderer();
@@ -2,148 +2,79 @@ package net.irisshaders.iris;
import com.google.common.base.Throwables; import com.google.common.base.Throwables;
import com.mojang.blaze3d.platform.GlDebug; import com.mojang.blaze3d.platform.GlDebug;
import com.mojang.blaze3d.platform.InputConstants;
//? if fabric //? if fabric
/*import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper;*/ /*import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper;*/
import net.irisshaders.iris.compat.dh.DHCompat; import net.irisshaders.iris.compat.dh.DHCompat;
import net.irisshaders.iris.compat.sodium.impl.options.IrisSodiumOptions; import net.irisshaders.iris.compat.sodium.impl.options.IrisSodiumOptions;
import net.irisshaders.iris.config.IrisConfig;
import net.irisshaders.iris.gl.shader.ShaderCompileException;
import net.irisshaders.iris.gl.shader.StandardMacros;
import net.irisshaders.iris.gui.debug.DebugLoadFailedGridScreen;
import net.irisshaders.iris.gui.screen.ShaderPackScreen; import net.irisshaders.iris.gui.screen.ShaderPackScreen;
import net.irisshaders.iris.helpers.OptionalBoolean; import net.irisshaders.iris.pipeline.ModernIrisRenderingPipeline;
import net.irisshaders.iris.pipeline.IrisRenderingPipeline;
import net.irisshaders.iris.pipeline.PipelineManager; import net.irisshaders.iris.pipeline.PipelineManager;
import net.irisshaders.iris.pipeline.VanillaRenderingPipeline;
import net.irisshaders.iris.pipeline.WorldRenderingPipeline;
import net.irisshaders.iris.shaderpack.DimensionId; import net.irisshaders.iris.shaderpack.DimensionId;
import net.irisshaders.iris.shaderpack.ShaderPack;
import net.irisshaders.iris.shaderpack.discovery.ShaderpackDirectoryManager; import net.irisshaders.iris.shaderpack.discovery.ShaderpackDirectoryManager;
import net.irisshaders.iris.shaderpack.materialmap.NamespacedId; import net.irisshaders.iris.shaderpack.materialmap.NamespacedId;
import net.irisshaders.iris.shaderpack.option.OptionSet;
import net.irisshaders.iris.shaderpack.option.Profile;
import net.irisshaders.iris.shaderpack.option.values.MutableOptionValues;
import net.irisshaders.iris.shaderpack.option.values.OptionValues;
import net.irisshaders.iris.shaderpack.programs.ProgramSet;
import net.irisshaders.iris.texture.pbr.PBRTextureManager; import net.irisshaders.iris.texture.pbr.PBRTextureManager;
import net.minecraft.ChatFormatting; import net.minecraft.ChatFormatting;
import net.minecraft.SharedConstants; import net.minecraft.SharedConstants;
import net.minecraft.client.KeyMapping;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.network.chat.ClickEvent;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import org.embeddedt.embeddium.impl.Celeritas; import org.embeddedt.embeddium.impl.Celeritas;
import org.embeddedt.embeddium.impl.gl.debug.GLDebug; import org.embeddedt.embeddium.impl.gl.debug.GLDebug;
import org.embeddedt.embeddium.impl.loader.common.EarlyLoaderServices; import org.embeddedt.embeddium.impl.loader.common.EarlyLoaderServices;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.lwjgl.glfw.GLFW;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.FileSystem;
import java.nio.file.FileSystemNotFoundException;
import java.nio.file.FileSystems;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.Properties; import java.util.Properties;
import java.util.stream.Stream;
import java.util.zip.ZipError;
import java.util.zip.ZipException;
import static net.irisshaders.iris.IrisLogging.IRIS_LOGGER;
import static org.embeddedt.embeddium.compat.mc.PlatformUtilService.PLATFORM_UTIL; import static org.embeddedt.embeddium.compat.mc.PlatformUtilService.PLATFORM_UTIL;
public class Iris { public class Iris {
public static final IrisLogging logger = IrisLogging.IRIS_LOGGER; public static final IrisLogging logger = IRIS_LOGGER;
private static final Map<String, String> shaderPackOptionQueue = new HashMap<>();
// Change this for snapshots! // Change this for snapshots!
private static final String backupVersionNumber = "1.20.3"; private static final String backupVersionNumber = "1.20.3";
public static NamespacedId lastDimension = null;
public static boolean testing = false; public static boolean testing = false;
private static ShaderpackDirectoryManager shaderpacksDirectoryManager; private static ShaderpackDirectoryManager shaderpacksDirectoryManager;
private static ShaderPack currentPack;
private static String currentPackName;
private static Optional<Exception> storedError = Optional.empty();
private static boolean initialized;
private static PipelineManager pipelineManager;
private static IrisConfig irisConfig;
private static FileSystem zipFileSystem;
public static KeyMapping reloadKeybind;
public static KeyMapping toggleShadersKeybind;
public static KeyMapping shaderpackScreenKeybind;
public static KeyMapping wireframeKeybind;
// Flag variable used when reloading
// Used in favor of queueDefaultShaderPackOptionValues() for resetting as the
// behavior is more concrete and therefore is more likely to repair a user's issues
private static boolean resetShaderPackOptions = false;
private static boolean fallback;
private static boolean loadPackWhenPossible = false;
private static boolean renderSystemInit = false;
public static void loadShaderpackWhenPossible() {
loadPackWhenPossible = true;
}
public static boolean isPackInUseQuick() { public static boolean isPackInUseQuick() {
return pipelineManager.getPipelineNullable() instanceof IrisRenderingPipeline; return IrisCommon.getPipelineManager().getPipelineNullable() instanceof ModernIrisRenderingPipeline;
} }
/** /**
* Called once RenderSystem#initRenderer has completed. This means that we can safely access OpenGL. * Called once RenderSystem#initRenderer has completed. This means that we can safely access OpenGL.
*/ */
public static void onRenderSystemInit() { public static void onRenderSystemInit() {
if (!initialized) {
Iris.logger.warn("Iris::onRenderSystemInit was called, but Iris::onEarlyInitialize was not called." +
" Trying to avoid a crash but this is an odd state.");
return;
}
PBRTextureManager.INSTANCE.init(); PBRTextureManager.INSTANCE.init();
renderSystemInit = true;
// Only load the shader pack when we can access OpenGL // Only load the shader pack when we can access OpenGL
if (!EarlyLoaderServices.INSTANCE.isModLoaded("distanthorizons")) { if (!EarlyLoaderServices.INSTANCE.isModLoaded("distanthorizons")) {
loadShaderpack(); IrisCommon.loadShaderpack();
} }
} }
public static void duringRenderSystemInit() { public static void duringRenderSystemInit() {
setDebug(irisConfig.areDebugOptionsEnabled()); setDebug(IrisCommon.getIrisConfig().areDebugOptionsEnabled());
} }
/** /**
* Called when the title screen is initialized for the first time. * Called when the title screen is initialized for the first time.
*/ */
public static void onLoadingComplete() { public static void onLoadingComplete() {
if (!initialized) {
Iris.logger.warn("Iris::onLoadingComplete was called, but Iris::onEarlyInitialize was not called." +
" Trying to avoid a crash but this is an odd state.");
return;
}
// Initialize the pipeline now so that we don't increase world loading time. Just going to guess that
// the player is in the overworld.
// See: https://github.com/IrisShaders/Iris/issues/323
lastDimension = DimensionId.OVERWORLD;
Iris.getPipelineManager().preparePipeline(DimensionId.OVERWORLD); Iris.getPipelineManager().preparePipeline(DimensionId.OVERWORLD);
IrisSodiumOptions.init(); IrisSodiumOptions.init();
} }
public static void handleKeybinds(Minecraft minecraft) { public static void handleKeybinds(Minecraft minecraft) {
if (reloadKeybind.consumeClick()) { if (IrisModern.reloadKeybind.consumeClick()) {
try { try {
reload(); reload();
@@ -158,218 +89,47 @@ public class Iris {
minecraft.player.displayClientMessage(Component.translatable("iris.shaders.reloaded.failure", Throwables.getRootCause(e).getMessage()).withStyle(ChatFormatting.RED), false); minecraft.player.displayClientMessage(Component.translatable("iris.shaders.reloaded.failure", Throwables.getRootCause(e).getMessage()).withStyle(ChatFormatting.RED), false);
} }
} }
} else if (toggleShadersKeybind.consumeClick()) { } else if (IrisModern.toggleShadersKeybind.consumeClick()) {
try { try {
toggleShaders(minecraft, !irisConfig.areShadersEnabled()); toggleShaders(minecraft, !IrisCommon.getIrisConfig().areShadersEnabled());
} catch (Exception e) { } catch (Exception e) {
logger.error("Error while toggling shaders!", e); logger.error("Error while toggling shaders!", e);
if (minecraft.player != null) { if (minecraft.player != null) {
minecraft.player.displayClientMessage(Component.translatable("iris.shaders.toggled.failure", Throwables.getRootCause(e).getMessage()).withStyle(ChatFormatting.RED), false); minecraft.player.displayClientMessage(Component.translatable("iris.shaders.toggled.failure", Throwables.getRootCause(e).getMessage()).withStyle(ChatFormatting.RED), false);
} }
setShadersDisabled(); IrisCommon.setShadersDisabled();
fallback = true; IrisCommon.fallback = true;
} }
} else if (shaderpackScreenKeybind.consumeClick()) { } else if (IrisModern.shaderpackScreenKeybind.consumeClick()) {
minecraft.setScreen(new ShaderPackScreen(null)); minecraft.setScreen(new ShaderPackScreen(null));
} else if (wireframeKeybind.consumeClick()) { } else if (IrisModern.wireframeKeybind.consumeClick()) {
if (irisConfig.areDebugOptionsEnabled() && minecraft.player != null && !Minecraft.getInstance().isLocalServer()) { if (IrisCommon.getIrisConfig().areDebugOptionsEnabled() && minecraft.player != null && !Minecraft.getInstance().isLocalServer()) {
minecraft.player.displayClientMessage(Component.literal("No cheating; wireframe only in singleplayer!"), false); minecraft.player.displayClientMessage(Component.literal("No cheating; wireframe only in singleplayer!"), false);
} }
} }
} }
public static boolean shouldActivateWireframe() { public static boolean shouldActivateWireframe() {
return irisConfig.areDebugOptionsEnabled() && wireframeKeybind.isDown(); return IrisCommon.getIrisConfig().areDebugOptionsEnabled() && IrisModern.wireframeKeybind.isDown();
} }
public static void toggleShaders(Minecraft minecraft, boolean enabled) throws IOException { public static void toggleShaders(Minecraft minecraft, boolean enabled) throws IOException {
irisConfig.setShadersEnabled(enabled); IrisCommon.getIrisConfig().setShadersEnabled(enabled);
irisConfig.save(); IrisCommon.getIrisConfig().save();
reload(); reload();
if (minecraft.player != null) { if (minecraft.player != null) {
minecraft.player.displayClientMessage(enabled ? Component.translatable("iris.shaders.toggled", currentPackName) : Component.translatable("iris.shaders.disabled"), false); minecraft.player.displayClientMessage(enabled ? Component.translatable("iris.shaders.toggled", IrisCommon.currentPackName) : Component.translatable("iris.shaders.disabled"), false);
} }
} }
public static void loadShaderpack() {
if (irisConfig == null) {
if (!initialized) {
throw new IllegalStateException("Iris::loadShaderpack was called, but Iris::onInitializeClient wasn't" +
" called yet. How did this happen?");
} else {
throw new NullPointerException("Iris.irisConfig was null unexpectedly");
}
}
if (!irisConfig.areShadersEnabled()) {
logger.info("Shaders are disabled because enableShaders is set to false in iris.properties");
setShadersDisabled();
return;
}
// Attempt to load an external shaderpack if it is available
Optional<String> externalName = irisConfig.getShaderPackName();
if (externalName.isEmpty()) {
logger.info("Shaders are disabled because no valid shaderpack is selected");
setShadersDisabled();
return;
}
if (!loadExternalShaderpack(externalName.get())) {
logger.warn("Falling back to normal rendering without shaders because the shaderpack could not be loaded");
setShadersDisabled();
fallback = true;
}
}
@SuppressWarnings("unchecked")
private static boolean loadExternalShaderpack(String name) {
Path shaderPackRoot;
Path shaderPackConfigTxt;
try {
shaderPackRoot = IrisCommon.getShaderpacksDirectory().resolve(name);
shaderPackConfigTxt = IrisCommon.getShaderpacksDirectory().resolve(name + ".txt");
} catch (InvalidPathException e) {
logger.error("Failed to load the shaderpack \"{}\" because it contains invalid characters in its path", name);
return false;
}
if (!isValidShaderpack(shaderPackRoot)) {
logger.error("Pack \"{}\" is not valid! Can't load it.", name);
return false;
}
Path shaderPackPath;
if (!Files.isDirectory(shaderPackRoot) && shaderPackRoot.toString().endsWith(".zip")) {
Optional<Path> optionalPath;
try {
optionalPath = loadExternalZipShaderpack(shaderPackRoot);
} catch (FileSystemNotFoundException | NoSuchFileException e) {
logger.error("Failed to load the shaderpack \"{}\" because it does not exist in your shaderpacks folder!", name);
return false;
} catch (ZipException e) {
logger.error("The shaderpack \"{}\" appears to be corrupted, please try downloading it again!", name);
return false;
} catch (IOException e) {
logger.error("Failed to load the shaderpack \"{}\"!", name);
logger.error("", e);
return false;
}
if (optionalPath.isPresent()) {
shaderPackPath = optionalPath.get();
} else {
logger.error("Could not load the shaderpack \"{}\" because it appears to lack a \"shaders\" directory", name);
return false;
}
} else {
if (!Files.exists(shaderPackRoot)) {
logger.error("Failed to load the shaderpack \"{}\" because it does not exist!", name);
return false;
}
// If it's a folder-based shaderpack, just use the shaders subdirectory
shaderPackPath = shaderPackRoot.resolve("shaders");
}
if (!Files.exists(shaderPackPath)) {
logger.error("Could not load the shaderpack \"{}\" because it appears to lack a \"shaders\" directory", name);
return false;
}
Map<String, String> changedConfigs = tryReadConfigProperties(shaderPackConfigTxt)
.map(properties -> (Map<String, String>) (Object) properties)
.orElse(new HashMap<>());
changedConfigs.putAll(shaderPackOptionQueue);
clearShaderPackOptionQueue();
if (resetShaderPackOptions) {
changedConfigs.clear();
}
resetShaderPackOptions = false;
try {
currentPack = new ShaderPack(shaderPackPath, changedConfigs, StandardMacros.createStandardEnvironmentDefines());
MutableOptionValues changedConfigsValues = currentPack.getShaderPackOptions().getOptionValues().mutableCopy();
// Store changed values from those currently in use by the shader pack
Properties configsToSave = new Properties();
changedConfigsValues.getBooleanValues().forEach((k, v) -> configsToSave.setProperty(k, Boolean.toString(v)));
changedConfigsValues.getStringValues().forEach(configsToSave::setProperty);
tryUpdateConfigPropertiesFile(shaderPackConfigTxt, configsToSave);
} catch (Exception e) {
logger.error("Failed to load the shaderpack \"{}\"!", name);
logger.error("", e);
return false;
}
fallback = false;
currentPackName = name;
logger.info("Using shaderpack: " + name);
return true;
}
private static Optional<Path> loadExternalZipShaderpack(Path shaderpackPath) throws IOException {
FileSystem zipSystem = FileSystems.newFileSystem(shaderpackPath, Iris.class.getClassLoader());
zipFileSystem = zipSystem;
// Should only be one root directory for a zip shaderpack
Path root = zipSystem.getRootDirectories().iterator().next();
Path potentialShaderDir = zipSystem.getPath("shaders");
// If the shaders dir was immediately found return it
// Otherwise, manually search through each directory path until it ends with "shaders"
if (Files.exists(potentialShaderDir)) {
return Optional.of(potentialShaderDir);
}
// Sometimes shaderpacks have their shaders directory within another folder in the shaderpack
// For example Sildurs-Vibrant-Shaders.zip/shaders
// While other packs have Trippy-Shaderpack-master.zip/Trippy-Shaderpack-master/shaders
// This makes it hard to determine what is the actual shaders dir
try (Stream<Path> stream = Files.walk(root)) {
return stream
.filter(Files::isDirectory)
.filter(path -> path.endsWith("shaders"))
.findFirst();
}
}
private static void setShadersDisabled() {
currentPack = null;
fallback = false;
currentPackName = "(off)";
logger.info("Shaders are disabled");
}
public static void setDebug(boolean enable) { public static void setDebug(boolean enable) {
try { try {
irisConfig.setDebugEnabled(enable); IrisCommon.getIrisConfig().setDebugEnabled(enable);
irisConfig.save(); IrisCommon.getIrisConfig().save();
} catch (IOException e) { } catch (IOException e) {
Iris.logger.fatal("Failed to save config!", e); IRIS_LOGGER.fatal("Failed to save config!", e);
} }
int success; int success;
@@ -407,127 +167,19 @@ public class Iris {
return Optional.of(properties); return Optional.of(properties);
} }
private static void tryUpdateConfigPropertiesFile(Path path, Properties properties) {
try {
if (properties.isEmpty()) {
// Delete the file or don't create it if there are no changed configs
if (Files.exists(path)) {
Files.delete(path);
}
return;
}
try (OutputStream out = Files.newOutputStream(path)) {
properties.store(out, null);
}
} catch (IOException e) {
// TODO: Better error handling
}
}
public static boolean isValidToShowPack(Path pack) { public static boolean isValidToShowPack(Path pack) {
return Files.isDirectory(pack) || pack.toString().endsWith(".zip"); return Files.isDirectory(pack) || pack.toString().endsWith(".zip");
} }
public static boolean isValidShaderpack(Path pack) {
if (Files.isDirectory(pack)) {
// Sometimes the shaderpack directory itself can be
// identified as a shader pack due to it containing
// folders which contain "shaders" folders, this is
// necessary to check against that
if (pack.equals(IrisCommon.getShaderpacksDirectory())) {
return false;
}
try (Stream<Path> stream = Files.walk(pack)) {
return stream
.filter(Files::isDirectory)
// Prevent a pack simply named "shaders" from being
// identified as a valid pack
.filter(path -> !path.equals(pack))
.anyMatch(path -> path.endsWith("shaders"));
} catch (IOException ignored) {
// ignored, not a valid shader pack.
return false;
}
}
if (pack.toString().endsWith(".zip")) {
try (FileSystem zipSystem = FileSystems.newFileSystem(pack, Iris.class.getClassLoader())) {
Path root = zipSystem.getRootDirectories().iterator().next();
try (Stream<Path> stream = Files.walk(root)) {
return stream
.filter(Files::isDirectory)
.anyMatch(path -> path.endsWith("shaders"));
}
} catch (ZipError zipError) {
// Java 8 seems to throw a ZipError instead of a subclass of IOException
Iris.logger.warn("The ZIP at " + pack + " is corrupt");
} catch (IOException ignored) {
// ignored, not a valid shader pack.
}
}
return false;
}
public static Map<String, String> getShaderPackOptionQueue() {
return shaderPackOptionQueue;
}
public static void queueShaderPackOptionsFromProfile(Profile profile) {
getShaderPackOptionQueue().putAll(profile.optionValues);
}
public static void queueShaderPackOptionsFromProperties(Properties properties) {
queueDefaultShaderPackOptionValues();
properties.stringPropertyNames().forEach(key ->
getShaderPackOptionQueue().put(key, properties.getProperty(key)));
}
// Used in favor of resetShaderPackOptions as the aforementioned requires the pack to be reloaded
public static void queueDefaultShaderPackOptionValues() {
clearShaderPackOptionQueue();
getCurrentPack().ifPresent(pack -> {
OptionSet options = pack.getShaderPackOptions().getOptionSet();
OptionValues values = pack.getShaderPackOptions().getOptionValues();
options.getStringOptions().forEach((key, mOpt) -> {
if (values.getStringValue(key).isPresent()) {
getShaderPackOptionQueue().put(key, mOpt.getOption().getDefaultValue());
}
});
options.getBooleanOptions().forEach((key, mOpt) -> {
if (values.getBooleanValue(key) != OptionalBoolean.DEFAULT) {
getShaderPackOptionQueue().put(key, Boolean.toString(mOpt.getOption().getDefaultValue()));
}
});
});
}
public static void clearShaderPackOptionQueue() {
getShaderPackOptionQueue().clear();
}
public static void resetShaderPackOptionsOnNextReload() {
resetShaderPackOptions = true;
}
public static boolean shouldResetShaderPackOptionsOnNextReload() {
return resetShaderPackOptions;
}
public static void reload() throws IOException { public static void reload() throws IOException {
// allows shaderpacks to be changed at runtime // allows shaderpacks to be changed at runtime
irisConfig.initialize(); IrisCommon.getIrisConfig().initialize();
// Destroy all allocated resources // Destroy all allocated resources
destroyEverything(); IrisCommon.destroyEverything();
// Load the new shaderpack // Load the new shaderpack
loadShaderpack(); IrisCommon.loadShaderpack();
// Very important - we need to re-create the pipeline straight away. // Very important - we need to re-create the pipeline straight away.
// https://github.com/IrisShaders/Iris/issues/1330 // https://github.com/IrisShaders/Iris/issues/1330
@@ -536,28 +188,6 @@ public class Iris {
} }
} }
/**
* Destroys and deallocates all created OpenGL resources. Useful as part of a reload.
*/
private static void destroyEverything() {
currentPack = null;
getPipelineManager().destroyPipeline();
// Close the zip filesystem that the shaderpack was loaded from
//
// This prevents a FileSystemAlreadyExistsException when reloading shaderpacks.
if (zipFileSystem != null) {
try {
zipFileSystem.close();
} catch (NoSuchFileException e) {
logger.warn("Failed to close the shaderpack zip when reloading because it was deleted, proceeding anyways.");
} catch (IOException e) {
logger.error("Failed to close zip file system?", e);
}
}
}
public static NamespacedId getCurrentDimension() { public static NamespacedId getCurrentDimension() {
ClientLevel level = Minecraft.getInstance().level; ClientLevel level = Minecraft.getInstance().level;
@@ -567,82 +197,28 @@ public class Iris {
// This prevents us from reloading the shaderpack unless we need to. Otherwise, if the player is in the // This prevents us from reloading the shaderpack unless we need to. Otherwise, if the player is in the
// nether and quits the game, we might end up reloading the shaders on exit and on entry to the level // nether and quits the game, we might end up reloading the shaders on exit and on entry to the level
// because the code thinks that the dimension changed. // because the code thinks that the dimension changed.
return lastDimension; return IrisCommon.getLastDimension();
}
}
private static WorldRenderingPipeline createPipeline(NamespacedId dimensionId) {
if (currentPack == null) {
// Completely disables shader-based rendering
return new VanillaRenderingPipeline();
}
ProgramSet programs = currentPack.getProgramSet(dimensionId);
// We use DeferredWorldRenderingPipeline on 1.16, and NewWorldRendering pipeline on 1.17 when rendering shaders.
try {
return new IrisRenderingPipeline(programs);
} catch (Exception e) {
if (irisConfig.areDebugOptionsEnabled()) {
Minecraft.getInstance().setScreen(new DebugLoadFailedGridScreen(Minecraft.getInstance().screen, Component.literal(e instanceof ShaderCompileException ? "Failed to compile shaders" : "Exception"), e));
} else {
if (Minecraft.getInstance().player != null) {
Minecraft.getInstance().player.displayClientMessage(Component.translatable(e instanceof ShaderCompileException ? "iris.load.failure.shader" : "iris.load.failure.generic").append(Component.literal("Copy Info").withStyle(arg -> arg.withUnderlined(true).withColor(ChatFormatting.BLUE).withClickEvent(new ClickEvent(ClickEvent.Action.COPY_TO_CLIPBOARD, e.getMessage())))), false);
} else {
storedError = Optional.of(e);
}
}
logger.error("Failed to create shader rendering pipeline, disabling shaders!", e);
// TODO: This should be reverted if a dimension change causes shaders to compile again
fallback = true;
return new VanillaRenderingPipeline();
} }
} }
@NotNull @NotNull
public static PipelineManager getPipelineManager() { public static PipelineManager getPipelineManager() {
if (pipelineManager == null) { return IrisCommon.getPipelineManager();
pipelineManager = new PipelineManager(Iris::createPipeline);
}
if (loadPackWhenPossible && renderSystemInit) {
loadPackWhenPossible = false;
try {
reload();
} catch (IOException e) {
logger.error("Error while reloading Shaders for " + IrisConstants.MODNAME + "!", e);
if (Minecraft.getInstance().player != null) {
Minecraft.getInstance().player.displayClientMessage(Component.translatable("iris.shaders.reloaded.failure", Throwables.getRootCause(e).getMessage()).withStyle(ChatFormatting.RED), false);
}
}
}
return pipelineManager;
} }
public static Optional<Exception> getStoredError() { public static Optional<Exception> getStoredError() {
Optional<Exception> stored = Iris.storedError; Optional<Exception> stored = IrisCommon.getStoredError();
storedError = Optional.empty(); IrisCommon.setStoredError(Optional.empty());
return stored; return stored;
} }
@NotNull
public static Optional<ShaderPack> getCurrentPack() {
return Optional.ofNullable(currentPack);
}
public static String getCurrentPackName() { public static String getCurrentPackName() {
return currentPackName; return IrisCommon.currentPackName;
} }
public static IrisConfig getIrisConfig() {
return irisConfig;
}
public static boolean isFallback() { public static boolean isFallback() {
return fallback; return IrisCommon.fallback;
} }
public static String getVersion() { public static String getVersion() {
@@ -694,48 +270,5 @@ public class Iris {
return DHCompat.lastPackIncompatible(); return DHCompat.lastPackIncompatible();
} }
/**
* Called very early on in Minecraft initialization. At this point we *cannot* safely access OpenGL, but we can do
* some very basic setup, config loading, and environment checks.
*
* <p>This is roughly equivalent to Fabric Loader's ClientModInitializer#onInitializeClient entrypoint, except
* it's entirely cross platform & we get to decide its exact semantics.</p>
*
* <p>This is called right before options are loaded, so we can add key bindings here.</p>
*/
public static void onEarlyInitialize() {
reloadKeybind = new KeyMapping("iris.keybind.reload", InputConstants.Type.KEYSYM, GLFW.GLFW_KEY_R, "iris.keybinds");
toggleShadersKeybind = new KeyMapping("iris.keybind.toggleShaders", InputConstants.Type.KEYSYM, GLFW.GLFW_KEY_K, "iris.keybinds");
shaderpackScreenKeybind = new KeyMapping("iris.keybind.shaderPackSelection", InputConstants.Type.KEYSYM, GLFW.GLFW_KEY_O, "iris.keybinds");
wireframeKeybind = new KeyMapping("iris.keybind.wireframe", InputConstants.Type.KEYSYM, InputConstants.UNKNOWN.getValue(), "iris.keybinds");
//? if fabric {
/*KeyBindingHelper.registerKeyBinding(net.irisshaders.iris.Iris.reloadKeybind);
KeyBindingHelper.registerKeyBinding(net.irisshaders.iris.Iris.shaderpackScreenKeybind);
KeyBindingHelper.registerKeyBinding(net.irisshaders.iris.Iris.toggleShadersKeybind);
KeyBindingHelper.registerKeyBinding(net.irisshaders.iris.Iris.wireframeKeybind);
*///?}
DHCompat.run();
try {
if (!Files.exists(IrisCommon.getShaderpacksDirectory())) {
Files.createDirectories(IrisCommon.getShaderpacksDirectory());
}
} catch (IOException e) {
logger.warn("Failed to create the shaderpacks directory!");
logger.warn("", e);
}
irisConfig = new IrisConfig(PLATFORM_UTIL.getConfigDir().resolve(IrisConstants.MODID + "-shaders.properties"));
try {
irisConfig.initialize();
} catch (IOException e) {
logger.error("Failed to initialize Iris configuration, default values will be used instead");
logger.error("", e);
}
initialized = true;
}
} }
@@ -0,0 +1,257 @@
package net.irisshaders.iris;
import com.google.common.base.Throwables;
import com.mojang.blaze3d.platform.InputConstants;
import net.irisshaders.iris.compat.dh.DHCompat;
import net.irisshaders.iris.features.FeatureFlags;
import net.irisshaders.iris.gl.shader.ShaderCompileException;
import net.irisshaders.iris.gui.FeatureMissingErrorScreen;
import net.irisshaders.iris.gui.debug.DebugLoadFailedGridScreen;
import net.irisshaders.iris.gui.screen.ShaderPackScreen;
import net.irisshaders.iris.pipeline.IrisRenderingPipeline;
import net.irisshaders.iris.pipeline.ModernIrisRenderingPipeline;
import net.irisshaders.iris.pipeline.ModernVanillaRenderingPipeline;
import net.irisshaders.iris.pipeline.WorldRenderingPipeline;
import net.irisshaders.iris.shaderpack.materialmap.BlockEntry;
import net.irisshaders.iris.shaderpack.materialmap.NamespacedId;
import net.irisshaders.iris.shaderpack.programs.ProgramSet;
import net.irisshaders.iris.texture.pbr.PBRTextureManager;
import net.irisshaders.iris.uniforms.ModernBiomeUniforms;
import net.minecraft.ChatFormatting;
import net.minecraft.client.KeyMapping;
import net.minecraft.client.Minecraft;
import net.minecraft.network.chat.ClickEvent;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import org.apache.commons.lang3.SystemUtils;
import org.embeddedt.embeddium.compat.iris.IBlockEntry;
import org.embeddedt.embeddium.impl.loader.common.EarlyLoaderServices;
import org.jetbrains.annotations.NotNull;
import org.lwjgl.glfw.GLFW;
import org.taumc.celeritas.CeleritasShaderVersionService;
import org.taumc.celeritas.api.v0.CeleritasShadersApi;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
import static net.irisshaders.iris.IrisLogging.IRIS_LOGGER;
import static net.irisshaders.iris.uniforms.BiomeUniforms.BIOME_UNIFORMS;
public class IrisModern implements CeleritasShaderVersionService {
public static KeyMapping reloadKeybind;
public static KeyMapping toggleShadersKeybind;
public static KeyMapping shaderpackScreenKeybind;
public static KeyMapping wireframeKeybind;
@Override
public void reloadIris() throws IOException {
Iris.reload();
}
@Override
public boolean irisAllowConcurrentUpdate() {
return Iris.getPipelineManager().getPipeline().map(WorldRenderingPipeline::allowConcurrentCompute).orElse(false);
}
@Override
public void handleUnsupportedFeatureFlags(List<FeatureFlags> invalidFlagList, List<String> invalidFeatureFlags) {
if (Minecraft.getInstance().screen instanceof ShaderPackScreen) {
MutableComponent component = Component.translatable("iris.unsupported.pack.description", FeatureFlags.getInvalidStatus(invalidFlagList), invalidFeatureFlags.stream()
.collect(Collectors.joining(", ", ": ", ".")));
if (SystemUtils.IS_OS_MAC) {
component = component.append(Component.translatable("iris.unsupported.pack.macos"));
}
Minecraft.getInstance().setScreen(new FeatureMissingErrorScreen(Minecraft.getInstance().screen, Component.translatable("iris.unsupported.pack"), component));
}
}
@Override
public void processBiomeMap(BiConsumer<String, String> define) {
((ModernBiomeUniforms)BIOME_UNIFORMS).getBiomeMap().forEach((biome, id) ->
define.accept("BIOME_" + biome.location().getPath().toUpperCase(Locale.ROOT), String.valueOf(id))
);
}
@NotNull
@Override
public IBlockEntry parseBlockEntry(@NotNull String entry) {
if (entry.isEmpty()) {
throw new IllegalArgumentException("Called BlockEntry::parse with an empty string");
}
boolean isTag;
if (entry.startsWith("%")) {
isTag = true;
entry = entry.substring(1);
} else {
isTag = false;
}
// We can assume that this array is of at least array length because the input string is non-empty.
String[] splitStates = entry.split(":");
// Trivial case: no states, no namespace
if (splitStates.length == 1) {
return new BlockEntry(new NamespacedId("minecraft", entry), Collections.emptyMap(), isTag);
}
// Less trivial case: no states involved, just a namespace
//
// The first term MUST be a valid ResourceLocation component without an equals sign
// The second term, if it does not contain an equals sign, must be a valid ResourceLocation component.
if (splitStates.length == 2 && !splitStates[1].contains("=")) {
return new BlockEntry(new NamespacedId(splitStates[0], splitStates[1]), Collections.emptyMap(), isTag);
}
// Complex case: One or more states involved...
int statesStart;
NamespacedId id;
if (splitStates[1].contains("=")) {
// We have an entry of the form "tall_grass:half=upper"
statesStart = 1;
id = new NamespacedId("minecraft", splitStates[0]);
} else {
// We have an entry of the form "minecraft:tall_grass:half=upper"
statesStart = 2;
id = new NamespacedId(splitStates[0], splitStates[1]);
}
// We must parse each property key=value pair from the state entry.
//
// These pairs act as a filter on the block states. Thus, the shader pack does not have to specify all the
// individual block properties itself; rather, it only specifies the parts of the block state that it wishes
// to filter in/out.
//
// For example, some shader packs may make it so that hanging lantern blocks wave. They will put something of
// the form "lantern:hanging=false" in the ID map as a result. Note, however, that there are also waterlogged
// hanging lanterns, which would have "lantern:hanging=false:waterlogged=true". We must make sure that when the
// shader pack author writes "lantern:hanging=false", that we do not just match that individual state, but that
// we also match the waterlogged variant too.
Map<String, String> map = new HashMap<>();
for (int index = statesStart; index < splitStates.length; index++) {
// Split "key=value" into the key and value
String[] propertyParts = splitStates[index].split("=");
if (propertyParts.length != 2) {
IRIS_LOGGER.warn("Warning: the block ID map entry \"" + entry + "\" could not be fully parsed:");
IRIS_LOGGER.warn("- Block state property filters must be of the form \"key=value\", but "
+ splitStates[index] + " is not of that form!");
// Continue and ignore the invalid entry.
continue;
}
map.put(propertyParts[0], propertyParts[1]);
}
return new BlockEntry(id, map, isTag);
}
@Override
public IBlockEntry createBlockEntry(NamespacedId id) {
return new BlockEntry(id, Collections.emptyMap(), false);
}
@Override
public void onEarlyInitialize() {
reloadKeybind = new KeyMapping("iris.keybind.reload", InputConstants.Type.KEYSYM, GLFW.GLFW_KEY_R, "iris.keybinds");
toggleShadersKeybind = new KeyMapping("iris.keybind.toggleShaders", InputConstants.Type.KEYSYM, GLFW.GLFW_KEY_K, "iris.keybinds");
shaderpackScreenKeybind = new KeyMapping("iris.keybind.shaderPackSelection", InputConstants.Type.KEYSYM, GLFW.GLFW_KEY_O, "iris.keybinds");
wireframeKeybind = new KeyMapping("iris.keybind.wireframe", InputConstants.Type.KEYSYM, InputConstants.UNKNOWN.getValue(), "iris.keybinds");
//? if fabric {
/*KeyBindingHelper.registerKeyBinding(reloadKeybind);
KeyBindingHelper.registerKeyBinding(shaderpackScreenKeybind);
KeyBindingHelper.registerKeyBinding(toggleShadersKeybind);
KeyBindingHelper.registerKeyBinding(wireframeKeybind);
*///?}
DHCompat.run();
}
@Override
public void onRenderSystemInit() {
PBRTextureManager.INSTANCE.init();
// Only load the shader pack when we can access OpenGL
if (!EarlyLoaderServices.INSTANCE.isModLoaded("distanthorizons")) {
IrisCommon.loadShaderpack();
}
}
@Override
public void onLoadingComplete() {
}
@Override
public void destroyEverything() {
Iris.getPipelineManager().destroyPipeline();
}
@Override
public WorldRenderingPipeline createPipeline(NamespacedId dimensionId) {
if (IrisCommon.getCurrentPack().isEmpty()) {
// Completely disables shader-based rendering
return createVanillaRenderingPipeline();
}
ProgramSet programs = IrisCommon.getCurrentPack().get().getProgramSet(dimensionId);
// We use DeferredWorldRenderingPipeline on 1.16, and NewWorldRendering pipeline on 1.17 when rendering shaders.
try {
return new ModernIrisRenderingPipeline(programs);
} catch (Exception e) {
if (IrisCommon.getIrisConfig().areDebugOptionsEnabled()) {
Minecraft.getInstance().setScreen(new DebugLoadFailedGridScreen(Minecraft.getInstance().screen, Component.literal(e instanceof ShaderCompileException ? "Failed to compile shaders" : "Exception"), e));
} else {
if (Minecraft.getInstance().player != null) {
Minecraft.getInstance().player.displayClientMessage(Component.translatable(e instanceof ShaderCompileException ? "iris.load.failure.shader" : "iris.load.failure.generic").append(Component.literal("Copy Info").withStyle(arg -> arg.withUnderlined(true).withColor(ChatFormatting.BLUE).withClickEvent(new ClickEvent(ClickEvent.Action.COPY_TO_CLIPBOARD, e.getMessage())))), false);
} else {
IrisCommon.setStoredError(Optional.of(e));
}
}
IRIS_LOGGER.error("Failed to create shader rendering pipeline, disabling shaders!", e);
// TODO: This should be reverted if a dimension change causes shaders to compile again
IrisCommon.setFallback(true);
return createVanillaRenderingPipeline();
}
}
@Override
public WorldRenderingPipeline createVanillaRenderingPipeline() {
return new ModernVanillaRenderingPipeline();
}
@Override
public void reload() {
try {
Iris.reload();
} catch (IOException e) {
IRIS_LOGGER.error("Error while reloading Shaders for " + IrisConstants.MODNAME + "!", e);
if (Minecraft.getInstance().player != null) {
Minecraft.getInstance().player.displayClientMessage(Component.translatable("iris.shaders.reloaded.failure", Throwables.getRootCause(e).getMessage()).withStyle(ChatFormatting.RED), false);
}
}
}
@Override
public Object getDHCompatInstance(IrisRenderingPipeline pipeline, boolean renderDHShadow) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
return Class.forName("net.irisshaders.iris.compat.dh.DHCompatInternal").getDeclaredConstructor(ModernIrisRenderingPipeline.class, boolean.class).newInstance((ModernIrisRenderingPipeline)pipeline, renderDHShadow);
}
}
@@ -1,33 +1,36 @@
package net.irisshaders.iris.apiimpl; package net.irisshaders.iris.apiimpl;
import net.irisshaders.iris.Iris; import net.irisshaders.iris.Iris;
import net.irisshaders.iris.IrisCommon;
import net.irisshaders.iris.api.v0.IrisApiConfig; import net.irisshaders.iris.api.v0.IrisApiConfig;
import net.irisshaders.iris.config.IrisConfig; import net.irisshaders.iris.config.IrisConfig;
import java.io.IOException; import java.io.IOException;
import static net.irisshaders.iris.IrisLogging.IRIS_LOGGER;
public class IrisApiV0ConfigImpl implements IrisApiConfig { public class IrisApiV0ConfigImpl implements IrisApiConfig {
@Override @Override
public boolean areShadersEnabled() { public boolean areShadersEnabled() {
return Iris.getIrisConfig().areShadersEnabled(); return IrisCommon.getIrisConfig().areShadersEnabled();
} }
@Override @Override
public void setShadersEnabledAndApply(boolean enabled) { public void setShadersEnabledAndApply(boolean enabled) {
IrisConfig config = Iris.getIrisConfig(); IrisConfig config = IrisCommon.getIrisConfig();
config.setShadersEnabled(enabled); config.setShadersEnabled(enabled);
try { try {
config.save(); config.save();
} catch (IOException e) { } catch (IOException e) {
Iris.logger.error("Error saving configuration file!", e); IRIS_LOGGER.error("Error saving configuration file!", e);
} }
try { try {
Iris.reload(); Iris.reload();
} catch (IOException e) { } catch (IOException e) {
Iris.logger.error("Error reloading shader pack while applying changes!", e); IRIS_LOGGER.error("Error reloading shader pack while applying changes!", e);
} }
} }
} }
@@ -1,6 +1,7 @@
package net.irisshaders.iris.apiimpl; package net.irisshaders.iris.apiimpl;
import net.irisshaders.iris.Iris; import net.irisshaders.iris.Iris;
import net.irisshaders.iris.IrisCommon;
import net.irisshaders.iris.api.v0.IrisApi; import net.irisshaders.iris.api.v0.IrisApi;
import net.irisshaders.iris.api.v0.IrisApiConfig; import net.irisshaders.iris.api.v0.IrisApiConfig;
import net.irisshaders.iris.api.v0.IrisTextVertexSink; import net.irisshaders.iris.api.v0.IrisTextVertexSink;
@@ -14,7 +15,7 @@ import net.minecraft.client.gui.screens.Screen;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.util.function.IntFunction; import java.util.function.IntFunction;
public class IrisApiV0Impl implements IrisApi { public class IrisApiV0ImplModern implements IrisApi {
private static final IrisApiV0ConfigImpl CONFIG = new IrisApiV0ConfigImpl(); private static final IrisApiV0ConfigImpl CONFIG = new IrisApiV0ConfigImpl();
@Override @Override
@@ -54,7 +55,7 @@ public class IrisApiV0Impl implements IrisApi {
@Override @Override
public boolean areDebugOptionsEnabled() { public boolean areDebugOptionsEnabled() {
return Iris.getIrisConfig().areDebugOptionsEnabled(); return IrisCommon.getIrisConfig().areDebugOptionsEnabled();
} }
@Override @Override
@@ -3,6 +3,7 @@ package net.irisshaders.iris.compat.dh;
import java.io.IOException; import java.io.IOException;
import static com.mitchej123.glsm.RenderSystemService.RENDER_SYSTEM; import static com.mitchej123.glsm.RenderSystemService.RENDER_SYSTEM;
import static net.irisshaders.iris.IrisLogging.IRIS_LOGGER;
import com.seibel.distanthorizons.api.DhApi; import com.seibel.distanthorizons.api.DhApi;
import com.seibel.distanthorizons.api.interfaces.override.rendering.IDhApiFramebuffer; import com.seibel.distanthorizons.api.interfaces.override.rendering.IDhApiFramebuffer;
@@ -14,7 +15,7 @@ import net.irisshaders.iris.gl.IrisRenderSystem;
import net.irisshaders.iris.gl.framebuffer.GlFramebuffer; import net.irisshaders.iris.gl.framebuffer.GlFramebuffer;
import net.irisshaders.iris.gl.texture.DepthBufferFormat; import net.irisshaders.iris.gl.texture.DepthBufferFormat;
import net.irisshaders.iris.gl.texture.DepthCopyStrategy; import net.irisshaders.iris.gl.texture.DepthCopyStrategy;
import net.irisshaders.iris.pipeline.IrisRenderingPipeline; import net.irisshaders.iris.pipeline.ModernIrisRenderingPipeline;
import net.irisshaders.iris.shaderpack.programs.ProgramSource; import net.irisshaders.iris.shaderpack.programs.ProgramSource;
import net.irisshaders.iris.shaderpack.properties.CloudSetting; import net.irisshaders.iris.shaderpack.properties.CloudSetting;
import net.irisshaders.iris.targets.Blaze3dRenderTargetExt; import net.irisshaders.iris.targets.Blaze3dRenderTargetExt;
@@ -27,7 +28,7 @@ public class DHCompatInternal {
public static final DHCompatInternal SHADERLESS = new DHCompatInternal(null, false); public static final DHCompatInternal SHADERLESS = new DHCompatInternal(null, false);
static boolean dhEnabled; static boolean dhEnabled;
private static int guiScale = -1; private static int guiScale = -1;
private final IrisRenderingPipeline pipeline; private final ModernIrisRenderingPipeline pipeline;
public boolean shouldOverrideShadow; public boolean shouldOverrideShadow;
public boolean shouldOverride; public boolean shouldOverride;
private GlFramebuffer dhGenericFramebuffer; private GlFramebuffer dhGenericFramebuffer;
@@ -46,7 +47,7 @@ public class DHCompatInternal {
private boolean incompatible = false; private boolean incompatible = false;
private int cachedVersion; private int cachedVersion;
public DHCompatInternal(IrisRenderingPipeline pipeline, boolean dhShadowEnabled) { public DHCompatInternal(ModernIrisRenderingPipeline pipeline, boolean dhShadowEnabled) {
this.pipeline = pipeline; this.pipeline = pipeline;
if (pipeline == null || !DhApi.Delayed.configs.graphics().renderingEnabled().getValue()) { if (pipeline == null || !DhApi.Delayed.configs.graphics().renderingEnabled().getValue()) {
@@ -54,7 +55,7 @@ public class DHCompatInternal {
} }
if (pipeline.getDHTerrainShader().isEmpty() && pipeline.getDHWaterShader().isEmpty()) { if (pipeline.getDHTerrainShader().isEmpty() && pipeline.getDHWaterShader().isEmpty()) {
Iris.logger.warn("No DH shader found in this pack."); IRIS_LOGGER.warn("No DH shader found in this pack.");
incompatible = true; incompatible = true;
return; return;
} }
@@ -141,7 +142,7 @@ public class DHCompatInternal {
if (DhApi.Delayed.configs == null) return dhEnabled; if (DhApi.Delayed.configs == null) return dhEnabled;
if ((dhEnabled != DhApi.Delayed.configs.graphics().renderingEnabled().getValue() || guiScale != Minecraft.getInstance().options.guiScale().get()) if ((dhEnabled != DhApi.Delayed.configs.graphics().renderingEnabled().getValue() || guiScale != Minecraft.getInstance().options.guiScale().get())
&& Iris.getPipelineManager().getPipelineNullable() instanceof IrisRenderingPipeline) { && Iris.getPipelineManager().getPipelineNullable() instanceof ModernIrisRenderingPipeline) {
guiScale = Minecraft.getInstance().options.guiScale().get(); guiScale = Minecraft.getInstance().options.guiScale().get();
dhEnabled = DhApi.Delayed.configs.graphics().renderingEnabled().getValue(); dhEnabled = DhApi.Delayed.configs.graphics().renderingEnabled().getValue();
try { try {
@@ -29,7 +29,7 @@ import net.irisshaders.iris.gl.shader.GlShader;
import net.irisshaders.iris.gl.shader.ShaderType; import net.irisshaders.iris.gl.shader.ShaderType;
import net.irisshaders.iris.gl.state.FogMode; import net.irisshaders.iris.gl.state.FogMode;
import net.irisshaders.iris.gl.texture.TextureType; import net.irisshaders.iris.gl.texture.TextureType;
import net.irisshaders.iris.pipeline.IrisRenderingPipeline; import net.irisshaders.iris.pipeline.ModernIrisRenderingPipeline;
import net.irisshaders.iris.pipeline.foss_transform.TransformPatcherBridge; import net.irisshaders.iris.pipeline.foss_transform.TransformPatcherBridge;
import net.irisshaders.iris.pipeline.transform.PatchShaderType; import net.irisshaders.iris.pipeline.transform.PatchShaderType;
import net.irisshaders.iris.pipeline.transform.ShaderPrinter; import net.irisshaders.iris.pipeline.transform.ShaderPrinter;
@@ -73,7 +73,7 @@ public class IrisGenericRenderProgram implements IDhApiGenericObjectShaderProgra
private final int uSkyLight; private final int uSkyLight;
// This will bind AbstractVertexAttribute // This will bind AbstractVertexAttribute
private IrisGenericRenderProgram(String name, boolean isShadowPass, boolean translucent, BlendModeOverride override, BufferBlendOverride[] bufferBlendOverrides, String vertex, String tessControl, String tessEval, String geometry, String fragment, CustomUniforms customUniforms, IrisRenderingPipeline pipeline) { private IrisGenericRenderProgram(String name, boolean isShadowPass, boolean translucent, BlendModeOverride override, BufferBlendOverride[] bufferBlendOverrides, String vertex, String tessControl, String tessEval, String geometry, String fragment, CustomUniforms customUniforms, ModernIrisRenderingPipeline pipeline) {
id = GL43C.glCreateProgram(); id = GL43C.glCreateProgram();
GL32.glBindAttribLocation(this.id, 0, "vPosition"); GL32.glBindAttribLocation(this.id, 0, "vPosition");
@@ -155,7 +155,7 @@ public class IrisGenericRenderProgram implements IDhApiGenericObjectShaderProgra
this.uSkyLight = this.tryGetUniformLocation2("uSkyLight"); this.uSkyLight = this.tryGetUniformLocation2("uSkyLight");
} }
public static IrisGenericRenderProgram createProgram(String name, boolean isShadowPass, boolean translucent, ProgramSource source, CustomUniforms uniforms, IrisRenderingPipeline pipeline) { public static IrisGenericRenderProgram createProgram(String name, boolean isShadowPass, boolean translucent, ProgramSource source, CustomUniforms uniforms, ModernIrisRenderingPipeline pipeline) {
Map<PatchShaderType, String> transformed = TransformPatcherBridge.patchDHGeneric( Map<PatchShaderType, String> transformed = TransformPatcherBridge.patchDHGeneric(
name, name,
source.getVertexSource().orElseThrow(RuntimeException::new), source.getVertexSource().orElseThrow(RuntimeException::new),
@@ -268,7 +268,7 @@ public class IrisGenericRenderProgram implements IDhApiGenericObjectShaderProgra
@Override @Override
public boolean overrideThisFrame() { public boolean overrideThisFrame() {
return Iris.getPipelineManager().getPipelineNullable() instanceof IrisRenderingPipeline; return Iris.getPipelineManager().getPipelineNullable() instanceof ModernIrisRenderingPipeline;
} }
@Override @Override
@@ -20,7 +20,7 @@ import net.irisshaders.iris.gl.shader.GlShader;
import net.irisshaders.iris.gl.shader.ShaderType; import net.irisshaders.iris.gl.shader.ShaderType;
import net.irisshaders.iris.gl.state.FogMode; import net.irisshaders.iris.gl.state.FogMode;
import net.irisshaders.iris.gl.texture.TextureType; import net.irisshaders.iris.gl.texture.TextureType;
import net.irisshaders.iris.pipeline.IrisRenderingPipeline; import net.irisshaders.iris.pipeline.ModernIrisRenderingPipeline;
import net.irisshaders.iris.pipeline.foss_transform.TransformPatcherBridge; import net.irisshaders.iris.pipeline.foss_transform.TransformPatcherBridge;
import net.irisshaders.iris.pipeline.transform.PatchShaderType; import net.irisshaders.iris.pipeline.transform.PatchShaderType;
import net.irisshaders.iris.pipeline.transform.ShaderPrinter; import net.irisshaders.iris.pipeline.transform.ShaderPrinter;
@@ -58,7 +58,7 @@ public class IrisLodRenderProgram {
private final BufferBlendOverride[] bufferBlendOverrides; private final BufferBlendOverride[] bufferBlendOverrides;
// This will bind AbstractVertexAttribute // This will bind AbstractVertexAttribute
private IrisLodRenderProgram(String name, boolean isShadowPass, boolean translucent, BlendModeOverride override, BufferBlendOverride[] bufferBlendOverrides, String vertex, String tessControl, String tessEval, String geometry, String fragment, CustomUniforms customUniforms, IrisRenderingPipeline pipeline) { private IrisLodRenderProgram(String name, boolean isShadowPass, boolean translucent, BlendModeOverride override, BufferBlendOverride[] bufferBlendOverrides, String vertex, String tessControl, String tessEval, String geometry, String fragment, CustomUniforms customUniforms, ModernIrisRenderingPipeline pipeline) {
id = GL43C.glCreateProgram(); id = GL43C.glCreateProgram();
GL32.glBindAttribLocation(this.id, 0, "vPosition"); GL32.glBindAttribLocation(this.id, 0, "vPosition");
@@ -135,7 +135,7 @@ public class IrisLodRenderProgram {
clipDistanceUniform = tryGetUniformLocation2("clipDistance"); clipDistanceUniform = tryGetUniformLocation2("clipDistance");
} }
public static IrisLodRenderProgram createProgram(String name, boolean isShadowPass, boolean translucent, ProgramSource source, CustomUniforms uniforms, IrisRenderingPipeline pipeline) { public static IrisLodRenderProgram createProgram(String name, boolean isShadowPass, boolean translucent, ProgramSource source, CustomUniforms uniforms, ModernIrisRenderingPipeline pipeline) {
Map<PatchShaderType, String> transformed = TransformPatcherBridge.patchDHTerrain( Map<PatchShaderType, String> transformed = TransformPatcherBridge.patchDHTerrain(
name, name,
source.getVertexSource().orElseThrow(RuntimeException::new), source.getVertexSource().orElseThrow(RuntimeException::new),
@@ -1,6 +1,7 @@
package net.irisshaders.iris.compat.dh; package net.irisshaders.iris.compat.dh;
import static com.mitchej123.glsm.GLStateManagerService.GL_STATE_MANAGER; import static com.mitchej123.glsm.GLStateManagerService.GL_STATE_MANAGER;
import static net.irisshaders.iris.IrisLogging.IRIS_LOGGER;
import com.seibel.distanthorizons.api.DhApi; import com.seibel.distanthorizons.api.DhApi;
import com.seibel.distanthorizons.api.enums.rendering.EDhApiFogDrawMode; import com.seibel.distanthorizons.api.enums.rendering.EDhApiFogDrawMode;
@@ -27,6 +28,7 @@ import com.seibel.distanthorizons.api.methods.events.sharedParameterObjects.DhAp
import com.seibel.distanthorizons.api.objects.math.DhApiVec3f; import com.seibel.distanthorizons.api.objects.math.DhApiVec3f;
import com.seibel.distanthorizons.coreapi.DependencyInjection.OverrideInjector; import com.seibel.distanthorizons.coreapi.DependencyInjection.OverrideInjector;
import net.irisshaders.iris.Iris; import net.irisshaders.iris.Iris;
import net.irisshaders.iris.IrisCommon;
import net.irisshaders.iris.pipeline.WorldRenderingPipeline; import net.irisshaders.iris.pipeline.WorldRenderingPipeline;
import net.irisshaders.iris.shadows.ShadowRenderer; import net.irisshaders.iris.shadows.ShadowRenderer;
import net.irisshaders.iris.shadows.ShadowRenderingState; import net.irisshaders.iris.shadows.ShadowRenderingState;
@@ -48,14 +50,14 @@ public class LodRendererEvents {
public static void setupEventHandlers() { public static void setupEventHandlers() {
if (!eventHandlersBound) { if (!eventHandlersBound) {
eventHandlersBound = true; eventHandlersBound = true;
Iris.logger.info("Queuing DH event binding..."); IRIS_LOGGER.info("Queuing DH event binding...");
DhApiAfterDhInitEvent beforeCleanupEvent = new DhApiAfterDhInitEvent() { DhApiAfterDhInitEvent beforeCleanupEvent = new DhApiAfterDhInitEvent() {
@Override @Override
public void afterDistantHorizonsInit(DhApiEventParam<Void> event) { public void afterDistantHorizonsInit(DhApiEventParam<Void> event) {
Iris.logger.info("DH Ready, binding Iris event handlers..."); IRIS_LOGGER.info("DH Ready, binding Iris event handlers...");
Iris.loadShaderpackWhenPossible(); IrisCommon.loadShaderpackWhenPossible();
setupSetDeferredBeforeRenderingEvent(); setupSetDeferredBeforeRenderingEvent();
setupReconnectDepthTextureEvent(); setupReconnectDepthTextureEvent();
@@ -69,7 +71,7 @@ public class LodRendererEvents {
setupBeforeRenderPassEvent(); setupBeforeRenderPassEvent();
setupBeforeApplyShaderEvent(); setupBeforeApplyShaderEvent();
DHCompatInternal.dhEnabled = DhApi.Delayed.configs.graphics().renderingEnabled().getValue(); DHCompatInternal.dhEnabled = DhApi.Delayed.configs.graphics().renderingEnabled().getValue();
Iris.logger.info("DH Iris events bound."); IRIS_LOGGER.info("DH Iris events bound.");
} }
}; };
DhApi.events.bind(DhApiAfterDhInitEvent.class, beforeCleanupEvent); DhApi.events.bind(DhApiAfterDhInitEvent.class, beforeCleanupEvent);
@@ -273,7 +275,7 @@ public class LodRendererEvents {
DhApi.Delayed.configs.graphics().fog().drawMode().setValue(EDhApiFogDrawMode.FOG_DISABLED); DhApi.Delayed.configs.graphics().fog().drawMode().setValue(EDhApiFogDrawMode.FOG_DISABLED);
if (event.value.renderPass == EDhApiRenderPass.OPAQUE_AND_TRANSPARENT) { if (event.value.renderPass == EDhApiRenderPass.OPAQUE_AND_TRANSPARENT) {
Iris.logger.error("Unexpected; somehow the Opaque + Translucent pass ran with shaders on."); IRIS_LOGGER.error("Unexpected; somehow the Opaque + Translucent pass ran with shaders on.");
} }
} else { } else {
DhApi.Delayed.configs.graphics().ambientOcclusion().enabled().clearValue(); DhApi.Delayed.configs.graphics().ambientOcclusion().enabled().clearValue();
@@ -309,7 +311,7 @@ public class LodRendererEvents {
//float nearClip = DhApi.Delayed.renderProxy.getNearClipPlaneDistanceInBlocks(partialTicks); //float nearClip = DhApi.Delayed.renderProxy.getNearClipPlaneDistanceInBlocks(partialTicks);
//float farClip = (float) ((double) (DHCompatInternal.getDhBlockRenderDistance() + 512) * Math.sqrt(2.0)); //float farClip = (float) ((double) (DHCompatInternal.getDhBlockRenderDistance() + 512) * Math.sqrt(2.0));
//Iris.logger.info("event near clip: "+event.value.nearClipPlane+" event far clip: "+event.value.farClipPlane+ //IRIS_LOGGER.info("event near clip: "+event.value.nearClipPlane+" event far clip: "+event.value.farClipPlane+
// " \niris near clip: "+nearClip+" iris far clip: "+farClip); // " \niris near clip: "+nearClip+" iris far clip: "+farClip);
instance.getSolidShader().fillUniformData( instance.getSolidShader().fillUniformData(
@@ -342,7 +344,7 @@ public class LodRendererEvents {
//float nearClip = DhApi.Delayed.renderProxy.getNearClipPlaneDistanceInBlocks(partialTicks); //float nearClip = DhApi.Delayed.renderProxy.getNearClipPlaneDistanceInBlocks(partialTicks);
//float farClip = (float) ((double) (DHCompatInternal.getDhBlockRenderDistance() + 512) * Math.sqrt(2.0)); //float farClip = (float) ((double) (DHCompatInternal.getDhBlockRenderDistance() + 512) * Math.sqrt(2.0));
GL_STATE_MANAGER.disableCullFace(); GL_STATE_MANAGER.disableCullFace();
//Iris.logger.info("event near clip: "+event.value.nearClipPlane+" event far clip: "+event.value.farClipPlane+ //IRIS_LOGGER.info("event near clip: "+event.value.nearClipPlane+" event far clip: "+event.value.farClipPlane+
// " \niris near clip: "+nearClip+" iris far clip: "+farClip); // " \niris near clip: "+nearClip+" iris far clip: "+farClip);
instance.getTranslucentShader().fillUniformData( instance.getTranslucentShader().fillUniformData(
@@ -2,6 +2,7 @@ package net.irisshaders.iris.compat.sodium.impl.options;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import net.irisshaders.iris.Iris; import net.irisshaders.iris.Iris;
import net.irisshaders.iris.IrisCommon;
import net.irisshaders.iris.config.IrisConfig; import net.irisshaders.iris.config.IrisConfig;
import net.irisshaders.iris.gui.option.IrisVideoSettings; import net.irisshaders.iris.gui.option.IrisVideoSettings;
import net.irisshaders.iris.pathways.colorspace.ColorSpace; import net.irisshaders.iris.pathways.colorspace.ColorSpace;
@@ -19,11 +20,13 @@ import org.embeddedt.embeddium.impl.gui.SodiumGameOptionPages;
import java.io.IOException; import java.io.IOException;
import java.util.Set; import java.util.Set;
import static net.irisshaders.iris.IrisLogging.IRIS_LOGGER;
public class IrisSodiumOptions { public class IrisSodiumOptions {
private static final OptionStorage<IrisConfig> irisOpts = new OptionStorage<IrisConfig>() { private static final OptionStorage<IrisConfig> irisOpts = new OptionStorage<IrisConfig>() {
@Override @Override
public IrisConfig getData() { public IrisConfig getData() {
return Iris.getIrisConfig(); return IrisCommon.getIrisConfig();
} }
@Override @Override
@@ -35,7 +38,7 @@ public class IrisSodiumOptions {
Iris.reload(); Iris.reload();
} }
} catch (IOException e) { } catch (IOException e) {
Iris.logger.error("Error saving config", e); IRIS_LOGGER.error("Error saving config", e);
} }
} }
}; };
@@ -78,7 +81,7 @@ public class IrisSodiumOptions {
.setBinding((options, value) -> { .setBinding((options, value) -> {
IrisVideoSettings.shadowDistance = value; IrisVideoSettings.shadowDistance = value;
try { try {
Iris.getIrisConfig().save(); IrisCommon.getIrisConfig().save();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
@@ -98,7 +101,7 @@ public class IrisSodiumOptions {
.setBinding((options, value) -> { .setBinding((options, value) -> {
IrisVideoSettings.colorSpace = value; IrisVideoSettings.colorSpace = value;
try { try {
Iris.getIrisConfig().save(); IrisCommon.getIrisConfig().save();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
@@ -3,7 +3,7 @@ package net.irisshaders.iris.compat.sodium.impl.vertex_format.terrain_xhfp;
import it.unimi.dsi.fastutil.objects.Object2IntMap; import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2IntMaps; import it.unimi.dsi.fastutil.objects.Object2IntMaps;
import net.irisshaders.iris.shaderpack.materialmap.FallbackTextureMaterials; import net.irisshaders.iris.shaderpack.materialmap.FallbackTextureMaterials;
import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; import net.irisshaders.iris.shaderpack.materialmap.ModernWorldRenderingSettings;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.TextureAtlas; import net.minecraft.client.renderer.texture.TextureAtlas;
import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.texture.TextureAtlasSprite;
@@ -47,12 +47,12 @@ public class XHFPTerrainVertex implements ChunkVertexEncoder, ContextAwareChunkV
private boolean ignoreMidBlock; private boolean ignoreMidBlock;
private byte lightValue; private byte lightValue;
private final Object2IntMap<BlockState> blockStateIds = Objects.requireNonNullElse(WorldRenderingSettings.INSTANCE.getBlockStateIds(), Object2IntMaps.emptyMap()); private final Object2IntMap<BlockState> blockStateIds = Objects.requireNonNullElse(ModernWorldRenderingSettings.INSTANCE.getBlockStateIds(), Object2IntMaps.emptyMap());
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
private final TextureAtlas blocksAtlas = (TextureAtlas)Minecraft.getInstance().getTextureManager().getTexture(TextureAtlas.LOCATION_BLOCKS); private final TextureAtlas blocksAtlas = (TextureAtlas)Minecraft.getInstance().getTextureManager().getTexture(TextureAtlas.LOCATION_BLOCKS);
private final FallbackTextureMaterials fallbackMaterials = WorldRenderingSettings.INSTANCE.getFallbackTextureMaterialMapping(); private final FallbackTextureMaterials fallbackMaterials = ModernWorldRenderingSettings.INSTANCE.getFallbackTextureMaterialMapping();
private final ChunkVertexEncoder baseEncoder = XHFPModelVertexType.BASE_VERTEX_TYPE.getEncoder(); private final ChunkVertexEncoder baseEncoder = XHFPModelVertexType.BASE_VERTEX_TYPE.getEncoder();
@@ -10,7 +10,6 @@ import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderOptions;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexType; import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexType;
import net.irisshaders.iris.compat.sodium.impl.shader_overrides.IrisChunkProgramOverrides; import net.irisshaders.iris.compat.sodium.impl.shader_overrides.IrisChunkProgramOverrides;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Inject;
@@ -0,0 +1,50 @@
package net.irisshaders.iris.gl.state;
import com.mojang.blaze3d.vertex.DefaultVertexFormat;
import com.mojang.blaze3d.vertex.VertexFormat;
public class ShaderAttributeInputsBuilder {
private boolean color;
private boolean tex;
private boolean overlay;
private boolean light;
private boolean normal;
private boolean newLines;
private boolean glint;
private boolean text;
public ShaderAttributeInputsBuilder(VertexFormat format, boolean isFullbright, boolean isLines, boolean glint, boolean text) {
if (format == DefaultVertexFormat.POSITION_COLOR_NORMAL && !isLines) {
newLines = true;
}
this.text = text;
this.glint = glint;
format.getElementAttributeNames().forEach(name -> {
if ("Color".equals(name)) {
color = true;
}
if ("UV0".equals(name)) {
tex = true;
}
if ("UV1".equals(name)) {
overlay = true;
}
if ("UV2".equals(name) && !isFullbright) {
light = true;
}
if ("Normal".equals(name)) {
normal = true;
}
});
}
public ShaderAttributeInputs build() {
return new ShaderAttributeInputs(color, tex, overlay, light, normal, newLines, glint, text);
}
}
@@ -38,6 +38,8 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Properties; import java.util.Properties;
import static net.irisshaders.iris.IrisLogging.IRIS_LOGGER;
public class ShaderPackOptionList extends IrisContainerObjectSelectionList<ShaderPackOptionList.BaseEntry> { public class ShaderPackOptionList extends IrisContainerObjectSelectionList<ShaderPackOptionList.BaseEntry> {
private final List<AbstractElementWidget<?>> elementWidgets = new ArrayList<>(); private final List<AbstractElementWidget<?>> elementWidgets = new ArrayList<>();
private final ShaderPackScreen screen; private final ShaderPackScreen screen;
@@ -249,7 +251,7 @@ public class ShaderPackOptionList extends IrisContainerObjectSelectionList<Shade
private boolean resetButtonClicked(IrisElementRow.TextButtonElement button) { private boolean resetButtonClicked(IrisElementRow.TextButtonElement button) {
if (Screen.hasShiftDown()) { if (Screen.hasShiftDown()) {
Iris.resetShaderPackOptionsOnNextReload(); IrisCommon.resetShaderPackOptionsOnNextReload();
this.screen.applyChanges(); this.screen.applyChanges();
GuiUtil.playButtonClickSound(); GuiUtil.playButtonClickSound();
@@ -263,7 +265,7 @@ public class ShaderPackOptionList extends IrisContainerObjectSelectionList<Shade
GuiUtil.playButtonClickSound(); GuiUtil.playButtonClickSound();
// Invalid state to be in // Invalid state to be in
if (!Iris.getCurrentPack().isPresent()) { if (!IrisCommon.getCurrentPack().isPresent()) {
return false; return false;
} }
@@ -284,7 +286,7 @@ public class ShaderPackOptionList extends IrisContainerObjectSelectionList<Shade
"Shader Pack Settings (.txt)", "*.txt") "Shader Pack Settings (.txt)", "*.txt")
.whenComplete((path, err) -> { .whenComplete((path, err) -> {
if (err != null) { if (err != null) {
Iris.logger.error("Error selecting shader settings from file", err); IRIS_LOGGER.error("Error selecting shader settings from file", err);
return; return;
} }
@@ -301,7 +303,7 @@ public class ShaderPackOptionList extends IrisContainerObjectSelectionList<Shade
GuiUtil.playButtonClickSound(); GuiUtil.playButtonClickSound();
// Invalid state to be in // Invalid state to be in
if (!Iris.getCurrentPack().isPresent()) { if (!IrisCommon.getCurrentPack().isPresent()) {
return false; return false;
} }
@@ -320,7 +322,7 @@ public class ShaderPackOptionList extends IrisContainerObjectSelectionList<Shade
"Shader Pack Settings (.txt)", "*.txt") "Shader Pack Settings (.txt)", "*.txt")
.whenComplete((path, err) -> { .whenComplete((path, err) -> {
if (err != null) { if (err != null) {
Iris.logger.error("Error selecting file to export shader settings", err); IRIS_LOGGER.error("Error selecting file to export shader settings", err);
return; return;
} }
@@ -342,7 +344,7 @@ public class ShaderPackOptionList extends IrisContainerObjectSelectionList<Shade
try (OutputStream out = Files.newOutputStream(p)) { try (OutputStream out = Files.newOutputStream(p)) {
toSave.store(out, null); toSave.store(out, null);
} catch (IOException e) { } catch (IOException e) {
Iris.logger.error("Error saving properties to \"" + p + "\"", e); IRIS_LOGGER.error("Error saving properties to \"" + p + "\"", e);
} }
}); });
}); });
@@ -26,6 +26,8 @@ import java.nio.file.WatchService;
import java.util.List; import java.util.List;
import java.util.function.Function; import java.util.function.Function;
import static net.irisshaders.iris.IrisLogging.IRIS_LOGGER;
public class ShaderPackSelectionList extends IrisObjectSelectionList<ShaderPackSelectionList.BaseEntry> { public class ShaderPackSelectionList extends IrisObjectSelectionList<ShaderPackSelectionList.BaseEntry> {
private static final Component PACK_LIST_LABEL = Component.translatable("pack.iris.list.label").withStyle(ChatFormatting.ITALIC, ChatFormatting.GRAY); private static final Component PACK_LIST_LABEL = Component.translatable("pack.iris.list.label").withStyle(ChatFormatting.ITALIC, ChatFormatting.GRAY);
@@ -46,7 +48,7 @@ public class ShaderPackSelectionList extends IrisObjectSelectionList<ShaderPackS
WatchService watcher1; WatchService watcher1;
this.screen = screen; this.screen = screen;
this.topButtonRow = new TopButtonRowEntry(this, Iris.getIrisConfig().areShadersEnabled()); this.topButtonRow = new TopButtonRowEntry(this, IrisCommon.getIrisConfig().areShadersEnabled());
try { try {
watcher1 = FileSystems.getDefault().newWatchService(); watcher1 = FileSystems.getDefault().newWatchService();
key1 = IrisCommon.getShaderpacksDirectory().register(watcher1, key1 = IrisCommon.getShaderpacksDirectory().register(watcher1,
@@ -55,7 +57,7 @@ public class ShaderPackSelectionList extends IrisObjectSelectionList<ShaderPackS
StandardWatchEventKinds.ENTRY_DELETE); StandardWatchEventKinds.ENTRY_DELETE);
keyValid = true; keyValid = true;
} catch (IOException e) { } catch (IOException e) {
Iris.logger.error("Couldn't register file watcher!", e); IRIS_LOGGER.error("Couldn't register file watcher!", e);
watcher1 = null; watcher1 = null;
key1 = null; key1 = null;
keyValid = false; keyValid = false;
@@ -119,7 +121,7 @@ public class ShaderPackSelectionList extends IrisObjectSelectionList<ShaderPackS
try { try {
names = Iris.getShaderpacksDirectoryManager().enumerate(); names = Iris.getShaderpacksDirectoryManager().enumerate();
} catch (Throwable e) { } catch (Throwable e) {
Iris.logger.error("Error reading files while constructing selection UI", e); IRIS_LOGGER.error("Error reading files while constructing selection UI", e);
// Not translating this since it's going to be seen very rarely, // Not translating this since it's going to be seen very rarely,
// We're just trying to get more information on a seemingly untraceable bug: // We're just trying to get more information on a seemingly untraceable bug:
@@ -159,7 +161,7 @@ public class ShaderPackSelectionList extends IrisObjectSelectionList<ShaderPackS
public void addPackEntry(int index, String name) { public void addPackEntry(int index, String name) {
ShaderPackEntry entry = new ShaderPackEntry(index, this, name); ShaderPackEntry entry = new ShaderPackEntry(index, this, name);
Iris.getIrisConfig().getShaderPackName().ifPresent(currentPackName -> { IrisCommon.getIrisConfig().getShaderPackName().ifPresent(currentPackName -> {
if (name.equals(currentPackName)) { if (name.equals(currentPackName)) {
setSelected(entry); setSelected(entry);
setFocused(entry); setFocused(entry);
@@ -1,6 +1,6 @@
package net.irisshaders.iris.gui.element.widget; package net.irisshaders.iris.gui.element.widget;
import net.irisshaders.iris.Iris; import net.irisshaders.iris.IrisCommon;
import net.irisshaders.iris.gui.GuiUtil; import net.irisshaders.iris.gui.GuiUtil;
import net.irisshaders.iris.gui.NavigationController; import net.irisshaders.iris.gui.NavigationController;
import net.irisshaders.iris.gui.screen.ShaderPackScreen; import net.irisshaders.iris.gui.screen.ShaderPackScreen;
@@ -82,7 +82,7 @@ public class BooleanElementWidget extends BaseOptionElementWidget<OptionMenuBool
} }
private void queue() { private void queue() {
Iris.getShaderPackOptionQueue().put(this.option.getName(), this.getValue()); IrisCommon.getShaderPackOptionQueue().put(this.option.getName(), this.getValue());
} }
@Override @Override
@@ -1,6 +1,6 @@
package net.irisshaders.iris.gui.element.widget; package net.irisshaders.iris.gui.element.widget;
import net.irisshaders.iris.Iris; import net.irisshaders.iris.IrisCommon;
import net.irisshaders.iris.gui.GuiUtil; import net.irisshaders.iris.gui.GuiUtil;
import net.irisshaders.iris.gui.NavigationController; import net.irisshaders.iris.gui.NavigationController;
import net.irisshaders.iris.gui.screen.ShaderPackScreen; import net.irisshaders.iris.gui.screen.ShaderPackScreen;
@@ -75,7 +75,7 @@ public class ProfileElementWidget extends BaseOptionElementWidget<OptionMenuProf
return false; return false;
} }
Iris.queueShaderPackOptionsFromProfile(this.next); IrisCommon.queueShaderPackOptionsFromProfile(this.next);
return true; return true;
} }
@@ -86,7 +86,7 @@ public class ProfileElementWidget extends BaseOptionElementWidget<OptionMenuProf
return false; return false;
} }
Iris.queueShaderPackOptionsFromProfile(this.previous); IrisCommon.queueShaderPackOptionsFromProfile(this.previous);
return true; return true;
} }
@@ -1,6 +1,6 @@
package net.irisshaders.iris.gui.element.widget; package net.irisshaders.iris.gui.element.widget;
import net.irisshaders.iris.Iris; import net.irisshaders.iris.IrisCommon;
import net.irisshaders.iris.gui.GuiUtil; import net.irisshaders.iris.gui.GuiUtil;
import net.irisshaders.iris.gui.NavigationController; import net.irisshaders.iris.gui.NavigationController;
import net.irisshaders.iris.gui.screen.ShaderPackScreen; import net.irisshaders.iris.gui.screen.ShaderPackScreen;
@@ -89,7 +89,7 @@ public class StringElementWidget extends BaseOptionElementWidget<OptionMenuStrin
} }
protected void queue() { protected void queue() {
Iris.getShaderPackOptionQueue().put(this.option.getName(), this.getValue()); IrisCommon.getShaderPackOptionQueue().put(this.option.getName(), this.getValue());
} }
@Override @Override
Loaded 100 of 150 files, more files were not shown because too many files have changed in this diff. Show more