Compare commits

...
Author SHA1 Message Date
Kotmatross 1dd98978ad [Hotfix] Fix NTM:Space mixin targets for X5593_H261 (#1356) 2026-02-02 10:02:36 -08:00
Jason Mitchell dae986eb0b Fix crash with clearBufferSubData (#1355) 2026-02-01 12:41:53 -08:00
Jason Mitchell 5fdf84edd0 Camera and Menu Tweaks (#1354) 2026-02-01 12:14:32 -08:00
Jason Mitchell b19d023c11 Bump gtnhgradle 2026-02-01 09:26:19 -08:00
Jason Mitchell 41eafbd151 GLSL Downgrading (#1348) 2026-01-31 13:23:02 -08:00
sisyphussy dd970b4c6a Fix nested display lists rendering twice (#1349)
* Fix nested display lists rendering twice

* cleanup
2026-01-31 05:45:48 -08:00
Eclipse-Sol f79ad7f22a Fix arrows inheriting item material IDs (#1347) 2026-01-30 18:35:04 -08:00
Jason Mitchell 6947ffa3e2 Add IS_IRIS define as an option. 2026-01-30 18:10:27 -08:00
Jason Mitchell 969d2c3710 Backports tessellation shader support, safe zone shadow culling, and shader pack rendering directives. 2026-01-30 18:10:27 -08:00
Jason Mitchell c5988d29c3 Fix camera position and nether portal 3rd party rendering 2026-01-30 18:10:27 -08:00
Jason Mitchell dc68c2c265 Fix end portal w/ Shaders 2026-01-30 18:10:27 -08:00
Jason Mitchell 51533a81ec Misc Shaderpack loading fixes (#1343) 2026-01-30 14:53:41 -08:00
Eclipse-Sol 90eabb5d40 Add hardcoded entities and player_cape (#1327) 2026-01-30 14:53:26 -08:00
sisyphussyandJason Mitchell 74843cb1f9 Glc redirects (#1340)
Co-authored-by: Jason Mitchell <[email protected]>
2026-01-30 14:50:54 -08:00
Death Fuel 5e0344a529 remove unnecessary resource refresh (#1342) 2026-01-30 14:40:51 -08:00
Jason Mitchell 3cdd934987 First pass at setup/begin pass support (#1335) 2026-01-29 07:53:04 -08:00
Léa Gris 9d90ff137c fix(render): adapt hodgepodge fixBottomFaceUV (#1334) 2026-01-28 10:55:53 -08:00
Jason Mitchell bee9541797 Shadow Compute Shaders (#1333) 2026-01-28 00:03:04 -08:00
Jason Mitchell b75a5d8f7d Ya that won't work (#1332) 2026-01-27 15:32:42 -08:00
Jason Mitchell 8d3ab41c53 Use entity position instead of camera pos (#1330) 2026-01-26 22:19:54 -08:00
Jason Mitchell 48d032e654 Tweaks (#1329) 2026-01-26 21:08:09 -08:00
sisyphussy 1968914582 Fix hud flickering (#1325) 2026-01-26 10:19:49 -08:00
Guus Waals a70bd76ff3 Fix deadlock in CTMUtils (#1189) 2026-01-26 10:08:32 -08:00
mist475 db919b5f37 add biomeDictionary and lotr compat to BiomeUniforms (#1324) 2026-01-26 09:58:08 -08:00
MalTeeez cde47ea423 Add option to disable f3 additions (#1308) 2026-01-26 09:56:11 -08:00
Jason Mitchell 5ef6cb11c0 Don't double check infinite bounds (#1321) 2026-01-25 21:13:14 -08:00
Eclipse-Sol b7015bf10e Adds "name_tag" feature (#1318) 2026-01-25 20:00:49 -08:00
Jason Mitchell 46602ab921 Chunk Thread Saftey (#1320) 2026-01-25 19:58:33 -08:00
Jason Mitchell 63e9fa0df1 Dynamic Lights Improvements (#1319) 2026-01-25 19:07:11 -08:00
Eclipse-Sol dcea970a77 Various Shader Fixes (#1315) 2026-01-25 16:56:54 -08:00
Jason Mitchell b29240d6da Use the proper blockAccess on the main thread (#1317) 2026-01-25 16:55:45 -08:00
Jason Mitchell 9d5a02ed21 Optimize TileEntities (#1314) 2026-01-25 10:54:45 -08:00
Jason Mitchell b454483aae Add a nvidia workarounds from celeritas (#1286) 2026-01-24 18:52:52 -08:00
Jason Mitchell 72b13543c6 AABB Caching (#1309) 2026-01-24 18:52:22 -08:00
Jason Mitchell 36d98fcb22 Fix currentRenderedItemId for ItemBlocks (#1307) 2026-01-24 12:43:03 -08:00
Jason Mitchell 44c5b9617a Lighting fixes (#1306) 2026-01-24 12:23:59 -08:00
Kotmatross f3f1677db8 [Shaders] Fix NTM:Space sunset not rendering {2.0 regression} (#1275) 2026-01-24 19:47:30 +00:00
Jason Mitchell d396b611ad Buffer fixes (#1304) 2026-01-24 11:30:05 -08:00
Jason Mitchell 08f4c0f9db Make feature flag defines available in shader.properties preprocessing (#1303) 2026-01-24 10:10:13 -08:00
Eclipse-Sol 50b0d22dc2 Fix entity material handling. (#1298) 2026-01-23 20:24:27 -08:00
140 changed files with 4631 additions and 1489 deletions

No files matched your search

+4 -3
View File
@@ -71,9 +71,9 @@ dependencies {
// Iris Shaders
compileOnly('org.jetbrains:annotations:26.0.2')
api("com.github.GTNewHorizons:GTNHLib:0.9.0:dev")
api("com.github.GTNewHorizons:GTNHLib:0.9.6:dev")
shadowImplementation("org.anarres:jcpp:1.4.14") // Apache 2.0
shadowImplementation("org.taumc:glsl-transformation-lib:0.2.0-25.g3a943bb") {
shadowImplementation("org.taumc:glsl-transformation-lib:0.2.0-26.g5ee7d96-GTNH") {
exclude module: "antlr4" // we only want to shadow the runtime module
}
shadowImplementation("org.antlr:antlr4-runtime:4.13.2")
@@ -110,11 +110,12 @@ dependencies {
compileOnly("com.github.GTNewHorizons:NotEnoughIds:2.1.10:dev") // Mixin Version
compileOnly("com.github.GTNewHorizons:NotEnoughIds-Legacy:1.4.7:dev") // ASM Version
compileOnly(rfg.deobf("curse.maven:ntm-space-1121235:6974420"))
compileOnly(rfg.deobf("maven.modrinth:ntmspace:X5593_H261"))
compileOnly(rfg.deobf("curse.maven:campfirebackport-387444:4611675"))
compileOnly(rfg.deobf("curse.maven:xaeros-minimap-263420:5060684"))
compileOnly(rfg.deobf("curse.maven:security-craft-64760:2818228"))
compileOnly(rfg.deobf("curse.maven:et-futurum-requiem-441392:5873837"))
// runtimeOnlyNonPublishable("com.github.GTNewHorizons:CoreTweaks:0.3.3.6-GTNH")
// For testing alternative splash screens, can be sourced from https://github.com/MalTeeez/ModernSplash/releases
+1 -1
View File
@@ -16,5 +16,5 @@ pluginManagement {
}
plugins {
id("com.gtnewhorizons.gtnhsettingsconvention") version("2.0.13")
id("com.gtnewhorizons.gtnhsettingsconvention") version("2.0.19")
}
@@ -1,19 +1,21 @@
package com.gtnewhorizons.angelica;
import static com.gtnewhorizons.angelica.AngelicaMod.MOD_ID;
import com.gtnewhorizons.angelica.common.BlockError;
import com.gtnewhorizons.angelica.compat.ModStatus;
import com.gtnewhorizons.angelica.config.ConfigMigrator;
import com.gtnewhorizons.angelica.proxy.CommonProxy;
import com.gtnewhorizons.angelica.utils.AnimationMode;
import com.gtnewhorizons.angelica.utils.ManagedEnum;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.SidedProxy;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import me.jellysquid.mods.sodium.client.gui.SodiumGameOptions;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import static com.gtnewhorizons.angelica.AngelicaMod.MOD_ID;
@Mod(
modid = MOD_ID,
@@ -33,6 +35,15 @@ public class AngelicaMod {
public static final String MOD_ID = "angelica";
public static final Logger LOGGER = LogManager.getLogger("Angelica");
private static SodiumGameOptions CONFIG;
public static SodiumGameOptions options() {
if (CONFIG == null) {
CONFIG = SodiumGameOptions.load(ConfigMigrator.handleConfigMigration("angelica-options.json"));
}
return CONFIG;
}
@SidedProxy(clientSide = "com.gtnewhorizons.angelica.proxy.ClientProxy", serverSide = "com.gtnewhorizons.angelica.proxy.CommonProxy")
public static CommonProxy proxy;
@@ -72,7 +72,6 @@ public class FontStrategist {
DefaultResourcePack fontResourcePack = new DefaultResourcePack(packMap);
List defaultResourcePacks = ((ResourceAccessor) Minecraft.getMinecraft()).angelica$getDefaultResourcePacks();
defaultResourcePacks.add(fontResourcePack);
Minecraft.getMinecraft().refreshResources();
}
/**
@@ -0,0 +1,55 @@
package com.gtnewhorizons.angelica.compat;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.lwjgl.opengl.ARBDebugOutput;
import org.lwjgl.opengl.GL11;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
/**
* Checks for known problematic driver configurations and applies workarounds. Adapted from Embeddium/Sodium's LateDriverScanner.
*
* <p>The NVIDIA workaround can be disabled via: {@code -Dangelica.disableNvidiaWorkaround=true}
*/
public class DriverCompatabilityCheck {
private static final Logger LOGGER = LogManager.getLogger("Angelica");
private static final boolean DISABLE_NVIDIA_WORKAROUND = Boolean.getBoolean("angelica.disableNvidiaWorkaround");
/**
* Should be called after GL context is created and GLStateManager is initialized.
*/
public static void checkDriverCompatibility() {
final String vendor = GL11.glGetString(GL11.GL_VENDOR);
final String renderer = GL11.glGetString(GL11.GL_RENDERER);
final String version = GL11.glGetString(GL11.GL_VERSION);
LOGGER.info("OpenGL Vendor: {}", vendor);
LOGGER.info("OpenGL Renderer: {}", renderer);
LOGGER.info("OpenGL Version: {}", version);
if (vendor != null && vendor.contains("NVIDIA")) {
if (DISABLE_NVIDIA_WORKAROUND) {
LOGGER.info("NVIDIA workaround disabled via -Dangelica.disableNvidiaWorkaround=true");
} else {
applyNvidiaWorkaround();
}
}
}
/**
* https://github.com/godotengine/godot/issues/33969#issuecomment-917846774
* Attempt to force the driver to disable its submission thread by enabling synchronous debug output.
* This usually suppresses bad behavior from NVIDIA's "Threaded Optimizations" feature.
*/
private static void applyNvidiaWorkaround() {
if (!GLStateManager.capabilities.GL_ARB_debug_output) {
LOGGER.warn("Cannot apply NVIDIA workaround: ARB_debug_output not available");
return;
}
LOGGER.info("Enabling workaround for NVIDIA threaded optimizations");
GL11.glEnable(ARBDebugOutput.GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
}
}
@@ -1,5 +1,6 @@
package com.gtnewhorizons.angelica.compat.iris;
import com.gtnewhorizons.angelica.compat.ModStatus;
import net.coderbot.iris.parsing.BiomeCategories;
import net.minecraft.world.biome.BiomeGenBase;
@@ -8,7 +9,7 @@ import java.util.Map;
/**
* Detects and categorizes biomes from popular modded biome mods using cached class checks.
* Currently supports: BiomesOPlenty (BOP), Realistic World Gen (RWG)
* Currently supports: BiomesOPlenty (BOP), Realistic World Gen (RWG), lotr (b36.15)
*/
public class ModdedBiomeDetector {
private static boolean initialized = false;
@@ -23,12 +24,15 @@ public class ModdedBiomeDetector {
// LinkedHashMap maintains insertion order for deterministic behavior
private static final Map<Class<?>, BiomeCategories> rwgClassMap = new LinkedHashMap<>();
private static Class<?> lotrBiomeClass = null;
private static synchronized void initialize() {
if (initialized) return;
initialized = true;
initializeBOP();
initializeRWG();
initializeLOTR();
}
private static void initializeBOP() {
@@ -59,6 +63,16 @@ public class ModdedBiomeDetector {
tryAddRWGClass("rwg.biomes.base.BaseBiomeSnowForest", BiomeCategories.TAIGA); // Snow forests are taiga
}
private static void initializeLOTR() {
if (ModStatus.isLotrLoaded) {
try {
lotrBiomeClass = Class.forName("lotr.common.world.biome.LOTRBiome");
} catch (ClassNotFoundException ignored) {
// lotr not installed
}
}
}
private static void tryAddRWGClass(String className, BiomeCategories category) {
try {
final Class<?> clazz = Class.forName(className);
@@ -91,12 +105,64 @@ public class ModdedBiomeDetector {
// fall through to name/property-based detection
// Realistic World Gen detection
for (Map.Entry<Class<?>, BiomeCategories> entry : rwgClassMap.entrySet()) {
if (entry.getKey().isInstance(biome)) {
return entry.getValue();
if (biome.getBiomeClass().getName().contains("rwg.biomes")) {
for (Map.Entry<Class<?>, BiomeCategories> entry : rwgClassMap.entrySet()) {
if (entry.getKey().isInstance(biome)) {
return entry.getValue();
}
}
}
// lotr
if (lotrBiomeClass!= null && lotrBiomeClass.isInstance(biome)) {
return detectLOTRBiome(biome);
}
return null;
}
private static BiomeCategories detectLOTRBiome(BiomeGenBase biome) {
return switch (biome.biomeName) {
case "river", "farHaradJungleLake", "lake" -> BiomeCategories.RIVER;
case "rohan", "rivendell", "rhunIsland", "rhunLandHills", "rhunLandSteppe", "rhunLand", "andrast",
"blackrootVale", "lamedon", "imlothMelui", "towerHills", "dorwinion", "dale", "shireMoors", "wold",
"anduinVale", "rhun", "lebennin", "pertorogwaith", "breeland", "island", "pinnathGelin",
"minhiriath", "pelennor", "adornland", "nanCurunir", "ithilienWasteland", "fangornClearing",
"barrowDowns", "dorEnErnilHills", "dorEnErnil", "nurn", "wilderland", "eastBight", "lindon",
"eregion", "enedwaith", "meneltarma", "anduinHills", "eriador", "angle", "loneLandsHills",
"loneLands", "pelargir", "rohanUrukHighlands", "celebrant", "gondor", "shire", "nurnen", "farHarad" ->
BiomeCategories.PLAINS;
case "mistyMountains", "windMountains", "farHaradVolcano", "redMountains", "haradMountains",
"angmarMountains", "blueMountains", "greyMountains", "whiteMountains", "mordorMountains" ->
BiomeCategories.MOUNTAIN;
case "shireWoodlands", "rhunIslandForest", "rhunRedForest", "pukel", "lossarnach", "gulfHaradForest",
"nearHaradFertileForest", "dolGuldur", "rhunForest", "tauredainClearing", "umbarForest",
"farHaradForest", "chetwood", "woodlandRealmHills", "mirkwoodNorth", "whiteDowns", "ithilienHills",
"gondorWoodlands", "rohanWoodlands", "fangornWasteland", "mirkwoodMountains", "lindonWoodlands",
"lothlorienEdge", "erynVorn", "oldForest", "fangorn", "dunland", "ithilien", "mirkwoodCorrupted",
"woodlandRealm", "trollshaws", "lothlorien", "farHaradKanuka" -> BiomeCategories.FOREST;
case "mordor", "lastDesert", "harnedor", "easternDesolation", "morgulVale", "gorgoroth", "udun",
"nearHaradRedDesert", "nearHaradSemiDesert", "lostladen",
"nearHaradHills", "nearHarad", "nanUngol", "dagorlad", "brownLands" -> BiomeCategories.DESERT;
case "ironHills", "rivendellHills", "windMountainsFoothills", "lamedonHills", "redMountainsFoothills",
"tolfalas", "dorwinionHills", "whiteMountainsFoothills", "blueMountainsFoothills",
"greyMountainsFoothills", "mistyMountainsFoothills", "erebor", "angmar", "eriadorDowns",
"ettenmoors", "emynMuil" -> BiomeCategories.EXTREME_HILLS;
case "deadMarshes", "shireMarshes", "farHaradMangrove", "farHaradSwamp", "swanfleet", "nindalf",
"longMarshes", "entwashMouth", "nurnMarshes", "gladdenFields", "midgewater", "anduinMouth" ->
BiomeCategories.SWAMP;
case "harondor", "nearHaradOasis", "nearHaradRiverbank", "farHaradBushlandHills", "farHaradBushland",
"gulfHarad", "nearHaradFertile", "umbarHills", "umbar", "farHaradAridHills", "farHaradArid" ->
BiomeCategories.SAVANNA;
case "ocean" -> BiomeCategories.OCEAN;
case "forodwaith", "forodwaithGlacier", "tundra", "forodwaithMountains" -> BiomeCategories.ICY;
case "lindonCoast", "beachWhite", "farHaradCoast", "forodwaithCoast", "beachGravel", "beach" ->
BiomeCategories.BEACH;
case "coldfells", "wilderlandNorth", "taiga" -> BiomeCategories.TAIGA;
case "farHaradJungle", "halfTrollForest", "farHaradJungleMountains",
"farHaradCloudForest", "farHaradJungleEdge" -> BiomeCategories.JUNGLE;
case "utumno" -> BiomeCategories.NONE;
default -> null;
};
}
}
@@ -19,6 +19,7 @@ public class Camera {
public static final Camera INSTANCE = new Camera();
private final Vector3d pos = new Vector3d();
private final Vector3d entityPos = new Vector3d();
private final BlockPos blockPos = new BlockPos();
private final Vector3f offset = new Vector3f();
private final Matrix4f inverseModelView = new Matrix4f();
@@ -42,12 +43,14 @@ public class Camera {
this.partialTicks = partialTicks;
this.entity = entity;
// Entity position (interpolated, at feet level)
// Entity position (interpolated, at eye level)
final double entityX = entity.lastTickPosX + (entity.posX - entity.lastTickPosX) * partialTicks;
final double entityY = entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * partialTicks;
final double entityZ = entity.lastTickPosZ + (entity.posZ - entity.lastTickPosZ) * partialTicks;
final double eyeHeight = entity.getEyeHeight();
entityPos.set(entityX, entityY + eyeHeight, entityZ);
thirdPerson = Minecraft.getMinecraft().gameSettings.thirdPersonView > 0;
final double camX, camY, camZ;
@@ -1,7 +1,7 @@
package com.gtnewhorizons.angelica.compat.toremove;
import com.gtnewhorizons.angelica.AngelicaMod;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import me.jellysquid.mods.sodium.client.SodiumClientMod;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.renderer.texture.TextureMap;
@@ -147,7 +147,7 @@ public abstract class RenderPhase {
FOG = new Fog("fog", () -> {
// Unclear what this should do
// BackgroundRenderer.setFogBlack(), also levelFogColor()
SodiumClientMod.LOGGER.debug("Fog - Not setting level fog color");
AngelicaMod.LOGGER.debug("Fog - Not setting level fog color");
GLStateManager.enableFog();
}, GLStateManager::disableFog);
BLACK_FOG = new Fog("black_fog", () -> {
@@ -156,7 +156,7 @@ public abstract class RenderPhase {
}, () -> {
// Unclear what this should do
// BackgroundRenderer.setFogBlack(), also levelFogColor()
SodiumClientMod.LOGGER.debug("Fog - Not setting level fog color");
AngelicaMod.LOGGER.debug("Fog - Not setting level fog color");
GLStateManager.disableFog();
});
MAIN_TARGET = new Target("main_target", () -> {
@@ -164,7 +164,7 @@ public abstract class RenderPhase {
});
OUTLINE_TARGET = new Target("outline_target", () -> {
// TODO: Sodium
SodiumClientMod.LOGGER.debug("NOT enabling the entity outline framebuffer");
AngelicaMod.LOGGER.debug("NOT enabling the entity outline framebuffer");
//MinecraftClient.getInstance().worldRenderer.getEntityOutlinesFramebuffer().beginWrite(false);
}, () -> {
Minecraft.getMinecraft().getFramebuffer().bindFramebuffer(false);
@@ -172,7 +172,7 @@ public abstract class RenderPhase {
TRANSLUCENT_TARGET = new Target("translucent_target", () -> {
if (Minecraft.isFancyGraphicsEnabled()) {
// TODO: Sodium
SodiumClientMod.LOGGER.debug("NOT enabling the translucent framebuffer");
AngelicaMod.LOGGER.debug("NOT enabling the translucent framebuffer");
// MinecraftClient.getInstance().worldRenderer.getTranslucentFramebuffer().beginWrite(false);
}
@@ -345,7 +345,7 @@ public abstract class RenderPhase {
super("lightmap", () -> {
if (lightmap) {
// TODO: Sodium - LightmapTextureManager
SodiumClientMod.LOGGER.debug("Lightmap - enable (not implemented)");
AngelicaMod.LOGGER.debug("Lightmap - enable (not implemented)");
// throw new RuntimeException("Not Implemented Yet");
// MinecraftClient.getInstance().gameRenderer.getLightmapTextureManager().enable();
@@ -354,7 +354,7 @@ public abstract class RenderPhase {
}, () -> {
if (lightmap) {
// TODO: Sodium - LightmapTextureManager
SodiumClientMod.LOGGER.debug("Lightmap - disable (not implemented)");
AngelicaMod.LOGGER.debug("Lightmap - disable (not implemented)");
// throw new RuntimeException("Not Implemented Yet");
// MinecraftClient.getInstance().gameRenderer.getLightmapTextureManager().disable();
}
@@ -200,7 +200,7 @@ public class AngelicaConfig {
"net.minecraft.block.BlockStairs"
})
public static String[] blockCrackFixBlacklist;
@Config.Comment({"Block classes that have render pass other than 0 but still need to be manipulated.",
"Add a block class here if you see flickering (z-fighting) with fixBlockCrack enabled"
})
@@ -217,8 +217,16 @@ public class AngelicaConfig {
@Config.DefaultBoolean(false)
public static boolean enableHardcodedCustomUniforms;
@Config.Comment("Define IS_IRIS in shader macros.")
@Config.DefaultBoolean(true)
public static boolean defineIsIris;
@Config.Comment("Renders chunks before neighbors are ready. Improves loading at render distance edges, useful for low render distance servers.")
@Config.DefaultBoolean(false)
public static boolean useVanillaChunkTracking;
@Config.Comment("Disables additional F3 information added by Angelica.")
@Config.DefaultBoolean(false)
public static boolean disableF3Additions;
}
@@ -52,6 +52,7 @@ public class DynamicLights {
private static final double MAX_RADIUS_SQUARED = MAX_RADIUS * MAX_RADIUS;
private final Set<IDynamicLightSource> dynamicLightSources = new ObjectOpenHashSet<>();
private final ReentrantReadWriteLock lightSourcesLock = new ReentrantReadWriteLock();
private volatile int lightSourceCount = 0;
private final ChunkRebuildManager chunkRebuildManager = new ChunkRebuildManager();
private long lastUpdate = System.currentTimeMillis();
private int lastUpdateCount = 0;
@@ -70,6 +71,10 @@ public class DynamicLights {
(ShaderForce || !IrisApi.getInstance().isShaderPackInUse());
}
public boolean hasLightSources() {
return lightSourceCount > 0;
}
public static IDynamicLightWorldRenderer getActiveRenderer() {
return activeRenderer;
}
@@ -142,7 +147,9 @@ public class DynamicLights {
public void addLightSource(IDynamicLightSource lightSource) {
this.lightSourcesLock.writeLock().lock();
this.dynamicLightSources.add(lightSource);
if (this.dynamicLightSources.add(lightSource)) {
this.lightSourceCount = this.dynamicLightSources.size();
}
this.lightSourcesLock.writeLock().unlock();
}
@@ -160,6 +167,7 @@ public class DynamicLights {
it = dynamicLightSources.next();
if (it.equals(lightSource)) {
dynamicLightSources.remove();
this.lightSourceCount = this.dynamicLightSources.size();
if (activeRenderer != null)
lightSource.angelica$scheduleTrackedChunksRebuild(activeRenderer);
break;
@@ -183,6 +191,7 @@ public class DynamicLights {
it = dynamicLightSources.next();
if (filter.test(it)) {
dynamicLightSources.remove();
this.lightSourceCount = this.dynamicLightSources.size();
if (activeRenderer != null) {
if (it.angelica$getLuminance() > 0)
it.angelica$resetDynamicLight();
@@ -212,6 +221,7 @@ public class DynamicLights {
it.angelica$scheduleTrackedChunksRebuild(activeRenderer);
}
}
this.lightSourceCount = 0;
this.lightSourcesLock.writeLock().unlock();
}
@@ -1019,11 +1019,22 @@ public class DisplayListManager {
if (currentRecorder != null) {
recordCallList(list);
if (glListMode == GL11.GL_COMPILE) {
return;
if (getListMode() != GL11.GL_COMPILE) {
// Don't record the GL calls, we already recorded glCallList
final CommandRecorder recorder = currentRecorder;
currentRecorder = null;
executeDisplayList(list);
currentRecorder = recorder;
}
return;
}
executeDisplayList(list);
}
private static void executeDisplayList(int list) {
final CompiledDisplayList compiled = displayListCache.get(list);
if (compiled != null) {
final int prevList = currentRenderingList;
@@ -19,9 +19,6 @@ import org.lwjgl.opengl.GL43;
import org.lwjgl.opengl.KHRDebug;
import org.lwjgl.opengl.KHRDebugCallback;
import java.io.PrintStream;
import java.util.function.Consumer;
import static com.gtnewhorizons.angelica.loading.AngelicaTweaker.LOGGER;
import static org.lwjgl.opengl.ARBDebugOutput.glDebugMessageCallbackARB;
@@ -35,20 +32,9 @@ public final class GLDebug {
LOGGER.warn("setupDebugMessageCallback called from non-main thread!");
return 0;
}
return setupDebugMessageCallback(System.err);
return setupDebugMessageCallbackImpl();
}
private static void trace(Consumer<String> output) {
/*
* We can not just use a fixed stacktrace element offset, because some methods
* are intercepted and some are not. So, check the package name.
*/
StackTraceElement[] elems = filterStackTrace(new Throwable(), 4).getStackTrace();
for (StackTraceElement ste : elems) {
output.accept(ste.toString());
}
}
public static Throwable filterStackTrace(Throwable throwable, int offset) {
StackTraceElement[] elems = throwable.getStackTrace();
StackTraceElement[] filtered = new StackTraceElement[elems.length];
@@ -66,36 +52,48 @@ public final class GLDebug {
return throwable;
}
public static void printTrace(PrintStream stream) {
trace(new Consumer<String>() {
boolean first = true;
private static String buildStackTrace() {
StackTraceElement[] elems = filterStackTrace(new Throwable(), 4).getStackTrace();
StringBuilder sb = new StringBuilder();
for (StackTraceElement elem : elems) {
sb.append("\n\t").append(elem.toString());
}
return sb.toString();
}
public void accept(String str) {
if (first) {
printDetail(stream, "Stacktrace", str);
first = false;
} else {
printDetailLine(stream, "Stacktrace", str);
}
}
});
private static void logDebugMessage(int id, String source, String type, String severity, String message) {
String fullMessage = String.format("[GL] %s %s (0x%X) from %s: %s%s", severity, type, id, source, message, buildStackTrace());
if ("HIGH".equals(severity)) {
LOGGER.error(fullMessage);
} else if ("MEDIUM".equals(severity)) {
LOGGER.warn(fullMessage);
} else {
LOGGER.info(fullMessage);
}
}
private static void logDebugMessageAMD(int id, String category, String severity, String message) {
String fullMessage = String.format("[GL] %s %s (0x%X): %s%s", severity, category, id, message, buildStackTrace());
if ("HIGH".equals(severity)) {
LOGGER.error(fullMessage);
} else if ("MEDIUM".equals(severity)) {
LOGGER.warn(fullMessage);
} else {
LOGGER.info(fullMessage);
}
}
/**
* Sets up debug callbacks
* @return 0 for failure, 1 for success, 2 for restart required.
*/
public static int setupDebugMessageCallback(PrintStream stream) {
private static int setupDebugMessageCallbackImpl() {
if (GLStateManager.capabilities.OpenGL43 || GLStateManager.capabilities.GL_KHR_debug) {
LOGGER.info("[GL] Using OpenGL 4.3 for error logging.");
KHRDebugCallback proc = new KHRDebugCallback((source, type, id, severity, message) -> {
stream.println("[LWJGL] OpenGL debug message");
printDetail(stream, "ID", String.format("0x%X", id));
printDetail(stream, "Source", getDebugSource(source));
printDetail(stream, "Type", getDebugType(type));
printDetail(stream, "Severity", getDebugSeverity(severity));
printDetail(stream, "Message", message);
printTrace(stream);
final KHRDebugCallback proc = new KHRDebugCallback((source, type, id, severity, message) -> {
logDebugMessage(id, getDebugSource(source), getDebugType(type), getDebugSeverity(severity), message);
});
GL43.glDebugMessageControl(GL11.GL_DONT_CARE, GL11.GL_DONT_CARE, GL43.GL_DEBUG_SEVERITY_HIGH, null, true);
GL43.glDebugMessageControl(GL11.GL_DONT_CARE, GL11.GL_DONT_CARE, GL43.GL_DEBUG_SEVERITY_MEDIUM, null, false);
@@ -114,14 +112,8 @@ public final class GLDebug {
return 1;
} else if (GLStateManager.capabilities.GL_ARB_debug_output) {
LOGGER.info("[GL] Using ARB_debug_output for error logging.");
ARBDebugOutputCallback proc = new ARBDebugOutputCallback((source, type, id, severity, message) -> {
stream.println("[LWJGL] ARB_debug_output message");
printDetail(stream, "ID", String.format("0x%X", id));
printDetail(stream, "Source", getSourceARB(source));
printDetail(stream, "Type", getTypeARB(type));
printDetail(stream, "Severity", getSeverityARB(severity));
printDetail(stream, "Message", message);
printTrace(stream);
final ARBDebugOutputCallback proc = new ARBDebugOutputCallback((source, type, id, severity, message) -> {
logDebugMessage(id, getSourceARB(source), getTypeARB(type), getSeverityARB(severity), message);
});
ARBDebugOutput.glDebugMessageControlARB(GL11.GL_DONT_CARE, GL11.GL_DONT_CARE, GL43.GL_DEBUG_SEVERITY_HIGH, null, true);
ARBDebugOutput.glDebugMessageControlARB(GL11.GL_DONT_CARE, GL11.GL_DONT_CARE, GL43.GL_DEBUG_SEVERITY_MEDIUM, null, false);
@@ -134,13 +126,8 @@ public final class GLDebug {
return 1;
} else if (GLStateManager.capabilities.GL_AMD_debug_output) {
LOGGER.info("[GL] Using AMD_debug_output for error logging.");
AMDDebugOutputCallback proc = new AMDDebugOutputCallback((id, category, severity, message) -> {
stream.println("[LWJGL] AMD_debug_output message");
printDetail(stream, "ID", String.format("0x%X", id));
printDetail(stream, "Category", getCategoryAMD(category));
printDetail(stream, "Severity", getSeverityAMD(severity));
printDetail(stream, "Message", message);
printTrace(stream);
final AMDDebugOutputCallback proc = new AMDDebugOutputCallback((id, category, severity, message) -> {
logDebugMessageAMD(id, getCategoryAMD(category), getSeverityAMD(severity), message);
});
AMDDebugOutput.glDebugMessageEnableAMD(0, GL43.GL_DEBUG_SEVERITY_HIGH, null, true);
AMDDebugOutput.glDebugMessageEnableAMD(0, GL43.GL_DEBUG_SEVERITY_MEDIUM, null, false);
@@ -176,17 +163,6 @@ public final class GLDebug {
}
}
private static void printDetail(PrintStream stream, String type, String message) {
stream.printf("\t%s: %s\n", type, message);
}
private static void printDetailLine(PrintStream stream, String type, String message) {
stream.append(" ");
for (int i = 0; i < type.length(); i++) {
stream.append(" ");
}
stream.append(message).append("\n");
}
private static String getDebugSource(int source) {
return switch (source) {
@@ -577,6 +553,57 @@ public final class GLDebug {
};
}
public static String getFramebufferStatusName(int status) {
return switch (status) {
case GL30.GL_FRAMEBUFFER_COMPLETE -> "COMPLETE";
case GL30.GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT -> "INCOMPLETE_ATTACHMENT";
case GL30.GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT -> "INCOMPLETE_MISSING_ATTACHMENT";
case GL30.GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER -> "INCOMPLETE_DRAW_BUFFER";
case GL30.GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER -> "INCOMPLETE_READ_BUFFER";
case GL30.GL_FRAMEBUFFER_UNSUPPORTED -> "UNSUPPORTED";
case GL30.GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE -> "INCOMPLETE_MULTISAMPLE";
case 0 -> "NO_FRAMEBUFFER_BOUND";
default -> String.format("UNKNOWN(0x%X)", status);
};
}
public static String getInternalFormatName(int format) {
return switch (format) {
// Basic
case GL11.GL_RGBA -> "RGBA";
case GL11.GL_RGB -> "RGB";
// 8-bit normalized
case GL30.GL_R8 -> "R8";
case GL30.GL_RG8 -> "RG8";
case GL11.GL_RGB8 -> "RGB8";
case GL11.GL_RGBA8 -> "RGBA8";
// 8-bit signed normalized
case 0x8F94 -> "R8_SNORM";
case 0x8F95 -> "RG8_SNORM";
case 0x8F96 -> "RGB8_SNORM";
case 0x8F97 -> "RGBA8_SNORM";
// 16-bit normalized
case GL30.GL_R16 -> "R16";
case GL30.GL_RG16 -> "RG16";
case GL11.GL_RGB16 -> "RGB16";
case GL11.GL_RGBA16 -> "RGBA16";
// 16-bit float
case GL30.GL_R16F -> "R16F";
case GL30.GL_RG16F -> "RG16F";
case GL30.GL_RGB16F -> "RGB16F";
case GL30.GL_RGBA16F -> "RGBA16F";
// 32-bit float
case GL30.GL_R32F -> "R32F";
case GL30.GL_RG32F -> "RG32F";
case GL30.GL_RGB32F -> "RGB32F";
case GL30.GL_RGBA32F -> "RGBA32F";
// Packed
case GL30.GL_R11F_G11F_B10F -> "R11F_G11F_B10F";
case GL11.GL_RGB10_A2 -> "RGB10_A2";
default -> String.format("0x%X", format);
};
}
private static DebugState debugState;
private interface DebugState {
@@ -4,6 +4,7 @@ import com.gtnewhorizons.angelica.glsm.dsa.DSAARB;
import com.gtnewhorizons.angelica.glsm.dsa.DSAAccess;
import com.gtnewhorizons.angelica.glsm.dsa.DSACore;
import com.gtnewhorizons.angelica.glsm.dsa.DSAUnsupported;
import com.gtnewhorizons.angelica.glsm.texture.TextureInfoCache;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.Nullable;
@@ -28,6 +29,8 @@ import org.lwjgl.opengl.GL43;
import org.lwjgl.opengl.GL44;
import org.lwjgl.opengl.NVXGpuMemoryInfo;
import net.coderbot.iris.gl.shader.StandardMacros;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
@@ -44,9 +47,12 @@ public class RenderSystem {
private static boolean supportsSSBO;
private static boolean supportsBufferStorage;
private static boolean supportsClearTexture;
private static boolean supportsTesselation;
private static boolean supportsSamplerObjects;
private static int maxImageUnits;
private static int maxSSBOBindings;
private static int maxGlslVersion;
private static boolean supportsGpuShader4;
// Sampler object state tracking (null if unsupported)
private static int[] samplers;
@@ -73,6 +79,7 @@ public class RenderSystem {
}
supportsCompute = supportsCompute();
supportsTesselation = GLStateManager.capabilities.GL_ARB_tessellation_shader || GLStateManager.capabilities.OpenGL40;
supportsImageLoadStore = GLStateManager.capabilities.OpenGL42 || GLStateManager.capabilities.GL_ARB_shader_image_load_store || GLStateManager.capabilities.GL_EXT_shader_image_load_store;
supportsSSBO = GLStateManager.capabilities.OpenGL43 || GLStateManager.capabilities.GL_ARB_shader_storage_buffer_object;
@@ -110,6 +117,10 @@ public class RenderSystem {
samplers = new int[GL11.glGetInteger(GL20.GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS)];
}
maxGlslVersion = Integer.parseInt(StandardMacros.getGlVersion(GL20.GL_SHADING_LANGUAGE_VERSION));
supportsGpuShader4 = GLStateManager.capabilities.GL_EXT_gpu_shader4;
LOGGER.info("Max GLSL version: {}, GPU Shader4: {}", maxGlslVersion, supportsGpuShader4);
LOGGER.info("Image Load/Store: {}, Max Image Units: {}", supportsImageLoadStore, maxImageUnits);
LOGGER.info("SSBO: {}, Max SSBO Bindings: {}", supportsSSBO, maxSSBOBindings);
LOGGER.info("Buffer Storage: {}, Clear Texture: {}, Sampler Objects: {}", supportsBufferStorage, supportsClearTexture, supportsSamplerObjects);
@@ -124,8 +135,11 @@ public class RenderSystem {
}
public static void texImage2D(int texture, int target, int level, int internalformat, int width, int height, int border, int format, int type, @Nullable ByteBuffer pixels) {
GL11.glBindTexture(target, texture);
GLStateManager.glBindTexture(target, texture);
GL11.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels);
if (target == GL11.GL_TEXTURE_2D && level == 0) {
TextureInfoCache.INSTANCE.onTexImage2D(target, level, internalformat, width, height, border, format, type, pixels);
}
}
public static void uniformMatrix4fv(int location, boolean transpose, FloatBuffer matrix) {
@@ -407,10 +421,12 @@ public class RenderSystem {
}
public static void clearBufferSubData(int target, int internalFormat, long offset, long size, int format, int type, int[] data) {
final ByteBuffer buf = BufferUtils.createByteBuffer(data.length * 4);
buf.asIntBuffer().put(data);
if (GLStateManager.capabilities.OpenGL43) {
GL43.glClearBufferSubData(target, internalFormat, offset, size, format, type, (ByteBuffer) null);
GL43.glClearBufferSubData(target, internalFormat, offset, size, format, type, buf);
} else if (GLStateManager.capabilities.GL_ARB_clear_buffer_object) {
ARBClearBufferObject.glClearBufferSubData(target, internalFormat, offset, size, format, type, (ByteBuffer) null);
ARBClearBufferObject.glClearBufferSubData(target, internalFormat, offset, size, format, type, buf);
}
}
@@ -447,6 +463,26 @@ public class RenderSystem {
dsaState.textureStorage3D(texture, target, levels, internalFormat, width, height, depth);
}
public static int getMaxGlslVersion() {
return maxGlslVersion;
}
public static boolean supportsGpuShader4() {
return supportsGpuShader4;
}
public static boolean supportsSnormFormats() {
return GLStateManager.capabilities.OpenGL31;
}
public static boolean supportsPackedFloatRenderable() {
return GLStateManager.capabilities.OpenGL30 && maxGlslVersion >= 130;
}
public static boolean supportsTesselation() {
return supportsTesselation;
}
public static boolean supportsSamplerObjects() {
return supportsSamplerObjects;
}
@@ -41,10 +41,12 @@ public final class AngelicaRedirector {
private static final String Drawable = "org/lwjgl/opengl/Drawable";
private static final String GLStateManager = "com/gtnewhorizons/angelica/glsm/GLStateManager";
private static final String GL11 = "org/lwjgl/opengl/GL11";
private static final String GL11C = "org/lwjgl/opengl/GL11C";
private static final String GL12 = "org/lwjgl/opengl/GL12";
private static final String GL13 = "org/lwjgl/opengl/GL13";
private static final String GL14 = "org/lwjgl/opengl/GL14";
private static final String GL20 = "org/lwjgl/opengl/GL20";
private static final String GL30 = "org/lwjgl/opengl/GL30";
private static final String Project = "org/lwjgl/util/glu/Project";
private static final String OpenGlHelper = "net/minecraft/client/renderer/OpenGlHelper";
private static final String EXTBlendFunc = "org/lwjgl/opengl/EXTBlendFuncSeparate";
@@ -231,6 +233,9 @@ public final class AngelicaRedirector {
.add("glStencilOpSeparate")
.add("glUseProgram")
);
methodRedirects.put(GL30, RedirectMap.newMap()
.add("glBindFramebuffer")
);
methodRedirects.put(OpenGlHelper, RedirectMap.newMap()
.add("glBlendFunc", "tryBlendFuncSeparate")
.add("func_148821_a", "tryBlendFuncSeparate")
@@ -241,10 +246,19 @@ public final class AngelicaRedirector {
.add("func_153188_a", "glFramebufferTexture2D")
.add("setActiveTexture")
.add("setLightmapTextureCoords")
.add("isFramebufferEnabled"));
.add("isFramebufferEnabled")
);
methodRedirects.put(EXTBlendFunc, RedirectMap.newMap().add("glBlendFuncSeparateEXT", "tryBlendFuncSeparate"));
methodRedirects.put(ARBMultiTexture, RedirectMap.newMap().add("glActiveTextureARB"));
methodRedirects.put(Project, RedirectMap.newMap().add("gluPerspective"));
final String glPrefix = "org/lwjgl/opengl/GL";
for (var entry : new HashMap<>(methodRedirects).entrySet()) {
if (entry.getKey().startsWith(glPrefix)) {
methodRedirects.put(entry.getKey() + "C", entry.getValue());
cstPoolParser.addString(entry.getKey() + "C");
}
}
}
public String[] getTransformerExclusions() {
@@ -275,7 +289,7 @@ public final class AngelicaRedirector {
boolean redirectInMethod = false;
for (AbstractInsnNode node : mn.instructions.toArray()) {
if (node instanceof MethodInsnNode mNode) {
if (mNode.owner.equals(GL11) && (mNode.name.equals("glEnable") || mNode.name.equals("glDisable")) && mNode.desc.equals("(I)V")) {
if ((mNode.owner.equals(GL11) || mNode.owner.equals(GL11C)) && (mNode.name.equals("glEnable") || mNode.name.equals("glDisable")) && mNode.desc.equals("(I)V")) {
final AbstractInsnNode prevNode = node.getPrevious();
String name = null;
if (prevNode instanceof LdcInsnNode ldcNode) {
@@ -316,15 +330,18 @@ public final class AngelicaRedirector {
}
} else {
final Map<String, String> redirects = methodRedirects.get(mNode.owner);
if (redirects != null && redirects.containsKey(mNode.name)) {
if (LOG_SPAM) {
final String shortOwner = mNode.owner.substring(mNode.owner.lastIndexOf("/") + 1);
LOGGER.info("Redirecting call in {} from {}.{}{} to GLStateManager.{}{}", transformedName, shortOwner, mNode.name, mNode.desc, redirects.get(mNode.name), mNode.desc);
if (redirects != null) {
final String glsmName = redirects.get(mNode.name);
if (glsmName != null) {
if (LOG_SPAM) {
final String shortOwner = mNode.owner.substring(mNode.owner.lastIndexOf("/") + 1);
LOGGER.info("Redirecting call in {} from {}.{}{} to GLStateManager.{}{}", transformedName, shortOwner, mNode.name, mNode.desc, glsmName, mNode.desc);
}
mNode.owner = GLStateManager;
mNode.name = glsmName;
changed = true;
redirectInMethod = true;
}
mNode.owner = GLStateManager;
mNode.name = redirects.get(mNode.name);
changed = true;
redirectInMethod = true;
}
}
}
@@ -188,6 +188,7 @@ public enum Mixins implements IMixins {
, "celeritas.biome_blending.MixinBlockLeaves"
, "celeritas.biome_blending.MixinBlockLiquid"
, "celeritas.threading.MixinForgeHooksClient"
, "celeritas.terrain.MixinChunk"
)
),
@@ -195,20 +196,27 @@ public enum Mixins implements IMixins {
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.enableIris)
.addClientMixins(
"shaders.MixinEntityRenderer"
"shaders.MixinDroppedItemGlintEdges"
, "shaders.MixinEntityPickupFX"
, "shaders.MixinEntityRenderer"
, "shaders.MixinGuiIngameForge"
, "shaders.MixinFramebuffer"
, "shaders.MixinItem"
, "shaders.MixinLocale"
, "shaders.MixinRender"
, "shaders.MixinRenderBiped"
, "shaders.MixinRenderDragon"
, "shaders.MixinRenderEntityFlame"
, "shaders.MixinRendererLivingEntity"
, "shaders.MixinRenderGlobal"
, "shaders.MixinRenderHorse"
, "shaders.MixinRenderItem"
, "shaders.MixinRenderManager"
, "shaders.MixinRenderNameTag"
, "shaders.MixinRenderPlayerArmor"
, "shaders.MixinTileEntityBeaconRenderer"
, "shaders.MixinRenderEndPortal"
, "shaders.MixinTileEntityRendererDispatcher"
)
),
@@ -314,7 +322,7 @@ public enum Mixins implements IMixins {
.setPhase(Phase.LATE)
.addRequiredMod(TargetedMod.NTM_SPACE)
.setApplyIf(() -> CompatConfig.fixNTMSpace && AngelicaConfig.enableIris)
.addClientMixins("client.ntmSpace.MixinSkyProviderCelestial_ShaderCompat")),
.addClientMixins("client.ntmSpace.MixinSkyProviderCelestial_ShaderCompat", "client.ntmSpace.MixinSkyProviderLaytheSunset")),
SPEEDUP_CAMPFIRE_BACKPORT_ANIMATIONS(new MixinBuilder("Add animation speedup support to Campfire Backport")
.setPhase(Phase.LATE)
@@ -447,6 +455,12 @@ public enum Mixins implements IMixins {
"MixinBlockTFMagicLeaves"
))
),
ET_FUTURUM_ELYTRA_CAPE(new MixinBuilder("Set custom item ID for elytra with cape texture")
.setPhase(Phase.LATE)
.addRequiredMod(TargetedMod.ET_FUTURUM_REQUIEM)
.setApplyIf(() -> AngelicaConfig.enableIris)
.addClientMixins("client.etfuturum.MixinLayerBetterElytra")
),
MCPATCHER_FORGE(new MixinBuilder()
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.enableMCPatcherForgeFeatures)
@@ -14,6 +14,7 @@ public enum TargetedMod implements ITargetMod {
DYNAMIC_SURROUNDINGS_MIST("org.blockartistry.mod.DynSurround.mixinplugin.DynamicSurroundingsEarlyMixins", "dsurround"),
DYNAMIC_SURROUNDINGS_ORIGINAL("org.blockartistry.mod.DynSurround.asm.TransformLoader", "dsurround"),
DRAGON_API("Reika.DragonAPI.Auxiliary.DragonAPIASMHandler", "DragonAPI"),
ET_FUTURUM_REQUIEM(null, "etfuturum"),
EXTRAUTILS(null, "ExtraUtilities"),
FALSETWEAKS("com.falsepattern.falsetweaks.asm.CoreLoadingPlugin", "falsetweaks"),
MINEFACTORY_RELOADED(null, "MineFactoryReloaded"),
@@ -0,0 +1,7 @@
package com.gtnewhorizons.angelica.mixins.interfaces;
import com.gtnewhorizons.angelica.utils.ConcurrentTileEntityMap;
public interface IChunkTileEntityMapHolder {
ConcurrentTileEntityMap angelica$getConcurrentTEMap();
}
@@ -0,0 +1,9 @@
package com.gtnewhorizons.angelica.mixins.interfaces;
import net.minecraft.util.AxisAlignedBB;
public interface ITileEntityBoundingBoxCache {
AxisAlignedBB angelica$getCachedRenderBoundingBox();
boolean angelica$isInfiniteExtent();
}
@@ -1,11 +1,9 @@
package com.gtnewhorizons.angelica.proxy;
import static com.gtnewhorizons.angelica.AngelicaMod.MOD_ID;
import static com.gtnewhorizons.angelica.loading.AngelicaTweaker.LOGGER;
import com.google.common.base.Objects;
import com.gtnewhorizon.gtnhlib.client.model.loading.ModelRegistry;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.VAOManager;
import com.gtnewhorizons.angelica.commands.AngelicaCommand;
import com.gtnewhorizons.angelica.compat.ModStatus;
import com.gtnewhorizons.angelica.compat.bettercrashes.BetterCrashesCompat;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
@@ -18,6 +16,7 @@ import com.gtnewhorizons.angelica.dynamiclights.config.EntityLightConfig;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.debug.OpenGLDebugging;
import com.gtnewhorizons.angelica.hudcaching.HUDCaching;
import com.gtnewhorizons.angelica.loading.AngelicaTweaker;
import com.gtnewhorizons.angelica.mixins.interfaces.IGameSettingsExt;
import com.gtnewhorizons.angelica.render.CloudRenderer;
import com.gtnewhorizons.angelica.rendering.AngelicaBlockSafetyRegistry;
@@ -27,10 +26,7 @@ import com.gtnewhorizons.angelica.rendering.celeritas.threading.ChunkTaskRegistr
import com.gtnewhorizons.angelica.rendering.celeritas.threading.DefaultChunkTaskProvider;
import com.gtnewhorizons.angelica.rendering.celeritas.threading.ThreadedChunkTaskProvider;
import com.gtnewhorizons.angelica.zoom.Zoom;
import com.gtnewhorizons.angelica.commands.AngelicaCommand;
import cpw.mods.fml.client.registry.ClientRegistry;
import com.gtnewhorizons.angelica.loading.AngelicaTweaker;
import net.minecraftforge.client.ClientCommandHandler;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
@@ -40,10 +36,11 @@ import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent;
import cpw.mods.fml.common.registry.GameData;
import cpw.mods.fml.relauncher.ReflectionHelper;
import java.lang.management.ManagementFactory;
import java.util.Locale;
import java.util.concurrent.ConcurrentHashMap;
import jss.notfine.core.Settings;
import jss.notfine.gui.GuiCustomMenu;
import jss.notfine.gui.NotFineGameOptionPages;
import me.flashyreese.mods.reeses_sodium_options.client.gui.ReeseSodiumVideoOptionsScreen;
import me.jellysquid.mods.sodium.client.gui.SodiumOptionsGUI;
import net.coderbot.iris.Iris;
import net.coderbot.iris.client.IrisDebugScreenHandler;
import net.minecraft.block.Block;
@@ -51,6 +48,8 @@ import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.GuiMainMenu;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiVideoSettings;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.network.NetHandlerPlayClient;
import net.minecraft.client.settings.GameSettings;
@@ -61,14 +60,23 @@ import net.minecraft.util.MathHelper;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.world.EnumSkyBlock;
import net.minecraft.world.chunk.Chunk;
import net.minecraftforge.client.ClientCommandHandler;
import net.minecraftforge.client.event.EntityViewRenderEvent;
import net.minecraftforge.client.event.FOVUpdateEvent;
import net.minecraftforge.client.event.GuiOpenEvent;
import net.minecraftforge.client.event.GuiScreenEvent;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.world.WorldEvent;
import org.lwjgl.input.Keyboard;
import java.lang.management.ManagementFactory;
import java.util.Locale;
import java.util.concurrent.ConcurrentHashMap;
import static com.gtnewhorizons.angelica.AngelicaMod.MOD_ID;
import static com.gtnewhorizons.angelica.loading.AngelicaTweaker.LOGGER;
public class ClientProxy extends CommonProxy {
final Minecraft mc = Minecraft.getMinecraft();
@@ -323,6 +331,20 @@ public class ClientProxy extends CommonProxy {
}
}
@SubscribeEvent
public void onGuiInit(GuiScreenEvent.InitGuiEvent.Pre event) {
if(event.gui instanceof GuiVideoSettings eventGui) {
event.setCanceled(true);
if(AngelicaConfig.enableNotFineOptions || GuiScreen.isShiftKeyDown()) {
Minecraft.getMinecraft().displayGuiScreen(new GuiCustomMenu(eventGui.parentGuiScreen, NotFineGameOptionPages.general(), NotFineGameOptionPages.detail(), NotFineGameOptionPages.atmosphere(), NotFineGameOptionPages.particles(), NotFineGameOptionPages.other()));
} else if(!AngelicaConfig.enableReesesSodiumOptions || GuiScreen.isCtrlKeyDown()) {
Minecraft.getMinecraft().displayGuiScreen(new SodiumOptionsGUI(eventGui.parentGuiScreen));
} else {
Minecraft.getMinecraft().displayGuiScreen(new ReeseSodiumVideoOptionsScreen(eventGui.parentGuiScreen));
}
}
}
/* coerce NaN fog values back to 0 (https://bugs.mojang.com/browse/MC-10480) - from ArchaicFix */
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onFogColor(EntityViewRenderEvent.FogColors event) {
@@ -0,0 +1,27 @@
package com.gtnewhorizons.angelica.rendering;
import com.gtnewhorizons.angelica.rendering.celeritas.world.WorldSlice;
import net.minecraft.tileentity.TileEntity;
public class RenderThreadContext {
private static final ThreadLocal<WorldSlice> currentWorldSlice = new ThreadLocal<>();
public static void set(WorldSlice slice) {
currentWorldSlice.set(slice);
}
public static void clear() {
currentWorldSlice.remove();
}
public static TileEntity getSnapshotTE(int x, int y, int z) {
final WorldSlice slice = currentWorldSlice.get();
if (slice == null) return null;
return slice.getTileEntity(x, y, z);
}
public static boolean hasWorldSlice() {
return currentWorldSlice.get() != null;
}
}
@@ -0,0 +1,52 @@
package com.gtnewhorizons.angelica.rendering;
import it.unimi.dsi.fastutil.objects.Reference2ByteOpenHashMap;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
/**
* Registry for tracking which TileEntity classes always return INFINITE_EXTENT_AABB.
*/
public final class TileEntityRenderBoundsRegistry {
private static final byte UNKNOWN = 0;
private static final byte FINITE = 1;
private static final byte INFINITE = 2;
private static final Reference2ByteOpenHashMap<Class<? extends TileEntity>> classRegistry = new Reference2ByteOpenHashMap<>();
static {
classRegistry.defaultReturnValue(UNKNOWN);
}
private TileEntityRenderBoundsRegistry() {}
public static boolean isInfiniteExtentsBox(AxisAlignedBB box) {
return box == null || Double.isInfinite(box.minX) || Double.isInfinite(box.minY) || Double.isInfinite(box.minZ) || Double.isInfinite(box.maxX) || Double.isInfinite(box.maxY) || Double.isInfinite(box.maxZ);
}
public static boolean isAlwaysInfiniteExtent(TileEntity te) {
final Class<? extends TileEntity> clazz = te.getClass();
byte result = classRegistry.getByte(clazz);
if (result != UNKNOWN) {
return result == INFINITE;
}
return probeAndCache(te, clazz);
}
private static boolean probeAndCache(TileEntity te, Class<? extends TileEntity> clazz) {
boolean isInfinite = false;
try {
AxisAlignedBB aabb = te.getRenderBoundingBox();
isInfinite = isInfiniteExtentsBox(aabb);
} catch (Exception ignored) {}
classRegistry.put(clazz, isInfinite ? INFINITE : FINITE);
return isInfinite;
}
public static void clear() {
classRegistry.clear();
}
}
@@ -1,32 +1,29 @@
package com.gtnewhorizons.angelica.rendering.celeritas;
import com.gtnewhorizons.angelica.AngelicaMod;
import com.gtnewhorizons.angelica.dynamiclights.DynamicLights;
import com.gtnewhorizons.angelica.dynamiclights.IDynamicLightSource;
import java.util.Arrays;
import java.util.List;
import com.gtnewhorizons.angelica.rendering.celeritas.iris.BlockRenderContext;
import com.gtnewhorizons.angelica.rendering.celeritas.iris.IrisExtendedChunkVertexEncoder;
import org.embeddedt.embeddium.impl.model.light.LightPipeline;
import org.embeddedt.embeddium.impl.model.light.flat.FlatLightPipeline;
import org.embeddedt.embeddium.impl.render.chunk.ChunkColorWriter;
import com.gtnewhorizons.angelica.rendering.celeritas.light.LightDataCache;
import com.gtnewhorizons.angelica.rendering.celeritas.light.QuadLightingHelper;
import com.gtnewhorizons.angelica.rendering.celeritas.light.VanillaDiffuseProvider;
import org.embeddedt.embeddium.impl.model.light.smooth.SmoothLightPipeline;
import com.gtnewhorizons.angelica.rendering.celeritas.world.WorldSlice;
import lombok.Getter;
import me.jellysquid.mods.sodium.client.SodiumClientMod;
import net.coderbot.iris.block_rendering.BlockRenderingSettings;
import net.irisshaders.iris.api.v0.IrisApi;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.world.IBlockAccess;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.IBlockAccess;
import org.embeddedt.embeddium.impl.model.light.LightPipeline;
import org.embeddedt.embeddium.impl.model.light.data.LightDataAccess;
import org.embeddedt.embeddium.impl.model.light.data.QuadLightData;
import org.embeddedt.embeddium.impl.model.light.flat.FlatLightPipeline;
import org.embeddedt.embeddium.impl.model.light.smooth.SmoothLightPipeline;
import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing;
import org.embeddedt.embeddium.impl.render.chunk.ChunkColorWriter;
import org.embeddedt.embeddium.impl.render.chunk.RenderPassConfiguration;
import org.embeddedt.embeddium.impl.render.chunk.compile.ChunkBuildBuffers;
import org.embeddedt.embeddium.impl.render.chunk.compile.ChunkBuildContext;
@@ -36,6 +33,9 @@ import org.embeddedt.embeddium.impl.render.chunk.terrain.material.Material;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexEncoder;
import org.embeddedt.embeddium.impl.util.QuadUtil;
import java.util.Arrays;
import java.util.List;
public class AngelicaChunkBuildContext extends ChunkBuildContext {
public static final int NUM_PASSES = 2;
@@ -56,6 +56,7 @@ public class AngelicaChunkBuildContext extends ChunkBuildContext {
private final VertexArrayQuadView quadView;
private boolean lightPipelineReady = false;
private int originX, originY, originZ;
private IBlockAccess blockAccess;
public AngelicaChunkBuildContext(RenderPassConfiguration<?> renderPassConfiguration, WorldClient world) {
super(renderPassConfiguration);
@@ -71,6 +72,7 @@ public class AngelicaChunkBuildContext extends ChunkBuildContext {
}
public void setupLightPipeline(IBlockAccess blockAccess, int minBlockX, int minBlockY, int minBlockZ) {
this.blockAccess = blockAccess;
this.originX = minBlockX;
this.originY = minBlockY;
this.originZ = minBlockZ;
@@ -93,7 +95,7 @@ public class AngelicaChunkBuildContext extends ChunkBuildContext {
private Material selectMaterial(Material material, TextureAtlasSprite sprite, boolean isShaderPackOverride) {
// Don't apply transparency-based optimization when shader pack explicitly overrides the material
if (isShaderPackOverride) {
if (!AngelicaMod.options().performance.useRenderPassOptimization || isShaderPackOverride) {
return material;
}
if (sprite != null && sprite.getClass() == TextureAtlasSprite.class && !sprite.hasAnimationMetadata()) {
@@ -122,7 +124,7 @@ public class AngelicaChunkBuildContext extends ChunkBuildContext {
final boolean hasDynamicLights = chunkLightSources != null && !chunkLightSources.isEmpty();
final boolean separateAo = BlockRenderingSettings.INSTANCE.shouldUseSeparateAo();
final boolean celeritasSmoothLighting = SodiumClientMod.options().quality.useCeleritasSmoothLighting;
final boolean celeritasSmoothLighting = AngelicaMod.options().quality.useCeleritasSmoothLighting;
final boolean shaderActive = IrisApi.getInstance().isShaderPackInUse();
final boolean useAoCalculation = lightPipelineReady && (separateAo || celeritasSmoothLighting || shaderActive);
final boolean stripDiffuse = shaderActive && BlockRenderingSettings.INSTANCE.shouldDisableDirectionalShading();
@@ -132,6 +134,14 @@ public class AngelicaChunkBuildContext extends ChunkBuildContext {
int ptr = 0;
final int numQuads = vertexCount / 4;
final int blockX = blockRenderContext.localPosX;
final int blockY = blockRenderContext.localPosY;
final int blockZ = blockRenderContext.localPosZ;
final int worldX = originX + blockX;
final int worldY = originY + blockY;
final int worldZ = originZ + blockZ;
final boolean isEmissive = useAoCalculation && QuadLightingHelper.isBlockEmissive(blockAccess, worldX, worldY, worldZ);
for (int quadIdx = 0; quadIdx < numQuads; quadIdx++) {
float uSum = 0, vSum = 0;
@@ -171,11 +181,6 @@ public class AngelicaChunkBuildContext extends ChunkBuildContext {
}
if (useAoCalculation) {
final int blockX = blockRenderContext.localPosX;
final int blockY = blockRenderContext.localPosY;
final int blockZ = blockRenderContext.localPosZ;
final boolean isEmissive = LightDataAccess.unpackEM(lightDataCache.get(originX + blockX, originY + blockY, originZ + blockZ));
final boolean quadIsFullBright = QuadLightingHelper.isQuadFullBright(vertices);
if (isEmissive || quadIsFullBright) {
@@ -192,7 +197,7 @@ public class AngelicaChunkBuildContext extends ChunkBuildContext {
final ModelQuadFacing lightFace = quadView.getLightFace();
final LightPipeline pipeline = blockAllowsSmoothLighting ? smoothLightPipeline : flatLightPipeline;
final ModelQuadFacing cullFace = quadView.getCullFace();
pipeline.calculate(quadView, originX + blockX, originY + blockY, originZ + blockZ, quadLightData, cullFace, lightFace, shade, true);
pipeline.calculate(quadView, worldX, worldY, worldZ, quadLightData, cullFace, lightFace, shade, true);
}
for (int vIdx = 0; vIdx < 4; vIdx++) {
@@ -1,11 +1,12 @@
package com.gtnewhorizons.angelica.rendering.celeritas;
import com.gtnewhorizons.angelica.AngelicaMod;
import com.gtnewhorizons.angelica.mixins.interfaces.RenderSectionManagerAccessor;
import com.gtnewhorizons.angelica.rendering.AngelicaRenderQueue;
import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProviderHolder;
import com.gtnewhorizons.angelica.rendering.celeritas.threading.ChunkTaskProvider;
import com.gtnewhorizons.angelica.rendering.celeritas.threading.ChunkTaskRegistry;
import com.gtnewhorizons.angelica.rendering.celeritas.world.cloned.ClonedChunkSectionCache;
import me.jellysquid.mods.sodium.client.SodiumClientMod;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
@@ -15,7 +16,6 @@ import org.embeddedt.embeddium.impl.render.chunk.ChunkRenderMatrices;
import org.embeddedt.embeddium.impl.render.chunk.RenderPassConfiguration;
import org.embeddedt.embeddium.impl.render.chunk.RenderSection;
import org.embeddedt.embeddium.impl.render.chunk.RenderSectionManager;
import org.embeddedt.embeddium.impl.render.viewport.CameraTransform;
import org.embeddedt.embeddium.impl.render.chunk.compile.ChunkBuildOutput;
import org.embeddedt.embeddium.impl.render.chunk.compile.tasks.ChunkBuilderTask;
import org.embeddedt.embeddium.impl.render.chunk.lists.SectionTicker;
@@ -23,12 +23,11 @@ import org.embeddedt.embeddium.impl.render.chunk.occlusion.AsyncOcclusionMode;
import org.embeddedt.embeddium.impl.render.chunk.sprite.GenericSectionSpriteTicker;
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexType;
import org.embeddedt.embeddium.impl.render.viewport.CameraTransform;
import org.embeddedt.embeddium.impl.render.viewport.Viewport;
import org.embeddedt.embeddium.impl.util.PositionUtil;
import org.jetbrains.annotations.Nullable;
import com.gtnewhorizons.angelica.mixins.interfaces.RenderSectionManagerAccessor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@@ -88,7 +87,7 @@ public class AngelicaRenderSectionManager extends RenderSectionManager {
@Override
protected AsyncOcclusionMode getAsyncOcclusionMode() {
return AsyncOcclusionMode.EVERYTHING;
return AngelicaMod.options().performance.asyncOcclusionMode;
}
@Override
@@ -98,7 +97,7 @@ public class AngelicaRenderSectionManager extends RenderSectionManager {
@Override
protected boolean useFogOcclusion() {
return true;
return AngelicaMod.options().performance.useFogOcclusion && !IrisShaderProviderHolder.isActive();
}
@Override
@@ -108,10 +107,13 @@ public class AngelicaRenderSectionManager extends RenderSectionManager {
@Override
protected boolean shouldUseOcclusionCulling(Viewport positionedViewport, boolean spectator) {
if (!spectator) return true;
final var camBlockPos = positionedViewport.getBlockCoord();
return !this.world.getBlock(camBlockPos.x(), camBlockPos.y(), camBlockPos.z()).isOpaqueCube();
if (spectator) {
final var camBlockPos = positionedViewport.getBlockCoord();
if (this.world.getBlock(camBlockPos.x(), camBlockPos.y(), camBlockPos.z()).isOpaqueCube()) {
return false;
}
}
return AngelicaMod.options().performance.useOcclusionCulling;
}
@Override
@@ -150,7 +152,7 @@ public class AngelicaRenderSectionManager extends RenderSectionManager {
@Override
protected boolean allowImportantRebuilds() {
return !SodiumClientMod.options().performance.alwaysDeferChunkUpdates;
return !AngelicaMod.options().performance.alwaysDeferChunkUpdates;
}
@Override
@@ -1,6 +1,7 @@
package com.gtnewhorizons.angelica.rendering.celeritas;
import com.gtnewhorizons.angelica.Tags;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.dynamiclights.DynamicLights;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.states.FogState;
@@ -20,7 +21,7 @@ public class CeleritasDebugScreenHandler {
@SubscribeEvent(priority = EventPriority.LOW)
public void onRenderGameOverlayTextEvent(RenderGameOverlayEvent.Text event) {
final Minecraft mc = Minecraft.getMinecraft();
if (!mc.gameSettings.showDebugInfo) {
if (!mc.gameSettings.showDebugInfo || AngelicaConfig.disableF3Additions) {
return;
}
@@ -1,9 +1,14 @@
package com.gtnewhorizons.angelica.rendering.celeritas;
import com.gtnewhorizons.angelica.AngelicaMod;
import com.gtnewhorizons.angelica.dynamiclights.DynamicLights;
import com.gtnewhorizons.angelica.dynamiclights.IDynamicLightWorldRenderer;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.mixins.interfaces.ITileEntityBoundingBoxCache;
import com.gtnewhorizons.angelica.rendering.RenderingState;
import com.gtnewhorizons.angelica.rendering.TileEntityRenderBoundsRegistry;
import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProvider;
import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProviderHolder;
import net.coderbot.iris.pipeline.ShadowRenderer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.WorldClient;
@@ -21,9 +26,6 @@ import org.embeddedt.embeddium.impl.render.chunk.lists.ChunkRenderList;
import org.embeddedt.embeddium.impl.render.chunk.lists.SortedRenderLists;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkMeshFormats;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexType;
import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProvider;
import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProviderHolder;
import me.jellysquid.mods.sodium.client.SodiumClientMod;
import org.embeddedt.embeddium.impl.render.terrain.SimpleWorldRenderer;
import org.embeddedt.embeddium.impl.render.viewport.Viewport;
import org.joml.Matrix4f;
@@ -116,7 +118,7 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
}
}
if (SodiumClientMod.options().advanced.useCompactVertexFormat) {
if (AngelicaMod.options().performance.useCompactVertexFormat) {
return ChunkMeshFormats.COMPACT;
}
return ChunkMeshFormats.VANILLA_LIKE;
@@ -144,7 +146,7 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
renderSectionManager.setCameraPosition(transform.x, transform.y, transform.z);
this.useEntityCulling = true;
this.useEntityCulling = AngelicaMod.options().performance.useEntityCulling;
super.setupTerrain(viewport, cameraState, frame, spectator, updateChunksImmediately);
@@ -227,10 +229,13 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
return;
}
final AxisAlignedBB aabb = tileEntity.getRenderBoundingBox();
final ITileEntityBoundingBoxCache teCache = (ITileEntityBoundingBoxCache) tileEntity;
if (aabb != TileEntity.INFINITE_EXTENT_AABB && !this.currentViewport.isBoxVisible(aabb.minX, aabb.minY, aabb.minZ, aabb.maxX, aabb.maxY, aabb.maxZ)) {
return;
if (!teCache.angelica$isInfiniteExtent()) {
final AxisAlignedBB aabb = teCache.angelica$getCachedRenderBoundingBox();
if (aabb != null && !this.currentViewport.isBoxVisible(aabb.minX, aabb.minY, aabb.minZ, aabb.maxX, aabb.maxY, aabb.maxZ)) {
return;
}
}
try {
@@ -244,11 +249,6 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
}
}
private static boolean isInfiniteExtentsBox(AxisAlignedBB box) {
return box == null || Double.isInfinite(box.minX) || Double.isInfinite(box.minY) || Double.isInfinite(box.minZ)
|| Double.isInfinite(box.maxX) || Double.isInfinite(box.maxY) || Double.isInfinite(box.maxZ);
}
public boolean isEntityVisible(Entity entity) {
// During shadow pass, don't cull entities - shadow rendering uses different frustum
if (!this.useEntityCulling || this.renderSectionManager.isInShadowPass()) {
@@ -260,7 +260,7 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
box = entity.boundingBox;
}
if (isInfiniteExtentsBox(box)) {
if (TileEntityRenderBoundsRegistry.isInfiniteExtentsBox(box)) {
return true;
}
@@ -35,17 +35,6 @@ public class LightDataCache extends LightDataAccess {
// Opacity check - true if block is view-blocking (solid blocks)
final boolean op = block.getMaterial().isOpaque() && block.getLightOpacity() > 0;
boolean em;
if (lu > 0) {
em = true;
} else {
try {
em = block.getMixedBrightnessForBlock(EmptyBlockAccess.INSTANCE, x, y, z) == QuadLightingHelper.FULL_BRIGHT_15;
} catch (Exception e) {
em = false;
}
}
return packFC(fc) | packFO(fo) | packOP(op) | packEM(em) | packAO(ao) | packLU(lu) | packSL(sl) | packBL(bl);
return packFC(fc) | packFO(fo) | packOP(op) | packAO(ao) | packLU(lu) | packSL(sl) | packBL(bl);
}
}
@@ -1,5 +1,7 @@
package com.gtnewhorizons.angelica.rendering.celeritas.light;
import net.minecraft.block.Block;
import net.minecraft.world.IBlockAccess;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexEncoder;
public final class QuadLightingHelper {
@@ -9,6 +11,15 @@ public final class QuadLightingHelper {
public static final int FULL_BRIGHT_15 = (15 << 20) | (15 << 4); // 15728880
public static final int FULL_BRIGHT_14 = (14 << 20) | (14 << 4); // 14680288
public static boolean isBlockEmissive(IBlockAccess world, int x, int y, int z) {
final Block block = world.getBlock(x, y, z);
try {
return block.getMixedBrightnessForBlock(EmptyBlockAccess.INSTANCE, x, y, z) == FULL_BRIGHT_15;
} catch (Exception e) {
return false;
}
}
public static boolean isQuadFullBright(ChunkVertexEncoder.Vertex[] vertices) {
final int first = vertices[0].light;
@@ -2,6 +2,7 @@ package com.gtnewhorizons.angelica.rendering.celeritas.threading;
import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager;
import com.gtnewhorizons.angelica.rendering.AngelicaBlockSafetyRegistry;
import com.gtnewhorizons.angelica.rendering.RenderThreadContext;
import com.gtnewhorizons.angelica.rendering.celeritas.AngelicaChunkBuilderMeshingTask;
import com.gtnewhorizons.angelica.rendering.celeritas.SmoothBiomeColorCache;
import com.gtnewhorizons.angelica.rendering.celeritas.WorldClientExtension;
@@ -103,12 +104,16 @@ public class ThreadedAngelicaChunkBuilderMeshingTask extends AngelicaChunkBuilde
enteredLocalMode = !TessellatorManager.isOnMainThread();
if (enteredLocalMode) {
TessellatorManager.enterLocalMode();
if (blockAccess instanceof WorldSlice worldSlice) {
RenderThreadContext.set(worldSlice);
}
}
}
@Override
protected void onExitExecute() {
if (enteredLocalMode) {
RenderThreadContext.clear();
RenderPassHelper.resetWorldRenderPass();
TessellatorManager.exitLocalMode();
}
@@ -4,11 +4,17 @@ import com.falsepattern.endlessids.mixin.helpers.ChunkBiomeHook;
import com.gtnewhorizons.angelica.compat.ExtendedBlockStorageExt;
import com.gtnewhorizons.angelica.compat.ModStatus;
import com.gtnewhorizons.angelica.compat.mojang.ChunkSectionPos;
import it.unimi.dsi.fastutil.shorts.Short2ObjectMap;
import com.gtnewhorizons.angelica.mixins.interfaces.IChunkTileEntityMapHolder;
import com.gtnewhorizons.angelica.utils.ConcurrentTileEntityMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectMaps;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.shorts.Short2ObjectOpenHashMap;
import mega.fluidlogged.internal.mixin.hook.FLSubChunk;
import net.minecraft.block.Block;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.ChunkPosition;
import net.minecraft.world.EnumSkyBlock;
import net.minecraft.world.World;
import net.minecraft.world.biome.BiomeGenBase;
@@ -27,7 +33,7 @@ public class ClonedChunkSection {
private ChunkSectionPos pos;
private ExtendedBlockStorageExt data;
private BiomeGenBase[] biomeData;
private final Short2ObjectMap<TileEntity> tileEntities;
private final Short2ObjectOpenHashMap<TileEntity> tileEntities;
private long lastUsedTimestamp = Long.MAX_VALUE;
@@ -53,7 +59,7 @@ public class ClonedChunkSection {
this.pos = pos;
this.data = new ExtendedBlockStorageExt(chunk, section);
int bArrLength;
final int bArrLength;
if (ModStatus.isEIDBiomeLoaded) {
bArrLength = ((ChunkBiomeHook) chunk).getBiomeShortArray().length;
} else {
@@ -61,26 +67,7 @@ public class ClonedChunkSection {
}
this.biomeData = new BiomeGenBase[bArrLength];
this.tileEntities.clear();
// Check for tile entities
for (int y = pos.getMinY(); y <= pos.getMaxY(); y++) {
for (int z = pos.getMinZ(); z <= pos.getMaxZ(); z++) {
for (int x = pos.getMinX(); x <= pos.getMaxX(); x++) {
final int lX = x & 15, lY = y & 15, lZ = z & 15;
// We have to use this insanity because in 1.7 the tile entity isn't guaranteed to be created
// when the chunk gets scheduled for rendering. So we might have to create it.
// Cloning is done on the main thread so this will not introduce threading issues
final Block block = data.getBlockByExtId(lX, lY, lZ);
if (block.hasTileEntity(data.getExtBlockMetadata(lX, lY, lZ))) {
final TileEntity tileEntity = chunk.func_150806_e(x & 15, y, z & 15);
if (tileEntity != null) {
this.tileEntities.put(ChunkSectionPos.packLocal(tileEntity.xCoord & 15, tileEntity.yCoord & 15, tileEntity.zCoord & 15), tileEntity);
}
}
}
}
}
copyBlockEntities(chunk, pos);
// Fill biome data
for (int z = pos.getMinZ(); z <= pos.getMaxZ(); z++) {
@@ -90,6 +77,34 @@ public class ClonedChunkSection {
}
}
@SuppressWarnings("unchecked")
private void copyBlockEntities(Chunk chunk, ChunkSectionPos pos) {
this.tileEntities.clear();
final ConcurrentTileEntityMap map = ((IChunkTileEntityMapHolder) chunk).angelica$getConcurrentTEMap();
map.withReadLock(() -> {
final Object2ObjectOpenHashMap<ChunkPosition, TileEntity> delegate = map.getDelegate();
if (delegate.isEmpty()) return;
final int minY = pos.getMinY();
final int maxY = pos.getMaxY();
for (Object2ObjectMap.Entry<ChunkPosition, TileEntity> entry : Object2ObjectMaps.fastIterable(delegate)) {
final ChunkPosition tePos = entry.getKey();
if (tePos.chunkPosY < minY || tePos.chunkPosY > maxY) continue;
final TileEntity te = entry.getValue();
if (te != null && !te.isInvalid()) {
this.tileEntities.put(ChunkSectionPos.packLocal(tePos.chunkPosX & 15, tePos.chunkPosY & 15, tePos.chunkPosZ & 15), te);
}
}
});
this.tileEntities.trim();
}
public Block getBlock(int x, int y, int z) {
return data.getBlockByExtId(x, y, z);
}
@@ -0,0 +1,203 @@
package com.gtnewhorizons.angelica.utils;
import com.gtnewhorizons.angelica.rendering.RenderThreadContext;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.ChunkPosition;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* Thread-safe wrapper around Object2ObjectOpenHashMap for chunkTileEntityMap.
*/
public class ConcurrentTileEntityMap implements Map<ChunkPosition, TileEntity> {
private final Object2ObjectOpenHashMap<ChunkPosition, TileEntity> delegate = new Object2ObjectOpenHashMap<>();
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
private final ConcurrentLinkedQueue<ChunkPosition> invalidationQueue = new ConcurrentLinkedQueue<>();
public void queueInvalidation(ChunkPosition pos) {
invalidationQueue.add(pos);
}
private void processInvalidationQueue() {
ChunkPosition pos;
while ((pos = invalidationQueue.poll()) != null) {
final TileEntity te = delegate.get(pos);
if (te != null && te.isInvalid()) {
delegate.remove(pos);
}
}
}
public void withReadLock(Runnable action) {
lock.readLock().lock();
try {
action.run();
} finally {
lock.readLock().unlock();
}
}
public void withWriteLock(Runnable action) {
lock.writeLock().lock();
try {
action.run();
} finally {
lock.writeLock().unlock();
}
}
public Object2ObjectOpenHashMap<ChunkPosition, TileEntity> getDelegate() {
return delegate;
}
public TileEntity putDirect(ChunkPosition key, TileEntity value) {
return delegate.put(key, value);
}
private static boolean isRenderWorkerThread() {
return RenderThreadContext.hasWorldSlice();
}
@Override
public TileEntity get(Object key) {
if (!isRenderWorkerThread()) return delegate.get(key);
lock.readLock().lock();
try {
final TileEntity te = delegate.get(key);
if (te != null && te.isInvalid()) {
if (key instanceof ChunkPosition pos) {
invalidationQueue.add(pos);
}
return null;
}
return te;
} finally {
lock.readLock().unlock();
}
}
@Override
public TileEntity put(ChunkPosition key, TileEntity value) {
lock.writeLock().lock();
try {
processInvalidationQueue();
return delegate.put(key, value);
} finally {
lock.writeLock().unlock();
}
}
@Override
public TileEntity remove(Object key) {
if (isRenderWorkerThread()) {
if (key instanceof ChunkPosition pos) {
invalidationQueue.add(pos);
}
return null;
}
lock.writeLock().lock();
try {
processInvalidationQueue();
return delegate.remove(key);
} finally {
lock.writeLock().unlock();
}
}
@Override
public void putAll(Map<? extends ChunkPosition, ? extends TileEntity> m) {
lock.writeLock().lock();
try {
processInvalidationQueue();
delegate.putAll(m);
} finally {
lock.writeLock().unlock();
}
}
@Override
public void clear() {
lock.writeLock().lock();
try {
invalidationQueue.clear();
delegate.clear();
} finally {
lock.writeLock().unlock();
}
}
@Override
public int size() {
if (!isRenderWorkerThread()) return delegate.size();
lock.readLock().lock();
try {
return delegate.size();
} finally {
lock.readLock().unlock();
}
}
@Override
public boolean isEmpty() {
if (!isRenderWorkerThread()) return delegate.isEmpty();
lock.readLock().lock();
try {
return delegate.isEmpty();
} finally {
lock.readLock().unlock();
}
}
@Override
public boolean containsKey(Object key) {
if (!isRenderWorkerThread()) return delegate.containsKey(key);
lock.readLock().lock();
try {
return delegate.containsKey(key);
} finally {
lock.readLock().unlock();
}
}
@Override
public boolean containsValue(Object value) {
if (!isRenderWorkerThread()) return delegate.containsValue(value);
lock.readLock().lock();
try {
return delegate.containsValue(value);
} finally {
lock.readLock().unlock();
}
}
@Override
public Set<ChunkPosition> keySet() {
if (isRenderWorkerThread()) {
throw new IllegalStateException("keySet() called from render worker. Use withReadLock() for iteration.");
}
return delegate.keySet();
}
@Override
public Collection<TileEntity> values() {
if (isRenderWorkerThread()) {
throw new IllegalStateException("values() called from render worker. Use withReadLock() for iteration.");
}
return delegate.values();
}
@Override
public Set<Entry<ChunkPosition, TileEntity>> entrySet() {
if (isRenderWorkerThread()) {
throw new IllegalStateException("entrySet() called from render worker. Use withReadLock() for iteration.");
}
return delegate.entrySet();
}
}
@@ -1,6 +1,7 @@
package com.prupe.mcpatcher.ctm;
import net.minecraft.block.Block;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess;
@@ -8,6 +9,9 @@ import com.prupe.mcpatcher.mal.block.BlockStateMatcher;
final class BlockOrientation extends RenderBlockState {
private static final boolean fixedBottomFaceUV = (boolean) Launch.blackboard
.getOrDefault("hodgepodge.FixesConfig.fixBottomFaceUV", Boolean.FALSE);
// NEIGHBOR_OFFSETS[a][b][c] = offset from starting block
// a: face 0-5
// b: neighbor 0-7
@@ -16,7 +20,11 @@ final class BlockOrientation extends RenderBlockState {
// 1 2 3
// c: coordinate (x,y,z) 0-2
private static final int[][][] NEIGHBOR_OFFSET = new int[][][] {
makeNeighborOffset(WEST_FACE, SOUTH_FACE, EAST_FACE, NORTH_FACE), // BOTTOM_FACE
(
fixedBottomFaceUV
? makeNeighborOffset(EAST_FACE, SOUTH_FACE, WEST_FACE, NORTH_FACE) // BOTTOM_FACE fixedBottomFaceUV
: makeNeighborOffset(WEST_FACE, SOUTH_FACE, EAST_FACE, NORTH_FACE) // BOTTOM_FACE not fixed
),
makeNeighborOffset(WEST_FACE, SOUTH_FACE, EAST_FACE, NORTH_FACE), // TOP_FACE
makeNeighborOffset(EAST_FACE, BOTTOM_FACE, WEST_FACE, TOP_FACE), // NORTH_FACE
makeNeighborOffset(WEST_FACE, BOTTOM_FACE, EAST_FACE, TOP_FACE), // SOUTH_FACE
@@ -7,6 +7,8 @@ import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import net.minecraft.block.Block;
import net.minecraft.util.IIcon;
@@ -37,6 +39,7 @@ public class CTMUtils {
private static TileLoader tileLoader;
private static TileOverride lastOverride;
private static final Lock lock = new ReentrantLock();
private static final TileOverrideIterator.IJK ijkIterator = newIJKIterator();
private static final TileOverrideIterator.Metadata metadataIterator = newMetadataIterator();
@@ -52,64 +55,76 @@ public class CTMUtils {
} catch (Exception ignore) {}
TexturePackChangeHandler.register(new TexturePackChangeHandler(MCPatcherUtils.CONNECTED_TEXTURES, 3) {
@Override
public void initialize() {}
public void initialize() {
}
@Override
public void beforeChange() {
RenderPassAPI.instance.clear();
lock.lock();
try {
GlassPaneRenderer.clear();
} catch (Exception e) {
e.printStackTrace();
}
renderBlockState.clear();
ijkIterator.clear();
metadataIterator.clear();
allOverrides.clear();
blockOverrides.clear();
tileOverrides.clear();
lastOverride = null;
RenderBlocksUtils.blankIcon = null;
tileLoader = new TileLoader("textures/blocks", logger);
RenderPassAPI.instance.refreshBlendingOptions();
if (MCPatcherForgeConfig.ConnectedTextures.standard || MCPatcherForgeConfig.ConnectedTextures.nonStandard) {
for (ResourceLocation resource : ResourceList.getInstance()
.listResources(TexturePackAPI.MCPATCHER_SUBDIR + "ctm", ".properties", true)) {
registerOverride(TileOverride.create(resource, tileLoader));
RenderPassAPI.instance.clear();
try {
GlassPaneRenderer.clear();
} catch (NoClassDefFoundError e) {
// nothing
} catch (Exception e) {
e.printStackTrace();
}
}
for (ResourceLocation resource : BlendMethod.getAllBlankResources()) {
tileLoader.preloadTile(resource, false);
renderBlockState.clear();
ijkIterator.clear();
metadataIterator.clear();
allOverrides.clear();
blockOverrides.clear();
tileOverrides.clear();
lastOverride = null;
RenderBlocksUtils.blankIcon = null;
tileLoader = new TileLoader("textures/blocks", logger);
RenderPassAPI.instance.refreshBlendingOptions();
if (MCPatcherForgeConfig.ConnectedTextures.standard || MCPatcherForgeConfig.ConnectedTextures.nonStandard) {
for (ResourceLocation resource : ResourceList.getInstance()
.listResources(TexturePackAPI.MCPATCHER_SUBDIR + "ctm", ".properties", true)) {
registerOverride(TileOverride.create(resource, tileLoader));
}
}
for (ResourceLocation resource : BlendMethod.getAllBlankResources()) {
tileLoader.preloadTile(resource, false);
}
} finally {
lock.unlock();
}
}
@Override
public void afterChange() {
for (TileOverride override : allOverrides) {
override.registerIcons();
}
for (Map.Entry<Block, List<BlockStateMatcher>> entry : blockOverrides.entrySet()) {
for (BlockStateMatcher matcher : entry.getValue()) {
TileOverride override = (TileOverride) matcher.getData();
if (override.getRenderPass() >= 0) {
RenderPassAPI.instance.setRenderPassForBlock(entry.getKey(), override.getRenderPass());
lock.lock();
try {
for (TileOverride override : allOverrides) {
override.registerIcons();
}
for (Map.Entry<Block, List<BlockStateMatcher>> entry : blockOverrides.entrySet()) {
for (BlockStateMatcher matcher : entry.getValue()) {
TileOverride override = (TileOverride) matcher.getData();
if (override.getRenderPass() >= 0) {
RenderPassAPI.instance.setRenderPassForBlock(entry.getKey(), override.getRenderPass());
}
}
}
for (List<BlockStateMatcher> overrides : blockOverrides.values()) {
overrides.sort((m1, m2) -> {
TileOverride o1 = (TileOverride) m1.getData();
TileOverride o2 = (TileOverride) m2.getData();
return o1.compareTo(o2);
});
}
for (List<TileOverride> overrides : tileOverrides.values()) {
Collections.sort(overrides);
}
setBlankResource();
} finally {
lock.unlock();
}
for (List<BlockStateMatcher> overrides : blockOverrides.values()) {
overrides.sort((m1, m2) -> {
TileOverride o1 = (TileOverride) m1.getData();
TileOverride o2 = (TileOverride) m2.getData();
return o1.compareTo(o2);
});
}
for (List<TileOverride> overrides : tileOverrides.values()) {
Collections.sort(overrides);
}
setBlankResource();
}
});
}
@@ -118,40 +133,53 @@ public class CTMUtils {
haveBlockFace = false;
}
public static synchronized IIcon getBlockIcon(IIcon icon, Block block, IBlockAccess blockAccess,
int x, int y, int z, int face) {
lastOverride = null;
if (blockAccess != null && checkFace(face)) {
if (!haveBlockFace) {
renderBlockState.setBlock(block, blockAccess, x, y, z);
renderBlockState.setFace(face);
}
lastOverride = ijkIterator.go(renderBlockState, icon);
if (lastOverride != null) {
icon = ijkIterator.getIcon();
public static IIcon getBlockIcon(IIcon icon, Block block, IBlockAccess blockAccess,
int x, int y, int z, int face) {
lock.lock();
try {
lastOverride = null;
if (blockAccess != null && checkFace(face)) {
if (!haveBlockFace) {
renderBlockState.setBlock(block, blockAccess, x, y, z);
renderBlockState.setFace(face);
}
lastOverride = ijkIterator.go(renderBlockState, icon);
if (lastOverride != null) {
icon = ijkIterator.getIcon();
}
}
clearBlockFace();
IIcon result = lastOverride == null && skipDefaultRendering(block) ? RenderBlocksUtils.blankIcon : icon;
return result;
} finally {
lock.unlock();
}
clearBlockFace();
return lastOverride == null && skipDefaultRendering(block) ? RenderBlocksUtils.blankIcon : icon;
}
public static synchronized IIcon getBlockIcon(IIcon icon, Block block, int face, int metadata) {
lastOverride = null;
if (checkFace(face) && checkRenderType(block)) {
renderBlockState.setBlockMetadata(block, metadata, face);
lastOverride = metadataIterator.go(renderBlockState, icon);
if (lastOverride != null) {
icon = metadataIterator.getIcon();
public static IIcon getBlockIcon(IIcon icon, Block block, int face, int metadata) {
lock.lock();
try {
lastOverride = null;
if (checkFace(face) && checkRenderType(block)) {
renderBlockState.setBlockMetadata(block, metadata, face);
lastOverride = metadataIterator.go(renderBlockState, icon);
if (lastOverride != null) {
icon = metadataIterator.getIcon();
}
}
return icon;
} finally {
lock.unlock();
}
return icon;
}
public static IIcon getBlockIcon(IIcon icon, Block block, int face) {
return getBlockIcon(icon, block, face, 0);
}
public static void reset() {}
public static void reset() {
}
private static boolean checkFace(int face) {
return face < 0 ? MCPatcherForgeConfig.ConnectedTextures.nonStandard : MCPatcherForgeConfig.ConnectedTextures.standard;
@@ -165,50 +193,60 @@ public class CTMUtils {
};
}
private static synchronized boolean skipDefaultRendering(Block block) {
private static boolean skipDefaultRendering(Block block) {
return RenderPassAPI.instance.skipDefaultRendering(block);
}
private static synchronized void registerOverride(TileOverride override) {
if (override != null && !override.isDisabled()) {
boolean registered = false;
List<BlockStateMatcher> matchingBlocks = override.getMatchingBlocks();
if (!MCPatcherUtils.isNullOrEmpty(matchingBlocks)) {
for (BlockStateMatcher matcher : matchingBlocks) {
if (matcher == null) {
continue;
private static void registerOverride(TileOverride override) {
lock.lock();
try {
if (override != null && !override.isDisabled()) {
boolean registered = false;
List<BlockStateMatcher> matchingBlocks = override.getMatchingBlocks();
if (!MCPatcherUtils.isNullOrEmpty(matchingBlocks)) {
for (BlockStateMatcher matcher : matchingBlocks) {
if (matcher == null) {
continue;
}
Block block = matcher.getBlock();
List<BlockStateMatcher> list = blockOverrides.computeIfAbsent(block, k -> new ArrayList<>());
list.add(matcher);
logger.fine("using %s for block %s", override, BlockAPI.getBlockName(block));
registered = true;
}
Block block = matcher.getBlock();
List<BlockStateMatcher> list = blockOverrides.computeIfAbsent(block, k -> new ArrayList<>());
list.add(matcher);
logger.fine("using %s for block %s", override, BlockAPI.getBlockName(block));
registered = true;
}
Set<String> matchingTiles = override.getMatchingTiles();
if (!MCPatcherUtils.isNullOrEmpty(matchingTiles)) {
for (String name : matchingTiles) {
List<TileOverride> list = tileOverrides.computeIfAbsent(name, k -> new ArrayList<>());
list.add(override);
logger.fine("using %s for tile %s", override, name);
registered = true;
}
}
if (registered) {
allOverrides.add(override);
}
}
Set<String> matchingTiles = override.getMatchingTiles();
if (!MCPatcherUtils.isNullOrEmpty(matchingTiles)) {
for (String name : matchingTiles) {
List<TileOverride> list = tileOverrides.computeIfAbsent(name, k -> new ArrayList<>());
list.add(override);
logger.fine("using %s for tile %s", override, name);
registered = true;
}
}
if (registered) {
allOverrides.add(override);
}
} finally {
lock.unlock();
}
}
public static synchronized void setBlankResource() {
RenderBlocksUtils.blankIcon = tileLoader.getIcon(RenderPassAPI.instance.getBlankResource());
public static void setBlankResource() {
lock.lock();
try {
RenderBlocksUtils.blankIcon = tileLoader.getIcon(RenderPassAPI.instance.getBlankResource());
} finally {
lock.unlock();
}
}
public static TileOverrideIterator.IJK newIJKIterator() {
private static TileOverrideIterator.IJK newIJKIterator() {
return new TileOverrideIterator.IJK(blockOverrides, tileOverrides);
}
public static TileOverrideIterator.Metadata newMetadataIterator() {
private static TileOverrideIterator.Metadata newMetadataIterator() {
return new TileOverrideIterator.Metadata(blockOverrides, tileOverrides);
}
}
@@ -37,7 +37,7 @@ abstract public class TileOverrideIterator implements Iterator<TileOverride> {
this.allTileOverrides = allTileOverrides;
}
synchronized void clear() {
void clear() {
currentIcon = null;
blockOverrides = null;
tileOverrides = null;
@@ -46,7 +46,7 @@ abstract public class TileOverrideIterator implements Iterator<TileOverride> {
skipOverrides.clear();
}
private synchronized void resetForNextPass() {
private void resetForNextPass() {
blockOverrides = null;
tileOverrides = allTileOverrides.get(currentIcon.getIconName());
blockPos = 0;
@@ -55,7 +55,7 @@ abstract public class TileOverrideIterator implements Iterator<TileOverride> {
}
@Override
public synchronized boolean hasNext() {
public boolean hasNext() {
if (foundNext) {
return true;
}
@@ -80,7 +80,7 @@ abstract public class TileOverrideIterator implements Iterator<TileOverride> {
}
@Override
public synchronized TileOverride next() {
public TileOverride next() {
if (!foundNext) {
throw new IllegalStateException("next called before hasNext() == true");
}
@@ -89,11 +89,11 @@ abstract public class TileOverrideIterator implements Iterator<TileOverride> {
}
@Override
public synchronized void remove() {
public void remove() {
throw new UnsupportedOperationException("remove not supported");
}
private synchronized boolean checkOverride(TileOverride override) {
private boolean checkOverride(TileOverride override) {
if (override != null && !override.isDisabled() && !skipOverrides.contains(override)) {
foundNext = true;
nextOverride = override;
@@ -103,7 +103,7 @@ abstract public class TileOverrideIterator implements Iterator<TileOverride> {
}
}
public synchronized TileOverride go(RenderBlockState renderBlockState, IIcon origIcon) {
public TileOverride go(RenderBlockState renderBlockState, IIcon origIcon) {
this.renderBlockState = renderBlockState;
renderBlockState.setFilter(null);
currentIcon = origIcon;
@@ -133,7 +133,7 @@ abstract public class TileOverrideIterator implements Iterator<TileOverride> {
return lastMatchedOverride;
}
public synchronized IIcon getIcon() {
public IIcon getIcon() {
return currentIcon;
}
@@ -146,7 +146,7 @@ abstract public class TileOverrideIterator implements Iterator<TileOverride> {
}
@Override
protected synchronized IIcon getTile(TileOverride override, RenderBlockState renderBlockState, IIcon origIcon) {
protected IIcon getTile(TileOverride override, RenderBlockState renderBlockState, IIcon origIcon) {
return override.getTileWorld(renderBlockState, origIcon);
}
}
@@ -158,7 +158,7 @@ abstract public class TileOverrideIterator implements Iterator<TileOverride> {
}
@Override
protected synchronized IIcon getTile(TileOverride override, RenderBlockState renderBlockState, IIcon origIcon) {
protected IIcon getTile(TileOverride override, RenderBlockState renderBlockState, IIcon origIcon) {
return override.getTileHeld(renderBlockState, origIcon);
}
}
@@ -1,7 +1,6 @@
package jss.notfine.gui;
import com.google.common.collect.ImmutableList;
import com.gtnewhorizons.angelica.dynamiclights.DynamicLights;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import jss.notfine.config.NotFineConfig;
import jss.notfine.core.Settings;
@@ -297,7 +296,7 @@ public class NotFineGameOptionPages {
.setTooltip(I18n.format("sodium.options.use_block_face_culling.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.MEDIUM)
.setBinding((opts, value) -> opts.advanced.useBlockFaceCulling = value, opts -> opts.advanced.useBlockFaceCulling)
.setBinding((opts, value) -> opts.performance.useBlockFaceCulling = value, opts -> opts.performance.useBlockFaceCulling)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build())
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
@@ -305,14 +304,14 @@ public class NotFineGameOptionPages {
.setTooltip(I18n.format("sodium.options.use_compact_vertex_format.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.MEDIUM)
.setBinding((opts, value) -> opts.advanced.useCompactVertexFormat = value, opts -> opts.advanced.useCompactVertexFormat)
.setBinding((opts, value) -> opts.performance.useCompactVertexFormat = value, opts -> opts.performance.useCompactVertexFormat)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build())
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setName(I18n.format("sodium.options.use_fog_occlusion.name"))
.setTooltip(I18n.format("sodium.options.use_fog_occlusion.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.advanced.useFogOcclusion = value, opts -> opts.advanced.useFogOcclusion)
.setBinding((opts, value) -> opts.performance.useFogOcclusion = value, opts -> opts.performance.useFogOcclusion)
.setImpact(OptionImpact.MEDIUM)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build())
@@ -320,7 +319,7 @@ public class NotFineGameOptionPages {
.setName(I18n.format("sodium.options.translucency_sorting.name"))
.setTooltip(I18n.format("sodium.options.translucency_sorting.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.advanced.translucencySorting = value, opts -> opts.advanced.translucencySorting)
.setBinding((opts, value) -> opts.performance.translucencySorting = value, opts -> opts.performance.translucencySorting)
.setImpact(OptionImpact.MEDIUM)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build())
@@ -329,7 +328,7 @@ public class NotFineGameOptionPages {
.setTooltip(I18n.format("sodium.options.use_entity_culling.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.MEDIUM)
.setBinding((opts, value) -> opts.advanced.useEntityCulling = value, opts -> opts.advanced.useEntityCulling)
.setBinding((opts, value) -> opts.performance.useEntityCulling = value, opts -> opts.performance.useEntityCulling)
.build())
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setName(I18n.format("sodium.options.use_particle_culling.name"))
@@ -345,7 +344,7 @@ public class NotFineGameOptionPages {
.setTooltip(I18n.format("sodium.options.animate_only_visible_textures.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.MEDIUM)
.setBinding((opts, value) -> opts.advanced.animateOnlyVisibleTextures = value, opts -> opts.advanced.animateOnlyVisibleTextures)
.setBinding((opts, value) -> opts.performance.animateOnlyVisibleTextures = value, opts -> opts.performance.animateOnlyVisibleTextures)
.build())
.build());
groups.add(OptionGroup.createBuilder()
@@ -4,7 +4,6 @@ import com.gtnewhorizons.angelica.client.gui.FontConfigScreen;
import com.gtnewhorizons.angelica.compat.mojang.Element;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import jss.notfine.gui.GuiCustomMenu;
import net.coderbot.iris.Iris;
import me.flashyreese.mods.reeses_sodium_options.client.gui.frame.AbstractFrame;
import me.flashyreese.mods.reeses_sodium_options.client.gui.frame.BasicFrame;
import me.flashyreese.mods.reeses_sodium_options.client.gui.frame.components.SearchTextFieldComponent;
@@ -19,6 +18,7 @@ import me.jellysquid.mods.sodium.client.gui.options.OptionPage;
import me.jellysquid.mods.sodium.client.gui.options.storage.OptionStorage;
import me.jellysquid.mods.sodium.client.gui.widgets.FlatButtonWidget;
import me.jellysquid.mods.sodium.client.util.Dim2i;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gui.screen.ShaderPackScreen;
import net.irisshaders.iris.api.v0.IrisApi;
import net.minecraft.client.gui.GuiScreen;
@@ -283,7 +283,7 @@ public class ReeseSodiumVideoOptionsScreen extends SodiumOptionsGUI {
}
if (keyCode == Keyboard.KEY_P) {
if(isShiftKeyDown()){
this.mc.displayGuiScreen(new GuiCustomMenu(this.prevScreen, SodiumGameOptionPages.general(), SodiumGameOptionPages.quality(), SodiumGameOptionPages.advanced(), SodiumGameOptionPages.performance()));
this.mc.displayGuiScreen(new GuiCustomMenu(this.prevScreen, SodiumGameOptionPages.general(), SodiumGameOptionPages.quality(), SodiumGameOptionPages.advanced(), SodiumGameOptionPages.performance(), SodiumGameOptionPages.appearance(), SodiumGameOptionPages.debug()));
} else if (isCtrlKeyDown()) {
this.mc.displayGuiScreen(new SodiumOptionsGUI(this.prevScreen));
}
@@ -1,88 +0,0 @@
package me.jellysquid.mods.sodium.client;
import com.gtnewhorizons.angelica.Tags;
import com.gtnewhorizons.angelica.config.ConfigMigrator;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import lombok.Getter;
import me.jellysquid.mods.sodium.client.gui.SodiumGameOptions;
import me.jellysquid.mods.sodium.proxy.CommonProxy;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@Mod(modid = SodiumClientMod.MODID,
name = SodiumClientMod.NAME,
version = Tags.VERSION,
acceptedMinecraftVersions = "[1.7.10]",
acceptableRemoteVersions = "*")
public class SodiumClientMod {
@SidedProxy(clientSide = "me.jellysquid.mods.sodium.proxy.ClientProxy", serverSide = "me.jellysquid.mods.sodium.proxy.CommonProxy")
public static CommonProxy proxy;
private static SodiumGameOptions CONFIG;
public static Logger LOGGER = LogManager.getLogger("Embeddium");
private static String MOD_VERSION = Tags.VERSION;
public static final String MODID = "embeddium";
public static final String NAME = "Embeddium";
@Getter
private static Thread MainThread;
public SodiumClientMod() {
MainThread = Thread.currentThread();
}
public static SodiumGameOptions options() {
if (CONFIG == null) {
CONFIG = loadConfig();
}
return CONFIG;
}
public static Logger logger() {
if (LOGGER == null) {
LOGGER = LogManager.getLogger("Embeddium");
}
return LOGGER;
}
private static SodiumGameOptions loadConfig() {
return SodiumGameOptions.load(ConfigMigrator.handleConfigMigration("angelica-options.json"));
}
public static String getVersion() {
if (MOD_VERSION == null) {
throw new NullPointerException("Mod version hasn't been populated yet");
}
return MOD_VERSION;
}
@Mod.EventHandler
public void preInit(FMLPreInitializationEvent event) {
proxy.preInit(event);
}
@Mod.EventHandler
public void init(FMLInitializationEvent event) {
proxy.init(event);
}
@Mod.EventHandler
public void postInit(FMLPostInitializationEvent event) {
proxy.postInit(event);
}
public static boolean isDirectMemoryAccessEnabled() {
return options().advanced.allowDirectMemoryAccess;
}
}
@@ -2,7 +2,6 @@ package me.jellysquid.mods.sodium.client.gui;
import com.google.common.collect.ImmutableList;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.dynamiclights.DynamicLights;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import jss.notfine.core.Settings;
import jss.notfine.core.SettingsManager;
@@ -28,6 +27,7 @@ import net.coderbot.iris.gui.option.IrisVideoSettings;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.I18n;
import net.minecraft.client.settings.GameSettings;
import org.embeddedt.embeddium.impl.render.chunk.occlusion.AsyncOcclusionMode;
import org.lwjgl.opengl.Display;
import java.io.IOException;
@@ -80,19 +80,6 @@ public class SodiumGameOptionPages {
.setControl(opt -> new SliderControl(opt, 0, 100, 1, ControlValueFormatter.brightness()))
.setBinding((opts, value) -> opts.gammaSetting = value * 0.01F, (opts) -> (int) (opts.gammaSetting / 0.01F))
.build());
firstGroupBuilder.add(Settings.MODE_LIGHT_FLICKER.option)
.add(Settings.MODE_SKY.option)
.add(Settings.MODE_SUN_MOON.option)
.add(Settings.RENDER_DISTANCE_CLOUDS.option)
.add(Settings.CLOUD_HEIGHT.option)
.add(Settings.CLOUD_SCALE.option)
.add(Settings.MODE_CLOUD_TRANSLUCENCY.option)
.add(Settings.MODE_STARS.option)
.add(Settings.TOTAL_STARS.option)
.add(Settings.HORIZON_DISABLE.option)
.add(Settings.FOG_DISABLE.option)
.add(Settings.FOG_NEAR_DISTANCE.option)
.add(Settings.VOID_FOG.option);
groups.add(firstGroupBuilder.build());
int maxGuiScale = Math.max(3, Math.min(Minecraft.getMinecraft().displayWidth / 320, Minecraft.getMinecraft().displayHeight / 240));
@@ -166,24 +153,6 @@ public class SodiumGameOptionPages {
.add(Settings.DYNAMIC_FOV.option)
.add(Settings.MODE_WATER.option)
.add(Settings.MODE_DROPPED_ITEMS.option)
.add(
OptionImpl.createBuilder(int.class, angelicaOpts)
.setName(I18n.format("options.angelica.droppedItemLimit"))
.setTooltip(I18n.format("options.angelica.droppedItemLimit.tooltip"))
.setControl(option -> new SliderControl(option, 32, 2048, 32, ControlValueFormatter.droppedItemLimitLimit()))
.setBinding((options, value) -> AngelicaConfig.droppedItemLimit = value, options -> AngelicaConfig.droppedItemLimit)
.setImpact(OptionImpact.MEDIUM)
.build()
)
.add(
OptionImpl.createBuilder(int.class, angelicaOpts)
.setName(I18n.format("options.angelica.mobSpawnerRenderDistance"))
.setTooltip(I18n.format("options.angelica.mobSpawnerRenderDistance.tooltip"))
.setControl(option -> new SliderControl(option, 16, 64, 1, ControlValueFormatter.number()))
.setBinding((options, value) -> AngelicaConfig.mobSpawnerRenderDistance = value, options -> (int) AngelicaConfig.mobSpawnerRenderDistance)
.setImpact(OptionImpact.MEDIUM)
.build()
)
.build());
return new OptionPage(I18n.format("stat.generalButton"), ImmutableList.copyOf(groups));
@@ -305,7 +274,7 @@ public class SodiumGameOptionPages {
.setTooltip(I18n.format("sodium.options.use_block_face_culling.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.MEDIUM)
.setBinding((opts, value) -> opts.advanced.useBlockFaceCulling = value, opts -> opts.advanced.useBlockFaceCulling)
.setBinding((opts, value) -> opts.performance.useBlockFaceCulling = value, opts -> opts.performance.useBlockFaceCulling)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build()
)
@@ -314,7 +283,7 @@ public class SodiumGameOptionPages {
.setTooltip(I18n.format("sodium.options.use_compact_vertex_format.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.MEDIUM)
.setBinding((opts, value) -> opts.advanced.useCompactVertexFormat = value, opts -> opts.advanced.useCompactVertexFormat)
.setBinding((opts, value) -> opts.performance.useCompactVertexFormat = value, opts -> opts.performance.useCompactVertexFormat)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build()
)
@@ -322,7 +291,7 @@ public class SodiumGameOptionPages {
.setName(I18n.format("sodium.options.use_fog_occlusion.name"))
.setTooltip(I18n.format("sodium.options.use_fog_occlusion.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.advanced.useFogOcclusion = value, opts -> opts.advanced.useFogOcclusion)
.setBinding((opts, value) -> opts.performance.useFogOcclusion = value, opts -> opts.performance.useFogOcclusion)
.setImpact(OptionImpact.MEDIUM)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build()
@@ -331,7 +300,7 @@ public class SodiumGameOptionPages {
.setName(I18n.format("sodium.options.translucency_sorting.name"))
.setTooltip(I18n.format("sodium.options.translucency_sorting.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.advanced.translucencySorting = value, opts -> opts.advanced.translucencySorting)
.setBinding((opts, value) -> opts.performance.translucencySorting = value, opts -> opts.performance.translucencySorting)
.setImpact(OptionImpact.MEDIUM)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build()
@@ -341,7 +310,7 @@ public class SodiumGameOptionPages {
.setTooltip(I18n.format("sodium.options.use_entity_culling.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.MEDIUM)
.setBinding((opts, value) -> opts.advanced.useEntityCulling = value, opts -> opts.advanced.useEntityCulling)
.setBinding((opts, value) -> opts.performance.useEntityCulling = value, opts -> opts.performance.useEntityCulling)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
@@ -357,7 +326,34 @@ public class SodiumGameOptionPages {
.setTooltip(I18n.format("sodium.options.animate_only_visible_textures.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.MEDIUM)
.setBinding((opts, value) -> opts.advanced.animateOnlyVisibleTextures = value, opts -> opts.advanced.animateOnlyVisibleTextures)
.setBinding((opts, value) -> opts.performance.animateOnlyVisibleTextures = value, opts -> opts.performance.animateOnlyVisibleTextures)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setName(I18n.format("sodium.options.use_render_pass_optimization.name"))
.setTooltip(I18n.format("sodium.options.use_render_pass_optimization.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.MEDIUM)
.setBinding((opts, value) -> opts.performance.useRenderPassOptimization = value, opts -> opts.performance.useRenderPassOptimization)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setName(I18n.format("sodium.options.use_occlusion_culling.name"))
.setTooltip(I18n.format("sodium.options.use_occlusion_culling.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.EXTREME)
.setBinding((opts, value) -> opts.performance.useOcclusionCulling = value, opts -> opts.performance.useOcclusionCulling)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build()
)
.add(OptionImpl.createBuilder(AsyncOcclusionMode.class, sodiumOpts)
.setName(I18n.format("sodium.options.async_occlusion_mode.name"))
.setTooltip(I18n.format("sodium.options.async_occlusion_mode.tooltip"))
.setControl(o -> new CyclingControl<>(o, AsyncOcclusionMode.class, new String[]{"None", "Only Shadow", "Everything"}))
.setImpact(OptionImpact.MEDIUM)
.setBinding((opts, value) -> opts.performance.asyncOcclusionMode = value, opts -> opts.performance.asyncOcclusionMode)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build()
)
.build());
@@ -383,22 +379,6 @@ public class SodiumGameOptionPages {
)
.build());
groups.add(OptionGroup.createBuilder()
.add(OptionImpl.createBuilder(int.class, angelicaOpts)
.setName(I18n.format("options.angelica.itemdisplaylistcount"))
.setTooltip(I18n.format("options.angelica.itemdisplaylistcount.tooltip"))
.setControl(o -> new SliderControl(o, 256, 1024, 16, ControlValueFormatter.number()))
.setImpact(OptionImpact.MEDIUM)
.setBinding((opts, value) -> AngelicaConfig.itemRendererCacheSize = value, options -> AngelicaConfig.itemRendererCacheSize)
.build()
)
.build());
groups.add(OptionGroup.createBuilder()
.add(Settings.MODE_GUI_BACKGROUND.option)
.add(Settings.GUI_BACKGROUND.option)
.build());
return new OptionPage(I18n.format("sodium.options.pages.advanced"), ImmutableList.copyOf(groups));
}
@@ -440,14 +420,6 @@ public class SodiumGameOptionPages {
.setBinding((opts, value) -> opts.performance.useNoErrorGLContext = value, opts -> opts.performance.useNoErrorGLContext)
.setFlags(OptionFlag.REQUIRES_GAME_RESTART)
.build())
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setName(I18n.format("sodium.options.use_gl_state_cache.name"))
.setTooltip(I18n.format("sodium.options.use_gl_state_cache.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.EXTREME)
.setBinding((opts, value) -> GLStateManager.BYPASS_CACHE = !value, opts -> !GLStateManager.BYPASS_CACHE)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build())
.add(OptionImpl.createBuilder(boolean.class, angelicaOpts)
.setName(I18n.format("options.angelica.aggressiveChunkLoading"))
.setTooltip(I18n.format("options.angelica.aggressiveChunkLoading.tooltip"))
@@ -456,9 +428,94 @@ public class SodiumGameOptionPages {
.setBinding((opts, value) -> AngelicaConfig.useVanillaChunkTracking = value, opts -> AngelicaConfig.useVanillaChunkTracking)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build())
.add(OptionImpl.createBuilder(int.class, sodiumOpts)
.setName(I18n.format("sodium.options.cpu_render_ahead_limit.name"))
.setTooltip(I18n.format("sodium.options.cpu_render_ahead_limit.tooltip"))
.setControl(o -> new SliderControl(o, 0, 9, 1, ControlValueFormatter.quantity("sodium.options.cpu_render_ahead_limit.value")))
.setImpact(OptionImpact.MEDIUM)
.setBinding((opts, value) -> opts.performance.cpuRenderAheadLimit = value, opts -> opts.performance.cpuRenderAheadLimit)
.setEnabled(GLStateManager.capabilities != null && GLStateManager.capabilities.OpenGL32)
.build())
.build());
groups.add(OptionGroup.createBuilder()
.add(OptionImpl.createBuilder(int.class, angelicaOpts)
.setName(I18n.format("options.angelica.droppedItemLimit"))
.setTooltip(I18n.format("options.angelica.droppedItemLimit.tooltip"))
.setControl(option -> new SliderControl(option, 32, 2048, 32, ControlValueFormatter.droppedItemLimitLimit()))
.setBinding((options, value) -> AngelicaConfig.droppedItemLimit = value, options -> AngelicaConfig.droppedItemLimit)
.setImpact(OptionImpact.MEDIUM)
.build())
.add(OptionImpl.createBuilder(int.class, angelicaOpts)
.setName(I18n.format("options.angelica.mobSpawnerRenderDistance"))
.setTooltip(I18n.format("options.angelica.mobSpawnerRenderDistance.tooltip"))
.setControl(option -> new SliderControl(option, 16, 64, 1, ControlValueFormatter.number()))
.setBinding((options, value) -> AngelicaConfig.mobSpawnerRenderDistance = value, options -> (int) AngelicaConfig.mobSpawnerRenderDistance)
.setImpact(OptionImpact.MEDIUM)
.build())
.add(OptionImpl.createBuilder(int.class, angelicaOpts)
.setName(I18n.format("options.angelica.itemdisplaylistcount"))
.setTooltip(I18n.format("options.angelica.itemdisplaylistcount.tooltip"))
.setControl(o -> new SliderControl(o, 256, 1024, 16, ControlValueFormatter.number()))
.setImpact(OptionImpact.MEDIUM)
.setBinding((opts, value) -> AngelicaConfig.itemRendererCacheSize = value, options -> AngelicaConfig.itemRendererCacheSize)
.build())
.build());
return new OptionPage(I18n.format("sodium.options.pages.performance"), ImmutableList.copyOf(groups));
}
public static OptionPage appearance() {
final List<OptionGroup> groups = new ArrayList<>();
groups.add(OptionGroup.createBuilder()
.add(Settings.MODE_SKY.option)
.add(Settings.MODE_SUN_MOON.option)
.add(Settings.RENDER_DISTANCE_CLOUDS.option)
.add(Settings.CLOUD_HEIGHT.option)
.add(Settings.CLOUD_SCALE.option)
.add(Settings.MODE_CLOUD_TRANSLUCENCY.option)
.add(Settings.MODE_STARS.option)
.add(Settings.TOTAL_STARS.option)
.add(Settings.HORIZON_DISABLE.option)
.add(Settings.MODE_LIGHT_FLICKER.option)
.build());
groups.add(OptionGroup.createBuilder()
.add(Settings.FOG_DISABLE.option)
.add(Settings.FOG_NEAR_DISTANCE.option)
.add(Settings.VOID_FOG.option)
.build());
groups.add(OptionGroup.createBuilder()
.add(Settings.MODE_GUI_BACKGROUND.option)
.add(Settings.GUI_BACKGROUND.option)
.add(OptionImpl.createBuilder(boolean.class, angelicaOpts)
.setName(I18n.format("options.angelica.disablef3"))
.setTooltip(I18n.format("options.angelica.disablef3.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> AngelicaConfig.disableF3Additions = value, opts -> AngelicaConfig.disableF3Additions)
.build())
.build());
return new OptionPage(I18n.format("sodium.options.pages.appearance"), ImmutableList.copyOf(groups));
}
public static OptionPage debug() {
final List<OptionGroup> groups = new ArrayList<>();
groups.add(OptionGroup.createBuilder()
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setName(I18n.format("sodium.options.use_gl_state_cache.name"))
.setTooltip(I18n.format("sodium.options.use_gl_state_cache.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.EXTREME)
.setBinding((opts, value) -> GLStateManager.BYPASS_CACHE = !value, opts -> !GLStateManager.BYPASS_CACHE)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build())
.build());
return new OptionPage(I18n.format("sodium.options.pages.debug"), ImmutableList.copyOf(groups));
}
}
@@ -4,9 +4,11 @@ import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import me.jellysquid.mods.sodium.client.SodiumClientMod;
import com.gtnewhorizons.angelica.AngelicaMod;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import me.jellysquid.mods.sodium.client.gui.options.named.GraphicsQuality;
import net.coderbot.iris.Iris;
import org.embeddedt.embeddium.impl.render.chunk.occlusion.AsyncOcclusionMode;
import java.io.FileReader;
import java.io.IOException;
@@ -26,21 +28,26 @@ public class SodiumGameOptions {
public boolean useVertexArrayObjects = true;
public boolean useChunkMultidraw = true;
public boolean animateOnlyVisibleTextures = true;
public boolean useEntityCulling = true;
public boolean useParticleCulling = true;
public boolean useFogOcclusion = true;
public boolean useCompactVertexFormat = true;
public boolean useBlockFaceCulling = true;
public boolean allowDirectMemoryAccess = true;
public boolean ignoreDriverBlacklist = false;
public boolean translucencySorting = true;
}
public static class PerformanceSettings {
public int chunkBuilderThreads = 0;
public boolean alwaysDeferChunkUpdates = true;
public boolean useNoErrorGLContext = true;
public AsyncOcclusionMode asyncOcclusionMode = AsyncOcclusionMode.EVERYTHING;
public boolean useOcclusionCulling = true;
public boolean animateOnlyVisibleTextures = true;
public boolean useEntityCulling = true;
public boolean useFogOcclusion = true;
public boolean useBlockFaceCulling = true;
public boolean useCompactVertexFormat = true;
public boolean translucencySorting = true;
public boolean useRenderPassOptimization = true;
public int cpuRenderAheadLimit = 3;
}
public static class EntityRenderDistance {
@@ -74,7 +81,7 @@ public class SodiumGameOptions {
} catch (IOException e) {
throw new RuntimeException("Could not parse config", e);
} catch (JsonSyntaxException e) {
SodiumClientMod.logger().error("Could not parse config, will fallback to default settings", e);
AngelicaMod.LOGGER.error("Could not parse config, will fallback to default settings", e);
config = new SodiumGameOptions();
resaveConfig = false;
}
@@ -84,6 +91,11 @@ public class SodiumGameOptions {
config.configPath = path;
// Clamp render-ahead to 0 if GL 3.2 fences aren't available
if (GLStateManager.capabilities == null || !GLStateManager.capabilities.OpenGL32) {
config.performance.cpuRenderAheadLimit = 0;
}
try {
if(resaveConfig)
config.writeChanges();
@@ -7,7 +7,6 @@ import com.gtnewhorizons.angelica.compat.mojang.Drawable;
import com.gtnewhorizons.angelica.compat.mojang.Element;
import com.gtnewhorizons.angelica.dynamiclights.DynamicLights;
import jss.notfine.gui.GuiCustomMenu;
import net.coderbot.iris.Iris;
import me.jellysquid.mods.sodium.client.gui.options.Option;
import me.jellysquid.mods.sodium.client.gui.options.OptionFlag;
import me.jellysquid.mods.sodium.client.gui.options.OptionGroup;
@@ -19,6 +18,7 @@ import me.jellysquid.mods.sodium.client.gui.options.control.element.SodiumContro
import me.jellysquid.mods.sodium.client.gui.options.storage.OptionStorage;
import me.jellysquid.mods.sodium.client.gui.widgets.FlatButtonWidget;
import me.jellysquid.mods.sodium.client.util.Dim2i;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gui.screen.ShaderPackScreen;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.resources.I18n;
@@ -62,6 +62,7 @@ public class SodiumOptionsGUI extends ScrollableGuiScreen {
this.pages.add(SodiumGameOptionPages.quality());
this.pages.add(SodiumGameOptionPages.advanced());
this.pages.add(SodiumGameOptionPages.performance());
this.pages.add(SodiumGameOptionPages.appearance());
// Add Dynamic Lights page if enabled
if (DynamicLights.configEnabled) {
@@ -75,6 +76,8 @@ public class SodiumOptionsGUI extends ScrollableGuiScreen {
shaderPacks = new OptionPage(I18n.format("options.iris.shaderPackSelection"), ImmutableList.of());
this.pages.add(shaderPacks);
}
this.pages.add(SodiumGameOptionPages.debug());
}
public void setPage(OptionPage page) {
@@ -298,7 +301,8 @@ public class SodiumOptionsGUI extends ScrollableGuiScreen {
if (keyCode == Keyboard.KEY_P && isShiftKeyDown()) {
this.mc.displayGuiScreen(new GuiCustomMenu(this.prevScreen, SodiumGameOptionPages.general(),
SodiumGameOptionPages.quality(), SodiumGameOptionPages.advanced(), SodiumGameOptionPages.performance()));
SodiumGameOptionPages.quality(), SodiumGameOptionPages.advanced(), SodiumGameOptionPages.performance(),
SodiumGameOptionPages.appearance(), SodiumGameOptionPages.debug()));
}
}
@@ -1,8 +1,8 @@
package me.jellysquid.mods.sodium.client.gui.options.storage;
import com.gtnewhorizon.gtnhlib.config.ConfigurationManager;
import com.gtnewhorizons.angelica.AngelicaMod;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import me.jellysquid.mods.sodium.client.SodiumClientMod;
public class AngelicaOptionsStorage implements OptionStorage<AngelicaConfig> {
@@ -18,6 +18,6 @@ public class AngelicaOptionsStorage implements OptionStorage<AngelicaConfig> {
@Override
public void save() {
ConfigurationManager.save(AngelicaConfig.class);
SodiumClientMod.logger().info("Flushed changes to Angelica configuration");
AngelicaMod.LOGGER.info("Flushed changes to Angelica configuration");
}
}
@@ -1,6 +1,6 @@
package me.jellysquid.mods.sodium.client.gui.options.storage;
import me.jellysquid.mods.sodium.client.SodiumClientMod;
import com.gtnewhorizons.angelica.AngelicaMod;
import net.minecraft.client.Minecraft;
import net.minecraft.client.settings.GameSettings;
@@ -20,6 +20,6 @@ public class MinecraftOptionsStorage implements OptionStorage<GameSettings> {
public void save() {
this.getData().saveOptions();
SodiumClientMod.logger().info("Flushed changes to Minecraft configuration");
AngelicaMod.LOGGER.info("Flushed changes to Minecraft configuration");
}
}
@@ -1,6 +1,6 @@
package me.jellysquid.mods.sodium.client.gui.options.storage;
import me.jellysquid.mods.sodium.client.SodiumClientMod;
import com.gtnewhorizons.angelica.AngelicaMod;
import me.jellysquid.mods.sodium.client.gui.SodiumGameOptions;
import java.io.IOException;
@@ -9,7 +9,7 @@ public class SodiumOptionsStorage implements OptionStorage<SodiumGameOptions> {
private final SodiumGameOptions options;
public SodiumOptionsStorage() {
this.options = SodiumClientMod.options();
this.options = AngelicaMod.options();
}
@Override
@@ -25,6 +25,6 @@ public class SodiumOptionsStorage implements OptionStorage<SodiumGameOptions> {
throw new RuntimeException("Couldn't save configuration changes", e);
}
SodiumClientMod.logger().info("Flushed changes to Angelica configuration");
AngelicaMod.LOGGER.info("Flushed changes to Angelica configuration");
}
}
@@ -1,6 +1,6 @@
package me.jellysquid.mods.sodium.client.gui.utils;
import me.jellysquid.mods.sodium.client.SodiumClientMod;
import com.gtnewhorizons.angelica.AngelicaMod;
import net.minecraft.util.Util;
import java.io.IOException;
@@ -19,7 +19,7 @@ public class URLUtils {
try {
Runtime.getRuntime().exec(getURLOpenCommand(url));
} catch (IOException exception) {
SodiumClientMod.logger().error("Couldn't open url '{}'", url, exception);
AngelicaMod.LOGGER.error("Couldn't open url '{}'", url, exception);
}
}
@@ -1,56 +0,0 @@
package me.jellysquid.mods.sodium.proxy;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import jss.notfine.gui.GuiCustomMenu;
import jss.notfine.gui.NotFineGameOptionPages;
import me.flashyreese.mods.reeses_sodium_options.client.gui.ReeseSodiumVideoOptionsScreen;
import me.jellysquid.mods.sodium.client.gui.SodiumOptionsGUI;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiVideoSettings;
import net.minecraftforge.client.event.GuiScreenEvent;
import net.minecraftforge.common.MinecraftForge;
public class ClientProxy extends CommonProxy {
@Override
public void preInit(FMLPreInitializationEvent event) {
// FMLCommonHandler.instance().bus().register(this);
MinecraftForge.EVENT_BUS.register(this);
}
@SubscribeEvent
public void onGui(GuiScreenEvent.InitGuiEvent.Pre event) {
if(event.gui instanceof GuiVideoSettings eventGui) {
event.setCanceled(true);
if(AngelicaConfig.enableNotFineOptions || GuiScreen.isShiftKeyDown()) {
Minecraft.getMinecraft().displayGuiScreen(new GuiCustomMenu(eventGui.parentGuiScreen,
NotFineGameOptionPages.general(),
NotFineGameOptionPages.detail(), NotFineGameOptionPages.atmosphere(),
NotFineGameOptionPages.particles(), NotFineGameOptionPages.other()
));
} else if(!AngelicaConfig.enableReesesSodiumOptions || GuiScreen.isCtrlKeyDown()) {
Minecraft.getMinecraft().displayGuiScreen(new SodiumOptionsGUI(eventGui.parentGuiScreen));
} else {
Minecraft.getMinecraft().displayGuiScreen(new ReeseSodiumVideoOptionsScreen(eventGui.parentGuiScreen));
}
}
}
@Override
public void init(FMLInitializationEvent event) {
// Nothing to do here (yet)
}
@Override
public void postInit(FMLPostInitializationEvent event) {
// Nothing to do here (yet)
}
}
@@ -1,16 +0,0 @@
package me.jellysquid.mods.sodium.proxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
public class CommonProxy {
public void preInit(FMLPreInitializationEvent event) {
}
public void init(FMLInitializationEvent event) {}
public void postInit(FMLPostInitializationEvent event) {}
}
@@ -390,6 +390,9 @@ public class Iris {
// Warm up the threadpool so shader transformations are faster when we need them
ShaderTransformExecutor.warmup();
// Initialize version hoisting pattern based on GL capabilities
ShaderTransformer.init();
PBRTextureManager.INSTANCE.init();
// Only load the shader pack when we can access OpenGL
@@ -12,8 +12,10 @@ import net.coderbot.iris.gl.program.ProgramUniforms;
import net.coderbot.iris.pipeline.PatchedShaderPrinter;
import net.coderbot.iris.pipeline.transform.PatchShaderType;
import net.coderbot.iris.rendertarget.RenderTargets;
import net.coderbot.iris.gl.state.FogMode;
import net.coderbot.iris.uniforms.CommonUniforms;
import net.coderbot.iris.uniforms.builtin.BuiltinReplacementUniforms;
import net.coderbot.iris.shaderpack.ProgramSource;
import net.coderbot.iris.uniforms.custom.CustomUniforms;
import org.jetbrains.annotations.Nullable;
@@ -60,124 +62,82 @@ public class CeleritasTerrainPipeline {
IntFunction<ProgramImages> createTerrainImages,
IntFunction<ProgramImages> createShadowImages,
CustomUniforms customUniforms,
String terrainSourceName,
String translucentSourceName,
String shadowSourceName,
Optional<ProgramSource> terrainSource,
Optional<ProgramSource> translucentSource,
Optional<ProgramSource> shadowSource,
CompletableFuture<Map<PatchShaderType, String>> terrainFuture,
CompletableFuture<Map<PatchShaderType, String>> translucentFuture,
CompletableFuture<Map<PatchShaderType, String>> shadowFuture,
RenderTargets renderTargets,
ImmutableSet<Integer> flippedAfterPrepare,
ImmutableSet<Integer> flippedAfterTranslucent,
@Nullable GlFramebuffer shadowFramebuffer,
int[] terrainDrawBuffers
@Nullable GlFramebuffer shadowFramebuffer
) {
this.customUniforms = customUniforms;
// Initialize PassInfo for each pass
for (IrisTerrainPass pass : IrisTerrainPass.VALUES) {
passInfoMap.put(pass, new PassInfo());
}
// Process terrain shaders (used for GBUFFER_SOLID and GBUFFER_CUTOUT)
if (terrainFuture != null) {
try {
final Map<PatchShaderType, String> result = terrainFuture.join();
final PassInfo solidInfo = passInfoMap.get(IrisTerrainPass.GBUFFER_SOLID);
final PassInfo cutoutInfo = passInfoMap.get(IrisTerrainPass.GBUFFER_CUTOUT);
solidInfo.setSource(PatchShaderType.VERTEX, result.get(PatchShaderType.VERTEX));
solidInfo.setSource(PatchShaderType.GEOMETRY, result.get(PatchShaderType.GEOMETRY));
solidInfo.setSource(PatchShaderType.FRAGMENT, result.get(PatchShaderType.FRAGMENT));
cutoutInfo.setSource(PatchShaderType.VERTEX, result.get(PatchShaderType.VERTEX));
cutoutInfo.setSource(PatchShaderType.GEOMETRY, result.get(PatchShaderType.GEOMETRY));
cutoutInfo.setSource(PatchShaderType.FRAGMENT, result.get(PatchShaderType.FRAGMENT));
PatchedShaderPrinter.debugPatchedShaders(terrainSourceName + "_celeritas",
result.get(PatchShaderType.VERTEX), result.get(PatchShaderType.GEOMETRY), result.get(PatchShaderType.FRAGMENT));
} catch (Exception e) {
Iris.logger.error("Failed to transform terrain shader for Celeritas: {}", terrainSourceName, e);
throw new RuntimeException("Shader transformation failed for " + terrainSourceName, e);
}
}
// Process translucent shaders (used for GBUFFER_TRANSLUCENT)
if (translucentFuture != null) {
try {
final Map<PatchShaderType, String> result = translucentFuture.join();
final PassInfo translucentInfo = passInfoMap.get(IrisTerrainPass.GBUFFER_TRANSLUCENT);
translucentInfo.setSource(PatchShaderType.VERTEX, result.get(PatchShaderType.VERTEX));
translucentInfo.setSource(PatchShaderType.GEOMETRY, result.get(PatchShaderType.GEOMETRY));
translucentInfo.setSource(PatchShaderType.FRAGMENT, result.get(PatchShaderType.FRAGMENT));
PatchedShaderPrinter.debugPatchedShaders(translucentSourceName + "_celeritas",
result.get(PatchShaderType.VERTEX), result.get(PatchShaderType.GEOMETRY), result.get(PatchShaderType.FRAGMENT));
} catch (Exception e) {
Iris.logger.error("Failed to transform translucent shader for Celeritas: {}", translucentSourceName, e);
throw new RuntimeException("Shader transformation failed for " + translucentSourceName, e);
}
}
// Process shadow shaders (used for SHADOW and SHADOW_CUTOUT)
if (shadowFuture != null) {
try {
final Map<PatchShaderType, String> result = shadowFuture.join();
final PassInfo shadowInfo = passInfoMap.get(IrisTerrainPass.SHADOW);
final PassInfo shadowCutoutInfo = passInfoMap.get(IrisTerrainPass.SHADOW_CUTOUT);
shadowInfo.setSource(PatchShaderType.VERTEX, result.get(PatchShaderType.VERTEX));
shadowInfo.setSource(PatchShaderType.GEOMETRY, result.get(PatchShaderType.GEOMETRY));
shadowInfo.setSource(PatchShaderType.FRAGMENT, result.get(PatchShaderType.FRAGMENT));
shadowCutoutInfo.setSource(PatchShaderType.VERTEX, result.get(PatchShaderType.VERTEX));
shadowCutoutInfo.setSource(PatchShaderType.GEOMETRY, result.get(PatchShaderType.GEOMETRY));
shadowCutoutInfo.setSource(PatchShaderType.FRAGMENT, result.get(PatchShaderType.FRAGMENT));
PatchedShaderPrinter.debugPatchedShaders(shadowSourceName + "_celeritas",
result.get(PatchShaderType.VERTEX), result.get(PatchShaderType.GEOMETRY), result.get(PatchShaderType.FRAGMENT));
} catch (Exception e) {
Iris.logger.error("Failed to transform shadow shader for Celeritas: {}", shadowSourceName, e);
throw new RuntimeException("Shader transformation failed for " + shadowSourceName, e);
}
}
// Set up framebuffers for each pass
// Shadow passes use the shadow framebuffer
if (shadowFramebuffer != null) {
passInfoMap.get(IrisTerrainPass.SHADOW).framebuffer = shadowFramebuffer;
passInfoMap.get(IrisTerrainPass.SHADOW_CUTOUT).framebuffer = shadowFramebuffer;
}
// GBuffer passes use render target framebuffers
if (renderTargets != null && terrainDrawBuffers != null) {
final GlFramebuffer solidFb = renderTargets.createGbufferFramebuffer(flippedAfterPrepare, terrainDrawBuffers);
final GlFramebuffer translucentFb = renderTargets.createGbufferFramebuffer(flippedAfterTranslucent, terrainDrawBuffers);
passInfoMap.get(IrisTerrainPass.GBUFFER_SOLID).framebuffer = solidFb;
passInfoMap.get(IrisTerrainPass.GBUFFER_CUTOUT).framebuffer = solidFb;
passInfoMap.get(IrisTerrainPass.GBUFFER_TRANSLUCENT).framebuffer = translucentFb;
}
// Set blend mode overrides
passInfoMap.get(IrisTerrainPass.GBUFFER_SOLID).blendModeOverride = BlendModeOverride.OFF;
passInfoMap.get(IrisTerrainPass.GBUFFER_CUTOUT).blendModeOverride = BlendModeOverride.OFF;
passInfoMap.get(IrisTerrainPass.GBUFFER_TRANSLUCENT).blendModeOverride = null; // Default blending
passInfoMap.get(IrisTerrainPass.SHADOW).blendModeOverride = BlendModeOverride.OFF;
passInfoMap.get(IrisTerrainPass.SHADOW_CUTOUT).blendModeOverride = BlendModeOverride.OFF;
// Set alpha references
passInfoMap.get(IrisTerrainPass.GBUFFER_SOLID).alphaReference = 0.0f;
passInfoMap.get(IrisTerrainPass.GBUFFER_CUTOUT).alphaReference = 0.1f;
passInfoMap.get(IrisTerrainPass.GBUFFER_TRANSLUCENT).alphaReference = 0.0f;
passInfoMap.get(IrisTerrainPass.SHADOW).alphaReference = 0.0f;
passInfoMap.get(IrisTerrainPass.SHADOW_CUTOUT).alphaReference = 0.1f;
this.createTerrainSamplers = createTerrainSamplers;
this.createShadowSamplers = createShadowSamplers;
this.createTerrainImages = createTerrainImages;
this.createShadowImages = createShadowImages;
// Build program source map (local - only needed during construction)
final EnumMap<IrisTerrainPass, Optional<ProgramSource>> gbufferProgramSource = new EnumMap<>(IrisTerrainPass.class);
gbufferProgramSource.put(IrisTerrainPass.GBUFFER_SOLID, terrainSource);
gbufferProgramSource.put(IrisTerrainPass.GBUFFER_CUTOUT, terrainSource);
gbufferProgramSource.put(IrisTerrainPass.GBUFFER_TRANSLUCENT, translucentSource.isPresent() ? translucentSource : terrainSource);
gbufferProgramSource.put(IrisTerrainPass.SHADOW, shadowSource);
// Initialize PassInfo, framebuffers, blend modes, and alpha in single pass
for (IrisTerrainPass pass : IrisTerrainPass.VALUES) {
PassInfo passInfo = new PassInfo();
passInfoMap.put(pass, passInfo);
// Set up framebuffer
if (pass == IrisTerrainPass.SHADOW || pass == IrisTerrainPass.SHADOW_CUTOUT) {
passInfo.framebuffer = shadowFramebuffer;
} else if (renderTargets != null) {
ImmutableSet<Integer> flipped = pass == IrisTerrainPass.GBUFFER_TRANSLUCENT ? flippedAfterTranslucent : flippedAfterPrepare;
Optional<ProgramSource> programSource = gbufferProgramSource.get(pass);
programSource.ifPresentOrElse(source -> passInfo.framebuffer = renderTargets.createGbufferFramebuffer(flipped, source.getDirectives().getDrawBuffers()), () -> passInfo.framebuffer = renderTargets.createGbufferFramebuffer(flipped, new int[] {0}));
}
// Set blend mode override
passInfo.blendModeOverride = switch (pass) {
case GBUFFER_TRANSLUCENT -> null; // Default blending
default -> BlendModeOverride.OFF;
};
// Set alpha reference
passInfo.alphaReference = switch (pass) {
case GBUFFER_CUTOUT, SHADOW_CUTOUT -> 0.1f;
default -> 0.0f;
};
}
// Process and apply shader sources
processShaderFuture(terrainFuture, terrainSource, passInfoMap.get(IrisTerrainPass.GBUFFER_SOLID), passInfoMap.get(IrisTerrainPass.GBUFFER_CUTOUT));
processShaderFuture(translucentFuture, translucentSource, passInfoMap.get(IrisTerrainPass.GBUFFER_TRANSLUCENT));
processShaderFuture(shadowFuture, shadowSource, passInfoMap.get(IrisTerrainPass.SHADOW), passInfoMap.get(IrisTerrainPass.SHADOW_CUTOUT));
}
private void processShaderFuture(@Nullable CompletableFuture<Map<PatchShaderType, String>> future, Optional<ProgramSource> source, PassInfo... targets) {
if (future == null || source.isEmpty()) {
return;
}
final String sourceName = source.get().getName();
try {
final Map<PatchShaderType, String> result = future.join();
for (PassInfo target : targets) {
target.setSource(PatchShaderType.VERTEX, result.get(PatchShaderType.VERTEX));
target.setSource(PatchShaderType.GEOMETRY, result.get(PatchShaderType.GEOMETRY));
target.setSource(PatchShaderType.FRAGMENT, result.get(PatchShaderType.FRAGMENT));
}
PatchedShaderPrinter.debugPatchedShaders(sourceName + "_celeritas",
result.get(PatchShaderType.VERTEX), result.get(PatchShaderType.GEOMETRY), result.get(PatchShaderType.FRAGMENT));
} catch (Exception e) {
Iris.logger.error("Failed to transform shader for Celeritas: {}", sourceName, e);
throw new RuntimeException("Shader transformation failed for " + sourceName, e);
}
}
public PassInfo getPassInfo(IrisTerrainPass pass) {
@@ -187,7 +147,7 @@ public class CeleritasTerrainPipeline {
public ProgramUniforms.Builder initUniforms(int programId) {
final ProgramUniforms.Builder uniforms = ProgramUniforms.builder("<celeritas shaders>", programId);
CommonUniforms.addDynamicUniforms(uniforms);
CommonUniforms.addDynamicUniforms(uniforms, FogMode.PER_VERTEX);
customUniforms.assignTo(uniforms);
BuiltinReplacementUniforms.addBuiltinReplacementUniforms(uniforms);
@@ -37,7 +37,7 @@ public class IrisDebugScreenHandler {
@SubscribeEvent(priority = EventPriority.LOW)
public void onRenderGameOverlayTextEvent(RenderGameOverlayEvent.Text event) {
final Minecraft mc = Minecraft.getMinecraft();
if (mc.gameSettings.showDebugInfo) {
if (mc.gameSettings.showDebugInfo && !AngelicaConfig.disableF3Additions) {
event.right.add(Math.min(event.right.size(), 2), "Direct Buffers: +" + iris$humanReadableByteCountBin(iris$directPool.getMemoryUsed()));
if (Iris.getIrisConfig().areShadersEnabled()) {
@@ -15,6 +15,10 @@ public enum FeatureFlags {
BLOCK_EMISSION_ATTRIBUTE(() -> true, () -> true),
CUSTOM_IMAGES(() -> true, RenderSystem::supportsImageLoadStore),
SSBO(() -> true, RenderSystem::supportsSSBO),
HIGHER_SHADOWCOLOR(() -> true, () -> true),
TESSELLATION_SHADERS(() -> true, RenderSystem::supportsTesselation),
REVERSED_CULLING(() -> true, () -> true),
CAN_DISABLE_WEATHER(() -> true, () -> true),
UNKNOWN(() -> false, () -> false);
private final BooleanSupplier irisRequirement;
@@ -55,16 +59,16 @@ public enum FeatureFlags {
}
public static boolean isInvalid(String name) {
try {
return !FeatureFlags.valueOf(name).isUsable();
} catch (IllegalArgumentException e) {
return true;
}
FeatureFlags flag = getValue(name);
return flag == UNKNOWN || !flag.isUsable();
}
public static FeatureFlags getValue(String value) {
if (value.equalsIgnoreCase("TESSELATION_SHADERS")) {
value = "TESSELLATION_SHADERS";
}
try {
return FeatureFlags.valueOf(value);
return FeatureFlags.valueOf(value.toUpperCase(java.util.Locale.US));
} catch (IllegalArgumentException e) {
return FeatureFlags.UNKNOWN;
}
@@ -1,6 +1,8 @@
package net.coderbot.iris.gl.blending;
public class AlphaTest {
public static final AlphaTest ALWAYS = new AlphaTest(AlphaTestFunction.ALWAYS, 0.0f);
private final AlphaTestFunction function;
private final float reference;
@@ -16,4 +18,45 @@ public class AlphaTest {
public float getReference() {
return reference;
}
public String toExpression(String indentation) {
return toExpression("gl_FragData[0].a", "iris_currentAlphaTest", indentation);
}
public String toExpression(String alphaAccessor, String alphaThreshold, String indentation) {
String expr = function.getExpression();
if (function == AlphaTestFunction.ALWAYS) {
return "// alpha test disabled\n";
} else if (function == AlphaTestFunction.NEVER) {
return "discard;\n";
}
return indentation + "if (!(" + alphaAccessor + " " + expr + " " + alphaThreshold + ")) {\n" +
indentation + " discard;\n" +
indentation + "}\n";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((function == null) ? 0 : function.hashCode());
result = prime * result + Float.floatToIntBits(reference);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AlphaTest other = (AlphaTest) obj;
if (function != other.function)
return false;
return Float.floatToIntBits(reference) == Float.floatToIntBits(other.reference);
}
}
@@ -5,33 +5,35 @@ import org.lwjgl.opengl.GL11;
import java.util.Optional;
public enum AlphaTestFunction {
NEVER(GL11.GL_NEVER),
LESS(GL11.GL_LESS),
EQUAL(GL11.GL_EQUAL),
LEQUAL(GL11.GL_LEQUAL),
GREATER(GL11.GL_GREATER),
NOTEQUAL(GL11.GL_NOTEQUAL),
GEQUAL(GL11.GL_GEQUAL),
ALWAYS(GL11.GL_ALWAYS);
NEVER(GL11.GL_NEVER, null),
LESS(GL11.GL_LESS, "<"),
EQUAL(GL11.GL_EQUAL, "=="),
LEQUAL(GL11.GL_LEQUAL, "<="),
GREATER(GL11.GL_GREATER, ">"),
NOTEQUAL(GL11.GL_NOTEQUAL, "!="),
GEQUAL(GL11.GL_GEQUAL, ">="),
ALWAYS(GL11.GL_ALWAYS, null);
private final int glId;
private final String expression;
AlphaTestFunction(int glFormat) {
AlphaTestFunction(int glFormat, String expression) {
this.glId = glFormat;
this.expression = expression;
}
public static Optional<AlphaTestFunction> fromGlId(int glId) {
return switch (glId) {
case GL11.GL_NEVER -> Optional.of(NEVER);
case GL11.GL_LESS -> Optional.of(LESS);
case GL11.GL_EQUAL -> Optional.of(EQUAL);
case GL11.GL_LEQUAL -> Optional.of(LEQUAL);
case GL11.GL_GREATER -> Optional.of(GREATER);
case GL11.GL_NOTEQUAL -> Optional.of(NOTEQUAL);
case GL11.GL_GEQUAL -> Optional.of(GEQUAL);
case GL11.GL_ALWAYS -> Optional.of(ALWAYS);
default -> Optional.empty();
};
return switch (glId) {
case GL11.GL_NEVER -> Optional.of(NEVER);
case GL11.GL_LESS -> Optional.of(LESS);
case GL11.GL_EQUAL -> Optional.of(EQUAL);
case GL11.GL_LEQUAL -> Optional.of(LEQUAL);
case GL11.GL_GREATER -> Optional.of(GREATER);
case GL11.GL_NOTEQUAL -> Optional.of(NOTEQUAL);
case GL11.GL_GEQUAL -> Optional.of(GEQUAL);
case GL11.GL_ALWAYS -> Optional.of(ALWAYS);
default -> Optional.empty();
};
}
public static Optional<AlphaTestFunction> fromString(String name) {
@@ -54,4 +56,8 @@ public enum AlphaTestFunction {
public int getGlId() {
return glId;
}
public String getExpression() {
return expression;
}
}
@@ -19,6 +19,6 @@ public class ImageBinding {
public void update() {
// We can assume that image bindings are supported here as either the EXT extension or 4.2 core, as otherwise ImageLimits
// would report that zero image units are supported.
RenderSystem.bindImageTexture(imageUnit, textureID.getAsInt(), 0, false, 0, GL15.GL_READ_WRITE, internalFormat);
RenderSystem.bindImageTexture(imageUnit, textureID.getAsInt(), 0, true, 0, GL15.GL_READ_WRITE, internalFormat);
}
}
@@ -34,36 +34,31 @@ public class ProgramBuilder extends ProgramUniforms.Builder implements SamplerHo
public static ProgramBuilder begin(String name, @Nullable String vertexSource, @Nullable String geometrySource,
@Nullable String fragmentSource, ImmutableSet<Integer> reservedTextureUnits) {
GlShader vertex;
GlShader geometry;
GlShader fragment;
return begin(name, vertexSource, geometrySource, null, null, fragmentSource, reservedTextureUnits);
}
vertex = buildShader(ShaderType.VERTEX, name + ".vsh", vertexSource);
public static ProgramBuilder begin(String name, @Nullable String vertexSource, @Nullable String geometrySource,
@Nullable String tessControlSource, @Nullable String tessEvalSource,
@Nullable String fragmentSource, ImmutableSet<Integer> reservedTextureUnits) {
GlShader vertex = buildShader(ShaderType.VERTEX, name + ".vsh", vertexSource);
GlShader geometry = geometrySource != null ? buildShader(ShaderType.GEOMETRY, name + ".gsh", geometrySource) : null;
GlShader tessControl = tessControlSource != null ? buildShader(ShaderType.TESSELATION_CONTROL, name + ".tcs", tessControlSource) : null;
GlShader tessEval = tessEvalSource != null ? buildShader(ShaderType.TESSELATION_EVAL, name + ".tes", tessEvalSource) : null;
GlShader fragment = buildShader(ShaderType.FRAGMENT, name + ".fsh", fragmentSource);
if (geometrySource != null) {
geometry = buildShader(ShaderType.GEOMETRY, name + ".gsh", geometrySource);
} else {
geometry = null;
java.util.List<GlShader> shaders = new java.util.ArrayList<>();
shaders.add(vertex);
if (geometry != null) shaders.add(geometry);
if (tessControl != null) shaders.add(tessControl);
if (tessEval != null) shaders.add(tessEval);
shaders.add(fragment);
int programId = ProgramCreator.create(name, shaders.toArray(new GlShader[0]));
for (GlShader shader : shaders) {
shader.destroy();
}
fragment = buildShader(ShaderType.FRAGMENT, name + ".fsh", fragmentSource);
int programId;
if (geometry != null) {
programId = ProgramCreator.create(name, vertex, geometry, fragment);
} else {
programId = ProgramCreator.create(name, vertex, fragment);
}
vertex.destroy();
if (geometry != null) {
geometry.destroy();
}
fragment.destroy();
return new ProgramBuilder(name, programId, reservedTextureUnits);
}
@@ -17,7 +17,7 @@ import java.util.Locale;
* A compiled OpenGL shader object.
*/
public class GlShader extends GlResource {
private static final Logger LOGGER = LogManager.getLogger(GlShader.class);
private static final Logger LOGGER = LogManager.getLogger("GlShader");
private final String name;
@@ -12,7 +12,7 @@ import org.lwjgl.opengl.KHRDebug;
public class ProgramCreator {
private static final Logger LOGGER = LogManager.getLogger(ProgramCreator.class);
private static final Logger LOGGER = LogManager.getLogger("ProgramCreator");
public static final int MC_ENTITY = 11;
public static final int MC_MID_TEX_COORD = 12;
@@ -4,6 +4,7 @@ package net.coderbot.iris.gl.shader;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL32;
import org.lwjgl.opengl.GL40;
import org.lwjgl.opengl.GL43;
/**
@@ -12,6 +13,8 @@ import org.lwjgl.opengl.GL43;
public enum ShaderType {
VERTEX(GL20.GL_VERTEX_SHADER),
GEOMETRY(GL32.GL_GEOMETRY_SHADER),
TESSELATION_CONTROL(GL40.GL_TESS_CONTROL_SHADER),
TESSELATION_EVAL(GL40.GL_TESS_EVALUATION_SHADER),
FRAGMENT(GL20.GL_FRAGMENT_SHADER),
COMPUTE(GL43.GL_COMPUTE_SHADER);
@@ -2,6 +2,7 @@ package net.coderbot.iris.gl.shader;
import com.google.common.collect.ImmutableList;
import com.gtnewhorizons.angelica.Tags;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import cpw.mods.fml.common.Loader;
import net.coderbot.iris.parsing.BiomeCategories;
import net.coderbot.iris.pipeline.HandRenderer;
@@ -75,6 +76,9 @@ public class StandardMacros {
define(standardDefines, "MC_RENDER_QUALITY", "1.0");
define(standardDefines, "MC_SHADOW_QUALITY", "1.0");
define(standardDefines, "IS_ANGELICA");
if (AngelicaConfig.defineIsIris) {
define(standardDefines, "IS_IRIS");
}
define(standardDefines, "ANGELICA_VERSION", makeAngelicaVersion());
define(standardDefines, "MC_HAND_DEPTH", Float.toString(HandRenderer.DEPTH));
@@ -0,0 +1,18 @@
package net.coderbot.iris.gl.state;
public enum FogMode {
/**
* Fog is disabled.
*/
OFF,
/**
* Per-vertex fog, applicable to most geometry.
*/
PER_VERTEX,
/**
* Per-fragment fog, for extra-long geometry like beacon beams.
*/
PER_FRAGMENT
}
@@ -1,5 +1,6 @@
package net.coderbot.iris.gl.texture;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import net.coderbot.iris.gl.GlVersion;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL30;
@@ -105,4 +106,29 @@ public enum InternalTextureFormat {
public GlVersion getMinimumGlVersion() {
return minimumGlVersion;
}
public InternalTextureFormat getColorRenderableFallback() {
if (!RenderSystem.supportsSnormFormats()) {
return switch (this) {
case R8_SNORM, RG8_SNORM, RGB8_SNORM, RGBA8_SNORM -> RGBA16F;
case R16_SNORM, RG16_SNORM, RGB16_SNORM, RGBA16_SNORM -> RGBA16F;
default -> this.getPackedFloatFallback();
};
}
return this.getPackedFloatFallback();
}
private InternalTextureFormat getPackedFloatFallback() {
if (!RenderSystem.supportsPackedFloatRenderable()) {
return switch (this) {
case R11F_G11F_B10F, RGB9_E5 -> RGBA16F;
case RGB8 -> RGBA8;
case RGB16 -> RGBA16;
case RGB16F -> RGBA16F;
case RGB32F -> RGBA32F;
default -> this;
};
}
return this;
}
}
@@ -23,7 +23,7 @@ public enum PixelType {
UNSIGNED_SHORT_4_4_4_4_REV(GL12.GL_UNSIGNED_SHORT_4_4_4_4_REV, GlVersion.GL_12),
UNSIGNED_SHORT_5_5_5_1(GL12.GL_UNSIGNED_SHORT_5_5_5_1, GlVersion.GL_12),
UNSIGNED_SHORT_1_5_5_5_REV(GL12.GL_UNSIGNED_SHORT_1_5_5_5_REV, GlVersion.GL_12),
UNSIGNED_INT(GL11.GL_UNSIGNED_BYTE, GlVersion.GL_11),
UNSIGNED_INT(GL11.GL_UNSIGNED_INT, GlVersion.GL_11),
UNSIGNED_INT_8_8_8_8(GL12.GL_UNSIGNED_INT_8_8_8_8, GlVersion.GL_12),
UNSIGNED_INT_8_8_8_8_REV(GL12.GL_UNSIGNED_INT_8_8_8_8_REV, GlVersion.GL_12),
UNSIGNED_INT_10_10_10_2(GL12.GL_UNSIGNED_INT_10_10_10_2, GlVersion.GL_12),
@@ -96,7 +96,7 @@ public class ShaderPackScreen extends GuiScreen implements HudHideable {
@Override
public void drawScreen(int mouseX, int mouseY, float delta) {
GLStateManager.glPushAttrib(GL11.GL_COLOR_BUFFER_BIT);
if(dirty) {
dirty = false;
this.initGui();
@@ -174,7 +174,7 @@ public class ShaderPackScreen extends GuiScreen implements HudHideable {
} else {
this.fontRendererObj.drawStringWithShadow(irisTextComponent, 2, this.height - 10, 0xFFFFFF);
}
GLStateManager.glPopAttrib();
}
@@ -507,7 +507,7 @@ public class ShaderPackScreen extends GuiScreen implements HudHideable {
}
public boolean isDisplayingComment() {
return this.hoveredElementCommentTimer > 20 &&
return this.hoveredElementCommentTimer > 10 &&
this.hoveredElementCommentTitle.isPresent() &&
!this.hoveredElementCommentBody.isEmpty();
}
@@ -1,5 +1,6 @@
package net.coderbot.iris.pipeline;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import net.coderbot.iris.gl.framebuffer.GlFramebuffer;
import net.minecraft.client.Minecraft;
import org.joml.Vector4f;
@@ -24,7 +25,7 @@ public class ClearPass {
}
public void execute(Vector4f defaultClearColor) {
GL11.glViewport(0, 0, viewportX.getAsInt(), viewportY.getAsInt());
GLStateManager.glViewport(0, 0, viewportX.getAsInt(), viewportY.getAsInt());
framebuffer.bind();
Vector4f color = Objects.requireNonNull(defaultClearColor);
@@ -86,7 +86,7 @@ public class ClearPassCreator {
// Sort buffers by their clear color so we can group up glClear calls.
Map<Vector4f, IntList> clearByColor = new HashMap<>();
for (int i = 0; i < renderTargetDirectives.getColorSamplingSettings().size(); i++) {
for (int i = 0; i < Math.min(renderTargetDirectives.getColorSamplingSettings().size(), renderTargets.getNumColorTextures()); i++) {
// unboxed
PackShadowDirectives.SamplingSettings settings = renderTargetDirectives.getColorSamplingSettings().get(i);
@@ -9,15 +9,13 @@ import com.gtnewhorizons.angelica.glsm.RenderSystem;
import com.gtnewhorizons.angelica.glsm.texture.TextureInfoCache;
import com.gtnewhorizons.angelica.rendering.RenderingState;
import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap;
import net.coderbot.iris.gl.buffer.ShaderStorageBufferHolder;
import net.coderbot.iris.gl.buffer.ShaderStorageInfo;
import net.coderbot.iris.gl.image.GlImage;
import net.coderbot.iris.gl.image.ImageInformation;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import net.coderbot.iris.Iris;
import net.coderbot.iris.block_rendering.BlockMaterialMapping;
import net.coderbot.iris.block_rendering.BlockRenderingSettings;
import net.coderbot.iris.celeritas.CeleritasTerrainPipeline;
import net.coderbot.iris.compat.dh.DHCompat;
import net.coderbot.iris.block_rendering.BlockRenderingSettings;
import net.coderbot.iris.features.FeatureFlags;
import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability;
import net.coderbot.iris.gbuffer_overrides.matching.ProgramTable;
import net.coderbot.iris.gbuffer_overrides.matching.RenderCondition;
@@ -26,14 +24,20 @@ import net.coderbot.iris.gbuffer_overrides.state.RenderTargetStateListener;
import net.coderbot.iris.gl.blending.AlphaTestOverride;
import net.coderbot.iris.gl.blending.BlendModeOverride;
import net.coderbot.iris.gl.blending.BufferBlendOverride;
import net.coderbot.iris.gl.buffer.ShaderStorageBufferHolder;
import net.coderbot.iris.gl.buffer.ShaderStorageInfo;
import net.coderbot.iris.gl.framebuffer.GlFramebuffer;
import net.coderbot.iris.gl.image.GlImage;
import net.coderbot.iris.gl.image.ImageInformation;
import net.coderbot.iris.gl.program.ComputeProgram;
import net.coderbot.iris.gl.program.Program;
import net.coderbot.iris.gl.program.ProgramBuilder;
import net.coderbot.iris.gl.program.ProgramImages;
import net.coderbot.iris.gl.program.ProgramSamplers;
import net.coderbot.iris.gl.state.FogMode;
import net.coderbot.iris.gl.texture.DepthBufferFormat;
import net.coderbot.iris.layer.GbufferPrograms;
import net.coderbot.iris.gl.texture.TextureType;
import net.coderbot.iris.helpers.Tri;
import net.coderbot.iris.pipeline.transform.PatchShaderType;
import net.coderbot.iris.pipeline.transform.TransformPatcher;
import net.coderbot.iris.postprocess.BufferFlipper;
@@ -48,7 +52,6 @@ import net.coderbot.iris.samplers.IrisImages;
import net.coderbot.iris.samplers.IrisSamplers;
import net.coderbot.iris.shaderpack.CloudSetting;
import net.coderbot.iris.shaderpack.ComputeSource;
import net.coderbot.iris.shaderpack.IdMap;
import net.coderbot.iris.shaderpack.OptionalBoolean;
import net.coderbot.iris.shaderpack.PackDirectives;
import net.coderbot.iris.shaderpack.PackShadowDirectives;
@@ -58,6 +61,7 @@ import net.coderbot.iris.shaderpack.ProgramSet;
import net.coderbot.iris.shaderpack.ProgramSource;
import net.coderbot.iris.shaderpack.loading.ProgramId;
import net.coderbot.iris.shaderpack.texture.TextureStage;
import net.coderbot.iris.shadows.ShadowCompositeRenderer;
import net.coderbot.iris.shadows.ShadowRenderTargets;
import net.coderbot.iris.texture.format.TextureFormat;
import net.coderbot.iris.texture.format.TextureFormatLoader;
@@ -80,6 +84,7 @@ import org.joml.Vector4f;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL30;
import org.lwjgl.opengl.GL42;
import java.util.ArrayList;
import java.util.Collections;
@@ -117,10 +122,14 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
private ImmutableList<ClearPass> shadowClearPasses;
private ImmutableList<ClearPass> shadowClearPassesFull;
private final ComputeProgram[] setup;
private final CompositeRenderer beginRenderer;
private final CompositeRenderer prepareRenderer;
@Nullable
private final ShadowRenderer shadowRenderer;
@Nullable
private final ShadowCompositeRenderer shadowCompositeRenderer;
private final CustomUniforms customUniforms;
@@ -156,6 +165,10 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
private final boolean shouldRenderVignette;
private final boolean shouldRenderSun;
private final boolean shouldRenderMoon;
private final boolean shouldRenderStars;
private final boolean shouldRenderSkyDisc;
private final boolean shouldRenderWeather;
private final boolean shouldRenderWeatherParticles;
private final boolean shouldWriteRainAndSnowToDepthBuffer;
private final boolean shouldRenderParticlesBeforeDeferred;
private final boolean shouldRenderPrepareBeforeShadow;
@@ -176,6 +189,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
private int currentNormalTexture;
private int currentSpecularTexture;
private PackDirectives packDirectives;
private final Set<FeatureFlags> activeFeatures;
public DeferredWorldRenderingPipeline(ProgramSet programs) {
Objects.requireNonNull(programs);
@@ -207,6 +221,10 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
this.shouldRenderVignette = programs.getPackDirectives().vignette();
this.shouldRenderSun = programs.getPackDirectives().shouldRenderSun();
this.shouldRenderMoon = programs.getPackDirectives().shouldRenderMoon();
this.shouldRenderStars = programs.getPackDirectives().shouldRenderStars();
this.shouldRenderSkyDisc = programs.getPackDirectives().shouldRenderSkyDisc();
this.shouldRenderWeather = programs.getPackDirectives().shouldRenderWeather();
this.shouldRenderWeatherParticles = programs.getPackDirectives().shouldRenderWeatherParticles();
this.shouldWriteRainAndSnowToDepthBuffer = programs.getPackDirectives().rainDepth();
this.shouldRenderParticlesBeforeDeferred = programs.getPackDirectives().getParticleRenderingSettings()
.map(s -> s == net.coderbot.iris.shaderpack.ParticleRenderingSettings.BEFORE || s == net.coderbot.iris.shaderpack.ParticleRenderingSettings.MIXED)
@@ -217,6 +235,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
this.updateNotifier = new FrameUpdateNotifier();
this.packDirectives = programs.getPackDirectives();
this.activeFeatures = programs.getPack().getActiveFeatures();
final Framebuffer main = Minecraft.getMinecraft().getFramebuffer();
@@ -304,8 +323,6 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
this.flippedBeforeShadow = ImmutableSet.of();
BufferFlipper flipper = new BufferFlipper();
this.centerDepthSampler = new CenterDepthSampler(() -> getRenderTargets().getDepthTexture(), programs.getPackDirectives().getCenterDepthHalfLife());
@@ -314,7 +331,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
this.shadowTargetsSupplier = () -> {
if (shadowRenderTargets == null) {
this.shadowRenderTargets = new ShadowRenderTargets(shadowMapResolution, shadowDirectives);
this.shadowRenderTargets = new ShadowRenderTargets(this, shadowMapResolution, shadowDirectives);
}
return shadowRenderTargets;
@@ -322,18 +339,26 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
PatchedShaderPrinter.resetPrintState();
final ProgramBuildContext beginBuildContext = new ProgramBuildContext(renderTargets, customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, shadowTargetsSupplier, customTextureManager.getCustomTextureIdMap(TextureStage.BEGIN), customUniforms, customImages, customTextureManager.getIrisCustomTextures(), this);
final ProgramBuildContext prepareBuildContext = new ProgramBuildContext(renderTargets, customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, shadowTargetsSupplier, customTextureManager.getCustomTextureIdMap(TextureStage.PREPARE), customUniforms, customImages, customTextureManager.getIrisCustomTextures(), this);
final ProgramBuildContext deferredBuildContext = new ProgramBuildContext(renderTargets, customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, shadowTargetsSupplier, customTextureManager.getCustomTextureIdMap(TextureStage.DEFERRED), customUniforms, customImages, customTextureManager.getIrisCustomTextures(), this);
final ProgramBuildContext compositeBuildContext = new ProgramBuildContext(renderTargets, customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, shadowTargetsSupplier, customTextureManager.getCustomTextureIdMap(TextureStage.COMPOSITE_AND_FINAL), customUniforms, customImages, customTextureManager.getIrisCustomTextures(), this);
this.prepareRenderer = new CompositeRenderer(programs.getPrepare(), programs.getPrepareCompute(), flipper, prepareBuildContext, programs.getPackDirectives().getExplicitFlips("prepare_pre"), prepareTransformFutures, "prepare");
this.setup = createSetupComputes(programs.getSetup());
this.beginRenderer = new CompositeRenderer(programs.getBegin(), programs.getBeginCompute(), flipper, beginBuildContext, programs.getPackDirectives().getExplicitFlips("begin_pre"), null, "begin", TextureStage.BEGIN);
this.flippedBeforeShadow = flipper.snapshot();
this.prepareRenderer = new CompositeRenderer(programs.getPrepare(), programs.getPrepareCompute(), flipper, prepareBuildContext, programs.getPackDirectives().getExplicitFlips("prepare_pre"), prepareTransformFutures, "prepare", TextureStage.PREPARE);
flippedAfterPrepare = flipper.snapshot();
this.deferredRenderer = new CompositeRenderer(programs.getDeferred(), programs.getDeferredCompute(), flipper, deferredBuildContext, programs.getPackDirectives().getExplicitFlips("deferred_pre"), deferredTransformFutures, "deferred");
this.deferredRenderer = new CompositeRenderer(programs.getDeferred(), programs.getDeferredCompute(), flipper, deferredBuildContext, programs.getPackDirectives().getExplicitFlips("deferred_pre"), deferredTransformFutures, "deferred", TextureStage.DEFERRED);
flippedAfterTranslucent = flipper.snapshot();
this.compositeRenderer = new CompositeRenderer(programs.getComposite(), programs.getCompositeCompute(), flipper, compositeBuildContext, programs.getPackDirectives().getExplicitFlips("composite_pre"), compositeTransformFutures, "composite");
this.compositeRenderer = new CompositeRenderer(programs.getComposite(), programs.getCompositeCompute(), flipper, compositeBuildContext, programs.getPackDirectives().getExplicitFlips("composite_pre"), compositeTransformFutures, "composite", TextureStage.COMPOSITE_AND_FINAL);
this.finalPassRenderer = new FinalPassRenderer(programs, compositeBuildContext, flipper.snapshot(), this.compositeRenderer.getFlippedAtLeastOnceFinal(), finalTransformFuture, "final");
// [(textured=false,lightmap=false), (textured=true,lightmap=false), (textured=true,lightmap=true)]
@@ -423,16 +448,24 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
});
});
if (shadowRenderTargets == null && shadowDirectives.isShadowEnabled() == OptionalBoolean.TRUE) {
shadowRenderTargets = new ShadowRenderTargets(shadowMapResolution, shadowDirectives);
shadowRenderTargets = new ShadowRenderTargets(this, shadowMapResolution, shadowDirectives);
}
if (shadowRenderTargets != null) {
this.shadowClearPasses = ClearPassCreator.createShadowClearPasses(shadowRenderTargets, false, shadowDirectives);
this.shadowClearPassesFull = ClearPassCreator.createShadowClearPasses(shadowRenderTargets, true, shadowDirectives);
this.shadowCompositeRenderer = new ShadowCompositeRenderer(this, programs.getPackDirectives(),
programs.getShadowComposite(), programs.getShadowCompCompute(), this.shadowRenderTargets,
ssboHolder,
customTextureManager.getNoiseTexture(), updateNotifier,
customTextureManager.getCustomTextureIdMap(TextureStage.SHADOWCOMP),
customImages, programs.getPackDirectives().getExplicitFlips("shadowcomp_pre"),
customTextureManager.getIrisCustomTextures(), customUniforms);
if (programs.getPackDirectives().getShadowDirectives().isShadowEnabled().orElse(true)) {
this.shadowRenderer = new ShadowRenderer(programs.getShadow().orElse(null),
programs.getPackDirectives(), shadowRenderTargets);
programs.getPackDirectives(), shadowRenderTargets, shadowCompositeRenderer);
Program shadowProgram = table.match(RenderCondition.SHADOW, new InputAvailability(true, true)).getProgram();
shadowRenderer.setUsesImages(shadowProgram != null && shadowProgram.getActiveImages() > 0);
} else {
@@ -441,6 +474,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
} else {
this.shadowClearPasses = ImmutableList.of();
this.shadowClearPassesFull = ImmutableList.of();
this.shadowCompositeRenderer = null;
this.shadowRenderer = null;
}
@@ -449,6 +483,25 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
this.clearPassesFull = ClearPassCreator.createClearPasses(renderTargets, true, programs.getPackDirectives().getRenderTargetDirectives());
this.clearPasses = ClearPassCreator.createClearPasses(renderTargets, false, programs.getPackDirectives().getRenderTargetDirectives());
boolean hasSetup = false;
for (ComputeProgram program : setup) {
if (program != null) {
if (!hasSetup) {
hasSetup = true;
renderTargets.onFullClear();
final Vector4f fogColor = new Vector4f(1.0F, 1.0F, 1.0F, 1.0F);
clearPassesFull.forEach(clearPass -> clearPass.execute(fogColor));
}
program.use();
customUniforms.push(program);
program.dispatch(1, 1);
}
}
if (hasSetup) {
ComputeProgram.unbind();
RenderSystem.memoryBarrier(GL42.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL42.GL_TEXTURE_FETCH_BARRIER_BIT);
}
// Terrain pipeline sampler/image factory setup follows.
Supplier<ImmutableSet<Integer>> flipped = () -> isBeforeTranslucent ? flippedAfterPrepare : flippedAfterTranslucent;
@@ -524,19 +577,16 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
final GlFramebuffer celeritasShadowFb = (shadowRenderTargets != null && shadowRenderer != null)
? shadowRenderTargets.createShadowFramebuffer(shadowRenderTargets.snapshot(), new int[] {0, 1})
: null;
final int[] celeritasTerrainDrawBuffers = terrainSource
.map(source -> source.getDirectives().getDrawBuffers())
.orElse(new int[] {0});
this.celeritasTerrainPipeline = new CeleritasTerrainPipeline(createTerrainSamplers,
shadowRenderer == null ? null : createShadowTerrainSamplers, createTerrainImages,
shadowRenderer == null ? null : createShadowTerrainImages, this.customUniforms,
terrainSource.map(ProgramSource::getName).orElse(null),
translucentSource.map(ProgramSource::getName).orElse(null),
shadowSource.map(ProgramSource::getName).orElse(null),
terrainSource,
translucentSource,
shadowSource,
celeritasTerrainFuture, celeritasTranslucentFuture, celeritasShadowFuture,
renderTargets, flippedAfterPrepare, flippedAfterTranslucent,
celeritasShadowFb, celeritasTerrainDrawBuffers);
celeritasShadowFb);
this.dhCompat = new DHCompat();
}
@@ -589,6 +639,26 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
return shouldRenderMoon;
}
@Override
public boolean shouldRenderStars() {
return shouldRenderStars;
}
@Override
public boolean shouldRenderSkyDisc() {
return shouldRenderSkyDisc;
}
@Override
public boolean shouldRenderWeather() {
return shouldRenderWeather;
}
@Override
public boolean shouldRenderWeatherParticles() {
return shouldRenderWeatherParticles;
}
@Override
public boolean shouldWriteRainAndSnowToDepthBuffer() {
return shouldWriteRainAndSnowToDepthBuffer;
@@ -609,6 +679,16 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
return sunPathRotation;
}
@Override
public boolean hasFeature(FeatureFlags flag) {
return activeFeatures.contains(flag);
}
@Override
public Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> getTextureMap() {
return packDirectives.getTextureMap();
}
private RenderCondition getCondition(WorldRenderingPhase phase) {
if (isRenderingShadow) {
return RenderCondition.SHADOW;
@@ -707,17 +787,21 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
transformed = TransformPatcher.patchAttributes(
source.getVertexSource().orElseThrow(NullPointerException::new),
source.getGeometrySource().orElse(null),
source.getTessControlSource().orElse(null),
source.getTessEvalSource().orElse(null),
source.getFragmentSource().orElseThrow(NullPointerException::new),
availability);
}
String vertex = transformed.get(PatchShaderType.VERTEX);
String geometry = transformed.get(PatchShaderType.GEOMETRY);
String tessControl = transformed.get(PatchShaderType.TESS_CONTROL);
String tessEval = transformed.get(PatchShaderType.TESS_EVAL);
String fragment = transformed.get(PatchShaderType.FRAGMENT);
PatchedShaderPrinter.debugPatchedShaders(source.getName(), vertex, geometry, fragment);
PatchedShaderPrinter.debugPatchedShaders(source.getName(), vertex, geometry, tessControl, tessEval, fragment);
ProgramBuilder builder = ProgramBuilder.begin(source.getName(), vertex, geometry, fragment,
ProgramBuilder builder = ProgramBuilder.begin(source.getName(), vertex, geometry, tessControl, tessEval, fragment,
IrisSamplers.WORLD_RESERVED_TEXTURE_UNITS);
return createPassInner(builder, source.getDirectives(), availability, shadow, id);
@@ -725,7 +809,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
private Pass createPassInner(ProgramBuilder builder, ProgramDirectives programDirectives, InputAvailability availability, boolean shadow, ProgramId id) {
CommonUniforms.addDynamicUniforms(builder);
CommonUniforms.addDynamicUniforms(builder, FogMode.PER_VERTEX);
this.customUniforms.assignTo(builder);
Supplier<ImmutableSet<Integer>> flipped;
@@ -757,6 +841,10 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, customTextureManager.getNoiseTexture());
IrisSamplers.addCustomImages(customTextureSamplerInterceptor, customImages);
IrisSamplers.addCustomTextures(customTextureSamplerInterceptor, customTextureManager.getIrisCustomTextures());
IrisImages.addCustomImages(builder, customImages);
if (IrisSamplers.hasShadowSamplers(customTextureSamplerInterceptor)) {
if (!shadow) {
shadowTargetsSupplier.get();
@@ -867,10 +955,10 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
}
if (shadowViewport) {
GL11.glViewport(0, 0, shadowMapResolution, shadowMapResolution);
GLStateManager.glViewport(0, 0, shadowMapResolution, shadowMapResolution);
} else {
final Framebuffer main = Minecraft.getMinecraft().getFramebuffer();
GL11.glViewport(0, 0, main.framebufferWidth, main.framebufferHeight);
GLStateManager.glViewport(0, 0, main.framebufferWidth, main.framebufferHeight);
}
if (program != null) {
@@ -930,12 +1018,22 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
// Destroy the composite rendering pipeline
//
// This destroys all the loaded composite programs as well.
beginRenderer.destroy();
prepareRenderer.destroy();
compositeRenderer.destroy();
deferredRenderer.destroy();
finalPassRenderer.destroy();
centerDepthSampler.destroy();
// Destroy setup compute programs
if (setup != null) {
for (ComputeProgram compute : setup) {
if (compute != null) {
compute.destroy();
}
}
}
// Destroy shadow compute programs
if (shadowComputes != null) {
for (ComputeProgram compute : shadowComputes) {
@@ -945,6 +1043,11 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
}
}
// Destroy shadow composite renderer
if (shadowCompositeRenderer != null) {
shadowCompositeRenderer.destroy();
}
horizonRenderer.destroy();
// Make sure that any custom framebuffers are not bound before destroying render targets
@@ -1053,6 +1156,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
main.framebufferHeight, depthBufferFormat, packDirectives);
if (changed) {
beginRenderer.recalculateSizes();
prepareRenderer.recalculateSizes();
deferredRenderer.recalculateSizes();
compositeRenderer.recalculateSizes();
@@ -1073,6 +1177,21 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
if (ssboHolder != null) {
ssboHolder.hasResizedScreen(main.framebufferWidth, main.framebufferHeight);
}
// Re-run setup computes after resize (SETUP dispatches with 1,1 workgroups)
boolean ranSetup = false;
for (ComputeProgram program : setup) {
if (program != null) {
ranSetup = true;
program.use();
customUniforms.push(program);
program.dispatch(1, 1);
}
}
if (ranSetup) {
ComputeProgram.unbind();
RenderSystem.memoryBarrier(GL42.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL42.GL_TEXTURE_FETCH_BARRIER_BIT);
}
}
final ImmutableList<ClearPass> passes;
@@ -1108,13 +1227,15 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
ProgramBuilder builder;
try {
builder = ProgramBuilder.beginCompute(source.getName(), source.getSource().orElse(null), IrisSamplers.WORLD_RESERVED_TEXTURE_UNITS);
String transformed = TransformPatcher.patchCompute(source.getName(), source.getSource().orElse(null), TextureStage.GBUFFERS_AND_SHADOW, getTextureMap());
PatchedShaderPrinter.debugPatchedShaders(source.getName() + "_compute", null, null, null, transformed);
builder = ProgramBuilder.beginCompute(source.getName(), transformed, IrisSamplers.WORLD_RESERVED_TEXTURE_UNITS);
} catch (RuntimeException e) {
// TODO: Better error handling
throw new RuntimeException("Shader compilation failed!", e);
}
CommonUniforms.addDynamicUniforms(builder);
CommonUniforms.addDynamicUniforms(builder, FogMode.PER_VERTEX);
this.customUniforms.assignTo(builder);
Supplier<ImmutableSet<Integer>> flipped;
@@ -1133,6 +1254,9 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, customTextureManager.getNoiseTexture());
IrisSamplers.addCustomImages(customTextureSamplerInterceptor, customImages);
IrisSamplers.addCustomTextures(customTextureSamplerInterceptor, customTextureManager.getIrisCustomTextures());
if (IrisSamplers.hasShadowSamplers(customTextureSamplerInterceptor)) {
if (shadowRenderTargets != null) {
IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowRenderTargets, null, true);
@@ -1140,6 +1264,8 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
}
}
IrisImages.addCustomImages(builder, customImages);
programs[i] = builder.buildCompute();
this.customUniforms.mapholderToPass(builder, programs[i]);
@@ -1152,6 +1278,60 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
return programs;
}
private ComputeProgram[] createSetupComputes(ComputeSource[] compute) {
ComputeProgram[] programs = new ComputeProgram[compute.length];
for (int i = 0; i < programs.length; i++) {
ComputeSource source = compute[i];
if (source == null || !source.getSource().isPresent()) {
continue;
} else {
ProgramBuilder builder;
try {
String transformed = TransformPatcher.patchCompute(source.getName(), source.getSource().orElse(null), TextureStage.SETUP, getTextureMap());
PatchedShaderPrinter.debugPatchedShaders(source.getName() + "_compute", null, null, null, transformed);
builder = ProgramBuilder.beginCompute(source.getName(), transformed, IrisSamplers.COMPOSITE_RESERVED_TEXTURE_UNITS);
} catch (RuntimeException e) {
throw new RuntimeException("Shader compilation failed for setup compute " + source.getName() + "!", e);
}
CommonUniforms.addDynamicUniforms(builder, FogMode.OFF);
this.customUniforms.assignTo(builder);
ImmutableSet<Integer> empty = ImmutableSet.of();
Supplier<ImmutableSet<Integer>> flipped = () -> empty;
ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor =
ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureManager.getCustomTextureIdMap(TextureStage.SETUP));
IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, flipped, renderTargets, true, this);
IrisSamplers.addCustomImages(customTextureSamplerInterceptor, customImages);
IrisSamplers.addCustomTextures(customTextureSamplerInterceptor, customTextureManager.getIrisCustomTextures());
IrisImages.addRenderTargetImages(builder, flipped, renderTargets);
IrisImages.addCustomImages(builder, customImages);
IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, customTextureManager.getNoiseTexture());
IrisSamplers.addCompositeSamplers(customTextureSamplerInterceptor, renderTargets);
if (IrisSamplers.hasShadowSamplers(customTextureSamplerInterceptor)) {
if (shadowRenderTargets != null) {
IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowRenderTargets, null, true);
IrisImages.addShadowColorImages(builder, shadowRenderTargets, null);
}
}
programs[i] = builder.buildCompute();
this.customUniforms.mapholderToPass(builder, programs[i]);
programs[i].setWorkGroupInfo(source.getWorkGroupRelative(), source.getWorkGroups(), null);
}
}
return programs;
}
@Override
public void beginHand() {
// We need to copy the current depth texture so that depthtex2 can contain the depth values for
@@ -1274,6 +1454,10 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
image.clear();
}
isRenderingFullScreenPass = true;
beginRenderer.renderAll();
isRenderingFullScreenPass = false;
setPhase(WorldRenderingPhase.SKY);
// Render our horizon box before actual sky rendering to avoid being broken by mods that do weird things
@@ -1407,7 +1591,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
private static final InputAvailability[] INPUT_AVAILABILITIES = { INPUT_NONE, INPUT_TEXTURE, INPUT_TEXTURE_LIGHTMAP };
private static CompletableFuture<Map<PatchShaderType, String>> submitCompositeTransform(ProgramSource source) {
return Iris.ShaderTransformExecutor.submitTracked(() -> TransformPatcher.patchComposite(source.getVertexSource().orElse(null), source.getGeometrySource().orElse(null), source.getFragmentSource().orElse(null)));
return Iris.ShaderTransformExecutor.submitTracked(() -> TransformPatcher.patchComposite(source.getVertexSource().orElse(null), source.getGeometrySource().orElse(null), source.getTessControlSource().orElse(null), source.getTessEvalSource().orElse(null), source.getFragmentSource().orElse(null)));
}
private static Map<Integer, CompletableFuture<Map<PatchShaderType, String>>> submitCompositeTransforms(ProgramSource[] sources) {
@@ -1435,7 +1619,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
processedSourceNames.add(source.getName());
for (InputAvailability avail : INPUT_AVAILABILITIES) {
Pair<String, InputAvailability> key = Pair.of(source.getName(), avail);
futures.put(key, Iris.ShaderTransformExecutor.submitTracked(() -> TransformPatcher.patchAttributes(source.getVertexSource().orElse(null), source.getGeometrySource().orElse(null), source.getFragmentSource().orElse(null), avail)));
futures.put(key, Iris.ShaderTransformExecutor.submitTracked(() -> TransformPatcher.patchAttributes(source.getVertexSource().orElse(null), source.getGeometrySource().orElse(null), source.getTessControlSource().orElse(null), source.getTessEvalSource().orElse(null), source.getFragmentSource().orElse(null), avail)));
}
}
}
@@ -1,13 +1,19 @@
package net.coderbot.iris.pipeline;
import com.gtnewhorizons.angelica.compat.mojang.Camera;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectMaps;
import net.coderbot.iris.block_rendering.BlockRenderingSettings;
import net.coderbot.iris.celeritas.CeleritasTerrainPipeline;
import net.coderbot.iris.compat.dh.DHCompat;
import net.coderbot.iris.features.FeatureFlags;
import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability;
import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition;
import net.coderbot.iris.gbuffer_overrides.state.RenderTargetStateListener;
import net.coderbot.iris.gl.texture.TextureType;
import net.coderbot.iris.helpers.Tri;
import net.coderbot.iris.shaderpack.CloudSetting;
import net.coderbot.iris.shaderpack.texture.TextureStage;
import net.coderbot.iris.uniforms.FrameUpdateNotifier;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.EntityRenderer;
@@ -166,6 +172,26 @@ public class FixedFunctionWorldRenderingPipeline implements WorldRenderingPipeli
return true;
}
@Override
public boolean shouldRenderStars() {
return true;
}
@Override
public boolean shouldRenderSkyDisc() {
return true;
}
@Override
public boolean shouldRenderWeather() {
return true;
}
@Override
public boolean shouldRenderWeatherParticles() {
return true;
}
@Override
public boolean shouldWriteRainAndSnowToDepthBuffer() {
return false;
@@ -186,4 +212,14 @@ public class FixedFunctionWorldRenderingPipeline implements WorldRenderingPipeli
// No sun tilt
return 0;
}
@Override
public boolean hasFeature(FeatureFlags flag) {
return false;
}
@Override
public Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> getTextureMap() {
return Object2ObjectMaps.emptyMap();
}
}
@@ -27,6 +27,18 @@ public class PatchedShaderPrinter {
}
public static void debugPatchedShaders(String name, String vertex, String geometry, String fragment) {
debugPatchedShaders(name, vertex, geometry, null, null, fragment, null);
}
public static void debugPatchedShaders(String name, String vertex, String geometry, String tessControl, String tessEval, String fragment) {
debugPatchedShaders(name, vertex, geometry, tessControl, tessEval, fragment, null);
}
public static void debugPatchedShaders(String name, String vertex, String geometry, String fragment, String compute) {
debugPatchedShaders(name, vertex, geometry, null, null, fragment, compute);
}
public static void debugPatchedShaders(String name, String vertex, String geometry, String tessControl, String tessEval, String fragment, String compute) {
if (prettyPrintShaders) {
final Path debugOutDir = Minecraft.getMinecraft().mcDataDir.toPath().resolve("patched_shaders");
if (!outputLocationCleared) {
@@ -59,9 +71,18 @@ public class PatchedShaderPrinter {
if (geometry != null) {
Files.write(debugOutDir.resolve(prefix + name + ".gsh"), geometry.getBytes(StandardCharsets.UTF_8));
}
if (tessControl != null) {
Files.write(debugOutDir.resolve(prefix + name + ".tcs"), tessControl.getBytes(StandardCharsets.UTF_8));
}
if (tessEval != null) {
Files.write(debugOutDir.resolve(prefix + name + ".tes"), tessEval.getBytes(StandardCharsets.UTF_8));
}
if (fragment != null) {
Files.write(debugOutDir.resolve(prefix + name + ".fsh"), fragment.getBytes(StandardCharsets.UTF_8));
}
if (compute != null) {
Files.write(debugOutDir.resolve(prefix + name + ".csh"), compute.getBytes(StandardCharsets.UTF_8));
}
} catch (IOException e) {
Iris.logger.warn("Failed to write debug patched shader source", e);
}
@@ -23,11 +23,13 @@ import net.coderbot.iris.shaderpack.PackShadowDirectives;
import net.coderbot.iris.shaderpack.ProgramSource;
import net.coderbot.iris.shadow.ShadowMatrices;
import net.coderbot.iris.shadows.CullingDataCache;
import net.coderbot.iris.shadows.ShadowCompositeRenderer;
import net.coderbot.iris.shadows.ShadowRenderTargets;
import net.coderbot.iris.shadows.frustum.BoxCuller;
import net.coderbot.iris.shadows.frustum.CullEverythingFrustum;
import net.coderbot.iris.shadows.frustum.FrustumHolder;
import net.coderbot.iris.shadows.frustum.advanced.AdvancedShadowCullingFrustum;
import net.coderbot.iris.shadows.frustum.advanced.SafeZoneCullingFrustum;
import net.coderbot.iris.shadows.frustum.fallback.BoxCullingFrustum;
import net.coderbot.iris.shadows.frustum.fallback.NonCullingFrustum;
import net.coderbot.iris.uniforms.CameraUniforms;
@@ -48,7 +50,7 @@ import net.minecraft.tileentity.TileEntity;
import com.gtnewhorizons.angelica.compat.mojang.GameModeUtil;
import org.embeddedt.embeddium.impl.render.viewport.ViewportProvider;
import org.joml.Matrix4f;
import org.joml.Vector3dc;
import org.joml.Vector3d;
import org.joml.Vector3f;
import org.joml.Vector4f;
import org.lwjgl.BufferUtils;
@@ -72,6 +74,7 @@ public class ShadowRenderer {
public static ShadowRenderTargets CURRENT_TARGETS = null;
private final float halfPlaneLength;
private final float voxelDistance;
private final float renderDistanceMultiplier;
private final float entityShadowDistanceMultiplier;
private final int resolution;
@@ -79,6 +82,7 @@ public class ShadowRenderer {
private final Float fov;
private final ShadowRenderTargets targets;
private final ShadowCullState packCullingState;
private final ShadowCompositeRenderer compositeRenderer;
private boolean packHasVoxelization;
private final boolean shouldRenderTerrain;
private final boolean shouldRenderTranslucent;
@@ -108,13 +112,14 @@ public class ShadowRenderer {
private double lastAdvancedBoxCullerDistance = -1;
private double lastTileEntityCullerDistance = -1;
public ShadowRenderer(ProgramSource shadow, PackDirectives directives, ShadowRenderTargets shadowRenderTargets) {
public ShadowRenderer(ProgramSource shadow, PackDirectives directives, ShadowRenderTargets shadowRenderTargets, ShadowCompositeRenderer compositeRenderer) {
this.profiler = Minecraft.getMinecraft().mcProfiler;
final PackShadowDirectives shadowDirectives = directives.getShadowDirectives();
this.halfPlaneLength = shadowDirectives.getDistance();
this.voxelDistance = shadowDirectives.getVoxelDistance();
this.renderDistanceMultiplier = shadowDirectives.getDistanceRenderMul();
this.entityShadowDistanceMultiplier = shadowDirectives.getEntityShadowDistanceMul();
this.resolution = shadowDirectives.getResolution();
@@ -125,6 +130,8 @@ public class ShadowRenderer {
this.shouldRenderPlayer = shadowDirectives.shouldRenderPlayer();
this.shouldRenderBlockEntities = shadowDirectives.shouldRenderBlockEntities();
this.compositeRenderer = compositeRenderer;
debugStringOverall = "half plane = " + halfPlaneLength + " meters @ " + resolution + "x" + resolution;
this.terrainFrustumHolder = new FrustumHolder();
@@ -162,24 +169,21 @@ public class ShadowRenderer {
}
public static MatrixStack createShadowModelView(float sunPathRotation, float intervalSize) {
// Determine the camera position
final Vector3dc cameraPos = CameraUniforms.getUnshiftedCameraPosition();
final double cameraX = cameraPos.x();
final double cameraY = cameraPos.y();
final double cameraZ = cameraPos.z();
// Use entity position for shadow matrix
final Vector3d entityPos = Camera.INSTANCE.getEntityPos();
// Set up our modelview matrix stack
final MatrixStack modelView = new MatrixStack();
ShadowMatrices.createModelViewMatrix(modelView, getShadowAngle(), intervalSize, sunPathRotation, cameraX, cameraY, cameraZ);
ShadowMatrices.createModelViewMatrix(modelView, getShadowAngle(), intervalSize, sunPathRotation, entityPos.x, entityPos.y, entityPos.z);
return modelView;
}
private MatrixStack getShadowModelView() {
final Vector3dc cameraPos = CameraUniforms.getUnshiftedCameraPosition();
final Vector3d entityPos = Camera.INSTANCE.getEntityPos();
shadowModelView.reset();
ShadowMatrices.createModelViewMatrix(shadowModelView, getShadowAngle(), this.intervalSize, this.sunPathRotation, cameraPos.x(), cameraPos.y(), cameraPos.z());
ShadowMatrices.createModelViewMatrix(shadowModelView, getShadowAngle(), this.intervalSize, this.sunPathRotation, entityPos.x, entityPos.y, entityPos.z);
return shadowModelView;
}
@@ -224,7 +228,8 @@ public class ShadowRenderer {
configureDepthSampler(targets.getDepthTextureNoTranslucents().getTextureId(), depthSamplingSettings.get(1));
for (int i = 0; i < colorSamplingSettings.size(); i++) {
for (int i = 0; i < Math.min(colorSamplingSettings.size(), targets.getNumColorTextures()); i++) {
if (targets.get(i) == null) continue;
int glTextureId = targets.get(i).getMainTexture();
configureSampler(glTextureId, colorSamplingSettings.get(i));
@@ -285,7 +290,7 @@ public class ShadowRenderer {
// TODO: Cull entities / block entities with Advanced Frustum Culling even if voxelization is detected.
String distanceInfo;
String cullingInfo;
if ((packCullingState == ShadowCullState.DISTANCE || packHasVoxelization) && packCullingState != ShadowCullState.ADVANCED) {
if ((packCullingState == ShadowCullState.DISTANCE || packHasVoxelization) && packCullingState != ShadowCullState.ADVANCED && packCullingState != ShadowCullState.SAFE_ZONE) {
double distance = halfPlaneLength * renderMultiplier;
String reason;
@@ -307,26 +312,29 @@ public class ShadowRenderer {
holder.setInfo(getOrCreateBoxCullingFrustum(distance), distanceInfo, cullingInfo);
}
} else {
final BoxCuller boxCuller;
BoxCuller boxCuller;
double distance = halfPlaneLength * renderMultiplier;
boolean hasSafeZone = packCullingState == ShadowCullState.SAFE_ZONE;
if (hasSafeZone && renderMultiplier < 0) renderMultiplier = 1.0f;
double distance = (hasSafeZone ? voxelDistance : halfPlaneLength) * renderMultiplier;
String setter = "(set by shader pack)";
if (renderMultiplier < 0) {
// TODO: GUI
distance = IrisVideoSettings.shadowDistance * 16; // can be zero :(
//distance = 32 * 16;
setter = "(set by user)";
}
if (distance >= Minecraft.getMinecraft().gameSettings.renderDistanceChunks * 16) {
if (distance >= Minecraft.getMinecraft().gameSettings.renderDistanceChunks * 16 && !hasSafeZone) {
distanceInfo = Minecraft.getMinecraft().gameSettings.renderDistanceChunks * 16
+ " blocks (capped by normal render distance)";
boxCuller = null;
} else {
distanceInfo = distance + " blocks " + setter;
if (distance == 0.0) {
if (distance == 0.0 && !hasSafeZone) {
cullingInfo = "no shadows rendered";
return holder.setInfo(CULL_EVERYTHING_FRUSTUM, distanceInfo, cullingInfo);
}
@@ -334,15 +342,22 @@ public class ShadowRenderer {
boxCuller = getOrCreateAdvancedBoxCuller(distance);
}
cullingInfo = "Advanced Frustum Culling enabled";
cullingInfo = (hasSafeZone ? "Safe Zone" : "Advanced") + " Frustum Culling enabled";
final Vector4f shadowLightPosition = celestialUniforms.getShadowLightPositionInWorldSpace();
shadowLightVectorCache.set(shadowLightPosition.x(), shadowLightPosition.y(), shadowLightPosition.z());
shadowLightVectorCache.normalize();
cachedAdvancedFrustum.init(RenderingState.INSTANCE.getModelViewMatrix(), RenderingState.INSTANCE.getProjectionMatrix(), shadowLightVectorCache, boxCuller);
return holder.setInfo(cachedAdvancedFrustum, distanceInfo, cullingInfo);
if (hasSafeZone) {
BoxCuller distanceCuller = new BoxCuller(halfPlaneLength * renderMultiplier);
SafeZoneCullingFrustum safeZoneFrustum = new SafeZoneCullingFrustum(
RenderingState.INSTANCE.getModelViewMatrix(), RenderingState.INSTANCE.getProjectionMatrix(),
shadowLightVectorCache, boxCuller, distanceCuller);
return holder.setInfo(safeZoneFrustum, distanceInfo, cullingInfo);
} else {
cachedAdvancedFrustum.init(RenderingState.INSTANCE.getModelViewMatrix(), RenderingState.INSTANCE.getProjectionMatrix(), shadowLightVectorCache, boxCuller);
return holder.setInfo(cachedAdvancedFrustum, distanceInfo, cullingInfo);
}
}
return holder;
@@ -385,7 +400,7 @@ public class ShadowRenderer {
private void setupGlState(Matrix4f projMatrix) {
// Bind shadow framebuffer and set viewport to shadow resolution
targets.getDepthSourceFb().bind();
GL11.glViewport(0, 0, resolution, resolution);
GLStateManager.glViewport(0, 0, resolution, resolution);
// Set up our projection matrix and load it into the legacy matrix stack
RenderSystem.setupProjectionMatrix(projMatrix);
@@ -410,7 +425,7 @@ public class ShadowRenderer {
// Restore main framebuffer and viewport
Minecraft mc = Minecraft.getMinecraft();
mc.getFramebuffer().bindFramebuffer(false);
GL11.glViewport(0, 0, mc.displayWidth, mc.displayHeight);
GLStateManager.glViewport(0, 0, mc.displayWidth, mc.displayHeight);
}
private void copyPreTranslucentDepth() {
@@ -635,15 +650,14 @@ public class ShadowRenderer {
terrainFrustumHolder = createShadowFrustum(renderDistanceMultiplier, terrainFrustumHolder);
// Determine the player camera position
final Vector3dc cameraPos = CameraUniforms.getUnshiftedCameraPosition();
// Use the player/entity position for shadow rendering
final Vector3d entityPos = playerCamera.getEntityPos();
final double entityX = entityPos.x;
final double entityY = entityPos.y;
final double entityZ = entityPos.z;
final double cameraX = cameraPos.x();
final double cameraY = cameraPos.y();
final double cameraZ = cameraPos.z();
// Center the frustum on the player camera position
terrainFrustumHolder.getFrustum().setPosition(cameraX, cameraY, cameraZ);
// Center the frustum on the player position
terrainFrustumHolder.getFrustum().setPosition(entityX, entityY, entityZ);
profiler.endSection();
@@ -679,7 +693,7 @@ public class ShadowRenderer {
}
// Reset viewport in case terrain rendering changed it
GL11.glViewport(0, 0, resolution, resolution);
GLStateManager.glViewport(0, 0, resolution, resolution);
profiler.endStartSection("entities");
@@ -699,7 +713,7 @@ public class ShadowRenderer {
}
Frustrum entityShadowFrustum = entityFrustumHolder.getFrustum();
entityShadowFrustum.setPosition(cameraX, cameraY, cameraZ);
entityShadowFrustum.setPosition(entityX, entityY, entityZ);
// Set viewport for entity visibility checks during shadow pass (matches modern Celeritas)
if (AngelicaConfig.enableCeleritas) {
@@ -709,13 +723,13 @@ public class ShadowRenderer {
// Render nearby entities
if (shouldRenderEntities) {
renderEntities(levelRenderer, entityShadowFrustum, null, modelView, cameraX, cameraY, cameraZ, tickDelta);
renderEntities(levelRenderer, entityShadowFrustum, null, modelView, entityX, entityY, entityZ, tickDelta);
} else if (shouldRenderPlayer) {
renderPlayerEntity(levelRenderer, entityShadowFrustum, null, modelView, cameraX, cameraY, cameraZ, tickDelta);
renderPlayerEntity(levelRenderer, entityShadowFrustum, null, modelView, entityX, entityY, entityZ, tickDelta);
}
if (shouldRenderBlockEntities) {
renderTileEntities(null, modelView, cameraX, cameraY, cameraZ, tickDelta, hasEntityFrustum);
renderTileEntities(null, modelView, entityX, entityY, entityZ, tickDelta, hasEntityFrustum);
}
profiler.endStartSection("draw entities");
@@ -754,6 +768,10 @@ public class ShadowRenderer {
((CullingDataCache) levelRenderer).restoreState();
}
profiler.endStartSection("shadowcomp");
if (compositeRenderer != null) compositeRenderer.renderAll();
ACTIVE = false;
CURRENT_TARGETS = null;
profiler.endSection();
@@ -1,12 +1,17 @@
package net.coderbot.iris.pipeline;
import com.gtnewhorizons.angelica.compat.mojang.Camera;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import net.coderbot.iris.compat.dh.DHCompat;
import net.coderbot.iris.features.FeatureFlags;
import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability;
import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition;
import net.coderbot.iris.gbuffer_overrides.state.RenderTargetStateListener;
import net.coderbot.iris.celeritas.CeleritasTerrainPipeline;
import net.coderbot.iris.gl.texture.TextureType;
import net.coderbot.iris.helpers.Tri;
import net.coderbot.iris.shaderpack.CloudSetting;
import net.coderbot.iris.shaderpack.texture.TextureStage;
import net.coderbot.iris.uniforms.FrameUpdateNotifier;
import net.minecraft.client.renderer.EntityRenderer;
@@ -49,9 +54,16 @@ public interface WorldRenderingPipeline {
boolean shouldRenderVignette();
boolean shouldRenderSun();
boolean shouldRenderMoon();
boolean shouldRenderStars();
boolean shouldRenderSkyDisc();
boolean shouldRenderWeather();
boolean shouldRenderWeatherParticles();
boolean shouldWriteRainAndSnowToDepthBuffer();
boolean shouldRenderParticlesBeforeDeferred();
boolean allowConcurrentCompute();
float getSunPathRotation();
boolean hasFeature(FeatureFlags flag);
Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> getTextureMap();
}
@@ -14,8 +14,16 @@ import java.util.Map;
class AttributeTransformer {
public static void transform(Transformer transformer, AttributeParameters parameters, String profile, int version) {
boolean isCore = profile.equals("core") || (version > 140 && !profile.equals("compatibility"));
// Common patches (compatibility profile)
CommonTransformer.transform(transformer, parameters, isCore, version);
// Entity ID and overlay color patching (uniform path)
EntityPatcher.patchEntityId(transformer, parameters);
EntityPatcher.patchOverlayColor(transformer, parameters);
if (isCore) {
if (parameters.type == PatchShaderType.VERTEX) {
if (parameters.type == ShaderType.VERTEX) {
throw new IllegalStateException("Vertex shaders must be in the compatibility profile to run properly!");
}
return;
@@ -28,66 +36,49 @@ class AttributeTransformer {
transformer.rename("gl_MultiTexCoord2", "gl_MultiTexCoord1");
}
Map<String, String> texCoordReplacements = new HashMap<>();
if (!parameters.inputs.lightmap) {
texCoordReplacements.put("gl_MultiTexCoord1", "vec4(240.0, 240.0, 0.0, 1.0)");
texCoordReplacements.put("gl_MultiTexCoord2", "vec4(240.0, 240.0, 0.0, 1.0)");
}
if (!parameters.inputs.texture) {
texCoordReplacements.put("gl_MultiTexCoord0", "vec4(240.0, 240.0, 0.0, 1.0)");
}
texCoordReplacements.forEach(transformer::replaceExpression);
Map<String, String> texCoordReplacements = new HashMap<>();
if (!parameters.inputs.lightmap) {
texCoordReplacements.put("gl_MultiTexCoord1", "vec4(240.0, 240.0, 0.0, 1.0)");
texCoordReplacements.put("gl_MultiTexCoord2", "vec4(240.0, 240.0, 0.0, 1.0)");
}
if (!parameters.inputs.texture) {
texCoordReplacements.put("gl_MultiTexCoord0", "vec4(240.0, 240.0, 0.0, 1.0)");
}
texCoordReplacements.forEach(transformer::replaceExpression);
patchTextureMatrices(transformer, parameters.inputs.lightmap);
if (parameters.type.glShaderType == ShaderType.VERTEX
&& transformer.hasVariable("gl_MultiTexCoord3")
&& !transformer.hasVariable("mc_midTexCoord")) {
// TODO: proper type conversion
// gl_MultiTexCoord3 is a super legacy alias of mc_midTexCoord. We don't do this
// replacement if we think mc_midTexCoord could be defined just we can't handle
// an existing declaration robustly. But basically the proper way to do this is
// to define mc_midTexCoord only if it's not defined, and if it is defined,
// figure out its type, then replace all occurrences of gl_MultiTexCoord3 with
// the correct conversion from mc_midTexCoord's declared type to vec4.
transformer.rename("gl_MultiTexCoord3", "mc_midTexCoord");
if (parameters.type == ShaderType.VERTEX && transformer.hasVariable("gl_MultiTexCoord3") && !transformer.hasVariable("mc_midTexCoord")) {
transformer.rename("gl_MultiTexCoord3", "mc_midTexCoord");
transformer.injectVariable("attribute vec4 mc_midTexCoord;");
}
}
private static void patchTextureMatrices(Transformer transformer, boolean hasLightmap) {
transformer.rename("gl_TextureMatrix", "iris_TextureMatrix");
transformer.rename("gl_TextureMatrix", "iris_TextureMatrix");
// TODO: These were originally marked const, but that breaks things
// If these are marked const, then using them below in the iris_LightmapTextureMatrix creation
// breaks with them being undefined. I suppose the const variables cause them to get defined later than otherwise?
// Similarly, if you make them a const, then iris_ONE_OVER_32 breaks because it references iris_ONE_OVER_256.
// Not sure if it really matters if these are marked const or not. Alternatively they can be marked const
// and the values hardcoded within the places that use them here, that seems to work fine, but this probably
// stayed closer to the original way it worked.
transformer.injectVariable("float iris_ONE_OVER_256 = 0.00390625;");
transformer.injectVariable("float iris_ONE_OVER_32 = iris_ONE_OVER_256 * 8;");
transformer.injectVariable("float iris_ONE_OVER_256 = 0.00390625;");
transformer.injectVariable("float iris_ONE_OVER_32 = iris_ONE_OVER_256 * 8;");
if (hasLightmap) {
transformer.injectVariable("mat4 iris_LightmapTextureMatrix = gl_TextureMatrix[1];");
} else {
transformer.injectVariable("mat4 iris_LightmapTextureMatrix =" +
"mat4(iris_ONE_OVER_256, 0.0, 0.0, 0.0," +
" 0.0, iris_ONE_OVER_256, 0.0, 0.0," +
" 0.0, 0.0, iris_ONE_OVER_256, 0.0," +
" iris_ONE_OVER_32, iris_ONE_OVER_32, iris_ONE_OVER_32, iris_ONE_OVER_256);");
}
if (hasLightmap) {
transformer.injectVariable("mat4 iris_LightmapTextureMatrix = gl_TextureMatrix[1];");
} else {
transformer.injectVariable("mat4 iris_LightmapTextureMatrix =" +
"mat4(iris_ONE_OVER_256, 0.0, 0.0, 0.0," +
" 0.0, iris_ONE_OVER_256, 0.0, 0.0," +
" 0.0, 0.0, iris_ONE_OVER_256, 0.0," +
" iris_ONE_OVER_32, iris_ONE_OVER_32, iris_ONE_OVER_32, iris_ONE_OVER_256);");
}
// column major
transformer.injectVariable("mat4 iris_TextureMatrix[8] = mat4[8](" +
"gl_TextureMatrix[0]," +
"iris_LightmapTextureMatrix," +
"mat4(1.0)," +
"mat4(1.0)," +
"mat4(1.0)," +
"mat4(1.0)," +
"mat4(1.0)," +
"mat4(1.0)" +
");");
transformer.injectVariable("mat4 iris_TextureMatrix[8] = mat4[8](" +
"gl_TextureMatrix[0]," +
"iris_LightmapTextureMatrix," +
"mat4(1.0)," +
"mat4(1.0)," +
"mat4(1.0)," +
"mat4(1.0)," +
"mat4(1.0)," +
"mat4(1.0)" +
");");
}
}
@@ -1,18 +1,17 @@
package net.coderbot.iris.pipeline.transform;
import net.coderbot.iris.gl.shader.ShaderType;
import net.coderbot.iris.pipeline.transform.parameter.Parameters;
import org.taumc.glsl.Transformer;
import java.util.HashMap;
import java.util.Map;
import static net.coderbot.iris.pipeline.transform.PatchShaderType.FRAGMENT;
import static net.coderbot.iris.pipeline.transform.PatchShaderType.VERTEX;
class CeleritasTransformer {
public static void transform(Transformer transformer, Parameters parameters) {
public static void transform(Transformer transformer, Parameters parameters, int glslVersion) {
CommonTransformer.transform(transformer, parameters, false, glslVersion);
switch (parameters.type) {
// For Celeritas patching, treat fragment and geometry the same
case FRAGMENT:
case GEOMETRY:
transformFragment(transformer, parameters);
@@ -26,7 +25,7 @@ class CeleritasTransformer {
}
public static void transformVertex(Transformer transformer, Parameters parameters) {
transformer.injectVariable("uniform vec3 u_RegionOffset;"); // Per-region offset from setRegionOffset()
transformer.injectVariable("uniform vec3 u_RegionOffset;");
transformer.injectVariable("vec4 iris_LightTexCoord;");
transformer.injectFunction("vec4 iris_ftransform() { return gl_ModelViewProjectionMatrix * _celeritas_getVertexPosition(); }");
transformer.injectFunction(
@@ -57,7 +56,6 @@ class CeleritasTransformer {
}
public static void transformFragment(Transformer transformer, Parameters parameters) {
// interestingly there is nothing that isn't shared
transformShared(transformer, parameters);
}
@@ -82,31 +80,5 @@ class CeleritasTransformer {
sharedReplacements.put("gl_TextureMatrix[1]", "iris_LightmapTextureMatrix");
sharedReplacements.put("gl_ModelViewProjectionMatrix", "(iris_ProjectionMatrix * iris_ModelViewMatrix)");
sharedReplacements.forEach(transformer::replaceExpression);
transformFog(transformer, parameters);
}
private static void transformFog(Transformer transformer, Parameters parameters) {
transformer.injectVariable("uniform float iris_FogDensity;");
transformer.injectVariable("uniform float iris_FogStart;");
transformer.injectVariable("uniform float iris_FogEnd;");
transformer.injectVariable("uniform vec4 iris_FogColor;");
transformer.injectFunction("struct iris_FogParameters { vec4 color; float density; float start; float end; float scale; };");
transformer.injectFunction(
"iris_FogParameters iris_Fog = iris_FogParameters(iris_FogColor, iris_FogDensity, " +
"iris_FogStart, iris_FogEnd, 1.0 / (iris_FogEnd - iris_FogStart));");
final Map<String, String> fogRenames = new HashMap<>();
fogRenames.put("gl_Fog", "iris_Fog");
fogRenames.put("gl_FogFragCoord", "iris_FogFragCoord");
transformer.rename(fogRenames);
if (parameters.type == VERTEX) {
transformer.injectVariable("out float iris_FogFragCoord;");
transformer.prependMain("iris_FogFragCoord = 0.0;");
} else if (parameters.type == FRAGMENT) {
transformer.injectVariable("in float iris_FogFragCoord;");
}
}
}
@@ -0,0 +1,80 @@
package net.coderbot.iris.pipeline.transform;
import net.coderbot.iris.gl.blending.AlphaTest;
import net.coderbot.iris.gl.shader.ShaderType;
import net.coderbot.iris.pipeline.transform.parameter.Parameters;
import org.taumc.glsl.Transformer;
import java.util.Map;
public class CommonTransformer {
private static final Map<String, String> COMMON_TEXTURE_RENAMES = Map.ofEntries(
Map.entry("texture2D", "texture"),
Map.entry("texture3D", "texture"),
Map.entry("texture2DLod", "textureLod"),
Map.entry("texture3DLod", "textureLod"),
Map.entry("texture2DProj", "textureProj"),
Map.entry("texture3DProj", "textureProj"),
Map.entry("texture2DGrad", "textureGrad"),
Map.entry("texture2DGradARB", "textureGrad"),
Map.entry("texture3DGrad", "textureGrad"),
Map.entry("texelFetch2D", "texelFetch"),
Map.entry("texelFetch3D", "texelFetch"),
Map.entry("textureSize2D", "textureSize")
);
public static void transform(Transformer root, Parameters parameters, boolean core, int glslVersion) {
root.rename("gl_FogFragCoord", "iris_FogFragCoord");
if (parameters.type == ShaderType.VERTEX) {
root.injectVariable("out float iris_FogFragCoord;");
root.prependMain("iris_FogFragCoord = 0.0f;");
} else if (parameters.type == ShaderType.FRAGMENT) {
root.injectVariable("in float iris_FogFragCoord;");
}
if (parameters.type == ShaderType.VERTEX) {
root.injectVariable("vec4 iris_FrontColor;");
root.rename("gl_FrontColor", "iris_FrontColor");
}
if (parameters.type == ShaderType.FRAGMENT) {
if (root.containsCall("gl_FragColor")) {
root.replaceExpression("gl_FragColor", "gl_FragData[0]");
}
// Note: In compatibility profile, gl_FragData is a built-in array.
if (!core && parameters.getAlphaTest() != AlphaTest.ALWAYS) {
root.injectVariable("uniform float iris_currentAlphaTest;");
root.appendMain(parameters.getAlphaTest().toExpression("gl_FragData[0].a", "iris_currentAlphaTest", ""));
}
}
if (root.containsCall("texture") && root.hasVariable("texture")) {
root.rename("texture", "gtexture");
}
if (root.hasVariable("iris_renamed_texture")) {
root.rename("iris_renamed_texture", "gtexture");
}
if (root.containsCall("gcolor") && root.hasVariable("gcolor")) {
root.rename("gcolor", "gtexture");
}
root.rename("gl_Fog", "iris_Fog");
root.injectVariable("uniform float iris_FogDensity;");
root.injectVariable("uniform float iris_FogStart;");
root.injectVariable("uniform float iris_FogEnd;");
root.injectVariable("uniform vec4 iris_FogColor;");
root.injectFunction("struct iris_FogParameters {vec4 color;float density;float start;float end;float scale;};");
root.injectFunction("iris_FogParameters iris_Fog = iris_FogParameters(iris_FogColor, iris_FogDensity, iris_FogStart, iris_FogEnd, 1.0f / (iris_FogEnd - iris_FogStart));");
// GLSL 120 natively uses texture2D/shadow2D etc. Ttexture/textureLod don't exist in 120, so only rename for versions that support them.
if (glslVersion > 120) {
root.renameFunctionCall(COMMON_TEXTURE_RENAMES);
root.renameAndWrapShadow("shadow2D", "texture");
root.renameAndWrapShadow("shadow2DLod", "textureLod");
}
}
}
@@ -15,8 +15,7 @@ public class CompatibilityTransformer {
public static void transformEach(Transformer transformer, Parameters parameters) {
if (parameters.type == PatchShaderType.VERTEX) {
;
if (parameters.type == ShaderType.VERTEX) {
// TODO: sildur's jankness
// This is a hacky patch for sildur's shaders that changes the way it does it's waving water to make it work better?
// Why is this the GLSL transformation code in Iris, tell sildur to fix it and remove this?
@@ -1,15 +1,17 @@
package net.coderbot.iris.pipeline.transform;
import net.coderbot.iris.pipeline.transform.parameter.Parameters;
import org.taumc.glsl.Transformer;
class CompositeDepthTransformer {
public static void transform(Transformer transformer) {
// replace original declaration
int type = transformer.findType("centerDepthSmooth");
if (type != 0) {
transformer.injectVariable("uniform sampler2D iris_centerDepthSmooth;");
transformer.replaceExpression("centerDepthSmooth", "texture2D(iris_centerDepthSmooth, vec2(0.5)).r");
}
public static void transform(Transformer transformer, Parameters parameters, int glslVersion) {
CommonTransformer.transform(transformer, parameters, false, glslVersion);
int type = transformer.findType("centerDepthSmooth");
if (type != 0) {
transformer.injectVariable("uniform sampler2D iris_centerDepthSmooth;");
transformer.replaceExpression("centerDepthSmooth", "texture2D(iris_centerDepthSmooth, vec2(0.5)).r");
}
}
}
@@ -0,0 +1,11 @@
package net.coderbot.iris.pipeline.transform;
import net.coderbot.iris.pipeline.transform.parameter.Parameters;
import org.taumc.glsl.Transformer;
public class ComputeTransformer {
public static void transform(Transformer transformer, Parameters parameters, int glslVersion) {
CommonTransformer.transform(transformer, parameters, true, glslVersion);
}
}
@@ -0,0 +1,23 @@
package net.coderbot.iris.pipeline.transform;
import net.coderbot.iris.pipeline.transform.parameter.AttributeParameters;
import org.taumc.glsl.Transformer;
class EntityPatcher {
public static void patchEntityId(Transformer transformer, AttributeParameters parameters) {
injectUniformIfUndeclared(transformer, "entityId", "uniform int entityId;");
injectUniformIfUndeclared(transformer, "blockEntityId", "uniform int blockEntityId;");
injectUniformIfUndeclared(transformer, "currentRenderedItemId", "uniform int currentRenderedItemId;");
}
public static void patchOverlayColor(Transformer transformer, AttributeParameters parameters) {
injectUniformIfUndeclared(transformer, "entityColor", "uniform vec4 entityColor;");
}
private static void injectUniformIfUndeclared(Transformer transformer, String name, String declaration) {
if (transformer.containsCall(name) && !transformer.hasVariable(name)) {
transformer.injectVariable(declaration);
}
}
}
@@ -3,5 +3,6 @@ package net.coderbot.iris.pipeline.transform;
public enum Patch {
ATTRIBUTES,
CELERITAS_TERRAIN,
COMPOSITE
COMPOSITE,
COMPUTE
}
@@ -5,7 +5,10 @@ import net.coderbot.iris.gl.shader.ShaderType;
public enum PatchShaderType {
VERTEX(ShaderType.VERTEX),
GEOMETRY(ShaderType.GEOMETRY),
FRAGMENT(ShaderType.FRAGMENT);
TESS_CONTROL(ShaderType.TESSELATION_CONTROL),
TESS_EVAL(ShaderType.TESSELATION_EVAL),
FRAGMENT(ShaderType.FRAGMENT),
COMPUTE(ShaderType.COMPUTE);
public static final PatchShaderType[] VALUES = values();
@@ -19,8 +22,10 @@ public enum PatchShaderType {
return switch (glShaderType) {
case VERTEX -> new PatchShaderType[] { VERTEX };
case GEOMETRY -> new PatchShaderType[] { GEOMETRY };
case TESSELATION_CONTROL -> new PatchShaderType[] { TESS_CONTROL };
case TESSELATION_EVAL -> new PatchShaderType[] { TESS_EVAL };
case FRAGMENT -> new PatchShaderType[] { FRAGMENT };
default -> throw new IllegalArgumentException("Unknown shader type: " + glShaderType);
case COMPUTE -> new PatchShaderType[] { COMPUTE };
};
}
}
@@ -2,63 +2,282 @@ package net.coderbot.iris.pipeline.transform;
import com.google.common.base.Stopwatch;
import com.gtnewhorizons.angelica.rendering.celeritas.iris.IrisExtendedChunkVertexType;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gl.shader.ShaderType;
import net.coderbot.iris.pipeline.transform.parameter.Parameters;
import net.coderbot.iris.pipeline.transform.parameter.AttributeParameters;
import org.antlr.v4.runtime.CommonToken;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.embeddedt.embeddium.impl.gl.shader.ShaderConstants;
import org.embeddedt.embeddium.impl.render.shader.ShaderLoader;
import org.taumc.glsl.ShaderParser;
import org.taumc.glsl.StorageCollector;
import org.taumc.glsl.Transformer;
import org.taumc.glsl.grammar.GLSLLexer;
import org.taumc.glsl.grammar.GLSLParser;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.BooleanSupplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ShaderTransformer {
private static final Pattern versionPattern = Pattern.compile("#version\\s+(\\d+)(?:\\s+(\\w+))?");
private static final Pattern inOutVaryingPattern = Pattern.compile("(?m)^\\s*(in|out)(\\s+)");
private static final Pattern inPattern = Pattern.compile("(?m)^\\s*(in)(\\s+)");
private static final Pattern outPattern = Pattern.compile("(?m)^\\s*(out)(\\s+)");
private static final Pattern inOutVaryingPattern = Pattern.compile("(?m)^(\\s*(?:(?:flat|smooth|noperspective)\\s+)?)(in|out)(\\s+)");
private static final Pattern inPattern = Pattern.compile("(?m)^(\\s*(?:(?:flat|smooth|noperspective)\\s+)?)(in)(\\s+)");
private static final Pattern outPattern = Pattern.compile("(?m)^(\\s*(?:(?:flat|smooth|noperspective)\\s+)?)(out)(\\s+)");
private static final Pattern texturePattern = Pattern.compile("\\btexture\\s*\\(|(\\btexture\\b)");
private static final Pattern unsignedSuffixPattern = Pattern.compile("(\\b(?:\\d+|0[xX][0-9a-fA-F]+))[uU]\\b");
private static final int CACHE_SIZE = 100;
private static final Object2ObjectLinkedOpenHashMap<TransformKey<?>, Map<PatchShaderType, String>> shaderTransformationCache = new Object2ObjectLinkedOpenHashMap<>();
private static final boolean useCache = true;
// Track logged negotiations to avoid spam - cleared on shader pack reload
private static final Set<String> loggedNegotiations = new HashSet<>();
public static void clearCache() {
synchronized (shaderTransformationCache) {
shaderTransformationCache.clear();
}
loggedNegotiations.clear();
}
/**
* These are words which need to be renamed by iris if a shader uses them, regardless o the GLSL version.
* The words will get caught and renamed to iris_renamed_$WORD
*/
private static final List<String> fullReservedWords = new ArrayList<>();
/**
* This does the same thing as fullReservedWords, but based on a maximum GLSL version. As an example
* if something was register to 400 here, it would get applied on any version below 400.
*/
private static final Map<Integer, List<String>> versionedReservedWords = new HashMap<>();
static {
// texture seems to be reserved by some drivers but not others, however this is not actually reserved by the GLSL spec
fullReservedWords.add("texture");
private static String replaceTexture(String input) {
final var matcher = texturePattern.matcher(input);
final StringBuilder builder = new StringBuilder();
while (matcher.find()) {
if (matcher.group(1) != null) {
matcher.appendReplacement(builder, "iris_renamed_texture");
} else {
matcher.appendReplacement(builder, Matcher.quoteReplacement(matcher.group(0)));
}
}
matcher.appendTail(builder);
return builder.toString();
}
static {
// sample was added as a keyword in GLSL 400, many shaders use it
versionedReservedWords.put(400, Arrays.asList("sample"));
versionedReservedWords.put(400, List.of("sample"));
}
private record VersionRequirement(String keyword, int minVersion, BooleanSupplier supported) {}
// Sorted descending by minVersion for early exit in getRequiredVersion
private static final VersionRequirement[] VERSION_REQUIREMENTS = {
new VersionRequirement("std430", 430, RenderSystem::supportsSSBO),
new VersionRequirement("iimage", 420, RenderSystem::supportsImageLoadStore),
new VersionRequirement("uimage", 420, RenderSystem::supportsImageLoadStore),
new VersionRequirement("imageLoad", 420, RenderSystem::supportsImageLoadStore),
new VersionRequirement("imageStore", 420, RenderSystem::supportsImageLoadStore),
new VersionRequirement("uint", 130, () -> RenderSystem.getMaxGlslVersion() >= 130),
new VersionRequirement("uvec2", 130, () -> RenderSystem.getMaxGlslVersion() >= 130),
new VersionRequirement("uvec3", 130, () -> RenderSystem.getMaxGlslVersion() >= 130),
new VersionRequirement("uvec4", 130, () -> RenderSystem.getMaxGlslVersion() >= 130),
new VersionRequirement("flat", 130, () -> RenderSystem.getMaxGlslVersion() >= 130),
};
private record DowngradeRule(
int fromVersion,
int toVersion,
BooleanSupplier supported,
List<String> extensions,
Map<String, String> defines,
List<String> preprocessorDefines,
boolean convertStorageQualifiers
) {}
private static final DowngradeRule[] DOWNGRADE_RULES = {
new DowngradeRule(130, 120,
RenderSystem::supportsGpuShader4,
List.of("GL_EXT_gpu_shader4"),
Map.of("texture", "texture2D"),
List.of(
// Preprocessor defines
"#define uint int",
"#define uvec2 ivec2",
"#define uvec3 ivec3",
"#define uvec4 ivec4",
"#define isnan(x) ((x) != (x))",
"#define isinf(x) ((x) == (1.0/0.0) || (x) == (-1.0/0.0))",
"#define trunc(x) (sign(x) * floor(abs(x)))",
"#define round(x) (floor((x) + 0.5))",
"#define texelFetch texelFetch2D",
"#define textureSize textureSize2D",
"#define modf iris_modf",
// Function definitions
"GLSL_FUNC:float iris_modf(float x, out float i) { i = sign(x) * floor(abs(x)); return x - i; }",
"GLSL_FUNC:vec2 iris_modf(vec2 x, out vec2 i) { i = sign(x) * floor(abs(x)); return x - i; }",
"GLSL_FUNC:vec3 iris_modf(vec3 x, out vec3 i) { i = sign(x) * floor(abs(x)); return x - i; }",
"GLSL_FUNC:vec4 iris_modf(vec4 x, out vec4 i) { i = sign(x) * floor(abs(x)); return x - i; }",
"GLSL_FUNC:vec2 mix(vec2 a, vec2 b, bvec2 sel) { return vec2(sel.x ? b.x : a.x, sel.y ? b.y : a.y); }",
"GLSL_FUNC:vec3 mix(vec3 a, vec3 b, bvec3 sel) { return vec3(sel.x ? b.x : a.x, sel.y ? b.y : a.y, sel.z ? b.z : a.z); }",
"GLSL_FUNC:vec4 mix(vec4 a, vec4 b, bvec4 sel) { return vec4(sel.x ? b.x : a.x, sel.y ? b.y : a.y, sel.z ? b.z : a.z, sel.w ? b.w : a.w); }",
"GLSL_FUNC:bool any(bool b) { return b; }",
"GLSL_FUNC:bool all(bool b) { return b; }"
),
true
)
};
record NegotiationResult(
int targetVersion,
String profile,
List<String> extensions,
Map<String, String> defines,
List<String> preprocessorDefines,
boolean convertStorageQualifiers,
String error
) {
static NegotiationResult success(int targetVersion, String profile, List<String> extensions, Map<String, String> defines, List<String> preprocessorDefines, boolean convertStorageQualifiers) {
return new NegotiationResult(targetVersion, profile, extensions, defines, preprocessorDefines, convertStorageQualifiers, null);
}
static NegotiationResult error(String message) {
return new NegotiationResult(-1, "", List.of(), Map.of(), List.of(), false, message);
}
static NegotiationResult noop(int version, String profile) {
return new NegotiationResult(version, profile, List.of(), Map.of(), List.of(), false, null);
}
boolean isError() { return error != null; }
}
private static int getStageMinimumVersion(PatchShaderType stage) {
return switch (stage) {
case COMPUTE -> 330;
case TESS_CONTROL, TESS_EVAL -> 400;
case GEOMETRY -> 150;
default -> 110;
};
}
static NegotiationResult negotiateVersion(int effectiveVersion, PatchShaderType stage) {
final int maxGlsl = RenderSystem.getMaxGlslVersion();
if (effectiveVersion <= maxGlsl) {
if (effectiveVersion <= 120 && RenderSystem.supportsGpuShader4()) {
final String profile = "";
for (DowngradeRule rule : DOWNGRADE_RULES) {
if (rule.fromVersion == 130 && rule.toVersion == 120) {
final List<String> definesOnly = rule.preprocessorDefines.stream().filter(d -> !d.startsWith("GLSL_FUNC:")).toList();
return NegotiationResult.success(effectiveVersion, profile, rule.extensions, rule.defines, definesOnly, true);
}
}
return NegotiationResult.success(effectiveVersion, profile, List.of("GL_EXT_gpu_shader4"), Map.of(), List.of(), true);
}
return NegotiationResult.noop(effectiveVersion, effectiveVersion >= 150 ? "compatibility" : "");
}
final int stageMin = getStageMinimumVersion(stage);
if (maxGlsl < stageMin) {
return NegotiationResult.error("Hardware GLSL " + maxGlsl + " below stage minimum " + stageMin + " for " + stage.name());
}
// Walk downgrade rules from effectiveVersion toward maxGlsl
final List<String> accExtensions = new ArrayList<>();
final Map<String, String> accDefines = new HashMap<>();
final List<String> accPreprocessorDefines = new ArrayList<>();
boolean accConvertQualifiers = false;
int currentVersion = effectiveVersion;
while (currentVersion > maxGlsl) {
DowngradeRule matched = null;
for (DowngradeRule rule : DOWNGRADE_RULES) {
if (rule.fromVersion == currentVersion) {
matched = rule;
break;
}
}
if (matched == null) {
return NegotiationResult.error("No downgrade rule from GLSL " + currentVersion + " (hardware max: " + maxGlsl + ", shader requires: " + effectiveVersion + ")");
}
// Verify rule's required extensions are supported
if (!matched.supported.getAsBoolean()) {
return NegotiationResult.error("Downgrade from " + matched.fromVersion + " to " + matched.toVersion + " requires extensions " + matched.extensions + " which are not supported");
}
accExtensions.addAll(matched.extensions);
accDefines.putAll(matched.defines);
accPreprocessorDefines.addAll(matched.preprocessorDefines);
accConvertQualifiers |= matched.convertStorageQualifiers;
currentVersion = matched.toVersion;
}
if (currentVersion < stageMin) {
return NegotiationResult.error("Downgrade reached GLSL " + currentVersion + " which is below stage minimum " + stageMin + " for " + stage.name());
}
final String profile = currentVersion >= 150 ? "compatibility" : "";
return NegotiationResult.success(currentVersion, profile, accExtensions, accDefines, accPreprocessorDefines, accConvertQualifiers);
}
private static Pattern hoistPattern;
private static Object2IntMap<String> keywordToVersion;
private static int maxSupportedHoistVersion;
public static void init() {
final StringBuilder patternBuilder = new StringBuilder();
final Object2IntOpenHashMap<String> versionMap = new Object2IntOpenHashMap<>();
int maxVersion = 0;
for (VersionRequirement req : VERSION_REQUIREMENTS) {
if (req.supported.getAsBoolean()) {
if (!patternBuilder.isEmpty()) patternBuilder.append('|');
patternBuilder.append("\\b").append(Pattern.quote(req.keyword)).append("\\b");
versionMap.put(req.keyword, req.minVersion);
maxVersion = Math.max(maxVersion, req.minVersion);
}
}
if (!patternBuilder.isEmpty()) {
hoistPattern = Pattern.compile(patternBuilder.toString());
keywordToVersion = versionMap;
}
maxSupportedHoistVersion = maxVersion;
Iris.logger.info("Shader version hoisting: {} feature(s) GLSL {}", versionMap.size(), maxVersion > 0 ? maxVersion : "N/A");
}
private static int getRequiredVersion(String shaderSource, int declaredVersion) {
if (hoistPattern == null || declaredVersion >= maxSupportedHoistVersion) {
return declaredVersion;
}
final Matcher m = hoistPattern.matcher(shaderSource);
int required = declaredVersion;
while (m.find()) {
final int ver = keywordToVersion.getInt(m.group());
if (ver > required) {
required = ver;
if (required >= maxSupportedHoistVersion) break;
}
}
return required;
}
private static final class TransformKey<P extends Parameters> {
@@ -96,8 +315,8 @@ public class ShaderTransformer {
}
}
public static <P extends Parameters> Map<PatchShaderType, String> transform(String vertex, String geometry, String fragment, P parameters) {
if (vertex == null && geometry == null && fragment == null) {
public static <P extends Parameters> Map<PatchShaderType, String> transform(String vertex, String geometry, String tessControl, String tessEval, String fragment, P parameters) {
if (vertex == null && geometry == null && tessControl == null && tessEval == null && fragment == null) {
return null;
} else {
Map<PatchShaderType, String> result;
@@ -107,6 +326,8 @@ public class ShaderTransformer {
EnumMap<PatchShaderType, String> inputs = new EnumMap<>(PatchShaderType.class);
inputs.put(PatchShaderType.VERTEX, vertex);
inputs.put(PatchShaderType.GEOMETRY, geometry);
inputs.put(PatchShaderType.TESS_CONTROL, tessControl);
inputs.put(PatchShaderType.TESS_EVAL, tessEval);
inputs.put(PatchShaderType.FRAGMENT, fragment);
var key = new TransformKey<>(patchType, inputs, parameters);
@@ -135,24 +356,142 @@ public class ShaderTransformer {
}
}
private static <P extends Parameters> Map<PatchShaderType, String> transformInternal(EnumMap<PatchShaderType, String> inputs, Patch patchType, P parameters) {
EnumMap<PatchShaderType, String> result = new EnumMap<>(PatchShaderType.class);
EnumMap<PatchShaderType, Transformer> types = new EnumMap<>(PatchShaderType.class);
EnumMap<PatchShaderType, String> prepatched = new EnumMap<>(PatchShaderType.class);
List<Transformer> textureLodExtensionPatches = new ArrayList<>();
List<Transformer> hacky120Patches = new ArrayList<>();
public static <P extends Parameters> Map<PatchShaderType, String> transformCompute(String compute, P parameters) {
if (compute == null) {
return null;
} else {
Map<PatchShaderType, String> result;
Stopwatch watch = Stopwatch.createStarted();
final var patchType = parameters.patch;
EnumMap<PatchShaderType, String> inputs = new EnumMap<>(PatchShaderType.class);
inputs.put(PatchShaderType.COMPUTE, compute);
final var key = new TransformKey<>(patchType, inputs, parameters);
synchronized (shaderTransformationCache) {
result = shaderTransformationCache.getAndMoveToLast(key);
}
if (result == null || !useCache) {
result = transformComputeInternal(compute, patchType, parameters);
// Clear this, we don't want whatever random type was last transformed being considered for the key
parameters.type = null;
synchronized (shaderTransformationCache) {
// Double-check in case another thread added it while we were transforming
final Map<PatchShaderType, String> existing = shaderTransformationCache.getAndMoveToLast(key);
if (existing != null) {
return existing;
}
if (shaderTransformationCache.size() >= CACHE_SIZE) {
shaderTransformationCache.removeFirst();
}
shaderTransformationCache.putAndMoveToLast(key, result);
}
}
return result;
}
}
private static <P extends Parameters> Map<PatchShaderType, String> transformComputeInternal(String compute, Patch patchType, P parameters) {
final EnumMap<PatchShaderType, String> result = new EnumMap<>(PatchShaderType.class);
final Stopwatch watch = Stopwatch.createStarted();
parameters.type = ShaderType.COMPUTE;
final Matcher matcher = versionPattern.matcher(compute);
if (!matcher.find()) {
throw new IllegalArgumentException("No #version directive found in compute shader source code!");
}
String versionString = matcher.group(1);
int versionInt = Integer.parseInt(versionString);
// Check if shader uses features requiring a higher GLSL version
final int requiredVersion = getRequiredVersion(compute, versionInt);
if (requiredVersion > versionInt) {
Iris.logger.debug("Compute shader requires GLSL {} for detected features, hoisting from {}", requiredVersion, versionInt);
versionInt = requiredVersion;
versionString = String.valueOf(versionInt);
}
// Compute shaders always use core profile, minimum 330
if (versionInt < 330) {
versionString = "330";
versionInt = 330;
}
// Negotiate version downgrade if needed
final NegotiationResult negotiation = negotiateVersion(versionInt, PatchShaderType.COMPUTE);
if (negotiation.isError()) {
throw new RuntimeException("Compute shader version negotiation failed: " + negotiation.error());
}
if (negotiation.targetVersion() != versionInt) {
Iris.logger.debug("Negotiated compute shader from GLSL {} to {}", versionInt, negotiation.targetVersion());
versionInt = negotiation.targetVersion();
versionString = String.valueOf(versionInt);
}
String profileString = "#version " + versionString + " core\n";
// Rename reserved words
String input = replaceTexture(compute);
for (int version : versionedReservedWords.keySet()) {
if (versionInt < version) {
for (String reservedWord : versionedReservedWords.get(version)) {
final String newName = "iris_renamed_" + reservedWord;
input = input.replaceAll("\\b" + reservedWord + "\\b", newName);
}
}
}
final var parsedShader = ShaderParser.parseShader(input);
final var transformer = new Transformer(parsedShader.full());
doTransform(transformer, patchType, parameters, "core", versionInt);
// Extract extensions
final var extensions = versionPattern.matcher(getFormattedShader(parsedShader.pre(), "")).replaceFirst("").trim();
final String finalHeader = profileString + (extensions.isEmpty() ? "" : "\n" + extensions);
final StringBuilder formattedShaderBuilder = new StringBuilder();
transformer.mutateTree(tree -> {
formattedShaderBuilder.append(getFormattedShader(tree, finalHeader));
});
String formattedShader = formattedShaderBuilder.toString();
// Restore identifiers that were temporarily renamed
formattedShader = formattedShader.replace("iris_renamed_texture", "texture");
formattedShader = formattedShader.replace("iris_renamed_sample", "sample");
result.put(PatchShaderType.COMPUTE, formattedShader);
watch.stop();
Iris.logger.info("[Load #{}] Transformed compute shader for {} in {}", Iris.getShaderPackLoadId(), patchType.name(), watch);
return result;
}
private static <P extends Parameters> Map<PatchShaderType, String> transformInternal(EnumMap<PatchShaderType, String> inputs, Patch patchType, P parameters) {
final EnumMap<PatchShaderType, String> result = new EnumMap<>(PatchShaderType.class);
final EnumMap<PatchShaderType, Transformer> types = new EnumMap<>(PatchShaderType.class);
final EnumMap<PatchShaderType, String> prepatched = new EnumMap<>(PatchShaderType.class);
final EnumMap<PatchShaderType, NegotiationResult> negotiations = new EnumMap<>(PatchShaderType.class);
final EnumMap<PatchShaderType, Boolean> needsTextureLodExtension = new EnumMap<>(PatchShaderType.class);
final Stopwatch watch = Stopwatch.createStarted();
for (PatchShaderType type : PatchShaderType.VALUES) {
parameters.type = type;
parameters.type = type.glShaderType;
if (inputs.get(type) == null) {
continue;
}
String input = inputs.get(type);
Matcher matcher = versionPattern.matcher(input);
final Matcher matcher = versionPattern.matcher(input);
if (!matcher.find()) {
throw new IllegalArgumentException("No #version directive found in source code!");
}
@@ -164,60 +503,85 @@ public class ShaderTransformer {
String profile = "";
int versionInt = Integer.parseInt(versionString);
if (versionInt >= 150) {
profile = matcher.group(2);
if (profile == null) {
profile = "core";
}
// Include celeritas header in scan — it's injected post-negotiation but contains uint/uvec3
final String scanSource = (patchType == Patch.CELERITAS_TERRAIN && type == PatchShaderType.VERTEX) ? input + computeCeleritasHeader() : input;
final int requiredVersion = getRequiredVersion(scanSource, versionInt);
if (requiredVersion > versionInt) {
Iris.logger.debug("Shader requires GLSL {} for detected features, hoisting from {}", requiredVersion, versionInt);
versionInt = requiredVersion;
versionString = String.valueOf(versionInt);
}
String profileString = "#version " + versionString + " " + profile + "\n";
// Negotiate version downgrade if needed
final NegotiationResult negotiation = negotiateVersion(versionInt, type);
if (negotiation.isError()) {
throw new RuntimeException("Shader version negotiation failed for " + type.name() + ": " + negotiation.error());
}
if (negotiation.targetVersion() != versionInt) {
String negotiationKey = type.name() + "_" + versionInt + "_" + negotiation.targetVersion();
if (loggedNegotiations.add(negotiationKey)) {
Iris.logger.info("Negotiated {} shader from GLSL {} to {} (extensions: {}, polyfills: {})", type.name(), versionInt, negotiation.targetVersion(), negotiation.extensions(), negotiation.preprocessorDefines().size());
}
versionInt = negotiation.targetVersion();
versionString = String.valueOf(versionInt);
profile = negotiation.profile();
} else {
if (versionInt >= 150) {
profile = matcher.group(2);
if (profile == null) {
profile = "compatibility";
}
}
}
negotiations.put(type, negotiation);
final String profileString = "#version " + versionString + (profile.isEmpty() ? "" : " " + profile) + "\n";
input = replaceTexture(input);
// The primary reason we rename words here using regex, is because if the words cause invalid
// GLSL, regardless of the version being used, it will cause glsl-transformation-lib to fail
// so we need to rename them prior to passing the shader input to glsl-transformation-lib.
for (String reservedWord : fullReservedWords) {
String newName = "iris_renamed_" + reservedWord;
input = input.replaceAll("\\b" + reservedWord + "\\b", newName);
}
for (int version : versionedReservedWords.keySet()) {
if (versionInt < version) {
for (String reservedWord : versionedReservedWords.get(version)) {
String newName = "iris_renamed_" + reservedWord;
final String newName = "iris_renamed_" + reservedWord;
input = input.replaceAll("\\b" + reservedWord + "\\b", newName);
}
}
}
var parsedShader = ShaderParser.parseShader(input);
var transformer = new Transformer(parsedShader.full());
final var parsedShader = ShaderParser.parseShader(input);
final var transformer = new Transformer(parsedShader.full());
if (parameters.type == ShaderType.VERTEX || parameters.type == ShaderType.FRAGMENT) {
upgradeStorageQualifiers(transformer, parameters);
}
doTransform(transformer, patchType, parameters, profile, versionInt);
// Check if we need to patch in texture LOD extension enabling
if (versionInt <= 120 && (transformer.containsCall("texture2DLod") || transformer.containsCall("texture3DLod") || transformer.containsCall("texture2DGradARB"))) {
textureLodExtensionPatches.add(transformer);
}
// Check if we need to patch in some hacky GLSL 120 compat
if (versionInt <= 120) {
hacky120Patches.add(transformer);
needsTextureLodExtension.put(type, true);
}
// Extract extensions from the pre-parsed content (version + extensions before main code)
// This preserves #extension directives that the shader pack declares
var extensions = versionPattern.matcher(getFormattedShader(parsedShader.pre(), "")).replaceFirst("").trim();
final var extensions = versionPattern.matcher(getFormattedShader(parsedShader.pre(), "")).replaceFirst("").trim();
types.put(type, transformer);
prepatched.put(type, profileString + (extensions.isEmpty() ? "" : "\n" + extensions));
}
CompatibilityTransformer.transformGrouped(types, parameters);
for (var entry : types.entrySet()) {
final PatchShaderType shaderType = entry.getKey();
final Transformer transformer = entry.getValue();
String header = prepatched.get(entry.getKey());
String header = prepatched.get(shaderType);
final NegotiationResult negotiation = negotiations.get(shaderType);
// For Celeritas terrain vertex shaders, inject chunk_vertex.glsl header
if (patchType == Patch.CELERITAS_TERRAIN && entry.getKey() == PatchShaderType.VERTEX) {
if (patchType == Patch.CELERITAS_TERRAIN && shaderType == PatchShaderType.VERTEX) {
header += computeCeleritasHeader();
}
@@ -234,39 +598,38 @@ public class ShaderTransformer {
formattedShader = formattedShader.replace("iris_renamed_texture", "texture");
formattedShader = formattedShader.replace("iris_renamed_sample", "sample");
// Please don't mind the entire rest of this loop basically, we're doing awful fragile regex on the transformed
// shader output to do things that I can't figure out with AST because I'm bad at it
if (textureLodExtensionPatches.contains(transformer)) {
String[] parts = formattedShader.split("\n", 2);
// Inject texture LOD extension if needed
if (needsTextureLodExtension.containsKey(shaderType)) {
final String[] parts = formattedShader.split("\n", 2);
parts[1] = "#extension GL_ARB_shader_texture_lod : require\n" + parts[1];
formattedShader = parts[0] + "\n" + parts[1];
}
if (hacky120Patches.contains(transformer)) {
// Forcibly enable GL_EXT_gpu_shader4, it has a lot of compatibility backports with GLSL 130+
// and seems more or less universally supported by hardware/drivers
String[] parts = formattedShader.split("\n", 2);
parts[1] = "#extension GL_EXT_gpu_shader4 : require\n" + parts[1];
formattedShader = parts[0] + "\n" + parts[1];
if (negotiation != null && (!negotiation.extensions().isEmpty() || !negotiation.preprocessorDefines().isEmpty())) {
formattedShader = injectGlslPreamble(formattedShader, negotiation.extensions(), negotiation.preprocessorDefines());
}
// GLSL 120 compatibility for in/out specifiers:
// - Vertex shaders: "in" = vertex attribute input -> "attribute", "out" = to fragment -> "varying"
// - Fragment shaders: "in" = from vertex -> "varying", "out" = color output -> handled elsewhere
if (entry.getKey() == PatchShaderType.VERTEX) {
// In vertex shaders, "in" declarations are vertex attributes, not varyings
Matcher inMatcher = inPattern.matcher(formattedShader);
formattedShader = inMatcher.replaceAll("attribute$2");
Matcher outMatcher = outPattern.matcher(formattedShader);
formattedShader = outMatcher.replaceAll("varying$2");
} else {
// In fragment (and geometry) shaders, both in/out become varying
Matcher inOutVaryingMatcher = inOutVaryingPattern.matcher(formattedShader);
formattedShader = inOutVaryingMatcher.replaceAll("varying$2");
if (negotiation != null && !negotiation.defines().isEmpty()) {
for (var defineEntry : negotiation.defines().entrySet()) {
formattedShader = formattedShader.replaceAll("\\b" + Pattern.quote(defineEntry.getKey()) + "\\b", Matcher.quoteReplacement(defineEntry.getValue()));
}
}
result.put(entry.getKey(), formattedShader);
// Convert storage qualifiers for downgraded shaders or native 120 shaders
if (negotiation != null && (negotiation.convertStorageQualifiers() || negotiation.targetVersion() <= 120)) {
if (shaderType == PatchShaderType.VERTEX) {
final Matcher inMatcher = inPattern.matcher(formattedShader);
formattedShader = inMatcher.replaceAll("$1attribute$3");
final Matcher outMatcher = outPattern.matcher(formattedShader);
formattedShader = outMatcher.replaceAll("$1varying$3");
} else {
final Matcher inOutVaryingMatcher = inOutVaryingPattern.matcher(formattedShader);
formattedShader = inOutVaryingMatcher.replaceAll("$1varying$3");
}
formattedShader = unsignedSuffixPattern.matcher(formattedShader).replaceAll("$1");
}
result.put(shaderType, formattedShader);
}
watch.stop();
Iris.logger.info("[Load #{}] Transformed shader for {} in {}", Iris.getShaderPackLoadId(), patchType.name(), watch);
@@ -276,18 +639,21 @@ public class ShaderTransformer {
private static void doTransform(Transformer transformer, Patch patchType, Parameters parameters, String profile, int versionInt) {
switch (patchType) {
case CELERITAS_TERRAIN:
CeleritasTransformer.transform(transformer, parameters);
CeleritasTransformer.transform(transformer, parameters, versionInt);
// Handle mc_midTexCoord for Celeritas
patchMultiTexCoord3(transformer, parameters);
replaceMidTexCoord(transformer, IrisExtendedChunkVertexType.MID_TEX_SCALE);
applyIntelHd4000Workaround(transformer);
break;
case COMPOSITE:
CompositeDepthTransformer.transform(transformer);
CompositeDepthTransformer.transform(transformer, parameters, versionInt);
break;
case ATTRIBUTES:
AttributeTransformer.transform(transformer, (AttributeParameters) parameters, profile, versionInt);
break;
case COMPUTE:
ComputeTransformer.transform(transformer, parameters, versionInt);
break;
default:
throw new IllegalStateException("Unknown patch type: " + patchType.name());
}
@@ -298,22 +664,15 @@ public class ShaderTransformer {
transformer.renameFunctionCall("ftransform", "iris_ftransform");
}
public static void replaceGlMultiTexCoordBounded(Transformer transformer, int min, int max) {
for (int i = min; i <= max; i++) {
transformer.replaceExpression("gl_MultiTexCoord" + i, "vec4(0.0, 0.0, 0.0, 1.0)");
}
}
public static void patchMultiTexCoord3(Transformer transformer, Parameters parameters) {
if (parameters.type.glShaderType == ShaderType.VERTEX && transformer.hasVariable("gl_MultiTexCoord3") && !transformer.hasVariable("mc_midTexCoord")) {
if (parameters.type == ShaderType.VERTEX && transformer.hasVariable("gl_MultiTexCoord3") && !transformer.hasVariable("mc_midTexCoord")) {
transformer.rename("gl_MultiTexCoord3", "mc_midTexCoord");
transformer.injectVariable("attribute vec4 mc_midTexCoord;");
}
}
public static void replaceMidTexCoord(Transformer transformer, float textureScale) {
int type = transformer.findType("mc_midTexCoord");
final int type = transformer.findType("mc_midTexCoord");
if (type != 0) {
transformer.removeVariable("mc_midTexCoord");
}
@@ -370,6 +729,89 @@ public class ShaderTransformer {
return "\n\n" + chunkVertexHeader + "\n\n";
}
/**
* Converts GLSL 120 storage qualifiers (varying/attribute) to modern in/out tokens so downstream AST transforms (e.g. CompatibilityTransformer) can find them.
* The hacky120Patches regex pass converts them back for the final output.
*/
public static void upgradeStorageQualifiers(Transformer root, Parameters parameters) {
final List<TerminalNode> tokens = new ArrayList<>();
root.mutateTree(tree -> ParseTreeWalker.DEFAULT.walk(new StorageCollector(tokens), tree));
for (TerminalNode node : tokens) {
if (!(node.getSymbol() instanceof CommonToken token)) {
return;
}
if (token.getType() == GLSLParser.ATTRIBUTE) {
token.setType(GLSLParser.IN);
token.setText(GLSLParser.VOCABULARY.getLiteralName(GLSLParser.IN).replace("'", ""));
} else if (token.getType() == GLSLParser.VARYING) {
if (parameters.type == ShaderType.VERTEX) {
token.setType(GLSLParser.OUT);
token.setText(GLSLParser.VOCABULARY.getLiteralName(GLSLParser.OUT).replace("'", ""));
} else {
token.setType(GLSLParser.IN);
token.setText(GLSLParser.VOCABULARY.getLiteralName(GLSLParser.IN).replace("'", ""));
}
}
}
}
private static String injectGlslPreamble(String shader, List<String> extensions, List<String> preprocessorDefines) {
final StringBuilder extensionBlock = new StringBuilder();
final StringBuilder defineBlock = new StringBuilder();
final StringBuilder functionBlock = new StringBuilder();
for (String ext : extensions) {
extensionBlock.append("#extension ").append(ext).append(" : require\n");
}
for (String define : preprocessorDefines) {
if (define.startsWith("GLSL_FUNC:")) {
functionBlock.append(define.substring(10)).append("\n");
} else {
defineBlock.append(define).append("\n");
}
}
// Find where preprocessor section ends and code begins
final String[] lines = shader.split("\n");
final StringBuilder shaderResult = new StringBuilder();
boolean extensionsInjected = false, definesInjected = false, functionsInjected = false;
for (String line : lines) {
final String trimmed = line.trim();
final boolean isPreprocessor = trimmed.startsWith("#");
final boolean isExtension = trimmed.startsWith("#extension");
final boolean isVersion = trimmed.startsWith("#version");
// Inject our extensions right after #version
if (isVersion) {
shaderResult.append(line).append("\n");
shaderResult.append(extensionBlock);
extensionsInjected = true;
continue;
}
// Inject our defines after the last #extension line (before other preprocessor or code)
if (!definesInjected && extensionsInjected && !isExtension && !trimmed.isEmpty()) {
shaderResult.append(defineBlock);
definesInjected = true;
}
// Inject our functions after all preprocessor lines
if (!functionsInjected && definesInjected && !isPreprocessor && !trimmed.isEmpty()) {
shaderResult.append(functionBlock);
functionsInjected = true;
}
shaderResult.append(line).append("\n");
}
if (!definesInjected) shaderResult.append(defineBlock);
if (!functionsInjected) shaderResult.append(functionBlock);
return shaderResult.toString();
}
public static String getFormattedShader(ParseTree tree, String string) {
final StringBuilder sb = new StringBuilder(string + "\n");
final String[] tabHolder = {""};
@@ -1,8 +1,15 @@
package net.coderbot.iris.pipeline.transform;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability;
import net.coderbot.iris.gl.texture.TextureType;
import net.coderbot.iris.helpers.Tri;
import net.coderbot.iris.pipeline.transform.parameter.AttributeParameters;
import net.coderbot.iris.pipeline.transform.parameter.CeleritasTerrainParameters;
import net.coderbot.iris.pipeline.transform.parameter.ComputeParameters;
import net.coderbot.iris.pipeline.transform.parameter.Parameters;
import net.coderbot.iris.pipeline.transform.parameter.TextureStageParameters;
import net.coderbot.iris.shaderpack.texture.TextureStage;
import java.util.LinkedHashMap;
import java.util.Map;
@@ -23,12 +30,16 @@ public class TransformPatcher {
final Parameters parameters;
final String vertex;
final String geometry;
final String tessControl;
final String tessEval;
final String fragment;
public CacheKey(Parameters parameters, String vertex, String geometry, String fragment) {
public CacheKey(Parameters parameters, String vertex, String geometry, String tessControl, String tessEval, String fragment) {
this.parameters = parameters;
this.vertex = vertex;
this.geometry = geometry;
this.tessControl = tessControl;
this.tessEval = tessEval;
this.fragment = fragment;
}
@@ -38,6 +49,8 @@ public class TransformPatcher {
int result = 1;
result = prime * result + ((fragment == null) ? 0 : fragment.hashCode());
result = prime * result + ((geometry == null) ? 0 : geometry.hashCode());
result = prime * result + ((tessControl == null) ? 0 : tessControl.hashCode());
result = prime * result + ((tessEval == null) ? 0 : tessEval.hashCode());
result = prime * result + ((parameters == null) ? 0 : parameters.hashCode());
result = prime * result + ((vertex == null) ? 0 : vertex.hashCode());
return result;
@@ -45,39 +58,20 @@ public class TransformPatcher {
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
final TransformPatcher.CacheKey other = (TransformPatcher.CacheKey) obj;
if (fragment == null) {
if (other.fragment != null)
return false;
} else if (!fragment.equals(other.fragment))
return false;
if (geometry == null) {
if (other.geometry != null)
return false;
} else if (!geometry.equals(other.geometry))
return false;
if (parameters == null) {
if (other.parameters != null)
return false;
} else if (!parameters.equals(other.parameters))
return false;
if (vertex == null) {
if (other.vertex != null)
return false;
} else if (!vertex.equals(other.vertex))
return false;
return true;
return java.util.Objects.equals(fragment, other.fragment)
&& java.util.Objects.equals(geometry, other.geometry)
&& java.util.Objects.equals(tessControl, other.tessControl)
&& java.util.Objects.equals(tessEval, other.tessEval)
&& java.util.Objects.equals(parameters, other.parameters)
&& java.util.Objects.equals(vertex, other.vertex);
}
}
private static Map<PatchShaderType, String> transform(String vertex, String geometry, String fragment, Parameters parameters) {
if (vertex == null && geometry == null && fragment == null) {
private static Map<PatchShaderType, String> transform(String vertex, String geometry, String tessControl, String tessEval, String fragment, Parameters parameters) {
if (vertex == null && geometry == null && tessControl == null && tessEval == null && fragment == null) {
return null;
}
@@ -85,7 +79,7 @@ public class TransformPatcher {
TransformPatcher.CacheKey key = null;
Map<PatchShaderType, String> result = null;
if (useCache) {
key = new TransformPatcher.CacheKey(parameters, vertex, geometry, fragment);
key = new TransformPatcher.CacheKey(parameters, vertex, geometry, tessControl, tessEval, fragment);
synchronized (cache) {
result = cache.get(key);
}
@@ -93,7 +87,7 @@ public class TransformPatcher {
// if there is no cache result, transform the shaders
if (result == null) {
result = ShaderTransformer.transform(vertex, geometry, fragment, parameters);
result = ShaderTransformer.transform(vertex, geometry, tessControl, tessEval, fragment, parameters);
if (useCache) {
synchronized (cache) {
// Double-check in case another thread added it while we were transforming
@@ -109,16 +103,40 @@ public class TransformPatcher {
return result;
}
public static Map<PatchShaderType, String> patchAttributes(String vertex, String geometry, String tessControl, String tessEval, String fragment, InputAvailability inputs) {
return transform(vertex, geometry, tessControl, tessEval, fragment, new AttributeParameters(Patch.ATTRIBUTES, geometry != null, inputs));
}
public static Map<PatchShaderType, String> patchAttributes(String vertex, String geometry, String fragment, InputAvailability inputs) {
return transform(vertex, geometry, fragment, new AttributeParameters(Patch.ATTRIBUTES, geometry != null, inputs));
return patchAttributes(vertex, geometry, null, null, fragment, inputs);
}
public static Map<PatchShaderType, String> patchCeleritasTerrain(String vertex, String geometry, String fragment) {
return transform(vertex, geometry, fragment, new Parameters(Patch.CELERITAS_TERRAIN));
return transform(vertex, geometry, null, null, fragment, new CeleritasTerrainParameters(Patch.CELERITAS_TERRAIN));
}
public static Map<PatchShaderType, String> patchComposite(String vertex, String geometry, String fragment) {
return transform(vertex, geometry, fragment, new Parameters(Patch.COMPOSITE));
return patchComposite(vertex, geometry, null, null, fragment, TextureStage.COMPOSITE_AND_FINAL, null);
}
public static Map<PatchShaderType, String> patchComposite(String vertex, String geometry, String tessControl, String tessEval, String fragment) {
return patchComposite(vertex, geometry, tessControl, tessEval, fragment, TextureStage.COMPOSITE_AND_FINAL, null);
}
public static Map<PatchShaderType, String> patchComposite(String vertex, String geometry, String tessControl, String tessEval, String fragment, TextureStage stage, Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> textureMap) {
return transform(vertex, geometry, tessControl, tessEval, fragment, new TextureStageParameters(Patch.COMPOSITE, stage, textureMap));
}
public static Map<PatchShaderType, String> patchComposite(String vertex, String geometry, String fragment, TextureStage stage, Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> textureMap) {
return patchComposite(vertex, geometry, null, null, fragment, stage, textureMap);
}
public static String patchCompute(String name, String compute, TextureStage stage, Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> textureMap) {
if (compute == null) {
return null;
}
Map<PatchShaderType, String> result = ShaderTransformer.transformCompute(compute, new ComputeParameters(Patch.COMPUTE, stage, textureMap));
return result != null ? result.get(PatchShaderType.COMPUTE) : null;
}
public static void clearCache() {
@@ -2,42 +2,49 @@ package net.coderbot.iris.pipeline.transform.parameter;
import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability;
import net.coderbot.iris.pipeline.transform.Patch;
import net.coderbot.iris.shaderpack.texture.TextureStage;
public class AttributeParameters extends Parameters {
public final boolean hasGeometry;
public final InputAvailability inputs;
public final boolean hasGeometry;
public final InputAvailability inputs;
// WARNING: adding new fields requires updating hashCode and equals methods!
public AttributeParameters(Patch patch, boolean hasGeometry, InputAvailability inputs) {
super(patch);
this.hasGeometry = hasGeometry;
this.inputs = inputs;
}
public AttributeParameters(Patch patch, boolean hasGeometry, InputAvailability inputs) {
super(patch, null);
this.hasGeometry = hasGeometry;
this.inputs = inputs;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + (hasGeometry ? 1231 : 1237);
result = prime * result + ((inputs == null) ? 0 : inputs.hashCode());
return result;
}
@Override
public TextureStage getTextureStage() {
return TextureStage.GBUFFERS_AND_SHADOW;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
AttributeParameters other = (AttributeParameters) obj;
if (hasGeometry != other.hasGeometry)
return false;
if (inputs == null) {
if (other.inputs != null)
return false;
} else if (!inputs.equals(other.inputs))
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + (hasGeometry ? 1231 : 1237);
result = prime * result + ((inputs == null) ? 0 : inputs.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
AttributeParameters other = (AttributeParameters) obj;
if (hasGeometry != other.hasGeometry)
return false;
if (inputs == null) {
if (other.inputs != null)
return false;
} else if (!inputs.equals(other.inputs))
return false;
return true;
}
}
@@ -0,0 +1,19 @@
package net.coderbot.iris.pipeline.transform.parameter;
import net.coderbot.iris.pipeline.transform.Patch;
import net.coderbot.iris.shaderpack.texture.TextureStage;
public class CeleritasTerrainParameters extends Parameters {
// WARNING: adding new fields requires updating hashCode and equals methods!
public CeleritasTerrainParameters(Patch patch) {
super(patch, null);
}
@Override
public TextureStage getTextureStage() {
return TextureStage.GBUFFERS_AND_SHADOW;
}
// since this class has no additional fields, hashCode() and equals() are inherited from Parameters
}
@@ -0,0 +1,24 @@
package net.coderbot.iris.pipeline.transform.parameter;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import net.coderbot.iris.gl.blending.AlphaTest;
import net.coderbot.iris.gl.texture.TextureType;
import net.coderbot.iris.helpers.Tri;
import net.coderbot.iris.pipeline.transform.Patch;
import net.coderbot.iris.shaderpack.texture.TextureStage;
public class ComputeParameters extends TextureStageParameters {
// WARNING: adding new fields requires updating hashCode and equals methods!
public ComputeParameters(Patch patch, TextureStage stage, Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> textureMap) {
super(patch, stage, textureMap);
}
@Override
public AlphaTest getAlphaTest() {
return AlphaTest.ALWAYS;
}
// since this class has no fields, hashCode() and equals() are inherited from
// TextureStageParameters
}
@@ -1,20 +0,0 @@
package net.coderbot.iris.pipeline.transform.parameter;
public interface JobParameters {
JobParameters EMPTY = new JobParameters() {
@Override
public boolean equals(Object other) {
return other == this;
}
@Override
public int hashCode() {
return 0;
}
};
boolean equals(Object other);
int hashCode();
}
@@ -1,37 +1,59 @@
package net.coderbot.iris.pipeline.transform.parameter;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import net.coderbot.iris.gl.blending.AlphaTest;
import net.coderbot.iris.gl.shader.ShaderType;
import net.coderbot.iris.gl.texture.TextureType;
import net.coderbot.iris.helpers.Tri;
import net.coderbot.iris.pipeline.transform.Patch;
import net.coderbot.iris.pipeline.transform.PatchShaderType;
import net.coderbot.iris.shaderpack.texture.TextureStage;
public class Parameters implements JobParameters {
public final Patch patch;
public PatchShaderType type;
// WARNING: adding new fields requires updating hashCode and equals methods!
public abstract class Parameters {
public final Patch patch;
private final Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> textureMap;
public ShaderType type;
// WARNING: adding new fields requires updating hashCode and equals methods!
// name of the shader, this should not be part of hash/equals
public String name; // set by TransformPatcher
public Parameters(Patch patch, Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> textureMap) {
this.patch = patch;
this.textureMap = textureMap;
}
public Parameters(Patch patch) {
this.patch = patch;
}
public AlphaTest getAlphaTest() {
return AlphaTest.ALWAYS;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((patch == null) ? 0 : patch.hashCode());
return result;
}
public abstract TextureStage getTextureStage();
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Parameters other = (Parameters) obj;
return patch == other.patch;
}
public Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> getTextureMap() {
return textureMap;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((patch == null) ? 0 : patch.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
result = prime * result + ((textureMap == null) ? 0 : textureMap.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Parameters other = (Parameters) obj;
if (patch != other.patch)
return false;
if (type != other.type)
return false;
if (textureMap == null) {
return other.textureMap == null;
} else return textureMap.equals(other.textureMap);
}
}
@@ -0,0 +1,48 @@
package net.coderbot.iris.pipeline.transform.parameter;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import net.coderbot.iris.gl.blending.AlphaTest;
import net.coderbot.iris.gl.texture.TextureType;
import net.coderbot.iris.helpers.Tri;
import net.coderbot.iris.pipeline.transform.Patch;
import net.coderbot.iris.shaderpack.texture.TextureStage;
public class TextureStageParameters extends Parameters {
private final TextureStage stage;
// WARNING: adding new fields requires updating hashCode and equals methods!
public TextureStageParameters(Patch patch, TextureStage stage, Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> textureMap) {
super(patch, textureMap);
this.stage = stage;
}
@Override
public TextureStage getTextureStage() {
return stage;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((stage == null) ? 0 : stage.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
TextureStageParameters other = (TextureStageParameters) obj;
return stage == other.stage;
}
@Override
public AlphaTest getAlphaTest() {
return AlphaTest.ALWAYS;
}
}
@@ -82,7 +82,7 @@ public class CenterDepthSampler {
this.framebuffer.bind();
this.program.use();
GL11.glViewport(0, 0, 1, 1);
GLStateManager.glViewport(0, 0, 1, 1);
FullScreenQuadRenderer.INSTANCE.render();
@@ -7,6 +7,7 @@ import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import lombok.Getter;
import net.coderbot.iris.features.FeatureFlags;
import net.coderbot.iris.gl.framebuffer.GlFramebuffer;
import net.coderbot.iris.gl.framebuffer.ViewportData;
import net.coderbot.iris.gl.image.GlImage;
@@ -29,7 +30,9 @@ import net.coderbot.iris.shaderpack.ComputeSource;
import net.coderbot.iris.shaderpack.PackDirectives;
import net.coderbot.iris.shaderpack.ProgramDirectives;
import net.coderbot.iris.shaderpack.ProgramSource;
import net.coderbot.iris.shaderpack.texture.TextureStage;
import net.coderbot.iris.shadows.ShadowRenderTargets;
import net.coderbot.iris.gl.state.FogMode;
import net.coderbot.iris.uniforms.CommonUniforms;
import net.coderbot.iris.uniforms.FrameUpdateNotifier;
import net.coderbot.iris.uniforms.custom.CustomUniforms;
@@ -41,6 +44,7 @@ import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
import org.lwjgl.opengl.GL42;
import java.util.Map;
import java.util.Objects;
@@ -61,6 +65,7 @@ public class CompositeRenderer {
@Nullable private final Set<GlImage> customImages;
@Nullable private final Object2ObjectMap<String, TextureAccess> irisCustomTextures;
@Nullable private final WorldRenderingPipeline pipeline;
private final TextureStage textureStage;
@Getter
private final ImmutableSet<Integer> flippedAtLeastOnceFinal;
@@ -71,10 +76,10 @@ public class CompositeRenderer {
Object2ObjectMap<String, TextureAccess> customTextureIds, ImmutableMap<Integer, Boolean> explicitPreFlips,
CustomUniforms customUniforms,
Map<Integer, CompletableFuture<Map<PatchShaderType, String>>> precomputedTransformFutures) {
this(sources, computes, bufferFlipper, new ProgramBuildContext(renderTargets, noiseTexture, updateNotifier, centerDepthSampler, shadowTargetsSupplier, customTextureIds, customUniforms, null, null, null), explicitPreFlips, precomputedTransformFutures, "unknown");
this(sources, computes, bufferFlipper, new ProgramBuildContext(renderTargets, noiseTexture, updateNotifier, centerDepthSampler, shadowTargetsSupplier, customTextureIds, customUniforms, null, null, null), explicitPreFlips, precomputedTransformFutures, "unknown", TextureStage.COMPOSITE_AND_FINAL);
}
public CompositeRenderer(ProgramSource[] sources, ComputeSource[][] computes, BufferFlipper bufferFlipper, ProgramBuildContext context, ImmutableMap<Integer, Boolean> explicitPreFlips, Map<Integer, CompletableFuture<Map<PatchShaderType, String>>> precomputedTransformFutures, String stageName) {
public CompositeRenderer(ProgramSource[] sources, ComputeSource[][] computes, BufferFlipper bufferFlipper, ProgramBuildContext context, ImmutableMap<Integer, Boolean> explicitPreFlips, Map<Integer, CompletableFuture<Map<PatchShaderType, String>>> precomputedTransformFutures, String stageName, TextureStage textureStage) {
this.noiseTexture = context.noiseTexture();
this.updateNotifier = context.updateNotifier();
this.centerDepthSampler = context.centerDepthSampler();
@@ -84,6 +89,7 @@ public class CompositeRenderer {
this.customImages = context.customImages();
this.irisCustomTextures = context.irisCustomTextures();
this.pipeline = context.pipeline();
this.textureStage = textureStage;
final ImmutableList.Builder<Pass> passes = ImmutableList.builder();
final ImmutableSet.Builder<Integer> flippedAtLeastOnce = new ImmutableSet.Builder<>();
@@ -167,7 +173,7 @@ public class CompositeRenderer {
OpenGlHelper.func_153171_g/*glBindFramebuffer*/(GL30.GL_READ_FRAMEBUFFER, 0);
}
private static Map<PatchShaderType, String> getTransformed(ProgramSource source, Map<Integer, CompletableFuture<Map<PatchShaderType, String>>> transformFutures, int index, String stageName) {
private Map<PatchShaderType, String> getTransformed(ProgramSource source, Map<Integer, CompletableFuture<Map<PatchShaderType, String>>> transformFutures, int index, String stageName) {
if (transformFutures != null) {
final CompletableFuture<Map<PatchShaderType, String>> future = transformFutures.get(index);
if (future != null) {
@@ -183,7 +189,7 @@ public class CompositeRenderer {
}
// Fallback: transform synchronously
return TransformPatcher.patchComposite(source.getVertexSource().orElseThrow(NullPointerException::new), source.getGeometrySource().orElse(null), source.getFragmentSource().orElseThrow(NullPointerException::new));
return TransformPatcher.patchComposite(source.getVertexSource().orElseThrow(NullPointerException::new), source.getGeometrySource().orElse(null), source.getTessControlSource().orElse(null), source.getTessEvalSource().orElse(null), source.getFragmentSource().orElseThrow(NullPointerException::new), this.textureStage, pipeline != null ? pipeline.getTextureMap() : null);
}
public void recalculateSizes() {
@@ -258,7 +264,7 @@ public class CompositeRenderer {
}
if (ranCompute) {
RenderSystem.memoryBarrier(40);
RenderSystem.memoryBarrier(GL42.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL42.GL_TEXTURE_FETCH_BARRIER_BIT);
}
Program.unbind();
@@ -279,7 +285,7 @@ public class CompositeRenderer {
final float scaledHeight = renderPass.viewHeight * renderPass.viewportScale.scale();
final float viewportX = renderPass.viewWidth * renderPass.viewportScale.viewportX();
final float viewportY = renderPass.viewHeight * renderPass.viewportScale.viewportY();
GL11.glViewport((int) viewportX, (int) viewportY, (int) scaledWidth, (int) scaledHeight);
GLStateManager.glViewport((int) viewportX, (int) viewportY, (int) scaledWidth, (int) scaledHeight);
renderPass.framebuffer.bind();
renderPass.program.use();
@@ -339,21 +345,23 @@ public class CompositeRenderer {
Supplier<ShadowRenderTargets> shadowTargetsSupplier) {
String vertex = transformed.get(PatchShaderType.VERTEX);
String geometry = transformed.get(PatchShaderType.GEOMETRY);
String tessControl = transformed.get(PatchShaderType.TESS_CONTROL);
String tessEval = transformed.get(PatchShaderType.TESS_EVAL);
String fragment = transformed.get(PatchShaderType.FRAGMENT);
PatchedShaderPrinter.debugPatchedShaders(source.getName(), vertex, geometry, fragment);
PatchedShaderPrinter.debugPatchedShaders(source.getName(), vertex, geometry, tessControl, tessEval, fragment);
Objects.requireNonNull(flipped);
ProgramBuilder builder;
try {
builder = ProgramBuilder.begin(source.getName(), vertex, geometry, fragment,
builder = ProgramBuilder.begin(source.getName(), vertex, geometry, tessControl, tessEval, fragment,
IrisSamplers.COMPOSITE_RESERVED_TEXTURE_UNITS);
} catch (RuntimeException e) {
// TODO: Better error handling
throw new RuntimeException("Shader compilation failed!", e);
}
CommonUniforms.addDynamicUniforms(builder);
CommonUniforms.addDynamicUniforms(builder, FogMode.OFF);
this.customUniforms.assignTo(builder);
ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureIds, flippedAtLeastOnceSnapshot);
@@ -369,7 +377,7 @@ public class CompositeRenderer {
IrisSamplers.addCompositeSamplers(customTextureSamplerInterceptor, renderTargets);
if (IrisSamplers.hasShadowSamplers(customTextureSamplerInterceptor)) {
IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowTargetsSupplier.get(), null, false);
IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowTargetsSupplier.get(), null, pipeline != null && pipeline.hasFeature(FeatureFlags.SEPARATE_HARDWARE_SAMPLERS));
IrisImages.addShadowColorImages(builder, shadowTargetsSupplier.get(), null);
}
@@ -395,7 +403,9 @@ public class CompositeRenderer {
ProgramBuilder builder;
try {
builder = ProgramBuilder.beginCompute(source.getName(), source.getSource().orElse(null), IrisSamplers.COMPOSITE_RESERVED_TEXTURE_UNITS);
String transformed = TransformPatcher.patchCompute(source.getName(), source.getSource().orElse(null), this.textureStage, pipeline != null ? pipeline.getTextureMap() : null);
PatchedShaderPrinter.debugPatchedShaders(source.getName() + "_compute", null, null, null, transformed);
builder = ProgramBuilder.beginCompute(source.getName(), transformed, IrisSamplers.COMPOSITE_RESERVED_TEXTURE_UNITS);
} catch (RuntimeException e) {
// TODO: Better error handling
throw new RuntimeException("Shader compilation failed!", e);
@@ -403,7 +413,7 @@ public class CompositeRenderer {
ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureIds, flippedAtLeastOnceSnapshot);
CommonUniforms.addDynamicUniforms(builder);
CommonUniforms.addDynamicUniforms(builder, FogMode.OFF);
this.customUniforms.assignTo(builder);
@@ -418,7 +428,7 @@ public class CompositeRenderer {
IrisSamplers.addCompositeSamplers(customTextureSamplerInterceptor, renderTargets);
if (IrisSamplers.hasShadowSamplers(customTextureSamplerInterceptor)) {
IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowTargetsSupplier.get(), null, false);
IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowTargetsSupplier.get(), null, pipeline != null && pipeline.hasFeature(FeatureFlags.SEPARATE_HARDWARE_SAMPLERS));
IrisImages.addShadowColorImages(builder, shadowTargetsSupplier.get(), null);
}
@@ -6,6 +6,7 @@ import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import it.unimi.dsi.fastutil.ints.IntList;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import net.coderbot.iris.features.FeatureFlags;
import net.coderbot.iris.gl.framebuffer.GlFramebuffer;
import net.coderbot.iris.gl.image.GlImage;
import net.coderbot.iris.gl.program.ComputeProgram;
@@ -28,7 +29,9 @@ import net.coderbot.iris.shaderpack.ComputeSource;
import net.coderbot.iris.shaderpack.ProgramDirectives;
import net.coderbot.iris.shaderpack.ProgramSet;
import net.coderbot.iris.shaderpack.ProgramSource;
import net.coderbot.iris.shaderpack.texture.TextureStage;
import net.coderbot.iris.shadows.ShadowRenderTargets;
import net.coderbot.iris.gl.state.FogMode;
import net.coderbot.iris.uniforms.CommonUniforms;
import net.coderbot.iris.uniforms.FrameUpdateNotifier;
import net.coderbot.iris.uniforms.custom.CustomUniforms;
@@ -40,6 +43,7 @@ import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
import org.lwjgl.opengl.GL42;
import java.util.Map;
import java.util.Objects;
@@ -155,7 +159,7 @@ public class FinalPassRenderer {
throw new RuntimeException("Shader transformation failed for '" + source.getName() + "' in stage '" + stageName + "'", e.getCause() != null ? e.getCause() : e);
}
}
return TransformPatcher.patchComposite(source.getVertexSource().orElseThrow(NullPointerException::new), source.getGeometrySource().orElse(null), source.getFragmentSource().orElseThrow(NullPointerException::new));
return TransformPatcher.patchComposite(source.getVertexSource().orElseThrow(NullPointerException::new), source.getGeometrySource().orElse(null), source.getTessControlSource().orElse(null), source.getTessEvalSource().orElse(null), source.getFragmentSource().orElseThrow(NullPointerException::new));
}
private static final class Pass {
@@ -220,7 +224,7 @@ public class FinalPassRenderer {
}
}
RenderSystem.memoryBarrier(40);
RenderSystem.memoryBarrier(GL42.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL42.GL_TEXTURE_FETCH_BARRIER_BIT);
if (!finalPass.mipmappedBuffers.isEmpty()) {
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
@@ -349,14 +353,16 @@ public class FinalPassRenderer {
Supplier<ShadowRenderTargets> shadowTargetsSupplier) {
final String vertex = transformed.get(PatchShaderType.VERTEX);
final String geometry = transformed.get(PatchShaderType.GEOMETRY);
final String tessControl = transformed.get(PatchShaderType.TESS_CONTROL);
final String tessEval = transformed.get(PatchShaderType.TESS_EVAL);
final String fragment = transformed.get(PatchShaderType.FRAGMENT);
PatchedShaderPrinter.debugPatchedShaders(source.getName(), vertex, geometry, fragment);
PatchedShaderPrinter.debugPatchedShaders(source.getName(), vertex, geometry, tessControl, tessEval, fragment);
Objects.requireNonNull(flipped);
final ProgramBuilder builder;
try {
builder = ProgramBuilder.begin(source.getName(), vertex, geometry, fragment,
builder = ProgramBuilder.begin(source.getName(), vertex, geometry, tessControl, tessEval, fragment,
IrisSamplers.COMPOSITE_RESERVED_TEXTURE_UNITS);
} catch (RuntimeException e) {
// TODO: Better error handling
@@ -367,7 +373,7 @@ public class FinalPassRenderer {
final ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureIds, flippedAtLeastOnceSnapshot);
CommonUniforms.addDynamicUniforms(builder);
CommonUniforms.addDynamicUniforms(builder, FogMode.OFF);
IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> flipped, renderTargets, true, pipeline);
// Bind custom images as samplers BEFORE render target images
IrisSamplers.addCustomImages(customTextureSamplerInterceptor, customImages);
@@ -382,7 +388,7 @@ public class FinalPassRenderer {
IrisSamplers.addCompositeSamplers(customTextureSamplerInterceptor, renderTargets);
if (IrisSamplers.hasShadowSamplers(customTextureSamplerInterceptor)) {
IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowTargetsSupplier.get(), null, false);
IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowTargetsSupplier.get(), null, pipeline != null && pipeline.hasFeature(FeatureFlags.SEPARATE_HARDWARE_SAMPLERS));
IrisImages.addShadowColorImages(builder, shadowTargetsSupplier.get(), null);
}
@@ -408,7 +414,9 @@ public class FinalPassRenderer {
final ProgramBuilder builder;
try {
builder = ProgramBuilder.beginCompute(source.getName(), source.getSource().orElse(null), IrisSamplers.COMPOSITE_RESERVED_TEXTURE_UNITS);
String transformed = TransformPatcher.patchCompute(source.getName(), source.getSource().orElse(null), TextureStage.COMPOSITE_AND_FINAL, pipeline != null ? pipeline.getTextureMap() : null);
PatchedShaderPrinter.debugPatchedShaders(source.getName() + "_compute", null, null, null, transformed);
builder = ProgramBuilder.beginCompute(source.getName(), transformed, IrisSamplers.COMPOSITE_RESERVED_TEXTURE_UNITS);
} catch (RuntimeException e) {
// TODO: Better error handling
throw new RuntimeException("Shader compilation failed!", e);
@@ -418,7 +426,7 @@ public class FinalPassRenderer {
customUniforms.assignTo(builder);
CommonUniforms.addDynamicUniforms(builder);
CommonUniforms.addDynamicUniforms(builder, FogMode.OFF);
IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> flipped, renderTargets, true, pipeline);
IrisSamplers.addCustomImages(customTextureSamplerInterceptor, customImages);
IrisSamplers.addCustomTextures(customTextureSamplerInterceptor, irisCustomTextures);
@@ -430,7 +438,7 @@ public class FinalPassRenderer {
IrisSamplers.addCompositeSamplers(customTextureSamplerInterceptor, renderTargets);
if (IrisSamplers.hasShadowSamplers(customTextureSamplerInterceptor)) {
IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowTargetsSupplier.get(), null, false);
IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowTargetsSupplier.get(), null, pipeline != null && pipeline.hasFeature(FeatureFlags.SEPARATE_HARDWARE_SAMPLERS));
IrisImages.addShadowColorImages(builder, shadowTargetsSupplier.get(), null);
}
@@ -4,6 +4,7 @@ import com.google.common.collect.ImmutableSet;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import lombok.Getter;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gl.framebuffer.GlFramebuffer;
import net.coderbot.iris.gl.texture.DepthBufferFormat;
import net.coderbot.iris.gl.texture.DepthCopyStrategy;
@@ -46,9 +47,15 @@ public class RenderTargets {
renderTargets.forEach((index, settings) -> {
// TODO: Handle mipmapping?
Vector2i dimensions = packDirectives.getTextureScaleOverride(index, width, height);
// Apply format fallback for opengl versions with limited color-renderable format support (e.g., macOS GL 2.1)
var requestedFormat = settings.getInternalFormat();
var actualFormat = requestedFormat.getColorRenderableFallback();
if (actualFormat != requestedFormat) {
Iris.logger.info("Render target {} using fallback format {} (requested {})", index, actualFormat, requestedFormat);
}
targets[index] = RenderTarget.builder().setDimensions(dimensions.x, dimensions.y)
.setInternalFormat(settings.getInternalFormat())
.setPixelFormat(settings.getInternalFormat().getPixelFormat()).build();
.setInternalFormat(actualFormat)
.setPixelFormat(actualFormat.getPixelFormat()).build();
});
this.currentDepthTexture = depthTexture;
this.currentDepthFormat = depthFormat;
@@ -106,7 +106,7 @@ public class IrisSamplers {
final ImmutableList.Builder<String> shadowSamplers = ImmutableList.<String>builder()
.add("shadowtex0", "shadowtex0HW", "shadowtex0DH", "shadowtex1", "shadowtex1HW", "shadowtex1DH", "shadow", "watershadow", "shadowcolor");
for (int i = 0; i < PackShadowDirectives.MAX_SHADOW_COLOR_BUFFERS; i++) {
for (int i = 0; i < PackShadowDirectives.MAX_SHADOW_COLOR_BUFFERS_IRIS; i++) {
shadowSamplers.add("shadowcolor" + i);
shadowSamplers.add("shadowcolorimg" + i);
}
@@ -33,6 +33,10 @@ public class PackDirectives {
private boolean vignette;
private boolean sun;
private boolean moon;
private boolean stars;
private boolean sky;
private boolean weather;
private boolean weatherParticles;
private boolean rainDepth;
private boolean separateAo;
private boolean voxelizeLightBlocks;
@@ -76,6 +80,10 @@ public class PackDirectives {
vignette = properties.getVignette().orElse(false);
sun = properties.getSun().orElse(true);
moon = properties.getMoon().orElse(true);
stars = properties.getStars().orElse(true);
sky = properties.getSky().orElse(true);
weather = properties.getWeather().orElse(true);
weatherParticles = properties.getWeatherParticles().orElse(true);
rainDepth = properties.getRainDepth().orElse(false);
separateAo = properties.getSeparateAo().orElse(false);
voxelizeLightBlocks = properties.getVoxelizeLightBlocks().orElse(false);
@@ -129,6 +137,22 @@ public class PackDirectives {
return moon;
}
public boolean shouldRenderStars() {
return stars;
}
public boolean shouldRenderSkyDisc() {
return sky;
}
public boolean shouldRenderWeather() {
return weather;
}
public boolean shouldRenderWeatherParticles() {
return weatherParticles;
}
public boolean rainDepth() {
return rainDepth;
}
@@ -9,10 +9,8 @@ import org.joml.Vector4f;
import java.util.Optional;
public class PackShadowDirectives {
// Bump this up if you want more shadow color buffers!
// This is currently set at 2 for ShadersMod / OptiFine parity but can theoretically be bumped up to 8.
// TODO: Make this configurable?
public static final int MAX_SHADOW_COLOR_BUFFERS = 2;
public static final int MAX_SHADOW_COLOR_BUFFERS_IRIS = 8;
public static final int MAX_SHADOW_COLOR_BUFFERS_OF = 2;
private final OptionalBoolean shadowEnabled;
@@ -20,6 +18,7 @@ public class PackShadowDirectives {
// Use a boxed form so we can use null to indicate that there is not an FOV specified.
private Float fov;
private float distance;
private float voxelDistance;
private float distanceRenderMul;
private float entityShadowDistanceMul;
private boolean explicitRenderDistance;
@@ -54,6 +53,7 @@ public class PackShadowDirectives {
// shadowRenderDistanceMul to a nonzero value, since having a high shadow render distance will impact
// performance quite heavily on most systems.
this.distance = 160.0f;
this.voxelDistance = 0.0f;
// By default, shadows are not culled based on distance from the player. However, pack authors may
// enable this by setting shadowRenderDistanceMul to a nonzero value.
@@ -86,7 +86,7 @@ public class PackShadowDirectives {
ImmutableList.Builder<SamplingSettings> colorSamplingSettings = ImmutableList.builder();
for (int i = 0; i < MAX_SHADOW_COLOR_BUFFERS; i++) {
for (int i = 0; i < MAX_SHADOW_COLOR_BUFFERS_IRIS; i++) {
colorSamplingSettings.add(new SamplingSettings());
}
@@ -97,6 +97,7 @@ public class PackShadowDirectives {
this.resolution = shadowDirectives.resolution;
this.fov = shadowDirectives.fov;
this.distance = shadowDirectives.distance;
this.voxelDistance = shadowDirectives.voxelDistance;
this.distanceRenderMul = shadowDirectives.distanceRenderMul;
this.entityShadowDistanceMul = shadowDirectives.entityShadowDistanceMul;
this.explicitRenderDistance = shadowDirectives.explicitRenderDistance;
@@ -124,6 +125,10 @@ public class PackShadowDirectives {
return distance;
}
public float getVoxelDistance() {
return voxelDistance;
}
public float getDistanceRenderMul() {
return distanceRenderMul;
}
@@ -192,6 +197,8 @@ public class PackShadowDirectives {
directives.acceptConstFloatDirective("shadowIntervalSize",
intervalSize -> this.intervalSize = intervalSize);
directives.acceptConstFloatDirective("voxelDistance", distance -> this.voxelDistance = distance);
acceptHardwareFilteringSettings(directives, depthSamplingSettings);
acceptDepthMipmapSettings(directives, depthSamplingSettings);
acceptColorMipmapSettings(directives, colorSamplingSettings);
@@ -21,6 +21,7 @@ public class ProgramDirectives {
private static final ImmutableList<String> LEGACY_RENDER_TARGETS = PackRenderTargetDirectives.LEGACY_RENDER_TARGETS;
private final int[] drawBuffers;
private boolean unknownDrawBuffers;
private final ViewportData viewportScale;
@Nullable
private final AlphaTestOverride alphaTestOverride;
@@ -40,6 +41,7 @@ public class ProgramDirectives {
this.bufferBlendInformations = bufferBlendInformations;
this.mipmappedBuffers = mipmappedBuffers;
this.explicitFlips = explicitFlips;
this.unknownDrawBuffers = false;
}
ProgramDirectives(ProgramSource source, ShaderProperties properties, Set<Integer> supportedRenderTargets, @Nullable BlendModeOverride defaultBlendOverride) {
@@ -53,7 +55,7 @@ public class ProgramDirectives {
final Optional<CommentDirective> optionalDrawbuffersDirective = findDrawbuffersDirective(source.getFragmentSource());
final Optional<CommentDirective> optionalRendertargetsDirective = findRendertargetsDirective(source.getFragmentSource());
final Optional<CommentDirective> optionalCommentDirective = getAppliedDirective(optionalDrawbuffersDirective, optionalRendertargetsDirective);
Optional<CommentDirective> optionalCommentDirective = getAppliedDirective(optionalDrawbuffersDirective, optionalRendertargetsDirective);
drawBuffers = optionalCommentDirective.map(commentDirective -> {
if (commentDirective.getType() == CommentDirective.Type.DRAWBUFFERS) {
return parseDigits(commentDirective.getDirective().toCharArray());
@@ -62,7 +64,10 @@ public class ProgramDirectives {
} else {
throw new IllegalStateException("Unhandled comment directive type!");
}
}).orElse(new int[] { 0 });
}).orElseGet(() -> {
unknownDrawBuffers = true;
return new int[]{0};
});
if (properties != null) {
viewportScale = properties.getViewportScaleOverrides().getOrDefault(source.getName(), ViewportData.defaultValue());
@@ -160,6 +165,10 @@ public class ProgramDirectives {
return drawBuffers;
}
public boolean hasUnknownDrawBuffers() {
return unknownDrawBuffers;
}
public ViewportData getViewportScale() {
return viewportScale;
}
@@ -20,6 +20,9 @@ public class ProgramSet {
private final ProgramSource[] shadowcomp;
private final ComputeSource[][] shadowCompCompute;
private final ComputeSource[] setup;
private final ProgramSource[] begin;
private final ComputeSource[][] beginCompute;
private final ProgramSource[] prepare;
private final ComputeSource[][] prepareCompute;
@@ -82,6 +85,14 @@ public class ProgramSet {
this.shadowCompCompute[i] = readComputeArray(directory, sourceProvider, "shadowcomp" + ((i == 0) ? "" : i));
}
this.setup = readComputeProgramArray(directory, sourceProvider, "setup");
this.begin = readProgramArray(directory, sourceProvider, "begin", shaderProperties);
this.beginCompute = new ComputeSource[begin.length][];
for (int i = 0; i < begin.length; i++) {
this.beginCompute[i] = readComputeArray(directory, sourceProvider, "begin" + ((i == 0) ? "" : i));
}
this.prepare = readProgramArray(directory, sourceProvider, "prepare", shaderProperties);
this.prepareCompute = new ComputeSource[prepare.length][];
for (int i = 0; i < prepare.length; i++) {
@@ -162,6 +173,18 @@ public class ProgramSet {
return programs;
}
private ComputeSource[] readComputeProgramArray(AbsolutePackPath directory, Function<AbsolutePackPath, String> sourceProvider, String name) {
ComputeSource[] programs = new ComputeSource[100];
for (int i = 0; i < programs.length; i++) {
String suffix = i == 0 ? "" : Integer.toString(i);
programs[i] = readComputeSource(directory, sourceProvider, name + suffix, this);
}
return programs;
}
private ComputeSource[] readComputeArray(AbsolutePackPath directory,
Function<AbsolutePackPath, String> sourceProvider, String name) {
ComputeSource[] programs = new ComputeSource[27];
@@ -187,6 +210,7 @@ public class ProgramSet {
programs.add(shadow);
programs.addAll(Arrays.asList(shadowcomp));
programs.addAll(Arrays.asList(begin));
programs.addAll(Arrays.asList(prepare));
programs.addAll (Arrays.asList(
@@ -212,6 +236,16 @@ public class ProgramSet {
computes.addAll(Arrays.asList(computeSources));
}
for (ComputeSource computeSource : setup) {
if (computeSource != null) {
computes.add(computeSource);
}
}
for (ComputeSource[] computeSources : beginCompute) {
computes.addAll(Arrays.asList(computeSources));
}
Collections.addAll(computes, finalCompute);
Collections.addAll(computes, shadowCompute);
@@ -263,6 +297,18 @@ public class ProgramSet {
return shadowcomp;
}
public ComputeSource[] getSetup() {
return setup;
}
public ProgramSource[] getBegin() {
return begin;
}
public ComputeSource[][] getBeginCompute() {
return beginCompute;
}
public ProgramSource[] getPrepare() {
return prepare;
}
@@ -431,11 +477,21 @@ public class ProgramSet {
AbsolutePackPath geometryPath = directory.resolve(program + ".gsh");
String geometrySource = sourceProvider.apply(geometryPath);
String tessControlSource = null;
String tessEvalSource = null;
if (programSet.pack.hasFeature(net.coderbot.iris.features.FeatureFlags.TESSELLATION_SHADERS)) {
AbsolutePackPath tessControlPath = directory.resolve(program + ".tcs");
tessControlSource = sourceProvider.apply(tessControlPath);
AbsolutePackPath tessEvalPath = directory.resolve(program + ".tes");
tessEvalSource = sourceProvider.apply(tessEvalPath);
}
AbsolutePackPath fragmentPath = directory.resolve(program + ".fsh");
String fragmentSource = sourceProvider.apply(fragmentPath);
return new ProgramSource(program, vertexSource, geometrySource, fragmentSource, programSet, properties,
defaultBlendModeOverride);
return new ProgramSource(program, vertexSource, geometrySource, tessControlSource, tessEvalSource,
fragmentSource, programSet, properties, defaultBlendModeOverride);
}
private static ComputeSource readComputeSource(AbsolutePackPath directory,
@@ -8,25 +8,33 @@ public class ProgramSource {
private final String name;
private final String vertexSource;
private final String geometrySource;
private final String tessControlSource;
private final String tessEvalSource;
private final String fragmentSource;
private final ProgramDirectives directives;
private final ProgramSet parent;
private ProgramSource(String name, String vertexSource, String geometrySource, String fragmentSource,
private ProgramSource(String name, String vertexSource, String geometrySource, String tessControlSource,
String tessEvalSource, String fragmentSource,
ProgramDirectives directives, ProgramSet parent) {
this.name = name;
this.vertexSource = vertexSource;
this.geometrySource = geometrySource;
this.tessControlSource = tessControlSource;
this.tessEvalSource = tessEvalSource;
this.fragmentSource = fragmentSource;
this.directives = directives;
this.parent = parent;
}
public ProgramSource(String name, String vertexSource, String geometrySource, String fragmentSource,
public ProgramSource(String name, String vertexSource, String geometrySource, String tessControlSource,
String tessEvalSource, String fragmentSource,
ProgramSet parent, ShaderProperties properties, BlendModeOverride defaultBlendModeOverride) {
this.name = name;
this.vertexSource = vertexSource;
this.geometrySource = geometrySource;
this.tessControlSource = tessControlSource;
this.tessEvalSource = tessEvalSource;
this.fragmentSource = fragmentSource;
this.parent = parent;
this.directives = new ProgramDirectives(this, properties,
@@ -34,7 +42,7 @@ public class ProgramSource {
}
public ProgramSource withDirectiveOverride(ProgramDirectives overrideDirectives) {
return new ProgramSource(name, vertexSource, geometrySource, fragmentSource, overrideDirectives, parent);
return new ProgramSource(name, vertexSource, geometrySource, tessControlSource, tessEvalSource, fragmentSource, overrideDirectives, parent);
}
public String getName() {
@@ -49,6 +57,14 @@ public class ProgramSource {
return Optional.ofNullable(geometrySource);
}
public Optional<String> getTessControlSource() {
return Optional.ofNullable(tessControlSource);
}
public Optional<String> getTessEvalSource() {
return Optional.ofNullable(tessEvalSource);
}
public Optional<String> getFragmentSource() {
return Optional.ofNullable(fragmentSource);
}
@@ -70,9 +70,11 @@ public class ShaderPack {
public final CustomUniforms.Builder customUniforms;
private final ProgramSet base;
private final Set<FeatureFlags> activeFeatures;
private final Map<String, String> dimensionMap;
private final Map<String, ProgramSet> dimensionProgramSets;
private final Set<String> foldersWithShaderFiles;
private final Function<AbsolutePackPath, String> sourceProvider;
private final ShaderProperties shaderProperties;
private boolean hasLoggedCacheLimitReached = false;
@@ -114,6 +116,7 @@ public class ShaderPack {
// Parse dimension.properties to get dimension name -> folder mappings
this.dimensionMap = new HashMap<>();
this.foldersWithShaderFiles = new HashSet<>();
Iris.logger.info("Dimension shader cache size: {} (3 vanilla pinned + {} modded), configurable via -Diris.dimensionCacheSize",
MAX_DIMENSION_CACHE, Math.max(0, MAX_DIMENSION_CACHE - PINNED_DIMENSIONS.size()));
@@ -135,7 +138,9 @@ public class ShaderPack {
if (!dimensionFolders.isEmpty()) {
for (String folderName : dimensionFolders) {
boolean folderExists = checkAndAddDimensionFolder(starts, root, potentialFileNames, folderName);
if (!folderExists) {
if (folderExists) {
foldersWithShaderFiles.add(folderName);
} else {
Iris.logger.warn("dimension.properties references folder '{}' but it doesn't exist or has no shader files", folderName);
}
}
@@ -164,6 +169,7 @@ public class ShaderPack {
boolean exists = checkAndAddDimensionFolder(starts, root, potentialFileNames, folderName);
if (exists) {
foundFolders.add(folderName);
foldersWithShaderFiles.add(folderName);
}
} catch (IOException e) {
Iris.logger.warn("Failed to scan dimension folder: {}", folderName, e);
@@ -173,8 +179,8 @@ public class ShaderPack {
Iris.logger.warn("Failed to scan for dimension folders", e);
}
// Set up default name mappings for vanilla dimensions only
// Other world{ID} folders are handled via dimension ID fallback at runtime
// Set up dimension mappings
// If world0 folder exists with shader files, use it for Overworld. Otherwise use base for all oher dims.
if (foundFolders.contains("world0")) {
dimensionMap.put("Overworld", "world0");
}
@@ -203,11 +209,35 @@ public class ShaderPack {
this.shaderPackOptions = new ShaderPackOptions(graph, changedConfigs);
graph = this.shaderPackOptions.getIncludes();
Iterable<StringPair> finalEnvironmentDefines = environmentDefines;
List<StringPair> finalEnvironmentDefines = new ArrayList<>();
environmentDefines.forEach(finalEnvironmentDefines::add);
for (FeatureFlags flag : FeatureFlags.values()) {
boolean usable = flag.isUsable();
Iris.logger.info("FeatureFlag {} usable: {}", flag.name(), usable);
if (usable) {
finalEnvironmentDefines.add(new StringPair("IRIS_FEATURE_" + flag.name(), ""));
if (flag == FeatureFlags.TESSELLATION_SHADERS) {
finalEnvironmentDefines.add(new StringPair("IRIS_FEATURE_TESSELATION_SHADERS", ""));
}
}
}
Iris.logger.info("Environment defines: {}", finalEnvironmentDefines.stream()
.map(p -> p.getKey() + "=" + p.getValue())
.collect(java.util.stream.Collectors.joining(", ")));
this.shaderProperties = Optional.ofNullable(readProperties(root, "shaders.properties"))
.map(source -> new ShaderProperties(source, shaderPackOptions, finalEnvironmentDefines))
.orElseGet(ShaderProperties::empty);
// Build the set of active feature flags from required and optional flags
this.activeFeatures = new HashSet<>();
for (String flag : shaderProperties.getRequiredFeatureFlags()) {
activeFeatures.add(FeatureFlags.getValue(flag));
}
for (String flag : shaderProperties.getOptionalFeatureFlags()) {
activeFeatures.add(FeatureFlags.getValue(flag));
}
List<FeatureFlags> invalidFlagList = shaderProperties.getRequiredFeatureFlags().stream().filter(FeatureFlags::isInvalid).map(FeatureFlags::getValue).collect(Collectors.toList());
List<String> invalidFeatureFlags = invalidFlagList.stream().map(FeatureFlags::getHumanReadableName).collect(Collectors.toList());
@@ -220,15 +250,6 @@ public class ShaderPack {
IrisApi.getInstance().getConfig().setShadersEnabledAndApply(false);
}
List<String> optionalFeatureFlags = shaderProperties.getOptionalFeatureFlags().stream().filter(flag -> !FeatureFlags.isInvalid(flag)).collect(Collectors.toList());
if (!optionalFeatureFlags.isEmpty()) {
List<StringPair> newEnvDefines = new ArrayList<>();
environmentDefines.forEach(newEnvDefines::add);
optionalFeatureFlags.forEach(flag -> newEnvDefines.add(new StringPair("IRIS_FEATURE_" + flag, "")));
environmentDefines = ImmutableList.copyOf(newEnvDefines);
}
ProfileSet profiles = ProfileSet.fromTree(shaderProperties.getProfiles(), this.shaderPackOptions.getOptionSet());
this.profile = profiles.scan(this.shaderPackOptions.getOptionSet(), this.shaderPackOptions.getOptionValues());
@@ -262,7 +283,7 @@ public class ShaderPack {
IncludeProcessor includeProcessor = new IncludeProcessor(graph);
// Set up our source provider for creating ProgramSets
Iterable<StringPair> finalEnvironmentDefines1 = environmentDefines;
Iterable<StringPair> finalEnvironmentDefines1 = finalEnvironmentDefines;
this.sourceProvider = (path) -> {
String pathString = path.getPathString();
// Removes the first "/" in the path if present, and the file
@@ -294,6 +315,10 @@ public class ShaderPack {
// directly. This removes one obstacle to accurate reporting of line numbers for errors,
// though there exist many more (such as relocating all #extension directives and similar things)
String source = builder.toString();
// Apply shader pack workarounds for version compatibility (before preprocessing)
source = ShaderPackWorkarounds.apply(source);
source = JcppProcessor.glslPreprocessSource(source, finalEnvironmentDefines1);
return source;
@@ -574,15 +599,24 @@ public class ShaderPack {
* The LinkedHashMap maintains access order, so oldest entries are at the front.
*/
private void evictOldDimensions() {
// If cache is disabled, evict everything except pinned
// Build set of pinned folders (folders that vanilla dimensions map to)
Set<String> pinnedFolders = new HashSet<>();
for (String pinnedDimName : PINNED_DIMENSIONS) {
String folder = dimensionMap.get(pinnedDimName);
if (folder != null) {
pinnedFolders.add(folder);
}
}
// If cache is disabled, evict everything except pinned folders
if (MAX_DIMENSION_CACHE == 0) {
dimensionProgramSets.entrySet().removeIf(e -> !PINNED_DIMENSIONS.contains(e.getKey()));
dimensionProgramSets.entrySet().removeIf(e -> !pinnedFolders.contains(e.getKey()));
return;
}
// Count non-pinned entries
long nonPinnedCount = dimensionProgramSets.entrySet().stream()
.filter(e -> !PINNED_DIMENSIONS.contains(e.getKey()))
.filter(e -> !pinnedFolders.contains(e.getKey()))
.count();
int maxNonPinned = Math.max(0, MAX_DIMENSION_CACHE - PINNED_DIMENSIONS.size());
@@ -599,7 +633,7 @@ public class ShaderPack {
// Find the first (oldest/least recently used) non-pinned entry
String toEvict = null;
for (Map.Entry<String, ProgramSet> entry : dimensionProgramSets.entrySet()) {
if (!PINNED_DIMENSIONS.contains(entry.getKey())) {
if (!pinnedFolders.contains(entry.getKey())) {
toEvict = entry.getKey();
break;
}
@@ -645,16 +679,20 @@ public class ShaderPack {
}
// If still no match, try world{ID} folder as fallback for backward compatibility
// But only if that folder actually has shader files!
if (folderName == null) {
folderName = "world" + dimensionId;
String worldFolder = "world" + dimensionId;
if (foldersWithShaderFiles.contains(worldFolder)) {
folderName = worldFolder;
}
}
// If we have a folder name, try to get or create its ProgramSet
if (folderName != null) {
// If we have a folder name that contains shader files, try to get or create its ProgramSet
if (folderName != null && foldersWithShaderFiles.contains(folderName)) {
ProgramSet programSet = dimensionProgramSets.get(folderName);
if (programSet == null) {
// Create ProgramSet on-demand for any dimension folder
// Create ProgramSet on-demand for dimension folder
try {
programSet = new ProgramSet(
AbsolutePackPath.fromAbsolutePath("/" + folderName),
@@ -662,23 +700,14 @@ public class ShaderPack {
shaderProperties,
this
);
} catch (Exception e) {
// If the folder doesn't exist, just fall back to base silently.
// Expected since I don't think literally anyone has ever done custom dimension shaders
String message = e.getMessage();
if (message != null && (message.contains("does not contain") || message.contains("No sources found"))) {
Iris.logger.debug("Dimension folder '" + folderName + "' not found, using base shaders");
} else {
Iris.logger.error("Failed to create ProgramSet for dimension folder '{}', falling back to base", folderName, e);
}
programSet = null;
}
if (programSet != null) {
dimensionProgramSets.put(folderName, programSet);
// Check cache size limit and evict LRU dimensions if needed
// Check cache size limit and evict LRU dimensions if needed
evictOldDimensions();
} catch (Exception e) {
// This shouldn't happen but just in case.
Iris.logger.error("Failed to create ProgramSet for dimension folder '{}', falling back to base", folderName, e);
programSet = null;
}
}
@@ -710,4 +739,11 @@ public class ShaderPack {
return Optional.ofNullable(customNoiseTexture);
}
public Set<FeatureFlags> getActiveFeatures() {
return activeFeatures;
}
public boolean hasFeature(FeatureFlags feature) {
return activeFeatures.contains(feature);
}
}
@@ -0,0 +1,37 @@
package net.coderbot.iris.shaderpack;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import java.util.List;
/**
* Shader pack workarounds for specific GLSL versions. These are applied before preprocessing.
*/
public class ShaderPackWorkarounds {
private record Workaround(int maxVersion, String find, String replace) {
boolean appliesTo(int glslVersion) {
return glslVersion <= maxVersion;
}
}
private static final List<Workaround> WORKAROUNDS = List.of(
// Complementary: Catmull-Rom TAA filter causes "creeping black fog" on OGL 2.1
new Workaround(120,
"#define TAA_MOVEMENT_IMPROVEMENT_FILTER",
"// #define TAA_MOVEMENT_IMPROVEMENT_FILTER // disabled: OGL 2.1 workaround"
)
);
public static String apply(String source) {
int glslVersion = RenderSystem.getMaxGlslVersion();
for (Workaround w : WORKAROUNDS) {
if (w.appliesTo(glslVersion)) {
source = source.replace(w.find, w.replace);
}
}
return source;
}
}
@@ -73,6 +73,10 @@ public class ShaderProperties {
@Getter private OptionalBoolean underwaterOverlay = OptionalBoolean.DEFAULT;
@Getter private OptionalBoolean sun = OptionalBoolean.DEFAULT;
@Getter private OptionalBoolean moon = OptionalBoolean.DEFAULT;
@Getter private OptionalBoolean stars = OptionalBoolean.DEFAULT;
@Getter private OptionalBoolean sky = OptionalBoolean.DEFAULT;
@Getter private OptionalBoolean weather = OptionalBoolean.DEFAULT;
@Getter private OptionalBoolean weatherParticles = OptionalBoolean.DEFAULT;
@Getter private OptionalBoolean vignette = OptionalBoolean.DEFAULT;
@Getter private OptionalBoolean backFaceSolid = OptionalBoolean.DEFAULT;
@Getter private OptionalBoolean backFaceCutout = OptionalBoolean.DEFAULT;
@@ -184,8 +188,8 @@ public class ShaderProperties {
shadowCulling = ShadowCullState.DISTANCE;
} else if ("true".equals(value)) {
shadowCulling = ShadowCullState.ADVANCED;
} else if ("reversed".equals(value)) {
shadowCulling = ShadowCullState.REVERSED;
} else if ("reversed".equals(value) || "safe_zone".equals(value)) {
shadowCulling = ShadowCullState.SAFE_ZONE;
} else {
Iris.logger.error("Unrecognized shadow culling setting: " + value);
}
@@ -203,6 +207,8 @@ public class ShaderProperties {
handleBooleanDirective(key, value, "underwaterOverlay", bool -> underwaterOverlay = bool);
handleBooleanDirective(key, value, "sun", bool -> sun = bool);
handleBooleanDirective(key, value, "moon", bool -> moon = bool);
handleBooleanDirective(key, value, "stars", bool -> stars = bool);
handleBooleanDirective(key, value, "sky", bool -> sky = bool);
handleBooleanDirective(key, value, "vignette", bool -> vignette = bool);
handleBooleanDirective(key, value, "backFace.solid", bool -> backFaceSolid = bool);
handleBooleanDirective(key, value, "backFace.cutout", bool -> backFaceCutout = bool);
@@ -227,6 +233,14 @@ public class ShaderProperties {
handleBooleanDirective(key, value, "supportsColorCorrection", bool -> supportsColorCorrection = bool);
handleIntDirective(key, value, "fallbackTex", val -> fallbackTex = val);
if ("weather".equals(key)) {
String[] parts = value.split(" ");
weather = parts[0].equals("true") ? OptionalBoolean.TRUE : OptionalBoolean.FALSE;
if (parts.length > 1) {
weatherParticles = parts[1].equals("true") ? OptionalBoolean.TRUE : OptionalBoolean.FALSE;
}
}
if (key.startsWith("particles.ordering")) {
Optional<ParticleRenderingSettings> settings = ParticleRenderingSettings.fromString(value.trim().toUpperCase(Locale.ROOT));
if (settings.isPresent()) {
@@ -307,7 +321,8 @@ public class ShaderProperties {
if (pass.contains(".")) {
if (!RenderSystem.supportsBufferBlending()) {
throw new RuntimeException("Buffer blending is not supported on this platform, however it was attempted to be used!");
Iris.logger.warn("Per-buffer blending directive '{}' ignored - buffer blending requires OpenGL 4.0 or GL_ARB_draw_buffers_blend", key);
return;
}
final String[] parts = pass.split("\\.");
@@ -3,6 +3,6 @@ package net.coderbot.iris.shaderpack;
public enum ShadowCullState {
DEFAULT,
ADVANCED,
REVERSED,
SAFE_ZONE,
DISTANCE
}
@@ -0,0 +1,396 @@
package net.coderbot.iris.shadows;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import net.coderbot.iris.features.FeatureFlags;
import net.coderbot.iris.gl.buffer.ShaderStorageBufferHolder;
import net.coderbot.iris.gl.framebuffer.GlFramebuffer;
import net.coderbot.iris.gl.framebuffer.ViewportData;
import net.coderbot.iris.gl.image.GlImage;
import net.coderbot.iris.gl.program.ComputeProgram;
import net.coderbot.iris.gl.program.Program;
import net.coderbot.iris.gl.program.ProgramBuilder;
import net.coderbot.iris.gl.program.ProgramSamplers;
import net.coderbot.iris.gl.program.ProgramUniforms;
import net.coderbot.iris.gl.state.FogMode;
import net.coderbot.iris.gl.texture.TextureAccess;
import net.coderbot.iris.pipeline.PatchedShaderPrinter;
import net.coderbot.iris.pipeline.WorldRenderingPipeline;
import net.coderbot.iris.pipeline.transform.PatchShaderType;
import net.coderbot.iris.pipeline.transform.TransformPatcher;
import net.coderbot.iris.postprocess.FullScreenQuadRenderer;
import net.coderbot.iris.rendertarget.RenderTarget;
import net.coderbot.iris.samplers.IrisImages;
import net.coderbot.iris.samplers.IrisSamplers;
import net.coderbot.iris.shaderpack.ComputeSource;
import net.coderbot.iris.shaderpack.FilledIndirectPointer;
import net.coderbot.iris.shaderpack.PackDirectives;
import net.coderbot.iris.shaderpack.PackRenderTargetDirectives;
import net.coderbot.iris.shaderpack.ProgramDirectives;
import net.coderbot.iris.shaderpack.ProgramSource;
import net.coderbot.iris.shaderpack.texture.TextureStage;
import net.coderbot.iris.uniforms.CommonUniforms;
import net.coderbot.iris.uniforms.FrameUpdateNotifier;
import net.coderbot.iris.uniforms.custom.CustomUniforms;
import net.minecraft.client.Minecraft;
import net.minecraft.client.shader.Framebuffer;
import org.jetbrains.annotations.Nullable;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL30;
import org.lwjgl.opengl.GL42;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
public class ShadowCompositeRenderer {
private final ShadowRenderTargets renderTargets;
private final ImmutableList<Pass> passes;
private final TextureAccess noiseTexture;
private final FrameUpdateNotifier updateNotifier;
private final Object2ObjectMap<String, TextureAccess> customTextureIds;
private final ImmutableSet<Integer> flippedAtLeastOnceFinal;
private final CustomUniforms customUniforms;
private final Object2ObjectMap<String, TextureAccess> irisCustomTextures;
private final WorldRenderingPipeline pipeline;
private final Set<GlImage> irisCustomImages;
@Nullable
private final ShaderStorageBufferHolder ssboHolder;
public ShadowCompositeRenderer(WorldRenderingPipeline pipeline, PackDirectives packDirectives, ProgramSource[] sources, ComputeSource[][] computes,
ShadowRenderTargets renderTargets, @Nullable ShaderStorageBufferHolder ssboHolder, TextureAccess noiseTexture, FrameUpdateNotifier updateNotifier,
Object2ObjectMap<String, TextureAccess> customTextureIds, Set<GlImage> customImages, ImmutableMap<Integer, Boolean> explicitPreFlips,
Object2ObjectMap<String, TextureAccess> irisCustomTextures, CustomUniforms customUniforms) {
this.pipeline = pipeline;
this.noiseTexture = noiseTexture;
this.updateNotifier = updateNotifier;
this.renderTargets = renderTargets;
this.ssboHolder = ssboHolder;
this.customTextureIds = customTextureIds;
this.irisCustomTextures = irisCustomTextures;
this.irisCustomImages = customImages;
this.customUniforms = customUniforms;
final PackRenderTargetDirectives renderTargetDirectives = packDirectives.getRenderTargetDirectives();
final Map<Integer, PackRenderTargetDirectives.RenderTargetSettings> renderTargetSettings = renderTargetDirectives.getRenderTargetSettings();
final ImmutableList.Builder<Pass> passes = ImmutableList.builder();
final ImmutableSet.Builder<Integer> flippedAtLeastOnce = new ImmutableSet.Builder<>();
explicitPreFlips.forEach((buffer, shouldFlip) -> {
if (shouldFlip) {
renderTargets.flip(buffer);
// NB: Flipping deferred_pre or composite_pre does NOT cause the "flippedAtLeastOnce" flag to trigger
}
});
for (int i = 0, sourcesLength = sources.length; i < sourcesLength; i++) {
ProgramSource source = sources[i];
ImmutableSet<Integer> flipped = renderTargets.snapshot();
ImmutableSet<Integer> flippedAtLeastOnceSnapshot = flippedAtLeastOnce.build();
if (source == null || !source.isValid()) {
if (computes[i] != null) {
ComputeOnlyPass pass = new ComputeOnlyPass();
pass.computes = createComputes(computes[i], flipped, flippedAtLeastOnceSnapshot, renderTargets);
passes.add(pass);
}
continue;
}
Pass pass = new Pass();
ProgramDirectives directives = source.getDirectives();
pass.program = createProgram(source, flipped, flippedAtLeastOnceSnapshot, renderTargets);
pass.computes = createComputes(computes[i], flipped, flippedAtLeastOnceSnapshot, renderTargets);
int[] drawBuffers = directives.hasUnknownDrawBuffers() ? new int[] { 0, 1 } : directives.getDrawBuffers();
GlFramebuffer framebuffer = renderTargets.createColorFramebuffer(flipped, drawBuffers);
pass.stageReadsFromAlt = flipped;
pass.framebuffer = framebuffer;
pass.viewportScale = directives.getViewportScale();
pass.mipmappedBuffers = directives.getMipmappedBuffers();
pass.flippedAtLeastOnce = flippedAtLeastOnceSnapshot;
passes.add(pass);
ImmutableMap<Integer, Boolean> explicitFlips = directives.getExplicitFlips();
// Flip the buffers that this shader wrote to
for (int buffer : drawBuffers) {
// compare with boxed Boolean objects to avoid NPEs
if (explicitFlips.get(buffer) == Boolean.FALSE) {
continue;
}
renderTargets.flip(buffer);
flippedAtLeastOnce.add(buffer);
}
explicitFlips.forEach((buffer, shouldFlip) -> {
if (shouldFlip) {
renderTargets.flip(buffer);
flippedAtLeastOnce.add(buffer);
}
});
}
this.passes = passes.build();
this.flippedAtLeastOnceFinal = flippedAtLeastOnce.build();
GLStateManager.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, 0);
}
private static void setupMipmapping(RenderTarget target, boolean readFromAlt) {
if (target == null) {
return;
}
int texture = readFromAlt ? target.getAltTexture() : target.getMainTexture();
// TODO: Only generate the mipmap if a valid mipmap hasn't been generated or if we've written to the buffer
// (since the last mipmap was generated)
//
// NB: We leave mipmapping enabled even if the buffer is written to again, this appears to match the
// behavior of ShadersMod/OptiFine, however I'm not sure if it's desired behavior. It's possible that a
// program could use mipmapped sampling with a stale mipmap, which probably isn't great. However, the
// sampling mode is always reset between frames, so this only persists after the first program to use
// mipmapping on this buffer.
//
// Also note that this only applies to one of the two buffers in a render target buffer pair - making it
// unlikely that this issue occurs in practice with most shader packs.
RenderSystem.generateMipmaps(texture, GL11.GL_TEXTURE_2D);
RenderSystem.texParameteri(texture, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, target.getInternalFormat().getPixelFormat().isInteger() ? GL11.GL_NEAREST_MIPMAP_NEAREST : GL11.GL_LINEAR_MIPMAP_LINEAR);
}
private static void resetRenderTarget(RenderTarget target) {
// Resets the sampling mode of the given render target and then unbinds it to prevent accidental sampling of it
// elsewhere.
int filter = GL11.GL_LINEAR;
if (target.getInternalFormat().getPixelFormat().isInteger()) {
filter = GL11.GL_NEAREST;
}
RenderSystem.texParameteri(target.getMainTexture(), GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, filter);
RenderSystem.texParameteri(target.getAltTexture(), GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, filter);
}
public ImmutableSet<Integer> getFlippedAtLeastOnceFinal() {
return this.flippedAtLeastOnceFinal;
}
public void renderAll() {
GLStateManager.disableBlend();
FullScreenQuadRenderer.INSTANCE.begin();
for (Pass renderPass : passes) {
boolean ranCompute = false;
for (ComputeProgram computeProgram : renderPass.computes) {
if (computeProgram != null) {
ranCompute = true;
final Framebuffer main = Minecraft.getMinecraft().getFramebuffer();
computeProgram.use();
this.customUniforms.push(computeProgram);
computeProgram.dispatch(main.framebufferWidth, main.framebufferHeight);
}
}
if (ranCompute) {
// Memory barrier for shader image access and texture fetch
RenderSystem.memoryBarrier(GL42.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL42.GL_TEXTURE_FETCH_BARRIER_BIT);
}
Program.unbind();
if (renderPass instanceof ComputeOnlyPass) {
continue;
}
if (!renderPass.mipmappedBuffers.isEmpty()) {
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
for (int index : renderPass.mipmappedBuffers) {
setupMipmapping(renderTargets.get(index), renderPass.stageReadsFromAlt.contains(index));
}
}
float scaledWidth = renderTargets.getResolution() * renderPass.viewportScale.scale();
float scaledHeight = renderTargets.getResolution() * renderPass.viewportScale.scale();
int beginWidth = (int) (renderTargets.getResolution() * renderPass.viewportScale.viewportX());
int beginHeight = (int) (renderTargets.getResolution() * renderPass.viewportScale.viewportY());
GLStateManager.glViewport(beginWidth, beginHeight, (int) scaledWidth, (int) scaledHeight);
renderPass.framebuffer.bind();
renderPass.program.use();
this.customUniforms.push(renderPass.program);
FullScreenQuadRenderer.INSTANCE.renderQuad();
}
FullScreenQuadRenderer.INSTANCE.end();
ProgramUniforms.clearActiveUniforms();
ProgramSamplers.clearActiveSamplers();
for (int i = 0; i < renderTargets.getRenderTargetCount(); i++) {
// Reset mipmapping states at the end of the frame.
if (renderTargets.get(i) != null) {
resetRenderTarget(renderTargets.get(i));
}
}
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
}
// TODO: Don't just copy this from DeferredWorldRenderingPipeline
private Program createProgram(ProgramSource source, ImmutableSet<Integer> flipped, ImmutableSet<Integer> flippedAtLeastOnceSnapshot,
ShadowRenderTargets targets) {
// TODO: Properly handle empty shaders
Map<PatchShaderType, String> transformed = TransformPatcher.patchComposite(
source.getVertexSource().orElseThrow(NullPointerException::new),
source.getGeometrySource().orElse(null),
source.getTessControlSource().orElse(null),
source.getTessEvalSource().orElse(null),
source.getFragmentSource().orElseThrow(NullPointerException::new));
String vertex = transformed.get(PatchShaderType.VERTEX);
String geometry = transformed.get(PatchShaderType.GEOMETRY);
String tessControl = transformed.get(PatchShaderType.TESS_CONTROL);
String tessEval = transformed.get(PatchShaderType.TESS_EVAL);
String fragment = transformed.get(PatchShaderType.FRAGMENT);
PatchedShaderPrinter.debugPatchedShaders(source.getName(), vertex, geometry, tessControl, tessEval, fragment);
Objects.requireNonNull(flipped);
ProgramBuilder builder;
try {
builder = ProgramBuilder.begin(source.getName(), vertex, geometry, tessControl, tessEval, fragment, IrisSamplers.COMPOSITE_RESERVED_TEXTURE_UNITS);
} catch (RuntimeException e) {
// TODO: Better error handling
throw new RuntimeException("Shader compilation failed for shadow composite " + source.getName() + "!", e);
}
ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(
builder,
customTextureIds,
flippedAtLeastOnceSnapshot);
CommonUniforms.addDynamicUniforms(builder, FogMode.OFF);
this.customUniforms.assignTo(builder);
IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, noiseTexture);
IrisSamplers.addCustomTextures(customTextureSamplerInterceptor, irisCustomTextures);
IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, targets, flipped, pipeline.hasFeature(FeatureFlags.SEPARATE_HARDWARE_SAMPLERS));
IrisImages.addShadowColorImages(builder, targets, flipped);
IrisImages.addCustomImages(builder, irisCustomImages);
IrisSamplers.addCustomImages(customTextureSamplerInterceptor, irisCustomImages);
Program build = builder.build();
this.customUniforms.mapholderToPass(builder, build);
return build;
}
private ComputeProgram[] createComputes(ComputeSource[] sources, ImmutableSet<Integer> flipped, ImmutableSet<Integer> flippedAtLeastOnceSnapshot,
ShadowRenderTargets targets) {
if (sources == null) {
return new ComputeProgram[0];
}
ComputeProgram[] programs = new ComputeProgram[sources.length];
for (int i = 0; i < programs.length; i++) {
ComputeSource source = sources[i];
if (source == null || !source.getSource().isPresent()) {
continue;
} else {
Objects.requireNonNull(flipped);
ProgramBuilder builder;
try {
String transformed = TransformPatcher.patchCompute(source.getName(), source.getSource().orElse(null),
TextureStage.SHADOWCOMP, pipeline.getTextureMap());
PatchedShaderPrinter.debugPatchedShaders(source.getName() + "_compute", null, null, null, transformed);
builder = ProgramBuilder.beginCompute(source.getName(), transformed, IrisSamplers.COMPOSITE_RESERVED_TEXTURE_UNITS);
} catch (RuntimeException e) {
// TODO: Better error handling
throw new RuntimeException("Shader compilation failed for shadowcomp compute " + source.getName() + "!", e);
}
ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(
builder,
customTextureIds,
flippedAtLeastOnceSnapshot);
CommonUniforms.addDynamicUniforms(builder, FogMode.OFF);
this.customUniforms.assignTo(builder);
IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, noiseTexture);
IrisSamplers.addCustomTextures(customTextureSamplerInterceptor, irisCustomTextures);
IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, targets, flipped, pipeline.hasFeature(FeatureFlags.SEPARATE_HARDWARE_SAMPLERS));
IrisImages.addShadowColorImages(builder, targets, flipped);
IrisImages.addCustomImages(builder, irisCustomImages);
IrisSamplers.addCustomImages(customTextureSamplerInterceptor, irisCustomImages);
programs[i] = builder.buildCompute();
this.customUniforms.mapholderToPass(builder, programs[i]);
programs[i].setWorkGroupInfo(
source.getWorkGroupRelative(),
source.getWorkGroups(),
ssboHolder != null ? FilledIndirectPointer.basedOff(ssboHolder, source.getIndirectPointer()) : null);
}
}
return programs;
}
public void destroy() {
for (Pass renderPass : passes) {
renderPass.destroy();
}
}
private static class Pass {
Program program;
GlFramebuffer framebuffer;
ImmutableSet<Integer> flippedAtLeastOnce;
ImmutableSet<Integer> stageReadsFromAlt;
ImmutableSet<Integer> mipmappedBuffers;
ViewportData viewportScale;
ComputeProgram[] computes;
protected void destroy() {
this.program.destroy();
for (ComputeProgram compute : this.computes) {
if (compute != null) {
compute.destroy();
}
}
}
}
private static class ComputeOnlyPass extends Pass {
@Override
protected void destroy() {
for (ComputeProgram compute : this.computes) {
if (compute != null) {
compute.destroy();
}
}
}
}
}
Loaded 100 of 140 files, more files were not shown because too many files have changed in this diff. Show more