Compare commits

..
Author SHA1 Message Date
Algent 48fcc4c943 Fix state leak 2026-08-13 11:33:02 +02:00
198 changed files with 1521 additions and 6284 deletions

No files matched your search

+3 -5
View File
@@ -2,8 +2,7 @@
# Builds the libTracyClient shared library for the tracy-client module.
set -euo pipefail
TRACY_VERSION="${TRACY_VERSION:-v0.14.0}"
TRACY_VERSION_BARE="${TRACY_VERSION#v}"
TRACY_VERSION="${TRACY_VERSION:-v0.13.1}"
OUT_DIR="${OUT_DIR:-dist/tracy-natives}"
TRACY_REPO="https://github.com/wolfpld/tracy"
@@ -17,7 +16,7 @@ case "$(uname -m)" in
arm64|aarch64) PLAT_ARCH="arm64" ;;
*) PLAT_ARCH="x64" ;;
esac
RES_DIR="${RES_DIR:-$REPO_ROOT/tracy-client/src/main/resources/natives/tracy/$TRACY_VERSION_BARE/$PLAT_OS-$PLAT_ARCH}"
RES_DIR="${RES_DIR:-$REPO_ROOT/tracy-client/src/main/resources/natives/tracy/$PLAT_OS-$PLAT_ARCH}"
WORK_DIR="$(mktemp -d)"
trap 'rm -rf "$WORK_DIR"' EXIT
@@ -34,8 +33,7 @@ fi
BUILD_DIR="$WORK_DIR/build"
export MACOSX_DEPLOYMENT_TARGET="${MACOSX_DEPLOYMENT_TARGET:-11.0}"
cmake -S "$REPO_ROOT/tracy-client/src/main/native" -B "$BUILD_DIR" \
-DTRACY_SRC_DIR="$SRC_DIR" \
cmake -S "$SRC_DIR" -B "$BUILD_DIR" \
-DCMAKE_BUILD_TYPE=Release \
-DBUILD_SHARED_LIBS=ON \
-DTRACY_STATIC=OFF \
+23 -12
View File
@@ -6,6 +6,10 @@ on:
- "tracy-v*"
workflow_dispatch:
inputs:
tracy-version:
description: Tracy git tag to build
required: false
default: v0.13.1
publish:
description: Publish angelica-tracy.jar to the GTNH maven
type: boolean
@@ -16,25 +20,25 @@ jobs:
build:
strategy:
matrix:
platform: [linux-x64, windows-x64, macos-x64, macos-arm64]
include:
- platform: linux-x64
os: ubuntu-22.04
- platform: windows-x64
os: windows-2025
- platform: macos-x64
os: macos-15-intel
- platform: macos-arm64
os: macos-15
- os: ubuntu-22.04
platform: linux-x64
- os: windows-2025
platform: windows-x64
- os: macos-15-intel
platform: macos-x64
- os: macos-15
platform: macos-arm64
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v5
- name: Build libTracyClient
shell: bash
env:
RAW_VERSION: ${{ github.ref_type == 'tag' && github.ref_name || inputs.tracy-version }}
OUT_DIR: dist/tracy-natives
run: |
export TRACY_VERSION="v$(sed -nE 's/^tracy = "(.*)"$/\1/p' gradle/libs.versions.toml)"
export TRACY_VERSION="${RAW_VERSION#tracy-}"
bash .github/scripts/build-tracy-natives.sh
- uses: actions/upload-artifact@v4
with:
@@ -52,6 +56,14 @@ jobs:
distribution: temurin
java-version: 21
- uses: gradle/actions/setup-gradle@v4
- name: Check tracy version matches the version catalog
shell: bash
env:
RAW_VERSION: ${{ github.ref_type == 'tag' && github.ref_name || inputs.tracy-version }}
run: |
ver="${RAW_VERSION#tracy-}"
grep -q "^tracy = \"${ver#v}\"$" gradle/libs.versions.toml \
|| { echo "libs.versions.toml tracy does not match $ver" >&2; exit 1; }
- uses: actions/download-artifact@v5
with:
pattern: tracy-natives-*
@@ -59,9 +71,8 @@ jobs:
- name: Stage natives into tracy-client resources
shell: bash
run: |
version="$(sed -nE 's/^tracy = "(.*)"$/\1/p' gradle/libs.versions.toml)"
for d in staging/tracy-natives-*; do
dest="tracy-client/src/main/resources/natives/tracy/$version/${d#staging/tracy-natives-}"
dest="tracy-client/src/main/resources/natives/tracy/${d#staging/tracy-natives-}"
mkdir -p "$dest"
cp "$d"/* "$dest/"
done
-2
View File
@@ -43,5 +43,3 @@ tracy-client/src/main/resources/natives/
tracy-client/angelica/
dist/tracy-natives/
*.tracy
tracy-client/angelica/
+2 -5
View File
@@ -52,8 +52,8 @@ configurations.configureEach {
}
DependencyHandlerScope.of(dependencies).apply {
compileOnly("com.github.GTNewHorizons:Hodgepodge:2.7.187:dev")
runtimeOnlyNonPublishable("com.github.GTNewHorizons:Hodgepodge:2.7.187:dev")
compileOnly("com.github.GTNewHorizons:Hodgepodge:2.7.166:dev")
runtimeOnlyNonPublishable("com.github.GTNewHorizons:Hodgepodge:2.7.166:dev")
runtimeOnlyNonPublishable(rfg.deobf("curse.maven:biomes-o-plenty-220318:2499612"))
@@ -161,8 +161,6 @@ DependencyHandlerScope.of(dependencies).apply {
compileOnly(rfg.deobf("curse.maven:xaeros-minimap-263420:5060684"))
compileOnly(rfg.deobf("curse.maven:security-craft-64760:2818228"))
compileOnly("ganymedes01.etfuturum:Et-Futurum-Requiem:2.6.49-GTNH:dev")
compileOnly("com.github.GTNewHorizons:OpenBlocks:1.12.19-GTNH:dev")
compileOnly("com.github.GTNewHorizons:Chisel:2.17.31-GTNH:dev")
compileOnly(rfg.deobf("curse.maven:biomes-o-plenty-220318:2499612"))
devOnlyNonPublishable("com.github.GTNewHorizons:CosmeticArmorReworked:1.0.6-GTNH:dev")
@@ -204,7 +202,6 @@ afterEvaluate {
glsmTestFixtures(testFixtures(project(":glsm")) as ModuleDependency) { isTransitive = false }
testCompileOnly(testFixtures(project(":glsm")))
testImplementation("mega:fluidlogged-mc1.7.10:0.1.2")
testRuntimeOnly(libs.fastutil)
testRuntimeOnly(libs.joml)
@@ -58,7 +58,7 @@ public final class SystemProperties {
public static final boolean DEBUG_F3_DETAIL = Boolean.getBoolean("angelica.debug.f3Detail");
public static final boolean ENABLE_TEST_BLOCKS = Boolean.getBoolean("angelica.debug.testBlocks");
public static final boolean DUMP_CLASS = Boolean.getBoolean("angelica.debug.dumpClass");
private static final boolean DUMP_SHADERS_PROP = Boolean.getBoolean("angelica.debug.dumpShaders");
public static final boolean DUMP_SHADERS = Boolean.getBoolean("angelica.debug.dumpShaders") || isDeobf();
public static final boolean REDIRECTOR_LOGSPAM = Boolean.getBoolean("angelica.debug.redirectorLogspam");
public static final boolean DEBUG_DISPLAY_LISTS = Boolean.getBoolean("angelica.debug.displayLists");
public static final boolean LOG_DISPLAY_LIST_COMPILATION = Boolean.getBoolean("angelica.debug.displayLists.compilation");
@@ -68,12 +68,8 @@ public final class SystemProperties {
// Set by us, read by celeritas
public static final String KEY_CELERITAS_ENABLE_GL_DEBUG = "celeritas.enableGLDebug";
public static boolean dumpShaders() {
return DUMP_SHADERS_PROP || isDeobf();
}
public static Path shaderDumpDir(String phase) {
return dumpShaders() ? Paths.get(SHADER_DUMP_ROOT, phase) : null;
return DUMP_SHADERS ? Paths.get(SHADER_DUMP_ROOT, phase) : null;
}
public enum UnmappedGLMode {
@@ -122,7 +118,7 @@ public final class SystemProperties {
}
}
public static boolean isDeobf() {
private static boolean isDeobf() {
return Launch.blackboard != null && Boolean.TRUE.equals(Launch.blackboard.get("fml.deobfuscatedEnvironment"));
}
@@ -307,11 +307,6 @@ public class DisplayListManager {
}
}
public static void recordSecondaryColor(float r, float g, float b) {
drawBarrier();
currentRecorder.writeSecondaryColor(r, g, b);
}
public static void recordColorMask(boolean r, boolean g, boolean b, boolean a) {
drawBarrier();
currentRecorder.writeColorMask(r, g, b, a);
@@ -99,7 +99,6 @@ public class Feature {
));
attribToFeatures.put(GL11.GL_CURRENT_BIT, ImmutableSet.of(
GLStateManager.getColor()
, GLStateManager.getSecondaryColor() // Current secondary color
, ShaderManager.getNormalStack() // Current normal vector
, ShaderManager.getTexCoordStack() // Current texture coordinates
// Current color index
@@ -123,7 +122,6 @@ public class Feature {
, GLStateManager.getBlendMode()
, GLStateManager.getColorLogicOpState()
, GLStateManager.getColorMaterial()
, GLStateManager.getColorSumState()
, GLStateManager.getCullState()
, GLStateManager.getDepthTest()
, GLStateManager.getDitherState()
@@ -199,7 +197,6 @@ public class Feature {
));
attribToFeatures.put(GL11.GL_FOG_BIT, ImmutableSet.of(
GLStateManager.getFogMode()
, GLStateManager.getColorSumState()
, GLStateManager.getFogState()
// ^^ Fog density
// ^^ Linear fog start
@@ -18,7 +18,6 @@ import com.gtnewhorizons.angelica.glsm.stacks.PointStateStack;
import com.gtnewhorizons.angelica.glsm.stacks.PolygonStateStack;
import com.gtnewhorizons.angelica.glsm.stacks.StencilStateStack;
import com.gtnewhorizons.angelica.glsm.stacks.ViewPortStateStack;
import com.gtnewhorizons.angelica.glsm.states.BlendState;
import com.gtnewhorizons.angelica.glsm.states.ClipPlaneState;
import com.gtnewhorizons.angelica.glsm.states.Color4;
import com.gtnewhorizons.angelica.glsm.states.PixelUnpackState;
@@ -31,7 +30,6 @@ import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL14;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
@@ -105,9 +103,6 @@ class GLContextState {
public final FogStateStack fogState = new FogStateStack();
public final BooleanStateStack fogMode = track(new BooleanStateStack(GL11.GL_FOG, false, true));
public final Color4Stack color = new Color4Stack();
// GL_CURRENT_SECONDARY_COLOR - alpha is always 1 and unused, the color sum only adds RGB
public final Color4Stack secondaryColor = new Color4Stack(new Color4(0.0F, 0.0F, 0.0F, 1.0F));
public final BooleanStateStack colorSumState = track(new BooleanStateStack(GL14.GL_COLOR_SUM, false, true));
public final Color4Stack clearColor = new Color4Stack(new Color4(0.0F, 0.0F, 0.0F, 0.0F));
public final ColorMaskStack colorMask = new ColorMaskStack();
public final IntegerStateStack drawBuffer = new IntegerStateStack(GLStateManager.DEFAULT_DRAW_BUFFER);
@@ -185,10 +180,7 @@ class GLContextState {
public final int[] clientAttribSavedVertexFlags = new int[GLStateManager.CLIENT_ATTRIB_STACK_DEPTH];
public int clientAttribStackPointer = 0;
public final boolean[] restoreUnitChanged = new boolean[GLStateManager.MAX_TEXTURE_UNITS];
public boolean restoreDepthChanged, restoreBlendChanged, restoreColorMaskChanged, restoreClearColorChanged, restoreDrawBufferChanged, restoreLogicOpChanged, restoreStencilChanged, restoreViewportChanged, restoreLineChanged, restorePointChanged, restorePolygonChanged, restoreActiveUnitChanged, restoreSecondaryColorChanged;
public final BlendState vanillaBlendBefore = new BlendState();
public final BlendState vanillaBlendAfter = new BlendState();
public boolean vanillaBlendEnabledBefore;
public boolean restoreDepthChanged, restoreBlendChanged, restoreColorMaskChanged, restoreClearColorChanged, restoreDrawBufferChanged, restoreLogicOpChanged, restoreStencilChanged, restoreViewportChanged, restoreLineChanged, restorePointChanged, restorePolygonChanged, restoreActiveUnitChanged;
public int drawFramebuffer = 0;
public int readFramebuffer = 0;
public int texGenGeneration;
@@ -14,7 +14,6 @@ import com.gtnewhorizons.angelica.glsm.backend.VSyncMode;
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
import com.gtnewhorizons.angelica.glsm.ffp.ShaderManager;
import com.gtnewhorizons.angelica.glsm.ffp.VAOManager;
import com.gtnewhorizons.angelica.glsm.ffp.VertexKey;
import com.gtnewhorizons.angelica.glsm.hooks.DeferredAlphaHandler;
import com.gtnewhorizons.angelica.glsm.hooks.DeferredBlendHandler;
import com.gtnewhorizons.angelica.glsm.hooks.DeferredDepthColorHandler;
@@ -45,8 +44,6 @@ import com.gtnewhorizons.angelica.glsm.stacks.PointStateStack;
import com.gtnewhorizons.angelica.glsm.stacks.PolygonStateStack;
import com.gtnewhorizons.angelica.glsm.stacks.StencilStateStack;
import com.gtnewhorizons.angelica.glsm.stacks.ViewPortStateStack;
import com.gtnewhorizons.angelica.glsm.states.AlphaState;
import com.gtnewhorizons.angelica.glsm.states.BlendState;
import com.gtnewhorizons.angelica.glsm.states.ClipPlaneState;
import com.gtnewhorizons.angelica.glsm.states.Color4;
import com.gtnewhorizons.angelica.glsm.states.PixelUnpackState;
@@ -172,6 +169,9 @@ public class GLStateManager {
}
static GLContextState enterWorkerContext() {
final GLContextState existing = tlWorkerContext.get();
if (existing != null) return existing;
final GLContextState st = new GLContextState();
tlWorkerContext.set(st);
synchronized (GLStateManager.class) {
@@ -504,7 +504,6 @@ public class GLStateManager {
.addFeature(GL11.GL_COLOR_WRITEMASK)
.addFeature(GL11.GL_CURRENT_COLOR)
.addFeature(GL11.GL_CURRENT_NORMAL)
.addFeature(GL14.GL_CURRENT_SECONDARY_COLOR)
.addFeature(GL11.GL_CURRENT_RASTER_COLOR)
.addFeature(GL11.GL_CURRENT_RASTER_POSITION)
.addFeature(GL11.GL_CURRENT_RASTER_TEXTURE_COORDS)
@@ -660,7 +659,6 @@ public class GLStateManager {
case GL11.GL_BLEND -> enableBlend();
case GL11.GL_COLOR_MATERIAL -> enableColorMaterial();
case GL11.GL_COLOR_LOGIC_OP -> glCtx.colorLogicOpState.enable();
case GL14.GL_COLOR_SUM -> glCtx.colorSumState.enable();
case GL11.GL_CULL_FACE -> enableCull();
case GL11.GL_DEPTH_TEST -> enableDepthTest();
case GL11.GL_DITHER -> glCtx.ditherState.enable();
@@ -742,7 +740,6 @@ public class GLStateManager {
case GL11.GL_BLEND -> disableBlend();
case GL11.GL_COLOR_MATERIAL -> disableColorMaterial();
case GL11.GL_COLOR_LOGIC_OP -> glCtx.colorLogicOpState.disable();
case GL14.GL_COLOR_SUM -> glCtx.colorSumState.disable();
case GL11.GL_CULL_FACE -> disableCull();
case GL11.GL_DEPTH_TEST -> disableDepthTest();
case GL11.GL_DITHER -> glCtx.ditherState.disable();
@@ -818,7 +815,6 @@ public class GLStateManager {
case GL11.GL_BLEND -> glCtx.blendMode.isEnabled();
case GL11.GL_COLOR_MATERIAL -> glCtx.colorMaterial.isEnabled();
case GL11.GL_COLOR_LOGIC_OP -> glCtx.colorLogicOpState.isEnabled();
case GL14.GL_COLOR_SUM -> glCtx.colorSumState.isEnabled();
case GL11.GL_CULL_FACE -> glCtx.cullState.isEnabled();
case GL11.GL_DEPTH_TEST -> glCtx.depthTest.isEnabled();
case GL11.GL_DITHER -> glCtx.ditherState.isEnabled();
@@ -894,7 +890,6 @@ public class GLStateManager {
case GL11.GL_BLEND -> glCtx.blendMode.isEnabled();
case GL11.GL_COLOR_MATERIAL -> glCtx.colorMaterial.isEnabled();
case GL11.GL_COLOR_LOGIC_OP -> glCtx.colorLogicOpState.isEnabled();
case GL14.GL_COLOR_SUM -> glCtx.colorSumState.isEnabled();
case GL11.GL_CULL_FACE -> glCtx.cullState.isEnabled();
case GL11.GL_DEPTH_TEST -> glCtx.depthTest.isEnabled();
case GL11.GL_DEPTH_WRITEMASK -> glCtx.depthState.isEnabled();
@@ -1138,7 +1133,6 @@ public class GLStateManager {
case GL11.GL_TEXTURE_MATRIX -> glCtx.textures.getTextureUnitMatrix(getActiveTextureUnit()).get(0, params);
case GL11.GL_COLOR_CLEAR_VALUE -> glCtx.clearColor.get(params);
case GL11.GL_CURRENT_COLOR -> glCtx.color.get(params);
case GL14.GL_CURRENT_SECONDARY_COLOR -> glCtx.secondaryColor.get(params);
case GL11.GL_DEPTH_RANGE -> {
final int pos = params.position();
params.put(pos, (float) glCtx.viewportState.depthRangeNear);
@@ -1237,7 +1231,7 @@ public class GLStateManager {
}
case GL11.GL_MODELVIEW_MATRIX, GL11.GL_PROJECTION_MATRIX, GL11.GL_TEXTURE_MATRIX -> widenFromFloat(pname, params, 16);
case GL11.GL_COLOR_CLEAR_VALUE, GL11.GL_CURRENT_COLOR, GL11.GL_CURRENT_TEXTURE_COORDS, GL11.GL_FOG_COLOR,
GL11.GL_LIGHT_MODEL_AMBIENT, GL14.GL_BLEND_COLOR, GL14.GL_CURRENT_SECONDARY_COLOR -> widenFromFloat(pname, params, 4);
GL11.GL_LIGHT_MODEL_AMBIENT, GL14.GL_BLEND_COLOR -> widenFromFloat(pname, params, 4);
case GL11.GL_CURRENT_NORMAL -> widenFromFloat(pname, params, 3);
default -> {
if (!HAS_MULTIPLE_SET.contains(pname)) {
@@ -1310,16 +1304,12 @@ public class GLStateManager {
return;
}
}
final BooleanStateStack blend = ctx().blendMode;
final boolean wasEnabled = blend.isEffectivelyEnabled();
final DeferredBlendHandler bh = GLSMHooks.blendHandler;
if (bh != null && bh.isBlendLocked()) {
blend.beforeModify();
bh.deferBlendModeToggle(true);
} else {
blend.enable();
return;
}
if (!wasEnabled && blend.isEffectivelyEnabled()) postVanillaBlendChange();
ctx().blendMode.enable();
}
public static void disableBlend() {
@@ -1330,80 +1320,12 @@ public class GLStateManager {
return;
}
}
final BooleanStateStack blend = ctx().blendMode;
final boolean wasEnabled = blend.isEffectivelyEnabled();
final DeferredBlendHandler bh = GLSMHooks.blendHandler;
if (bh != null && bh.isBlendLocked()) {
blend.beforeModify();
bh.deferBlendModeToggle(false);
} else {
blend.disable();
return;
}
if (wasEnabled && !blend.isEffectivelyEnabled()) postVanillaBlendChange();
}
private static void postVanillaBlendChange() {
if (GLSMHooks.VANILLA_BLEND_CHANGE.hasListeners()) {
GLSMHooks.VANILLA_BLEND_CHANGE.post(GLSMHooks.vanillaBlendChangeEvent);
}
}
private static boolean snapshotVanillaBlendFunc() {
if (!GLSMHooks.VANILLA_BLEND_CHANGE.hasListeners()) return false;
final GLContextState glCtx = ctx();
glCtx.blendState.readEffective(glCtx.vanillaBlendBefore);
glCtx.vanillaBlendEnabledBefore = glCtx.blendMode.isEffectivelyEnabled();
return true;
}
private static void postVanillaBlendChangeIfMoved(boolean snapshotted) {
if (!snapshotted) return;
final GLContextState glCtx = ctx();
final BlendState before = glCtx.vanillaBlendBefore;
final BlendState after = glCtx.blendState.readEffective(glCtx.vanillaBlendAfter);
if (glCtx.blendMode.isEffectivelyEnabled() != glCtx.vanillaBlendEnabledBefore
|| after.getSrcRgb() != before.getSrcRgb()
|| after.getDstRgb() != before.getDstRgb()
|| after.getSrcAlpha() != before.getSrcAlpha()
|| after.getDstAlpha() != before.getDstAlpha()) {
postVanillaBlendChange();
}
}
public static boolean isEffectiveBlendEnabled() {
return ctx().blendMode.isEffectivelyEnabled();
}
public static BlendState getEffectiveBlendState(BlendState out) {
return ctx().blendState.readEffective(out);
}
public static boolean isEffectiveDepthMaskEnabled() {
return ctx().depthState.isEffectiveMaskEnabled();
}
public static boolean isEffectiveAlphaTestEnabled() {
return ctx().alphaTest.isEffectivelyEnabled();
}
public static AlphaState getEffectiveAlphaState(AlphaState out) {
return ctx().alphaState.readEffective(out);
}
private static int foreignDrawDepth;
public static void beginForeignDraw() {
foreignDrawDepth++;
}
public static void endForeignDraw() {
if (foreignDrawDepth > 0 && --foreignDrawDepth == 0 && GLSMHooks.FOREIGN_DRAW_END.hasListeners()) {
GLSMHooks.FOREIGN_DRAW_END.post(GLSMHooks.foreignDrawEndEvent);
}
}
public static boolean isForeignDraw() {
return foreignDrawDepth > 0;
ctx().blendMode.disable();
}
public static void enableScissorTest() {
@@ -1437,11 +1359,9 @@ public class GLStateManager {
return;
}
}
final boolean snapshotted = snapshotVanillaBlendFunc();
final DeferredBlendHandler bh = GLSMHooks.blendHandler;
if (bh != null && bh.isBlendLocked()) {
bh.deferBlendFunc(srcFactor, dstFactor, srcFactor, dstFactor);
postVanillaBlendChangeIfMoved(snapshotted);
return;
}
final boolean caching = isCachingEnabled();
@@ -1455,7 +1375,6 @@ public class GLStateManager {
GLSMHooks.blendFuncChangeEvent.dstAlpha = GL11.GL_ONE_MINUS_SRC_ALPHA;
GLSMHooks.BLEND_FUNC_CHANGE.post(GLSMHooks.blendFuncChangeEvent);
}
postVanillaBlendChangeIfMoved(snapshotted);
return;
}
final boolean bypass = !caching;
@@ -1474,7 +1393,6 @@ public class GLStateManager {
GLSMHooks.BLEND_FUNC_CHANGE.post(GLSMHooks.blendFuncChangeEvent);
}
}
postVanillaBlendChangeIfMoved(snapshotted);
}
public static void glBlendEquation(int mode) {
@@ -1514,11 +1432,9 @@ public class GLStateManager {
return;
}
}
final boolean snapshotted = snapshotVanillaBlendFunc();
final DeferredBlendHandler bh = GLSMHooks.blendHandler;
if (bh != null && bh.isBlendLocked()) {
bh.deferBlendFunc(srcRgb, dstRgb, srcAlpha, dstAlpha);
postVanillaBlendChangeIfMoved(snapshotted);
return;
}
if (GLSMConfig.hudCacheOverride && dstAlpha != GL11.GL_ONE_MINUS_SRC_ALPHA) {
@@ -1538,7 +1454,6 @@ public class GLStateManager {
GLSMHooks.BLEND_FUNC_CHANGE.post(GLSMHooks.blendFuncChangeEvent);
}
}
postVanillaBlendChangeIfMoved(snapshotted);
}
public static void glBlendFuncSeparate(int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) {
@@ -1760,40 +1675,6 @@ public class GLStateManager {
return false;
}
public static void glSecondaryColor3f(float red, float green, float blue) {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
DisplayListManager.recordSecondaryColor(red, green, blue);
if (mode == RecordMode.COMPILE) {
return;
}
}
changeSecondaryColor(red, green, blue);
}
public static void glSecondaryColor3d(double red, double green, double blue) {
glSecondaryColor3f((float) red, (float) green, (float) blue);
}
public static void glSecondaryColor3b(byte red, byte green, byte blue) {
glSecondaryColor3f(b2f(red), b2f(green), b2f(blue));
}
public static void glSecondaryColor3ub(byte red, byte green, byte blue) {
glSecondaryColor3f(ub2f(red), ub2f(green), ub2f(blue));
}
/** Helper for glSecondaryColor* - the color sum is emulated by the FFP shaders, nothing is sent to the driver. */
private static void changeSecondaryColor(float red, float green, float blue) {
final GLContextState glCtx = ctx();
if (!isCachingEnabled() || red != glCtx.secondaryColor.getRed() || green != glCtx.secondaryColor.getGreen() || blue != glCtx.secondaryColor.getBlue()) {
glCtx.secondaryColor.setRed(red);
glCtx.secondaryColor.setGreen(green);
glCtx.secondaryColor.setBlue(blue);
glCtx.fragmentGeneration++;
}
}
private static final Color4 DirtyColor = new Color4(-1.0F, -1.0F, -1.0F, -1.0F);
public static void clearCurrentColor() {
@@ -1867,7 +1748,6 @@ public class GLStateManager {
}
final DeferredAlphaHandler ah = GLSMHooks.alphaHandler;
if (ah != null && ah.isAlphaTestLocked()) {
glCtx.alphaTest.beforeModify();
ah.deferAlphaTestToggle(true);
return;
}
@@ -1889,7 +1769,6 @@ public class GLStateManager {
}
final DeferredAlphaHandler ah = GLSMHooks.alphaHandler;
if (ah != null && ah.isAlphaTestLocked()) {
glCtx.alphaTest.beforeModify();
ah.deferAlphaTestToggle(false);
return;
}
@@ -3181,15 +3060,9 @@ public class GLStateManager {
return;
}
}
if (light >= VertexKey.FFP_LIGHT_COUNT && (warnedFfpLightMask & (1 << light)) == 0 && ShaderManager.getInstance().isEnabled()) {
warnedFfpLightMask |= (1 << light);
LOGGER.warn("GL_LIGHT{} enabled, but FFP shader emulation implements only GL_LIGHT0..{}", light, VertexKey.FFP_LIGHT_COUNT - 1, new Throwable("call site"));
}
ctx().lightStates[light].enable();
}
private static int warnedFfpLightMask = 0;
public static void enableColorMaterial() {
final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) {
@@ -3468,11 +3341,6 @@ public class GLStateManager {
}
CurrentThread = Thread.currentThread();
if (!splashComplete && CurrentThread != MainThread && !autoVaoBound.get()) {
autoVaoBound.set(Boolean.TRUE);
glBindVertexArray(glGenVertexArrays());
}
if (splashComplete) return;
if (drawableGL == null) {
@@ -3489,13 +3357,21 @@ public class GLStateManager {
}
if (drawableGL != null && drawable == drawableGL) {
exitWorkerContext();
// Switching TO DrawableGL - enable caching for this thread
drawableGLHolder = CurrentThread;
} else if (drawableGLHolder == CurrentThread) {
// This thread held DrawableGL but is switching AWAY - disable caching
drawableGLHolder = null;
} else {
enterWorkerContext();
if (drawableGLHolder == CurrentThread) {
// This thread held DrawableGL but is switching AWAY - disable caching
drawableGLHolder = null;
}
}
if (CurrentThread != MainThread && !autoVaoBound.get()) {
autoVaoBound.set(Boolean.TRUE);
glBindVertexArray(glGenVertexArrays());
}
// else: Thread switching to non-DrawableGL, wasn't holder - no change needed
}
public static void releaseContext(Drawable drawable) throws LWJGLException {
@@ -3503,6 +3379,7 @@ public class GLStateManager {
if (!handled) {
drawable.releaseContext();
}
exitWorkerContext();
if (drawableGLHolder == Thread.currentThread()) {
drawableGLHolder = null;
}
@@ -3655,9 +3532,6 @@ public class GLStateManager {
final int mask = glCtx.attribs.popInt();
glCtx.attribDepth--;
// Snapshot before the stacks pop, so applyRestoredState can tell whether vanilla blend actually moved.
final boolean blendSnapshotted = (mask & (GL11.GL_COLOR_BUFFER_BIT | GL11.GL_ENABLE_BIT)) != 0 && snapshotVanillaBlendFunc();
// First: restore BooleanStateStack states that were actually modified (fast path)
// These use lazy copy-on-write with global depth tracking
final List<IStateStack<?>> modified = glCtx.modifiedAtDepth[glCtx.attribDepth];
@@ -3676,12 +3550,7 @@ public class GLStateManager {
// Third: apply restored state to the GL driver. BooleanStateStacks already issue GL calls via setEnabled(); non-boolean stacks are pure data
// containers, so we must explicitly drive GL here.
applyRestoredState(mask, blendSnapshotted);
}
private static boolean isDepthColorOverridden() {
final DeferredDepthColorHandler dch = GLSMHooks.depthColorHandler;
return dch != null && dch.isOverrideHeld();
applyRestoredState(mask);
}
private static void captureRestoreChanges(int mask) {
@@ -3696,9 +3565,6 @@ public class GLStateManager {
glCtx.restoreDrawBufferChanged = glCtx.drawBuffer.topChanged();
glCtx.restoreLogicOpChanged = glCtx.logicOpMode.topChanged();
}
if ((mask & GL11.GL_CURRENT_BIT) != 0) {
glCtx.restoreSecondaryColorChanged = glCtx.secondaryColor.topChanged();
}
if ((mask & GL11.GL_STENCIL_BUFFER_BIT) != 0) {
glCtx.restoreStencilChanged = glCtx.stencilState.topChanged();
}
@@ -3773,25 +3639,20 @@ public class GLStateManager {
/**
* After popping GLSM stacks, apply restored state to the GL driver.
*/
private static void applyRestoredState(int mask, boolean blendSnapshotted) {
private static void applyRestoredState(int mask) {
final GLContextState glCtx = ctx();
if ((mask & GL11.GL_DEPTH_BUFFER_BIT) != 0 && glCtx.restoreDepthChanged) {
RENDER_BACKEND.depthFunc(glCtx.depthState.getFunc());
if (!isDepthColorOverridden()) {
RENDER_BACKEND.depthMask(glCtx.depthState.isEnabled());
}
RENDER_BACKEND.depthMask(glCtx.depthState.isEnabled());
RENDER_BACKEND.clearDepth(glCtx.depthState.getClearValue());
}
if ((mask & GL11.GL_COLOR_BUFFER_BIT) != 0) {
if (glCtx.restoreBlendChanged) {
final DeferredBlendHandler restoreBlendHandler = GLSMHooks.blendHandler;
if (restoreBlendHandler == null || !restoreBlendHandler.isOverrideHeld()) {
RENDER_BACKEND.blendFuncSeparate(glCtx.blendState.getSrcRgb(), glCtx.blendState.getDstRgb(), glCtx.blendState.getSrcAlpha(), glCtx.blendState.getDstAlpha());
}
RENDER_BACKEND.blendFuncSeparate(glCtx.blendState.getSrcRgb(), glCtx.blendState.getDstRgb(), glCtx.blendState.getSrcAlpha(), glCtx.blendState.getDstAlpha());
RENDER_BACKEND.blendEquationSeparate(glCtx.blendState.getEquationRgb(), glCtx.blendState.getEquationAlpha());
RENDER_BACKEND.blendColor(glCtx.blendState.getBlendColorR(), glCtx.blendState.getBlendColorG(), glCtx.blendState.getBlendColorB(), glCtx.blendState.getBlendColorA());
}
if (glCtx.restoreColorMaskChanged && !isDepthColorOverridden()) {
if (glCtx.restoreColorMaskChanged) {
RENDER_BACKEND.colorMask(glCtx.colorMask.red, glCtx.colorMask.green, glCtx.colorMask.blue, glCtx.colorMask.alpha);
}
if (glCtx.restoreClearColorChanged) {
@@ -3875,11 +3736,7 @@ public class GLStateManager {
ShaderManager.bumpTexCoordGeneration();
glCtx.dirtyTexCoordAttrib = true;
}
// The secondary color is a fragment stage uniform, not a vertex attribute
if (glCtx.restoreSecondaryColorChanged) glCtx.fragmentGeneration++;
}
postVanillaBlendChangeIfMoved(blendSnapshotted);
}
public static void glClear(int mask) {
@@ -5068,22 +4925,16 @@ public class GLStateManager {
final ShaderManager ffp = ShaderManager.getInstance();
if (program == 0 && ffp.isEnabled()) {
final int prev = glCtx.activeProgram;
final boolean changed = prev != 0;
if (changed) glCtx.programGeneration++;
final boolean caching = isCachingEnabled();
if (prev != 0) glCtx.programGeneration++;
glCtx.activeProgram = 0; // Track that FFP was requested
if (changed && GLSMHooks.PROGRAM_CHANGE.hasListeners()) {
if (GLSMHooks.PROGRAM_CHANGE.hasListeners()) {
GLSMHooks.programChangeEvent.previousProgram = prev;
GLSMHooks.programChangeEvent.newProgram = 0;
GLSMHooks.programChangeEvent.postBind = false;
GLSMHooks.PROGRAM_CHANGE.post(GLSMHooks.programChangeEvent);
}
ffp.activate();
if (changed && GLSMHooks.PROGRAM_CHANGE.hasListeners()) {
GLSMHooks.programChangeEvent.previousProgram = prev;
GLSMHooks.programChangeEvent.newProgram = 0;
GLSMHooks.programChangeEvent.postBind = true;
GLSMHooks.PROGRAM_CHANGE.post(GLSMHooks.programChangeEvent);
}
return;
}
@@ -7456,14 +7307,6 @@ public class GLStateManager {
return ctx().color;
}
public static Color4Stack getSecondaryColor() {
return ctx().secondaryColor;
}
public static BooleanStateStack getColorSumState() {
return ctx().colorSumState;
}
public static Color4Stack getClearColor() {
return ctx().clearColor;
}
@@ -103,7 +103,6 @@ public final class FFPUniformBlock {
public static final int TEX_ENV_COLOR_2 = vec4("u_TexEnvColor2");
public static final int TEX_ENV_COLOR_3 = vec4("u_TexEnvColor3");
public static final int OVERLAY_COLOR = vec4("u_OverlayColor");
public static final int SECONDARY_COLOR = vec3("u_SecondaryColor");
public static final int FOG_PARAMS = vec4("u_FogParams");
public static final int FOG_COLOR = vec4("u_FogColor");
@@ -1,83 +0,0 @@
package com.gtnewhorizons.angelica.glsm.ffp;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.states.LightState;
import com.gtnewhorizons.angelica.glsm.states.MaterialState;
import org.joml.Matrix3f;
import org.joml.Vector3f;
import org.joml.Vector4f;
public final class FFPVertexLighting {
private static final Vector3f scratchNormal = new Vector3f();
private static final Vector3f scratchLightVec = new Vector3f();
private static final Vector4f scratchEyePos = new Vector4f();
private static final Matrix3f scratchNormalMat = new Matrix3f();
private static final Vector3f scratchVec = new Vector3f();
private FFPVertexLighting() {}
public static boolean modulatesVertexColor(Vector3f destFactor) {
destFactor.set(1.0f);
if (!GLStateManager.getLightingState().isEnabled()) return false;
if (!GLStateManager.getColorMaterial().isEnabled()) return false;
if (VertexKey.encodeColorMaterialMode(GLStateManager.getColorMaterialParameter().getValue()) != VertexKey.CM_AMBIENT_AND_DIFFUSE) return false;
final MaterialState material = GLStateManager.getFrontMaterial();
if (material.emission.x != 0.0f || material.emission.y != 0.0f || material.emission.z != 0.0f)
return false;
final boolean materialHasSpecular = material.shininess > 0.0f && (material.specular.x != 0.0f || material.specular.y != 0.0f || material.specular.z != 0.0f);
final Vector4f lightModelAmbient = GLStateManager.getLightModel().ambient;
float r = lightModelAmbient.x;
float g = lightModelAmbient.y;
float b = lightModelAmbient.z;
final var lightEnables = GLStateManager.getLightStates();
final var lightData = GLStateManager.getLightDataStates();
boolean normalReady = false;
for (int i = 0; i < VertexKey.FFP_LIGHT_COUNT; i++) {
if (!lightEnables[i].isEnabled()) continue;
final LightState light = lightData[i];
if (materialHasSpecular && (light.specular.x != 0.0f || light.specular.y != 0.0f || light.specular.z != 0.0f))
return false;
if (!normalReady) {
transformCurrentNormal();
normalReady = true;
}
final float nDotVP = Math.max(scratchNormal.dot(lightDirection(light)), 0.0f);
r += light.ambient.x + nDotVP * light.diffuse.x;
g += light.ambient.y + nDotVP * light.diffuse.y;
b += light.ambient.z + nDotVP * light.diffuse.z;
}
if (r == 1.0f && g == 1.0f && b == 1.0f) return false;
if (!Float.isFinite(r + g + b)) return false;
destFactor.set(r, g, b);
return true;
}
private static void transformCurrentNormal() {
GLStateManager.getModelViewMatrix().normal(scratchNormalMat);
scratchNormal.set(ShaderManager.getCurrentNormal());
scratchNormalMat.transform(scratchNormal);
if (GLStateManager.getNormalizeState().isEnabled()) {
scratchNormal.normalize();
} else if (GLStateManager.getRescaleNormalState().isEnabled()) {
scratchNormal.mul(Uniforms.rescaleFactor(scratchNormalMat, scratchVec));
}
}
private static Vector3f lightDirection(LightState light) {
if (light.position.w == 0.0f) {
scratchLightVec.set(light.position.x, light.position.y, light.position.z);
} else {
scratchEyePos.set(0.0f, 0.0f, 0.0f, 1.0f).mul(GLStateManager.getModelViewMatrix());
scratchLightVec.set(light.position.x - scratchEyePos.x, light.position.y - scratchEyePos.y, light.position.z - scratchEyePos.z);
}
return scratchLightVec.normalize();
}
}
@@ -12,7 +12,7 @@ import org.lwjgl.opengl.GL13;
* Packed-long fragment shader permutation key for FFP emulation.
*
* Layout:
* long[0]: global bits (13) + unit 0 (47 bits at offset 13)
* long[0]: global bits (12) + unit 0 (47 bits at offset 12)
* long[1..3]: unit 1..3 (47 bits each, low-aligned)
* Only max(1, nrEnabledUnits) longs are significant.
*
@@ -63,7 +63,7 @@ public final class FragmentKey {
public static final int FOG_EXP = 2;
public static final int FOG_EXP2 = 3;
private static final int GLOBAL_BITS = 13;
private static final int GLOBAL_BITS = 12;
private static final int BIT_FOG_MODE = 0; // 2 bits
private static final int BIT_ALPHA_TEST = 2; // 1 bit
private static final int BIT_ALPHA_FUNC = 3; // 3 bits
@@ -71,7 +71,6 @@ public final class FragmentKey {
private static final int BIT_NR_ENABLED_UNITS = 7; // 3 bits
private static final int BIT_OVERLAY_ENABLED = 10; // 1 bit
private static final int BIT_LINE_STIPPLE = 11; // 1 bit
private static final int BIT_COLOR_SUM = 12; // 1 bit
private static final int U_ENABLED = 0;
private static final int U_MODE = 1; // 3 bits
@@ -131,12 +130,10 @@ public final class FragmentKey {
global |= (1L << BIT_LINE_STIPPLE);
}
// Separate specular / color sum
// Separate specular
if (GLStateManager.getLightingState().isEnabled()
&& GLStateManager.getLightModel().colorControl == GL12.GL_SEPARATE_SPECULAR_COLOR) {
global |= (1L << BIT_SEPARATE_SPECULAR);
} else if (GLStateManager.getColorSumState().isEnabled()) {
global |= (1L << BIT_COLOR_SUM);
}
// Per-unit state
@@ -241,7 +238,6 @@ public final class FragmentKey {
public boolean alphaTestEnabled() { return ((packed[0] >> BIT_ALPHA_TEST) & 1) != 0; }
public int alphaTestFunc() { return (int) ((packed[0] >> BIT_ALPHA_FUNC) & 0x7); }
public boolean separateSpecular() { return ((packed[0] >> BIT_SEPARATE_SPECULAR) & 1) != 0; }
public boolean colorSum() { return ((packed[0] >> BIT_COLOR_SUM) & 1) != 0; }
public boolean lineStipple() { return ((packed[0] >> BIT_LINE_STIPPLE) & 1) != 0; }
public int nrEnabledUnits() { return (int) ((packed[0] >> BIT_NR_ENABLED_UNITS) & 0x7); }
public boolean overlayEnabled() { return ((packed[0] >> BIT_OVERLAY_ENABLED) & 1) != 0; }
@@ -378,10 +374,10 @@ public final class FragmentKey {
default -> "?";
};
final StringBuilder sb = new StringBuilder();
sb.append(String.format("FFPFragmentKey[fog=%s alpha=%b(%s) specSep=%b colorSum=%b overlay=%b units=%d",
sb.append(String.format("FFPFragmentKey[fog=%s alpha=%b(%s) specSep=%b overlay=%b units=%d",
fogName, alphaTestEnabled(),
alphaTestEnabled() ? String.format("0x%04X", decodeAlphaFunc(alphaTestFunc())) : "-",
separateSpecular(), colorSum(), overlayEnabled(), nrEnabledUnits()));
separateSpecular(), overlayEnabled(), nrEnabledUnits()));
for (int i = 0; i < nrEnabledUnits(); i++) {
if (!unitEnabled(i)) {
sb.append(String.format(" u%d=OFF", i));
@@ -276,10 +276,6 @@ public final class FragmentShaderGenerator {
sb.append(" // Add separate specular\n");
sb.append(" color.rgb += v_SpecularColor;\n");
}
if (key.colorSum()) {
sb.append(" // Color sum - GL_COLOR_SUM with the current secondary color\n");
sb.append(" color.rgb += u_SecondaryColor;\n");
}
}
private static void emitAlphaTest(StringBuilder sb, FragmentKey key) {
@@ -232,12 +232,8 @@ public class Uniforms {
private void stageNormalMatrix() {
GLStateManager.getModelViewMatrix().normal(normalMatrix);
putMat3(FFPUniformBlock.NORMAL_MATRIX, normalMatrix);
putFloat(FFPUniformBlock.NORMAL_SCALE, rescaleFactor(normalMatrix, tempVec3));
}
static float rescaleFactor(Matrix3f normalMatrix, Vector3f scratch) {
final float f = normalMatrix.getColumn(2, scratch).lengthSquared();
return f > 1.0e-12f ? 1.0f / (float) Math.sqrt(f) : 1.0f;
final float scale = 1.0f / normalMatrix.getColumn(0, tempVec3).length();
putFloat(FFPUniformBlock.NORMAL_SCALE, scale);
}
private void stageTextureMatrices() {
@@ -331,9 +327,6 @@ public class Uniforms {
GLStateManager.getOverlayR(), GLStateManager.getOverlayG(),
GLStateManager.getOverlayB(), GLStateManager.getOverlayA());
final var secondary = GLStateManager.getSecondaryColor();
putVec3(FFPUniformBlock.SECONDARY_COLOR, secondary.getRed(), secondary.getGreen(), secondary.getBlue());
// Mesa STATE_FOG_PARAMS_OPTIMIZED
final FogState fog = GLStateManager.getFogState();
final float start = fog.getStart();
@@ -20,36 +20,38 @@ public final class VertexKey {
public static final int MAX_UNITS = 4;
public static final int FFP_LIGHT_COUNT = 2;
private final long packed;
private static final int BIT_LIGHTING = 0;
private static final int BIT_LIGHT_BASE = BIT_LIGHTING + 1;
private static final int BIT_LIGHT_DIR_BASE = BIT_LIGHT_BASE + FFP_LIGHT_COUNT;
private static final int BIT_COLOR_MATERIAL = BIT_LIGHT_DIR_BASE + FFP_LIGHT_COUNT;
private static final int BIT_SEPARATE_SPECULAR = BIT_COLOR_MATERIAL + 1;
private static final int BIT_FOG = BIT_SEPARATE_SPECULAR + 1;
private static final int BIT_FOG_DIST_MODE = BIT_FOG + 1;
private static final int BIT_NORMALIZE = BIT_FOG_DIST_MODE + 2;
private static final int BIT_RESCALE_NORMAL = BIT_NORMALIZE + 1;
private static final int BIT_UNIT_TEX_BASE = BIT_RESCALE_NORMAL + 1;
private static final int BIT_HAS_VERTEX_COLOR = BIT_UNIT_TEX_BASE + MAX_UNITS;
private static final int BIT_HAS_VERTEX_NORMAL = BIT_HAS_VERTEX_COLOR + 1;
private static final int BIT_HAS_VERTEX_TEX = BIT_HAS_VERTEX_NORMAL + 1;
private static final int BIT_HAS_VERTEX_LIGHTMAP = BIT_HAS_VERTEX_TEX + 1;
private static final int BIT_COLOR_MAT_MODE = BIT_HAS_VERTEX_LIGHTMAP + 1;
// TexGen modes are unit 0 only, for now.
private static final int BIT_TEXGEN_S = BIT_COLOR_MAT_MODE + 3;
private static final int BIT_TEXGEN_T = BIT_TEXGEN_S + 3;
private static final int BIT_TEXGEN_R = BIT_TEXGEN_T + 3;
private static final int BIT_TEXGEN_Q = BIT_TEXGEN_R + 3;
private static final int BIT_CLIP_PLANES = BIT_TEXGEN_Q + 3;
private static final int BIT_WIDE_LINE = BIT_CLIP_PLANES + 1;
private static final int BIT_UNIT_TEXMAT_BASE = BIT_WIDE_LINE + 1;
private static final int BIT_UNIT23_UV_FROM_UNIT0 = BIT_UNIT_TEXMAT_BASE + MAX_UNITS;
private static final int BIT_LINE_STIPPLE = BIT_UNIT23_UV_FROM_UNIT0 + 1;
private static final int BIT_INSTANCED = BIT_LINE_STIPPLE + 1;
private static final int BIT_LIGHT0 = 1;
private static final int BIT_LIGHT1 = 2;
private static final int BIT_LIGHT0_DIR = 3;
private static final int BIT_LIGHT1_DIR = 4;
private static final int BIT_COLOR_MATERIAL = 5;
private static final int BIT_SEPARATE_SPECULAR = 6;
private static final int BIT_FOG = 7;
private static final int BIT_FOG_DIST_MODE = 8; // 2 bits: 8-9
private static final int BIT_NORMALIZE = 10;
private static final int BIT_RESCALE_NORMAL = 11;
// Per-unit texcoord enable: bits 12-15 (unit 0..3). Unit 1 doubles as the lightmap flag.
private static final int BIT_UNIT_TEX_BASE = 12;
private static final int BIT_HAS_VERTEX_COLOR = 16;
private static final int BIT_HAS_VERTEX_NORMAL = 17;
private static final int BIT_HAS_VERTEX_TEX = 18;
private static final int BIT_HAS_VERTEX_LIGHTMAP = 19;
private static final int BIT_COLOR_MAT_MODE = 20; // 3 bits: 20-22
// TexGen modes (unit 0 only, for now): 3 bits each (0=NONE, 1=OBJ_LINEAR, 2=EYE_LINEAR).
private static final int BIT_TEXGEN_S = 23; // 3 bits: 23-25
private static final int BIT_TEXGEN_T = 26; // 3 bits: 26-28
private static final int BIT_TEXGEN_R = 29; // 3 bits: 29-31
private static final int BIT_TEXGEN_Q = 32; // 3 bits: 32-34
private static final int BIT_CLIP_PLANES = 35;
private static final int BIT_WIDE_LINE = 36;
// Per-unit texmat enable: bits 37-40 (unit 0..3). Unit 1 is the lightmap matrix.
private static final int BIT_UNIT_TEXMAT_BASE = 37;
private static final int BIT_UNIT23_UV_FROM_UNIT0 = 41;
private static final int BIT_LINE_STIPPLE = 42;
private static final int BIT_INSTANCED = 44;
public static final int TG_NONE = 0;
public static final int TG_OBJ_LINEAR = 1;
@@ -68,8 +70,10 @@ public final class VertexKey {
public long pack() { return packed; }
public boolean lightingEnabled() { return bit(BIT_LIGHTING); }
public boolean lightEnabled(int light) { return bit(BIT_LIGHT_BASE + light); }
public boolean lightDirectional(int light) { return bit(BIT_LIGHT_DIR_BASE + light); }
public boolean light0Enabled() { return bit(BIT_LIGHT0); }
public boolean light1Enabled() { return bit(BIT_LIGHT1); }
public boolean light0Directional() { return bit(BIT_LIGHT0_DIR); }
public boolean light1Directional() { return bit(BIT_LIGHT1_DIR); }
public boolean colorMaterialEnabled() { return bit(BIT_COLOR_MATERIAL); }
public boolean separateSpecular() { return bit(BIT_SEPARATE_SPECULAR); }
public boolean fogEnabled() { return bit(BIT_FOG); }
@@ -132,12 +136,17 @@ public final class VertexKey {
if (lighting) {
bits |= (1L << BIT_LIGHTING);
for (int i = 0; i < FFP_LIGHT_COUNT; i++) {
if (!GLStateManager.getLightStates()[i].isEnabled()) continue;
bits |= (1L << (BIT_LIGHT_BASE + i));
if (GLStateManager.getLightStates()[0].isEnabled()) {
bits |= (1L << BIT_LIGHT0);
// position.w == 0 means directional
if (GLStateManager.getLightDataStates()[i].position.w == 0.0f) {
bits |= (1L << (BIT_LIGHT_DIR_BASE + i));
if (GLStateManager.getLightDataStates()[0].position.w == 0.0f) {
bits |= (1L << BIT_LIGHT0_DIR);
}
}
if (GLStateManager.getLightStates()[1].isEnabled()) {
bits |= (1L << BIT_LIGHT1);
if (GLStateManager.getLightDataStates()[1].position.w == 0.0f) {
bits |= (1L << BIT_LIGHT1_DIR);
}
}
@@ -256,7 +265,7 @@ public final class VertexKey {
@Override
public String toString() {
return String.format("FFPVertexKey[0x%011X: lit=%b l0=%b l1=%b cm=%b fog=%b tex=%d%d%d%d texmat=%d%d%d%d col=%b nrm=%b vtex=%b vlm=%b tg=%d/%d/%d/%d clip=%b wline=%b inst=%b]",
packed, lightingEnabled(), lightEnabled(0), lightEnabled(1),
packed, lightingEnabled(), light0Enabled(), light1Enabled(),
colorMaterialEnabled(), fogEnabled(),
unitTexCoordEnabled(0)?1:0, unitTexCoordEnabled(1)?1:0, unitTexCoordEnabled(2)?1:0, unitTexCoordEnabled(3)?1:0,
unitTexMatEnabled(0)?1:0, unitTexMatEnabled(1)?1:0, unitTexMatEnabled(2)?1:0, unitTexMatEnabled(3)?1:0,
@@ -182,10 +182,11 @@ public final class VertexShaderGenerator {
}
// Per-light accumulation
for (int i = 0; i < VertexKey.FFP_LIGHT_COUNT; i++) {
if (key.lightEnabled(i)) {
emitLightContribution(sb, key, i);
}
if (key.light0Enabled()) {
emitLightContribution(sb, key, 0);
}
if (key.light1Enabled()) {
emitLightContribution(sb, key, 1);
}
sb.append(" v_Color = vec4(clamp(color0, 0.0, 1.0), outAlpha);\n");
@@ -197,7 +198,7 @@ public final class VertexShaderGenerator {
private static void emitLightContribution(StringBuilder sb, VertexKey key, int lightIndex) {
final String li = String.valueOf(lightIndex);
final boolean directional = key.lightDirectional(lightIndex);
final boolean directional = (lightIndex == 0) ? key.light0Directional() : key.light1Directional();
final String posUniform = "u_Light" + li + "Position";
sb.append(" { // Light ").append(li).append('\n');
@@ -2,7 +2,6 @@ package com.gtnewhorizons.angelica.glsm.hooks;
public interface DeferredBlendHandler {
boolean isBlendLocked();
boolean isOverrideHeld();
void deferBlendModeToggle(boolean enabled);
void deferBlendFunc(int srcRgb, int dstRgb, int srcAlpha, int dstAlpha);
void flushDeferredBlend();
@@ -2,7 +2,6 @@ package com.gtnewhorizons.angelica.glsm.hooks;
public interface DeferredDepthColorHandler {
boolean isDepthColorLocked();
boolean isOverrideHeld();
void deferDepthEnable(boolean enabled);
void deferColorMask(boolean r, boolean g, boolean b, boolean a);
}
@@ -6,14 +6,6 @@ public final class GLSMConfig {
public static float lastBrightnessX;
public static float lastBrightnessY;
public static int packBrightness(float x, float y) {
return ((int) y << 16) | ((int) x & 0xFFFF);
}
public static int packedLastBrightness() {
return packBrightness(lastBrightnessX, lastBrightnessY);
}
public static boolean hudCacheOverride;
public static volatile boolean expandVertexFormats;
@@ -25,8 +25,6 @@ public final class GLSMHooks {
public static final EventBus<LightmapCoordsEvent> LIGHTMAP_COORDS = EventBus.create(LightmapCoordsEvent.class);
public static final EventBus<AlphaStateChangeEvent> ALPHA_STATE_CHANGE = EventBus.create(AlphaStateChangeEvent.class);
public static final EventBus<ShaderColorChangeEvent> SHADER_COLOR_CHANGE = EventBus.create(ShaderColorChangeEvent.class);
public static final EventBus<ForeignDrawEndEvent> FOREIGN_DRAW_END = EventBus.create(ForeignDrawEndEvent.class);
public static final EventBus<VanillaBlendChangeEvent> VANILLA_BLEND_CHANGE = EventBus.create(VanillaBlendChangeEvent.class);
public static final EventBus<LoadingCheckpointEvent> LOADING_CHECKPOINT = EventBus.create(LoadingCheckpointEvent.class);
// Reusable event instances
@@ -40,8 +38,6 @@ public final class GLSMHooks {
public static final LightmapCoordsEvent lightmapCoordsEvent = new LightmapCoordsEvent();
public static final AlphaStateChangeEvent alphaStateChangeEvent = new AlphaStateChangeEvent();
public static final ShaderColorChangeEvent shaderColorChangeEvent = new ShaderColorChangeEvent();
public static final ForeignDrawEndEvent foreignDrawEndEvent = new ForeignDrawEndEvent();
public static final VanillaBlendChangeEvent vanillaBlendChangeEvent = new VanillaBlendChangeEvent();
public static final LoadingCheckpointEvent loadingCheckpointEvent = new LoadingCheckpointEvent();
private GLSMHooks() {}
@@ -1,8 +0,0 @@
package com.gtnewhorizons.angelica.glsm.hooks;
public interface VanillaBooleanLayer {
boolean isOverrideHeld();
boolean getVanilla();
void setVanilla(boolean enabled);
}
@@ -1,22 +0,0 @@
package com.gtnewhorizons.angelica.glsm.hooks;
public interface VanillaStateLayer<T> {
boolean isOverrideHeld();
void readVanilla(T into);
void writeVanilla(T from);
static boolean isHeld(VanillaStateLayer<?> layer) {
return layer != null && layer.isOverrideHeld();
}
static <T> void capture(VanillaStateLayer<T> layer, T slot) {
if (isHeld(layer)) layer.readVanilla(slot);
}
static <T> boolean restore(VanillaStateLayer<T> layer, T saved) {
if (!isHeld(layer)) return false;
layer.writeVanilla(saved);
return true;
}
}
@@ -1,6 +0,0 @@
package com.gtnewhorizons.angelica.glsm.hooks.events;
import net.minecraftforge.eventbus.api.event.MutableEvent;
public final class ForeignDrawEndEvent extends MutableEvent {
}
@@ -1,6 +0,0 @@
package com.gtnewhorizons.angelica.glsm.hooks.events;
import net.minecraftforge.eventbus.api.event.MutableEvent;
public final class VanillaBlendChangeEvent extends MutableEvent {
}
@@ -1,92 +0,0 @@
package com.gtnewhorizons.angelica.glsm.profiling;
import java.util.ArrayList;
import java.util.List;
public final class SectionRegistry {
public interface Emitter {
long enter(int category, String text);
void leave(long nativeId);
void setup(int category, String name);
boolean isConnected();
}
private static final class Category {
final int id;
final String name;
Category(int id, String name) {
this.id = id;
this.name = name;
}
}
private static final class Section {
final long token;
final int category;
final String text;
long nativeId;
Section(long token, int category, String text, long nativeId) {
this.token = token;
this.category = category;
this.text = text;
this.nativeId = nativeId;
}
}
private final Emitter emitter;
private final List<Category> categories = new ArrayList<>();
private final List<Section> open = new ArrayList<>();
private long nextToken;
private boolean connected;
public SectionRegistry(Emitter emitter) {
this.emitter = emitter;
}
public synchronized void registerCategory(int category, String name) {
categories.add(new Category(category, name));
}
public synchronized long enter(int category, String text) {
syncConnection();
final long token = ++nextToken;
open.add(new Section(token, category, text, emitter.enter(category, text)));
return token;
}
public synchronized void leave(long token) {
for (int i = 0; i < open.size(); i++) {
final Section section = open.get(i);
if (section.token == token) {
open.remove(i);
if (section.nativeId != 0L) emitter.leave(section.nativeId);
return;
}
}
}
public synchronized void poll() {
syncConnection();
}
private void syncConnection() {
final boolean now = emitter.isConnected();
if (now == connected) return;
connected = now;
if (now) replay();
}
private void replay() {
for (int i = 0; i < categories.size(); i++) {
final Category category = categories.get(i);
emitter.setup(category.id, category.name);
}
for (int i = 0; i < open.size(); i++) {
final Section section = open.get(i);
section.nativeId = emitter.enter(section.category, section.text);
}
}
}
@@ -44,18 +44,6 @@ public final class Tracy {
public static final int COLOR_IRIS = 0x9E862E; // gold
public static final int COLOR_FFP = 0x7A4E9E; // purple
public static final int SECTION_WORLD = 1;
public static final int SECTION_SHADERS = 2;
public static final int SECTION_BENCHMARK = 3;
public static final int SECTION_UI = 4;
private static final SectionRegistry SECTIONS = new SectionRegistry(new SectionRegistry.Emitter() {
@Override public long enter(int category, String text) { return BACKEND.sectionEnter(category, text); }
@Override public void leave(long nativeId) { BACKEND.sectionLeave(nativeId); }
@Override public void setup(int category, String name) { BACKEND.sectionSetup(category, name); }
@Override public boolean isConnected() { return BACKEND.isConnected(); }
});
private static final ThreadLocal<ZoneStack> STACK = new ThreadLocal<>() {
@Override
protected ZoneStack initialValue() {
@@ -74,10 +62,6 @@ public final class Tracy {
FINE_ZONES = ENABLED && SystemProperties.TRACY_FINE_ZONES;
if (ENABLED) {
Runtime.getRuntime().addShutdownHook(new Thread(Tracy::shutdown, "Tracy-Shutdown"));
SECTIONS.registerCategory(SECTION_WORLD, "World");
SECTIONS.registerCategory(SECTION_SHADERS, "Shaders");
SECTIONS.registerCategory(SECTION_BENCHMARK, "Benchmark");
SECTIONS.registerCategory(SECTION_UI, "UI");
LOGGER.info("Tracy profiling enabled");
}
}
@@ -111,7 +95,6 @@ public final class Tracy {
LOGGER.warn("Tracy requested (-Dangelica.tracy=true) but no TracyBackend service present");
return null;
}
if (!implementsCurrentAbi(found)) return null;
final TracyBackend backend = found;
final CountDownLatch done = new CountDownLatch(1);
final AtomicReference<Boolean> result = new AtomicReference<>();
@@ -137,28 +120,10 @@ public final class Tracy {
return backend;
}
private static final String ABI_SENTINEL = "sectionEnter";
private static boolean implementsCurrentAbi(TracyBackend backend) {
try {
backend.getClass().getMethod(ABI_SENTINEL, int.class, String.class);
return true;
} catch (NoSuchMethodException e) {
LOGGER.warn("Tracy backend {} was built against an older TracyBackend interface; profiling disabled", backend.getClass().getName());
return false;
}
}
private record InitRunner(TracyBackend backend, CountDownLatch done, AtomicReference<Boolean> result) implements Runnable {
@Override
public void run() {
boolean ok;
try {
ok = backend.init();
} catch (LinkageError e) {
LOGGER.warn("Tracy backend {} failed to link; profiling disabled: {}", backend.getClass().getName(), e);
ok = false;
}
final boolean ok = backend.init();
if (!result.compareAndSet(null, ok) && ok) {
backend.shutdown();
}
@@ -203,7 +168,7 @@ public final class Tracy {
final String name = stack.poppedName();
if (name != null && WARNED_LEAKS.add(name)) {
LOGGER.warn("Tracy: unbalanced profiler section '{}' left open (leaked by its caller); closed at next root", name);
BACKEND.message("unbalanced profiler section '" + name + "' closed at root", TracyBackend.SEVERITY_WARNING);
BACKEND.message("unbalanced profiler section '" + name + "' closed at root");
}
}
}
@@ -309,7 +274,6 @@ public final class Tracy {
threadNameRefreshed = true;
BACKEND.setCurrentThreadName(Thread.currentThread().getName());
}
SECTIONS.poll();
BACKEND.frameMark();
}
@@ -366,22 +330,8 @@ public final class Tracy {
}
public static void message(String text) {
message(text, TracyBackend.SEVERITY_INFO);
}
public static void message(String text, int severity) {
if (!ENABLED || SHUTTING_DOWN || !CaptureGate.markersThisFrame) return;
BACKEND.message(text, severity);
}
public static long sectionEnter(int category, String text) {
if (!ENABLED || SHUTTING_DOWN) return 0L;
return SECTIONS.enter(category, text);
}
public static void sectionLeave(long token) {
if (token == 0L || !ENABLED || SHUTTING_DOWN) return;
SECTIONS.leave(token);
BACKEND.message(text);
}
public static boolean isConnected() {
@@ -5,13 +5,6 @@ public interface TracyBackend {
int PLOT_FORMAT_MEMORY = 1;
int PLOT_FORMAT_PERCENTAGE = 2;
int SEVERITY_TRACE = 0;
int SEVERITY_DEBUG = 1;
int SEVERITY_INFO = 2;
int SEVERITY_WARNING = 3;
int SEVERITY_ERROR = 4;
int SEVERITY_FATAL = 5;
boolean init();
long internSrcLoc(String name, int color);
@@ -31,14 +24,7 @@ public interface TracyBackend {
void plotInt(long namePtr, long value);
void plot(long namePtr, double value);
void message(String text, int severity);
default void message(String text) { message(text, SEVERITY_INFO); }
long sectionEnter(int category, String text);
void sectionLeave(long id);
void sectionSetup(int category, String name);
void message(String text);
void setCurrentThreadName(String name);
boolean isConnected();
void shutdown();
@@ -2,7 +2,7 @@ package com.gtnewhorizons.angelica.glsm.profiling;
public final class ZoneStack {
public static final long EMPTY = -1L;
public static final int MAX_DEPTH = 512;
static final int MAX_DEPTH = 512;
private long[] stack = new long[64];
private boolean[] gpu = new boolean[64];
@@ -274,13 +274,6 @@ public final class CommandBufferExecutor {
ptr += 16;
GLStateManager.glColor4f(r, g, b, a);
}
case GLCommand.SECONDARY_COLOR -> {
final float r = memGetFloat(ptr);
final float g = memGetFloat(ptr + 4);
final float b = memGetFloat(ptr + 8);
ptr += 12;
GLStateManager.glSecondaryColor3f(r, g, b);
}
case GLCommand.CLEAR_COLOR -> {
final float r = memGetFloat(ptr);
final float g = memGetFloat(ptr + 4);
@@ -356,14 +356,6 @@ public final class CommandRecorder {
writeFloat(a);
}
public void writeSecondaryColor(float r, float g, float b) {
ensureCapacity(16);
writeInt(GLCommand.SECONDARY_COLOR);
writeFloat(r);
writeFloat(g);
writeFloat(b);
}
public void writeClearColor(float r, float g, float b, float a) {
ensureCapacity(20);
writeInt(GLCommand.CLEAR_COLOR);
@@ -61,7 +61,6 @@ public final class GLCommand {
public static final int COLOR = 54; // [cmd:4][r:4f][g:4f][b:4f][a:4f]
public static final int CLEAR_COLOR = 55; // [cmd:4][r:4f][g:4f][b:4f][a:4f]
public static final int BLEND_COLOR = 56; // [cmd:4][r:4f][g:4f][b:4f][a:4f]
public static final int SECONDARY_COLOR = 57; // [cmd:4][r:4f][g:4f][b:4f]
// === Mixed int+float commands ===
public static final int ALPHA_FUNC = 60; // [cmd:4][func:4][ref:4f]
@@ -156,7 +155,6 @@ public final class GLCommand {
case COLOR -> "COLOR";
case CLEAR_COLOR -> "CLEAR_COLOR";
case BLEND_COLOR -> "BLEND_COLOR";
case SECONDARY_COLOR -> "SECONDARY_COLOR";
case ALPHA_FUNC -> "ALPHA_FUNC";
case FOGF -> "FOGF";
case LIGHTF -> "LIGHTF";
@@ -213,7 +211,7 @@ public final class GLCommand {
// Three int commands (16 bytes)
case GLCommand.STENCIL_FUNC, GLCommand.STENCIL_OP, GLCommand.TEX_PARAMETERI,
GLCommand.LIGHTF, GLCommand.LIGHTI,
GLCommand.MATERIALF, GLCommand.TEX_PARAMETERF, GLCommand.SECONDARY_COLOR -> 16;
GLCommand.MATERIALF, GLCommand.TEX_PARAMETERF -> 16;
// Four int commands (20 bytes)
case GLCommand.VIEWPORT, GLCommand.BLEND_FUNC, GLCommand.COLOR_MASK,
@@ -142,7 +142,6 @@ public class GLSMRedirector {
private static final String GLU = "org/lwjgl/util/glu/GLU";
private static final String OpenGlHelper = "net/minecraft/client/renderer/OpenGlHelper";
private static final String EXTBlendFunc = "org/lwjgl/opengl/EXTBlendFuncSeparate";
private static final String EXTSecondaryColor = "org/lwjgl/opengl/EXTSecondaryColor";
private static final String ARBMultiTexture = "org/lwjgl/opengl/ARBMultitexture";
private static final String ARBShaderObjects = "org/lwjgl/opengl/ARBShaderObjects";
private static final String ARBInstancedArrays = "org/lwjgl/opengl/ARBInstancedArrays";
@@ -404,12 +403,7 @@ public class GLSMRedirector {
.add("glBlendEquation")
.add("glMultiDrawArrays")
.add("glPointParameterf")
.add("glPointParameteri")
// Removed in core profile - emulated by the FFP shaders, calling through would abort the JVM
.add("glSecondaryColor3f")
.add("glSecondaryColor3d")
.add("glSecondaryColor3b")
.add("glSecondaryColor3ub");
.add("glPointParameteri");
final var gl15 = RedirectMap.newMap()
.add("glGenBuffers")
.add("glBindBuffer")
@@ -595,11 +589,6 @@ public class GLSMRedirector {
.add("isFramebufferEnabled")
);
methodRedirects.put(EXTBlendFunc, RedirectMap.newMap().add("glBlendFuncSeparateEXT", "tryBlendFuncSeparate"));
methodRedirects.put(EXTSecondaryColor, RedirectMap.newMap()
.add("glSecondaryColor3bEXT", "glSecondaryColor3b")
.add("glSecondaryColor3fEXT", "glSecondaryColor3f")
.add("glSecondaryColor3dEXT", "glSecondaryColor3d")
.add("glSecondaryColor3ubEXT", "glSecondaryColor3ub"));
// ARB
methodRedirects.put(ARBMultiTexture, RedirectMap.newMap()
@@ -2,9 +2,7 @@ package com.gtnewhorizons.angelica.glsm.stacks;
import com.gtnewhorizon.gtnhlib.client.renderer.stacks.IStateStack;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.hooks.VanillaStateLayer;
import com.gtnewhorizons.angelica.glsm.states.AlphaState;
import lombok.Setter;
public class AlphaStateStack extends AlphaState implements IStateStack<AlphaState> {
@@ -12,8 +10,6 @@ public class AlphaStateStack extends AlphaState implements IStateStack<AlphaStat
protected int pointer;
@Setter private VanillaStateLayer<AlphaState> vanillaLayer;
public AlphaStateStack() {
stack = new AlphaState[GLStateManager.MAX_ATTRIB_STACK_DEPTH];
for (int i = 0; i < GLStateManager.MAX_ATTRIB_STACK_DEPTH; i++) {
@@ -26,7 +22,7 @@ public class AlphaStateStack extends AlphaState implements IStateStack<AlphaStat
throw new IllegalStateException("Stack overflow size " + (pointer + 1) + " reached");
}
VanillaStateLayer.capture(vanillaLayer, stack[pointer++].set(this));
stack[pointer++].set(this);
return this;
}
@@ -35,19 +31,10 @@ public class AlphaStateStack extends AlphaState implements IStateStack<AlphaStat
throw new IllegalStateException("Stack underflow");
}
final AlphaState saved = stack[--pointer];
if (!VanillaStateLayer.restore(vanillaLayer, saved)) {
set(saved);
}
set(stack[--pointer]);
return this;
}
public AlphaState readEffective(AlphaState out) {
out.set(this);
VanillaStateLayer.capture(vanillaLayer, out);
return out;
}
public boolean isEmpty() {
return pointer == 0;
}
@@ -2,9 +2,7 @@ package com.gtnewhorizons.angelica.glsm.stacks;
import com.gtnewhorizon.gtnhlib.client.renderer.stacks.IStateStack;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.hooks.VanillaStateLayer;
import com.gtnewhorizons.angelica.glsm.states.BlendState;
import lombok.Setter;
public class BlendStateStack extends BlendState implements IStateStack<BlendStateStack> {
@@ -12,8 +10,6 @@ public class BlendStateStack extends BlendState implements IStateStack<BlendStat
protected int pointer;
@Setter private VanillaStateLayer<BlendState> vanillaLayer;
public BlendStateStack() {
stack = new BlendState[GLStateManager.MAX_ATTRIB_STACK_DEPTH];
for (int i = 0; i < GLStateManager.MAX_ATTRIB_STACK_DEPTH; i++) {
@@ -26,7 +22,7 @@ public class BlendStateStack extends BlendState implements IStateStack<BlendStat
throw new IllegalStateException("Stack overflow size " + (pointer + 1) + " reached");
}
VanillaStateLayer.capture(vanillaLayer, stack[pointer++].set(this));
stack[pointer++].set(this);
return this;
}
@@ -35,21 +31,10 @@ public class BlendStateStack extends BlendState implements IStateStack<BlendStat
throw new IllegalStateException("Stack underflow");
}
final BlendState saved = stack[--pointer];
if (VanillaStateLayer.restore(vanillaLayer, saved)) {
setExceptFunc(saved);
} else {
set(saved);
}
set(stack[--pointer]);
return this;
}
public BlendState readEffective(BlendState out) {
out.set(this);
VanillaStateLayer.capture(vanillaLayer, out);
return out;
}
public boolean isEmpty() {
return pointer == 0;
}
@@ -2,9 +2,7 @@ package com.gtnewhorizons.angelica.glsm.stacks;
import com.gtnewhorizon.gtnhlib.client.renderer.stacks.IStateStack;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.hooks.VanillaBooleanLayer;
import com.gtnewhorizons.angelica.glsm.states.BooleanState;
import lombok.Setter;
/**
* A stack for boolean GL state with lazy copy-on-write optimization.
@@ -16,7 +14,6 @@ import lombok.Setter;
public class BooleanStateStack extends BooleanState implements IStateStack<BooleanStateStack> {
protected final boolean[] stack;
@Setter private VanillaBooleanLayer vanillaLayer;
/**
* The depth at which state has been saved. Compared against GLStateManager.getAttribDepth()
@@ -59,7 +56,7 @@ public class BooleanStateStack extends BooleanState implements IStateStack<Boole
if (savedDepth >= stack.length) {
throw new IllegalStateException("Stack overflow size " + (savedDepth + 1) + " reached");
}
stack[savedDepth++] = vanillaValue();
stack[savedDepth++] = enabled;
return this;
}
@@ -68,26 +65,12 @@ public class BooleanStateStack extends BooleanState implements IStateStack<Boole
if (savedDepth == 0) {
throw new IllegalStateException("Stack underflow");
}
restore(stack[--savedDepth]);
final boolean oldValue = stack[--savedDepth];
// Call setEnabledDirect to avoid triggering beforeModify during restore
setEnabledDirect(oldValue);
return this;
}
public boolean isEffectivelyEnabled() {
return (vanillaLayer != null && vanillaLayer.isOverrideHeld()) ? vanillaLayer.getVanilla() : enabled;
}
private boolean vanillaValue() {
return isEffectivelyEnabled();
}
private void restore(boolean value) {
if (vanillaLayer != null && vanillaLayer.isOverrideHeld()) {
vanillaLayer.setVanilla(value);
} else {
setEnabledDirect(value);
}
}
@Override
public boolean isEmpty() {
return savedDepth == 0;
@@ -109,7 +92,8 @@ public class BooleanStateStack extends BooleanState implements IStateStack<Boole
public BooleanStateStack popDepth() {
// We're only called if we were modified, so savedDepth should match
if (savedDepth > 0) {
restore(stack[--savedDepth]);
final boolean oldValue = stack[--savedDepth];
setEnabledDirect(oldValue);
}
return this;
}
@@ -122,7 +106,7 @@ public class BooleanStateStack extends BooleanState implements IStateStack<Boole
public void beforeModify() {
final int globalDepth = GLStateManager.getAttribDepth();
if (savedDepth < globalDepth) {
stack[savedDepth++] = vanillaValue();
stack[savedDepth++] = enabled;
GLStateManager.registerModifiedState(this);
}
}
@@ -2,9 +2,7 @@ package com.gtnewhorizons.angelica.glsm.stacks;
import com.gtnewhorizon.gtnhlib.client.renderer.stacks.IStateStack;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.hooks.VanillaStateLayer;
import com.gtnewhorizons.angelica.glsm.states.ColorMask;
import lombok.Setter;
public class ColorMaskStack extends ColorMask implements IStateStack<ColorMaskStack> {
@@ -12,8 +10,6 @@ public class ColorMaskStack extends ColorMask implements IStateStack<ColorMaskSt
protected int pointer;
@Setter private VanillaStateLayer<ColorMask> vanillaLayer;
public ColorMaskStack() {
stack = new ColorMask[GLStateManager.MAX_ATTRIB_STACK_DEPTH];
for (int i = 0; i < GLStateManager.MAX_ATTRIB_STACK_DEPTH; i++) {
@@ -26,7 +22,7 @@ public class ColorMaskStack extends ColorMask implements IStateStack<ColorMaskSt
throw new IllegalStateException("Stack overflow size " + (pointer + 1) + " reached");
}
VanillaStateLayer.capture(vanillaLayer, stack[pointer++].set(this));
stack[pointer++].set(this);
return this;
}
@@ -35,10 +31,7 @@ public class ColorMaskStack extends ColorMask implements IStateStack<ColorMaskSt
throw new IllegalStateException("Stack underflow");
}
final ColorMask saved = stack[--pointer];
if (!VanillaStateLayer.restore(vanillaLayer, saved)) {
set(saved);
}
set(stack[--pointer]);
return this;
}
@@ -2,9 +2,7 @@ package com.gtnewhorizons.angelica.glsm.stacks;
import com.gtnewhorizon.gtnhlib.client.renderer.stacks.IStateStack;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.hooks.VanillaStateLayer;
import com.gtnewhorizons.angelica.glsm.states.DepthState;
import lombok.Setter;
public class DepthStateStack extends DepthState implements IStateStack<DepthStateStack> {
@@ -12,10 +10,6 @@ public class DepthStateStack extends DepthState implements IStateStack<DepthStat
protected int pointer;
@Setter private VanillaStateLayer<DepthState> vanillaLayer;
private final DepthState effective = new DepthState();
public DepthStateStack() {
stack = new DepthState[GLStateManager.MAX_ATTRIB_STACK_DEPTH];
for (int i = 0; i < GLStateManager.MAX_ATTRIB_STACK_DEPTH; i++) {
@@ -28,7 +22,7 @@ public class DepthStateStack extends DepthState implements IStateStack<DepthStat
throw new IllegalStateException("Stack overflow size " + (pointer + 1) + " reached");
}
VanillaStateLayer.capture(vanillaLayer, stack[pointer++].set(this));
stack[pointer++].set(this);
return this;
}
@@ -37,21 +31,10 @@ public class DepthStateStack extends DepthState implements IStateStack<DepthStat
throw new IllegalStateException("Stack underflow");
}
final DepthState saved = stack[--pointer];
if (VanillaStateLayer.restore(vanillaLayer, saved)) {
setExceptMask(saved);
} else {
set(saved);
}
set(stack[--pointer]);
return this;
}
public boolean isEffectiveMaskEnabled() {
if (!VanillaStateLayer.isHeld(vanillaLayer)) return isEnabled();
vanillaLayer.readVanilla(effective);
return effective.isEnabled();
}
public boolean isEmpty() {
return pointer == 0;
}
@@ -55,15 +55,6 @@ public class BlendState implements ISettableState<BlendState> {
return this;
}
public void setExceptFunc(BlendState state) {
final int sRgb = srcRgb, dRgb = dstRgb, sAlpha = srcAlpha, dAlpha = dstAlpha;
set(state);
this.srcRgb = sRgb;
this.dstRgb = dRgb;
this.srcAlpha = sAlpha;
this.dstAlpha = dAlpha;
}
@Override
public boolean sameAs(Object state) {
if (this == state) return true;
@@ -18,12 +18,6 @@ public class DepthState implements ISettableState<DepthState> {
return this;
}
public void setExceptMask(DepthState state) {
final boolean mask = enabled;
set(state);
this.enabled = mask;
}
@Override
public boolean sameAs(Object state) {
if (this == state) return true;
@@ -108,7 +108,7 @@ public class TessellatorStreamingDrawer {
final int defaultBrightness;
if (!tess.hasBrightness) {
defaultBrightness = GLSMConfig.packedLastBrightness();
defaultBrightness = ((int) GLSMConfig.lastBrightnessY << 16) | ((int) GLSMConfig.lastBrightnessX & 0xFFFF);
} else {
defaultBrightness = 0;
}
@@ -4,11 +4,8 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL14;
import java.nio.FloatBuffer;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -25,7 +22,6 @@ public class GLSM_CoreRemovedCaps_GLTest {
cap("GL_POLYGON_STIPPLE", GL11.GL_POLYGON_STIPPLE),
cap("GL_INDEX_LOGIC_OP", GL11.GL_INDEX_LOGIC_OP),
cap("GL_AUTO_NORMAL", GL11.GL_AUTO_NORMAL),
cap("GL_COLOR_SUM", GL14.GL_COLOR_SUM),
cap("GL_MAP1_COLOR_4", GL11.GL_MAP1_COLOR_4),
cap("GL_MAP1_INDEX", GL11.GL_MAP1_INDEX),
cap("GL_MAP1_NORMAL", GL11.GL_MAP1_NORMAL),
@@ -50,14 +46,6 @@ public class GLSM_CoreRemovedCaps_GLTest {
return Arguments.of(name, value);
}
private static void assertSecondaryColor(float red, float green, float blue) {
final FloatBuffer params = BufferUtils.createFloatBuffer(4);
GLStateManager.glGetFloat(GL14.GL_CURRENT_SECONDARY_COLOR, params);
assertEquals(red, params.get(0), "red must round-trip through the cache");
assertEquals(green, params.get(1), "green must round-trip through the cache");
assertEquals(blue, params.get(2), "blue must round-trip through the cache");
}
private static void assertNoGlError(String what) {
final int error = GL11.glGetError();
assertEquals(GL11.GL_NO_ERROR, error, () -> what + " raised 0x" + Integer.toHexString(error));
@@ -95,71 +83,6 @@ public class GLSM_CoreRemovedCaps_GLTest {
}
}
@Test
void secondaryColorIsCacheOnly() {
try {
// Calling through to the driver here aborts the JVM in a core profile - the color sum is emulated by the FFP shaders
GLStateManager.glSecondaryColor3f(0.25F, 0.5F, 0.75F);
assertNoGlError("glSecondaryColor3f");
assertSecondaryColor(0.25F, 0.5F, 0.75F);
} finally {
GLStateManager.glSecondaryColor3f(0.0F, 0.0F, 0.0F);
while (GL11.glGetError() != GL11.GL_NO_ERROR) {}
}
}
@Test
void secondaryColorIsRestoredByPopAttrib() {
try {
GLStateManager.glSecondaryColor3f(0.125F, 0.25F, 0.375F);
GLStateManager.glPushAttrib(GL11.GL_CURRENT_BIT);
GLStateManager.glSecondaryColor3f(1.0F, 1.0F, 1.0F);
GLStateManager.glPopAttrib();
assertNoGlError("glPushAttrib/glSecondaryColor3f/glPopAttrib");
assertSecondaryColor(0.125F, 0.25F, 0.375F);
} finally {
GLStateManager.glSecondaryColor3f(0.0F, 0.0F, 0.0F);
while (GL11.glGetError() != GL11.GL_NO_ERROR) {}
}
}
@Test
void colorSumIsRestoredByFogBitPopAttrib() {
try {
GLStateManager.glPushAttrib(GL11.GL_FOG_BIT);
GLStateManager.glEnable(GL14.GL_COLOR_SUM);
GLStateManager.glPopAttrib();
assertNoGlError("glPushAttrib(GL_FOG_BIT)/glEnable(GL_COLOR_SUM)/glPopAttrib");
assertFalse(GLStateManager.glIsEnabled(GL14.GL_COLOR_SUM));
} finally {
GLStateManager.glDisable(GL14.GL_COLOR_SUM);
while (GL11.glGetError() != GL11.GL_NO_ERROR) {}
}
}
@Test
void secondaryColorReplaysFromDisplayList() {
final int list = GLStateManager.glGenLists(1);
try {
GLStateManager.glNewList(list, GL11.GL_COMPILE);
GLStateManager.glSecondaryColor3f(0.5F, 0.625F, 0.75F);
GLStateManager.glEndList();
assertNoGlError("glSecondaryColor3f display list compile");
GLStateManager.glSecondaryColor3f(0.0F, 0.0F, 0.0F);
GLStateManager.glCallList(list);
assertNoGlError("glSecondaryColor3f display list replay");
assertSecondaryColor(0.5F, 0.625F, 0.75F);
} finally {
GLStateManager.glDeleteLists(list, 1);
GLStateManager.glSecondaryColor3f(0.0F, 0.0F, 0.0F);
while (GL11.glGetError() != GL11.GL_NO_ERROR) {}
}
}
@Test
void displayListReplayIsCacheOnly() {
final int list = GLStateManager.glGenLists(1);
@@ -106,7 +106,7 @@ public class GLSM_ServerSideState_UnitTest {
backgroundError = e;
} finally {
try {
sharedDrawable.releaseContext();
GLStateManager.releaseContext(sharedDrawable);
} catch (LWJGLException e) {
// Ignore on cleanup
}
@@ -342,6 +342,41 @@ public class GLSM_ServerSideState_UnitTest {
}
}
@Test
void testDepthStateDoesNotBleedFromSharedDrawable() throws InterruptedException {
final boolean originalDepthTest = GLStateManager.getDepthTest().isEnabled();
final int originalDepthFunc = GLStateManager.getDepthState().getFunc();
final boolean originalDepthMask = GLStateManager.getDepthState().isEnabled();
try {
GLStateManager.enableDepthTest();
GLStateManager.glDepthFunc(GL11.GL_LEQUAL);
GLStateManager.glDepthMask(true);
executeOnSharedDrawable(() -> {
GLStateManager.disableDepthTest();
GLStateManager.glDepthFunc(GL11.GL_ALWAYS);
GLStateManager.glDepthMask(false);
assertFalse(GLStateManager.getDepthTest().isEnabled());
assertEquals(GL11.GL_ALWAYS, GLStateManager.getDepthState().getFunc());
assertFalse(GLStateManager.getDepthState().isEnabled());
});
assertTrue(GLStateManager.getDepthTest().isEnabled(), "SharedDrawable depth test leaked into the main cache");
assertEquals(GL11.GL_LEQUAL, GLStateManager.getDepthState().getFunc(), "SharedDrawable depth func leaked into the main cache");
assertTrue(GLStateManager.getDepthState().isEnabled(), "SharedDrawable depth mask leaked into the main cache");
} finally {
if (originalDepthTest) {
GLStateManager.enableDepthTest();
} else {
GLStateManager.disableDepthTest();
}
GLStateManager.glDepthFunc(originalDepthFunc);
GLStateManager.glDepthMask(originalDepthMask);
}
}
/**
* Test glTexParameterf (float parameters like LOD_BIAS).
*/
@@ -1,241 +0,0 @@
package com.gtnewhorizons.angelica.glsm.ffp;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormatElement;
import com.gtnewhorizons.angelica.glsm.GLCoreTest;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import org.joml.Vector3f;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL15;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import static com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags.COLOR_BIT;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@GLCoreTest
class FFPVertexLightingGLTest {
private static final int POSITION_LOC = VertexFormatElement.Usage.POSITION.getAttributeLocation();
private static final int COLOR_LOC = VertexFormatElement.Usage.COLOR.getAttributeLocation();
private static final int STRIDE = 16;
private static final int VERTEX_COLOR = 0xFF808080;
private static final float VERTEX_CHANNEL = 0x80 / 255.0f;
private static final Vector3f IDENTITY_FACTOR = new Vector3f(1.0f, 1.0f, 1.0f);
private final Vector3f factor = new Vector3f();
private int vao;
private int vbo;
@BeforeEach
void setUpState() {
GLStateManager.glMatrixMode(GL11.GL_PROJECTION);
GLStateManager.glLoadIdentity();
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
GLStateManager.glLoadIdentity();
GLStateManager.glViewport(0, 0, 800, 600);
GLStateManager.disableDepthTest();
GLStateManager.disableCull();
GLStateManager.disableBlend();
GLStateManager.disableTexture();
GLStateManager.glNormal3f(0.0f, 0.0f, 1.0f);
standardItemLighting();
GLStateManager.glMaterial(GL11.GL_FRONT_AND_BACK, GL11.GL_EMISSION, floats(0.0f, 0.0f, 0.0f, 1.0f));
GLStateManager.glMaterial(GL11.GL_FRONT_AND_BACK, GL11.GL_SPECULAR, floats(0.0f, 0.0f, 0.0f, 1.0f));
GLStateManager.glMaterialf(GL11.GL_FRONT_AND_BACK, GL11.GL_SHININESS, 0.0f);
}
@AfterEach
void cleanup() {
GLStateManager.glDisable(GL11.GL_NORMALIZE);
GLStateManager.glDisable(GL12.GL_RESCALE_NORMAL);
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
GLStateManager.glLoadIdentity();
GLStateManager.glDisable(GL11.GL_LIGHTING);
GLStateManager.glDisable(GL11.GL_LIGHT0);
GLStateManager.glDisable(GL11.GL_LIGHT1);
GLStateManager.glDisable(GL11.GL_LIGHT2);
GLStateManager.glDisable(GL11.GL_COLOR_MATERIAL);
final ShaderManager sm = ShaderManager.getInstance();
if (sm.isActive()) sm.deactivate();
sm.disable();
GLStateManager.glBindVertexArray(0);
if (vbo != 0) {
GLStateManager.glDeleteBuffers(vbo);
vbo = 0;
}
if (vao != 0) {
GLStateManager.glDeleteVertexArrays(vao);
vao = 0;
}
}
private static void standardItemLighting() {
GLStateManager.glEnable(GL11.GL_LIGHTING);
GLStateManager.glEnable(GL11.GL_LIGHT0);
GLStateManager.glEnable(GL11.GL_LIGHT1);
GLStateManager.glEnable(GL11.GL_COLOR_MATERIAL);
GLStateManager.glColorMaterial(GL11.GL_FRONT_AND_BACK, GL11.GL_AMBIENT_AND_DIFFUSE);
GLStateManager.glLightModel(GL11.GL_LIGHT_MODEL_AMBIENT, floats(0.4f, 0.4f, 0.4f, 1.0f));
light(GL11.GL_LIGHT0, 0.2f, 1.0f, -0.7f);
light(GL11.GL_LIGHT1, -0.2f, 1.0f, 0.7f);
}
private static void light(int light, float x, float y, float z) {
GLStateManager.glLight(light, GL11.GL_POSITION, floats(x, y, z, 0.0f));
GLStateManager.glLight(light, GL11.GL_DIFFUSE, floats(0.6f, 0.6f, 0.6f, 1.0f));
GLStateManager.glLight(light, GL11.GL_AMBIENT, floats(0.0f, 0.0f, 0.0f, 1.0f));
GLStateManager.glLight(light, GL11.GL_SPECULAR, floats(0.0f, 0.0f, 0.0f, 1.0f));
}
private static String gateState() {
final var material = GLStateManager.getFrontMaterial();
return "lighting=" + GLStateManager.getLightingState().isEnabled()
+ " colorMaterial=" + GLStateManager.getColorMaterial().isEnabled()
+ " cmParam=0x" + Integer.toHexString(GLStateManager.getColorMaterialParameter().getValue())
+ " emission=" + material.emission
+ " specular=" + material.specular
+ " shininess=" + material.shininess
+ " lmAmbient=" + GLStateManager.getLightModel().ambient
+ " light0=" + GLStateManager.getLightStates()[0].isEnabled()
+ " light1=" + GLStateManager.getLightStates()[1].isEnabled();
}
private static FloatBuffer floats(float... values) {
final FloatBuffer buf = BufferUtils.createFloatBuffer(values.length);
buf.put(values).flip();
return buf;
}
private void buildTriangle() {
vao = GLStateManager.glGenVertexArrays();
GLStateManager.glBindVertexArray(vao);
final ByteBuffer data = BufferUtils.createByteBuffer(3 * STRIDE);
putVertex(data, -0.9f, -0.9f);
putVertex(data, 0.9f, -0.9f);
putVertex(data, 0.0f, 0.9f);
data.flip();
vbo = GLStateManager.glGenBuffers();
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo);
GLStateManager.glBufferData(GL15.GL_ARRAY_BUFFER, data, GL15.GL_STATIC_DRAW);
GLStateManager.glEnableVertexAttribArray(POSITION_LOC);
GLStateManager.glVertexAttribPointer(POSITION_LOC, 3, GL11.GL_FLOAT, false, STRIDE, 0L);
GLStateManager.glEnableVertexAttribArray(COLOR_LOC);
GLStateManager.glVertexAttribPointer(COLOR_LOC, 4, GL11.GL_UNSIGNED_BYTE, true, STRIDE, 12L);
VAOManager.setCurrentVertexFlags(COLOR_BIT);
}
private static void putVertex(ByteBuffer buf, float x, float y) {
final int base = buf.position();
buf.putFloat(base, x).putFloat(base + 4, y).putFloat(base + 8, 0.0f);
buf.putInt(base + 12, VERTEX_COLOR);
buf.position(base + STRIDE);
}
private float[] drawAndReadCenter() {
buildTriangle();
final ShaderManager sm = ShaderManager.getInstance();
sm.enable();
sm.activate();
GLStateManager.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
GLStateManager.glClear(GL11.GL_COLOR_BUFFER_BIT);
GLStateManager.glDrawArrays(GL11.GL_TRIANGLES, 0, 3);
assertEquals(GL11.GL_NO_ERROR, GL11.glGetError(), "FFP draw must not raise a GL error");
final ByteBuffer pixel = BufferUtils.createByteBuffer(4);
GL11.glReadPixels(400, 200, 1, 1, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, pixel);
return new float[] { (pixel.get(0) & 0xFF) / 255.0f, (pixel.get(1) & 0xFF) / 255.0f, (pixel.get(2) & 0xFF) / 255.0f };
}
private void assertSolverMatchesShader(String context) {
assertTrue(FFPVertexLighting.modulatesVertexColor(factor), context + ": expected a representable factor");
final float[] actual = drawAndReadCenter();
final float[] expected = { Math.min(1.0f, VERTEX_CHANNEL * factor.x), Math.min(1.0f, VERTEX_CHANNEL * factor.y), Math.min(1.0f, VERTEX_CHANNEL * factor.z) };
for (int c = 0; c < 3; c++) {
assertEquals(expected[c], actual[c], 2.0f / 255.0f, context + ": channel " + c + " solver=" + expected[c] + " shader=" + actual[c] + " factor=" + factor);
}
}
@Test
void faceOnNormalMatchesGeneratedShader() {
GLStateManager.glNormal3f(0.0f, 0.0f, 1.0f);
assertSolverMatchesShader("face-on normal");
}
@Test
void signNormalMatchesGeneratedShader() {
GLStateManager.glNormal3f(0.0f, 0.0f, -0.010416667f);
assertSolverMatchesShader("sign normal");
assertTrue(factor.x < 0.45f, "a 0.0104-long normal must stay at the 0.4 light model ambient floor rather than pick up 0.6 per light, got " + factor.x);
}
@Test
void tiltedNormalMatchesGeneratedShader() {
GLStateManager.glNormal3f(0.3f, 0.8f, 0.5f);
assertSolverMatchesShader("tilted normal");
}
@Test
void rescaleNormalMatchesGeneratedShader() {
GLStateManager.glEnable(GL12.GL_RESCALE_NORMAL);
GLStateManager.glScalef(1.0f, 2.0f, 1.0f);
GLStateManager.glNormal3f(0.0f, 1.0f, 0.0f);
assertSolverMatchesShader("rescale normal");
}
@Test
void normalizeMatchesGeneratedShader() {
GLStateManager.glEnable(GL11.GL_NORMALIZE);
GLStateManager.glScalef(1.0f, 2.0f, 1.0f);
GLStateManager.glNormal3f(0.0f, 1.0f, 0.0f);
assertSolverMatchesShader("normalize");
assertTrue(factor.x > 1.2f, "normalize restores the unit normal, which must pick up more diffuse than rescale's 0.5-long one, got " + factor.x);
}
@Test
void materialEmissionIsNotRepresentable() {
GLStateManager.glMaterial(GL11.GL_FRONT_AND_BACK, GL11.GL_EMISSION, floats(0.1f, 0.1f, 0.1f, 1.0f));
assertFalse(FFPVertexLighting.modulatesVertexColor(factor), "emission is additive, so the lit colour is not vertexColor * factor");
assertEquals(IDENTITY_FACTOR, factor, "a rejected solve must leave an identity factor");
}
@Test
void specularContributionIsNotRepresentable() {
GLStateManager.glMaterial(GL11.GL_FRONT_AND_BACK, GL11.GL_SPECULAR, floats(1.0f, 1.0f, 1.0f, 1.0f));
GLStateManager.glMaterialf(GL11.GL_FRONT_AND_BACK, GL11.GL_SHININESS, 16.0f);
GLStateManager.glLight(GL11.GL_LIGHT0, GL11.GL_SPECULAR, floats(1.0f, 1.0f, 1.0f, 1.0f));
assertFalse(FFPVertexLighting.modulatesVertexColor(factor), "specular is additive, so the lit colour is not vertexColor * factor");
}
@Test
void nonAmbientAndDiffuseColorMaterialIsNotRepresentable() {
GLStateManager.glColorMaterial(GL11.GL_FRONT_AND_BACK, GL11.GL_EMISSION);
assertFalse(FFPVertexLighting.modulatesVertexColor(factor), "only AMBIENT_AND_DIFFUSE makes the lit colour scale with the vertex colour");
}
@Test
void lightsBeyondTheFfpCountAreIgnored() {
assertTrue(FFPVertexLighting.modulatesVertexColor(factor), FFPVertexLightingGLTest::gateState);
final Vector3f twoLights = new Vector3f(factor);
light(GL11.GL_LIGHT2, 0.0f, 0.0f, 1.0f);
GLStateManager.glEnable(GL11.GL_LIGHT2);
assertTrue(FFPVertexLighting.modulatesVertexColor(factor), FFPVertexLightingGLTest::gateState);
assertEquals(twoLights, factor, "VertexShaderGenerator emits only GL_LIGHT0/GL_LIGHT1, so text must not see GL_LIGHT2 either");
}
}
@@ -1,32 +0,0 @@
package com.gtnewhorizons.angelica.glsm.ffp;
import org.joml.Matrix3f;
import org.joml.Matrix4f;
import org.joml.Vector3f;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class UniformsRescaleTest {
private static float rescaleFactorFor(float sx, float sy, float sz) {
final Matrix3f normalMatrix = new Matrix3f();
new Matrix4f().rotateY(0.7f).scale(sx, sy, sz).normal(normalMatrix);
return Uniforms.rescaleFactor(normalMatrix, new Vector3f());
}
@Test
void rescaleFactorUsesTheInverseModelviewBottomRow() {
assertEquals(8.0f, rescaleFactorFor(4.0f, 2.0f, 8.0f), 1.0e-5f, "wrong normal matrix column");
}
@Test
void uniformScaleIsRowIndependent() {
assertEquals(2.0f, rescaleFactorFor(2.0f, 2.0f, 2.0f), 1.0e-5f);
}
@Test
void singularMatrixFallsBackToUnitScale() {
assertEquals(1.0f, rescaleFactorFor(1.0f, 1.0f, 0.0f), 1.0e-5f, "a degenerate normal matrix must not divide by zero");
}
}
@@ -1,113 +0,0 @@
package com.gtnewhorizons.angelica.glsm.profiling;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class SectionRegistryTest {
private static final class RecordingEmitter implements SectionRegistry.Emitter {
final List<String> setups = new ArrayList<>();
final List<String> enters = new ArrayList<>();
final List<Long> leaves = new ArrayList<>();
long nextId;
boolean connected;
@Override
public long enter(int category, String text) {
enters.add(category + ":" + text);
return connected ? ++nextId : 0L;
}
@Override
public void leave(long nativeId) {
leaves.add(nativeId);
}
@Override
public void setup(int category, String name) {
setups.add(category + ":" + name);
}
@Override
public boolean isConnected() {
return connected;
}
}
private final RecordingEmitter emitter = new RecordingEmitter();
private final SectionRegistry registry = new SectionRegistry(emitter);
private void reconnect() {
emitter.connected = false;
registry.poll();
emitter.connected = true;
registry.poll();
}
@Test
void tokensOutliveEveryReplayAndLeaveUsesTheNewestId() {
final long openedWhileDisconnected = registry.enter(1, "world");
assertNotEquals(0L, openedWhileDisconnected, "token must be valid while disconnected");
assertEquals(0L, emitter.nextId, "no native id while disconnected");
emitter.connected = true;
registry.poll();
final long openedWhileConnected = registry.enter(2, "shaders");
assertNotEquals(openedWhileDisconnected, openedWhileConnected);
reconnect();
emitter.leaves.clear();
registry.leave(openedWhileDisconnected);
registry.leave(openedWhileConnected);
assertEquals(List.of(3L, 4L), emitter.leaves, "leave must use the post-reconnect ids");
}
@Test
void aSectionEnteredOnTheConnectingFrameIsNotEnteredTwice() {
emitter.connected = true;
registry.enter(2, "shaders pack / Overworld");
registry.poll();
assertEquals(List.of("2:shaders pack / Overworld"), emitter.enters, "must not re-enter a section already live on this connection");
}
@Test
void reconnectReplaysEveryCategoryAndEveryOpenSection() {
registry.registerCategory(1, "World");
registry.registerCategory(4, "UI");
emitter.connected = true;
registry.poll();
registry.enter(1, "world");
registry.enter(4, "pause");
emitter.setups.clear();
emitter.enters.clear();
reconnect();
assertEquals(List.of("1:World", "4:UI"), emitter.setups, "all categories re-registered");
assertEquals(List.of("1:world", "4:pause"), emitter.enters, "all open sections re-entered");
}
@Test
void leftSectionsAreNotResurrectedByAReconnect() {
emitter.connected = true;
registry.poll();
final long token = registry.enter(1, "transient");
registry.leave(token);
emitter.enters.clear();
emitter.leaves.clear();
reconnect();
registry.leave(token);
assertTrue(emitter.enters.isEmpty(), "closed sections must not be re-entered");
assertTrue(emitter.leaves.isEmpty(), "closed tokens must not be left twice");
}
}
+1 -1
View File
@@ -15,7 +15,7 @@ eventbus = "7.0-beta.15"
glslTransformLib = "0.2.0-33.g3ec381e"
antlr4Runtime = "4.13.2"
jcpp = "1.4.14"
tracy = "0.14.0"
tracy = "0.13.1"
retroFuturaBootstrap = "1.1.0"
lombok = "1.18.46"
@@ -88,6 +88,7 @@ import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import org.lwjgl.sdl.SDLGPU;
import org.lwjgl.sdl.SDLSurface;
import org.lwjgl.sdl.SDL_GPUBlitInfo;
import org.lwjgl.sdl.SDL_GPUBufferLocation;
import org.lwjgl.sdl.SDL_GPUTextureLocation;
@@ -110,7 +111,7 @@ public class SDLGPURenderBackend extends RenderBackend {
private final Device device = SDLGPUGate.device();
private final FrameManager frameManager = new FrameManager(device);
private volatile Presenter presenter;
private Presenter presenter;
private final ResourceManager resourceManager = new ResourceManager(device, frameManager);
private final Image3DClear image3DClear = new Image3DClear();
private final ShaderManager shaderManager = new ShaderManager(device);
@@ -154,8 +155,7 @@ public class SDLGPURenderBackend extends RenderBackend {
private volatile boolean shutdown;
private volatile OffscreenTarget splashTarget;
private volatile boolean splashTeardownPending;
private OffscreenTarget splashTarget;
private static final ThreadRegistry<ContextState> registeredStates = new ThreadRegistry<>(new ContextState[0]);
private static final ThreadLocal<ContextState> tlState = new ThreadLocal<>();
@@ -241,12 +241,16 @@ public class SDLGPURenderBackend extends RenderBackend {
});
GLSMHooks.LOADING_CHECKPOINT
.addListener(event -> {
if (!GLStateManager.isSplashComplete()) {
if (Thread.currentThread() == GLStateManager.getMainThread()) {
SplashDispatcher.tryDispatch(this, splashTarget, false);
if (Thread.currentThread() == GLStateManager.getMainThread()) {
if (!GLStateManager.isSplashComplete()) {
SplashDispatcher.tryDispatch(this, splashTarget);
} else if (splashTarget != null) {
SplashDispatcher.signalFrameReady();
SplashDispatcher.tryDispatch(this, splashTarget);
splashTarget.destroy(resourceManager);
splashTarget = null;
SplashDispatcher.reset();
}
} else if (splashTarget != null) {
splashTeardownPending = true;
}
if (event.requiresSync) {
frameManager.requestSyncFlushOnAllRegisteredFrames();
@@ -407,12 +411,12 @@ public class SDLGPURenderBackend extends RenderBackend {
@Override public boolean wantsDisplayUpdateGateTiming() { return false; }
@Override public long lastFrameGateNanos() {
if (presenter != null) return frameManager.windowFrame().lastFrameGateNanos;
if (presenter != null && presenter.isEngaged()) return frameManager.windowFrame().lastFrameGateNanos;
return frameManager.lastFrameGateNanos();
}
@Override public long lastFrameGateEndNanos() {
if (presenter != null) return frameManager.windowFrame().lastFrameGateEndNanos;
if (presenter != null && presenter.isEngaged()) return frameManager.windowFrame().lastFrameGateEndNanos;
return frameManager.lastFrameGateEndNanos();
}
@@ -516,9 +520,8 @@ public class SDLGPURenderBackend extends RenderBackend {
@Override public boolean handleMakeCurrent(Object drawable) {
if (!isSDLManagedDrawable(drawable)) return false;
Lwjgl3GLCapabilitiesShim.installOnCurrentThread(advertisedCapabilities());
final OffscreenTarget splash = splashTarget;
if (splash != null && Thread.currentThread() != GLStateManager.getMainThread()) {
s().boundFboId = splash.fboId();
if (splashTarget != null && Thread.currentThread() != GLStateManager.getMainThread()) {
s().boundFboId = splashTarget.fboId();
frameManager.frame().swapchainUnavailable = true;
}
return true;
@@ -539,8 +542,7 @@ public class SDLGPURenderBackend extends RenderBackend {
}
@Override public boolean handleSwapBuffers() {
final OffscreenTarget splash = splashTarget;
if (splash != null && splash.isFor(s()) && Thread.currentThread() != GLStateManager.getMainThread()) {
if (splashTarget != null && splashTarget.isFor(s()) && Thread.currentThread() != GLStateManager.getMainThread()) {
endFrameUploadFlush();
frameManager.endFrame();
SplashDispatcher.signalFrameReady((int) s().viewportW, (int) s().viewportH);
@@ -558,24 +560,13 @@ public class SDLGPURenderBackend extends RenderBackend {
final long drawnSize = SplashDispatcher.getDrawnSize();
final int srcW = Math.max(1, Math.min((int) (drawnSize >> 32), target.width()));
final int srcH = Math.max(1, Math.min((int) drawnSize, target.height()));
frameManager.presentSplash(target.colorTexture(), srcW, srcH);
}
private void finishSplash() {
splashTeardownPending = false;
final OffscreenTarget target = splashTarget;
if (target == null) return;
SplashDispatcher.signalFrameReady();
SplashDispatcher.tryDispatch(this, target, true);
if (presenter != null) presenter.drain();
splashTarget = null;
target.destroy(resourceManager);
SplashDispatcher.reset();
final FrameState f = frameManager.frame();
frameManager.presentBlit(f, target.colorTexture(), srcW, srcH, SDLSurface.SDL_FLIP_VERTICAL);
f.presentedThisFrame = false;
}
@Override public void onFrameBegin() {
if (shutdown) return;
if (splashTeardownPending) finishSplash();
if (GLStateManager.isSplashComplete()) applyPendingVSync();
frameManager.beginFrame();
beginFrameInit();
@@ -30,7 +30,6 @@ import java.util.concurrent.atomic.AtomicLong;
import static org.lwjgl.sdl.SDLGPU.*;
import static org.lwjgl.sdl.SDLSurface.SDL_FLIP_NONE;
import static org.lwjgl.sdl.SDLSurface.SDL_FLIP_VERTICAL;
import static org.lwjgl.system.MemoryStack.*;
/**
@@ -62,6 +61,7 @@ public final class FrameManager {
public boolean fbo0UsedThisFrame;
public boolean presentedThisFrame;
public boolean swapchainUnavailable;
public boolean windowThreadChecked;
public long renderPassGeneration;
public boolean wantFenceOnNextSubmit;
@@ -464,20 +464,6 @@ public final class FrameManager {
}
}
private volatile boolean acquireThreadReported;
private void checkAcquireOnWindowThread() {
if (acquireThreadReported) return;
final Thread self = Thread.currentThread();
final Thread window = device.getWindowThread();
if (window == null || window == self) return;
acquireThreadReported = true;
final String message = "Swapchain acquired on '" + self.getName() + "', window created on '" + window.getName() + "'";
if (SystemProperties.isDeobf() && !SystemProperties.DISABLE_SDL_PRESENTER_THREAD) throw new IllegalStateException(message);
LOG.warn(message);
}
public long ensureCopyPass() {
final FrameState f = frame();
if (f.copyPass != 0) {
@@ -877,7 +863,7 @@ public final class FrameManager {
return frame().lastFrameGateEndNanos;
}
private volatile Presenter presenter;
private Presenter presenter;
public void setPresenter(Presenter presenter) {
this.presenter = presenter;
@@ -891,24 +877,18 @@ public final class FrameManager {
public void presentFinalTarget() {
if (!finalTarget.hasContent()) return;
present(finalTarget.colorTexture(), finalTarget.width(), finalTarget.height(), SDL_FLIP_NONE, false);
}
public void presentSplash(long srcTexture, int srcW, int srcH) {
present(srcTexture, srcW, srcH, SDL_FLIP_VERTICAL, true);
}
private void present(long srcTexture, int srcW, int srcH, int flipMode, boolean splash) {
final FrameState f = frame();
if (f.presentedThisFrame) return;
final long texture = finalTarget.colorTexture();
final int width = finalTarget.width();
final int height = finalTarget.height();
final Presenter p = presenter;
if (p != null) {
if (p != null && p.isEngaged()) {
final FrameState f = frame();
if (f.presentedThisFrame) return;
f.presentedThisFrame = true;
p.requestPresent(srcTexture, srcW, srcH, flipMode);
p.requestPresent(texture, width, height);
} else {
presentBlit(f, srcTexture, srcW, srcH, flipMode);
presentBlit(frame(), texture, width, height, SDL_FLIP_NONE);
}
if (splash) f.presentedThisFrame = false;
}
private final AtomicLong windowAcquireWaitNanos = new AtomicLong();
@@ -935,8 +915,8 @@ public final class FrameManager {
else f.presentSkipsThisFrame++;
}
public void presentOnWindowThread(long srcTexture, int srcW, int srcH, int flipMode) {
presentBlit(windowFrame, srcTexture, srcW, srcH, flipMode);
public void presentOnWindowThread(long srcTexture, int srcW, int srcH) {
presentBlit(windowFrame, srcTexture, srcW, srcH, SDL_FLIP_NONE);
windowFrame.presentedThisFrame = false;
windowFrame.swapchainUnavailable = false;
}
@@ -945,7 +925,16 @@ public final class FrameManager {
if (srcTexture == 0 || srcW <= 0 || srcH <= 0) return false;
if (f.presentedThisFrame || f.swapchainUnavailable) return false;
checkAcquireOnWindowThread();
if (!f.windowThreadChecked) {
f.windowThreadChecked = true;
final Thread self = Thread.currentThread();
final Thread windowThread = device.getWindowThread();
if (windowThread != null && windowThread != self) {
LOG.warn("Swapchain acquired on '{}' but the SDL window was created on '{}'; SDL requires acquire on the window-creating thread", self.getName(), windowThread.getName());
} else {
LOG.info("First swapchain acquire on thread={}", self.getName());
}
}
final long window = device.getClaimedWindow();
if (window == 0) return false;
@@ -1,5 +1,7 @@
package com.gtnewhorizons.angelica.sdlgpu.frame;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import java.util.concurrent.Executor;
import java.util.concurrent.Semaphore;
@@ -14,13 +16,17 @@ public final class Presenter {
this.windowThreadExecutor = windowThreadExecutor;
}
public void requestPresent(long srcTexture, int srcW, int srcH, int flipMode) {
public boolean isEngaged() {
return windowThreadExecutor != null && GLStateManager.isSplashComplete();
}
public void requestPresent(long srcTexture, int srcW, int srcH) {
pending.acquireUninterruptibly();
boolean submitted = false;
try {
windowThreadExecutor.execute(() -> {
try {
frameManager.presentOnWindowThread(srcTexture, srcW, srcH, flipMode);
frameManager.presentOnWindowThread(srcTexture, srcW, srcH);
} finally {
pending.release();
}
@@ -57,6 +57,7 @@ final class SdlFramePlots {
private static final long PLOT_PIPELINE_KEY_RECOMPUTES = Tracy.plotHandle("sdl.pipelineKeyRecomputes");
private static final long PLOT_PIPELINE_FAST_PATH_HITS = Tracy.plotHandle("sdl.pipelineFastPathHits");
private static final long PLOT_MID_FRAME_SUBMITS = Tracy.plotHandle("sdl.midFrameSubmits");
private static final long PLOT_GATE_US = Tracy.plotHandle("sdl.gateUs");
private static final int[] contextCounters = new int[SDLGPURenderBackend.CTR_COUNT];
@@ -109,5 +110,6 @@ final class SdlFramePlots {
Tracy.plotInt(PLOT_EMPTY_FRAMES, f.emptyFramesThisFrame);
Tracy.plotInt(PLOT_DROPPED_DRAWS, f.droppedDrawsThisFrame);
Tracy.plotInt(PLOT_MID_FRAME_SUBMITS, f.midFrameSubmitsThisFrame);
Tracy.plotInt(PLOT_GATE_US, f.lastFrameGateNanos / 1000);
}
}
@@ -681,7 +681,7 @@ public final class ShaderManager {
return null;
}
LOG.info("Vertex attribute conversion: program {} converted {}", program, attribs);
if (SystemProperties.dumpShaders()) dumpVariantSource(program, src);
if (SystemProperties.DUMP_SHADERS) dumpVariantSource(program, src);
return v;
} finally {
memFree(r.spirv());
@@ -80,7 +80,7 @@ public final class DxbcCrossCompile {
return new Output(copy, cached.entrypoint);
}
final int dumpId = SystemProperties.dumpShaders() ? CrossCompileUtil.SHADER_DUMP_COUNTER.getAndIncrement() : -1;
final int dumpId = SystemProperties.DUMP_SHADERS ? CrossCompileUtil.SHADER_DUMP_COUNTER.getAndIncrement() : -1;
if (dumpId >= 0) CrossCompileUtil.dumpSpirv(spirv, dumpId, glShaderType);
final String hlsl = compileToHlsl(spirv, glShaderType);
@@ -87,7 +87,7 @@ public final class MslCrossCompile {
return new Output(copy, cached.entrypoint);
}
final int dumpId = SystemProperties.dumpShaders() ? CrossCompileUtil.SHADER_DUMP_COUNTER.getAndIncrement() : -1;
final int dumpId = SystemProperties.DUMP_SHADERS ? CrossCompileUtil.SHADER_DUMP_COUNTER.getAndIncrement() : -1;
if (dumpId >= 0) CrossCompileUtil.dumpSpirv(spirv, dumpId, glShaderType);
try (MemoryStack stack = stackPush()) {
@@ -33,10 +33,10 @@ public final class SplashDispatcher {
return (long) w << 32 | (h & 0xffffffffL);
}
public static void tryDispatch(SDLGPURenderBackend backend, OffscreenTarget target, boolean force) {
public static void tryDispatch(SDLGPURenderBackend backend, OffscreenTarget target) {
if (!frameReady || target == null) return;
final long now = System.nanoTime();
if (!force && now - lastBlitNanos < MIN_INTERVAL_NS) return;
if (now - lastBlitNanos < MIN_INTERVAL_NS) return;
lastBlitNanos = now;
frameReady = false;
backend.dispatchSplashBlit(target);
@@ -10,7 +10,6 @@ import java.util.concurrent.Executor;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.lwjgl.sdl.SDLSurface.SDL_FLIP_NONE;
@Timeout(10)
class PresenterTest {
@@ -44,10 +43,10 @@ class PresenterTest {
final DeferredExecutor executor = new DeferredExecutor();
final Presenter p = presenter(executor);
p.requestPresent(1L, 10, 10, SDL_FLIP_NONE);
p.requestPresent(1L, 10, 10);
assertEquals(1, executor.tasks.size());
final Thread second = new Thread(() -> p.requestPresent(2L, 10, 10, SDL_FLIP_NONE));
final Thread second = new Thread(() -> p.requestPresent(2L, 10, 10));
second.start();
awaitWaiting(second);
assertEquals(1, executor.tasks.size(), "second present must not enqueue while the first is in flight");
@@ -62,7 +61,7 @@ class PresenterTest {
final DeferredExecutor executor = new DeferredExecutor();
final Presenter p = presenter(executor);
p.requestPresent(1L, 10, 10, SDL_FLIP_NONE);
p.requestPresent(1L, 10, 10);
final Thread drainer = new Thread(p::drain);
drainer.start();
@@ -75,8 +74,8 @@ class PresenterTest {
@Test
void anInlineExecutorReleasesTheSlotImmediately() {
final Presenter p = new Presenter(new FrameManager(new Device()), Runnable::run);
p.requestPresent(1L, 10, 10, SDL_FLIP_NONE);
p.requestPresent(2L, 10, 10, SDL_FLIP_NONE);
p.requestPresent(1L, 10, 10);
p.requestPresent(2L, 10, 10);
p.drain();
}
@@ -88,7 +87,7 @@ class PresenterTest {
fm.frame();
final int before = fm.registeredFrameCount();
p.requestPresent(1L, 10, 10, SDL_FLIP_NONE);
p.requestPresent(1L, 10, 10);
final Thread windowThread = new Thread(executor::runNext, "window-thread");
windowThread.start();
@@ -96,18 +95,4 @@ class PresenterTest {
assertEquals(before, fm.registeredFrameCount(), "the window thread must stay out of the frame registry");
}
@Test
void theSplashPresentGoesThroughTheWindowThreadToo() {
final DeferredExecutor executor = new DeferredExecutor();
final FrameManager fm = new FrameManager(new Device());
fm.setPresenter(new Presenter(fm, executor));
fm.frame();
final int before = fm.registeredFrameCount();
fm.presentSplash(1L, 10, 10);
assertEquals(1, executor.tasks.size(), "the splash blit must be enqueued on the window thread");
assertEquals(before, fm.registeredFrameCount(), "the splash present must not touch the calling thread's frame");
}
}
@@ -1,76 +0,0 @@
package com.gtnewhorizons.angelica.sdlgpu.shader;
import com.gtnewhorizons.angelica.glsm.shader.GlslVulkanPreprocess;
import com.gtnewhorizons.angelica.glsm.shader.SpirvCompiler;
import com.gtnewhorizons.angelica.glsm.testutil.TestPaths;
import com.gtnewhorizons.angelica.sdlgpu.sampler.SamplerLookup;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import org.junit.jupiter.api.Test;
import org.lwjgl.opengl.GL20;
import org.lwjgl.util.shaderc.Shaderc;
import java.nio.ByteBuffer;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.lwjgl.system.MemoryUtil.memFree;
class FontFilterVertexSamplerTest {
private static final String FONT_FILTER_VSH = TestPaths.readString("src/main/resources/assets/angelica/shaders/fontFilter.vsh");
private static String runSdlPipeline(String raw) {
final GlslVulkanPreprocess.Result pre = GlslVulkanPreprocess.run(raw, GL20.GL_VERTEX_SHADER, "fontFilter.vsh", true);
String src = pre != null ? pre.rewrittenSource() : raw;
src = ClipZRemap.injectGLToVulkanClipZ(src);
src = SamplerStripper.stripUnused(src);
return src;
}
private static ShaderManager.StageReflection reflect(String source) {
final SpirvCompiler.Result r = SpirvCompiler.compile(source, Shaderc.shaderc_vertex_shader,
"fontFilter.vsh", SpirvCompiler.Options.vulkanForced460Core());
assertNotNull(r.spirv(), () -> "fontFilter.vsh failed to compile for Vulkan: " + r.error());
final ByteBuffer spirv = r.spirv();
try {
return ShaderManager.reflectStage(spirv, true);
} finally {
memFree(spirv);
}
}
@Test
void samplerSurvivesStrippingAndReflectsOnTheVertexStage() {
final String transformed = runSdlPipeline(FONT_FILTER_VSH);
assertTrue(transformed.contains("uniform sampler2D lightmap"), "a reference inside a runtime if must keep the declaration; only preprocessor #if hides it");
final List<String> samplers = reflect(transformed).samplerNames();
assertEquals(List.of("lightmap"), samplers, "the vertex stage must expose exactly the lightmap sampler");
}
@Test
void looseVec3UniformReflectsWithAStd140Offset() {
final List<ShaderManager.UboMember> members = reflect(runSdlPipeline(FONT_FILTER_VSH)).uboMembers();
final ShaderManager.UboMember lightmap = members.stream()
.filter(m -> m.name().endsWith("u_Lightmap"))
.findFirst()
.orElseThrow(() -> new AssertionError("u_Lightmap missing from the default uniform block: " + members));
assertEquals(3, lightmap.vectorSize(), "u_Lightmap must reflect as a 3-wide vector");
assertEquals(1, lightmap.columns(), "u_Lightmap is a vector, not a matrix");
assertEquals(0, lightmap.arrayStride(), "a scalar member takes Std140Writer's contiguous path");
assertEquals(0, lightmap.offset() % 16, "std140 aligns a vec3 to 16 bytes");
}
@Test
void samplerNamedLightmapResolvesToTextureUnitOne() {
final List<String> samplers = reflect(runSdlPipeline(FONT_FILTER_VSH)).samplerNames();
final Object2IntOpenHashMap<String> noExplicitUnits = new Object2IntOpenHashMap<>();
noExplicitUnits.defaultReturnValue(-1);
assertEquals(1, SamplerLookup.getSamplerTextureUnit(samplers, noExplicitUnits, 0), "even without a glUniform1i the SDL fallback must put a sampler named 'lightmap' on unit 1");
}
}
@@ -4,61 +4,45 @@ import com.google.common.collect.ImmutableSet;
import com.gtnewhorizon.gtnhlib.bytebuf.MemoryStack;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.IndexBuffer;
import com.gtnewhorizon.gtnhlib.util.font.GlyphReplacements;
import static com.gtnewhorizons.angelica.client.font.ColorCodeUtils.FORMATTING_CHAR;
import static com.gtnewhorizons.angelica.client.font.ColorCodeUtils.GRADIENT_PAYLOAD;
import static com.gtnewhorizons.angelica.client.font.ColorCodeUtils.SECTION_X_LENGTH;
import static com.gtnewhorizons.angelica.client.font.ColorCodeUtils.SECTION_X_PAYLOAD;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.config.FontConfig;
import com.gtnewhorizons.angelica.hudcaching.HUDCaching;
import com.gtnewhorizons.angelica.AngelicaMod;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.ffp.FFPVertexLighting;
import com.gtnewhorizons.angelica.glsm.ffp.ShaderManager;
import com.gtnewhorizons.angelica.glsm.hooks.GLSMConfig;
import com.gtnewhorizons.angelica.glsm.states.BlendState;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import com.gtnewhorizons.angelica.glsm.streaming.PersistentStreamingBuffer;
import com.gtnewhorizons.angelica.glsm.streaming.StreamingUploader;
import com.gtnewhorizons.angelica.hudcaching.HUDCaching;
import com.gtnewhorizons.angelica.mixins.interfaces.FontRendererAccessor;
import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher;
import com.gtnewhorizons.angelica.rendering.tesr.TesrBatchRenderer;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import lombok.Setter;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gl.program.Program;
import net.coderbot.iris.gl.program.ProgramBuilder;
import net.coderbot.iris.layer.GbufferPrograms;
import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline;
import net.coderbot.iris.pipeline.PipelineManager;
import net.coderbot.iris.uniforms.CapturedRenderingState;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ResourceLocation;
import org.embeddedt.embeddium.impl.render.shader.ShaderLoader;
import org.joml.Matrix4f;
import org.joml.Vector3f;
import org.joml.Vector4f;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL20;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Objects;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryStack.stackPush;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAlloc;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memFree;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetByte;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetFloat;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutByte;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutFloat;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutShort;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memRealloc;
import static com.gtnewhorizons.angelica.client.font.ColorCodeUtils.FORMATTING_CHAR;
import static com.gtnewhorizons.angelica.client.font.ColorCodeUtils.GRADIENT_PAYLOAD;
import static com.gtnewhorizons.angelica.client.font.ColorCodeUtils.SECTION_X_LENGTH;
import static com.gtnewhorizons.angelica.client.font.ColorCodeUtils.SECTION_X_PAYLOAD;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*;
/**
* A batching replacement for {@code FontRenderer}
@@ -83,8 +67,6 @@ public class BatchingFontRenderer {
private final int AAStrength;
private final int alphaTestRefLocation;
private final int mvpMatrixLocation;
private final int lightmapLocation;
private final int lightmapSamplerLocation;
private final int fontShaderId;
final boolean isSGA;
@@ -97,7 +79,6 @@ public class BatchingFontRenderer {
private static class FontAAShader {
private static Program fontShader = null;
public static Program getProgram() {
if (fontShader == null) {
final String vsh = ShaderLoader.getShaderSource("angelica:fontFilter.vsh");
@@ -130,8 +111,6 @@ public class BatchingFontRenderer {
AAStrength = GLStateManager.glGetUniformLocation(fontShaderId, "strength");
alphaTestRefLocation = GLStateManager.glGetUniformLocation(fontShaderId, "alphaTestRef");
mvpMatrixLocation = GLStateManager.glGetUniformLocation(fontShaderId, "u_MVPMatrix");
lightmapLocation = GLStateManager.glGetUniformLocation(fontShaderId, "u_Lightmap");
lightmapSamplerLocation = GLStateManager.glGetUniformLocation(fontShaderId, "lightmap");
if (ebo == null) {
ebo = new IndexBuffer();
vbo = GLStateManager.glGenBuffers();
@@ -149,9 +128,6 @@ public class BatchingFontRenderer {
// [v, v, t, t, c, c, c, c, tb, tb, tb, tb]
// v, t and tb are floats, c is bytes; 36 bytes total
private static final int VERTEX_SIZE = 36;
/** {@code OpenGlHelper.lightmapTexUnit} */
private static final int LIGHTMAP_TEX_UNIT = 1;
private static int rawCapacity = INITIAL_BATCH_SIZE * VERTEX_SIZE;
private static ByteBuffer vertexData = memAlloc(rawCapacity);
private static long vertexDataAddress = memAddress0(vertexData);
@@ -162,7 +138,6 @@ public class BatchingFontRenderer {
private static int fontVAO = 0;
private static int vbo;
private static IndexBuffer ebo;
private static int lightmapSamplerProgram;
private static final int RING_CAPACITY = 2 * 1024 * 1024;
private static PersistentStreamingBuffer streamRing;
@@ -183,74 +158,11 @@ public class BatchingFontRenderer {
private int blendSrcRGB = GL11.GL_SRC_ALPHA;
private int blendDstRGB = GL11.GL_ONE_MINUS_SRC_ALPHA;
private final BlendState blendStateBefore = new BlendState();
private static final BlendState deferredBlendStateBefore = new BlendState();
private float lightmapU = 0.0f;
private float lightmapV = 0.0f;
private boolean lightmapActive = false;
private int lightmapTextureId = 0;
private final Vector3f lightingFactor = new Vector3f(1.0f, 1.0f, 1.0f);
private boolean lightingFactorActive = false;
private static final Vector4f scratchLightmapUv = new Vector4f();
private int applyLighting(int argb) {
if (!lightingFactorActive) return argb;
final int red = Math.max(0, Math.min(255, (int) (((argb >> 16) & 0xFF) * lightingFactor.x + 0.5f)));
final int green = Math.max(0, Math.min(255, (int) (((argb >> 8) & 0xFF) * lightingFactor.y + 0.5f)));
final int blue = Math.max(0, Math.min(255, (int) ((argb & 0xFF) * lightingFactor.z + 0.5f)));
return (argb & 0xFF000000) | (red << 16) | (green << 8) | blue;
}
/**
* True only for a perspective projection (world-space text: signs, nameplates, etc).
* GUI/HUD text uses an orthographic projection and must never be shaded by world lighting -
* mods rely on getting back the exact color they requested (e.g. GTNHLib's ColorResource).
*/
private static boolean isWorldSpaceText() {
return GLStateManager.getProjectionMatrix().m33() == 0.0f;
}
private void captureLightmapState() {
final int unitBinding = GLStateManager.getTextures().getTextureUnitBindings(LIGHTMAP_TEX_UNIT).getBinding();
final boolean active = isWorldSpaceText() && unitBinding != 0;
float u = 0.0f;
float v = 0.0f;
int texture = 0;
if (active) {
scratchLightmapUv.set(GLSMConfig.lastBrightnessX, GLSMConfig.lastBrightnessY, 0.0f, 1.0f).mul(GLStateManager.getTextures().getTextureUnitMatrix(LIGHTMAP_TEX_UNIT));
u = scratchLightmapUv.x;
v = scratchLightmapUv.y;
texture = unitBinding;
}
if (active == lightmapActive && u == lightmapU && v == lightmapV && texture == lightmapTextureId) {
return;
}
sealBatchSegment();
lightmapActive = active;
lightmapU = u;
lightmapV = v;
lightmapTextureId = texture;
}
private static final class TextSegment {
final Matrix4f mvp = new Matrix4f();
final Matrix4f modelView = new Matrix4f();
BatchingFontRenderer owner;
int cmdStart;
int cmdEnd;
float lightmapU;
float lightmapV;
boolean lightmapActive;
int lightmapTexture;
int packedLight;
float normalX, normalY, normalZ;
int blockEntityId;
}
// 16-bit EBO index range
@@ -262,6 +174,7 @@ public class BatchingFontRenderer {
private int deferredCmdWatermark;
private static final ObjectArrayList<TextSegment> deferredSegments = ObjectArrayList.wrap(new TextSegment[16], 0);
private static final ObjectArrayList<TextSegment> deferredSegmentPool = ObjectArrayList.wrap(new TextSegment[16], 0);
private boolean deferCurrentBatch;
private final Matrix4f batchProj = new Matrix4f();
private final Matrix4f batchModelView = new Matrix4f();
@@ -270,6 +183,7 @@ public class BatchingFontRenderer {
private int batchSealedEnd;
private static BatchingFontRenderer arenaOwner;
private void allocateBuffers() {
populateEBO(rawCapacity / VERTEX_SIZE);
}
@@ -341,7 +255,6 @@ public class BatchingFontRenderer {
private void pushVtx(float x, float y, int rgba, float u, float v, float uMin, float uMax, float vMin, float vMax) {
final long ptr = vertexDataAddress + vertexDataPos;
rgba = applyLighting(rgba);
// v, v
memPutFloat(ptr, x);
@@ -493,10 +406,6 @@ public class BatchingFontRenderer {
}
}
private void resolveModelView(Matrix4f dest) {
dest.set(batchMatrixValid ? batchModelView : GLStateManager.getModelViewMatrix());
}
private void sealBatchSegment() {
final int end = batchCommands.size();
if (end == batchSealedEnd) return;
@@ -505,17 +414,6 @@ public class BatchingFontRenderer {
segment.cmdStart = batchSealedEnd;
segment.cmdEnd = end;
resolveMvp(segment.mvp);
resolveModelView(segment.modelView);
segment.lightmapActive = lightmapActive;
segment.lightmapU = lightmapU;
segment.lightmapV = lightmapV;
segment.lightmapTexture = lightmapTextureId;
segment.packedLight = GLSMConfig.packedLastBrightness();
final Vector3f normal = ShaderManager.getCurrentNormal();
segment.normalX = normal.x;
segment.normalY = normal.y;
segment.normalZ = normal.z;
segment.blockEntityId = CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity();
batchSegments.add(segment);
batchSealedEnd = end;
}
@@ -536,29 +434,27 @@ public class BatchingFontRenderer {
}
batchDepth--;
if (batchDepth == 0) {
// We finished any nested batches.
if (shouldDeferNow()) {
deferBatch();
} else {
flushBatch();
}
// We finished any nested batches
flushBatch();
}
}
private static boolean shouldDeferNow() {
if (!GLStateManager.isMainThread()) return false;
return TesrBatchRenderer.INSTANCE.hasPendingGeometry() || ModelPartBatcher.INSTANCE.isActive();
}
public void beginDeferredBatch() {
if (batchDepth == 0 && shouldDeferNow() && deferredIdxPos / 6 > QUAD_BUDGET / 2) {
deferCurrentBatch = batchDepth == 0 && TesrBatchRenderer.INSTANCE.hasActivePass() || ModelPartBatcher.INSTANCE.isActive();
if (deferCurrentBatch && deferredIdxPos / 6 > QUAD_BUDGET / 2) {
flushDeferredText();
}
beginBatch();
}
public void endDeferredBatch() {
endBatch();
if (deferCurrentBatch && batchDepth == 1) {
deferCurrentBatch = false;
batchDepth = 0;
deferBatch();
} else {
endBatch();
}
}
private void deferBatch() {
@@ -583,123 +479,34 @@ public class BatchingFontRenderer {
public static void flushDeferredText() {
if (deferredSegments.isEmpty()) return;
if (deferredSegments.getFirst().owner.shouldDrawThroughPipeline()) {
flushDeferredThroughPipeline();
return;
}
GLStateManager.beginForeignDraw();
try {
flushDeferredTextInner();
} finally {
GLStateManager.endForeignDraw();
}
}
private static void flushDeferredThroughPipeline() {
final BatchingFontRenderer first = deferredSegments.getFirst().owner;
final boolean isTextureEnabledBefore = GLStateManager.glIsEnabled(GL11.GL_TEXTURE_2D);
final boolean isBlendEnabledBefore = GLStateManager.isEffectiveBlendEnabled();
final boolean isAlphaTestEnabledBefore = GLStateManager.isEffectiveAlphaTestEnabled();
GLStateManager.getEffectiveBlendState(deferredBlendStateBefore);
final int boundTextureBefore = GLStateManager.glGetInteger(GL11.GL_TEXTURE_BINDING_2D);
final boolean depthMaskBefore = GLStateManager.isEffectiveDepthMaskEnabled();
final int prevBlockEntityId = CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity();
boolean textureChanged = false;
GLStateManager.enableTexture();
GLStateManager.enableAlphaTest();
GLStateManager.enableBlend();
GLStateManager.tryBlendFuncSeparate(first.blendSrcRGB, first.blendDstRGB, GL11.GL_ONE, GL11.GL_ZERO);
GLStateManager.glDepthMask(false);
final Boolean prevTranslucency = GbufferPrograms.beginTranslucencyDeclaration(Boolean.TRUE);
GbufferPrograms.setBlockEntityDefaults();
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
GLStateManager.glPushMatrix();
try {
for (final TextSegment segment : deferredSegments) {
final BatchingFontRenderer owner = segment.owner;
if (segment.cmdStart == segment.cmdEnd) continue;
GLStateManager.setModelViewMatrix(segment.modelView);
CapturedRenderingState.INSTANCE.setCurrentBlockEntity(segment.blockEntityId);
final FontDrawCmd[] cmdsData = owner.batchCommands.elements();
Arrays.sort(cmdsData, segment.cmdStart, segment.cmdEnd, FontDrawCmd.DRAW_ORDER_COMPARATOR);
textureChanged |= emitRangeThroughPipeline(owner, cmdsData, segment.cmdStart, segment.cmdEnd,
segment.packedLight, segment.normalX, segment.normalY, segment.normalZ);
}
} finally {
GLStateManager.glPopMatrix();
CapturedRenderingState.INSTANCE.setCurrentBlockEntity(prevBlockEntityId);
GbufferPrograms.endTranslucencyDeclaration(prevTranslucency);
GLStateManager.glDepthMask(depthMaskBefore);
if (isTextureEnabledBefore) {
GLStateManager.enableTexture();
} else {
GLStateManager.disableTexture();
}
if (isBlendEnabledBefore) {
GLStateManager.enableBlend();
} else {
GLStateManager.disableBlend();
}
GLStateManager.tryBlendFuncSeparate(deferredBlendStateBefore.getSrcRgb(), deferredBlendStateBefore.getDstRgb(),
deferredBlendStateBefore.getSrcAlpha(), deferredBlendStateBefore.getDstAlpha());
if (isAlphaTestEnabledBefore) {
GLStateManager.enableAlphaTest();
} else {
GLStateManager.disableAlphaTest();
}
if (textureChanged) {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, boundTextureBefore);
}
discardDeferredText();
}
}
private static void flushDeferredTextInner() {
uploadVertexData(deferredVertexPos);
final int prevProgram = GLStateManager.glGetInteger(GL20.GL_CURRENT_PROGRAM);
final boolean isTextureEnabledBefore = GLStateManager.glIsEnabled(GL11.GL_TEXTURE_2D);
final boolean isBlendEnabledBefore = GLStateManager.isEffectiveBlendEnabled();
final boolean isAlphaTestEnabledBefore = GLStateManager.isEffectiveAlphaTestEnabled();
GLStateManager.getEffectiveBlendState(deferredBlendStateBefore);
final int shadeModelBefore = GLStateManager.glGetInteger(GL11.GL_SHADE_MODEL);
final boolean isBlendEnabledBefore = GLStateManager.glIsEnabled(GL11.GL_BLEND);
final int boundTextureBefore = GLStateManager.glGetInteger(GL11.GL_TEXTURE_BINDING_2D);
final int lightmapBindingBefore = boundLightmapTexture();
final boolean depthTestBefore = GLStateManager.getDepthTest().isEnabled();
final boolean depthMaskBefore = GLStateManager.isEffectiveDepthMaskEnabled();
final boolean depthMaskBefore = GLStateManager.getDepthState().isEnabled();
deferredSegments.get(0).owner.setupFontDrawState();
GLStateManager.glDepthMask(false);
flushLastTexture = DUMMY_RESOURCE_LOCATION;
flushTextureChanged = false;
resetFlushLightmap();
try {
try (MemoryStack stack = stackPush()) {
final FloatBuffer mvpBuf = stack.mallocFloat(16);
for (final TextSegment segment : deferredSegments) {
mvpBuf.clear();
segment.mvp.get(mvpBuf);
GLStateManager.glUniformMatrix4(segment.owner.mvpMatrixLocation, false, mvpBuf);
uploadLightmap(segment.owner.lightmapLocation, segment.lightmapActive, segment.lightmapU,
segment.lightmapV, segment.lightmapTexture);
drawCommands(segment.owner.batchCommands.elements(), segment.cmdStart, segment.cmdEnd, segment.owner);
}
try (MemoryStack stack = stackPush()) {
final FloatBuffer mvpBuf = stack.mallocFloat(16);
for (int i = 0, n = deferredSegments.size(); i < n; i++) {
final TextSegment segment = deferredSegments.get(i);
mvpBuf.clear();
segment.mvp.get(mvpBuf);
GLStateManager.glUniformMatrix4(segment.owner.mvpMatrixLocation, false, mvpBuf);
drawCommands(segment.owner.batchCommands.elements(), segment.cmdStart, segment.cmdEnd, segment.owner);
}
} finally {
restoreFontDrawState(prevProgram, isTextureEnabledBefore, isBlendEnabledBefore, boundTextureBefore,
lightmapBindingBefore, isAlphaTestEnabledBefore, deferredBlendStateBefore, shadeModelBefore);
restoreDepth(depthTestBefore, depthMaskBefore);
discardDeferredText();
}
restoreFontDrawState(prevProgram, isTextureEnabledBefore, isBlendEnabledBefore, boundTextureBefore);
restoreDepth(depthTestBefore, depthMaskBefore);
discardDeferredText();
}
public static void discardDeferredText() {
@@ -710,7 +517,6 @@ public class BatchingFontRenderer {
segment.owner.recycleBatchSegments();
segment.owner.batchSealedEnd = 0;
segment.owner.batchMatrixValid = false;
segment.owner.resetLightmapState();
segment.owner = null;
}
deferredSegmentPool.addAll(deferredSegments);
@@ -738,47 +544,18 @@ public class BatchingFontRenderer {
}
private static final Matrix4f scratchMvp = new Matrix4f();
private static final Matrix4f scratchModelView = new Matrix4f();
private int fontAAModeLast = -1;
private int fontAAStrengthLast = -1;
private void flushBatch() {
final boolean locked = GLStateManager.acquireDrawLock();
try {
if (shouldDrawThroughPipeline()) {
flushBatchThroughPipeline();
} else {
GLStateManager.beginForeignDraw();
try {
flushBatchInner();
} finally {
GLStateManager.endForeignDraw();
}
}
flushBatchInner();
} finally {
if (locked) GLStateManager.releaseDrawLock();
}
}
private boolean shouldDrawThroughPipeline() {
if (FontConfig.fontAAMode != 0) {
return false;
}
if (!GLStateManager.isMainThread()) {
return false;
}
final PipelineManager pipelines = Iris.getPipelineManagerNullable();
if (pipelines == null) {
return false;
}
return !Tessellator.instance.isDrawing
&& pipelines.getPipelineNullable() instanceof DeferredWorldRenderingPipeline drp
&& drp.shouldOverrideShaders();
}
private void flushBatchInner() {
final int cmdCount = batchCommands.size();
final int segmentCount = batchSegments.size();
@@ -799,19 +576,14 @@ public class BatchingFontRenderer {
Arrays.sort(cmds, batchSealedEnd, cmdCount, FontDrawCmd.DRAW_ORDER_COMPARATOR);
final boolean isTextureEnabledBefore = GLStateManager.glIsEnabled(GL11.GL_TEXTURE_2D);
final boolean isBlendEnabledBefore = GLStateManager.isEffectiveBlendEnabled();
final boolean isAlphaTestEnabledBefore = GLStateManager.isEffectiveAlphaTestEnabled();
GLStateManager.getEffectiveBlendState(blendStateBefore);
final int shadeModelBefore = GLStateManager.glGetInteger(GL11.GL_SHADE_MODEL);
final boolean isBlendEnabledBefore = GLStateManager.glIsEnabled(GL11.GL_BLEND);
final int boundTextureBefore = GLStateManager.glGetInteger(GL11.GL_TEXTURE_BINDING_2D);
final int lightmapBindingBefore = boundLightmapTexture();
final boolean depthTestBefore = GLStateManager.getDepthTest().isEnabled();
final boolean depthMaskBefore = GLStateManager.isEffectiveDepthMaskEnabled();
final boolean depthMaskBefore = GLStateManager.getDepthState().isEnabled();
setupFontDrawState();
flushLastTexture = DUMMY_RESOURCE_LOCATION;
flushTextureChanged = false;
resetFlushLightmap();
try (MemoryStack stack = stackPush()) {
final FloatBuffer mvpBuf = stack.mallocFloat(16);
for (int i = 0; i < segmentCount; i++) {
@@ -819,7 +591,6 @@ public class BatchingFontRenderer {
mvpBuf.clear();
segment.mvp.get(mvpBuf);
GLStateManager.glUniformMatrix4(mvpMatrixLocation, false, mvpBuf);
uploadLightmap(lightmapLocation, segment.lightmapActive, segment.lightmapU, segment.lightmapV, segment.lightmapTexture);
drawCommands(cmds, segment.cmdStart, segment.cmdEnd, this);
}
if (batchSealedEnd < cmdCount) {
@@ -827,12 +598,10 @@ public class BatchingFontRenderer {
resolveMvp(scratchMvp);
scratchMvp.get(mvpBuf);
GLStateManager.glUniformMatrix4(mvpMatrixLocation, false, mvpBuf);
uploadLightmap(lightmapLocation, lightmapActive, lightmapU, lightmapV, lightmapTextureId);
drawCommands(cmds, batchSealedEnd, cmdCount, this);
}
}
restoreFontDrawState(prevProgram, isTextureEnabledBefore, isBlendEnabledBefore, boundTextureBefore,
lightmapBindingBefore, isAlphaTestEnabledBefore, blendStateBefore, shadeModelBefore);
restoreFontDrawState(prevProgram, isTextureEnabledBefore, isBlendEnabledBefore, boundTextureBefore);
restoreDepth(depthTestBefore, depthMaskBefore);
truncateBatchToWatermark();
@@ -855,10 +624,6 @@ public class BatchingFontRenderer {
GLStateManager.glUniform1f(AAStrength, FontConfig.fontAAStrength / 120.f);
}
GLStateManager.glUniform1f(alphaTestRefLocation, GLStateManager.getAlphaState().getReference());
if (lightmapSamplerProgram != fontShaderId) {
GLStateManager.glUniform1i(lightmapSamplerLocation, LIGHTMAP_TEX_UNIT);
lightmapSamplerProgram = fontShaderId;
}
if (fontVAO == 0) {
fontVAO = GLStateManager.glGenVertexArrays();
@@ -889,38 +654,6 @@ public class BatchingFontRenderer {
private static ResourceLocation flushLastTexture;
private static boolean flushTextureChanged;
private static float flushLastLightmapU;
private static float flushLastLightmapV;
private static boolean flushLastLightmapActive;
private static void resetFlushLightmap() {
flushLastLightmapU = Float.NaN;
flushLastLightmapV = Float.NaN;
flushLastLightmapActive = false;
}
private static int boundLightmapTexture() {
return GLStateManager.getTextures().getTextureUnitBindings(LIGHTMAP_TEX_UNIT).getBinding();
}
private static void bindLightmapTexture(int texture) {
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + LIGHTMAP_TEX_UNIT);
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texture);
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
}
private static void uploadLightmap(int uniformLocation, boolean active, float u, float v, int texture) {
if (u != flushLastLightmapU || v != flushLastLightmapV || active != flushLastLightmapActive) {
GLStateManager.glUniform3f(uniformLocation, u, v, active ? 1.0f : 0.0f);
flushLastLightmapU = u;
flushLastLightmapV = v;
flushLastLightmapActive = active;
}
if (active && texture != 0 && boundLightmapTexture() != texture) {
bindLightmapTexture(texture);
}
}
private static void drawCommands(FontDrawCmd[] cmdsData, int from, int to, BatchingFontRenderer owner) {
for (int i = from; i < to; i++) {
final FontDrawCmd cmd = cmdsData[i];
@@ -940,9 +673,7 @@ public class BatchingFontRenderer {
}
}
private static void restoreFontDrawState(int prevProgram, boolean textureEnabledBefore, boolean blendEnabledBefore,
int boundTextureBefore, int lightmapBindingBefore, boolean alphaTestEnabledBefore, BlendState blendBefore,
int shadeModelBefore) {
private static void restoreFontDrawState(int prevProgram, boolean textureEnabledBefore, boolean blendEnabledBefore, int boundTextureBefore) {
GLStateManager.glUseProgram(prevProgram);
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
@@ -951,177 +682,19 @@ public class BatchingFontRenderer {
if (textureEnabledBefore) {
GLStateManager.glEnable(GL11.GL_TEXTURE_2D);
}
if (blendEnabledBefore) {
GLStateManager.enableBlend();
} else {
if (!blendEnabledBefore) {
GLStateManager.disableBlend();
}
GLStateManager.tryBlendFuncSeparate(blendBefore.getSrcRgb(), blendBefore.getDstRgb(),
blendBefore.getSrcAlpha(), blendBefore.getDstAlpha());
if (alphaTestEnabledBefore) {
GLStateManager.enableAlphaTest();
} else {
GLStateManager.disableAlphaTest();
}
GLStateManager.glShadeModel(shadeModelBefore);
if (flushTextureChanged) {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, boundTextureBefore);
}
if (boundLightmapTexture() != lightmapBindingBefore) {
bindLightmapTexture(lightmapBindingBefore);
}
}
private void flushBatchThroughPipeline() {
final int cmdCount = batchCommands.size();
final int segmentCount = batchSegments.size();
if (segmentCount == 0 && (vertexDataPos == deferredVertexPos || cmdCount == deferredCmdWatermark)) {
truncateBatchToWatermark();
return;
}
final boolean isTextureEnabledBefore = GLStateManager.glIsEnabled(GL11.GL_TEXTURE_2D);
final boolean isBlendEnabledBefore = GLStateManager.isEffectiveBlendEnabled();
final boolean isAlphaTestEnabledBefore = GLStateManager.isEffectiveAlphaTestEnabled();
GLStateManager.getEffectiveBlendState(blendStateBefore);
final int boundTextureBefore = GLStateManager.glGetInteger(GL11.GL_TEXTURE_BINDING_2D);
final int prevBlockEntityId = CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity();
boolean textureChanged = false;
GLStateManager.enableTexture();
GLStateManager.enableAlphaTest();
GLStateManager.enableBlend();
GLStateManager.tryBlendFuncSeparate(blendSrcRGB, blendDstRGB, GL11.GL_ONE, GL11.GL_ZERO);
final Boolean prevTranslucency = GbufferPrograms.beginTranslucencyDeclaration(Boolean.TRUE);
GbufferPrograms.setBlockEntityDefaults();
final FontDrawCmd[] cmdsData = batchCommands.elements();
for (int i = 0; i < segmentCount; i++) {
final TextSegment segment = batchSegments.get(i);
Arrays.sort(cmdsData, segment.cmdStart, segment.cmdEnd, FontDrawCmd.DRAW_ORDER_COMPARATOR);
}
Arrays.sort(cmdsData, batchSealedEnd, cmdCount, FontDrawCmd.DRAW_ORDER_COMPARATOR);
// The unsealed tail still belongs to the modelview live at flush time; capture it before the segments move it.
resolveModelView(scratchModelView);
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
GLStateManager.glPushMatrix();
try {
for (int i = 0; i < segmentCount; i++) {
final TextSegment segment = batchSegments.get(i);
if (segment.cmdStart == segment.cmdEnd) continue;
GLStateManager.setModelViewMatrix(segment.modelView);
CapturedRenderingState.INSTANCE.setCurrentBlockEntity(segment.blockEntityId);
textureChanged |= emitRangeThroughPipeline(this, cmdsData, segment.cmdStart, segment.cmdEnd,
segment.packedLight, segment.normalX, segment.normalY, segment.normalZ);
}
if (batchSealedEnd < cmdCount) {
GLStateManager.setModelViewMatrix(scratchModelView);
CapturedRenderingState.INSTANCE.setCurrentBlockEntity(prevBlockEntityId);
final Vector3f normal = ShaderManager.getCurrentNormal();
textureChanged |= emitRangeThroughPipeline(this, cmdsData, batchSealedEnd, cmdCount,
GLSMConfig.packedLastBrightness(), normal.x, normal.y, normal.z);
}
} finally {
GLStateManager.glPopMatrix();
CapturedRenderingState.INSTANCE.setCurrentBlockEntity(prevBlockEntityId);
GbufferPrograms.endTranslucencyDeclaration(prevTranslucency);
if (isTextureEnabledBefore) {
GLStateManager.enableTexture();
} else {
GLStateManager.disableTexture();
}
if (isBlendEnabledBefore) {
GLStateManager.enableBlend();
} else {
GLStateManager.disableBlend();
}
GLStateManager.tryBlendFuncSeparate(blendStateBefore.getSrcRgb(), blendStateBefore.getDstRgb(),
blendStateBefore.getSrcAlpha(), blendStateBefore.getDstAlpha());
if (isAlphaTestEnabledBefore) {
GLStateManager.enableAlphaTest();
} else {
GLStateManager.disableAlphaTest();
}
if (textureChanged) {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, boundTextureBefore);
}
truncateBatchToWatermark();
}
}
/** Replays one sealed command range through the Tessellator so Iris sees it as ordinary geometry. */
private static boolean emitRangeThroughPipeline(BatchingFontRenderer owner, FontDrawCmd[] cmdsData, int from, int to,
int packedLight, float normalX, float normalY, float normalZ) {
final Tessellator tessellator = Tessellator.instance;
ResourceLocation lastTexture = DUMMY_RESOURCE_LOCATION;
boolean textureChanged = false;
boolean drawing = false;
try {
for (int i = from; i < to; i++) {
final FontDrawCmd cmd = cmdsData[i];
if (!Objects.equals(lastTexture, cmd.texture)) {
if (drawing) {
tessellator.draw();
drawing = false;
}
if (cmd.texture == null) {
GLStateManager.disableTexture();
} else {
GLStateManager.enableTexture();
((FontRendererAccessor) owner.underlying).angelica$bindTexture(cmd.texture);
textureChanged = true;
}
lastTexture = cmd.texture;
}
if (!drawing) {
tessellator.startDrawingQuads();
tessellator.setBrightness(packedLight);
tessellator.setNormal(normalX, normalY, normalZ);
drawing = true;
}
owner.emitCommand(tessellator, cmd);
}
} finally {
if (drawing) {
tessellator.draw();
}
}
return textureChanged;
}
private void emitCommand(Tessellator tessellator, FontDrawCmd cmd) {
final int firstVertex = cmd.startVtx / 6 * 4;
final int quadCount = cmd.idxCount / 6;
for (int q = 0; q < quadCount; q++) {
final long base = vertexDataAddress + (long) (firstVertex + q * 4) * VERTEX_SIZE;
emitVertex(tessellator, base);
emitVertex(tessellator, base + VERTEX_SIZE);
emitVertex(tessellator, base + 3L * VERTEX_SIZE);
emitVertex(tessellator, base + 2L * VERTEX_SIZE);
}
}
private void emitVertex(Tessellator tessellator, long ptr) {
tessellator.setColorRGBA(
memGetByte(ptr + 16) & 0xFF,
memGetByte(ptr + 17) & 0xFF,
memGetByte(ptr + 18) & 0xFF,
memGetByte(ptr + 19) & 0xFF);
tessellator.addVertexWithUV(memGetFloat(ptr), memGetFloat(ptr + 4), 0.0D,
memGetFloat(ptr + 8), memGetFloat(ptr + 12));
}
private static void restoreDepth(boolean testBefore, boolean maskBefore) {
if (testBefore != GLStateManager.getDepthTest().isEnabled()) {
if (testBefore) GLStateManager.enableDepthTest(); else GLStateManager.disableDepthTest();
}
if (maskBefore != GLStateManager.isEffectiveDepthMaskEnabled()) {
if (maskBefore != GLStateManager.getDepthState().isEnabled()) {
GLStateManager.glDepthMask(maskBefore);
}
}
@@ -1136,19 +709,11 @@ public class BatchingFontRenderer {
batchMatrixValid = false;
vertexDataPos = deferredVertexPos;
idxWriterIndex = deferredIdxPos;
resetLightmapState();
if (arenaOwner == this) {
arenaOwner = null;
}
}
private void resetLightmapState() {
lightmapActive = false;
lightmapU = 0.0f;
lightmapV = 0.0f;
lightmapTextureId = 0;
}
// === Actual text mesh generation
public static boolean charInRange(char what, char fromInclusive, char toInclusive) {
@@ -1179,7 +744,7 @@ public class BatchingFontRenderer {
}
private static int hsvToRgb(float hue, float sat, float val) {
int h = (int) (hue / 60f) % 6;
int h = (int)(hue / 60f) % 6;
float f = hue / 60f - h;
float p = val * (1 - sat);
float q = val * (1 - f * sat);
@@ -1193,12 +758,11 @@ public class BatchingFontRenderer {
case 4: r=t; g=p; b=val; break;
default: r=val; g=p; b=q; break;
}
return ((int) (r * 255) << 16) | ((int) (g * 255) << 8) | (int) (b * 255);
return ((int)(r*255) << 16) | ((int)(g*255) << 8) | (int)(b*255);
}
private static final int RAINBOW_LUT_SIZE = 24;
private static final int[] RAINBOW_LUT = new int[RAINBOW_LUT_SIZE];
static {
for (int i = 0; i < RAINBOW_LUT_SIZE; i++) {
RAINBOW_LUT[i] = hsvToRgb(i * 15f, 1f, 1f);
@@ -1233,7 +797,7 @@ public class BatchingFontRenderer {
private static final float WAVE_FREQUENCY = 0.5f;
public float drawString(final float anchorX, final float anchorY, final int color, final boolean enableShadow,
final boolean unicodeFlag, final CharSequence string, int stringOffset, int stringLength) {
final boolean unicodeFlag, final CharSequence string, int stringOffset, int stringLength) {
// noinspection SizeReplaceableByIsEmpty
if (string == null || string.length() == 0) {
return anchorX + (enableShadow ? 1.0f : 0.0f);
@@ -1244,8 +808,6 @@ public class BatchingFontRenderer {
FontProviderMC.get(this.isSGA).locationFontTexture = this.locationFontTexture;
this.beginBatch();
this.captureLightmapState();
this.lightingFactorActive = isWorldSpaceText() && FFPVertexLighting.modulatesVertexColor(this.lightingFactor);
float curX = anchorX;
try {
final int totalStringLength = string.length();
@@ -1322,86 +884,86 @@ public class BatchingFontRenderer {
charIdx += SECTION_X_PAYLOAD;
}
} else {
final boolean is09 = charInRange(fmtCode, '0', '9');
final boolean isAF = charInRange(fmtCode, 'a', 'f');
if (is09 || isAF) {
curRandom = false;
curBold = false;
curStrikethrough = false;
curUnderline = false;
curItalic = false;
curRainbow = false;
curGradient = false;
// wave/dinnerbone NOT reset — they're positional effects, independent of color
final boolean is09 = charInRange(fmtCode, '0', '9');
final boolean isAF = charInRange(fmtCode, 'a', 'f');
if (is09 || isAF) {
curRandom = false;
curBold = false;
curStrikethrough = false;
curUnderline = false;
curItalic = false;
curRainbow = false;
curGradient = false;
// wave/dinnerbone NOT reset — they're positional effects, independent of color
final int colorIdx = is09 ? (fmtCode - '0') : (fmtCode - 'a' + 10);
final int rgb = this.colorCode[colorIdx];
curColor = (curColor & 0xFF000000) | (rgb & 0x00FFFFFF);
final int shadowRgb = this.colorCode[colorIdx + 16];
curShadowColor = (curShadowColor & 0xFF000000) | (shadowRgb & 0x00FFFFFF);
} else if (fmtCode == 'k') {
curRandom = true;
} else if (fmtCode == 'l') {
curBold = true;
} else if (fmtCode == 'm') {
curStrikethrough = true;
strikethroughStartX = curX - 1.0f;
strikethroughEndX = strikethroughStartX;
} else if (fmtCode == 'n') {
curUnderline = true;
underlineStartX = curX - 1.0f;
underlineEndX = underlineStartX;
} else if (fmtCode == 'o') {
curItalic = true;
} else if (fmtCode == 'q' && AngelicaConfig.enableRainbow) {
curRainbow = true;
curGradient = false;
rainbowCharIndex = 0;
} else if (fmtCode == 'z' && AngelicaConfig.enableWaveText) {
curWave = !curWave;
} else if (fmtCode == 'v' && AngelicaConfig.enableDinnerboneText) {
curDinnerbone = !curDinnerbone;
} else if (fmtCode == 'u' && AngelicaConfig.enableDropShadow) {
int customRgb = (charIdx + SECTION_X_LENGTH < stringEnd)
? ColorCodeUtils.parseSectionXAt(string, charIdx + 1)
: -1;
if (customRgb != -1) {
curShadow = true;
curShadowCustomColor = true;
curShadowColorOverride = customRgb;
charIdx += SECTION_X_LENGTH;
} else {
curShadow = !curShadow;
if (!curShadow) curShadowCustomColor = false;
}
} else if (fmtCode == 'g' && AngelicaConfig.enableGradients && charIdx + GRADIENT_PAYLOAD < stringEnd) {
int color1 = ColorCodeUtils.parseSectionXAt(string, charIdx + 1);
int color2 = ColorCodeUtils.parseSectionXAt(string, charIdx + 1 + SECTION_X_LENGTH);
if (color1 != -1 && color2 != -1) {
curGradient = true;
curRainbow = false;
gradientStartRgb = color1;
gradientEndRgb = color2;
gradientCharIndex = 0;
gradientTotalChars = countVisibleChars(string, charIdx + 1 + GRADIENT_PAYLOAD, stringEnd);
gradientStep = gradientTotalChars > 1 ? 1f / (gradientTotalChars - 1) : 0f;
charIdx += GRADIENT_PAYLOAD;
}
} else if (fmtCode == 'r') {
curRandom = false;
curBold = false;
curStrikethrough = false;
curUnderline = false;
curItalic = false;
curRainbow = false;
curWave = false;
curDinnerbone = false;
curGradient = false;
curShadow = false;
curShadowCustomColor = false;
curColor = color;
curShadowColor = shadowColor;
final int colorIdx = is09 ? (fmtCode - '0') : (fmtCode - 'a' + 10);
final int rgb = this.colorCode[colorIdx];
curColor = (curColor & 0xFF000000) | (rgb & 0x00FFFFFF);
final int shadowRgb = this.colorCode[colorIdx + 16];
curShadowColor = (curShadowColor & 0xFF000000) | (shadowRgb & 0x00FFFFFF);
} else if (fmtCode == 'k') {
curRandom = true;
} else if (fmtCode == 'l') {
curBold = true;
} else if (fmtCode == 'm') {
curStrikethrough = true;
strikethroughStartX = curX - 1.0f;
strikethroughEndX = strikethroughStartX;
} else if (fmtCode == 'n') {
curUnderline = true;
underlineStartX = curX - 1.0f;
underlineEndX = underlineStartX;
} else if (fmtCode == 'o') {
curItalic = true;
} else if (fmtCode == 'q' && AngelicaConfig.enableRainbow) {
curRainbow = true;
curGradient = false;
rainbowCharIndex = 0;
} else if (fmtCode == 'z' && AngelicaConfig.enableWaveText) {
curWave = !curWave;
} else if (fmtCode == 'v' && AngelicaConfig.enableDinnerboneText) {
curDinnerbone = !curDinnerbone;
} else if (fmtCode == 'u' && AngelicaConfig.enableDropShadow) {
int customRgb = (charIdx + SECTION_X_LENGTH < stringEnd)
? ColorCodeUtils.parseSectionXAt(string, charIdx + 1)
: -1;
if (customRgb != -1) {
curShadow = true;
curShadowCustomColor = true;
curShadowColorOverride = customRgb;
charIdx += SECTION_X_LENGTH;
} else {
curShadow = !curShadow;
if (!curShadow) curShadowCustomColor = false;
}
} else if (fmtCode == 'g' && AngelicaConfig.enableGradients && charIdx + GRADIENT_PAYLOAD < stringEnd) {
int color1 = ColorCodeUtils.parseSectionXAt(string, charIdx + 1);
int color2 = ColorCodeUtils.parseSectionXAt(string, charIdx + 1 + SECTION_X_LENGTH);
if (color1 != -1 && color2 != -1) {
curGradient = true;
curRainbow = false;
gradientStartRgb = color1;
gradientEndRgb = color2;
gradientCharIndex = 0;
gradientTotalChars = countVisibleChars(string, charIdx + 1 + GRADIENT_PAYLOAD, stringEnd);
gradientStep = gradientTotalChars > 1 ? 1f / (gradientTotalChars - 1) : 0f;
charIdx += GRADIENT_PAYLOAD;
}
} else if (fmtCode == 'r') {
curRandom = false;
curBold = false;
curStrikethrough = false;
curUnderline = false;
curItalic = false;
curRainbow = false;
curWave = false;
curDinnerbone = false;
curGradient = false;
curShadow = false;
curShadowCustomColor = false;
curColor = color;
curShadowColor = shadowColor;
}
} // close else block for non-§x codes
continue;
@@ -1445,9 +1007,9 @@ public class BatchingFontRenderer {
}
if (curGradient && gradientTotalChars > 0) {
float t = Math.min(gradientCharIndex * gradientStep, 1f);
int gr = (int) ((gradientStartRgb >> 16 & 0xFF) * (1 - t) + (gradientEndRgb >> 16 & 0xFF) * t);
int gg = (int) ((gradientStartRgb >> 8 & 0xFF) * (1 - t) + (gradientEndRgb >> 8 & 0xFF) * t);
int gb = (int) ((gradientStartRgb & 0xFF) * (1 - t) + (gradientEndRgb & 0xFF) * t);
int gr = (int)((gradientStartRgb >> 16 & 0xFF) * (1-t) + (gradientEndRgb >> 16 & 0xFF) * t);
int gg = (int)((gradientStartRgb >> 8 & 0xFF) * (1-t) + (gradientEndRgb >> 8 & 0xFF) * t);
int gb = (int)((gradientStartRgb & 0xFF) * (1-t) + (gradientEndRgb & 0xFF) * t);
int rgbEffect = (gr << 16) | (gg << 8) | gb;
curColor = (curColor & 0xFF000000) | rgbEffect;
curShadowColor = (curShadowColor & 0xFF000000) | ((rgbEffect & 0xFCFCFC) >> 2);
@@ -1470,7 +1032,7 @@ public class BatchingFontRenderer {
// Wave: Y offset via sine wave
float renderY = heightNorth;
if (curWave) {
float time = HUDCaching.renderingCacheOverride ? 0f : (float) ((System.nanoTime() & 0xFFFFFFFFFFFFL) * WAVE_TIME_SCALE);
float time = HUDCaching.renderingCacheOverride ? 0f : (float)((System.nanoTime() & 0xFFFFFFFFFFFFL) * WAVE_TIME_SCALE);
renderY += (float) Math.sin(visibleCharIndex * WAVE_FREQUENCY + time) * AngelicaConfig.waveAmplitude;
}
@@ -1,96 +0,0 @@
package com.gtnewhorizons.angelica.client.gui;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
public record DynamicLightsEntityFilter(List<String> modPrefixes, List<String> nameTerms, DynamicLightsEntityFilter.State state) {
public enum State {
ANY,
ENABLED,
DISABLED
}
private static final Pattern WHITESPACE = Pattern.compile("\\s+");
private static final DynamicLightsEntityFilter MATCH_ALL = new DynamicLightsEntityFilter(List.of(), List.of(), State.ANY);
public DynamicLightsEntityFilter {
modPrefixes = List.copyOf(modPrefixes);
nameTerms = List.copyOf(nameTerms);
}
public static DynamicLightsEntityFilter parse(String query) {
if (query == null) {
return MATCH_ALL;
}
final var normalized = query.strip().toLowerCase(Locale.ROOT);
if (normalized.isEmpty()) {
return MATCH_ALL;
}
final var modPrefixes = new ArrayList<String>();
final var nameTerms = new ArrayList<String>();
var wantEnabled = false;
var wantDisabled = false;
for (final var token : WHITESPACE.split(normalized)) {
switch (token) {
case "$on" -> wantEnabled = true;
case "$off" -> wantDisabled = true;
default -> {
if (token.length() > 1 && token.charAt(0) == '@') {
modPrefixes.add(token.substring(1));
} else {
nameTerms.add(token);
}
}
}
}
final var state = wantEnabled == wantDisabled ? State.ANY : wantEnabled ? State.ENABLED : State.DISABLED;
if (modPrefixes.isEmpty() && nameTerms.isEmpty() && state == State.ANY) {
return MATCH_ALL;
}
return new DynamicLightsEntityFilter(modPrefixes, nameTerms, state);
}
public boolean isMatchAll() {
return modPrefixes.isEmpty() && nameTerms.isEmpty() && state == State.ANY;
}
public boolean matches(String lowerName, String lowerModId, boolean enabled) {
return matchesState(enabled) && matchesAnyMod(lowerModId) && containsAllTerms(lowerName);
}
private boolean matchesState(boolean enabled) {
return switch (state) {
case ANY -> true;
case ENABLED -> enabled;
case DISABLED -> !enabled;
};
}
private boolean matchesAnyMod(String lowerModId) {
if (modPrefixes.isEmpty()) {
return true;
}
for (final var prefix : modPrefixes) {
if (lowerModId.startsWith(prefix)) {
return true;
}
}
return false;
}
private boolean containsAllTerms(String lowerName) {
for (final var term : nameTerms) {
if (!lowerName.contains(term)) {
return false;
}
}
return true;
}
}
@@ -1,242 +0,0 @@
package com.gtnewhorizons.angelica.client.gui;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiTextField;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.resources.I18n;
import net.minecraft.util.EnumChatFormatting;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import com.gtnewhorizons.angelica.dynamiclights.config.EntityLightConfig;
import com.gtnewhorizons.angelica.dynamiclights.config.EntityTypeEntry;
import net.coderbot.iris.gui.element.IrisGuiSlot;
import net.coderbot.iris.gui.element.widget.IrisButton;
public class DynamicLightsEntityScreen extends GuiScreen {
private static final String ENABLED_PREFIX = EnumChatFormatting.GREEN + "[x] " + EnumChatFormatting.WHITE;
private static final String DISABLED_PREFIX = EnumChatFormatting.DARK_GRAY + "[ ] " + EnumChatFormatting.GRAY;
private static List<EntityTypeEntry> entityTypes;
private final GuiScreen parent;
private final String title = I18n.format("options.dynamiclights.entities.title");
private final String info = I18n.format("options.dynamiclights.entities.info");
private List<EntityTypeEntry> displayed;
private String countLabel;
private String search = "";
private boolean dirty;
private GuiTextField searchBox;
private EntityRowList rowList;
private IrisButton toggleButton;
public DynamicLightsEntityScreen(GuiScreen parent) {
this.parent = parent;
this.refilter();
}
private static List<EntityTypeEntry> entityTypes() {
if (entityTypes == null) {
entityTypes = EntityLightConfig.getAllEntityTypes();
}
return entityTypes;
}
@Override
public void initGui() {
Keyboard.enableRepeatEvents(true);
this.searchBox = new GuiTextField(this.fontRendererObj, this.width / 2 - 150, 30, 300, 20);
this.searchBox.setMaxStringLength(64);
this.searchBox.setText(this.search);
this.rowList = new EntityRowList();
this.toggleButton = new IrisButton(this.width / 2 - 154, this.height - 27, 150, 20, "", button -> this.toggleVisible());
this.updateToggleButton();
this.buttonList.add(this.toggleButton);
this.buttonList.add(new IrisButton(this.width / 2 + 4, this.height - 27, 150, 20, I18n.format("gui.done"), button -> this.onClose()));
}
@Override
public void onGuiClosed() {
Keyboard.enableRepeatEvents(false);
}
private void onClose() {
if (this.dirty) {
EntityLightConfig.save();
this.dirty = false;
}
this.mc.displayGuiScreen(this.parent);
}
private void refilter() {
final var filter = DynamicLightsEntityFilter.parse(this.search);
if (filter.isMatchAll()) {
this.displayed = entityTypes();
} else {
final var matches = new ArrayList<EntityTypeEntry>();
for (final var entry : entityTypes()) {
if (filter.matches(entry.getSearchName(), entry.getSearchModId(), EntityLightConfig.isEntityTypeEnabled(entry.getEntityClass()))) {
matches.add(entry);
}
}
this.displayed = matches;
}
this.countLabel = this.displayed.size() + " / " + entityTypes().size();
this.updateToggleButton();
}
private boolean anyDisplayedEnabled() {
for (final var entry : this.displayed) {
if (EntityLightConfig.isEntityTypeEnabled(entry.getEntityClass())) {
return true;
}
}
return false;
}
private void updateToggleButton() {
if (this.toggleButton == null) {
return;
}
final var subset = this.displayed.size() != entityTypes().size();
final var key = this.anyDisplayedEnabled()
? (subset ? "options.dynamiclights.entities.disableshown" : "options.dynamiclights.entities.disableall")
: (subset ? "options.dynamiclights.entities.enableshown" : "options.dynamiclights.entities.enableall");
this.toggleButton.displayString = I18n.format(key);
this.toggleButton.enabled = !this.displayed.isEmpty();
}
private void toggleVisible() {
final var enable = !this.anyDisplayedEnabled();
for (final var entry : this.displayed) {
EntityLightConfig.setEntityTypeEnabled(entry.getEntityClass(), enable);
}
this.dirty = true;
this.refilter();
}
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
this.drawDefaultBackground();
this.rowList.drawScreen(mouseX, mouseY, partialTicks);
super.drawScreen(mouseX, mouseY, partialTicks);
drawCenteredString(this.fontRendererObj, this.title, this.width / 2, 8, 0xFFFFFF);
drawCenteredString(this.fontRendererObj, this.info, this.width / 2, 20, 0xA0A0A0);
this.searchBox.drawTextBox();
if (!this.searchBox.isFocused() && this.search.isEmpty()) {
this.drawString(this.fontRendererObj, I18n.format("options.dynamiclights.entities.search"), this.width / 2 - 144, 36, 0x808080);
}
drawCenteredString(this.fontRendererObj, this.countLabel, this.width / 2, this.height - 39, 0x808080);
}
@Override
public void updateScreen() {
this.searchBox.updateCursorCounter();
}
@Override
protected void mouseClicked(int mouseX, int mouseY, int mouseButton) {
if (!this.rowList.mouseClicked(mouseX, mouseY, mouseButton)) {
super.mouseClicked(mouseX, mouseY, mouseButton);
}
this.searchBox.mouseClicked(mouseX, mouseY, mouseButton);
}
@Override
protected void mouseMovedOrUp(int mouseX, int mouseY, int state) {
if (state == -1 || !this.rowList.mouseReleased(mouseX, mouseY, Mouse.getEventButton())) {
super.mouseMovedOrUp(mouseX, mouseY, state);
}
}
@Override
protected void actionPerformed(GuiButton button) {
if (button.enabled && button instanceof IrisButton irisButton) {
irisButton.onPress();
}
}
@Override
protected void keyTyped(char typedChar, int keyCode) {
if (this.searchBox.isFocused()) {
if (keyCode == Keyboard.KEY_ESCAPE) {
this.searchBox.setFocused(false);
return;
}
this.searchBox.textboxKeyTyped(typedChar, keyCode);
if (!this.searchBox.getText().equals(this.search)) {
this.search = this.searchBox.getText();
this.refilter();
}
return;
}
if (keyCode == Keyboard.KEY_ESCAPE) {
this.onClose();
return;
}
super.keyTyped(typedChar, keyCode);
}
private class EntityRowList extends IrisGuiSlot {
EntityRowList() {
super(DynamicLightsEntityScreen.this.mc, DynamicLightsEntityScreen.this.width, DynamicLightsEntityScreen.this.height, 56, DynamicLightsEntityScreen.this.height - 44, 18);
this.setRenderBackground(false);
}
@Override
protected int getSize() {
return displayed.size();
}
@Override
protected boolean isSelected(int index) {
return false;
}
@Override
protected void drawBackground() {}
@Override
public int getListWidth() {
return Math.min(400, DynamicLightsEntityScreen.this.width - 40);
}
@Override
protected boolean elementClicked(int index, boolean doubleClick, int mouseX, int mouseY, int button) {
if (button != 0 || index >= displayed.size()) {
return false;
}
final var entry = displayed.get(index);
EntityLightConfig.setEntityTypeEnabled(entry.getEntityClass(), !EntityLightConfig.isEntityTypeEnabled(entry.getEntityClass()));
dirty = true;
updateToggleButton();
return true;
}
@Override
protected void drawSlot(int index, int x, int y, int slotHeight, Tessellator tessellator, int mouseX, int mouseY) {
final var entry = displayed.get(index);
final var enabled = EntityLightConfig.isEntityTypeEnabled(entry.getEntityClass());
final var label = (enabled ? ENABLED_PREFIX : DISABLED_PREFIX) + entry.getDisplayName() + EnumChatFormatting.DARK_GRAY + " (" + entry.getModId() + ")";
drawString(fontRendererObj, fontRendererObj.trimStringToWidth(label, this.getListWidth() - 8), x, y + 5, 0xFFFFFF);
}
}
}
@@ -1,32 +1,105 @@
package com.gtnewhorizons.angelica.client.gui;
import com.google.common.collect.ImmutableList;
import com.gtnewhorizons.angelica.dynamiclights.DynamicLights;
import com.gtnewhorizons.angelica.dynamiclights.config.EntityLightConfig;
import com.gtnewhorizons.angelica.dynamiclights.config.EntityLightConfigStorage;
import com.gtnewhorizons.angelica.dynamiclights.config.EntityTypeEntry;
import jss.notfine.core.Settings;
import me.jellysquid.mods.sodium.client.gui.options.Option;
import me.jellysquid.mods.sodium.client.gui.options.OptionGroup;
import me.jellysquid.mods.sodium.client.gui.options.OptionImpl;
import me.jellysquid.mods.sodium.client.gui.options.OptionImpact;
import me.jellysquid.mods.sodium.client.gui.options.OptionPage;
import me.jellysquid.mods.sodium.client.gui.options.SubScreenOption;
import me.jellysquid.mods.sodium.client.gui.options.control.TickBoxControl;
import net.minecraft.client.resources.I18n;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class DynamicLightsOptionPages {
public static OptionPage dynamicLights() {
return new OptionPage(I18n.format("options.dynamiclights.page"), ImmutableList.of(
OptionGroup.createBuilder()
.add(Settings.DYNAMIC_LIGHTS.option)
.add(Settings.DYNAMIC_LIGHTS_SHADER_FORCE.option)
.build(),
OptionGroup.createBuilder()
.add(Settings.DYNAMIC_LIGHTS_FRUSTUM_CULLING.option)
.add(Settings.DYNAMIC_LIGHTS_ADAPTIVE_TICKING.option)
.add(Settings.DYNAMIC_LIGHTS_CULL_TIMEOUT.option)
.build(),
OptionGroup.createBuilder()
.add(Settings.DYNAMIC_LIGHTS_SLOW_DIST.option)
.add(Settings.DYNAMIC_LIGHTS_SLOWER_DIST.option)
.add(Settings.DYNAMIC_LIGHTS_BACKGROUND_DIST.option)
.build(),
OptionGroup.createBuilder()
.add(new SubScreenOption(I18n.format("options.dynamiclights.entities"), I18n.format("options.dynamiclights.entities.tooltip"), DynamicLightsEntityScreen::new))
.build()));
if (!DynamicLights.configEnabled) {
return null;
}
List<OptionGroup> groups = new ArrayList<>();
groups.add(OptionGroup.createBuilder()
.add(Settings.DYNAMIC_LIGHTS.option)
.add(Settings.DYNAMIC_LIGHTS_SHADER_FORCE.option)
.build());
groups.add(OptionGroup.createBuilder()
.add(Settings.DYNAMIC_LIGHTS_FRUSTUM_CULLING.option)
.add(Settings.DYNAMIC_LIGHTS_ADAPTIVE_TICKING.option)
.add(Settings.DYNAMIC_LIGHTS_CULL_TIMEOUT.option)
.build());
groups.add(OptionGroup.createBuilder()
.add(Settings.DYNAMIC_LIGHTS_SLOW_DIST.option)
.add(Settings.DYNAMIC_LIGHTS_SLOWER_DIST.option)
.add(Settings.DYNAMIC_LIGHTS_BACKGROUND_DIST.option)
.build());
// Entity type toggles - grouped by mod ID
List<EntityTypeEntry> allEntities = EntityLightConfig.getAllEntityTypes();
Map<String, List<EntityTypeEntry>> byMod = new LinkedHashMap<>();
for (EntityTypeEntry entry : allEntities) {
byMod.computeIfAbsent(entry.getModId(), _ -> new ArrayList<>()).add(entry);
}
// Create a group for each mod's entities
for (Map.Entry<String, List<EntityTypeEntry>> modEntry : byMod.entrySet()) {
String modId = modEntry.getKey();
List<EntityTypeEntry> entities = modEntry.getValue();
OptionGroup.Builder groupBuilder = OptionGroup.createBuilder();
for (EntityTypeEntry entity : entities) {
Option<Boolean> option = createEntityOption(entity);
if (option != null) {
groupBuilder.add(option);
}
}
// Only add group if it has options
OptionGroup group = groupBuilder.build();
if (!group.getOptions().isEmpty()) {
groups.add(group);
}
}
return new OptionPage(I18n.format("options.dynamiclights.page"), ImmutableList.copyOf(groups));
}
private static Option<Boolean> createEntityOption(EntityTypeEntry entry) {
final String className = entry.getClassName();
// Resolve class once during option creation, not on every get/set
Class<?> resolvedClass;
try {
resolvedClass = Class.forName(className);
} catch (ClassNotFoundException e) {
// Class not loaded, skip this option
return null;
}
final Class<?> entityClass = resolvedClass;
return OptionImpl.createBuilder(Boolean.class, EntityLightConfigStorage.INSTANCE)
.setName(entry.getDisplayName() + " (" + entry.getModId() + ")")
.setTooltip(I18n.format("options.dynamiclights.entity.tooltip", entry.getDisplayName()))
.setControl(TickBoxControl::new)
.setBinding(
(_, value) -> EntityLightConfig.setEntityTypeEnabled(entityClass, value),
storage -> EntityLightConfig.isEntityTypeEnabled(entityClass)
)
.setImpact(OptionImpact.LOW)
.build();
}
}
@@ -17,10 +17,6 @@ public final class BopFogColorSource implements BopFogBlend.ColorSource {
return this;
}
public void freeWorld() {
this.world = null;
}
@Override
public int fogColour(int x, int y, int z) {
final BiomeGenBase biome = FogBiomeCache.get(world, x, z);
@@ -9,7 +9,7 @@ public final class FogBiomeCache {
private static final int MAX_ENTRIES = 16384;
private static final Long2ObjectOpenHashMap<BiomeGenBase> CACHE = new Long2ObjectOpenHashMap<>();
private static World cachedWorld;
private static World lastWorld;
private static int generation;
private FogBiomeCache() {}
@@ -18,14 +18,10 @@ public final class FogBiomeCache {
return generation;
}
public static void invalidate() {
cachedWorld = null;
}
public static BiomeGenBase get(World world, int x, int z) {
if (world != cachedWorld) {
if (world != lastWorld) {
CACHE.clear();
cachedWorld = world;
lastWorld = world;
generation++;
}
final long key = ((long) x << 32) | (z & 0xFFFFFFFFL);
@@ -15,7 +15,6 @@ import net.coderbot.batchedentityrendering.impl.BlendingStateHolder;
import net.coderbot.batchedentityrendering.impl.TransparencyType;
import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition;
import net.coderbot.iris.layer.GbufferPrograms;
import net.coderbot.iris.layer.PassOverride;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
@@ -69,9 +68,11 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
return TRANSLUCENT;
}
private static MultiPhaseParameters.Builder tesrMaterialPhases(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits) {
private static MultiPhaseParameters.Builder tesrMaterialPhases(ResourceLocation texture, TesrMaterial material) {
final MultiPhaseParameters.Builder b = MultiPhaseParameters.builder();
b.texture(texture != null ? new RenderPhase.Texture(texture, false, false) : NO_TEXTURE);
if (texture != null) {
b.texture(new RenderPhase.Texture(texture, false, false));
}
if (material.isNoCull()) {
b.cull(DISABLE_CULLING);
}
@@ -84,16 +85,19 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
if (material.isDepthOnly()) {
b.writeMaskState(DEPTH_MASK);
}
b.alpha(material.cutoutAlpha() > 0 ? new RenderPhase.Alpha(material.cutoutAlpha()) : ZERO_ALPHA);
b.depthTest(material.isDepthEqual() ? EQUAL_DEPTH_TEST : LEQUAL_DEPTH_TEST);
if (material.cutoutAlpha() > 0) {
b.alpha(new RenderPhase.Alpha(material.cutoutAlpha()));
}
if (material.isDepthEqual()) {
b.depthTest(EQUAL_DEPTH_TEST);
}
switch (material.transparency()) {
case TRANSLUCENT -> b.transparency(TRANSLUCENT_TRANSPARENCY);
case ADDITIVE -> b.transparency(ADDITIVE_TRANSPARENCY);
case ADDITIVE_ALPHA -> b.transparency(LIGHTNING_TRANSPARENCY);
case GLINT -> b.transparency(GLINT_TRANSPARENCY);
case OPAQUE -> b.transparency(NO_TRANSPARENCY);
case OPAQUE -> {}
}
boolean shaderPhaseTaken = true;
switch (material.special()) {
case GLINT -> b.shader(SPECIAL_GLINT);
case BEACON_BEAM -> b.shader(SPECIAL_BEACON_BEAM);
@@ -101,15 +105,9 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
final TesrShader shader = material.shader();
if (shader != null) {
b.shader(new RenderPhase.Shader("angelica_tesr_shader_" + shader.name(), shader.bind(), shader.release()));
} else {
shaderPhaseTaken = false;
}
}
}
if (!shaderPhaseTaken && pass != PassOverride.NONE) {
b.shader(new RenderPhase.Shader("angelica_tesr_pass" + pass.nameSuffix(), pass::apply, pass::clear));
}
b.layering(polygonOffset(offsetFactor, offsetUnits));
return b;
}
@@ -121,21 +119,19 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
GbufferPrograms::teardownSpecialRenderCondition);
public static RenderLayer tesr(ResourceLocation texture, TesrMaterial material) {
return tesr(texture, material, PassOverride.NONE, 0.0f, 0.0f);
}
public static RenderLayer tesr(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits) {
final MultiPhaseParameters.Builder b = tesrMaterialPhases(texture, material, pass, offsetFactor, offsetUnits).shadeModel(SMOOTH_SHADE_MODEL);
final MultiPhaseParameters.Builder b = tesrMaterialPhases(texture, material).shadeModel(SMOOTH_SHADE_MODEL).lightmap(ENABLE_LIGHTMAP);
if (material.transparency() == TesrMaterial.Transparency.TRANSLUCENT) {
b.target(TRANSLUCENT_TARGET);
}
final boolean sortsTranslucent = material.transparency() != TesrMaterial.Transparency.OPAQUE;
return of("angelica_tesr_" + material.transparency().name().toLowerCase(Locale.ROOT) + pass.nameSuffix()
+ (offsetFactor == 0.0f && offsetUnits == 0.0f ? "" : "_offset" + offsetFactor + "_" + offsetUnits),
return of("angelica_tesr_" + material.transparency().name().toLowerCase(Locale.ROOT),
BatchVertexFormats.POSITION_COLOR_TEXTURE_LIGHTF_NORMAL, GL11.GL_QUADS, 65536, true, sortsTranslucent, b.build(false));
}
public static RenderLayer tesrNoPass(ResourceLocation texture, TesrMaterial material) {
return of("angelica_tesr_nopass_" + material.transparency().name().toLowerCase(Locale.ROOT),
BatchVertexFormats.POSITION_COLOR_TEXTURE_LIGHTF_NORMAL, GL11.GL_QUADS, 65536, true, false,
tesrMaterialPhases(texture, material, PassOverride.NONE, 0.0f, 0.0f).build(false));
tesrMaterialPhases(texture, material).build(false));
}
public static RenderLayer getOutline(ResourceLocation texture, RenderPhase.Cull cull) {
@@ -158,7 +154,7 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
@Override
public TransparencyType getTransparencyType() {
return phases.transparency == null ? TransparencyType.OPAQUE : phases.transparency.getTransparencyType();
return phases.transparency.getTransparencyType();
}
private MultiPhase(String name, VertexFormat vertexFormat, int drawMode, int expectedBufferSize, boolean hasCrumbling, boolean translucent, MultiPhaseParameters phases) {
@@ -174,7 +170,7 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
}
});
this.phases = phases;
this.affectedOutline = phases.outlineMode == RenderLayer.OutlineMode.AFFECTS_OUTLINE && phases.texture != null ? phases.texture.getId().map((arg2) -> {
this.affectedOutline = phases.outlineMode == RenderLayer.OutlineMode.AFFECTS_OUTLINE ? phases.texture.getId().map((arg2) -> {
return getOutline(arg2, phases.cull);
}) : Optional.empty();
this.hash = Objects.hash(new Object[]{super.hashCode(), phases});
@@ -191,7 +187,7 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
@Override
public ResourceLocation getTextureId() {
return phases.texture == null ? null : phases.texture.getId().orElse(null);
return phases.texture.getId().orElse(null);
}
@Override
@@ -227,9 +223,7 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
if (arg == arg2) {
return true;
} else {
return arg != null && arg2 != null && arg.name.equals(arg2.name)
&& arg.getVertexFormat() == arg2.getVertexFormat() && arg.getDrawMode() == arg2.getDrawMode()
&& Objects.equals(arg.phases, arg2.phases);
return arg != null && arg2 != null ? Objects.equals(arg.phases, arg2.phases) : false;
}
}
}
@@ -269,13 +263,7 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
this.writeMaskState = writeMaskState;
this.shader = shader;
this.outlineMode = outlineMode;
final ImmutableList.Builder<RenderPhase> declared = ImmutableList.builder();
for (RenderPhase phase : new RenderPhase[] { this.texture, this.transparency, this.diffuseLighting,
this.shadeModel, this.alpha, this.depthTest, this.cull, this.lightmap, this.fog, this.layering,
this.target, this.texturing, this.writeMaskState, this.shader }) {
if (phase != null) declared.add(phase);
}
this.phases = declared.build();
this.phases = ImmutableList.of(this.texture, this.transparency, this.diffuseLighting, this.shadeModel, this.alpha, this.depthTest, this.cull, this.lightmap, this.fog, this.layering, this.target, this.texturing, this.writeMaskState, this.shader);
}
@Override
@@ -320,7 +308,22 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
private RenderPhase.WriteMaskState writeMaskState;
private RenderPhase.Shader shader;
private Builder() {}
private Builder() {
this.texture = RenderPhase.NO_TEXTURE ;
this.transparency = RenderPhase.NO_TRANSPARENCY;
this.diffuseLighting = RenderPhase.DISABLE_DIFFUSE_LIGHTING;
this.shadeModel = RenderPhase.SHADE_MODEL;
this.alpha = RenderPhase.ZERO_ALPHA;
this.depthTest = RenderPhase.LEQUAL_DEPTH_TEST;
this.cull = RenderPhase.ENABLE_CULLING;
this.lightmap = RenderPhase.DISABLE_LIGHTMAP;
this.fog = RenderPhase.FOG;
this.layering = RenderPhase.NO_LAYERING;
this.target = RenderPhase.MAIN_TARGET;
this.texturing = RenderPhase.DEFAULT_TEXTURING;
this.writeMaskState = RenderPhase.ALL_MASK;
this.shader = RenderPhase.NO_SHADER;
}
public Builder texture(RenderPhase.Texture texture) {
this.texture = texture;
@@ -332,10 +335,6 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
return this;
}
public void layering(Layering layering) {
this.layering = layering;
}
public Builder shadeModel(RenderPhase.ShadeModel shadeModel) {
this.shadeModel = shadeModel;
return this;
@@ -9,9 +9,7 @@ import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
import javax.annotation.Nullable;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Optional;
@@ -79,7 +77,6 @@ public abstract class RenderPhase {
protected static final WriteMaskState COLOR_MASK;
protected static final WriteMaskState DEPTH_MASK;
protected static final Layering NO_LAYERING;
protected static final Fog NO_FOG;
protected static final Fog FOG;
protected static final Fog BLACK_FOG;
@@ -88,22 +85,6 @@ public abstract class RenderPhase {
protected static final Target TRANSLUCENT_TARGET;
protected static final Shader NO_SHADER = new Shader("no_shader", () -> {}, () -> {});
private static final Map<Long, Layering> POLYGON_OFFSET_LAYERINGS = new ConcurrentHashMap<>();
public static Layering polygonOffset(float factor, float units) {
if (factor == 0.0f && units == 0.0f) {
return NO_LAYERING;
}
final long key = ((long) Float.floatToIntBits(factor) << 32) | (Float.floatToIntBits(units) & 0xFFFFFFFFL);
return POLYGON_OFFSET_LAYERINGS.computeIfAbsent(key, k -> new Layering("polygon_offset_" + factor + "_" + units, () -> {
GLStateManager.glEnable(GL11.GL_POLYGON_OFFSET_FILL);
GLStateManager.glPolygonOffset(factor, units);
}, () -> {
GLStateManager.glDisable(GL11.GL_POLYGON_OFFSET_FILL);
GLStateManager.glPolygonOffset(0.0f, 0.0f);
}));
}
public RenderPhase(String name, Runnable beginAction, Runnable endAction) {
this.name = name;
this.beginAction = beginAction;
@@ -2,7 +2,6 @@ package com.gtnewhorizons.angelica.config;
import com.gtnewhorizon.gtnhlib.config.Config;
import com.gtnewhorizons.angelica.rendering.culling.GpuCulling;
import net.coderbot.iris.shadows.ShadowGraphGate;
@Config(modid = "angelica", filename = "angelica-modules")
public class AngelicaConfig {
@@ -348,20 +347,6 @@ public class AngelicaConfig {
@Config.DefaultBoolean(true)
public static boolean shadowSkipInMeshTileEntities;
@Config.Comment({
"How much a celestial body can move before the shadow map can update.",
"",
"Note this option is disabled when a shader pack utilizes voxelization features."
})
@Config.DefaultFloat(ShadowGraphGate.DEFAULT_ANGLE_DELTA_DEGREES)
@Config.RangeFloat(min = 0f, max = 0.1f)
public static float shadowGraphAngleDelta;
@Config.Comment("Adjusts the rate the shadow map rebuilds when when a celestial body is near the horizon. Rate is sinusoidal")
@Config.DefaultFloat(ShadowGraphGate.DEFAULT_HORIZON_SCALE)
@Config.RangeFloat(min = 0f, max = 1.0f)
public static float shadowGraphHorizonScale;
@Config.Comment("ASM transformer exclusion narrowing for mod compatibility. Disable per-mod if narrowing causes class loading issues.")
public static TransformerCompat transformerCompat = new TransformerCompat();
@@ -452,18 +437,6 @@ public class AngelicaConfig {
@Config.RequiresMcRestart
public static GLProfile glProfile;
@Config.Comment("Enable random top-face texture orientation for configured blocks")
@Config.DefaultBoolean(true)
public static boolean enableNaturalTextures = true;
@Config.Comment("List of block registry names to apply random top-face texture rotation to")
@Config.DefaultStringList({
"minecraft:andesite", "minecraft:dirt", "minecraft:granite", "minecraft:grass", "minecraft:mycelium", "minecraft:sand", "minecraft:soul_sand", "etfuturum:calcite", "etfuturum:coarse_dirt", "etfuturum:cobbled_deepslate", "etfuturum:concrete_powder", "etfuturum:deepslate", "etfuturum:polished_deepslate", "etfuturum:soul_soil", "etfuturum:tuff", "BiomesOPlenty:ash", "BiomesOPlenty:cragRock", "BiomesOPlenty:driedDirt", "BiomesOPlenty:hardDirt", "BiomesOPlenty:hardSand", "BiomesOPlenty:mud", "BiomesOPlenty:newBopDirt", "Botania:dirtPath", "Botania:enchantedSoil", "Botania:livingrock", "Botania:prismarine", "Botania:shimmerrock", "Botany:loam", "Botany:loamNoWeed", "Botany:soil", "Botany:soilNoWeed", "chisel:moss", "chisel:moss_carpet", "DraconicEvolution:earth", "dreamcraft:SandClayMix", "ExtraUtilities:color_hellsand", "ExtraUtilities:cursedearthside", "GalaxySpace:acentauribbgrunt", "GalaxySpace:acentauribbsubgrunt", "GalaxySpace:barnardaCdirt", "GalaxySpace:barnardaEgrunt", "GalaxySpace:barnardaEsubgrunt", "GalaxySpace:barnardaFgrunt", "GalaxySpace:barnardaFsubgrunt", "GalaxySpace:callistoblocks", "GalaxySpace:ceresblocks", "GalaxySpace:deimosblocks", "GalaxySpace:europagrunt", "GalaxySpace:ganymedeblocks", "GalaxySpace:haumeablocks", "GalaxySpace:ioblocks", "GalaxySpace:makemakegrunt", "GalaxySpace:mercuryblocks", "GalaxySpace:mirandablocks", "GalaxySpace:oberonblocks", "GalaxySpace:phobosblocks", "GalaxySpace:proteusblocks", "GalaxySpace:tcetieblocks", "GalaxySpace:titanblocks", "GalaxySpace:tritonblocks", "GalaxySpace:vegabgrunt", "GalaxySpace:vegabsubgrunt", "GalaxySpace:venusblocks", "gregtech:gt.blockgranites", "IC2:blockBasalt", "MagicBees:magicbees.enchantedEarth", "Natura:heatsand", "RandomThings:fertilizedDirt", "TConstruct:CraftedSoil", "TConstruct:SpeedBlock", "thaumicbases:oldCobble", "thaumicbases:oldCobbleMossy", "ToxicEverglades:blockDarkWorldGround2", "VillageNames:concretePowder", "witchery:pitdirt"
})
public static String[] naturalTextureBlocks = new String[] {
"minecraft:andesite", "minecraft:dirt", "minecraft:granite", "minecraft:grass", "minecraft:mycelium", "minecraft:sand", "minecraft:soul_sand", "etfuturum:calcite", "etfuturum:coarse_dirt", "etfuturum:cobbled_deepslate", "etfuturum:concrete_powder", "etfuturum:deepslate", "etfuturum:polished_deepslate", "etfuturum:soul_soil", "etfuturum:tuff", "BiomesOPlenty:ash", "BiomesOPlenty:cragRock", "BiomesOPlenty:driedDirt", "BiomesOPlenty:hardDirt", "BiomesOPlenty:hardSand", "BiomesOPlenty:mud", "BiomesOPlenty:newBopDirt", "Botania:dirtPath", "Botania:enchantedSoil", "Botania:livingrock", "Botania:prismarine", "Botania:shimmerrock", "Botany:loam", "Botany:loamNoWeed", "Botany:soil", "Botany:soilNoWeed", "chisel:moss", "chisel:moss_carpet", "DraconicEvolution:earth", "dreamcraft:SandClayMix", "ExtraUtilities:color_hellsand", "ExtraUtilities:cursedearthside", "GalaxySpace:acentauribbgrunt", "GalaxySpace:acentauribbsubgrunt", "GalaxySpace:barnardaCdirt", "GalaxySpace:barnardaEgrunt", "GalaxySpace:barnardaEsubgrunt", "GalaxySpace:barnardaFgrunt", "GalaxySpace:barnardaFsubgrunt", "GalaxySpace:callistoblocks", "GalaxySpace:ceresblocks", "GalaxySpace:deimosblocks", "GalaxySpace:europagrunt", "GalaxySpace:ganymedeblocks", "GalaxySpace:haumeablocks", "GalaxySpace:ioblocks", "GalaxySpace:makemakegrunt", "GalaxySpace:mercuryblocks", "GalaxySpace:mirandablocks", "GalaxySpace:oberonblocks", "GalaxySpace:phobosblocks", "GalaxySpace:proteusblocks", "GalaxySpace:tcetieblocks", "GalaxySpace:titanblocks", "GalaxySpace:tritonblocks", "GalaxySpace:vegabgrunt", "GalaxySpace:vegabsubgrunt", "GalaxySpace:venusblocks", "gregtech:gt.blockgranites", "IC2:blockBasalt", "MagicBees:magicbees.enchantedEarth", "Natura:heatsand", "RandomThings:fertilizedDirt", "TConstruct:CraftedSoil", "TConstruct:SpeedBlock", "thaumicbases:oldCobble", "thaumicbases:oldCobbleMossy", "ToxicEverglades:blockDarkWorldGround2", "VillageNames:concretePowder", "witchery:pitdirt"
};
public static void applyGpuCullingMode() {
GpuCulling.setMode(gpuCullingMode == null ? GpuCullingMode.CPU_ONLY : gpuCullingMode);
}
@@ -56,9 +56,7 @@ public class FontConfig {
@Config.RangeFloat(min = -2F, max = 2F)
public static float glyphSpacing;
@Config.Comment({
"Controls font antialiasing. 0 = none, 1 = 4x MSAA, 2 = 16x MSAA.",
"Turning off AA lets shaders pick up the text."})
@Config.Comment("Controls font antialiasing. 0 = none, 1 = 4x MSAA, 2 = 16x MSAA.")
@Config.DefaultInt(2)
@Config.RangeInt(min = 0, max = 2)
public static int fontAAMode;
@@ -2,7 +2,6 @@ package com.gtnewhorizons.angelica.debug.flyby;
import com.gtnewhorizons.angelica.config.SystemProperties;
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
import com.gtnewhorizons.angelica.rendering.FramePacer;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent;
import net.minecraft.client.Minecraft;
@@ -58,10 +57,6 @@ public final class FlybyRunner {
private long plotTurning;
private int lastPhase = -1;
private long warmupSection;
private long runSection;
private long legSection;
private long[] frameTimesNs = NO_FRAMES;
private int frameCount;
private boolean framesTruncated;
@@ -185,13 +180,9 @@ public final class FlybyRunner {
this.buildPath();
this.freezeTimeAndWeather(mc);
this.state = this.warmupTicks > 0 ? State.WARMUP : State.RUNNING;
this.tick = 0;
if (this.warmupTicks > 0) {
this.state = State.WARMUP;
this.warmupSection = Tracy.sectionEnter(Tracy.SECTION_BENCHMARK, "flyby warmup");
} else {
this.beginMeasuring();
}
if (this.state == State.RUNNING) this.beginMeasuring();
LOGGER.info("Flyby {} starting at {} {} {} yaw {}", this.route.id(),
this.originX, this.originY, this.originZ, this.originYaw);
@@ -261,18 +252,12 @@ public final class FlybyRunner {
final int phase = (leg << 1) | turning;
if (phase != this.lastPhase) {
this.lastPhase = phase;
final String label = "flyby " + (turning != 0 ? "turn" : "leg") + " " + leg;
Tracy.message(label);
Tracy.sectionLeave(this.legSection);
this.legSection = Tracy.sectionEnter(Tracy.SECTION_BENCHMARK, label);
Tracy.message("flyby " + (turning != 0 ? "turn" : "leg") + " " + leg);
}
}
private void beginMeasuring() {
this.state = State.RUNNING;
Tracy.sectionLeave(this.warmupSection);
this.warmupSection = 0L;
if (Tracy.ENABLED) this.runSection = Tracy.sectionEnter(Tracy.SECTION_BENCHMARK, "flyby " + this.route.id());
this.plotLeg = Tracy.plotHandle("flyby.leg");
this.plotTurning = Tracy.plotHandle("flyby.turning");
this.lastPhase = -1;
@@ -280,10 +265,11 @@ public final class FlybyRunner {
this.frameCount = 0;
this.lastFrameNs = 0L;
this.runStartNs = System.nanoTime();
FramePacer.beginStats();
if (Tracy.ENABLED) {
Tracy.message("flyby start route=" + this.route.id() + " length=" + this.runLength + this.route.lengthUnit() + " speed=" + this.route.speedOr(this.speed) + "b/t ticks=" + this.runTicks + " sdlgpu=" + SystemProperties.USE_SDL_GPU);
}
Tracy.message("flyby start route=" + this.route.id()
+ " length=" + this.runLength + this.route.lengthUnit()
+ " speed=" + this.route.speedOr(this.speed) + "b/t"
+ " ticks=" + this.runTicks
+ " sdlgpu=" + SystemProperties.USE_SDL_GPU);
}
private void holdPosition(EntityClientPlayerMP player) {
@@ -378,15 +364,10 @@ public final class FlybyRunner {
this.state = State.SETTLE;
this.tick = 0;
final long elapsedNs = System.nanoTime() - this.runStartNs;
Tracy.sectionLeave(this.legSection);
this.legSection = 0L;
Tracy.sectionLeave(this.runSection);
this.runSection = 0L;
if (Tracy.ENABLED) Tracy.message("flyby end route=" + this.route.id() + " frames=" + this.frameCount);
Tracy.message("flyby end route=" + this.route.id() + " frames=" + this.frameCount);
final String summary = this.summarise(elapsedNs, player);
LOGGER.info(summary);
LOGGER.info(FramePacer.endStats());
if (mc.thePlayer != null) {
mc.thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.AQUA + "[Angelica] " + EnumChatFormatting.WHITE + summary));
}
@@ -441,13 +422,6 @@ public final class FlybyRunner {
if (this.isActive()) {
LOGGER.info("Flyby cancelled");
this.state = State.DONE;
Tracy.sectionLeave(this.warmupSection);
this.warmupSection = 0L;
Tracy.sectionLeave(this.legSection);
this.legSection = 0L;
Tracy.sectionLeave(this.runSection);
this.runSection = 0L;
FramePacer.endStats();
}
}
@@ -71,6 +71,7 @@ public final class EntityLightConfig {
}
}
@SuppressWarnings("unchecked")
public static List<EntityTypeEntry> getAllEntityTypes() {
List<EntityTypeEntry> entries = new ArrayList<>();
Set<String> seenClasses = new HashSet<>();
@@ -87,8 +88,9 @@ public final class EntityLightConfig {
String modId = getModIdForEntity(entityClass, entityId);
String displayName = getDisplayName(entityId, entityClass);
boolean enabled = !disabledClassNames.contains(className);
entries.add(new EntityTypeEntry(displayName, entityClass, modId));
entries.add(new EntityTypeEntry(displayName, className, modId, enabled));
}
// Sort by mod ID, then by display name
@@ -0,0 +1,20 @@
package com.gtnewhorizons.angelica.dynamiclights.config;
import me.jellysquid.mods.sodium.client.gui.options.storage.OptionStorage;
public class EntityLightConfigStorage implements OptionStorage<EntityLightConfigStorage> {
public static final EntityLightConfigStorage INSTANCE = new EntityLightConfigStorage();
private EntityLightConfigStorage() {}
@Override
public EntityLightConfigStorage getData() {
return this;
}
@Override
public void save() {
EntityLightConfig.save();
}
}
@@ -1,47 +1,42 @@
package com.gtnewhorizons.angelica.dynamiclights.config;
import java.util.Locale;
import org.jetbrains.annotations.NotNull;
public final class EntityTypeEntry {
public class EntityTypeEntry {
private final String displayName;
private final Class<?> entityClass;
private final String className;
private final String modId;
private final String searchName;
private final String searchModId;
private boolean enabled;
public EntityTypeEntry(@NotNull String displayName, @NotNull Class<?> entityClass, @NotNull String modId) {
public EntityTypeEntry(@NotNull String displayName, @NotNull String className, @NotNull String modId, boolean enabled) {
this.displayName = displayName;
this.entityClass = entityClass;
this.className = className;
this.modId = modId;
this.searchName = displayName.toLowerCase(Locale.ROOT);
this.searchModId = modId.toLowerCase(Locale.ROOT);
this.enabled = enabled;
}
public String getDisplayName() {
return displayName;
}
public Class<?> getEntityClass() {
return entityClass;
public String getClassName() {
return className;
}
public String getModId() {
return modId;
}
public String getSearchName() {
return searchName;
public boolean isEnabled() {
return enabled;
}
public String getSearchModId() {
return searchModId;
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
@Override
public String toString() {
return displayName + " (" + modId + ")";
return displayName + " (" + modId + ") [" + (enabled ? "ON" : "OFF") + "]";
}
}
@@ -1,35 +0,0 @@
package com.gtnewhorizons.angelica.helpers;
import static com.gtnewhorizons.angelica.client.font.ColorCodeUtils.FORMATTING_CHAR;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.EnumChatFormatting;
public final class RendererLivingEntityHelper {
private RendererLivingEntityHelper() {}
public static String getUpsideDownName(EntityLivingBase entity) {
if (entity instanceof EntityLiving living) {
return living.hasCustomNameTag() ? entity.getCommandSenderName() : "";
}
if (entity instanceof EntityPlayer player) {
return player.getHideCape() ? "" : entity.getCommandSenderName();
}
return entity.getCommandSenderName();
}
public static String stripFormattingCodes(String entityName) {
if (entityName == null || entityName.isEmpty()) {
return "";
}
return entityName.indexOf(FORMATTING_CHAR) < 0
? entityName
: EnumChatFormatting.getTextWithoutFormattingCodes(entityName);
}
}
@@ -10,9 +10,6 @@ import com.gtnewhorizons.angelica.glsm.hooks.ShaderTransformPostProcessor;
import com.gtnewhorizons.angelica.glsm.shader.ShaderType;
import org.taumc.glsl.grammar.GLSLParser;
import com.gtnewhorizons.angelica.glsm.hooks.ShaderWorkSubmitter;
import com.gtnewhorizons.angelica.glsm.hooks.VanillaBooleanLayer;
import com.gtnewhorizons.angelica.glsm.hooks.VanillaStateLayer;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.sdlgpu.SDLGPUGate;
import net.coderbot.iris.Iris;
import java.util.concurrent.CompletableFuture;
@@ -41,20 +38,7 @@ public class IrisGLSMBridge {
private static Runnable fogDensityListener = null;
private static Runnable colorModulatorListener = null;
private static boolean inputsDeferred = false;
private static boolean blendDeferred = false;
private static boolean programRestoreDeferred = false;
private static final Int2IntOpenHashMap programLastUpdatedFrame = new Int2IntOpenHashMap();
private static void refreshBlendCondition() {
if (Iris.getPipelineManager().getPipelineNullable() instanceof DeferredWorldRenderingPipeline drp) {
drp.onVanillaBlendChanged();
}
}
static {
programLastUpdatedFrame.defaultReturnValue(-1);
StateUpdateNotifiers.alphaFuncNotifier = listener -> alphaFuncListener = listener;
@@ -88,44 +72,6 @@ public class IrisGLSMBridge {
};
}
private static VanillaBooleanLayer gated(VanillaBooleanLayer layer) {
return new VanillaBooleanLayer() {
@Override
public boolean isOverrideHeld() {
return Iris.enabled && layer.isOverrideHeld();
}
@Override
public boolean getVanilla() {
return layer.getVanilla();
}
@Override
public void setVanilla(boolean enabled) {
layer.setVanilla(enabled);
}
};
}
private static <T> VanillaStateLayer<T> gated(VanillaStateLayer<T> layer) {
return new VanillaStateLayer<>() {
@Override
public boolean isOverrideHeld() {
return Iris.enabled && layer.isOverrideHeld();
}
@Override
public void readVanilla(T into) {
layer.readVanilla(into);
}
@Override
public void writeVanilla(T from) {
layer.writeVanilla(from);
}
};
}
public static void register() {
GLSMConfig.expandVertexFormats = Iris.enabled;
IrisSamplers.initRenderer();
@@ -142,11 +88,6 @@ public class IrisGLSMBridge {
return Iris.enabled && BlendModeStorage.isBlendLocked();
}
@Override
public boolean isOverrideHeld() {
return Iris.enabled && BlendModeStorage.isOverrideHeld();
}
@Override
public void deferBlendModeToggle(boolean enabled) {
BlendModeStorage.deferBlendModeToggle(enabled);
@@ -163,13 +104,6 @@ public class IrisGLSMBridge {
}
};
GLStateManager.getBlendMode().setVanillaLayer(gated(BlendModeStorage.ENABLE_LAYER));
GLStateManager.getBlendState().setVanillaLayer(gated(BlendModeStorage.FUNC_LAYER));
GLStateManager.getAlphaTest().setVanillaLayer(gated(AlphaTestStorage.ENABLE_LAYER));
GLStateManager.getAlphaState().setVanillaLayer(gated(AlphaTestStorage.FUNC_LAYER));
GLStateManager.getDepthState().setVanillaLayer(gated(DepthColorStorage.DEPTH_LAYER));
GLStateManager.getColorMask().setVanillaLayer(gated(DepthColorStorage.COLOR_LAYER));
GLSMHooks.alphaHandler = new DeferredAlphaHandler() {
@Override
public boolean isAlphaTestLocked() {
@@ -193,11 +127,6 @@ public class IrisGLSMBridge {
return Iris.enabled && DepthColorStorage.isDepthColorLocked();
}
@Override
public boolean isOverrideHeld() {
return Iris.enabled && DepthColorStorage.isOverrideHeld();
}
@Override
public void deferDepthEnable(boolean enabled) {
DepthColorStorage.deferDepthEnable(enabled);
@@ -261,41 +190,9 @@ public class IrisGLSMBridge {
StateTracker.INSTANCE.lightmapSampler = event.enabled;
updatePipeline = true;
}
if (!updatePipeline) return;
if (GLStateManager.isForeignDraw()) {
inputsDeferred = true;
return;
}
Iris.getPipelineManager().getPipeline().ifPresent(p -> p.setInputs(StateTracker.INSTANCE.getInputs()));
});
GLSMHooks.VANILLA_BLEND_CHANGE.addListener(event -> {
if (!Iris.enabled) return;
if (GLStateManager.isForeignDraw()) {
blendDeferred = true;
return;
}
refreshBlendCondition();
});
GLSMHooks.FOREIGN_DRAW_END.addListener(event -> {
if (!Iris.enabled) return;
if (inputsDeferred) {
inputsDeferred = false;
if (updatePipeline) {
Iris.getPipelineManager().getPipeline().ifPresent(p -> p.setInputs(StateTracker.INSTANCE.getInputs()));
}
if (blendDeferred) {
blendDeferred = false;
refreshBlendCondition();
}
if (programRestoreDeferred) {
programRestoreDeferred = false;
final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable();
if (pipeline instanceof DeferredWorldRenderingPipeline drp && drp.shouldOverrideShaders()) {
drp.restorePassAfterModProgram(GLStateManager.getActiveProgram());
}
}
});
GLSMHooks.PROGRAM_CHANGE.addListener(event -> {
@@ -311,29 +208,15 @@ public class IrisGLSMBridge {
final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable();
if (!(pipeline instanceof DeferredWorldRenderingPipeline drp)) return;
if (!drp.shouldOverrideShaders()) return;
DepthColorStorage.unlockDepthColor();
if (drp.getActivePassProgramId() == -1) return;
if (event.newProgram != 0 && !DepthColorStorage.isOwnedProgram(event.newProgram)) {
if (DepthColorStorage.isOwnedProgram(event.newProgram)) {
DepthColorStorage.unlockDepthColor();
} else {
drp.onModProgramOverride();
}
});
GLSMHooks.PROGRAM_CHANGE.addListener(event -> {
if (!Iris.enabled) return;
if (!event.postBind) return;
final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable();
if (!(pipeline instanceof DeferredWorldRenderingPipeline drp)) return;
if (!drp.shouldOverrideShaders()) return;
if (GLStateManager.isForeignDraw()) {
programRestoreDeferred = true;
return;
}
drp.restorePassAfterModProgram(event.newProgram);
});
GLSMHooks.PROGRAM_CHANGE.addListener(event -> {
if (!Iris.enabled) return;
if (!event.postBind) return;
@@ -3,7 +3,6 @@ package com.gtnewhorizons.angelica.loading.fml.transformers;
import com.gtnewhorizons.angelica.loading.AngelicaClientTweaker;
import com.gtnewhorizons.angelica.loading.shared.AngelicaClassDump;
import com.gtnewhorizons.angelica.loading.shared.transformers.CeleritasBlockTransform;
import com.gtnewhorizons.angelica.loading.shared.transformers.TileEntityMarkerTransform;
import net.minecraft.launchwrapper.IClassTransformer;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
@@ -13,12 +12,10 @@ import org.objectweb.asm.tree.ClassNode;
public class CeleritasBlockTransformer implements IClassTransformer {
private final CeleritasBlockTransform inner;
private final TileEntityMarkerTransform tileEntities;
private final String[] exclusions;
public CeleritasBlockTransformer() {
this.inner = new CeleritasBlockTransform(AngelicaClientTweaker.isObfEnv());
this.tileEntities = new TileEntityMarkerTransform(AngelicaClientTweaker.isObfEnv());
this.exclusions = inner.getTransformerExclusions();
}
@@ -34,19 +31,14 @@ public class CeleritasBlockTransformer implements IClassTransformer {
}
final ClassReader cr = new ClassReader(basicClass);
final String className = cr.getClassName();
inner.trackBlockSubclasses(className, cr.getSuperName());
tileEntities.track(className, cr.getSuperName());
inner.trackBlockSubclasses(cr.getClassName(), cr.getSuperName());
final int markers = tileEntities.markersFor(className, basicClass);
final byte[] marked = markers == 0 ? basicClass : tileEntities.addMarkers(basicClass, markers);
if (!inner.shouldTransform(marked)) {
return marked;
if (!inner.shouldTransform(basicClass)) {
return basicClass;
}
final ClassNode cn = new ClassNode();
(markers == 0 ? cr : new ClassReader(marked)).accept(cn, 0);
cr.accept(cn, 0);
final boolean changed = inner.transformClassNode(transformedName, cn);
if (changed) {
final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
@@ -55,7 +47,7 @@ public class CeleritasBlockTransformer implements IClassTransformer {
AngelicaClassDump.dumpClass(transformedName, basicClass, bytes, this);
return bytes;
}
return marked;
return basicClass;
}
}
@@ -2,7 +2,6 @@ package com.gtnewhorizons.angelica.loading.rfb.transformers;
import com.gtnewhorizons.angelica.loading.shared.AngelicaClassDump;
import com.gtnewhorizons.angelica.loading.shared.transformers.CeleritasBlockTransform;
import com.gtnewhorizons.angelica.loading.shared.transformers.TileEntityMarkerTransform;
import com.gtnewhorizons.retrofuturabootstrap.api.ClassHeaderMetadata;
import com.gtnewhorizons.retrofuturabootstrap.api.ClassNodeHandle;
import com.gtnewhorizons.retrofuturabootstrap.api.ExtensibleClassLoader;
@@ -10,18 +9,15 @@ import com.gtnewhorizons.retrofuturabootstrap.api.RfbClassTransformer;
import org.intellij.lang.annotations.Pattern;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.objectweb.asm.tree.ClassNode;
import java.util.jar.Manifest;
public class RFBCeleritasBlockTransformer implements RfbClassTransformer {
private final CeleritasBlockTransform inner;
private final TileEntityMarkerTransform tileEntities;
public RFBCeleritasBlockTransformer(boolean isObf) {
inner = new CeleritasBlockTransform(isObf);
tileEntities = new TileEntityMarkerTransform(isObf);
}
@Pattern("[a-z0-9-]+")
@@ -58,32 +54,15 @@ public class RFBCeleritasBlockTransformer implements RfbClassTransformer {
return false;
}
final String thisName = metadata.binaryThisName();
final String superName = metadata.binarySuperName();
final byte[] originalBytes = classNode.getOriginalBytes();
inner.trackBlockSubclasses(thisName, superName);
if (context == RfbClassTransformer.Context.LCL_WITH_TRANSFORMS) {
tileEntities.track(thisName, superName);
if (tileEntities.markersFor(thisName, originalBytes) != 0) return true;
}
return inner.shouldTransform(originalBytes);
inner.trackBlockSubclasses(metadata.binaryThisName(), metadata.binarySuperName());
return inner.shouldTransform(classNode.getOriginalBytes());
}
@Override
public boolean transformClassIfNeeded(@NotNull ExtensibleClassLoader classLoader,
@NotNull RfbClassTransformer.Context context, @Nullable Manifest manifest,
@NotNull String className, @NotNull ClassNodeHandle classNode) {
final ClassNode node = classNode.getNode();
boolean changed = false;
if (context == RfbClassTransformer.Context.LCL_WITH_TRANSFORMS) {
final int markers = tileEntities.markersFor(node.name, classNode.getOriginalBytes());
if (markers != 0) {
tileEntities.addMarkers(node, markers);
changed = true;
}
}
changed |= inner.transformClassNode(className, node);
final boolean changed = inner.transformClassNode(className, classNode.getNode());
if (changed) {
classNode.computeMaxs();
AngelicaClassDump.dumpRFBClass(className, classNode, this);
@@ -1,130 +0,0 @@
package com.gtnewhorizons.angelica.loading.shared.transformers;
import com.gtnewhorizon.gtnhlib.asm.ClassConstantPoolParser;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* Marks TileEntity subclasses that declare getDescriptionPacket, shouldRenderInPass or getDistanceFrom with a
* corresponding interface, so runtime code can test with instanceof instead of reflection.
*/
public final class TileEntityMarkerTransform {
public static final int MARK_DESCRIPTION_PACKET = 1 << 0;
public static final int MARK_SHOULD_RENDER_IN_PASS = 1 << 1;
public static final int MARK_GET_DISTANCE_FROM = 1 << 2;
private static final String SENDS_DESCRIPTION_PACKET = "com/gtnewhorizons/angelica/mixins/interfaces/SendsDescriptionPacket";
private static final String OVERRIDES_SHOULD_RENDER_IN_PASS = "com/gtnewhorizons/angelica/mixins/interfaces/OverridesShouldRenderInPass";
private static final String OVERRIDES_GET_DISTANCE_FROM = "com/gtnewhorizons/angelica/mixins/interfaces/OverridesGetDistanceFrom";
private static final String TILE_ENTITY = "net/minecraft/tileentity/TileEntity";
private static final int SCAN_FLAGS = ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES;
private record Marker(int bit, String method, String desc, String iface) {}
private final Marker[] markers;
private final ClassConstantPoolParser prefilter;
private final Set<String> tileEntities = Collections.newSetFromMap(new ConcurrentHashMap<>());
public TileEntityMarkerTransform(boolean isObf) {
this.markers = new Marker[] {
new Marker(MARK_DESCRIPTION_PACKET, isObf ? "func_145844_m" : "getDescriptionPacket", "()Lnet/minecraft/network/Packet;", SENDS_DESCRIPTION_PACKET),
new Marker(MARK_SHOULD_RENDER_IN_PASS, "shouldRenderInPass", "(I)Z", OVERRIDES_SHOULD_RENDER_IN_PASS),
new Marker(MARK_GET_DISTANCE_FROM, isObf ? "func_145835_a" : "getDistanceFrom", "(DDD)D", OVERRIDES_GET_DISTANCE_FROM) };
final String[] methods = new String[markers.length];
for (int i = 0; i < markers.length; i++) methods[i] = markers[i].method();
this.prefilter = new ClassConstantPoolParser(methods);
}
private boolean isTileEntity(String className) {
return className != null && (className.startsWith(TILE_ENTITY) || tileEntities.contains(className));
}
public void track(String className, String superClassName) {
if (className != null && isTileEntity(superClassName)) tileEntities.add(className);
}
public int markersFor(String className, byte[] classBytes) {
if (TILE_ENTITY.equals(className) || !isTileEntity(className) || !prefilter.find(classBytes)) return 0;
final MarkerScanner scanner = new MarkerScanner();
new ClassReader(classBytes).accept(scanner, SCAN_FLAGS);
return scanner.declared & ~scanner.alreadyPresent;
}
public byte[] addMarkers(byte[] classBytes, int markers) {
final ClassReader cr = new ClassReader(classBytes);
final ClassWriter cw = new ClassWriter(cr, 0);
cr.accept(new ClassVisitor(Opcodes.ASM5, cw) {
@Override
public void visit(int version, int access, String name, String sig, String superName, String[] interfaces) {
final String[] added = interfacesFor(markers);
if (interfaces == null) {
super.visit(version, access, name, sig, superName, added);
return;
}
final String[] merged = Arrays.copyOf(interfaces, interfaces.length + added.length);
System.arraycopy(added, 0, merged, interfaces.length, added.length);
super.visit(version, access, name, sig, superName, merged);
}
}, 0);
return cw.toByteArray();
}
public void addMarkers(ClassNode cn, int markers) {
Collections.addAll(cn.interfaces, interfacesFor(markers));
}
private int bitOf(int access, String name, String desc) {
if ((access & Opcodes.ACC_PUBLIC) == 0 || (access & Opcodes.ACC_STATIC) != 0) return 0;
for (Marker m : markers) if (m.method().equals(name) && m.desc().equals(desc)) return m.bit();
return 0;
}
private int bitOf(String interfaceName) {
for (Marker m : markers) if (m.iface().equals(interfaceName)) return m.bit();
return 0;
}
private String[] interfacesFor(int wanted) {
final String[] names = new String[Integer.bitCount(wanted)];
int next = 0;
for (Marker m : markers) if ((wanted & m.bit()) != 0) names[next++] = m.iface();
return names;
}
private final class MarkerScanner extends ClassVisitor {
private int declared;
private int alreadyPresent;
MarkerScanner() {
super(Opcodes.ASM5);
}
@Override
public void visit(int version, int access, String name, String sig, String superName, String[] interfaces) {
if (interfaces == null) return;
for (String iface : interfaces) alreadyPresent |= bitOf(iface);
}
@Override
public MethodVisitor visitMethod(int access, String name, String desc, String sig, String[] exceptions) {
declared |= bitOf(access, name, desc);
return null;
}
}
}
@@ -70,12 +70,6 @@ public enum Mixins implements IMixins {
)
),
STARMINER_RENDERER_LIVING_ENTITY_OPTIMIZATION(new MixinBuilder()
.setPhase(Phase.LATE)
.addRequiredMod(TargetedMod.STARMINER)
.addClientMixins("client.starminer.MixinTransformClientHelper")
),
ANGELICA_ENTITY_OVERLAYS(new MixinBuilder()
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.entityOverlayFixes)
@@ -383,11 +377,6 @@ public enum Mixins implements IMixins {
, "celeritas.biome_blending.MixinBlockLiquid"
, "celeritas.threading.MixinForgeHooksClient"
, "celeritas.terrain.MixinChunk"
, "celeritas.terrain.MixinWorldClient_WorkerAccess"
, "celeritas.terrain.MixinWorld_WorkerMutationGuard"
, "celeritas.terrain.MixinTileEntity_AwaitingDescriptor"
, "celeritas.terrain.MixinNetHandlerPlayClient_DescriptorRepair"
, "celeritas.terrain.MixinWorld_AwaitingDescriptor"
, "celeritas.terrain.MixinRenderRegion"
, "celeritas.terrain.MixinSectionRenderDataStorage"
, "celeritas.terrain.MixinDefaultChunkRenderer"
@@ -417,13 +406,11 @@ public enum Mixins implements IMixins {
.addClientMixins(
"shaders.MixinDroppedItemGlintEdges"
, "shaders.MixinHeldItemGlintEdges"
, "shaders.MixinEffectRenderer_Particles"
, "shaders.MixinEntityPickupFX"
, "shaders.MixinEntityRenderer"
, "shaders.MixinGuiIngameForge"
, "shaders.MixinFramebuffer"
, "shaders.MixinItem"
, "shaders.MixinItemRenderer_ItemId"
, "shaders.MixinLocale"
, "shaders.MixinRender"
, "shaders.MixinRenderBiped"
@@ -746,24 +733,6 @@ public enum Mixins implements IMixins {
.setApplyIf(() -> AngelicaConfig.enableIris)
.addClientMixins("client.etfuturum.MixinLayerBetterElytra")
),
ET_FUTURUM_BEACON_BEAM(new MixinBuilder("Iris Et Futurum Beacon Beam")
.setPhase(Phase.LATE)
.addRequiredMod(TargetedMod.ET_FUTURUM_REQUIEM)
.setApplyIf(() -> AngelicaConfig.enableIris)
.addClientMixins("client.etfuturum.MixinTileEntityNewBeaconRenderer")
),
OPENBLOCKS_TROPHY_ENTITY_GBUFFER(new MixinBuilder("Render OpenBlocks trophies with the entity gbuffer programs")
.setPhase(Phase.LATE)
.addRequiredMod(TargetedMod.OPENBLOCKS)
.setApplyIf(() -> AngelicaConfig.enableIris)
.addClientMixins("client.openblocks.MixinTileEntityTrophyRenderer")
),
DRAGONAPI_PARTICLE_SPLIT(new MixinBuilder("Split DragonAPI's replacement particle renderer between the particle gbuffer programs")
.setPhase(Phase.LATE)
.addRequiredMod(TargetedMod.DRAGON_API)
.setApplyIf(() -> AngelicaConfig.enableIris)
.addClientMixins("client.dragonapi.MixinThrottleableEffectRenderer")
),
MCPATCHER_FORGE(new MixinBuilder()
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.enableMCPatcherForgeFeatures)
@@ -23,9 +23,7 @@ public enum TargetedMod implements ITargetMod {
NTM_SPACE("com.hbm.dim.SolarSystem"),
IC2("ic2.core.coremod.IC2core", "IC2"),
NATURA(null, "Natura"),
OPENBLOCKS(null, "OpenBlocks"),
SECURITYCRAFT(null, "securitycraft"),
STARMINER("jp.mc.ancientred.starminer.core.SMPlugin", "modJ_StarMiner"),
SUPERNOVA("com.mitchej123.supernova.core.SupernovaCore", "supernova"),
THAUMCRAFT(null, "Thaumcraft"),
TINKERS_CONSTRUCT(null, "TConstruct"),
@@ -1,12 +0,0 @@
package com.gtnewhorizons.angelica.mixins.interfaces;
public interface AwaitingDescriptorTE {
boolean angelica$isAwaitingDescriptor();
void angelica$setAwaitingDescriptor(boolean awaiting);
int angelica$getDescriptorWaitTicks();
void angelica$setDescriptorWaitTicks(int ticks);
}
@@ -6,4 +6,6 @@ public interface ITileEntityBoundingBoxCache {
AxisAlignedBB angelica$getCachedRenderBoundingBox();
byte angelica$boundsClass();
byte angelica$passClass();
}
@@ -1,8 +0,0 @@
package com.gtnewhorizons.angelica.mixins.interfaces;
import net.minecraft.item.ItemStack;
public interface ItemRendererAccessor {
ItemStack angelica$getItemToRender();
}
@@ -1,3 +0,0 @@
package com.gtnewhorizons.angelica.mixins.interfaces;
public interface OverridesGetDistanceFrom {}
@@ -1,3 +0,0 @@
package com.gtnewhorizons.angelica.mixins.interfaces;
public interface OverridesShouldRenderInPass {}
@@ -1,3 +0,0 @@
package com.gtnewhorizons.angelica.mixins.interfaces;
public interface SendsDescriptionPacket {}
@@ -1,39 +0,0 @@
package com.gtnewhorizons.angelica.profiling;
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
import net.minecraft.client.gui.GuiMainMenu;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiIngameMenu;
import java.util.HashMap;
import java.util.Map;
public final class TracyUiSections {
private static final Map<Class<?>, String> LABELS = new HashMap<>();
private static Class<?> current = TracyUiSections.class;
private static long section;
private TracyUiSections() {}
public static void poll(GuiScreen screen) {
if (!Tracy.ENABLED) return;
final Class<?> screenClass = screen == null ? null : screen.getClass();
if (screenClass == current) return;
current = screenClass;
Tracy.sectionLeave(section);
section = Tracy.sectionEnter(Tracy.SECTION_UI, label(screenClass));
}
private static String label(Class<?> screenClass) {
if (screenClass == null) return "in world";
String label = LABELS.get(screenClass);
if (label == null) {
if (screenClass == GuiMainMenu.class) label = "main menu";
else if (screenClass == GuiIngameMenu.class) label = "pause";
else label = screenClass.getSimpleName();
LABELS.put(screenClass, label);
}
return label;
}
}
@@ -55,7 +55,6 @@ import com.gtnewhorizons.angelica.dynamiclights.DynamicLights;
import com.gtnewhorizons.angelica.dynamiclights.config.EntityLightConfig;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.backend.VSyncMode;
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
import com.gtnewhorizons.angelica.hudcaching.HUDCaching;
import com.gtnewhorizons.angelica.iris.IrisGLSMBridge;
import com.gtnewhorizons.angelica.loading.AngelicaClientTweaker;
@@ -217,15 +216,9 @@ public final class ClientProxy extends CommonProxy {
}
}
private long worldSection;
@SubscribeEvent
public void worldLoad(WorldEvent.Load event) {
if (!event.world.isRemote) return;
if (Tracy.ENABLED) {
Tracy.sectionLeave(this.worldSection);
this.worldSection = Tracy.sectionEnter(Tracy.SECTION_WORLD, "world " + event.world.provider.getDimensionName() + " (dim " + event.world.provider.dimensionId + ")");
}
if (GLStateManager.isRunningSplash()) {
GLStateManager.setRunningSplash(false);
LOGGER.info("World loaded - Enabling GLSM Cache");
@@ -245,8 +238,6 @@ public final class ClientProxy extends CommonProxy {
@SubscribeEvent
public void onWorldUnload(WorldEvent.Unload event) {
if (!event.world.isRemote) return;
Tracy.sectionLeave(this.worldSection);
this.worldSection = 0L;
DynamicLights.get().removeAllLightSources();
GpuCulling.onWorldUnload();
}
@@ -73,9 +73,6 @@ public final class SelectionBoxRenderer {
public static void draw(AxisAlignedBB aabb, int color) {
if (program == null || vao == null) return;
GLStateManager.enableDepthTest();
GLStateManager.glDepthFunc(GL11.GL_LEQUAL);
final float minX = (float) aabb.minX, minY = (float) aabb.minY, minZ = (float) aabb.minZ;
final float extX = (float) (aabb.maxX - aabb.minX);
final float extY = (float) (aabb.maxY - aabb.minY);
@@ -123,11 +123,11 @@ public class DeferredEntityOverlay {
GbufferPrograms.beginEntities();
try {
for (DeferredEntry entry : deferred) {
CapturedRenderingState.INSTANCE.setCurrentEntityAndItem(EntityIdHelper.getEntityId(entry.entity), 0);
CapturedRenderingState.INSTANCE.setCurrentEntity(EntityIdHelper.getEntityId(entry.entity));
renderOverlay(entry);
}
} finally {
CapturedRenderingState.INSTANCE.setCurrentEntityAndItem(-1, 0);
CapturedRenderingState.INSTANCE.setCurrentEntity(-1);
GbufferPrograms.endEntities();
}
recycle();
@@ -4,7 +4,6 @@ import com.gtnewhorizons.angelica.AngelicaMod;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.backend.VSyncMode;
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
import com.gtnewhorizons.angelica.glsm.profiling.TracyBackend;
import java.util.concurrent.locks.LockSupport;
@@ -26,21 +25,16 @@ public final class FramePacer {
private static final Tracy.ZoneId Z_PACER_IDLE = Tracy.zoneId("pacerIdleWork", Tracy.COLOR_CLIENT);
private static final Tracy.ZoneId Z_PACER_SLEEP = Tracy.zoneId("pacerSleep", Tracy.COLOR_SWAP);
private static final long P_FRAME_GATE_US = Tracy.plotHandle("frameGateUs");
private static final long P_SLACK_US = Tracy.plotHandle("pacer.slackUs");
private static final long P_SPIN_US = Tracy.plotHandle("pacer.spinUs");
private static final long P_CEILING_HZ = Tracy.plotHandle("pacer.ceilingHz");
private static final long P_GATE_ACTIVE = Tracy.plotHandle("pacer.gateActive");
private static long deadline;
private static long lastFrameTime;
private static boolean warnedUncapped;
private static boolean pacedLastFrame;
private static boolean statsActive;
private static VSyncMode lastVSyncMode = VSyncMode.ON;
private static int lastCapHz;
private static int lastRefreshHz;
private static int lastCeilingHz;
private static IdleWork idleWork;
private static PacerSleeper sleeper = newSleeper();
@@ -53,6 +47,7 @@ public final class FramePacer {
private static int loggedRefreshHz;
private static int loggedCapHz;
private static boolean gateBlocking;
private static long lastSeenGateEnd;
private FramePacer() {}
@@ -65,35 +60,6 @@ public final class FramePacer {
idleWork = work;
}
public static boolean pacedLastFrame() {
return pacedLastFrame;
}
public static void beginStats() {
sleeper.resetStats();
statsActive = true;
}
public static String endStats() {
statsActive = false;
final String summary = sleeper.summary(configLine());
Tracy.message(summary);
return summary;
}
static boolean statsActive() {
return statsActive;
}
static String configLine(VSyncMode mode, int refreshHz, int capHz, int ceilingHz) {
return "cfg=[" + mode + " refresh=" + refreshHz + "Hz cap=" + capHz + " ceiling=" + ceilingHz + "Hz]";
}
private static String configLine() {
return configLine(lastVSyncMode, lastRefreshHz, lastCapHz,
pacingCeilingHz(lastVSyncMode, lastCapHz, lastRefreshHz, gateActive()));
}
public static int plausibleRefreshHz(int hz) {
return hz >= MIN_PLAUSIBLE_REFRESH_HZ && hz <= MAX_PLAUSIBLE_REFRESH_HZ ? hz : 0;
}
@@ -189,6 +155,11 @@ public final class FramePacer {
}
public static long pace(int ceilingHz, Runnable renderAheadWait) {
if (ceilingHz != lastCeilingHz) {
lastCeilingHz = ceilingHz;
deadline = 0L;
}
long now = System.nanoTime();
long phaseEnd;
@@ -196,9 +167,6 @@ public final class FramePacer {
final long thresholdNanos = gateBlockThresholdNanos(targetNanos);
long frameGateNanos = 0L;
pacedLastFrame = ceilingHz > 0;
Tracy.plotInt(P_CEILING_HZ, ceilingHz);
if (ceilingHz > 0) {
frameGateNanos = GLStateManager.lastFrameGateNanos();
final long gateEnd = GLStateManager.lastFrameGateEndNanos();
@@ -224,11 +192,8 @@ public final class FramePacer {
now = phaseEnd;
}
final long slackNanos = deadline - now;
Tracy.plotInt(P_SLACK_US, slackNanos / 1000);
final boolean slept = now < deadline;
if (slept) {
if (now < deadline) {
final long preSleep = now;
Tracy.beginZone(Z_PACER_SLEEP);
try {
now = sleeper.sleepUntil(deadline, now);
@@ -236,10 +201,6 @@ public final class FramePacer {
Tracy.endZone();
}
}
if (Tracy.ENABLED || statsActive) {
sleeper.noteFrame(slackNanos, slept ? now - deadline : 0L, slept);
Tracy.plotInt(P_SPIN_US, sleeper.lastSpinNanos / 1000);
}
} else {
deadline = 0L;
}
@@ -254,18 +215,15 @@ public final class FramePacer {
final long waitNanos = phaseEnd - now;
now = phaseEnd;
if (ceilingHz > 0 && waitNanos > thresholdNanos) deadline = now;
final boolean gateBlocking = observeGate(ceilingHz > 0 ? Math.max(frameGateNanos, waitNanos) : 0L, thresholdNanos);
Tracy.plotInt(P_GATE_ACTIVE, gateBlocking ? 1 : 0);
gateBlocking = observeGate(ceilingHz > 0 ? Math.max(frameGateNanos, waitNanos) : 0L, thresholdNanos);
GLStateManager.pumpDisplayMessages();
if (pacingStatusChanged(gateBlocking, lastVSyncMode, lastRefreshHz, lastCapHz)) {
final boolean blocking = settledBlocking;
final String line = pacingLine(lastVSyncMode, lastRefreshHz, lastCapHz, blocking);
final boolean notHonoured = vsyncNotHonoured(lastVSyncMode, blocking);
if (notHonoured) AngelicaMod.LOGGER.warn(line);
if (vsyncNotHonoured(lastVSyncMode, blocking)) AngelicaMod.LOGGER.warn(line);
else AngelicaMod.LOGGER.info(line);
Tracy.message(line, notHonoured ? TracyBackend.SEVERITY_WARNING : TracyBackend.SEVERITY_INFO);
}
final long period = lastFrameTime == 0L ? 0L : now - lastFrameTime;
@@ -5,50 +5,31 @@ import java.util.function.LongSupplier;
final class PacerSleeper {
private static final long SPIN_FLOOR_NANOS = 100_000L;
private static final long MIN_PARK_NANOS = 1_000_000L;
private static final long MAX_OVERSHOOT_NANOS = 4_000_000L;
static final int SLOTS = 10;
static final long MIN_SPIN_FLOOR_NANOS = 20_000L;
private static final long MAX_SPIN_FLOOR_NANOS = 500_000L;
private static final int SLOTS = 10;
private final LongSupplier clock;
private final LongConsumer parker;
private final boolean spinWait;
private final long[] overshoots = new long[SLOTS];
private long overshootSum;
private long spinFloorNanos = MIN_SPIN_FLOOR_NANOS;
private int offset;
long lastSpinNanos;
int lastParks;
private long frames;
private long slackSum;
private long parkTotal;
private long lateFrames;
private long lateMax;
PacerSleeper(LongSupplier clock, LongConsumer parker, boolean spinWait) {
this.clock = clock;
this.parker = parker;
this.spinWait = spinWait;
}
long spinFloorNanos() {
return spinFloorNanos;
}
long sleepUntil(long deadlineNanos, long now) {
resetLastFrame();
long spinFloor = spinFloorNanos;
while (true) {
final long remaining = deadlineNanos - now;
if (remaining <= spinFloor) break;
if (remaining <= SPIN_FLOOR_NANOS) break;
if (Thread.currentThread().isInterrupted()) return clock.getAsLong();
long request = remaining - avgOvershootNanos() - spinFloor;
long request = remaining - avgOvershootNanos() - SPIN_FLOOR_NANOS;
if (request <= 0L) {
if (remaining <= MIN_PARK_NANOS) break;
request = MIN_PARK_NANOS;
@@ -58,51 +39,17 @@ final class PacerSleeper {
parker.accept(request);
now = clock.getAsLong();
record(Math.min(Math.max(0L, now - before - request), MAX_OVERSHOOT_NANOS));
spinFloor = spinFloorNanos;
lastParks++;
}
if (spinWait) {
final long spinStart = now;
while (now < deadlineNanos) {
if (deadlineNanos - now > spinFloor) Thread.yield();
else Thread.onSpinWait();
Thread.yield();
now = clock.getAsLong();
}
lastSpinNanos = now - spinStart;
}
return now;
}
void noteFrame(long slackNanos, long wakeLateNanos, boolean slept) {
if (!slept) resetLastFrame();
frames++;
slackSum += slackNanos;
parkTotal += lastParks;
if (slackNanos < 0L && -slackNanos > lateMax) lateMax = -slackNanos;
if (slackNanos < 0L || wakeLateNanos > 0L) lateFrames++;
}
private void resetLastFrame() {
lastSpinNanos = 0L;
lastParks = 0;
}
void resetStats() {
frames = 0L;
slackSum = 0L;
parkTotal = 0L;
lateFrames = 0L;
lateMax = 0L;
}
String summary(String config) {
if (frames == 0L) return "pacer: " + config + " no paced frames";
return "pacer: " + config + " frames=" + frames + " parks=" + parkTotal + " slackUs avg=" + slackSum / frames / 1000L + " floorUs=" + spinFloorNanos / 1000L
+ " overshootUs est=" + avgOvershootNanos() / 1000L + " lateFrames=" + lateFrames + " lateMaxUs=" + lateMax / 1000L;
}
long avgOvershootNanos() {
return overshootSum / SLOTS;
}
@@ -111,12 +58,5 @@ final class PacerSleeper {
overshootSum += nanos - overshoots[offset];
overshoots[offset] = nanos;
offset = (offset + 1) % SLOTS;
long max = 0L;
for (final long o : overshoots) {
if (o > max) max = o;
}
final long jitter = max - avgOvershootNanos();
spinFloorNanos = Math.max(MIN_SPIN_FLOOR_NANOS, Math.min(MAX_SPIN_FLOOR_NANOS, jitter));
}
}
@@ -1,63 +0,0 @@
package com.gtnewhorizons.angelica.rendering;
import com.gtnewhorizons.angelica.client.rendering.DeferredDrawBatcher;
import com.gtnewhorizons.angelica.rendering.celeritas.SpriteExtension;
import net.coderbot.iris.layer.GbufferPrograms;
import net.minecraft.client.particle.EntityCloudFX;
import net.minecraft.client.particle.EntityFX;
import net.minecraft.client.particle.EntityFireworkOverlayFX;
import net.minecraft.client.particle.EntityFireworkSparkFX;
import net.minecraft.client.particle.EntityFireworkStarterFX;
import net.minecraft.client.particle.EntitySpellParticleFX;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import org.embeddedt.embeddium.impl.render.chunk.sprite.SpriteTransparencyLevel;
/**
* Splits a particle run between {@code gbuffers_particles} and {@code gbuffers_particles_translucent}.
*/
public final class ParticleRunSplitter {
private static boolean runTranslucent;
private ParticleRunSplitter() {}
public static void beginRun() {
runTranslucent = false;
GbufferPrograms.setTranslucencyDeclaration(Boolean.FALSE);
}
public static void splitIfNeeded(EntityFX particle, Tessellator tessellator, float partialTicks) {
final boolean translucent = isTranslucent(particle);
if (translucent == runTranslucent) {
return;
}
final boolean batcherWasActive = DeferredDrawBatcher.isActive();
if (batcherWasActive) {
DeferredDrawBatcher.exitAndFlush();
}
tessellator.draw();
runTranslucent = translucent;
GbufferPrograms.setTranslucencyDeclaration(translucent);
tessellator.startDrawingQuads();
tessellator.setBrightness(particle.getBrightnessForRender(partialTicks));
if (batcherWasActive) {
DeferredDrawBatcher.enter();
}
}
public static boolean isTranslucent(EntityFX particle) {
if (particle.particleIcon instanceof TextureAtlasSprite sprite) {
return ((SpriteExtension) sprite).celeritas$getTransparencyLevel() == SpriteTransparencyLevel.TRANSLUCENT;
}
return particle instanceof EntityFireworkSparkFX
|| particle instanceof EntityFireworkOverlayFX
|| particle instanceof EntityFireworkStarterFX
|| particle instanceof EntitySpellParticleFX
|| particle instanceof EntityCloudFX;
}
}
@@ -71,7 +71,6 @@ public final class PlayerReflectionCapture {
private static final Matrix4f pendingModelView = new Matrix4f();
private static int pendingSkin;
private static int pendingEntityId;
private static int pendingItemId;
private static int vbo;
private static int vao;
@@ -135,7 +134,6 @@ public final class PlayerReflectionCapture {
pendingModelView.set(GLStateManager.getModelViewMatrix());
pendingSkin = GLStateManager.getBoundTextureForServerState(0);
pendingEntityId = CapturedRenderingState.INSTANCE.getCurrentRenderedEntity();
pendingItemId = CapturedRenderingState.INSTANCE.getCurrentRenderedItem();
pending = true;
}
@@ -330,10 +328,9 @@ public final class PlayerReflectionCapture {
final boolean prevDepthWrite = GLStateManager.getDepthState().isEnabled();
final int prevEntityId = CapturedRenderingState.INSTANCE.getCurrentRenderedEntity();
final int prevItemId = CapturedRenderingState.INSTANCE.getCurrentRenderedItem();
savedModelView.set(GLStateManager.getModelViewMatrix());
CapturedRenderingState.INSTANCE.setCurrentEntityAndItem(pendingEntityId, pendingItemId);
CapturedRenderingState.INSTANCE.setCurrentEntity(pendingEntityId);
GLStateManager.setModelViewMatrix(pendingModelView);
if (maskable) {
GLStateManager.glColorMask(false, false, false, false);
@@ -347,7 +344,7 @@ public final class PlayerReflectionCapture {
GLStateManager.glColorMask(pr, pg, pb, pa);
}
GLStateManager.setModelViewMatrix(savedModelView);
CapturedRenderingState.INSTANCE.setCurrentEntityAndItem(prevEntityId, prevItemId);
CapturedRenderingState.INSTANCE.setCurrentEntity(prevEntityId);
GLStateManager.glBindVertexArray(0);
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, prevTexture);
@@ -1,7 +1,7 @@
package com.gtnewhorizons.angelica.rendering;
import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager;
import com.gtnewhorizons.angelica.rendering.celeritas.world.WorldSlice;
import net.minecraft.tileentity.TileEntity;
public class RenderThreadContext {
@@ -15,13 +15,10 @@ public class RenderThreadContext {
currentWorldSlice.remove();
}
public static WorldSlice get() {
return currentWorldSlice.get();
}
public static WorldSlice workerSlice() {
if (TessellatorManager.isOnMainThread()) return null;
return currentWorldSlice.get();
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() {
@@ -1,20 +1,18 @@
package com.gtnewhorizons.angelica.rendering;
/// Despite not in the `api` package, this interface is used by GT5uNH and GTNHLib, possibly others. Be careful what you
/// change!
@SuppressWarnings("unused")
public interface StateAwareTessellator {
/// True if the vertex originated from a RenderBlocks method call with the enableAO flag set.
/**
* True if the vertex originated from a RenderBlocks method call with the enableAO flag set.
*/
int RENDERED_WITH_VANILLA_AO = 0x1;
int NO_DIRECTIONAL_SHADING = 0x2;
void angelica$setAppliedAo(boolean flag);
void angelica$setNoDirectionalShading(boolean flag);
/// Sets whether we're doing terrain meshing as part of celeritas -- collects additional information.
///
/// Enables per-vertex AO state collection into [#angelica$getVertexStates()].
/**
* Sets whether we're doing terrain meshing as part of celeritas -- collects additional information.
*
* Enables per-vertex AO state collection into {@link #angelica$getVertexStates()}.
*/
void angelica$setCeleritasMeshing(boolean active);
int[] angelica$getVertexStates();
@@ -1,6 +1,7 @@
package com.gtnewhorizons.angelica.rendering;
import it.unimi.dsi.fastutil.objects.Reference2ByteOpenHashMap;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
@@ -16,12 +17,25 @@ public final class TileEntityRenderBoundsRegistry {
public static final byte INFINITE = 2;
public static final byte DYNAMIC = 3;
public static final byte PASS0_ONLY = 1;
public static final byte PASS_OVERRIDES = 2;
private static final byte NOT_OVERRIDDEN = 1;
private static final byte OVERRIDDEN = 2;
private static final Reference2ByteOpenHashMap<Class<? extends TileEntity>> classRegistry = new Reference2ByteOpenHashMap<>();
private static final Reference2ByteOpenHashMap<Class<? extends TileEntity>> passClassRegistry = new Reference2ByteOpenHashMap<>();
private static final Reference2ByteOpenHashMap<Class<? extends TileEntity>> distanceOverrideRegistry = new Reference2ByteOpenHashMap<>();
private static final Set<String> dynamicClassNames = ConcurrentHashMap.newKeySet();
private static final String[] SHOULD_RENDER_IN_PASS_NAMES = { "shouldRenderInPass" };
private static String[] distanceFromNames;
static {
classRegistry.defaultReturnValue(UNKNOWN);
passClassRegistry.defaultReturnValue(UNKNOWN);
distanceOverrideRegistry.defaultReturnValue(UNKNOWN);
}
private TileEntityRenderBoundsRegistry() {}
@@ -59,4 +73,72 @@ public final class TileEntityRenderBoundsRegistry {
}
return result;
}
public static boolean overridesMethod(Class<?> clazz, Class<?> base, String[] candidateNames, Class<?>... params) {
for (String name : candidateNames) {
try {
return clazz.getMethod(name, params).getDeclaringClass() != base;
} catch (NoSuchMethodException ignored) {
} catch (Throwable t) {
return true;
}
}
return true;
}
private static String[] distanceFromNames() {
String[] names = distanceFromNames;
if (names == null) {
String resolved;
try {
resolved = Boolean.TRUE.equals(Launch.blackboard.get("fml.deobfuscatedEnvironment")) ? "getDistanceFrom" : "func_145835_a";
} catch (Throwable t) {
resolved = "getDistanceFrom";
}
distanceFromNames = names = new String[] { resolved };
}
return names;
}
public static byte classifyPass(TileEntity te) {
final Class<? extends TileEntity> clazz = te.getClass();
synchronized (passClassRegistry) {
final byte cached = passClassRegistry.getByte(clazz);
if (cached != UNKNOWN) return cached;
}
final byte result = overridesMethod(clazz, TileEntity.class, SHOULD_RENDER_IN_PASS_NAMES, int.class)
? PASS_OVERRIDES : PASS0_ONLY;
synchronized (passClassRegistry) {
passClassRegistry.put(clazz, result);
}
return result;
}
public static boolean overridesGetDistanceFrom(Class<? extends TileEntity> clazz) {
synchronized (distanceOverrideRegistry) {
final byte cached = distanceOverrideRegistry.getByte(clazz);
if (cached != UNKNOWN) return cached == OVERRIDDEN;
}
final boolean overrides = overridesMethod(clazz, TileEntity.class, distanceFromNames(), double.class, double.class, double.class);
synchronized (distanceOverrideRegistry) {
distanceOverrideRegistry.put(clazz, overrides ? OVERRIDDEN : NOT_OVERRIDDEN);
}
return overrides;
}
public static void clear() {
synchronized (classRegistry) {
classRegistry.clear();
}
synchronized (passClassRegistry) {
passClassRegistry.clear();
}
synchronized (distanceOverrideRegistry) {
distanceOverrideRegistry.clear();
}
}
}
@@ -1,120 +0,0 @@
package com.gtnewhorizons.angelica.rendering;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.CodeSource;
import java.util.Arrays;
import net.minecraft.block.Block;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.gtnewhorizons.angelica.mixins.interfaces.IRenderingRegistryExt;
import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler;
import cpw.mods.fml.client.registry.RenderingRegistry;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.ModContainer;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.GameRegistry.UniqueIdentifier;
public final class WorkerWorldAccess {
private static final String REPORT_URL = "https://github.com/GTNewHorizons/angelica/issues";
private static final int INITIAL_SLOTS = 64;
private static final Logger LOGGER = LogManager.getLogger("Angelica");
private static final LoggedRenderTypeErrors READS = new LoggedRenderTypeErrors();
private static final LoggedRenderTypeErrors WRITES = new LoggedRenderTypeErrors();
private WorkerWorldAccess() {}
public static void readOutsideSlice(String worldMethod, int x, int y, int z, Block renderingBlock) {
if (!READS.shouldLog(renderingBlock)) return;
LOGGER.warn(describe(worldMethod, "read outside the chunk slice", x, y, z, renderingBlock), new Throwable());
}
public static void blockedWrite(String worldMethod, int x, int y, int z, Block renderingBlock) {
if (!WRITES.shouldLog(renderingBlock)) return;
LOGGER.error(describe(worldMethod, "ignored, it would corrupt world data", x, y, z, renderingBlock), new Throwable());
}
private static String describe(String worldMethod, String outcome, int x, int y, int z, Block block) {
final StringBuilder sb = new StringBuilder(224);
sb.append("Off-thread World.").append(worldMethod).append(' ').append(outcome).append(" at ").append(x).append(',').append(y).append(',').append(z);
if (block != null) {
sb.append(". Rendering ").append(nameOf(block));
final ISimpleBlockRenderingHandler isbrh = isbrhOf(block);
if (isbrh != null) {
sb.append(" via ").append(isbrh.getClass().getName());
final String owner = modIdOf(isbrh.getClass());
if (owner != null) sb.append(" from ").append(owner);
}
}
return sb.append(". Please report with this trace: ").append(REPORT_URL).toString();
}
private static String nameOf(Block block) {
try {
final UniqueIdentifier id = GameRegistry.findUniqueIdentifierFor(block);
if (id != null) return id.modId + ':' + id.name;
} catch (Throwable ignored) {}
return block.getClass().getName();
}
@SuppressWarnings("deprecation")
private static ISimpleBlockRenderingHandler isbrhOf(Block block) {
try {
return ((IRenderingRegistryExt) RenderingRegistry.instance()).getISBRH(block.getRenderType());
} catch (Throwable ignored) {
return null;
}
}
private static String modIdOf(Class<?> clazz) {
try {
final CodeSource source = clazz.getProtectionDomain() == null ? null : clazz.getProtectionDomain().getCodeSource();
if (source == null || source.getLocation() == null) return null;
final File jar = new File(jarFileUrl(source.getLocation()).toURI());
for (ModContainer mod : Loader.instance().getModList()) {
if (jar.equals(mod.getSource())) return mod.getModId();
}
} catch (Throwable ignored) {}
return null;
}
private static URL jarFileUrl(URL location) throws MalformedURLException {
if (!"jar".equals(location.getProtocol())) return location;
final String nested = location.getPath();
final int separator = nested.indexOf("!/");
return new URL(separator < 0 ? nested : nested.substring(0, separator));
}
private static final class LoggedRenderTypeErrors {
private volatile boolean[] logged = new boolean[INITIAL_SLOTS];
boolean shouldLog(Block block) {
final int renderType = block == null ? -1 : block.getRenderType();
final int slot = renderType < 0 ? 0 : renderType + 1;
final boolean[] current = this.logged;
return (slot >= current.length || !current[slot]) && markLogged(slot);
}
private synchronized boolean markLogged(int slot) {
boolean[] current = this.logged;
if (slot < current.length) {
if (current[slot]) return false;
current[slot] = true;
return true;
}
current = Arrays.copyOf(current, Math.max(slot + 1, current.length * 2));
current[slot] = true;
this.logged = current;
return true;
}
}
}
@@ -1,7 +1,5 @@
package com.gtnewhorizons.angelica.rendering.celeritas;
import static com.gtnewhorizons.angelica.rendering.StateAwareTessellator.NO_DIRECTIONAL_SHADING;
import com.gtnewhorizons.angelica.api.ExtQuadLightData;
import com.gtnewhorizons.angelica.api.TintComputer;
import com.gtnewhorizons.angelica.api.TintRegistry;
@@ -30,7 +28,6 @@ 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.model.quad.properties.ModelQuadFlags;
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;
@@ -46,9 +43,6 @@ import java.util.List;
public class AngelicaChunkBuildContext extends ChunkBuildContext {
public static final int NUM_PASSES = 2;
// Yoinked from Celeritas
private static final int[] REVERSED_QUAD_ORDER = { 0, 3, 2, 1 };
private final TextureMapExtension textureAtlas;
private final ChunkVertexEncoder.Vertex[] vertices = ChunkVertexEncoder.Vertex.uninitializedQuad();
@Getter
@@ -68,8 +62,6 @@ public class AngelicaChunkBuildContext extends ChunkBuildContext {
private boolean lightPipelineReady = false;
private int originX, originY, originZ;
private float cachedSkylightSubtracted;
private final float[] fluidQuadPos = new float[12];
private ModelQuadFacing fluidQuadLightFace;
public AngelicaChunkBuildContext(RenderPassConfiguration<?> renderPassConfiguration, WorldClient world) {
super(renderPassConfiguration);
@@ -168,7 +160,6 @@ public class AngelicaChunkBuildContext extends ChunkBuildContext {
boolean hasCachedMaterial = false;
TextureAtlasSprite lastSprite = null;
Material lastMaterial = null;
this.fluidQuadLightFace = null;
for (int quadIdx = 0; quadIdx < numQuads; quadIdx++) {
float uSum = 0, vSum = 0;
@@ -210,8 +201,11 @@ public class AngelicaChunkBuildContext extends ChunkBuildContext {
// Otherwise, we need to use the block's lightmap values as they are as the ISBRH may have
// specified its own lightmaps for visual purposes (e.g. fullbright)
if (useAoCalculation && (quadState & StateAwareTessellator.RENDERED_WITH_VANILLA_AO) != 0) {
calculateQuadLight(trueNormal, blockX, blockY, blockZ, worldX, worldY, worldZ, isFluid,
blockAllowsSmoothLighting, shouldApplyDiffuse && (quadState & NO_DIRECTIONAL_SHADING) == 0);
quadView.setup(trueNormal, blockX, blockY, blockZ);
final ModelQuadFacing lightFace = quadView.getLightFace();
final LightPipeline pipeline = blockAllowsSmoothLighting ? smoothLightPipeline : flatLightPipeline;
final ModelQuadFacing cullFace = quadView.getCullFace();
pipeline.calculate(quadView, worldX, worldY, worldZ, quadLightData, cullFace, lightFace, shouldApplyDiffuse, true);
for (int vIdx = 0; vIdx < 4; vIdx++) {
final var vertex = vertices[vIdx];
@@ -233,8 +227,11 @@ public class AngelicaChunkBuildContext extends ChunkBuildContext {
}
if (useAoCalculation && isFluid) {
calculateQuadLight(trueNormal, blockX, blockY, blockZ, worldX, worldY, worldZ, true,
blockAllowsSmoothLighting, shouldApplyDiffuse);
quadView.setup(trueNormal, blockX, blockY, blockZ);
final ModelQuadFacing lightFace = quadView.getLightFace();
final LightPipeline pipeline = blockAllowsSmoothLighting ? smoothLightPipeline : flatLightPipeline;
final ModelQuadFacing cullFace = quadView.getCullFace();
pipeline.calculate(quadView, worldX, worldY, worldZ, quadLightData, cullFace, lightFace, shouldApplyDiffuse, true);
for (int vIdx = 0; vIdx < 4; vIdx++) {
vertices[vIdx].light = quadLightData.lm[vIdx];
}
@@ -277,42 +274,6 @@ public class AngelicaChunkBuildContext extends ChunkBuildContext {
}
}
private void calculateQuadLight(int trueNormal, int blockX, int blockY, int blockZ, int worldX, int worldY,
int worldZ, boolean isFluid, boolean blockAllowsSmoothLighting,
boolean shouldApplyDiffuse) {
final boolean isFlippedFluidCopy = isFluid && fluidQuadLightFace != null && isReversedFluidQuad();
quadView.setup(trueNormal, blockX, blockY, blockZ, isFluid ? ModelQuadFlags.IS_VANILLA_SHADED : 0,
isFlippedFluidCopy ? fluidQuadLightFace : null);
final LightPipeline pipeline = blockAllowsSmoothLighting ? smoothLightPipeline : flatLightPipeline;
pipeline.calculate(quadView, worldX, worldY, worldZ, quadLightData, quadView.getCullFace(),
quadView.getLightFace(), shouldApplyDiffuse, true);
if (isFluid && !isFlippedFluidCopy) {
fluidQuadLightFace = quadView.getLightFace();
for (int vIdx = 0; vIdx < 4; vIdx++) {
final var vertex = vertices[vIdx];
fluidQuadPos[vIdx * 3] = vertex.x;
fluidQuadPos[vIdx * 3 + 1] = vertex.y;
fluidQuadPos[vIdx * 3 + 2] = vertex.z;
}
} else if (!isFluid) {
fluidQuadLightFace = null;
}
}
private boolean isReversedFluidQuad() {
for (int vIdx = 0; vIdx < 4; vIdx++) {
final int src = REVERSED_QUAD_ORDER[vIdx] * 3;
final var vertex = vertices[vIdx];
if (vertex.x != fluidQuadPos[src] || vertex.y != fluidQuadPos[src + 1] || vertex.z != fluidQuadPos[src + 2]) {
return false;
}
}
return true;
}
private void applyBlockLightTint(int x, int y, int z, ChunkVertexEncoder.Vertex[] vertices) {
if (!hasColoredLight) return;
final ExtQuadLightData ext = (ExtQuadLightData) quadLightData;
@@ -4,15 +4,11 @@ import com.gtnewhorizon.gtnhlib.blockpos.BlockPos;
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
import com.gtnewhorizons.angelica.rendering.AngelicaRenderQueue;
import com.gtnewhorizons.angelica.rendering.StateAwareTessellator;
import com.gtnewhorizons.angelica.mixins.interfaces.OverridesGetDistanceFrom;
import com.gtnewhorizons.angelica.rendering.TileEntityRenderBoundsRegistry;
import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProvider;
import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProviderHolder;
import com.gtnewhorizons.angelica.rendering.celeritas.iris.BlockRenderContext;
import com.gtnewhorizons.angelica.rendering.celeritas.iris.ContextAwareChunkVertexEncoder;
import com.gtnewhorizons.angelica.rendering.celeritas.world.WorldSlice;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.utils.NaturalTextureUtils;
import com.prupe.mcpatcher.mal.block.RenderBlocksUtils;
import it.unimi.dsi.fastutil.floats.FloatArrayList;
import it.unimi.dsi.fastutil.objects.Reference2ReferenceMap;
@@ -115,8 +111,6 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask<C
final BlockPos blockPos = new BlockPos(minX, minY, minZ);
final IBlockAccess region = getBlockAccess();
final WorldSlice reportingSlice = region instanceof WorldSlice slice ? slice : null;
if (reportingSlice != null) reportingSlice.setRenderingBlock(null);
final SmoothBiomeColorCache biomeColorCache = getBiomeColorCache();
onEnterExecute();
@@ -161,8 +155,6 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask<C
continue;
}
if (reportingSlice != null) reportingSlice.setRenderingBlock(block);
final int meta = region.getBlockMetadata(x, y, z);
if (block.hasTileEntity(meta)) {
@@ -193,7 +185,7 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask<C
renderData.culledBlockEntities.add(tileEntity);
AngelicaBuiltRenderSectionData.packSectionLocalBounds(culledBounds, aabb, minX, minY, minZ);
double teDistSq;
if (tileEntity instanceof OverridesGetDistanceFrom) {
if (TileEntityRenderBoundsRegistry.overridesGetDistanceFrom(tileEntity.getClass())) {
teDistSq = Double.POSITIVE_INFINITY;
} else {
try {
@@ -363,16 +355,8 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask<C
setRenderPass(pass);
// Trigger side effects from canRenderInPass (some ISBRHs like BuildCraft set global state in this method that gets read elsewhere renderWorldBlock)
block.canRenderInPass(pass);
// Some blocks get randomly rotated top faces
final boolean applyNaturalTex = AngelicaConfig.enableNaturalTextures && NaturalTextureUtils.isNaturalBlock(block);
if (applyNaturalTex) { renderBlocks.uvRotateTop = NaturalTextureUtils.getTopRotation(x, y, z); }
tessellator.startDrawingQuads();
renderBlocks.renderBlockByRenderType(block, x, y, z);
if (applyNaturalTex) { renderBlocks.uvRotateTop = 0; } // Reset
boolean blockAllowsSmoothLighting = Minecraft.isAmbientOcclusionEnabled() // smooth lighting on
&& block.getLightValue() == 0; // does not emit real block light
buildContext.copyRawBuffer(tessellator.rawBuffer, tessellator.vertexCount,
@@ -6,8 +6,6 @@ import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import com.gtnewhorizons.angelica.compat.bop.BopFogBlend;
import com.gtnewhorizons.angelica.compat.bop.FogBiomeCache;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher;
@@ -47,7 +45,6 @@ import com.gtnewhorizons.angelica.dynamiclights.IDynamicLightWorldRenderer;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
import com.gtnewhorizons.angelica.mixins.interfaces.ITileEntityBoundingBoxCache;
import com.gtnewhorizons.angelica.mixins.interfaces.OverridesShouldRenderInPass;
import com.gtnewhorizons.angelica.profiling.RenderClassTimings;
import com.gtnewhorizons.angelica.proxy.ClientProxy;
import com.gtnewhorizons.angelica.rendering.RenderingState;
@@ -168,8 +165,6 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
TesrBatchRenderer.INSTANCE.clearRetained();
ModelPartBatcher.INSTANCE.clear();
GpuCulling.onWorldUnload();
BopFogBlend.invalidate();
FogBiomeCache.invalidate();
super.unloadWorld();
}
@@ -410,7 +405,7 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
try {
for (int i = 0; i < frameTEs.size(); i++) {
final TileEntity te = frameTEs.get(i);
if (!(te instanceof OverridesShouldRenderInPass)) {
if (((ITileEntityBoundingBoxCache) te).angelica$passClass() == TileEntityRenderBoundsRegistry.PASS0_ONLY) {
dispatchTE(te, partialTicks);
count++;
continue;
@@ -13,24 +13,18 @@ public class VertexArrayQuadView implements ModelQuadView {
private int blockX, blockY, blockZ;
private ModelQuadFacing lightFace;
private int flags;
private int extraFlags;
public VertexArrayQuadView(ChunkVertexEncoder.Vertex[] vertices) {
this.vertices = vertices;
}
public void setup(int trueNormal, int blockX, int blockY, int blockZ) {
setup(trueNormal, blockX, blockY, blockZ, 0, null);
}
public void setup(int trueNormal, int blockX, int blockY, int blockZ, int extraFlags, ModelQuadFacing forcedLightFace) {
this.trueNormal = trueNormal;
this.blockX = blockX;
this.blockY = blockY;
this.blockZ = blockZ;
this.lightFace = forcedLightFace;
this.lightFace = null; // Reset cached lightFace
this.flags = 0;
this.extraFlags = extraFlags;
}
@Override
@@ -71,7 +65,7 @@ public class VertexArrayQuadView implements ModelQuadView {
@Override
public int getFlags() {
if (flags == 0) {
flags = ModelQuadFlags.getQuadFlags(this, getLightFace(), extraFlags);
flags = ModelQuadFlags.getQuadFlags(this, getLightFace());
}
return flags;
}
@@ -1,6 +1,5 @@
package com.gtnewhorizons.angelica.rendering.celeritas.light;
import com.gtnewhorizons.angelica.rendering.celeritas.world.WorldSlice;
import lombok.Setter;
import net.minecraft.block.Block;
import net.minecraft.world.IBlockAccess;
@@ -10,16 +9,6 @@ import org.embeddedt.embeddium.impl.model.light.data.LightDataAccess;
public class LightDataCache extends LightDataAccess {
private IBlockAccess world;
/**
* Doing this to force packs like Steadfast's water to work properly.
*/
private static int skyLight(IBlockAccess world, Block block, int x, int y, int z, int neighborMaxed) {
if (world instanceof WorldSlice slice && block.getMaterial().isLiquid()) {
return slice.getRawSkyLight(x, y, z);
}
return neighborMaxed;
}
@Override
protected int compute(int x, int y, int z) {
final IBlockAccess world = this.world;
@@ -37,7 +26,7 @@ public class LightDataCache extends LightDataAccess {
} else {
final int packed = world.getLightBrightnessForSkyBlocks(x, y, z, 0);
bl = (packed >> 4) & 0xF;
sl = skyLight(world, block, x, y, z, (packed >> 20) & 0xF);
sl = (packed >> 20) & 0xF;
}
// AO value - blocks that emit light don't contribute to AO
Loaded 100 of 198 files, more files were not shown because too many files have changed in this diff. Show more