Compare commits

..
Author SHA1 Message Date
Jason Mitchell 21ef5905c8 Roll back some of the hacks (#1085) 2025-10-30 20:50:43 -07:00
ABKQPO 5b67eaa474 Quick fix PBR Resourcepack loader error (#1043) 2025-10-29 08:01:52 -07:00
SuperSoupr c9d59c3b90 Allow overriding of blend function in batching font renderer (#1075) 2025-10-29 07:59:27 -07:00
Death Fuel fa7ff74fec make an exception for the splash screen (#1069) 2025-10-29 07:57:41 -07:00
Kotmatross a34a3ebd39 Fix missing depth buffer writing before GUI rendering (#1073) 2025-10-29 07:56:45 -07:00
Nikita Manchuk 2e7476d287 render: set frustum position before BE culling (#1077) 2025-10-29 07:23:25 -07:00
Death Fuel 3244071012 font shader changes (#1071) 2025-10-24 14:44:32 -07:00
DarkShadow44 7035dbde02 Rework ANGELICA_VERSION into an integer (#873) 2025-10-22 01:19:15 +00:00
sisyphussy 97ae04c2fa Fix CME (#1008) 2025-10-20 14:38:30 -07:00
sisyphussy e7fa7f62d0 Fix framebuffer depth not clearing (#1051) 2025-10-20 14:36:02 -07:00
Wilhelm Schuster ea39712749 Add null check for zoom reset (#1061) 2025-10-20 14:35:29 -07:00
Death Fuel 66dd3eaa94 Custom/Smooth Font follow-up (#1040) 2025-10-20 14:35:06 -07:00
ah-OOG-ah 270697cd10 Refactor vendor detection (#1049)
* Refactor vendor detection

Only one vendor can be active at any given time, so make it an enum.

* lowercase vendor string
2025-10-13 15:48:21 -07:00
sisyphussy 2b53a851ef Fix intel build tests (#1048) 2025-10-13 10:31:48 -07:00
Jason Mitchell 34b6efde7b Maybe fix TAA (#1047) 2025-10-12 17:40:41 -07:00
Jason Mitchell 86edb721da GLSM updates (#1046) 2025-10-12 14:51:56 -07:00
Kotmatross 39c5f4bf7b Fix missing GL20 in cstPoolParser (#1042) 2025-10-09 12:26:55 -04:00
32 changed files with 819 additions and 195 deletions

No files matched your search

+1 -1
View File
@@ -15,7 +15,7 @@
# Required Dependencies
* [UniMixins](https://github.com/LegacyModdingMC/UniMixins/releases) >= 0.1.19
* [GTNHLib](https://github.com/GTNewHorizons/GTNHLib/releases) >= 0.6.20
* [GTNHLib](https://github.com/GTNewHorizons/GTNHLib/releases) >= 0.7.0
* NOTE: Some mods are not required, but a specific version is required if present - see: `Permanent Incompatibilities` below.
# Known (temporary) Incompatibilities
@@ -4,6 +4,7 @@ import com.google.common.collect.ImmutableSet;
import com.gtnewhorizons.angelica.config.FontConfig;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.mixins.interfaces.FontRendererAccessor;
import cpw.mods.fml.client.SplashProgress;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import net.coderbot.iris.gl.program.Program;
import net.coderbot.iris.gl.program.ProgramBuilder;
@@ -50,7 +51,8 @@ public class BatchingFontRenderer {
private final int texBoundAttrLocation;
private final int fontShaderId;
private final boolean isSGA;
final boolean isSGA;
final boolean isSplash;
private static class FontAAShader {
@@ -85,6 +87,8 @@ public class BatchingFontRenderer {
}
this.isSGA = Objects.equals(this.locationFontTexture.getResourcePath(), "textures/font/ascii_sga.png");
// noinspection deprecation
this.isSplash = underlying instanceof SplashProgress.SplashFontRenderer;
FontProviderMC.get(this.isSGA).charWidth = this.charWidth;
FontProviderMC.get(this.isSGA).locationFontTexture = this.locationFontTexture;
@@ -114,6 +118,9 @@ public class BatchingFontRenderer {
private final ObjectArrayList<FontDrawCmd> batchCommands = ObjectArrayList.wrap(new FontDrawCmd[64], 0);
private final ObjectArrayList<FontDrawCmd> batchCommandPool = ObjectArrayList.wrap(new FontDrawCmd[64], 0);
private int blendSrcRGB = GL11.GL_SRC_ALPHA;
private int blendDstRGB = GL11.GL_ONE_MINUS_SRC_ALPHA;
/** */
private void pushVtx(float x, float y, int rgba, float u, float v, float uMin, float uMax, float vMin, float vMax) {
final int oldCap = batchVtxPositions.capacity() / 2;
@@ -258,6 +265,7 @@ public class BatchingFontRenderer {
}
}
int lastActiveProgram;
int fontAAModeLast = -1;
int fontAAStrengthLast = -1;
private void flushBatch() {
@@ -272,13 +280,14 @@ public class BatchingFontRenderer {
GLStateManager.enableTexture();
GLStateManager.enableAlphaTest();
GLStateManager.enableBlend();
GLStateManager.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
GLStateManager.tryBlendFuncSeparate(blendSrcRGB, blendDstRGB, GL11.GL_ONE, GL11.GL_ZERO);
GLStateManager.glShadeModel(GL11.GL_FLAT);
if (FontConfig.fontAAMode != 0) {
GL20.glVertexAttribPointer(texBoundAttrLocation, 4, false, 0, batchVtxTexBounds);
GL20.glEnableVertexAttribArray(texBoundAttrLocation);
GL20.glUseProgram(fontShaderId);
lastActiveProgram = GLStateManager.getActiveProgram();
GLStateManager.glUseProgram(fontShaderId);
if (FontConfig.fontAAMode != fontAAModeLast) {
fontAAModeLast = FontConfig.fontAAMode;
GL20.glUniform1i(AAMode, FontConfig.fontAAMode);
@@ -319,7 +328,7 @@ public class BatchingFontRenderer {
GL11.glDrawElements(GL11.GL_TRIANGLES, batchIndices);
}
if (FontConfig.fontAAMode != 0) {
GL20.glUseProgram(0);
GLStateManager.glUseProgram(lastActiveProgram);
GL20.glDisableVertexAttribArray(texBoundAttrLocation);
}
@@ -349,24 +358,28 @@ public class BatchingFontRenderer {
return (what >= fromInclusive) && (what <= toInclusive);
}
public boolean forceDefaults() {
return this.isSGA || this.isSplash;
}
public float getGlyphScaleX() {
return this.isSGA ? 1 : (float) (FontConfig.glyphScale * Math.pow(2, FontConfig.glyphAspect)) * (FontStrategist.customFontInUse ? 1.5f : 1);
return forceDefaults() ? 1 : (float) (FontConfig.glyphScale * Math.pow(2, FontConfig.glyphAspect)) * (FontStrategist.customFontInUse ? 1.5f : 1);
}
public float getGlyphScaleY() {
return this.isSGA ? 1 : (float) (FontConfig.glyphScale / Math.pow(2, FontConfig.glyphAspect)) * (FontStrategist.customFontInUse ? 1.5f : 1);
return forceDefaults() ? 1 : (float) (FontConfig.glyphScale / Math.pow(2, FontConfig.glyphAspect)) * (FontStrategist.customFontInUse ? 1.5f : 1);
}
public float getGlyphSpacing() {
return (this.isSGA ? 1 : FontConfig.glyphSpacing);
return forceDefaults() ? 0 : FontConfig.glyphSpacing;
}
public float getWhitespaceScale() {
return (this.isSGA ? 1 : FontConfig.whitespaceScale);
return forceDefaults() ? 1 : FontConfig.whitespaceScale;
}
public float getShadowOffset() {
return (this.isSGA ? 1 : FontConfig.fontShadowOffset);
return forceDefaults() ? 1 : FontConfig.fontShadowOffset;
}
private static final char FORMATTING_CHAR = 167; // §
@@ -481,7 +494,7 @@ public class BatchingFontRenderer {
chr = FontProviderMC.get(this.isSGA).getRandomReplacement(chr);
}
FontProvider fontProvider = FontStrategist.getFontProvider(chr, this.isSGA, FontConfig.enableCustomFont, unicodeFlag);
FontProvider fontProvider = FontStrategist.getFontProvider(this, chr, FontConfig.enableCustomFont, unicodeFlag);
// Check ASCII space, NBSP, NNBSP
if (chr == ' ' || chr == '\u00A0' || chr == '\u202F') {
@@ -574,8 +587,18 @@ public class BatchingFontRenderer {
return 4 * this.getWhitespaceScale();
}
FontProvider fp = FontStrategist.getFontProvider(chr, isSGA, FontConfig.enableCustomFont, underlying.getUnicodeFlag());
FontProvider fp = FontStrategist.getFontProvider(this, chr, FontConfig.enableCustomFont, underlying.getUnicodeFlag());
return fp.getXAdvance(chr) * this.getGlyphScaleX();
}
public void overrideBlendFunc(int srcRgb, int dstRgb) {
blendSrcRGB = srcRgb;
blendDstRGB = dstRgb;
}
public void resetBlendFunc() {
blendSrcRGB = GL11.GL_SRC_ALPHA;
blendDstRGB = GL11.GL_ONE_MINUS_SRC_ALPHA;
}
}
@@ -16,7 +16,6 @@ import javax.imageio.ImageIO;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
@@ -40,7 +39,7 @@ public final class FontProviderCustom implements FontProvider {
private FontProviderCustom(byte id) {
this.id = id;
Font[] availableFonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
Font[] availableFonts = FontStrategist.getAvailableFonts();
if (availableFonts.length == 0) {
LOGGER.fatal("There seem to be no fonts available on this system! Disabling custom font and throwing an exception in an attempt to restore the session.");
FontConfig.enableCustomFont = false;
@@ -79,8 +78,7 @@ public final class FontProviderCustom implements FontProvider {
public void reloadFont(int fontID) {
currentFontQuality = FontConfig.customFontQuality;
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
font = ge.getAllFonts()[fontID].deriveFont(currentFontQuality);
font = FontStrategist.getAvailableFonts()[fontID].deriveFont(currentFontQuality);
File[] files = new File(getFontDir()).listFiles();
if (files != null) {
@@ -1,20 +1,61 @@
package com.gtnewhorizons.angelica.client.font;
import com.google.common.collect.HashMultiset;
import com.gtnewhorizons.angelica.config.FontConfig;
import com.gtnewhorizons.angelica.mixins.interfaces.ResourceAccessor;
import lombok.Getter;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.DefaultResourcePack;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.io.File;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
public class FontStrategist {
@Getter
private static final Font[] availableFonts;
public static final Logger LOGGER = LogManager.getLogger("Angelica");
public static boolean customFontInUse;
static {
// get available fonts without duplicates (250 copies of dialog.plain need not apply)
Font[] availableFontsDirty = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
HashMap<String, Font> fontSet = new HashMap<>();
HashMultiset<String> duplicates = HashMultiset.create(); // for debugging
for (Font font : availableFontsDirty) {
String fontName = font.getFontName();
if (fontSet.containsKey(fontName)) {
duplicates.add(fontName);
} else {
fontSet.put(fontName, font);
}
}
if (!duplicates.isEmpty()) {
StringBuilder sb = new StringBuilder(duplicates.size() + " duplicate font(s) found in the list reported by Java: ");
for (Iterator<String> iter = duplicates.stream().distinct().iterator(); iter.hasNext(); ) {
String dupe = iter.next();
sb.append(duplicates.count(dupe)).append("x ").append(dupe);
if (iter.hasNext()) {
sb.append(", ");
}
}
sb.append(". Some fonts may be missing from the font selection menu.");
LOGGER.warn(sb.toString());
}
availableFonts = fontSet.values().stream().sorted(Comparator.comparing(Font::getFontName)).toArray(Font[]::new);
// create and add the resource pack that provides fonts
HashMap<String, File> packMap = new HashMap<>();
for (int i = 0; i < FontProviderCustom.ATLAS_COUNT; i++) {
packMap.put(FontProviderCustom.getPrimary().getAtlasResourceName(i), new File(FontProviderCustom.getPrimary().getAtlasFullPath(i)));
@@ -26,7 +67,7 @@ public class FontStrategist {
defaultResourcePacks.add(fontResourcePack);
Minecraft.getMinecraft().refreshResources();
Font[] availableFonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
// determine if a custom font is in use based on config values
boolean primaryFontFound = false;
boolean fallbackFontFound = false;
for (Font availableFont : availableFonts) {
@@ -42,17 +83,15 @@ public class FontStrategist {
customFontInUse = (FontConfig.enableCustomFont && (primaryFontFound || fallbackFontFound));
}
public static boolean customFontInUse;
/**
Lets you get a FontProvider per char while respecting font priority and fallbacks, the unicode flag, whether or not
SGA is on, if a font can even display a character in the first place, etc.
SGA is on, if we're in a splash screen, if a font can even display a character in the first place, etc.
*/
public static FontProvider getFontProvider(char chr, boolean isSGA, boolean customFontEnabled, boolean forceUnicode) {
if (isSGA && FontProviderMC.get(true).isGlyphAvailable(chr)) {
public static FontProvider getFontProvider(BatchingFontRenderer me, char chr, boolean customFontEnabled, boolean forceUnicode) {
if (me.isSGA && FontProviderMC.get(true).isGlyphAvailable(chr)) {
return FontProviderMC.get(true);
}
if (customFontEnabled) {
if (customFontEnabled && !me.isSplash) {
FontProvider fp;
fp = FontProviderCustom.getPrimary();
if (fp.isGlyphAvailable(chr)) { return fp; }
@@ -69,7 +108,6 @@ public class FontStrategist {
}
public static void reloadCustomFontProviders() {
Font[] availableFonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
FontProviderCustom.getPrimary().setFont(null);
FontProviderCustom.getFallback().setFont(null);
boolean primaryFontFound = false;
@@ -14,7 +14,6 @@ import net.minecraft.client.resources.I18n;
import org.lwjgl.input.Keyboard;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@@ -23,10 +22,10 @@ import java.util.stream.Collectors;
public class FontConfigScreen extends GuiScreen {
private static final Font[] availableFonts = FontStrategist.getAvailableFonts();
private final GuiScreen parent;
private final String title;
private final String searchPrompt;
private final Font[] availableFonts;
private String currentPrimaryFontName;
private String currentFallbackFontName;
private FontList fontList;
@@ -41,7 +40,6 @@ public class FontConfigScreen extends GuiScreen {
this.parent = parent;
this.currentPrimaryFontName = FontConfig.customFontNamePrimary;
this.currentFallbackFontName = FontConfig.customFontNameFallback;
this.availableFonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
this.displayedFonts = new ArrayList<>(Arrays.asList(availableFonts));
for (int i = 0; i < availableFonts.length; i++) {
if (Objects.equals(this.currentPrimaryFontName, availableFonts[i].getFontName())) {
@@ -52,7 +52,7 @@ public class FontConfig {
public static int fontAAMode;
@Config.Comment("Affects font antialiasing sample spacing. Higher values increase blur.")
@Config.DefaultInt(5)
@Config.DefaultInt(7)
@Config.RangeInt(min = 1, max = 24)
public static int fontAAStrength;
}
@@ -43,6 +43,20 @@ public class Feature {
}
private static final Map<Integer, Set<IStateStack<?>>> attribToFeatures = new HashMap<>();
/**
* Helper method to add all texture gen states (S, T, R, Q) for all texture units to a collection.
* Used by both GL_ENABLE_BIT and GL_TEXTURE_BIT.
*/
private static void addTextureGenStates(Set<IStateStack<?>> collection) {
for(int i = 0 ; i < GLStateManager.MAX_TEXTURE_UNITS; i++) {
collection.add(GLStateManager.textures.getTexGenSStates(i));
collection.add(GLStateManager.textures.getTexGenTStates(i));
collection.add(GLStateManager.textures.getTexGenRStates(i));
collection.add(GLStateManager.textures.getTexGenQStates(i));
}
}
static {
attribToFeatures.put(GL11.GL_COLOR_BUFFER_BIT, ImmutableSet.of(
GLStateManager.alphaTest // GL_ALPHA_TEST enable bit
@@ -51,10 +65,10 @@ public class Feature {
, GLStateManager.blendState // Blending source and destination functions
// Constant blend color
// Blending equation
// GL_DITHER enable bit
// GL_DRAW_BUFFER setting
// GL_COLOR_LOGIC_OP enable bit
// GL_INDEX_LOGIC_OP enable bit
, GLStateManager.colorLogicOpState // GL_COLOR_LOGIC_OP enable bit
, GLStateManager.ditherState // GL_DITHER enable bit
, GLStateManager.drawBuffer // GL_DRAW_BUFFER setting
, GLStateManager.indexLogicOpState // GL_INDEX_LOGIC_OP enable bit
// Logic op function
, GLStateManager.colorMask // Color-mode and index-mode writemasks
, GLStateManager.clearColor // Color-mode and index-mode clear values
@@ -80,14 +94,15 @@ public class Feature {
final HashSet<IStateStack<?>> enableBits = new HashSet<>(ImmutableSet.of(
GLStateManager.alphaTest // GL_ALPHA_TEST flag
// GL_AUTO_NORMAL flag
, GLStateManager.autoNormalState // GL_AUTO_NORMAL flag
, GLStateManager.blendMode // GL_BLEND flag
// Enable bits for the user-definable clipping planes
, GLStateManager.colorLogicOpState // GL_COLOR_LOGIC_OP flag
, GLStateManager.colorMaterial // GL_COLOR_MATERIAL
, GLStateManager.cullState // GL_CULL_FACE flag
, GLStateManager.depthTest // GL_DEPTH_TEST flag
// GL_DITHER flag
, GLStateManager.ditherState // GL_DITHER flag
, GLStateManager.fogMode // GL_FOG flag
, GLStateManager.indexLogicOpState // GL_INDEX_LOGIC_OP flag
, GLStateManager.lightStates[0] // GL_LIGHT0
, GLStateManager.lightStates[1] // GL_LIGHT1
, GLStateManager.lightStates[2] // GL_LIGHT2
@@ -97,36 +112,57 @@ public class Feature {
, GLStateManager.lightStates[6] // GL_LIGHT6
, GLStateManager.lightStates[7] // GL_LIGHT7
, GLStateManager.lightingState // GL_LIGHTING flag
// GL_LINE_SMOOTH flag
// GL_LINE_STIPPLE flag
// GL_INDEX_LOGIC_OP flag
// GL_COLOR_LOGIC_OP flag
// GL_MAP1_x where x is a map type
// GL_MAP2_x where x is a map type
// GL_MULTISAMPLE flag
// GL_NORMALIZE flag
// GL_POINT_SMOOTH flag
// GL_POLYGON_OFFSET_LINE flag
// GL_POLYGON_OFFSET_FILL flag
// GL_POLYGON_OFFSET_POINT flag
// GL_POLYGON_SMOOTH flag
// GL_POLYGON_STIPPLE flag
// GL_SAMPLE_ALPHA_TO_COVERAGE flag
// GL_SAMPLE_ALPHA_TO_ONE flag
// GL_SAMPLE_COVERAGE flag
, GLStateManager.lineSmoothState // GL_LINE_SMOOTH flag
, GLStateManager.lineStippleState // GL_LINE_STIPPLE flag
, GLStateManager.map1Color4State // GL_MAP1_COLOR_4
, GLStateManager.map1IndexState // GL_MAP1_INDEX
, GLStateManager.map1NormalState // GL_MAP1_NORMAL
, GLStateManager.map1TextureCoord1State // GL_MAP1_TEXTURE_COORD_1
, GLStateManager.map1TextureCoord2State // GL_MAP1_TEXTURE_COORD_2
, GLStateManager.map1TextureCoord3State // GL_MAP1_TEXTURE_COORD_3
, GLStateManager.map1TextureCoord4State // GL_MAP1_TEXTURE_COORD_4
, GLStateManager.map1Vertex3State // GL_MAP1_VERTEX_3
, GLStateManager.map1Vertex4State // GL_MAP1_VERTEX_4
, GLStateManager.map2Color4State // GL_MAP2_COLOR_4
, GLStateManager.map2IndexState // GL_MAP2_INDEX
, GLStateManager.map2NormalState // GL_MAP2_NORMAL
, GLStateManager.map2TextureCoord1State // GL_MAP2_TEXTURE_COORD_1
, GLStateManager.map2TextureCoord2State // GL_MAP2_TEXTURE_COORD_2
, GLStateManager.map2TextureCoord3State // GL_MAP2_TEXTURE_COORD_3
, GLStateManager.map2TextureCoord4State // GL_MAP2_TEXTURE_COORD_4
, GLStateManager.map2Vertex3State // GL_MAP2_VERTEX_3
, GLStateManager.map2Vertex4State // GL_MAP2_VERTEX_4
, GLStateManager.multisampleState // GL_MULTISAMPLE flag
, GLStateManager.normalizeState // GL_NORMALIZE flag
, GLStateManager.pointSmoothState // GL_POINT_SMOOTH flag
, GLStateManager.polygonOffsetPointState // GL_POLYGON_OFFSET_POINT flag
, GLStateManager.polygonOffsetLineState // GL_POLYGON_OFFSET_LINE flag
, GLStateManager.polygonOffsetFillState // GL_POLYGON_OFFSET_FILL flag
, GLStateManager.polygonSmoothState // GL_POLYGON_SMOOTH flag
, GLStateManager.polygonStippleState // GL_POLYGON_STIPPLE flag
, GLStateManager.rescaleNormalState // GL_RESCALE_NORMAL flag
, GLStateManager.sampleAlphaToCoverageState // GL_SAMPLE_ALPHA_TO_COVERAGE flag
, GLStateManager.sampleAlphaToOneState // GL_SAMPLE_ALPHA_TO_ONE flag
, GLStateManager.sampleCoverageState // GL_SAMPLE_COVERAGE flag
, GLStateManager.scissorTest // GL_SCISSOR_TEST flag
// GL_STENCIL_TEST flag
// GL_TEXTURE_1D flag
// GL_TEXTURE_2D flag - Below
// GL_TEXTURE_3D flag
// Flags GL_TEXTURE_GEN_x where x is S, T, R, or Q
, GLStateManager.stencilTest // GL_STENCIL_TEST flag
));
// GL_TEXTURE_2D flag
for(int i = 0 ; i < GLStateManager.MAX_TEXTURE_UNITS; i++) {
enableBits.add(GLStateManager.textures.getTextureUnitStates(i));
// Enable bits for the user-definable clipping planes
for(int i = 0; i < GLStateManager.clipPlaneStates.length; i++) {
enableBits.add(GLStateManager.clipPlaneStates[i]);
}
// GL_TEXTURE_1D, GL_TEXTURE_2D, GL_TEXTURE_3D flags
for(int i = 0 ; i < GLStateManager.MAX_TEXTURE_UNITS; i++) {
enableBits.add(GLStateManager.textures.getTexture1DStates(i));
enableBits.add(GLStateManager.textures.getTextureUnitStates(i));
enableBits.add(GLStateManager.textures.getTexture3DStates(i));
}
// Flags GL_TEXTURE_GEN_x where x is S, T, R, or Q
addTextureGenStates(enableBits);
attribToFeatures.put(GL11.GL_ENABLE_BIT, enableBits);
attribToFeatures.put(GL11.GL_EVAL_BIT, ImmutableSet.of(
// GL_MAP1_x enable bits, where x is a map type
@@ -268,13 +304,16 @@ public class Feature {
// textureAttribs.add(GLStateManager.textures.getInfo(i))
}
// Enable bits GL_TEXTURE_GEN_x where x is S, T, R, or Q
addTextureGenStates(textureAttribs);
attribToFeatures.put(GL11.GL_TEXTURE_BIT, textureAttribs);
attribToFeatures.put(GL11.GL_TRANSFORM_BIT, ImmutableSet.of(
// Coefficients of the six clipping planes
// Enable bits for the user-definable clipping planes
GLStateManager.matrixMode
// GL_NORMALIZE flag
, GLStateManager.normalizeState // GL_NORMALIZE flag
, GLStateManager.rescaleNormalState // GL_RESCALE_NORMAL flag
));
attribToFeatures.put(GL11.GL_VIEWPORT_BIT, ImmutableSet.of(
@@ -81,8 +81,23 @@ import java.util.Map;
import java.util.Set;
import java.util.function.IntSupplier;
import static com.gtnewhorizons.angelica.glsm.Vendor.AMD;
import static com.gtnewhorizons.angelica.glsm.Vendor.INTEL;
import static com.gtnewhorizons.angelica.glsm.Vendor.MESA;
import static com.gtnewhorizons.angelica.glsm.Vendor.NVIDIA;
import static com.gtnewhorizons.angelica.loading.AngelicaTweaker.LOGGER;
/**
* OpenGL State Manager - Provides cached state tracking and management for OpenGL operations.
*
* <p><b>IMPORTANT INITIALIZATION ORDER:</b></p>
* <ul>
* <li>This class performs GL queries in static initializers (MAX_CLIP_PLANES, MAX_TEXTURE_UNITS, etc.)</li>
* <li>The class MUST NOT be loaded until after the GL context has been created and made current</li>
* <li>Violating this requirement will cause crashes with "No current context" or return invalid values</li>
* <li>Call {@link #preInit()} after GL context creation to initialize runtime state</li>
* </ul>
*/
@SuppressWarnings("unused") // Used in ASM
public class GLStateManager {
public static ContextCapabilities capabilities;
@@ -94,13 +109,14 @@ public class GLStateManager {
public static final int MAX_PROJECTION_STACK_DEPTH = GL11.glGetInteger(GL11.GL_MAX_PROJECTION_STACK_DEPTH);
public static final int MAX_TEXTURE_STACK_DEPTH = GL11.glGetInteger(GL11.GL_MAX_TEXTURE_STACK_DEPTH);
public static final int MAX_TEXTURE_UNITS = GL11.glGetInteger(GL20.GL_MAX_TEXTURE_IMAGE_UNITS);
public static final int MAX_CLIP_PLANES = GL11.glGetInteger(GL11.GL_MAX_CLIP_PLANES);
public static final GLFeatureSet HAS_MULTIPLE_SET = new GLFeatureSet();
@Getter protected static boolean NVIDIA;
@Getter protected static boolean AMD;
@Getter protected static boolean INTEL;
@Getter protected static boolean MESA;
@Getter private static Vendor VENDOR;
// This setting varies depending on driver, so it gets queried at runtime
public static final int DEFAULT_DRAW_BUFFER = GL11.glGetInteger(GL11.GL_DRAW_BUFFER);
// GLStateManager State Trackers
private static final IntStack attribs = new IntArrayList(MAX_ATTRIB_STACK_DEPTH);
@@ -119,12 +135,58 @@ public class GLStateManager {
@Getter protected static final Color4Stack color = new Color4Stack();
@Getter protected static final Color4Stack clearColor = new Color4Stack(new Color4(0.0F, 0.0F, 0.0F, 0.0F));
@Getter protected static final ColorMaskStack colorMask = new ColorMaskStack();
@Getter protected static final IntegerStateStack drawBuffer = new IntegerStateStack(DEFAULT_DRAW_BUFFER);
@Getter protected static final BooleanStateStack cullState = new BooleanStateStack(GL11.GL_CULL_FACE);
@Getter protected static final AlphaStateStack alphaState = new AlphaStateStack();
@Getter protected static final BooleanStateStack alphaTest = new BooleanStateStack(GL11.GL_ALPHA_TEST);
@Getter protected static final BooleanStateStack lightingState = new BooleanStateStack(GL11.GL_LIGHTING);
@Getter protected static final BooleanStateStack rescaleNormalState = new BooleanStateStack(GL12.GL_RESCALE_NORMAL);
@Getter protected static final BooleanStateStack normalizeState = new BooleanStateStack(GL11.GL_NORMALIZE);
// Additional enable bit states tracked by GL_ENABLE_BIT
@Getter protected static final BooleanStateStack ditherState = new BooleanStateStack(GL11.GL_DITHER, true); // Defaults to true per OpenGL spec
@Getter protected static final BooleanStateStack stencilTest = new BooleanStateStack(GL11.GL_STENCIL_TEST);
@Getter protected static final BooleanStateStack lineSmoothState = new BooleanStateStack(GL11.GL_LINE_SMOOTH);
@Getter protected static final BooleanStateStack lineStippleState = new BooleanStateStack(GL11.GL_LINE_STIPPLE);
@Getter protected static final BooleanStateStack pointSmoothState = new BooleanStateStack(GL11.GL_POINT_SMOOTH);
@Getter protected static final BooleanStateStack polygonSmoothState = new BooleanStateStack(GL11.GL_POLYGON_SMOOTH);
@Getter protected static final BooleanStateStack polygonStippleState = new BooleanStateStack(GL11.GL_POLYGON_STIPPLE);
@Getter protected static final BooleanStateStack multisampleState = new BooleanStateStack(GL13.GL_MULTISAMPLE, true); // Defaults to true per OpenGL spec
@Getter protected static final BooleanStateStack sampleAlphaToCoverageState = new BooleanStateStack(GL13.GL_SAMPLE_ALPHA_TO_COVERAGE);
@Getter protected static final BooleanStateStack sampleAlphaToOneState = new BooleanStateStack(GL13.GL_SAMPLE_ALPHA_TO_ONE);
@Getter protected static final BooleanStateStack sampleCoverageState = new BooleanStateStack(GL13.GL_SAMPLE_COVERAGE);
@Getter protected static final BooleanStateStack colorLogicOpState = new BooleanStateStack(GL11.GL_COLOR_LOGIC_OP);
@Getter protected static final BooleanStateStack indexLogicOpState = new BooleanStateStack(GL11.GL_INDEX_LOGIC_OP);
// Polygon offset states
@Getter protected static final BooleanStateStack polygonOffsetPointState = new BooleanStateStack(GL11.GL_POLYGON_OFFSET_POINT);
@Getter protected static final BooleanStateStack polygonOffsetLineState = new BooleanStateStack(GL11.GL_POLYGON_OFFSET_LINE);
@Getter protected static final BooleanStateStack polygonOffsetFillState = new BooleanStateStack(GL11.GL_POLYGON_OFFSET_FILL);
// Evaluator states
@Getter protected static final BooleanStateStack autoNormalState = new BooleanStateStack(GL11.GL_AUTO_NORMAL);
@Getter protected static final BooleanStateStack map1Color4State = new BooleanStateStack(GL11.GL_MAP1_COLOR_4);
@Getter protected static final BooleanStateStack map1IndexState = new BooleanStateStack(GL11.GL_MAP1_INDEX);
@Getter protected static final BooleanStateStack map1NormalState = new BooleanStateStack(GL11.GL_MAP1_NORMAL);
@Getter protected static final BooleanStateStack map1TextureCoord1State = new BooleanStateStack(GL11.GL_MAP1_TEXTURE_COORD_1);
@Getter protected static final BooleanStateStack map1TextureCoord2State = new BooleanStateStack(GL11.GL_MAP1_TEXTURE_COORD_2);
@Getter protected static final BooleanStateStack map1TextureCoord3State = new BooleanStateStack(GL11.GL_MAP1_TEXTURE_COORD_3);
@Getter protected static final BooleanStateStack map1TextureCoord4State = new BooleanStateStack(GL11.GL_MAP1_TEXTURE_COORD_4);
@Getter protected static final BooleanStateStack map1Vertex3State = new BooleanStateStack(GL11.GL_MAP1_VERTEX_3);
@Getter protected static final BooleanStateStack map1Vertex4State = new BooleanStateStack(GL11.GL_MAP1_VERTEX_4);
@Getter protected static final BooleanStateStack map2Color4State = new BooleanStateStack(GL11.GL_MAP2_COLOR_4);
@Getter protected static final BooleanStateStack map2IndexState = new BooleanStateStack(GL11.GL_MAP2_INDEX);
@Getter protected static final BooleanStateStack map2NormalState = new BooleanStateStack(GL11.GL_MAP2_NORMAL);
@Getter protected static final BooleanStateStack map2TextureCoord1State = new BooleanStateStack(GL11.GL_MAP2_TEXTURE_COORD_1);
@Getter protected static final BooleanStateStack map2TextureCoord2State = new BooleanStateStack(GL11.GL_MAP2_TEXTURE_COORD_2);
@Getter protected static final BooleanStateStack map2TextureCoord3State = new BooleanStateStack(GL11.GL_MAP2_TEXTURE_COORD_3);
@Getter protected static final BooleanStateStack map2TextureCoord4State = new BooleanStateStack(GL11.GL_MAP2_TEXTURE_COORD_4);
@Getter protected static final BooleanStateStack map2Vertex3State = new BooleanStateStack(GL11.GL_MAP2_VERTEX_3);
@Getter protected static final BooleanStateStack map2Vertex4State = new BooleanStateStack(GL11.GL_MAP2_VERTEX_4);
// Clip plane states
@Getter protected static final BooleanStateStack[] clipPlaneStates = new BooleanStateStack[MAX_CLIP_PLANES];
@Getter protected static final MatrixModeStack matrixMode = new MatrixModeStack();
@Getter protected static final Matrix4fStack modelViewMatrix = new Matrix4fStack(MAX_MODELVIEW_STACK_DEPTH);
@@ -148,8 +210,12 @@ public class GLStateManager {
lightDataStates[i] = new LightStateStack(GL11.GL_LIGHT0 + i);
}
for (int i = 0; i < MAX_CLIP_PLANES; i++) {
clipPlaneStates[i] = new BooleanStateStack(GL11.GL_CLIP_PLANE0 + i);
}
try {
Field curr = ReflectionHelper.findField(Matrix4fStack.class, "curr");
final Field curr = ReflectionHelper.findField(Matrix4fStack.class, "curr");
curr.setAccessible(true);
MAT4_STACK_CURR_DEPTH = MethodHandles.lookup().unreflectGetter(curr);
} catch (IllegalAccessException e) {
@@ -167,11 +233,11 @@ public class GLStateManager {
attribs.popInt();
}
List<IStateStack<?>> stacks = Feature.maskToFeatures(GL11.GL_ALL_ATTRIB_BITS);
int size = stacks.size();
final List<IStateStack<?>> stacks = Feature.maskToFeatures(GL11.GL_ALL_ATTRIB_BITS);
final int size = stacks.size();
for(int i = 0; i < size; i++) {
IStateStack<?> stack = stacks.get(i);
final IStateStack<?> stack = stacks.get(i);
while(!stack.isEmpty()) {
stack.pop();
@@ -245,16 +311,12 @@ public class GLStateManager {
.addFeature(GL11.GL_VIEWPORT);
String glVendor = GL11.glGetString(GL11.GL_VENDOR);
NVIDIA = glVendor.toLowerCase().contains("nvidia");
AMD = glVendor.toLowerCase().contains("ati") || glVendor.toLowerCase().contains("amd");
INTEL = glVendor.toLowerCase().contains("intel");
MESA = glVendor.toLowerCase().contains("mesa");
VENDOR = Vendor.getVendor(glVendor.toLowerCase());
if(AMD) {
if (vendorIsAMD()) {
// AMD Drivers seem to default to 0 for the matrix mode, so we need to set it to the default
GL11.glMatrixMode(GL11.GL_MODELVIEW);
}
}
public static void init() {
@@ -300,12 +362,23 @@ public class GLStateManager {
// LWJGL Overrides
public static void glEnable(int cap) {
// Handle clip planes dynamically (supports up to MAX_CLIP_PLANES)
if (cap >= GL11.GL_CLIP_PLANE0 && cap < GL11.GL_CLIP_PLANE0 + MAX_CLIP_PLANES) {
clipPlaneStates[cap - GL11.GL_CLIP_PLANE0].enable();
return;
}
switch (cap) {
case GL11.GL_ALPHA_TEST -> enableAlphaTest();
case GL11.GL_AUTO_NORMAL -> autoNormalState.enable();
case GL11.GL_BLEND -> enableBlend();
case GL11.GL_COLOR_MATERIAL -> enableColorMaterial();
case GL11.GL_COLOR_LOGIC_OP -> colorLogicOpState.enable();
case GL11.GL_CULL_FACE -> enableCull();
case GL11.GL_DEPTH_TEST -> enableDepthTest();
case GL11.GL_DITHER -> ditherState.enable();
case GL11.GL_FOG -> enableFog();
case GL11.GL_INDEX_LOGIC_OP -> indexLogicOpState.enable();
case GL11.GL_LIGHTING -> enableLighting();
case GL11.GL_LIGHT0 -> enableLight(0);
case GL11.GL_LIGHT1 -> enableLight(1);
@@ -315,21 +388,69 @@ public class GLStateManager {
case GL11.GL_LIGHT5 -> enableLight(5);
case GL11.GL_LIGHT6 -> enableLight(6);
case GL11.GL_LIGHT7 -> enableLight(7);
case GL11.GL_COLOR_MATERIAL -> enableColorMaterial();
case GL11.GL_SCISSOR_TEST -> enableScissorTest();
case GL11.GL_TEXTURE_2D -> enableTexture();
case GL11.GL_LINE_SMOOTH -> lineSmoothState.enable();
case GL11.GL_LINE_STIPPLE -> lineStippleState.enable();
case GL11.GL_MAP1_COLOR_4 -> map1Color4State.enable();
case GL11.GL_MAP1_INDEX -> map1IndexState.enable();
case GL11.GL_MAP1_NORMAL -> map1NormalState.enable();
case GL11.GL_MAP1_TEXTURE_COORD_1 -> map1TextureCoord1State.enable();
case GL11.GL_MAP1_TEXTURE_COORD_2 -> map1TextureCoord2State.enable();
case GL11.GL_MAP1_TEXTURE_COORD_3 -> map1TextureCoord3State.enable();
case GL11.GL_MAP1_TEXTURE_COORD_4 -> map1TextureCoord4State.enable();
case GL11.GL_MAP1_VERTEX_3 -> map1Vertex3State.enable();
case GL11.GL_MAP1_VERTEX_4 -> map1Vertex4State.enable();
case GL11.GL_MAP2_COLOR_4 -> map2Color4State.enable();
case GL11.GL_MAP2_INDEX -> map2IndexState.enable();
case GL11.GL_MAP2_NORMAL -> map2NormalState.enable();
case GL11.GL_MAP2_TEXTURE_COORD_1 -> map2TextureCoord1State.enable();
case GL11.GL_MAP2_TEXTURE_COORD_2 -> map2TextureCoord2State.enable();
case GL11.GL_MAP2_TEXTURE_COORD_3 -> map2TextureCoord3State.enable();
case GL11.GL_MAP2_TEXTURE_COORD_4 -> map2TextureCoord4State.enable();
case GL11.GL_MAP2_VERTEX_3 -> map2Vertex3State.enable();
case GL11.GL_MAP2_VERTEX_4 -> map2Vertex4State.enable();
case GL13.GL_MULTISAMPLE -> multisampleState.enable();
case GL11.GL_NORMALIZE -> normalizeState.enable();
case GL11.GL_POINT_SMOOTH -> pointSmoothState.enable();
case GL11.GL_POLYGON_OFFSET_POINT -> polygonOffsetPointState.enable();
case GL11.GL_POLYGON_OFFSET_LINE -> polygonOffsetLineState.enable();
case GL11.GL_POLYGON_OFFSET_FILL -> polygonOffsetFillState.enable();
case GL11.GL_POLYGON_SMOOTH -> polygonSmoothState.enable();
case GL11.GL_POLYGON_STIPPLE -> polygonStippleState.enable();
case GL12.GL_RESCALE_NORMAL -> enableRescaleNormal();
case GL13.GL_SAMPLE_ALPHA_TO_COVERAGE -> sampleAlphaToCoverageState.enable();
case GL13.GL_SAMPLE_ALPHA_TO_ONE -> sampleAlphaToOneState.enable();
case GL13.GL_SAMPLE_COVERAGE -> sampleCoverageState.enable();
case GL11.GL_SCISSOR_TEST -> enableScissorTest();
case GL11.GL_STENCIL_TEST -> stencilTest.enable();
case GL11.GL_TEXTURE_1D -> textures.getTexture1DStates(activeTextureUnit.getValue()).enable();
case GL11.GL_TEXTURE_2D -> enableTexture();
case GL12.GL_TEXTURE_3D -> textures.getTexture3DStates(activeTextureUnit.getValue()).enable();
case GL11.GL_TEXTURE_GEN_S -> textures.getTexGenSStates(activeTextureUnit.getValue()).enable();
case GL11.GL_TEXTURE_GEN_T -> textures.getTexGenTStates(activeTextureUnit.getValue()).enable();
case GL11.GL_TEXTURE_GEN_R -> textures.getTexGenRStates(activeTextureUnit.getValue()).enable();
case GL11.GL_TEXTURE_GEN_Q -> textures.getTexGenQStates(activeTextureUnit.getValue()).enable();
default -> GL11.glEnable(cap);
}
}
public static void glDisable(int cap) {
// Handle clip planes dynamically (supports up to MAX_CLIP_PLANES)
if (cap >= GL11.GL_CLIP_PLANE0 && cap < GL11.GL_CLIP_PLANE0 + MAX_CLIP_PLANES) {
clipPlaneStates[cap - GL11.GL_CLIP_PLANE0].disable();
return;
}
switch (cap) {
case GL11.GL_ALPHA_TEST -> disableAlphaTest();
case GL11.GL_AUTO_NORMAL -> autoNormalState.disable();
case GL11.GL_BLEND -> disableBlend();
case GL11.GL_COLOR_MATERIAL -> disableColorMaterial();
case GL11.GL_COLOR_LOGIC_OP -> colorLogicOpState.disable();
case GL11.GL_CULL_FACE -> disableCull();
case GL11.GL_DEPTH_TEST -> disableDepthTest();
case GL11.GL_DITHER -> ditherState.disable();
case GL11.GL_FOG -> disableFog();
case GL11.GL_INDEX_LOGIC_OP -> indexLogicOpState.disable();
case GL11.GL_LIGHTING -> disableLighting();
case GL11.GL_LIGHT0 -> disableLight(0);
case GL11.GL_LIGHT1 -> disableLight(1);
@@ -339,10 +460,47 @@ public class GLStateManager {
case GL11.GL_LIGHT5 -> disableLight(5);
case GL11.GL_LIGHT6 -> disableLight(6);
case GL11.GL_LIGHT7 -> disableLight(7);
case GL11.GL_COLOR_MATERIAL -> disableColorMaterial();
case GL11.GL_SCISSOR_TEST -> disableScissorTest();
case GL11.GL_TEXTURE_2D -> disableTexture();
case GL11.GL_LINE_SMOOTH -> lineSmoothState.disable();
case GL11.GL_LINE_STIPPLE -> lineStippleState.disable();
case GL11.GL_MAP1_COLOR_4 -> map1Color4State.disable();
case GL11.GL_MAP1_INDEX -> map1IndexState.disable();
case GL11.GL_MAP1_NORMAL -> map1NormalState.disable();
case GL11.GL_MAP1_TEXTURE_COORD_1 -> map1TextureCoord1State.disable();
case GL11.GL_MAP1_TEXTURE_COORD_2 -> map1TextureCoord2State.disable();
case GL11.GL_MAP1_TEXTURE_COORD_3 -> map1TextureCoord3State.disable();
case GL11.GL_MAP1_TEXTURE_COORD_4 -> map1TextureCoord4State.disable();
case GL11.GL_MAP1_VERTEX_3 -> map1Vertex3State.disable();
case GL11.GL_MAP1_VERTEX_4 -> map1Vertex4State.disable();
case GL11.GL_MAP2_COLOR_4 -> map2Color4State.disable();
case GL11.GL_MAP2_INDEX -> map2IndexState.disable();
case GL11.GL_MAP2_NORMAL -> map2NormalState.disable();
case GL11.GL_MAP2_TEXTURE_COORD_1 -> map2TextureCoord1State.disable();
case GL11.GL_MAP2_TEXTURE_COORD_2 -> map2TextureCoord2State.disable();
case GL11.GL_MAP2_TEXTURE_COORD_3 -> map2TextureCoord3State.disable();
case GL11.GL_MAP2_TEXTURE_COORD_4 -> map2TextureCoord4State.disable();
case GL11.GL_MAP2_VERTEX_3 -> map2Vertex3State.disable();
case GL11.GL_MAP2_VERTEX_4 -> map2Vertex4State.disable();
case GL13.GL_MULTISAMPLE -> multisampleState.disable();
case GL11.GL_NORMALIZE -> normalizeState.disable();
case GL11.GL_POINT_SMOOTH -> pointSmoothState.disable();
case GL11.GL_POLYGON_OFFSET_POINT -> polygonOffsetPointState.disable();
case GL11.GL_POLYGON_OFFSET_LINE -> polygonOffsetLineState.disable();
case GL11.GL_POLYGON_OFFSET_FILL -> polygonOffsetFillState.disable();
case GL11.GL_POLYGON_SMOOTH -> polygonSmoothState.disable();
case GL11.GL_POLYGON_STIPPLE -> polygonStippleState.disable();
case GL12.GL_RESCALE_NORMAL -> disableRescaleNormal();
case GL13.GL_SAMPLE_ALPHA_TO_COVERAGE -> sampleAlphaToCoverageState.disable();
case GL13.GL_SAMPLE_ALPHA_TO_ONE -> sampleAlphaToOneState.disable();
case GL13.GL_SAMPLE_COVERAGE -> sampleCoverageState.disable();
case GL11.GL_SCISSOR_TEST -> disableScissorTest();
case GL11.GL_STENCIL_TEST -> stencilTest.disable();
case GL11.GL_TEXTURE_1D -> textures.getTexture1DStates(activeTextureUnit.getValue()).disable();
case GL11.GL_TEXTURE_2D -> disableTexture();
case GL12.GL_TEXTURE_3D -> textures.getTexture3DStates(activeTextureUnit.getValue()).disable();
case GL11.GL_TEXTURE_GEN_S -> textures.getTexGenSStates(activeTextureUnit.getValue()).disable();
case GL11.GL_TEXTURE_GEN_T -> textures.getTexGenTStates(activeTextureUnit.getValue()).disable();
case GL11.GL_TEXTURE_GEN_R -> textures.getTexGenRStates(activeTextureUnit.getValue()).disable();
case GL11.GL_TEXTURE_GEN_Q -> textures.getTexGenQStates(activeTextureUnit.getValue()).disable();
default -> GL11.glDisable(cap);
}
}
@@ -351,12 +509,22 @@ public class GLStateManager {
if(shouldBypassCache()) {
return GL11.glIsEnabled(cap);
}
// Handle clip planes dynamically (supports up to MAX_CLIP_PLANES)
if (cap >= GL11.GL_CLIP_PLANE0 && cap < GL11.GL_CLIP_PLANE0 + MAX_CLIP_PLANES) {
return clipPlaneStates[cap - GL11.GL_CLIP_PLANE0].isEnabled();
}
return switch (cap) {
case GL11.GL_ALPHA_TEST -> alphaTest.isEnabled();
case GL11.GL_AUTO_NORMAL -> autoNormalState.isEnabled();
case GL11.GL_BLEND -> blendMode.isEnabled();
case GL11.GL_COLOR_MATERIAL -> colorMaterial.isEnabled();
case GL11.GL_COLOR_LOGIC_OP -> colorLogicOpState.isEnabled();
case GL11.GL_CULL_FACE -> cullState.isEnabled();
case GL11.GL_DEPTH_TEST -> depthTest.isEnabled();
case GL11.GL_DITHER -> ditherState.isEnabled();
case GL11.GL_FOG -> fogMode.isEnabled();
case GL11.GL_INDEX_LOGIC_OP -> indexLogicOpState.isEnabled();
case GL11.GL_LIGHTING -> lightingState.isEnabled();
case GL11.GL_LIGHT0 -> lightStates[0].isEnabled();
case GL11.GL_LIGHT1 -> lightStates[1].isEnabled();
@@ -366,10 +534,47 @@ public class GLStateManager {
case GL11.GL_LIGHT5 -> lightStates[5].isEnabled();
case GL11.GL_LIGHT6 -> lightStates[6].isEnabled();
case GL11.GL_LIGHT7 -> lightStates[7].isEnabled();
case GL11.GL_COLOR_MATERIAL -> colorMaterial.isEnabled();
case GL11.GL_SCISSOR_TEST -> scissorTest.isEnabled();
case GL11.GL_TEXTURE_2D -> textures.getTextureUnitStates(activeTextureUnit.getValue()).isEnabled();
case GL11.GL_LINE_SMOOTH -> lineSmoothState.isEnabled();
case GL11.GL_LINE_STIPPLE -> lineStippleState.isEnabled();
case GL11.GL_MAP1_COLOR_4 -> map1Color4State.isEnabled();
case GL11.GL_MAP1_INDEX -> map1IndexState.isEnabled();
case GL11.GL_MAP1_NORMAL -> map1NormalState.isEnabled();
case GL11.GL_MAP1_TEXTURE_COORD_1 -> map1TextureCoord1State.isEnabled();
case GL11.GL_MAP1_TEXTURE_COORD_2 -> map1TextureCoord2State.isEnabled();
case GL11.GL_MAP1_TEXTURE_COORD_3 -> map1TextureCoord3State.isEnabled();
case GL11.GL_MAP1_TEXTURE_COORD_4 -> map1TextureCoord4State.isEnabled();
case GL11.GL_MAP1_VERTEX_3 -> map1Vertex3State.isEnabled();
case GL11.GL_MAP1_VERTEX_4 -> map1Vertex4State.isEnabled();
case GL11.GL_MAP2_COLOR_4 -> map2Color4State.isEnabled();
case GL11.GL_MAP2_INDEX -> map2IndexState.isEnabled();
case GL11.GL_MAP2_NORMAL -> map2NormalState.isEnabled();
case GL11.GL_MAP2_TEXTURE_COORD_1 -> map2TextureCoord1State.isEnabled();
case GL11.GL_MAP2_TEXTURE_COORD_2 -> map2TextureCoord2State.isEnabled();
case GL11.GL_MAP2_TEXTURE_COORD_3 -> map2TextureCoord3State.isEnabled();
case GL11.GL_MAP2_TEXTURE_COORD_4 -> map2TextureCoord4State.isEnabled();
case GL11.GL_MAP2_VERTEX_3 -> map2Vertex3State.isEnabled();
case GL11.GL_MAP2_VERTEX_4 -> map2Vertex4State.isEnabled();
case GL13.GL_MULTISAMPLE -> multisampleState.isEnabled();
case GL11.GL_NORMALIZE -> normalizeState.isEnabled();
case GL11.GL_POINT_SMOOTH -> pointSmoothState.isEnabled();
case GL11.GL_POLYGON_OFFSET_POINT -> polygonOffsetPointState.isEnabled();
case GL11.GL_POLYGON_OFFSET_LINE -> polygonOffsetLineState.isEnabled();
case GL11.GL_POLYGON_OFFSET_FILL -> polygonOffsetFillState.isEnabled();
case GL11.GL_POLYGON_SMOOTH -> polygonSmoothState.isEnabled();
case GL11.GL_POLYGON_STIPPLE -> polygonStippleState.isEnabled();
case GL12.GL_RESCALE_NORMAL -> rescaleNormalState.isEnabled();
case GL13.GL_SAMPLE_ALPHA_TO_COVERAGE -> sampleAlphaToCoverageState.isEnabled();
case GL13.GL_SAMPLE_ALPHA_TO_ONE -> sampleAlphaToOneState.isEnabled();
case GL13.GL_SAMPLE_COVERAGE -> sampleCoverageState.isEnabled();
case GL11.GL_SCISSOR_TEST -> scissorTest.isEnabled();
case GL11.GL_STENCIL_TEST -> stencilTest.isEnabled();
case GL11.GL_TEXTURE_1D -> textures.getTexture1DStates(activeTextureUnit.getValue()).isEnabled();
case GL11.GL_TEXTURE_2D -> textures.getTextureUnitStates(activeTextureUnit.getValue()).isEnabled();
case GL12.GL_TEXTURE_3D -> textures.getTexture3DStates(activeTextureUnit.getValue()).isEnabled();
case GL11.GL_TEXTURE_GEN_S -> textures.getTexGenSStates(activeTextureUnit.getValue()).isEnabled();
case GL11.GL_TEXTURE_GEN_T -> textures.getTexGenTStates(activeTextureUnit.getValue()).isEnabled();
case GL11.GL_TEXTURE_GEN_R -> textures.getTexGenRStates(activeTextureUnit.getValue()).isEnabled();
case GL11.GL_TEXTURE_GEN_Q -> textures.getTexGenQStates(activeTextureUnit.getValue()).isEnabled();
default -> GL11.glIsEnabled(cap);
};
}
@@ -378,13 +583,23 @@ public class GLStateManager {
if(shouldBypassCache()) {
return GL11.glGetBoolean(pname);
}
// Handle clip planes dynamically (supports up to MAX_CLIP_PLANES)
if (pname >= GL11.GL_CLIP_PLANE0 && pname < GL11.GL_CLIP_PLANE0 + MAX_CLIP_PLANES) {
return clipPlaneStates[pname - GL11.GL_CLIP_PLANE0].isEnabled();
}
return switch (pname) {
case GL11.GL_ALPHA_TEST -> alphaTest.isEnabled();
case GL11.GL_AUTO_NORMAL -> autoNormalState.isEnabled();
case GL11.GL_BLEND -> blendMode.isEnabled();
case GL11.GL_COLOR_MATERIAL -> colorMaterial.isEnabled();
case GL11.GL_COLOR_LOGIC_OP -> colorLogicOpState.isEnabled();
case GL11.GL_CULL_FACE -> cullState.isEnabled();
case GL11.GL_DEPTH_TEST -> depthTest.isEnabled();
case GL11.GL_DEPTH_WRITEMASK -> depthState.isEnabled();
case GL11.GL_DITHER -> ditherState.isEnabled();
case GL11.GL_FOG -> fogMode.isEnabled();
case GL11.GL_INDEX_LOGIC_OP -> indexLogicOpState.isEnabled();
case GL11.GL_LIGHTING -> lightingState.isEnabled();
case GL11.GL_LIGHT0 -> lightStates[0].isEnabled();
case GL11.GL_LIGHT1 -> lightStates[1].isEnabled();
@@ -394,10 +609,47 @@ public class GLStateManager {
case GL11.GL_LIGHT5 -> lightStates[5].isEnabled();
case GL11.GL_LIGHT6 -> lightStates[6].isEnabled();
case GL11.GL_LIGHT7 -> lightStates[7].isEnabled();
case GL11.GL_COLOR_MATERIAL -> colorMaterial.isEnabled();
case GL11.GL_SCISSOR_TEST -> scissorTest.isEnabled();
case GL11.GL_TEXTURE_2D -> textures.getTextureUnitStates(activeTextureUnit.getValue()).isEnabled();
case GL11.GL_LINE_SMOOTH -> lineSmoothState.isEnabled();
case GL11.GL_LINE_STIPPLE -> lineStippleState.isEnabled();
case GL11.GL_MAP1_COLOR_4 -> map1Color4State.isEnabled();
case GL11.GL_MAP1_INDEX -> map1IndexState.isEnabled();
case GL11.GL_MAP1_NORMAL -> map1NormalState.isEnabled();
case GL11.GL_MAP1_TEXTURE_COORD_1 -> map1TextureCoord1State.isEnabled();
case GL11.GL_MAP1_TEXTURE_COORD_2 -> map1TextureCoord2State.isEnabled();
case GL11.GL_MAP1_TEXTURE_COORD_3 -> map1TextureCoord3State.isEnabled();
case GL11.GL_MAP1_TEXTURE_COORD_4 -> map1TextureCoord4State.isEnabled();
case GL11.GL_MAP1_VERTEX_3 -> map1Vertex3State.isEnabled();
case GL11.GL_MAP1_VERTEX_4 -> map1Vertex4State.isEnabled();
case GL11.GL_MAP2_COLOR_4 -> map2Color4State.isEnabled();
case GL11.GL_MAP2_INDEX -> map2IndexState.isEnabled();
case GL11.GL_MAP2_NORMAL -> map2NormalState.isEnabled();
case GL11.GL_MAP2_TEXTURE_COORD_1 -> map2TextureCoord1State.isEnabled();
case GL11.GL_MAP2_TEXTURE_COORD_2 -> map2TextureCoord2State.isEnabled();
case GL11.GL_MAP2_TEXTURE_COORD_3 -> map2TextureCoord3State.isEnabled();
case GL11.GL_MAP2_TEXTURE_COORD_4 -> map2TextureCoord4State.isEnabled();
case GL11.GL_MAP2_VERTEX_3 -> map2Vertex3State.isEnabled();
case GL11.GL_MAP2_VERTEX_4 -> map2Vertex4State.isEnabled();
case GL13.GL_MULTISAMPLE -> multisampleState.isEnabled();
case GL11.GL_NORMALIZE -> normalizeState.isEnabled();
case GL11.GL_POINT_SMOOTH -> pointSmoothState.isEnabled();
case GL11.GL_POLYGON_OFFSET_POINT -> polygonOffsetPointState.isEnabled();
case GL11.GL_POLYGON_OFFSET_LINE -> polygonOffsetLineState.isEnabled();
case GL11.GL_POLYGON_OFFSET_FILL -> polygonOffsetFillState.isEnabled();
case GL11.GL_POLYGON_SMOOTH -> polygonSmoothState.isEnabled();
case GL11.GL_POLYGON_STIPPLE -> polygonStippleState.isEnabled();
case GL12.GL_RESCALE_NORMAL -> rescaleNormalState.isEnabled();
case GL13.GL_SAMPLE_ALPHA_TO_COVERAGE -> sampleAlphaToCoverageState.isEnabled();
case GL13.GL_SAMPLE_ALPHA_TO_ONE -> sampleAlphaToOneState.isEnabled();
case GL13.GL_SAMPLE_COVERAGE -> sampleCoverageState.isEnabled();
case GL11.GL_SCISSOR_TEST -> scissorTest.isEnabled();
case GL11.GL_STENCIL_TEST -> stencilTest.isEnabled();
case GL11.GL_TEXTURE_1D -> textures.getTexture1DStates(activeTextureUnit.getValue()).isEnabled();
case GL11.GL_TEXTURE_2D -> textures.getTextureUnitStates(activeTextureUnit.getValue()).isEnabled();
case GL12.GL_TEXTURE_3D -> textures.getTexture3DStates(activeTextureUnit.getValue()).isEnabled();
case GL11.GL_TEXTURE_GEN_S -> textures.getTexGenSStates(activeTextureUnit.getValue()).isEnabled();
case GL11.GL_TEXTURE_GEN_T -> textures.getTexGenTStates(activeTextureUnit.getValue()).isEnabled();
case GL11.GL_TEXTURE_GEN_R -> textures.getTexGenRStates(activeTextureUnit.getValue()).isEnabled();
case GL11.GL_TEXTURE_GEN_Q -> textures.getTexGenQStates(activeTextureUnit.getValue()).isEnabled();
default -> GL11.glGetBoolean(pname);
};
}
@@ -997,7 +1249,7 @@ public class GLStateManager {
i = mipmap ? GL11.GL_LINEAR_MIPMAP_LINEAR : GL11.GL_LINEAR;
j = GL11.GL_LINEAR;
} else {
i = mipmap ? GL11.GL_NEAREST_MIPMAP_LINEAR : GL11.GL_NEAREST;
i = mipmap ? GL11.GL_LINEAR_MIPMAP_LINEAR : GL11.GL_NEAREST;
j = GL11.GL_NEAREST;
}
glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, i);
@@ -1885,6 +2137,20 @@ public class GLStateManager {
}
}
public static boolean vendorIsAMD() {
return VENDOR == AMD;
}
public static boolean vendorIsIntel() {
return VENDOR == INTEL;
}
public static boolean vendorIsMesa() {
return VENDOR == MESA;
}
public static boolean vendorIsNVIDIA() {
return VENDOR == NVIDIA;
}
}
@@ -0,0 +1,27 @@
package com.gtnewhorizons.angelica.glsm;
/// Matches
public enum Vendor {
AMD("amd"),
INTEL("intel"),
MESA("mesa"),
NVIDIA("nvidia"),
UNKNOWN("");
final String[] names;
Vendor(String... names) {
this.names = names;
}
public static Vendor getVendor(String vendorString) {
for (var v : values()) {
for (var name : v.names) {
if (vendorString.contains(name)) return v;
}
}
// Shouldn't be needed as "" matches everything, but sanity checks good.
return UNKNOWN;
}
}
@@ -12,7 +12,20 @@ public class BooleanStateStack extends BooleanState implements IStateStack<Boole
protected int pointer;
public BooleanStateStack(int glCap) {
// Most booleans default to false
this(glCap, false);
}
/**
* Create a BooleanStateStack with a custom initial state.
* Useful for GL states that default to true (e.g., GL_DITHER, GL_MULTISAMPLE).
*
* @param glCap GL capability constant
* @param initialState initial enabled state
*/
public BooleanStateStack(int glCap, boolean initialState) {
super(glCap);
this.enabled = initialState;
stack = new BooleanState[GLStateManager.MAX_ATTRIB_STACK_DEPTH];
for (int i = 0; i < GLStateManager.MAX_ATTRIB_STACK_DEPTH; i++) {
stack[i] = new BooleanState(glCap);
@@ -34,7 +47,7 @@ public class BooleanStateStack extends BooleanState implements IStateStack<Boole
}
set(stack[--pointer]);
if (GLStateManager.isAMD() && glCap == GL11.GL_BLEND) {
if (GLStateManager.vendorIsAMD() && glCap == GL11.GL_BLEND) {
setEnabled(enabled);
}
return this;
@@ -22,7 +22,7 @@ public class BooleanState implements ISettableState<BooleanState> {
}
public void setEnabled(boolean enabled) {
if (GLStateManager.shouldBypassCache() || enabled != this.enabled || (this.glCap == GL11.GL_BLEND && GLStateManager.isAMD() && GLStateManager.isPoppingAttributes())) {
if (GLStateManager.shouldBypassCache() || enabled != this.enabled || (this.glCap == GL11.GL_BLEND && GLStateManager.vendorIsAMD() && GLStateManager.isPoppingAttributes())) {
this.enabled = enabled;
if (enabled) {
GL11.glEnable(this.glCap);
@@ -124,7 +124,7 @@ public class MaterialState implements ISettableState<MaterialState> {
// glMaterial specifically for GL_COLOR_INDEXES. Other drivers do not do this.
// This probably breaks things but who knows, GLSM is setup to track to what the
// driver is doing for it right now.
if (GLStateManager.isNVIDIA()) {
if (GLStateManager.vendorIsNVIDIA()) {
vector3f.set(newBuffer.get(0), newBuffer.get(2), newBuffer.get(1));
} else {
vector3f.set(newBuffer);
@@ -6,21 +6,40 @@ import com.gtnewhorizons.angelica.glsm.stacks.TextureBindingStack;
import lombok.Getter;
import org.joml.Matrix4fStack;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
public class TextureUnitArray {
private final TextureBindingStack[] bindings;
private final BooleanStateStack[] states;
private final BooleanStateStack[] texture1DStates;
private final BooleanStateStack[] texture3DStates;
private final BooleanStateStack[] texGenSStates;
private final BooleanStateStack[] texGenTStates;
private final BooleanStateStack[] texGenRStates;
private final BooleanStateStack[] texGenQStates;
@Getter
public final Matrix4fStack[] textureMatricies;
public TextureUnitArray() {
bindings = new TextureBindingStack[GLStateManager.MAX_TEXTURE_UNITS];
states = new BooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS];
texture1DStates = new BooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS];
texture3DStates = new BooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS];
texGenSStates = new BooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS];
texGenTStates = new BooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS];
texGenRStates = new BooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS];
texGenQStates = new BooleanStateStack[GLStateManager.MAX_TEXTURE_UNITS];
textureMatricies = new Matrix4fStack[GLStateManager.MAX_TEXTURE_UNITS];
for (int i = 0; i < GLStateManager.MAX_TEXTURE_UNITS; i++) {
bindings[i] = new TextureBindingStack();
states[i] = new BooleanStateStack(GL11.GL_TEXTURE_2D);
texture1DStates[i] = new BooleanStateStack(GL11.GL_TEXTURE_1D);
texture3DStates[i] = new BooleanStateStack(GL12.GL_TEXTURE_3D);
texGenSStates[i] = new BooleanStateStack(GL11.GL_TEXTURE_GEN_S);
texGenTStates[i] = new BooleanStateStack(GL11.GL_TEXTURE_GEN_T);
texGenRStates[i] = new BooleanStateStack(GL11.GL_TEXTURE_GEN_R);
texGenQStates[i] = new BooleanStateStack(GL11.GL_TEXTURE_GEN_Q);
textureMatricies[i] = new Matrix4fStack(GLStateManager.MAX_TEXTURE_STACK_DEPTH);
}
}
@@ -33,6 +52,30 @@ public class TextureUnitArray {
return states[index];
}
public BooleanStateStack getTexture1DStates(int index) {
return texture1DStates[index];
}
public BooleanStateStack getTexture3DStates(int index) {
return texture3DStates[index];
}
public BooleanStateStack getTexGenSStates(int index) {
return texGenSStates[index];
}
public BooleanStateStack getTexGenTStates(int index) {
return texGenTStates[index];
}
public BooleanStateStack getTexGenRStates(int index) {
return texGenRStates[index];
}
public BooleanStateStack getTexGenQStates(int index) {
return texGenQStates[index];
}
public Matrix4fStack getTextureUnitMatrix(int index) {
return textureMatricies[index];
}
@@ -44,6 +87,12 @@ public class TextureUnitArray {
for (int i = 0; i < GLStateManager.MAX_TEXTURE_UNITS; i++) {
if (!bindings[i].sameAs(textureUnitArray.bindings[i])) return false;
if (!states[i].sameAs(textureUnitArray.states[i])) return false;
if (!texture1DStates[i].sameAs(textureUnitArray.texture1DStates[i])) return false;
if (!texture3DStates[i].sameAs(textureUnitArray.texture3DStates[i])) return false;
if (!texGenSStates[i].sameAs(textureUnitArray.texGenSStates[i])) return false;
if (!texGenTStates[i].sameAs(textureUnitArray.texGenTStates[i])) return false;
if (!texGenRStates[i].sameAs(textureUnitArray.texGenRStates[i])) return false;
if (!texGenQStates[i].sameAs(textureUnitArray.texGenQStates[i])) return false;
}
return true;
}
@@ -12,7 +12,7 @@ public class TextureInfo {
protected int width = -1;
protected int height = -1;
@Getter @Setter protected int minFilter = GL11.GL_NEAREST_MIPMAP_LINEAR;
@Getter @Setter protected int minFilter = GL11.GL_LINEAR_MIPMAP_LINEAR;
@Getter @Setter protected int magFilter = GL11.GL_LINEAR;
@Getter @Setter protected int wrapS = GL11.GL_REPEAT;
@Getter @Setter protected int wrapT = GL11.GL_REPEAT;
@@ -87,7 +87,7 @@ public final class AngelicaRedirector {
"net/minecraft/block/material/"
};
private static final ClassConstantPoolParser cstPoolParser = new ClassConstantPoolParser(GL11, GL13, GL14, OpenGlHelper, EXTBlendFunc, ARBMultiTexture, BlockPackage, Project);
private static final ClassConstantPoolParser cstPoolParser = new ClassConstantPoolParser(GL11, GL13, GL14, GL20, OpenGlHelper, EXTBlendFunc, ARBMultiTexture, BlockPackage, Project);
private static final Map<String, Map<String, String>> methodRedirects = new HashMap<>();
private static final Map<Integer, String> glCapRedirects = new HashMap<>();
@@ -39,8 +39,10 @@ public class Zoom {
}
private static void resetMouseFilters(Minecraft mc) {
((IMouseFilterExt) mc.entityRenderer.mouseFilterXAxis).angelica$reset();
((IMouseFilterExt) mc.entityRenderer.mouseFilterYAxis).angelica$reset();
if (mc.entityRenderer != null) {
((IMouseFilterExt) mc.entityRenderer.mouseFilterXAxis).angelica$reset();
((IMouseFilterExt) mc.entityRenderer.mouseFilterYAxis).angelica$reset();
}
}
public static void resetZoom() {
@@ -74,7 +74,7 @@ public class MipmapHelper {
int mipmaps = useMipmapsForTexture(textureName) ? getMipmapLevels(width, height, 1) : 0;
logger.finer("setupTexture(%s) %dx%d %d mipmaps", textureName, width, height, mipmaps);
int magFilter = blur ? GL11.GL_LINEAR : GL11.GL_NEAREST;
int minFilter = mipmaps > 0 ? GL11.GL_NEAREST_MIPMAP_LINEAR : magFilter;
int minFilter = mipmaps > 0 ? GL11.GL_LINEAR_MIPMAP_LINEAR : magFilter;
int wrap = clamp ? GL11.GL_CLAMP : GL11.GL_REPEAT;
if (mipmaps > 0) {
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL12.GL_TEXTURE_MAX_LEVEL, mipmaps);
@@ -311,20 +311,18 @@ public class TexturePackAPI {
public static void flushUnusedTextures() {
TextureManager textureManager = Minecraft.getMinecraft().getTextureManager();
if (textureManager != null) {
Set<ResourceLocation> texturesToUnload = new HashSet<>();
@SuppressWarnings("unchecked")
Set<Map.Entry<ResourceLocation, ITextureObject>> entrySet = textureManager.mapTextureObjects.entrySet();
for (Map.Entry<ResourceLocation, ITextureObject> entry : entrySet) {
ResourceLocation resource = entry.getKey();
Map.Entry<ResourceLocation, ITextureObject>[] arr = (Map.Entry<ResourceLocation, ITextureObject>[])
textureManager.mapTextureObjects.entrySet().toArray(new Map.Entry[0]);
for (Map.Entry<ResourceLocation, ITextureObject> entry : arr) {
ITextureObject texture = entry.getValue();
if (texture instanceof SimpleTexture && !(texture instanceof ThreadDownloadImageData)
&& !TexturePackAPI.hasResource(resource)) {
texturesToUnload.add(resource);
if (texture instanceof SimpleTexture && !(texture instanceof ThreadDownloadImageData)) {
ResourceLocation resource = entry.getKey();
if (!TexturePackAPI.hasResource(resource)) {
unloadTexture(resource);
}
}
}
for (ResourceLocation resource : texturesToUnload) {
unloadTexture(resource);
}
}
}
@@ -35,6 +35,24 @@ public class StandardMacros {
defines.add(new StringPair(key, value));
}
private static String makeAngelicaVersion()
{
String[] parts = Tags.VERSION.split("[.-]");
int major = Integer.parseInt(parts[0]);
int minor = Integer.parseInt(parts[1]);
int patch = Integer.parseInt(parts[2]);
int sub = 0;
// Handle optional prerelease (like beta62)
if (parts.length > 3) {
String pre = parts[3];
String num = pre.replaceAll("\\D+", ""); // remove all non-digits
if (!num.isEmpty())
sub = Integer.parseInt(num);
}
return String.format("%d%02d%02d%03d", major, minor, patch, sub);
}
public static Iterable<StringPair> createStandardEnvironmentDefines() {
ArrayList<StringPair> standardDefines = new ArrayList<>();
@@ -54,7 +72,7 @@ public class StandardMacros {
define(standardDefines, "MC_RENDER_QUALITY", "1.0");
define(standardDefines, "MC_SHADOW_QUALITY", "1.0");
define(standardDefines, "IS_ANGELICA");
define(standardDefines, "ANGELICA_VERSION", Tags.VERSION);
define(standardDefines, "ANGELICA_VERSION", makeAngelicaVersion());
define(standardDefines, "MC_HAND_DEPTH", Float.toString(HandRenderer.DEPTH));
TextureFormat textureFormat = TextureFormatLoader.getFormat();
@@ -175,7 +175,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
final Framebuffer main = Minecraft.getMinecraft().getFramebuffer();
final int depthTextureId = ((IRenderTargetExt)main).getIris$depthTextureId();
final int depthTextureId = ((IRenderTargetExt)main).iris$getDepthTextureId();
final int internalFormat = TextureInfoCache.INSTANCE.getInfo(depthTextureId).getInternalFormat();
final DepthBufferFormat depthBufferFormat = DepthBufferFormat.fromGlEnumOrDefault(internalFormat);
@@ -911,7 +911,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
final Framebuffer main = Minecraft.getMinecraft().getFramebuffer();
final int depthTextureId = ((IRenderTargetExt)main).getIris$depthTextureId();
final int depthTextureId = ((IRenderTargetExt)main).iris$getDepthTextureId();
final int internalFormat = TextureInfoCache.INSTANCE.getInfo(depthTextureId).getInternalFormat();
final DepthBufferFormat depthBufferFormat = DepthBufferFormat.fromGlEnumOrDefault(internalFormat);
@@ -222,6 +222,10 @@ public class ShaderTransformer {
for (var entry : types.entrySet()) {
String formattedShader = getFormattedShader(entry.getValue(), prepatched.get(entry.getKey()));
// Restore identifiers that were temporarily renamed to dodge GLSL reserved keywords.
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
@@ -101,23 +101,23 @@ public class FinalPassRenderer {
// TODO: We don't actually fully swap the content, we merely copy it from alt to main
// This works for the most part, but it's not perfect. A better approach would be creating secondary
// framebuffers for every other frame, but that would be a lot more complex...
ImmutableList.Builder<SwapPass> swapPasses = ImmutableList.builder();
flippedBuffers.forEach(i -> {
int target = i;
final ImmutableList.Builder<SwapPass> swapPasses = ImmutableList.builder();
flippedBuffers.forEach((i) -> {
final int target = i;
if (buffersToBeCleared.contains(target)) {
return;
}
SwapPass swap = new SwapPass();
RenderTarget target1 = renderTargets.get(target);
final SwapPass swap = new SwapPass();
final RenderTarget target1 = renderTargets.get(target);
swap.target = target;
swap.width = target1.getWidth();
swap.height = target1.getHeight();
// Non-flipped buffers write to ALT, copy ALT→MAIN to preserve data
swap.from = renderTargets.createColorFramebuffer(ImmutableSet.of(), new int[] {target});
// NB: This is handled in RenderTargets now.
//swap.from.readBuffer(target);
swap.targetTexture = renderTargets.get(target).getMainTexture();
swapPasses.add(swap);
@@ -264,8 +264,10 @@ public class FinalPassRenderer {
public void recalculateSwapPassSize() {
for (SwapPass swapPass : swapPasses) {
RenderTarget target = renderTargets.get(swapPass.target);
final RenderTarget target = renderTargets.get(swapPass.target);
renderTargets.destroyFramebuffer(swapPass.from);
// Match constructor logic - swap passes are only for non-flipped buffers
// Copy ALT→MAIN to preserve data written to ALT
swapPass.from = renderTargets.createColorFramebuffer(ImmutableSet.of(), new int[] {swapPass.target});
swapPass.width = target.getWidth();
swapPass.height = target.getHeight();
@@ -274,7 +276,7 @@ public class FinalPassRenderer {
}
private static void setupMipmapping(RenderTarget target, boolean readFromAlt) {
int texture = readFromAlt ? target.getAltTexture() : target.getMainTexture();
final 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)
@@ -319,13 +321,13 @@ public class FinalPassRenderer {
source.getVertexSource().orElseThrow(NullPointerException::new),
source.getGeometrySource().orElse(null),
source.getFragmentSource().orElseThrow(NullPointerException::new));
String vertex = transformed.get(PatchShaderType.VERTEX);
String geometry = transformed.get(PatchShaderType.GEOMETRY);
String fragment = transformed.get(PatchShaderType.FRAGMENT);
final String vertex = transformed.get(PatchShaderType.VERTEX);
final String geometry = transformed.get(PatchShaderType.GEOMETRY);
final String fragment = transformed.get(PatchShaderType.FRAGMENT);
PatchedShaderPrinter.debugPatchedShaders(source.getName(), vertex, geometry, fragment);
Objects.requireNonNull(flipped);
ProgramBuilder builder;
final ProgramBuilder builder;
try {
builder = ProgramBuilder.begin(source.getName(), vertex, geometry, fragment,
@@ -337,7 +339,7 @@ public class FinalPassRenderer {
this.customUniforms.assignTo(builder);
ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureIds, flippedAtLeastOnceSnapshot);
final ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureIds, flippedAtLeastOnceSnapshot);
CommonUniforms.addDynamicUniforms(builder);
IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> flipped, renderTargets, true);
@@ -361,15 +363,15 @@ public class FinalPassRenderer {
}
private ComputeProgram[] createComputes(ComputeSource[] compute, ImmutableSet<Integer> flipped, ImmutableSet<Integer> flippedAtLeastOnceSnapshot, Supplier<ShadowRenderTargets> shadowTargetsSupplier) {
ComputeProgram[] programs = new ComputeProgram[compute.length];
final ComputeProgram[] programs = new ComputeProgram[compute.length];
for (int i = 0; i < programs.length; i++) {
ComputeSource source = compute[i];
final ComputeSource source = compute[i];
if (source == null || !source.getSource().isPresent()) {
continue;
} else {
// TODO: Properly handle empty shaders
Objects.requireNonNull(flipped);
ProgramBuilder builder;
final ProgramBuilder builder;
try {
builder = ProgramBuilder.beginCompute(source.getName(), source.getSource().orElse(null), IrisSamplers.COMPOSITE_RESERVED_TEXTURE_UNITS);
@@ -5,6 +5,5 @@ public interface IRenderTargetExt {
int iris$getColorBufferVersion();
public boolean getIris$useDepth();
public int getIris$depthTextureId();
int iris$getDepthTextureId();
}
@@ -4,6 +4,9 @@ import net.minecraft.util.ResourceLocation;
import org.apache.commons.io.FilenameUtils;
import org.jetbrains.annotations.Nullable;
import java.net.URI;
import java.net.URISyntaxException;
public enum PBRType {
NORMAL("_n", 0x7F7FFFFF),
SPECULAR("_s", 0x00000000);
@@ -26,17 +29,37 @@ public enum PBRType {
return defaultValue;
}
public ResourceLocation appendToFileLocation(ResourceLocation location) {
String path = location.getResourcePath();
String newPath;
int extensionIndex = FilenameUtils.indexOfExtension(path);
if (extensionIndex != -1) {
newPath = path.substring(0, extensionIndex) + suffix + path.substring(extensionIndex);
} else {
newPath = path + suffix;
}
return new ResourceLocation(location.getResourceDomain(), newPath);
}
public ResourceLocation appendToFileLocation(ResourceLocation location) {
String domain = location.getResourceDomain();
String path = location.getResourcePath();
String newPath;
try {
URI uri = new URI(null, null, path, null);
String cleanPath = uri.getPath();
int extensionIndex = FilenameUtils.indexOfExtension(cleanPath);
if (extensionIndex != -1) {
newPath = cleanPath.substring(0, extensionIndex) + suffix + cleanPath.substring(extensionIndex);
} else {
newPath = cleanPath + suffix;
}
URI newUri = new URI(null, null, newPath, null);
newPath = newUri.getPath();
} catch (URISyntaxException e) {
String fallback = path.replace(':', '/');
int extensionIndex = FilenameUtils.indexOfExtension(fallback);
if (extensionIndex != -1) {
newPath = fallback.substring(0, extensionIndex) + suffix + fallback.substring(extensionIndex);
} else {
newPath = fallback + suffix;
}
}
return new ResourceLocation(domain, newPath);
}
/**
* Returns the PBR type corresponding to the suffix of the given file location.
@@ -103,7 +103,11 @@ public class AtlasPBRLoader implements PBRTextureLoader<TextureMap> {
NativeImage nativeImage = NativeImage.read(resource.getInputStream());
AnimationMetadataSection animationMetadata = (AnimationMetadataSection) resource.getMetadata("animation");
if (animationMetadata == null) {
animationMetadata = new AnimationMetadataSection(Lists.newArrayList(), -1, -1, -1);
final IResource resourceOriginal = resourceManager.getResource(imageLocation);
animationMetadata = (AnimationMetadataSection) resourceOriginal.getMetadata("animation");
if (animationMetadata == null) {
animationMetadata = new AnimationMetadataSection(Lists.newArrayList(), -1, -1, -1);
}
}
final Pair<Integer, Integer> frameSize = this.getFrameSize(nativeImage.getWidth(), nativeImage.getHeight(), animationMetadata);
@@ -28,11 +28,13 @@ float txSample(vec2 uv, float du, float dv, float factorU, float factorV) {
void main() {
vec2 texCoords = gl_TexCoord[0].st;
vec2 texScaled = texCoords * strength;
vec4 col = color;
float original_alpha = col.a;
if (texCoords.s != 0 || texCoords.t != 0) {
float res = 0;
float fu = strength * fwidth(texCoords.x);
float fv = strength * fwidth(texCoords.y);
float fu = abs(dFdx(texScaled.x)) + abs(dFdy(texScaled.x));
float fv = abs(dFdx(texScaled.y)) + abs(dFdy(texScaled.y));
totalWt = 0;
if (aaMode == 1) {
res += txSample(texCoords, 2, 6, fu, fv);
@@ -58,7 +60,7 @@ void main() {
res += txSample(texCoords, -7, -8, fu, fv);
}
res /= totalWt;
col.a = res;
col.a = original_alpha * res;
}
gl_FragColor = col;
@@ -1,6 +1,7 @@
package com.gtnewhorizons.angelica.mixins.early.shaders;
import com.gtnewhorizons.angelica.compat.mojang.Camera;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import com.llamalad7.mixinextras.sugar.Share;
@@ -21,7 +22,6 @@ import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.resources.IResourceManagerReloadListener;
import net.minecraft.client.settings.GameSettings;
import net.minecraft.entity.EntityLivingBase;
import org.lwjgl.opengl.GL11;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
@@ -55,6 +55,7 @@ public abstract class MixinEntityRenderer implements IResourceManagerReloadListe
pipeline.get().finalizeLevelRendering();
pipeline.set(null);
Program.unbind();
GLStateManager.glDepthMask(true);
}
@WrapOperation(method = "renderHand", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/ItemRenderer;renderItemInFirstPerson(F)V"))
@@ -100,7 +101,7 @@ public abstract class MixinEntityRenderer implements IResourceManagerReloadListe
private void iris$beginWeatherAndwriteRainAndSnowToDepthBuffer(float partialTicks, long startTime, CallbackInfo ci, @Share("pipeline") LocalRef<WorldRenderingPipeline> pipeline) {
pipeline.get().setPhase(WorldRenderingPhase.RAIN_SNOW);
if (pipeline.get().shouldWriteRainAndSnowToDepthBuffer()) {
GL11.glDepthMask(true);
GLStateManager.glDepthMask(true);
}
}
@@ -1,7 +1,6 @@
package com.gtnewhorizons.angelica.mixins.early.shaders;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import lombok.Getter;
import net.coderbot.iris.rendertarget.IRenderTargetExt;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.shader.Framebuffer;
@@ -11,20 +10,22 @@ import org.lwjgl.opengl.GL14;
import org.lwjgl.opengl.GL30;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.nio.IntBuffer;
@Mixin(Framebuffer.class)
public abstract class MixinFramebuffer implements IRenderTargetExt {
private int iris$depthBufferVersion;
public class MixinFramebuffer implements IRenderTargetExt {
private int iris$colorBufferVersion;
@Unique private int iris$depthBufferVersion;
@Getter public boolean iris$useDepth;
@Getter public int iris$depthTextureId = -1;
@Unique private int iris$colorBufferVersion;
@Unique public int iris$depthTextureId = -1;
@Shadow public boolean useDepth;
@@ -45,16 +46,12 @@ public abstract class MixinFramebuffer implements IRenderTargetExt {
return iris$colorBufferVersion;
}
// Use a depth texture instead of a depth drawScreen buffer
@Inject(method="Lnet/minecraft/client/shader/Framebuffer;createBindFramebuffer(II)V", at=@At(value="HEAD"))
private void iris$useDepthTexture(int width, int height, CallbackInfo ci) {
if(this.useDepth) {
this.useDepth = false;
this.iris$useDepth = true;
}
@Override
public int iris$getDepthTextureId() {
return iris$depthTextureId;
}
@Inject(method="deleteFramebuffer()V", at=@At(value="FIELD", target="Lnet/minecraft/client/shader/Framebuffer;depthBuffer:I", shift = At.Shift.BEFORE, ordinal = 0))
@Inject(method="deleteFramebuffer()V", at=@At(value="FIELD", target="Lnet/minecraft/client/shader/Framebuffer;depthBuffer:I", shift = At.Shift.BEFORE, ordinal = 0), require = 1)
private void iris$deleteDepthBuffer(CallbackInfo ci) {
if(this.iris$depthTextureId > -1 ) {
GLStateManager.glDeleteTextures(this.iris$depthTextureId);
@@ -62,19 +59,17 @@ public abstract class MixinFramebuffer implements IRenderTargetExt {
}
}
@Inject(method="createFramebuffer(II)V", at=@At(value="FIELD", target="Lnet/minecraft/client/shader/Framebuffer;useDepth:Z", shift=At.Shift.BEFORE, ordinal = 0))
private void iris$createDepthTextureID(int width, int height, CallbackInfo ci) {
if (this.iris$useDepth) {
this.iris$depthTextureId = GL11.glGenTextures();
}
// Prevent the creation of a depth buffer, it will get replaced by a depth texture.
@Redirect(method = "createFramebuffer", at = @At(value = "FIELD", target = "Lnet/minecraft/client/shader/Framebuffer;useDepth:Z"))
private boolean iris$noopDepthBuffer(Framebuffer instance) {
return false;
}
@Inject(method="createFramebuffer(II)V", at=@At(value="FIELD", target="Lnet/minecraft/client/shader/Framebuffer;useDepth:Z", shift=At.Shift.BEFORE, ordinal = 1))
// Uses a depth texture instead of a depth buffer
@Inject(method = "createFramebuffer", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/shader/Framebuffer;framebufferClear()V", shift = At.Shift.BEFORE, ordinal = 1), require = 1)
private void iris$createDepthTexture(int width, int height, CallbackInfo ci) {
if(this.iris$useDepth) {
if(this.iris$depthTextureId == -1) {
this.iris$depthTextureId = GL11.glGenTextures();
}
if(this.useDepth) {
this.iris$depthTextureId = GL11.glGenTextures();
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, this.iris$depthTextureId);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST);
@@ -82,14 +77,15 @@ public abstract class MixinFramebuffer implements IRenderTargetExt {
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_CLAMP);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_CLAMP);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_COMPARE_MODE, 0);
if (MinecraftForgeClient.getStencilBits() != 0) {
final boolean stencil = MinecraftForgeClient.getStencilBits() != 0;
if (stencil) {
GLStateManager.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL30.GL_DEPTH24_STENCIL8, width, height, 0, GL30.GL_DEPTH_STENCIL, GL30.GL_UNSIGNED_INT_24_8, (IntBuffer) null);
} else {
GLStateManager.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_DEPTH_COMPONENT, width, height, 0, GL11.GL_DEPTH_COMPONENT, GL11.GL_FLOAT, (IntBuffer) null);
}
OpenGlHelper.func_153188_a/*glFramebufferTexture2D*/(GL30.GL_FRAMEBUFFER, GL30.GL_DEPTH_ATTACHMENT, GL11.GL_TEXTURE_2D, this.iris$depthTextureId, 0);
if (MinecraftForgeClient.getStencilBits() != 0) {
OpenGlHelper.func_153188_a/*glFramebufferTexture2D*/(GL30.GL_FRAMEBUFFER, GL30.GL_STENCIL_ATTACHMENT, GL11.GL_TEXTURE_2D, this.iris$depthTextureId, 0);
OpenGlHelper.func_153188_a(GL30.GL_FRAMEBUFFER, GL30.GL_DEPTH_ATTACHMENT, GL11.GL_TEXTURE_2D, this.iris$depthTextureId, 0);
if (stencil) {
OpenGlHelper.func_153188_a(GL30.GL_FRAMEBUFFER, GL30.GL_STENCIL_ATTACHMENT, GL11.GL_TEXTURE_2D, this.iris$depthTextureId, 0);
}
}
}
@@ -223,6 +223,7 @@ public class MixinRenderGlobal implements IRenderGlobalExt {
boolean hasForcedFrustum = false;
boolean spectator = isSpectatorMode();
Camera camera = new Camera(mc.renderViewEntity, partialTicks);
frustum.setPosition(camera.getPos().x, camera.getPos().y, camera.getPos().z);
try {
this.renderer.updateChunks(camera, frustum, hasForcedFrustum, sodium$frame++, spectator);
@@ -295,7 +295,7 @@ public class GLSM_Lighting_UnitTest {
GLStateManager.glPushAttrib(GL11.GL_LIGHTING_BIT);
newf4b(0.8F, 0.6F, 0.4F, 0.0F);
GLStateManager.glMaterial(GL11.GL_FRONT, GL11.GL_COLOR_INDEXES, f4b);
if (GLStateManager.isNVIDIA()) {
if (GLStateManager.vendorIsNVIDIA()) {
verifyMaterialState(GL11.GL_FRONT, GL11.GL_COLOR_INDEXES, new float[]{0.8F, 0.4F, 0.6F}, "");
} else {
verifyMaterialState(GL11.GL_FRONT, GL11.GL_COLOR_INDEXES, new float[]{0.8F, 0.6F, 0.4F}, "");
@@ -2,6 +2,8 @@ package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizons.angelica.AngelicaExtension;
import com.gtnewhorizons.angelica.util.GLBit;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.lwjgl.BufferUtils;
@@ -14,6 +16,7 @@ import org.lwjgl.opengl.GL20;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import static com.gtnewhorizons.angelica.util.GLSMUtil.resetGLState;
import static com.gtnewhorizons.angelica.util.GLSMUtil.verifyIsEnabled;
import static com.gtnewhorizons.angelica.util.GLSMUtil.verifyLightState;
import static com.gtnewhorizons.angelica.util.GLSMUtil.verifyNotDefaultState;
@@ -22,6 +25,18 @@ import static com.gtnewhorizons.angelica.util.GLSMUtil.verifyState;
@ExtendWith(AngelicaExtension.class)
class GLSM_PushPop_UnitTest {
@BeforeEach
void setUp() {
// Reset GL state before each test to ensure clean starting point
resetGLState();
}
@AfterEach
void tearDown() {
// Reset GL state after each test to prevent contamination
resetGLState();
}
public static final boolean[] BOOLEAN_ARRAY_4_TRUE = { true, true, true, true };
public static final boolean[] BOOLEAN_ARRAY_4_FALSE = { false, false, false, false };
public static final float[] FLOAT_ARRAY_3_001 = { 0f, 0f, 1f };
@@ -103,17 +118,13 @@ class GLSM_PushPop_UnitTest {
verifyState(GL14.GL_BLEND_EQUATION, GL14.GL_FUNC_ADD, "Blend Equation - Reset");
verifyState(GL20.GL_BLEND_EQUATION_ALPHA, GL14.GL_FUNC_ADD, "Blend Equation Alpha - Reset");
verifyIsEnabled(GL11.GL_DITHER, true, "Dither Enable - Reset");
verifyState(GL11.GL_DRAW_BUFFER, GL11.GL_BACK, "Draw Buffer - Reset");
verifyState(GL11.GL_DRAW_BUFFER, GLStateManager.DEFAULT_DRAW_BUFFER, "Draw Buffer - Reset");
verifyIsEnabled(GL11.GL_COLOR_LOGIC_OP, false, "Color Logic Op Enable - Reset");
verifyIsEnabled(GL11.GL_INDEX_LOGIC_OP, false, "Index Logic Op Enable - Reset");
verifyState(GL11.GL_LOGIC_OP_MODE, GL11.GL_COPY, "Logic Op Mode - Reset");
verifyState(GL11.GL_CURRENT_COLOR, FLOAT_ARRAY_4_POINT_5, "Current Color - (Not) Reset"); // This does not get reset
verifyState(GL11.GL_COLOR_WRITEMASK, BOOLEAN_ARRAY_4_TRUE, "Color Write Mask - Reset");
verifyState(GL11.GL_COLOR_CLEAR_VALUE, FLOAT_ARRAY_4_0, "Color Clear Value - Reset");
// Reset State
GLStateManager.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
}
@Test
@@ -205,8 +216,8 @@ class GLSM_PushPop_UnitTest {
bits.add(new GLBit(GL11.GL_DITHER, "Dither", true));
bits.add(new GLBit(GL11.GL_FOG, "Fog", false));
// This fails on the RESET test in xvfb
if(!(GLStateManager.MESA || GLStateManager.AMD)) {
for(i = 0 ; i < GL11.glGetInteger(GL11.GL_MAX_LIGHTS) ; i++) {
if (!(GLStateManager.vendorIsMesa() || GLStateManager.vendorIsAMD())) {
for (i = 0; i < GL11.glGetInteger(GL11.GL_MAX_LIGHTS); i++) {
bits.add(new GLBit(GL11.GL_LIGHT0 + i, "Light " + i, false));
}
}
@@ -236,7 +247,7 @@ class GLSM_PushPop_UnitTest {
bits.add(new GLBit(GL11.GL_MAP2_TEXTURE_COORD_3, "Map2 Texture Coord 3", false));
bits.add(new GLBit(GL11.GL_MAP2_TEXTURE_COORD_4, "Map2 Texture Coord 4", false));
// Seems to be broken at least on Nvidia
if(!GLStateManager.NVIDIA) bits.add(new GLBit(GL13.GL_MULTISAMPLE, "Multisample", true));
if (!GLStateManager.vendorIsNVIDIA()) bits.add(new GLBit(GL13.GL_MULTISAMPLE, "Multisample", true));
bits.add(new GLBit(GL11.GL_NORMALIZE, "Normalize", false));
bits.add(new GLBit(GL11.GL_POINT_SMOOTH, "Point Smooth", false));
bits.add(new GLBit(GL11.GL_POLYGON_OFFSET_LINE, "Polygon Offset Line", false));
@@ -244,6 +255,7 @@ class GLSM_PushPop_UnitTest {
bits.add(new GLBit(GL11.GL_POLYGON_OFFSET_POINT, "Polygon Offset Point", false));
bits.add(new GLBit(GL11.GL_POLYGON_SMOOTH, "Polygon Smooth", false));
bits.add(new GLBit(GL11.GL_POLYGON_STIPPLE, "Polygon Stipple", false));
bits.add(new GLBit(GL12.GL_RESCALE_NORMAL, "Rescale Normal", false));
bits.add(new GLBit(GL13.GL_SAMPLE_ALPHA_TO_COVERAGE, "Sample Alpha To Coverage", false));
bits.add(new GLBit(GL13.GL_SAMPLE_ALPHA_TO_ONE, "Sample Alpha To One", false));
bits.add(new GLBit(GL13.GL_SAMPLE_COVERAGE, "Sample Coverage", false));
@@ -270,17 +282,7 @@ class GLSM_PushPop_UnitTest {
GLStateManager.glPopAttrib();
//glEnable(GL_COLOR_MATERIAL) changes the material color state when it is triggered. We need to reset that
//here to not mess up the default state for other tests. We're not resetting with glPush/PopAttrib because
//we're specifically trying to test GL_ENABLE_BIT here.
FloatBuffer floatBuffer = BufferUtils.createFloatBuffer(16);
floatBuffer.put(0.2F).put(0.2F).put(0.2F).put(1.0F).flip();
GLStateManager.glMaterial(GL11.GL_FRONT_AND_BACK, GL11.GL_AMBIENT, floatBuffer);
floatBuffer.put(0.8F).put(0.8F).put(0.8F).put(1.0F).flip();
GLStateManager.glMaterial(GL11.GL_FRONT_AND_BACK, GL11.GL_DIFFUSE, floatBuffer);
bits.forEach(bit -> verifyState(bit.glEnum(), bit.initial(), bit.name() + " Reset State"));
}
@Test
@@ -295,7 +297,7 @@ class GLSM_PushPop_UnitTest {
GLStateManager.glFogf(GL11.GL_FOG_END, 0.5f);
GLStateManager.glFogf(GL11.GL_FOG_START, 0.5f);
GLStateManager.glFogf(GL11.GL_FOG_MODE, GL11.GL_LINEAR);
if(!GLStateManager.NVIDIA) GLStateManager.glFogf(GL11.GL_FOG_INDEX, 1f);
if (!GLStateManager.vendorIsNVIDIA()) GLStateManager.glFogf(GL11.GL_FOG_INDEX, 1f);
verifyIsEnabled(GL11.GL_FOG, true, "Fog Enable");
verifyState(GL11.GL_FOG_COLOR, FLOAT_ARRAY_4_POINT_5, "Fog Color");
@@ -303,7 +305,7 @@ class GLSM_PushPop_UnitTest {
verifyState(GL11.GL_FOG_END, 0.5f, "Fog End");
verifyState(GL11.GL_FOG_START, 0.5f, "Fog Start");
verifyState(GL11.GL_FOG_MODE, GL11.GL_LINEAR, "Fog Mode");
if(!GLStateManager.NVIDIA) verifyState(GL11.GL_FOG_INDEX, 1f, "Fog Index");
if (!GLStateManager.vendorIsNVIDIA()) verifyState(GL11.GL_FOG_INDEX, 1f, "Fog Index");
GLStateManager.glPopAttrib();
verifyIsEnabled(GL11.GL_FOG, false, "Fog Enable - Reset");
@@ -312,7 +314,7 @@ class GLSM_PushPop_UnitTest {
verifyState(GL11.GL_FOG_END, 1f, "Fog End - Reset");
verifyState(GL11.GL_FOG_START, 0f, "Fog Start - Reset");
verifyState(GL11.GL_FOG_MODE, GL11.GL_EXP, "Fog Mode - Reset");
if(!GLStateManager.NVIDIA) verifyState(GL11.GL_FOG_INDEX, 0f, "Fog Index - Reset");
if (!GLStateManager.vendorIsNVIDIA()) verifyState(GL11.GL_FOG_INDEX, 0f, "Fog Index - Reset");
}
@Test
@@ -3,6 +3,8 @@ package com.gtnewhorizons.angelica.util;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL13;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
@@ -15,6 +17,27 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals;
public class GLSMUtil {
// Cached GL limits (queried once at class load time)
private static final int MAX_CLIP_PLANES = GL11.glGetInteger(GL11.GL_MAX_CLIP_PLANES);
private static final int MAX_LIGHTS = GL11.glGetInteger(GL11.GL_MAX_LIGHTS);
private static final int MAX_TEXTURE_UNITS = GL11.glGetInteger(GL13.GL_MAX_TEXTURE_UNITS);
// MAP1 evaluator constants for DRY loops
private static final int[] MAP1_STATES = {
GL11.GL_MAP1_COLOR_4, GL11.GL_MAP1_INDEX, GL11.GL_MAP1_NORMAL,
GL11.GL_MAP1_TEXTURE_COORD_1, GL11.GL_MAP1_TEXTURE_COORD_2,
GL11.GL_MAP1_TEXTURE_COORD_3, GL11.GL_MAP1_TEXTURE_COORD_4,
GL11.GL_MAP1_VERTEX_3, GL11.GL_MAP1_VERTEX_4
};
// MAP2 evaluator constants for DRY loops
private static final int[] MAP2_STATES = {
GL11.GL_MAP2_COLOR_4, GL11.GL_MAP2_INDEX, GL11.GL_MAP2_NORMAL,
GL11.GL_MAP2_TEXTURE_COORD_1, GL11.GL_MAP2_TEXTURE_COORD_2,
GL11.GL_MAP2_TEXTURE_COORD_3, GL11.GL_MAP2_TEXTURE_COORD_4,
GL11.GL_MAP2_VERTEX_3, GL11.GL_MAP2_VERTEX_4
};
public static void verifyIsEnabled(int glCap, boolean expected) {
verifyIsEnabled(glCap, expected, "Is Enabled Mismatch");
}
@@ -133,4 +156,102 @@ public class GLSMUtil {
() -> assertEquals(expected[i], glsmFloatBuffer.get(i), 0.0001f, "GLSM State Mismatch: " + i)
));
}
/**
* Reset all GL state to known defaults to prevent test contamination.
* This should be called at the end of tests that modify a lot of state.
*/
public static void resetGLState() {
// Disable all enable/disable states (except those with non-false defaults)
GLStateManager.disableAlphaTest();
GLStateManager.glDisable(GL11.GL_AUTO_NORMAL);
GLStateManager.disableBlend();
// Disable all clip planes (using cached MAX_CLIP_PLANES)
for(int i = 0; i < MAX_CLIP_PLANES; i++) {
GLStateManager.glDisable(GL11.GL_CLIP_PLANE0 + i);
}
GLStateManager.disableColorMaterial();
GLStateManager.glDisable(GL11.GL_COLOR_LOGIC_OP);
GLStateManager.disableCull();
GLStateManager.disableDepthTest();
// GL_DITHER defaults to true
GLStateManager.glEnable(GL11.GL_DITHER);
GLStateManager.disableFog();
GLStateManager.glDisable(GL11.GL_INDEX_LOGIC_OP);
GLStateManager.disableLighting();
// Disable all lights (using cached MAX_LIGHTS)
for(int i = 0; i < MAX_LIGHTS; i++) {
GLStateManager.disableLight(i);
}
GLStateManager.glDisable(GL11.GL_LINE_SMOOTH);
GLStateManager.glDisable(GL11.GL_LINE_STIPPLE);
// Disable all MAP1 evaluators (DRY loop)
for(int state : MAP1_STATES) {
GLStateManager.glDisable(state);
}
// Disable all MAP2 evaluators (DRY loop)
for(int state : MAP2_STATES) {
GLStateManager.glDisable(state);
}
// GL_MULTISAMPLE defaults to true (but may vary by driver)
// We'll query the actual default rather than assume
if(GL11.glIsEnabled(GL13.GL_MULTISAMPLE)) {
GLStateManager.glEnable(GL13.GL_MULTISAMPLE);
} else {
GLStateManager.glDisable(GL13.GL_MULTISAMPLE);
}
GLStateManager.glDisable(GL11.GL_NORMALIZE);
GLStateManager.glDisable(GL11.GL_POINT_SMOOTH);
GLStateManager.glDisable(GL11.GL_POLYGON_OFFSET_POINT);
GLStateManager.glDisable(GL11.GL_POLYGON_OFFSET_LINE);
GLStateManager.glDisable(GL11.GL_POLYGON_OFFSET_FILL);
GLStateManager.glDisable(GL11.GL_POLYGON_SMOOTH);
GLStateManager.glDisable(GL11.GL_POLYGON_STIPPLE);
GLStateManager.disableRescaleNormal();
GLStateManager.glDisable(GL13.GL_SAMPLE_ALPHA_TO_COVERAGE);
GLStateManager.glDisable(GL13.GL_SAMPLE_ALPHA_TO_ONE);
GLStateManager.glDisable(GL13.GL_SAMPLE_COVERAGE);
GLStateManager.disableScissorTest();
GLStateManager.glDisable(GL11.GL_STENCIL_TEST);
// Reset texture state for all units (using cached MAX_TEXTURE_UNITS)
for(int i = 0; i < MAX_TEXTURE_UNITS; i++) {
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + i);
GLStateManager.glDisable(GL11.GL_TEXTURE_1D);
GLStateManager.disableTexture(); // GL_TEXTURE_2D
GLStateManager.glDisable(GL12.GL_TEXTURE_3D);
GLStateManager.glDisable(GL11.GL_TEXTURE_GEN_S);
GLStateManager.glDisable(GL11.GL_TEXTURE_GEN_T);
GLStateManager.glDisable(GL11.GL_TEXTURE_GEN_R);
GLStateManager.glDisable(GL11.GL_TEXTURE_GEN_Q);
}
// Reset to texture unit 0
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
// Reset matrix mode to default
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
// Reset color to white
GLStateManager.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
// Reset material colors to defaults (fixes GL_COLOR_MATERIAL side effects)
FloatBuffer materialBuffer = BufferUtils.createFloatBuffer(4);
materialBuffer.put(0.2F).put(0.2F).put(0.2F).put(1.0F).flip();
GLStateManager.glMaterial(GL11.GL_FRONT_AND_BACK, GL11.GL_AMBIENT, materialBuffer);
materialBuffer.clear();
materialBuffer.put(0.8F).put(0.8F).put(0.8F).put(1.0F).flip();
GLStateManager.glMaterial(GL11.GL_FRONT_AND_BACK, GL11.GL_DIFFUSE, materialBuffer);
// Reset draw buffer
GLStateManager.glDrawBuffer(GLStateManager.DEFAULT_DRAW_BUFFER);
}
}