Compare commits

..
Author SHA1 Message Date
Alexdoru 8e26a0179b Speedup block transformer by transforming every class directly (#1420)
* speedup block transformer by transforming every class directly

* stop using the cstpoolparser.add method
2026-02-24 15:45:35 +01:00
Alexdoru 1d96af8e3a re-enable Block Transformer when not running with rfb (#1418) 2026-02-23 14:58:40 -08:00
Yan Huang f7eb86cdb6 Parallelizing CTMUtils (#1393) 2026-02-23 20:21:35 +00:00
Alexdoru b38fafa831 ASM redirectors micro optimizations (#1416)
* redirector transformer micro optimizations

* use map for block fields redirect
2026-02-23 20:20:38 +01:00
Jason Mitchell 7dc2625f8c Maybe less leaky (#1414) 2026-02-23 08:57:21 -08:00
Jason Mitchell 3d97977050 Maybe fix holo inventory again - v2 - final.xlsx (#1413) 2026-02-22 20:37:08 -08:00
Eclipse-Sol 5f41c60bc2 Remove force blend as commit 0325a96b fixed this properly. (#1409) 2026-02-22 11:35:35 -08:00
Jason Mitchell 0325a96bc2 Add unknown blend state and BufferBlendOverride handling from modern Iris (#1408) 2026-02-21 15:27:22 -08:00
Caedis ad123d0bd5 Now with 200% more screen shake (#1402) 2026-02-18 09:20:47 -05:00
Caedis 4b89997985 Add slider for hurt screen shake intensity (#1401) 2026-02-18 04:23:57 +01:00
Death Fuel f5c9fa3301 slightly less stupid glyph size loading (#1390) 2026-02-15 18:49:44 -08:00
Death Fuel d6a6d3b525 Less logging + small refactor (#1379)
* less logging

* refactor

* missed a spot

* consistency
2026-02-15 18:48:51 -08:00
Ruling-0 f079bed977 TESRs Translucency Sorting (#1384)
* Iterate blocks in region towards the camera

* Sort translucent TESRs when translucency sorting is enabled
2026-02-15 18:48:05 -08:00
Caedis c9ec40e94b use mc.renderViewEntity instead of mc.thePlayer in shader shadow rendering (#1392) 2026-02-15 18:47:19 -08:00
embeddedt 8380f3853d Detect quads rendered by vanilla AO pipeline and only recalculate lighting for those (#1391)
* Detect quads rendered by vanilla AO pipeline and only recalculate lighting for those

* Handle oldLighting correctly
2026-02-15 18:46:58 -08:00
Yan Huang 534ae6b05c Remove support for NotEnoughIds-Legacy and update BetterCrashes dependency version, as the old files have been removed from the GTNH source. (#1388) 2026-02-15 09:35:09 -08:00
Jason Mitchell 68d523d3df Sign Culling (#1386) 2026-02-14 04:09:00 -08:00
Jason Mitchell 2f22a7b3ad Swap vanilla clipping helper with joml (#1385) 2026-02-13 14:29:31 -08:00
Jason Mitchell 7b79b90dd6 Fix crash without speedupAnimations enabled (#1377) 2026-02-09 12:00:36 -08:00
45 changed files with 964 additions and 398 deletions

No files matched your search

+2 -3
View File
@@ -108,8 +108,7 @@ dependencies {
compileOnly("curse.maven:minefactory-reloaded-66672:2277486")
compileOnly("com.github.GTNewHorizons:NotEnoughIds:2.1.10:dev") // Mixin Version
compileOnly("com.github.GTNewHorizons:NotEnoughIds-Legacy:1.4.7:dev") // ASM Version
compileOnly("com.github.GTNewHorizons:NotEnoughIds:2.1.10:dev")
compileOnly(rfg.deobf("maven.modrinth:ntmspace:X5593_H261"))
@@ -126,7 +125,7 @@ dependencies {
transformedMod("net.industrial-craft:industrialcraft-2:2.2.828-experimental:dev")
// Better Crashes
compileOnly("com.github.GTNewHorizons:BetterCrashes:1.4.0-GTNH:dev")
compileOnly("com.github.GTNewHorizons:BetterCrashes:1.4.1-GTNH:dev")
afterEvaluate {
dependencies {
@@ -75,11 +75,9 @@ public class BatchingFontRenderer {
}
}
public BatchingFontRenderer(FontRenderer underlying, int[] charWidth, byte[] glyphWidth,
int[] colorCode, ResourceLocation locationFontTexture) {
public BatchingFontRenderer(FontRenderer underlying, int[] charWidth, int[] colorCode, ResourceLocation locationFontTexture) {
this.underlying = underlying;
this.charWidth = charWidth;
this.glyphWidth = glyphWidth;
this.colorCode = colorCode;
this.locationFontTexture = locationFontTexture;
@@ -92,7 +90,6 @@ public class BatchingFontRenderer {
FontProviderMC.get(this.isSGA).charWidth = this.charWidth;
FontProviderMC.get(this.isSGA).locationFontTexture = this.locationFontTexture;
FontProviderUnicode.get().glyphWidth = this.glyphWidth;
//noinspection deprecation
fontShaderId = FontAAShader.getProgram().getProgramId();
@@ -1,6 +1,5 @@
package com.gtnewhorizons.angelica.client.font;
import com.gtnewhorizon.gtnhlib.config.ConfigurationManager;
import com.gtnewhorizons.angelica.config.FontConfig;
import lombok.Setter;
import lombok.Value;
@@ -46,7 +45,7 @@ public final class FontProviderCustom implements FontProvider {
default -> null;
};
if (Objects.equals(myFontName, "(none)")) {
font = null;
this.font = null;
return;
}
int fontPos = -1;
@@ -58,10 +57,10 @@ public final class FontProviderCustom implements FontProvider {
}
if (fontPos == -1) {
LOGGER.info("Could not find previously set font \"{}\". ", myFontName);
font = null;
this.font = null;
return;
}
font = availableFonts[fontPos].deriveFont(currentFontQuality);
this.font = availableFonts[fontPos].deriveFont(this.currentFontQuality);
}
private static class InstLoader {
static final FontProviderCustom instance0 = new FontProviderCustom((byte)0);
@@ -71,8 +70,8 @@ public final class FontProviderCustom implements FontProvider {
public static FontProviderCustom getFallback() { return InstLoader.instance1; }
public void reloadFont(int fontID) {
currentFontQuality = FontConfig.customFontQuality;
font = FontStrategist.getAvailableFonts()[fontID].deriveFont(currentFontQuality);
this.currentFontQuality = FontConfig.customFontQuality;
this.font = FontStrategist.getAvailableFonts()[fontID].deriveFont(this.currentFontQuality);
File[] files = new File(getFontDir()).listFiles();
if (files != null) {
@@ -94,7 +93,7 @@ public final class FontProviderCustom implements FontProvider {
}
}
fontAtlases = new FontAtlas[ATLAS_COUNT];
this.fontAtlases = new FontAtlas[ATLAS_COUNT];
}
private String getFontDir() {
@@ -134,50 +133,44 @@ public final class FontProviderCustom implements FontProvider {
}
void construct(Font font) {
float separator = currentFontQuality / 3f;
int atlasChars = 0;
for (int i = 0; i < ATLAS_SIZE; i++) {
final char ch = (char) (i + ATLAS_SIZE * this.id);
if (font.canDisplay(ch)) { atlasChars++; }
}
if (atlasChars == 0) { return; }
BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = image.createGraphics();
g2d.setFont(font);
FontMetrics fm = g2d.getFontMetrics();
g2d.dispose();
int width = 0;
int actualChars = 0;
for (int i = 0; i < ATLAS_SIZE; i++) {
final char ch = (char)(i + ATLAS_SIZE * this.id);
if (font.canDisplay(ch)) {
width += (int) (separator + fm.charWidth(ch));
actualChars++;
}
}
if (actualChars == 0) {
return;
}
final int atlasTilesX = (int) Math.ceil(Math.sqrt(actualChars) * 1.5f);
final int atlasTilesY = (int) Math.ceil((double) actualChars / atlasTilesX);
LOGGER.info("constructing custom font atlas (ID {}) of nominal size {} chars, actual: {}, {} rows by {} columns",
this.id, ATLAS_SIZE, actualChars, atlasTilesX, atlasTilesY);
width = 0;
actualChars = 0;
final int atlasTilesX = (int) Math.ceil(Math.sqrt(atlasChars) * 1.5f);
final int atlasTilesY = (int) Math.ceil((double) atlasChars / atlasTilesX);
final float charSeparator = currentFontQuality / 3f;
int rowWidth = 0;
int maxRowWidth = 0;
atlasChars = 0;
for (int i = 0; i < ATLAS_SIZE; i++) {
if (actualChars % atlasTilesX == 0) {
maxRowWidth = Math.max(maxRowWidth, width);
width = 0;
if (atlasChars % atlasTilesX == 0) {
maxRowWidth = Math.max(maxRowWidth, rowWidth);
rowWidth = 0;
}
final char ch = (char)(i + ATLAS_SIZE * this.id);
if (font.canDisplay(ch)) {
width += (int) (separator + fm.charWidth(ch));
actualChars++;
rowWidth += (int) (charSeparator + fm.charWidth(ch));
atlasChars++;
}
}
maxRowWidth = Math.max(maxRowWidth, width);
maxRowWidth = Math.max(maxRowWidth, rowWidth);
final int lineHeight = fm.getHeight();
final float desc = fm.getDescent();
final int imageWidth = (int) (maxRowWidth + separator);
final int imageHeight = (int) ((separator + lineHeight) * atlasTilesY + separator);
final int imageWidth = (int) (maxRowWidth + charSeparator);
final int imageHeight = (int) ((charSeparator + lineHeight) * atlasTilesY + charSeparator);
image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB);
g2d = image.createGraphics();
@@ -192,35 +185,34 @@ public final class FontProviderCustom implements FontProvider {
fm = g2d.getFontMetrics();
int tileX = 0, tileY = 0; // position in atlas tiles
int imgX = (int) separator; // position in pixels
int imgX = (int) charSeparator; // position in pixels
for (int i = 0; i < ATLAS_SIZE; i++) {
final char ch = (char)(i + ATLAS_SIZE * this.id);
final char ch = (char) (i + ATLAS_SIZE * this.id);
if (!font.canDisplay(ch)) { continue; }
if (tileX >= atlasTilesX) {
tileX = 0;
imgX = (int) separator;
imgX = (int) charSeparator;
tileY++;
}
final int charWidth = fm.charWidth(ch);
final float charAspectRatio = (float) charWidth / lineHeight;
final float inset = currentFontQuality / 16;
g2d.drawString(Character.toString(ch), imgX, (lineHeight + separator) * (tileY + 1) - desc);
g2d.drawString(Character.toString(ch), imgX, (lineHeight + charSeparator) * (tileY + 1) - desc);
final float uStart = (float) (imgX - inset * charAspectRatio) / imageWidth;
final float vStart = ((lineHeight + separator) * (tileY + 1) - lineHeight - inset) / imageHeight;
final float vStart = ((lineHeight + charSeparator) * (tileY + 1) - lineHeight - inset) / imageHeight;
final float xAdvance = charAspectRatio * 8 * charWidth / (charWidth + 2 * inset * charAspectRatio);
final float glyphW = charAspectRatio * 8 + 1;
final float uSz = (float) (charWidth + 2 * inset * charAspectRatio) / imageWidth;
final float vSz = (float) (lineHeight + 2 * inset) / imageHeight;
glyphData[i] = new GlyphData(uStart, vStart, xAdvance, glyphW, uSz, vSz);
imgX += (int) (charWidth + separator);
this.glyphData[i] = new GlyphData(uStart, vStart, xAdvance, glyphW, uSz, vSz);
imgX += (int) (charWidth + charSeparator);
tileX++;
}
g2d.dispose();
try {
LOGGER.info("writing custom font atlas texture ({}x{} px) to {}", imageWidth, imageHeight, getAtlasFullPath(this.id));
Files.createDirectories(Paths.get(getFontDir()));
ImageIO.write(image, "png", new File(getAtlasFullPath(this.id)));
} catch (IOException e) {
@@ -232,18 +224,18 @@ public final class FontProviderCustom implements FontProvider {
private FontAtlas getAtlas(char chr) {
int id = chr / ATLAS_SIZE;
FontAtlas fa = fontAtlases[id];
FontAtlas fa = this.fontAtlases[id];
if (fa == null) {
fa = new FontAtlas(id);
fa.construct(font);
fa.construct(this.font);
this.fontAtlases[id] = fa;
}
fontAtlases[id] = fa;
return fa;
}
@Override
public boolean isGlyphAvailable(char chr) {
if (font == null) { return false; }
if (this.font == null) { return false; }
return (getAtlas(chr).glyphData[chr % ATLAS_SIZE] != null);
}
@@ -1,16 +1,31 @@
package com.gtnewhorizons.angelica.client.font;
import com.gtnewhorizons.angelica.config.FontConfig;
import net.minecraft.client.Minecraft;
import net.minecraft.util.ResourceLocation;
import java.io.IOException;
import java.io.InputStream;
public final class FontProviderUnicode implements FontProvider {
private FontProviderUnicode() {}
private FontProviderUnicode() {
try {
InputStream inputstream = Minecraft.getMinecraft().getResourceManager()
.getResource(new ResourceLocation("font/glyph_sizes.bin")).getInputStream();
//noinspection ResultOfMethodCallIgnored
inputstream.read(this.glyphWidth);
}
catch (IOException ioexception) {
throw new RuntimeException(ioexception);
}
}
private static class InstLoader { static final FontProviderUnicode instance = new FontProviderUnicode(); }
public static FontProviderUnicode get() { return FontProviderUnicode.InstLoader.instance; }
private static final ResourceLocation[] unicodePageLocations = new ResourceLocation[256];
public byte[] glyphWidth;
private final byte[] glyphWidth = new byte[65536];
private ResourceLocation getUnicodePageLocation(int page) {
final ResourceLocation lookup = unicodePageLocations[page];
@@ -6,7 +6,6 @@ import com.gtnewhorizons.neid.mixins.interfaces.IExtendedBlockStorageMixin;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.NibbleArray;
import net.minecraft.world.chunk.storage.ExtendedBlockStorage;
import ru.fewizz.idextender.Hooks;
public class ExtendedBlockStorageExt extends ExtendedBlockStorage {
public boolean hasSky;
@@ -39,12 +38,6 @@ public class ExtendedBlockStorageExt extends ExtendedBlockStorage {
System.arraycopy(((IExtendedBlockStorageMixin)(Object)storage).getBlock16BMetaArray(), 0, block16BMetaArray, 0, block16BMetaArray.length);
}
}
else if (ModStatus.isOldNEIDLoaded){
final short[] blockLSBArray = Hooks.get(this);
System.arraycopy(Hooks.get(storage), 0, blockLSBArray, 0, blockLSBArray.length);
// getBlockMSBArray is nuked in asm version
arrayLen = blockLSBArray.length;
}
else {
final byte[] blockLSBArray = this.getBlockLSBArray();
System.arraycopy(storage.getBlockLSBArray(), 0, blockLSBArray, 0, blockLSBArray.length);
@@ -12,15 +12,8 @@ public class ModStatus {
public static final Logger LOGGER = LogManager.getLogger("ModCompat");
public static BackhandReflectionCompat backhandCompat;
/**
* Mixin Version
*/
public static boolean isNEIDLoaded;
/**
* ASM Version
*/
public static boolean isOldNEIDLoaded;
public static boolean isBetterCrashesLoaded;
public static boolean isNEIDLoaded;
public static boolean isNEIDMetadataExtended;
public static boolean isLotrLoaded;
public static boolean isChunkAPILoaded;
@@ -42,7 +35,6 @@ public class ModStatus {
isBetterCrashesLoaded = Loader.isModLoaded("bettercrashes");
isNEIDLoaded = Loader.isModLoaded("neid");
isOldNEIDLoaded = Loader.isModLoaded("notenoughIDs");
isLotrLoaded = Loader.isModLoaded("lotr");
isChunkAPILoaded = Loader.isModLoaded("chunkapi");
isEIDBiomeLoaded = Loader.isModLoaded("endlessids_biome");
@@ -1788,6 +1788,7 @@ public class GLStateManager {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glDrawElements in display lists not yet implemented - if you see this, please report!");
}
BlendModeStorage.flushDeferredBlend();
GL11.glDrawElements(mode, indices);
}
@@ -1795,6 +1796,7 @@ public class GLStateManager {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glDrawElements in display lists not yet implemented - if you see this, please report!");
}
BlendModeStorage.flushDeferredBlend();
GL11.glDrawElements(mode, indices);
}
@@ -1802,6 +1804,7 @@ public class GLStateManager {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glDrawElements in display lists not yet implemented - if you see this, please report!");
}
BlendModeStorage.flushDeferredBlend();
GL11.glDrawElements(mode, indices);
}
@@ -1809,6 +1812,7 @@ public class GLStateManager {
if (DisplayListManager.isRecording()) {
throw new UnsupportedOperationException("glDrawElements in display lists not yet implemented - if you see this, please report!");
}
BlendModeStorage.flushDeferredBlend();
GL11.glDrawElements(mode, count, type, indices);
}
@@ -1824,6 +1828,7 @@ public class GLStateManager {
return;
}
}
BlendModeStorage.flushDeferredBlend();
GL11.glDrawElements(mode, indices_count, type, indices_buffer_offset);
}
@@ -1850,6 +1855,7 @@ public class GLStateManager {
}
return;
}
BlendModeStorage.flushDeferredBlend();
GL11.glDrawArrays(mode, first, count);
}
@@ -347,10 +347,12 @@ public class RenderSystem {
public static void disableBufferBlend(int buffer) {
GL30.glDisablei(GL11.GL_BLEND, buffer);
GLStateManager.getBlendMode().setUnknownState();
}
public static void enableBufferBlend(int buffer) {
GL30.glEnablei(GL11.GL_BLEND, buffer);
GLStateManager.getBlendMode().setUnknownState();
}
public static void blendFuncSeparatei(int buffer, int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) {
@@ -8,11 +8,16 @@ public class BooleanState implements ISettableState<BooleanState> {
protected final int glCap;
@Getter protected boolean enabled;
protected boolean stateUnknown;
public BooleanState(int glCap) {
this.glCap = glCap;
}
public void setUnknownState() {
stateUnknown = true;
}
public void disable() {
this.setEnabled(false);
}
@@ -23,7 +28,8 @@ public class BooleanState implements ISettableState<BooleanState> {
public void setEnabled(boolean enabled) {
final boolean bypass = GLStateManager.shouldBypassCache();
if (bypass || enabled != this.enabled || (this.glCap == GL11.GL_BLEND && GLStateManager.vendorIsAMD() && GLStateManager.isPoppingAttributes())) {
if (stateUnknown || bypass || enabled != this.enabled || (this.glCap == GL11.GL_BLEND && GLStateManager.vendorIsAMD() && GLStateManager.isPoppingAttributes())) {
stateUnknown = false;
if (!bypass) {
this.enabled = enabled;
}
@@ -142,6 +142,9 @@ public class AngelicaTweaker implements IFMLLoadingPlugin, IEarlyMixinLoader {
boolean rfbLoaded = Launch.blackboard.getOrDefault("angelica.rfbPluginLoaded", Boolean.FALSE) == Boolean.TRUE;
if (!rfbLoaded) {
tweaks.add("com.gtnewhorizons.angelica.loading.fml.tweakers.AngelicaLateTweaker");
if (AngelicaConfig.enableCeleritas) {
tweaks.add("com.gtnewhorizons.angelica.loading.fml.tweakers.CeleritasLateTweaker");
}
}
}
}
@@ -2,26 +2,25 @@ package com.gtnewhorizons.angelica.loading.fml.transformers;
import com.gtnewhorizons.angelica.loading.AngelicaTweaker;
import com.gtnewhorizons.angelica.loading.shared.AngelicaClassDump;
import com.gtnewhorizons.angelica.loading.shared.transformers.AngelicaRedirector;
import com.gtnewhorizons.angelica.loading.shared.transformers.SodiumBlockTransform;
import com.gtnewhorizons.angelica.loading.shared.transformers.CeleritasBlockTransform;
import net.minecraft.launchwrapper.IClassTransformer;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.tree.ClassNode;
public class SodiumBlockTransformer implements IClassTransformer {
public class CeleritasBlockTransformer implements IClassTransformer {
private final SodiumBlockTransform inner;
private final CeleritasBlockTransform inner;
private final String[] exclusions;
public SodiumBlockTransformer() {
this.inner = new SodiumBlockTransform(AngelicaTweaker.isObfEnv());
public CeleritasBlockTransformer() {
this.inner = new CeleritasBlockTransform(AngelicaTweaker.isObfEnv());
this.exclusions = inner.getTransformerExclusions();
this.inner.setCeleritasSetting();
}
/**
* Delete the global vanilla bounding box fields off the Block object. {@link AngelicaRedirector}
* Delete the global vanilla bounding box fields off the Block object. {@link CeleritasBlockTransform}
* replaces these with a thread-safe alternative.
*/
@Override
@@ -31,10 +30,6 @@ public class SodiumBlockTransformer implements IClassTransformer {
if (transformedName.startsWith(exclusion)) return basicClass;
}
if (!inner.shouldTransform(basicClass)) {
return basicClass;
}
final ClassReader cr = new ClassReader(basicClass);
final ClassNode cn = new ClassNode();
cr.accept(cn, 0);
@@ -0,0 +1,35 @@
package com.gtnewhorizons.angelica.loading.fml.tweakers;
import cpw.mods.fml.relauncher.FMLRelaunchLog;
import net.minecraft.launchwrapper.ITweaker;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.launchwrapper.LaunchClassLoader;
import java.io.File;
import java.util.List;
public class CeleritasLateTweaker implements ITweaker {
@Override
public void acceptOptions(List<String> args, File gameDir, File assetsDir, String profile) {
// no-op
}
@Override
public void injectIntoClassLoader(LaunchClassLoader classLoader) {
// no-op
}
@Override
public String getLaunchTarget() {
return null;
}
@Override
public String[] getLaunchArguments() {
String transformer = "com.gtnewhorizons.angelica.loading.fml.transformers.CeleritasBlockTransformer";
FMLRelaunchLog.finer("Registering transformer %s", transformer);
Launch.classLoader.registerTransformer(transformer);
return new String[0];
}
}
@@ -1,7 +1,7 @@
package com.gtnewhorizons.angelica.loading.rfb;
import com.gtnewhorizons.angelica.loading.rfb.transformers.RFBAngelicaRedirector;
import com.gtnewhorizons.angelica.loading.rfb.transformers.RFBSodiumBlockTransformer;
import com.gtnewhorizons.angelica.loading.rfb.transformers.RFBCeleritasBlockTransformer;
import com.gtnewhorizons.retrofuturabootstrap.api.PluginContext;
import com.gtnewhorizons.retrofuturabootstrap.api.RetroFuturaBootstrap;
import com.gtnewhorizons.retrofuturabootstrap.api.RfbClassTransformer;
@@ -27,7 +27,7 @@ public class AngelicaRfbPlugin implements RfbPlugin {
final boolean isObf = RetroFuturaBootstrap.API.launchClassLoader().findClassMetadata("net.minecraft.world.World") == null;
return new RfbClassTransformer[] {
new RFBAngelicaRedirector(),
new RFBSodiumBlockTransformer(isObf)
new RFBCeleritasBlockTransformer(isObf)
};
}
}
@@ -1,7 +1,7 @@
package com.gtnewhorizons.angelica.loading.rfb.transformers;
import com.gtnewhorizons.angelica.loading.shared.AngelicaClassDump;
import com.gtnewhorizons.angelica.loading.shared.transformers.SodiumBlockTransform;
import com.gtnewhorizons.angelica.loading.shared.transformers.CeleritasBlockTransform;
import com.gtnewhorizons.retrofuturabootstrap.api.ClassNodeHandle;
import com.gtnewhorizons.retrofuturabootstrap.api.ExtensibleClassLoader;
import com.gtnewhorizons.retrofuturabootstrap.api.RfbClassTransformer;
@@ -11,12 +11,12 @@ import org.jetbrains.annotations.Nullable;
import java.util.jar.Manifest;
public class RFBSodiumBlockTransformer implements RfbClassTransformer {
public class RFBCeleritasBlockTransformer implements RfbClassTransformer {
private final SodiumBlockTransform inner;
private final CeleritasBlockTransform inner;
public RFBSodiumBlockTransformer(boolean isObf) {
inner = new SodiumBlockTransform(isObf);
public RFBCeleritasBlockTransformer(boolean isObf) {
inner = new CeleritasBlockTransform(isObf);
}
@Pattern("[a-z0-9-]+")
@@ -44,14 +44,7 @@ public class RFBSodiumBlockTransformer implements RfbClassTransformer {
public boolean shouldTransformClass(@NotNull ExtensibleClassLoader classLoader,
@NotNull RfbClassTransformer.Context context, @Nullable Manifest manifest, @NotNull String className,
@NotNull ClassNodeHandle classNode) {
if (!classNode.isPresent()) {
return false;
}
if (!classNode.isOriginal()) {
// If a class is already a transformed ClassNode, conservatively continue processing.
return true;
}
return inner.shouldTransform(classNode.getOriginalBytes());
return classNode.isPresent();
}
@Override
@@ -1,31 +1,23 @@
package com.gtnewhorizons.angelica.loading.shared.transformers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.gtnewhorizon.gtnhlib.asm.ClassConstantPoolParser;
import net.minecraft.launchwrapper.Launch;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.IntInsnNode;
import org.objectweb.asm.tree.LdcInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.util.Collections;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* This transformer redirects many GL calls to our custom GLStateManager
@@ -73,10 +65,10 @@ public final class AngelicaRedirector {
"initializeTextures", "func_77474_a"
);
private static final ClassConstantPoolParser cstPoolParser = new ClassConstantPoolParser(GL11, GL12, GL13, GL14, GL20, OpenGlHelper, EXTBlendFunc, ARBMultiTexture, Project);
private static final Map<String, Map<String, String>> methodRedirects = new HashMap<>();
private static final Map<String, Map<String, String>> interfaceRedirects = new HashMap<>();
private static final Map<Integer, String> glCapRedirects = new HashMap<>();
private static final ClassConstantPoolParser cstPoolParser;
static {
glCapRedirects.put(org.lwjgl.opengl.GL11.GL_ALPHA_TEST, "AlphaTest");
@@ -302,17 +294,27 @@ public final class AngelicaRedirector {
.add("glBindVertexArray")
);
cstPoolParser.addString(UniversalVAO);
cstPoolParser.addString(VaoFunctions);
cstPoolParser.addString(LWJGLService);
final List<String> stringsToSearch = new ArrayList<>();
stringsToSearch.add(GL11);
stringsToSearch.add(GL12);
stringsToSearch.add(GL13);
stringsToSearch.add(GL14);
stringsToSearch.add(GL20);
stringsToSearch.add(OpenGlHelper);
stringsToSearch.add(EXTBlendFunc);
stringsToSearch.add(ARBMultiTexture);
stringsToSearch.add(Project);
stringsToSearch.add(UniversalVAO);
stringsToSearch.add(VaoFunctions);
stringsToSearch.add(LWJGLService);
final String glPrefix = "org/lwjgl/opengl/GL";
for (var entry : new HashMap<>(methodRedirects).entrySet()) {
if (entry.getKey().startsWith(glPrefix)) {
methodRedirects.put(entry.getKey() + "C", entry.getValue());
cstPoolParser.addString(entry.getKey() + "C");
stringsToSearch.add(entry.getKey() + "C");
}
}
cstPoolParser = new ClassConstantPoolParser(stringsToSearch.toArray(new String[0]));
}
public String[] getTransformerExclusions() {
@@ -331,19 +333,17 @@ public final class AngelicaRedirector {
/** @return Was the class changed? */
public boolean transformClassNode(String transformedName, ClassNode cn) {
if (cn == null) {
return false;
}
boolean changed = false;
final boolean isOpenGlHelper = transformedName.equals("net.minecraft.client.renderer.OpenGlHelper");
final boolean isUniversalVAO = transformedName.startsWith(UniversalVAODot);
for (MethodNode mn : cn.methods) {
if (transformedName.equals("net.minecraft.client.renderer.OpenGlHelper") && (mn.name.equals("glBlendFunc") || mn.name.equals("func_148821_a"))) {
if (isOpenGlHelper && (mn.name.equals("glBlendFunc") || mn.name.equals("func_148821_a"))) {
continue;
}
boolean redirectInMethod = false;
for (AbstractInsnNode node : mn.instructions.toArray()) {
if (node instanceof MethodInsnNode mNode) {
if ((mNode.owner.equals(GL11) || mNode.owner.equals(GL11C)) && (mNode.name.equals("glEnable") || mNode.name.equals("glDisable")) && mNode.desc.equals("(I)V")) {
if (mNode.desc.equals("(I)V") && (mNode.owner.equals(GL11) || mNode.owner.equals(GL11C)) && (mNode.name.equals("glEnable") || mNode.name.equals("glDisable"))) {
final AbstractInsnNode prevNode = node.getPrevious();
String name = null;
if (prevNode instanceof LdcInsnNode ldcNode) {
@@ -373,7 +373,7 @@ public final class AngelicaRedirector {
}
changed = true;
redirectInMethod = true;
} else if (mNode.owner.startsWith(Drawable) && mNode.name.equals("makeCurrent")) {
} else if (mNode.name.equals("makeCurrent") && mNode.owner.startsWith(Drawable)) {
mNode.setOpcode(Opcodes.INVOKESTATIC);
mNode.owner = GLStateManager;
mNode.desc = "(L" + Drawable + ";)V";
@@ -387,7 +387,7 @@ public final class AngelicaRedirector {
if (redirects != null) {
final String glsmName = redirects.get(mNode.name);
// Skip VAO method redirects inside UniversalVAO
if (glsmName != null && !(transformedName.startsWith(UniversalVAODot) && UniversalVAOSkippedMethods.contains(glsmName))) {
if (glsmName != null && !(isUniversalVAO && UniversalVAOSkippedMethods.contains(glsmName))) {
if (LOG_SPAM) {
final String shortOwner = mNode.owner.substring(mNode.owner.lastIndexOf("/") + 1);
LOGGER.info("Redirecting call in {} from {}.{}{} to GLStateManager.{}{}", transformedName, shortOwner, mNode.name, mNode.desc, glsmName, mNode.desc);
@@ -403,7 +403,7 @@ public final class AngelicaRedirector {
final Map<String, String> ifaceRedirects = interfaceRedirects.get(mNode.owner);
if (ifaceRedirects != null) {
final String glsmName = ifaceRedirects.get(mNode.name);
if (glsmName != null && !(transformedName.startsWith(UniversalVAODot) && UniversalVAOSkippedMethods.contains(glsmName))) {
if (glsmName != null && !(isUniversalVAO && UniversalVAOSkippedMethods.contains(glsmName))) {
if (LOG_SPAM) {
final String shortOwner = mNode.owner.substring(mNode.owner.lastIndexOf("/") + 1);
LOGGER.info("Redirecting interface call in {} from {}.{}{} to GLStateManager.{}{}", transformedName, shortOwner, mNode.name, mNode.desc, glsmName, "(I)V");
@@ -1,7 +1,6 @@
package com.gtnewhorizons.angelica.loading.shared.transformers;
import com.google.common.collect.ImmutableList;
import com.gtnewhorizon.gtnhlib.asm.ClassConstantPoolParser;
import net.minecraft.launchwrapper.Launch;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.logging.log4j.LogManager;
@@ -18,32 +17,40 @@ import org.objectweb.asm.tree.MethodNode;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public class SodiumBlockTransform {
public final class CeleritasBlockTransform {
public SodiumBlockTransform(boolean isObf) {
this.IS_OBF = isObf;
private final List<String> blockFieldNames = new ArrayList<>();
private final Map<String, String> blockFieldRedirects = new HashMap<>();
public CeleritasBlockTransform(boolean isObf) {
final List<Pair<String, String>> mappings = ImmutableList.of(
Pair.of("minX", "field_149759_B"),
Pair.of("minY", "field_149760_C"),
Pair.of("minZ", "field_149754_D"),
Pair.of("maxX", "field_149755_E"),
Pair.of("maxY", "field_149756_F"),
Pair.of("maxZ", "field_149757_G")
);
for (Pair<String, String> pair : mappings) {
final String name = isObf ? pair.getRight() : pair.getLeft();
this.blockFieldNames.add(name);
this.blockFieldRedirects.put(name, pair.getLeft());
}
}
private final boolean IS_OBF;
private static final boolean LOG_SPAM = Boolean.getBoolean("angelica.redirectorLogspam");
private static final Logger LOGGER = LogManager.getLogger("SodiumBlockTransformer");
private static final Logger LOGGER = LogManager.getLogger("CeleritasBlockTransformer");
private static final String BlockClass = "net/minecraft/block/Block";
private static final String BlockPackage = "net/minecraft/block/Block";
private static final String ThreadedBlockData = "com/gtnewhorizons/angelica/glsm/ThreadedBlockData";
private static final List<Pair<String, String>> BlockBoundsFields = ImmutableList.of(
Pair.of("minX", "field_149759_B"),
Pair.of("minY", "field_149760_C"),
Pair.of("minZ", "field_149754_D"),
Pair.of("maxX", "field_149755_E"),
Pair.of("maxY", "field_149756_F"),
Pair.of("maxZ", "field_149757_G")
);
/** All classes in <tt>net.minecraft.block.*</tt> are the block subclasses save for these. */
private static final String[] VanillaBlockExclusions = {
"net/minecraft/block/IGrowable",
@@ -53,7 +60,6 @@ public class SodiumBlockTransform {
"net/minecraft/block/material/"
};
private static final ClassConstantPoolParser cstPoolParser = new ClassConstantPoolParser(BlockPackage);
private static final Set<String> moddedBlockSubclasses = Collections.newSetFromMap(new ConcurrentHashMap<>());
// Block owners we *shouldn't* redirect because they shadow one of our fields
private static final Set<String> blockOwnerExclusions = Collections.newSetFromMap(new ConcurrentHashMap<>());
@@ -95,10 +101,6 @@ public class SodiumBlockTransform {
return isVanillaBlockSubclass(className) || moddedBlockSubclasses.contains(className);
}
private String getFieldName(Pair<String, String> fieldPair) {
return IS_OBF ? fieldPair.getRight() : fieldPair.getLeft();
}
public String[] getTransformerExclusions() {
return new String[]{
"org.lwjgl",
@@ -109,50 +111,32 @@ public class SodiumBlockTransform {
};
}
public boolean shouldTransform(byte[] basicClass) {
return cstPoolParser.find(basicClass, true);
}
/** @return Was the class changed? */
public boolean transformClassNode(String transformedName, ClassNode cn) {
if (cn == null) {
return false;
}
if ("net.minecraft.block.Block".equals(transformedName) && isCeleritasEnabled()) {
cn.fields.removeIf(field -> BlockBoundsFields.stream().anyMatch(pair -> field.name.equals(pair.getLeft()) || field.name.equals(pair.getRight())));
cn.fields.removeIf(field -> blockFieldNames.stream().anyMatch(name -> field.name.equals(name)));
}
// Track subclasses of Block
if (!isVanillaBlockSubclass(cn.name) && isBlockSubclass(cn.superName)) {
moddedBlockSubclasses.add(cn.name);
cstPoolParser.addString(cn.name);
}
// Check if this class shadows any fields of the parent class
if (moddedBlockSubclasses.contains(cn.name)) {
// If a superclass shadows, then so do we, because JVM will resolve a reference on our class to that
// superclass
boolean doWeShadow;
boolean doWeShadow = false;
if (blockOwnerExclusions.contains(cn.superName)) {
doWeShadow = true;
} else {
// Check if we declare any known field names
boolean b = false;
for (Pair<String, String> pair : BlockBoundsFields) {
boolean result = false;
for (FieldNode field : cn.fields) {
if (field.name.equals(getFieldName(pair))) {
result = true;
break;
}
}
if (result) {
b = true;
for (FieldNode field : cn.fields) {
if (blockFieldNames.contains(field.name)) {
doWeShadow = true;
break;
}
}
doWeShadow = b;
}
if (doWeShadow) {
LOGGER.info("Class '{}' shadows one or more block bounds fields, these accesses won't be redirected!", cn.name);
@@ -160,21 +144,22 @@ public class SodiumBlockTransform {
}
}
if (!isCeleritasEnabled()) {
return false;
}
boolean changed = false;
for (MethodNode mn : cn.methods) {
for (AbstractInsnNode node : mn.instructions.toArray()) {
if ((node.getOpcode() == Opcodes.GETFIELD || node.getOpcode() == Opcodes.PUTFIELD) && node instanceof FieldInsnNode fNode) {
if (!blockOwnerExclusions.contains(fNode.owner) && isBlockSubclass(fNode.owner) && isCeleritasEnabled()) {
Pair<String, String> fieldToRedirect = BlockBoundsFields.stream()
.filter(pair -> fNode.name.equals(getFieldName(pair)))
.findFirst()
.orElse(null);
if (fieldToRedirect != null) {
if (!blockOwnerExclusions.contains(fNode.owner) && isBlockSubclass(fNode.owner)) {
String fieldRedirect = blockFieldRedirects.get(fNode.name);
if (fieldRedirect != null) {
if (LOG_SPAM) {
LOGGER.info("Redirecting Block.{} in {} to thread-safe wrapper", fNode.name, transformedName);
}
// Perform the redirect
fNode.name = fieldToRedirect.getLeft(); // use unobfuscated name
fNode.name = fieldRedirect; // use unobfuscated name
fNode.owner = ThreadedBlockData;
// Inject getter before the field access, to turn Block -> ThreadedBlockData
final MethodInsnNode getter = new MethodInsnNode(Opcodes.INVOKESTATIC, ThreadedBlockData, "get", "(L" + BlockClass + ";)L" + ThreadedBlockData + ";", false);
@@ -162,6 +162,7 @@ public enum Mixins implements IMixins {
, "rendering.MixinPlayerManager"
, "rendering.MixinRenderBlocks"
, "rendering.MixinRenderingRegistry"
, "rendering.MixinTessellator"
, "rendering.MixinTileEntity"
, "rendering.MixinTileEntityMobSpawner"
, "rendering.MixinTileEntityRendererDispatcher"
@@ -178,6 +179,8 @@ public enum Mixins implements IMixins {
, "celeritas.terrain.MixinRenderGlobal"
, "celeritas.terrain.MixinRenderSectionManager"
, "celeritas.terrain.MixinWorldClient"
, "celeritas.frustum.MixinClippingHelper"
, "celeritas.frustum.MixinClippingHelperImpl"
, "celeritas.frustum.MixinFrustrum"
, "celeritas.features.culling.MixinEffectRenderer"
, "celeritas.features.mipmaps.MixinTextureAtlasSprite"
@@ -0,0 +1,8 @@
package com.gtnewhorizons.angelica.mixins.interfaces;
import org.joml.FrustumIntersection;
public interface ClippingHelperExt {
FrustumIntersection celeritas$getFrustumIntersection();
void celeritas$updateFrustumIntersection();
}
@@ -0,0 +1,12 @@
package com.gtnewhorizons.angelica.rendering;
public interface StateAwareTessellator {
/**
* True if the vertex originated from a RenderBlocks method call with the enableAO flag set.
*/
int RENDERED_WITH_VANILLA_AO = 0x1;
void angelica$setAppliedAo(boolean flag);
int[] angelica$getVertexStates();
}
@@ -26,27 +26,29 @@ public final class TileEntityRenderBoundsRegistry {
public static boolean isAlwaysInfiniteExtent(TileEntity te) {
final Class<? extends TileEntity> clazz = te.getClass();
byte result = classRegistry.getByte(clazz);
if (result != UNKNOWN) {
return result == INFINITE;
synchronized (classRegistry) {
final byte result = classRegistry.getByte(clazz);
if (result != UNKNOWN) return result == INFINITE;
}
return probeAndCache(te, clazz);
}
private static boolean probeAndCache(TileEntity te, Class<? extends TileEntity> clazz) {
boolean isInfinite = false;
try {
AxisAlignedBB aabb = te.getRenderBoundingBox();
final AxisAlignedBB aabb = te.getRenderBoundingBox();
isInfinite = isInfiniteExtentsBox(aabb);
} catch (Exception ignored) {}
classRegistry.put(clazz, isInfinite ? INFINITE : FINITE);
synchronized (classRegistry) {
classRegistry.put(clazz, isInfinite ? INFINITE : FINITE);
}
return isInfinite;
}
public static void clear() {
classRegistry.clear();
synchronized (classRegistry) {
classRegistry.clear();
}
}
}
@@ -3,10 +3,10 @@ package com.gtnewhorizons.angelica.rendering.celeritas;
import com.gtnewhorizons.angelica.AngelicaMod;
import com.gtnewhorizons.angelica.dynamiclights.DynamicLights;
import com.gtnewhorizons.angelica.dynamiclights.IDynamicLightSource;
import com.gtnewhorizons.angelica.rendering.StateAwareTessellator;
import com.gtnewhorizons.angelica.rendering.celeritas.iris.BlockRenderContext;
import com.gtnewhorizons.angelica.rendering.celeritas.iris.IrisExtendedChunkVertexEncoder;
import com.gtnewhorizons.angelica.rendering.celeritas.light.LightDataCache;
import com.gtnewhorizons.angelica.rendering.celeritas.light.QuadLightingHelper;
import com.gtnewhorizons.angelica.rendering.celeritas.light.VanillaDiffuseProvider;
import com.gtnewhorizons.angelica.rendering.celeritas.world.WorldSlice;
import lombok.Getter;
@@ -110,7 +110,8 @@ public class AngelicaChunkBuildContext extends ChunkBuildContext {
}
@SuppressWarnings("unchecked")
public void copyRawBuffer(int[] rawBuffer, int vertexCount, ChunkBuildBuffers buffers, Material material, boolean isShaderPackOverride,
public void copyRawBuffer(int[] rawBuffer, int vertexCount, int[] vertexStates,
ChunkBuildBuffers buffers, Material material, boolean isShaderPackOverride,
boolean blockAllowsSmoothLighting) {
if (vertexCount == 0) {
return;
@@ -127,8 +128,7 @@ public class AngelicaChunkBuildContext extends ChunkBuildContext {
final boolean celeritasSmoothLighting = AngelicaMod.options().quality.useCeleritasSmoothLighting;
final boolean shaderActive = IrisApi.getInstance().isShaderPackInUse();
final boolean useAoCalculation = lightPipelineReady && (separateAo || celeritasSmoothLighting || shaderActive);
final boolean stripDiffuse = shaderActive && BlockRenderingSettings.INSTANCE.shouldDisableDirectionalShading();
final boolean shade = false; // Vanilla bakes it, or we remove it - so no need to shade
final boolean shouldApplyDiffuse = !BlockRenderingSettings.INSTANCE.shouldDisableDirectionalShading();
final ChunkColorWriter colorEncoder = separateAo ? ChunkColorWriter.SEPARATE_AO : ChunkColorWriter.EMBEDDIUM;
int ptr = 0;
@@ -140,11 +140,14 @@ public class AngelicaChunkBuildContext extends ChunkBuildContext {
final int worldX = originX + blockX;
final int worldY = originY + blockY;
final int worldZ = originZ + blockZ;
final boolean isEmissive = useAoCalculation && QuadLightingHelper.isBlockEmissive(blockAccess, worldX, worldY, worldZ);
int stateIdx = 0;
for (int quadIdx = 0; quadIdx < numQuads; quadIdx++) {
float uSum = 0, vSum = 0;
int quadState = -1;
for (int vIdx = 0; vIdx < 4; vIdx++) {
final var vertex = vertices[vIdx];
vertex.x = Float.intBitsToFloat(rawBuffer[ptr++]);
@@ -161,6 +164,8 @@ public class AngelicaChunkBuildContext extends ChunkBuildContext {
vertex.color = rawBuffer[ptr++];
vertex.vanillaNormal = rawBuffer[ptr++];
vertex.light = rawBuffer[ptr++];
quadState &= vertexStates[stateIdx++];
}
final int trueNormal = QuadUtil.calculateNormal(vertices);
@@ -171,34 +176,16 @@ public class AngelicaChunkBuildContext extends ChunkBuildContext {
animatedSprites.add(sprite);
}
// Strip vanilla's baked diffuse when shaders want oldLighting=false - multiply by an inversion factor
// instead of attempting to mixin/asm all the places that bake it in
if (stripDiffuse) {
final float inverseDiffuse = VanillaDiffuseProvider.INSTANCE.getInverseDiffuse(facing);
for (int vIdx = 0; vIdx < 4; vIdx++) {
vertices[vIdx].color = VanillaDiffuseProvider.multiplyColor(vertices[vIdx].color, inverseDiffuse);
}
}
if (useAoCalculation) {
final boolean quadIsFullBright = QuadLightingHelper.isQuadFullBright(vertices);
if (isEmissive || quadIsFullBright) {
Arrays.fill(quadLightData.br, 1.0f);
if (isEmissive) {
Arrays.fill(quadLightData.lm, LightDataAccess.FULL_BRIGHT);
} else {
for (int i = 0; i < 4; i++) {
quadLightData.lm[i] = vertices[i].light;
}
}
} else {
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, shade, true);
}
// If block used vanilla AO, then we can safely compute our own lighting data and ignore what vanilla
// computed. We suppress vanilla emitting the brightness/color in MixinRenderBlocks.
// 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) {
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];
@@ -207,6 +194,14 @@ public class AngelicaChunkBuildContext extends ChunkBuildContext {
vertex.light = quadLightData.lm[vIdx];
}
} else {
if (!shouldApplyDiffuse) {
// Calculate the inverse of the expected diffuse constant and apply it to the color to fake
// diffuse not having been applied
final float inverseDiffuse = VanillaDiffuseProvider.INSTANCE.getInverseDiffuse(facing);
for (int vIdx = 0; vIdx < 4; vIdx++) {
vertices[vIdx].color = VanillaDiffuseProvider.multiplyColor(vertices[vIdx].color, inverseDiffuse);
}
}
for (int vIdx = 0; vIdx < 4; vIdx++) {
vertices[vIdx].trueNormal = trueNormal;
}
@@ -2,6 +2,8 @@ package com.gtnewhorizons.angelica.rendering.celeritas;
import com.gtnewhorizon.gtnhlib.blockpos.BlockPos;
import com.gtnewhorizons.angelica.rendering.AngelicaRenderQueue;
import com.gtnewhorizons.angelica.rendering.StateAwareTessellator;
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;
@@ -135,8 +137,8 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask<C
if (block.hasTileEntity(meta)) {
final TileEntity tileEntity = region.getTileEntity(x, y, z);
if (TileEntityRendererDispatcher.instance.hasSpecialRenderer(tileEntity)) {
renderData.globalBlockEntities.add(tileEntity);
if (tileEntity != null && TileEntityRendererDispatcher.instance.hasSpecialRenderer(tileEntity)) {
(TileEntityRenderBoundsRegistry.isAlwaysInfiniteExtent(tileEntity) ? renderData.globalBlockEntities : renderData.culledBlockEntities).add(tileEntity);
}
}
@@ -248,15 +250,11 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask<C
block.canRenderInPass(pass);
tessellator.startDrawingQuads();
renderBlocks.renderBlockByRenderType(block, x, y, z);
// In modern versions, block models can specify whether to enable AO or not, but here we must
// rely on render ID heuristics to figure out which models would have turned it off
int vanillaRenderId = block.getRenderType();
boolean blockAllowsSmoothLighting = Minecraft.isAmbientOcclusionEnabled() // smooth lighting on
&& block.getLightValue() == 0 // does not emit real block light
&& vanillaRenderId != 1 // is not a "cross" block
&& vanillaRenderId != 40; // is not a double plant block
buildContext.copyRawBuffer(tessellator.rawBuffer, tessellator.vertexCount, buffers, passMaterial,
isShaderPackOverride, blockAllowsSmoothLighting);
&& block.getLightValue() == 0; // does not emit real block light
buildContext.copyRawBuffer(tessellator.rawBuffer, tessellator.vertexCount,
((StateAwareTessellator)tessellator).angelica$getVertexStates(),
buffers, passMaterial, isShaderPackOverride, blockAllowsSmoothLighting);
tessellator.reset();
tessellator.isDrawing = false;
@@ -21,6 +21,7 @@ import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.embeddedt.embeddium.impl.gl.device.CommandList;
import org.embeddedt.embeddium.impl.render.chunk.ChunkRenderMatrices;
import org.embeddedt.embeddium.impl.render.chunk.RenderSection;
import org.embeddedt.embeddium.impl.render.chunk.data.MinecraftBuiltRenderSectionData;
import org.embeddedt.embeddium.impl.render.chunk.lists.ChunkRenderList;
import org.embeddedt.embeddium.impl.render.chunk.lists.SortedRenderLists;
@@ -31,6 +32,8 @@ import org.embeddedt.embeddium.impl.render.viewport.Viewport;
import org.joml.Matrix4f;
import org.lwjgl.opengl.GL11;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
@@ -48,6 +51,12 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
// the volume of a section multiplied by the number of sections to be checked at most
private static final double MAX_ENTITY_CHECK_VOLUME = 16 * 16 * 16 * 15;
// For sorting transparent TESRs
private RenderSectionOrderer renderSectionOrderer = new RenderSectionOrderer();
private TileEntityOrderer tileEntityOrderer = new TileEntityOrderer();
private ArrayList<RenderSection> sortedRenderSections = new ArrayList<>();
private ArrayList<TileEntity> sortedTileEntities = new ArrayList<>();
private CeleritasWorldRenderer(Minecraft mc) {
// Private constructor for singleton
this.mc = mc;
@@ -219,9 +228,98 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
GLStateManager.glColor4f(1, 1, 1, 1);
}
private int renderCulledTileEntities(TileEntityRenderContext renderContext) {
int count = 0;
sortedTileEntities.clear();
SortedRenderLists renderLists = renderSectionManager.getRenderLists();
Iterator<ChunkRenderList> renderListIterator = renderLists.iterator();
while (renderListIterator.hasNext()) {
var renderList = renderListIterator.next();
var renderRegion = renderList.getRegion();
var renderSectionIterator = renderList.sectionsWithEntitiesIterator();
if (renderSectionIterator == null) {
continue;
}
while (renderSectionIterator.hasNext()) {
var renderSectionId = renderSectionIterator.nextByteAsInt();
var renderSection = renderRegion.getSection(renderSectionId);
if (renderSection == null) {
continue;
}
var context = renderSection.getBuiltContext();
if (!(context instanceof MinecraftBuiltRenderSectionData<?, ?> mcData)) {
continue;
}
// noinspection unchecked
var blockEntities = (List<TileEntity>) mcData.culledBlockEntities;
if (blockEntities.isEmpty()) {
continue;
}
for (TileEntity te : blockEntities) {
if (te.shouldRenderInPass(renderContext.pass)) sortedTileEntities.add(te);
}
}
}
sortedTileEntities.sort(tileEntityOrderer.setLastCameraState(lastCameraState));
this.renderBlockEntityList(sortedTileEntities, renderContext);
return sortedTileEntities.size();
}
private int renderGlobalTileEntities(TileEntityRenderContext renderContext) {
int count = 0;
sortedRenderSections.clear();
sortedRenderSections.addAll(renderSectionManager.getSectionsWithGlobalEntities());
sortedRenderSections.sort(renderSectionOrderer.setLastCameraState(lastCameraState));
for (var renderSection : sortedRenderSections) {
sortedTileEntities.clear();
var builtContext = renderSection.getBuiltContext();
if (!(builtContext instanceof MinecraftBuiltRenderSectionData<?, ?> mcData)) {
continue;
}
// noinspection unchecked
var blockEntities = (List<TileEntity>) mcData.globalBlockEntities;
if (blockEntities.isEmpty()) {
continue;
}
for (TileEntity te : blockEntities) {
if (te.shouldRenderInPass(renderContext.pass)) sortedTileEntities.add(te);
}
count += sortedTileEntities.size();
sortedTileEntities.sort(tileEntityOrderer.setLastCameraState(lastCameraState));
this.renderBlockEntityList(sortedTileEntities, renderContext);
}
return count;
}
public int renderBlockEntities(float partialTicks) {
final int pass = MinecraftForgeClient.getRenderPass();
return super.renderBlockEntities(teRenderContext.set(partialTicks, pass));
teRenderContext.set(partialTicks, pass);
if (pass == 0 || !AngelicaMod.options().performance.translucencySorting) {
return super.renderBlockEntities(teRenderContext);
}
int count = 0;
count += this.renderCulledTileEntities(teRenderContext);
count += this.renderGlobalTileEntities(teRenderContext);
return count;
}
private void renderTE(TileEntity tileEntity, int pass, float partialTicks) {
@@ -284,4 +382,51 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
return this;
}
}
private static class RenderSectionOrderer implements Comparator<RenderSection> {
public CameraState lastCameraState;
public RenderSectionOrderer() {
super();
}
public RenderSectionOrderer setLastCameraState(CameraState lastCameraState) {
this.lastCameraState = lastCameraState;
return this;
}
@Override
public int compare(RenderSection render1, RenderSection render2) {
final float x = (float) this.lastCameraState.x();
final float y = (float) this.lastCameraState.y();
final float z = (float) this.lastCameraState.z();
final float d1 = render1.getSquaredDistance(x, y, z);
final float d2 = render2.getSquaredDistance(x, y, z);
return Float.compare(d2, d1);
}
}
private static class TileEntityOrderer implements Comparator<TileEntity> {
public CameraState lastCameraState;
public TileEntityOrderer() {
super();
}
public TileEntityOrderer setLastCameraState(CameraState lastCameraState) {
this.lastCameraState = lastCameraState;
return this;
}
@Override
public int compare(TileEntity te1, TileEntity te2) {
final double x = this.lastCameraState.x();
final double y = this.lastCameraState.y();
final double z = this.lastCameraState.z();
final double d1 = te1.getDistanceFrom(x, y, z);
final double d2 = te2.getDistanceFrom(x, y, z);
return Double.compare(d2, d1);
}
}
}
@@ -1,39 +0,0 @@
package com.gtnewhorizons.angelica.rendering.celeritas.light;
import net.minecraft.block.Block;
import net.minecraft.world.IBlockAccess;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexEncoder;
public final class QuadLightingHelper {
private QuadLightingHelper() {}
// Known emissive brightness values set by mods/vanilla
public static final int FULL_BRIGHT_15 = (15 << 20) | (15 << 4); // 15728880
public static final int FULL_BRIGHT_14 = (14 << 20) | (14 << 4); // 14680288
public static boolean isBlockEmissive(IBlockAccess world, int x, int y, int z) {
final Block block = world.getBlock(x, y, z);
try {
return block.getMixedBrightnessForBlock(EmptyBlockAccess.INSTANCE, x, y, z) == FULL_BRIGHT_15;
} catch (Exception e) {
return false;
}
}
public static boolean isQuadFullBright(ChunkVertexEncoder.Vertex[] vertices) {
final int first = vertices[0].light;
// Must be a known emissive brightness value
if (first != FULL_BRIGHT_15 && first != FULL_BRIGHT_14) {
return false;
}
// All 4 vertices must have the same value
for (int i = 1; i < 4; i++) {
if (vertices[i].light != first) {
return false;
}
}
return true;
}
}
@@ -7,8 +7,8 @@ import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.StampedLock;
import net.minecraft.block.Block;
import net.minecraft.util.IIcon;
@@ -33,19 +33,36 @@ public class CTMUtils {
private static final MCLogger logger = MCLogger.getLogger(MCLogger.Category.CONNECTED_TEXTURES, "CTM");
private static final List<TileOverride> allOverrides = new ArrayList<>();
private static final Map<Block, List<BlockStateMatcher>> blockOverrides = new IdentityHashMap<>();
private static final Map<String, List<TileOverride>> tileOverrides = new HashMap<>();
private static class Overrides {
private final List<TileOverride> all = new ArrayList<>();
private final Map<Block, List<BlockStateMatcher>> block = new IdentityHashMap<>();
private final Map<String, List<TileOverride>> tile = new HashMap<>();
}
private static Overrides overrides = new Overrides();
private static Overrides newOverrides = null;
private static TileLoader tileLoader;
private static TileOverride lastOverride;
private static final Lock lock = new ReentrantLock();
private static final StampedLock lock = new StampedLock();
private static final TileOverrideIterator.IJK ijkIterator = newIJKIterator();
private static final TileOverrideIterator.Metadata metadataIterator = newMetadataIterator();
private static class StateAndIterator {
private final TileOverrideIterator.IJK ijkIterator = CTMUtils.newIJKIterator();
private final TileOverrideIterator.Metadata metadataIterator = CTMUtils.newMetadataIterator();
private final BlockOrientation renderBlockState = new BlockOrientation();
private final int texturePackChangeCounter;
private static boolean haveBlockFace;
private static final BlockOrientation renderBlockState = new BlockOrientation();
public StateAndIterator() {
this.texturePackChangeCounter = 0;
}
public StateAndIterator(int texturePackChangeCounter) {
this.texturePackChangeCounter = texturePackChangeCounter;
}
}
private static final ThreadLocal<StateAndIterator> stateAndIterator = ThreadLocal.withInitial(StateAndIterator::new);
private static final AtomicInteger texturePackChangeCounter = new AtomicInteger(0);
static {
try {
@@ -61,7 +78,7 @@ public class CTMUtils {
@Override
public void beforeChange() {
lock.lock();
long stamp = lock.writeLock();
try {
RenderPassAPI.instance.clear();
try {
@@ -71,39 +88,39 @@ public class CTMUtils {
} catch (Exception e) {
e.printStackTrace();
}
renderBlockState.clear();
ijkIterator.clear();
metadataIterator.clear();
allOverrides.clear();
blockOverrides.clear();
tileOverrides.clear();
lastOverride = null;
RenderBlocksUtils.blankIcon = null;
tileLoader = new TileLoader("textures/blocks", logger);
RenderPassAPI.instance.refreshBlendingOptions();
logger.info("loading CTM overrides");
newOverrides = new Overrides();
if (MCPatcherForgeConfig.ConnectedTextures.standard || MCPatcherForgeConfig.ConnectedTextures.nonStandard) {
for (ResourceLocation resource : ResourceList.getInstance()
.listResources(TexturePackAPI.MCPATCHER_SUBDIR + "ctm", ".properties", true)) {
registerOverride(TileOverride.create(resource, tileLoader));
registerOverrideWithoutLock(newOverrides, TileOverride.create(resource, tileLoader));
}
}
for (ResourceLocation resource : BlendMethod.getAllBlankResources()) {
tileLoader.preloadTile(resource, false);
}
} finally {
lock.unlock();
lock.unlockWrite(stamp);
}
}
@Override
public void afterChange() {
lock.lock();
if (newOverrides == null) {
logger.error("CTM overrides were not initialized during texture pack change");
logger.error("Maybe beforeChange was not called, or threw an exception?");
return;
}
long stamp = lock.writeLock();
try {
for (TileOverride override : allOverrides) {
for (TileOverride override : newOverrides.all) {
override.registerIcons();
}
for (Map.Entry<Block, List<BlockStateMatcher>> entry : blockOverrides.entrySet()) {
for (Map.Entry<Block, List<BlockStateMatcher>> entry : newOverrides.block.entrySet()) {
for (BlockStateMatcher matcher : entry.getValue()) {
TileOverride override = (TileOverride) matcher.getData();
if (override.getRenderPass() >= 0) {
@@ -111,67 +128,90 @@ public class CTMUtils {
}
}
}
for (List<BlockStateMatcher> overrides : blockOverrides.values()) {
for (List<BlockStateMatcher> overrides : newOverrides.block.values()) {
overrides.sort((m1, m2) -> {
TileOverride o1 = (TileOverride) m1.getData();
TileOverride o2 = (TileOverride) m2.getData();
return o1.compareTo(o2);
});
}
for (List<TileOverride> overrides : tileOverrides.values()) {
for (List<TileOverride> overrides : newOverrides.tile.values()) {
Collections.sort(overrides);
}
setBlankResource();
setBlankResourceWithoutLock();
overrides = newOverrides;
newOverrides = null;
texturePackChangeCounter.getAndIncrement();
} finally {
lock.unlock();
lock.unlockWrite(stamp);
}
}
});
}
private static void clearBlockFace() {
haveBlockFace = false;
private static StateAndIterator getStateAndIterator() {
int globalTexturePackChangeCounter = texturePackChangeCounter.get();
StateAndIterator local = stateAndIterator.get();
if (local.texturePackChangeCounter < globalTexturePackChangeCounter) {
local = new StateAndIterator(globalTexturePackChangeCounter);
stateAndIterator.set(local);
}
return local;
}
private static IIcon getBlockIconWithoutLock(IIcon icon, Block block, IBlockAccess blockAccess,
int x, int y, int z, int face) {
StateAndIterator local = getStateAndIterator();
if (blockAccess != null && checkFace(face)) {
local.renderBlockState.setBlock(block, blockAccess, x, y, z);
local.renderBlockState.setFace(face);
TileOverride lastOverride = local.ijkIterator.go(local.renderBlockState, icon);
if (lastOverride != null) {
return skipDefaultRendering(block) ? RenderBlocksUtils.blankIcon : local.ijkIterator.getIcon();
}
}
return skipDefaultRendering(block) ? RenderBlocksUtils.blankIcon : icon;
}
private static IIcon getBlockIconWithoutLock(IIcon icon, Block block, int face, int metadata) {
StateAndIterator local = getStateAndIterator();
if (checkFace(face) && checkRenderType(block)) {
local.renderBlockState.setBlockMetadata(block, metadata, face);
TileOverride lastOverride = local.metadataIterator.go(local.renderBlockState, icon);
if (lastOverride != null) {
return local.metadataIterator.getIcon();
}
}
return icon;
}
public static IIcon getBlockIcon(IIcon icon, Block block, IBlockAccess blockAccess,
int x, int y, int z, int face) {
lock.lock();
try {
lastOverride = null;
if (blockAccess != null && checkFace(face)) {
if (!haveBlockFace) {
renderBlockState.setBlock(block, blockAccess, x, y, z);
renderBlockState.setFace(face);
}
lastOverride = ijkIterator.go(renderBlockState, icon);
if (lastOverride != null) {
icon = ijkIterator.getIcon();
}
long stamp = lock.tryOptimisticRead();
IIcon value = getBlockIconWithoutLock(icon, block, blockAccess, x, y, z, face);
if (!lock.validate(stamp)) {
stamp = lock.readLock();
try {
value = getBlockIconWithoutLock(icon, block, blockAccess, x, y, z, face);
} finally {
lock.unlockRead(stamp);
}
clearBlockFace();
IIcon result = lastOverride == null && skipDefaultRendering(block) ? RenderBlocksUtils.blankIcon : icon;
return result;
} finally {
lock.unlock();
}
return value;
}
public static IIcon getBlockIcon(IIcon icon, Block block, int face, int metadata) {
lock.lock();
try {
lastOverride = null;
if (checkFace(face) && checkRenderType(block)) {
renderBlockState.setBlockMetadata(block, metadata, face);
lastOverride = metadataIterator.go(renderBlockState, icon);
if (lastOverride != null) {
icon = metadataIterator.getIcon();
}
long stamp = lock.tryOptimisticRead();
IIcon value = getBlockIconWithoutLock(icon, block, face, metadata);
if (!lock.validate(stamp)) {
stamp = lock.readLock();
try {
value = getBlockIconWithoutLock(icon, block, face, metadata);
} finally {
lock.unlockRead(stamp);
}
return icon;
} finally {
lock.unlock();
}
return value;
}
public static IIcon getBlockIcon(IIcon icon, Block block, int face) {
@@ -197,56 +237,55 @@ public class CTMUtils {
return RenderPassAPI.instance.skipDefaultRendering(block);
}
private static void registerOverride(TileOverride override) {
lock.lock();
try {
if (override != null && !override.isDisabled()) {
boolean registered = false;
List<BlockStateMatcher> matchingBlocks = override.getMatchingBlocks();
if (!MCPatcherUtils.isNullOrEmpty(matchingBlocks)) {
for (BlockStateMatcher matcher : matchingBlocks) {
if (matcher == null) {
continue;
}
Block block = matcher.getBlock();
List<BlockStateMatcher> list = blockOverrides.computeIfAbsent(block, k -> new ArrayList<>());
list.add(matcher);
logger.fine("using %s for block %s", override, BlockAPI.getBlockName(block));
registered = true;
private static void registerOverrideWithoutLock(Overrides overrides, TileOverride override) {
if (override != null && !override.isDisabled()) {
boolean registered = false;
List<BlockStateMatcher> matchingBlocks = override.getMatchingBlocks();
if (!MCPatcherUtils.isNullOrEmpty(matchingBlocks)) {
for (BlockStateMatcher matcher : matchingBlocks) {
if (matcher == null) {
continue;
}
}
Set<String> matchingTiles = override.getMatchingTiles();
if (!MCPatcherUtils.isNullOrEmpty(matchingTiles)) {
for (String name : matchingTiles) {
List<TileOverride> list = tileOverrides.computeIfAbsent(name, k -> new ArrayList<>());
list.add(override);
logger.fine("using %s for tile %s", override, name);
registered = true;
}
}
if (registered) {
allOverrides.add(override);
Block block = matcher.getBlock();
List<BlockStateMatcher> list = overrides.block.computeIfAbsent(block, k -> new ArrayList<>());
list.add(matcher);
logger.fine("using %s for block %s", override, BlockAPI.getBlockName(block));
registered = true;
}
}
} finally {
lock.unlock();
Set<String> matchingTiles = override.getMatchingTiles();
if (!MCPatcherUtils.isNullOrEmpty(matchingTiles)) {
for (String name : matchingTiles) {
List<TileOverride> list = overrides.tile.computeIfAbsent(name, k -> new ArrayList<>());
list.add(override);
logger.fine("using %s for tile %s", override, name);
registered = true;
}
}
if (registered) {
overrides.all.add(override);
}
}
}
private static void setBlankResourceWithoutLock() {
RenderBlocksUtils.blankIcon = tileLoader.getIcon(RenderPassAPI.instance.getBlankResource());
}
public static void setBlankResource() {
lock.lock();
long stamp = lock.writeLock();
try {
RenderBlocksUtils.blankIcon = tileLoader.getIcon(RenderPassAPI.instance.getBlankResource());
setBlankResourceWithoutLock();
} finally {
lock.unlock();
lock.unlockWrite(stamp);
}
}
private static TileOverrideIterator.IJK newIJKIterator() {
return new TileOverrideIterator.IJK(blockOverrides, tileOverrides);
return new TileOverrideIterator.IJK(overrides.block, overrides.tile);
}
private static TileOverrideIterator.Metadata newMetadataIterator() {
return new TileOverrideIterator.Metadata(blockOverrides, tileOverrides);
return new TileOverrideIterator.Metadata(overrides.block, overrides.tile);
}
}
@@ -50,6 +50,7 @@ public enum Settings {
}
},
DYNAMIC_FOV(new NotFineOptionTickBox(true, null)),
HURT_SHAKE(new NotFineOptionSliderPercentage(100, 0, 300, 5, OptionImpact.LOW)),
DYNAMIC_LIGHTS(new NotFineOptionCycling<>(DynamicLightsMode.FANCY, OptionImpact.VARIES)){
@Override
public void applyChanges() {
@@ -152,6 +152,7 @@ public class SodiumGameOptionPages {
.setBinding((opts, value) -> opts.viewBobbing = value, opts -> opts.viewBobbing)
.build())
.add(Settings.DYNAMIC_FOV.option)
.add(Settings.HURT_SHAKE.option)
.add(Settings.MODE_WATER.option)
.add(Settings.MODE_DROPPED_ITEMS.option)
.build());
@@ -1,11 +1,14 @@
package net.coderbot.iris.celeritas;
import com.google.common.collect.ImmutableSet;
import com.google.common.primitives.Ints;
import lombok.Getter;
import lombok.experimental.Accessors;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gl.blending.BlendModeOverride;
import net.coderbot.iris.gl.blending.BufferBlendOverride;
import net.coderbot.iris.gl.framebuffer.GlFramebuffer;
import net.coderbot.iris.shaderpack.loading.ProgramId;
import net.coderbot.iris.gl.program.ProgramImages;
import net.coderbot.iris.gl.program.ProgramSamplers;
import net.coderbot.iris.gl.program.ProgramUniforms;
@@ -19,7 +22,10 @@ import net.coderbot.iris.shaderpack.ProgramSource;
import net.coderbot.iris.uniforms.custom.CustomUniforms;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
@@ -43,6 +49,7 @@ public class CeleritasTerrainPipeline {
private final EnumMap<PatchShaderType, Optional<String>> sources = new EnumMap<>(PatchShaderType.class);
private GlFramebuffer framebuffer;
private BlendModeOverride blendModeOverride;
private List<BufferBlendOverride> bufferBlendOverrides;
private float alphaReference;
private PassInfo() {
@@ -91,21 +98,41 @@ public class CeleritasTerrainPipeline {
PassInfo passInfo = new PassInfo();
passInfoMap.put(pass, passInfo);
// Set up framebuffer
// Set up framebuffer, blend mode, and buffer blend overrides
final ProgramId programId = switch (pass) {
case GBUFFER_TRANSLUCENT -> ProgramId.Water;
case SHADOW, SHADOW_CUTOUT -> ProgramId.Shadow;
default -> ProgramId.Terrain;
};
if (pass == IrisTerrainPass.SHADOW || pass == IrisTerrainPass.SHADOW_CUTOUT) {
passInfo.framebuffer = shadowFramebuffer;
passInfo.blendModeOverride = programId.getBlendModeOverride();
passInfo.bufferBlendOverrides = Collections.emptyList();
} else if (renderTargets != null) {
ImmutableSet<Integer> flipped = pass == IrisTerrainPass.GBUFFER_TRANSLUCENT ? flippedAfterTranslucent : flippedAfterPrepare;
Optional<ProgramSource> programSource = gbufferProgramSource.get(pass);
programSource.ifPresentOrElse(source -> passInfo.framebuffer = renderTargets.createGbufferFramebuffer(flipped, source.getDirectives().getDrawBuffers()), () -> passInfo.framebuffer = renderTargets.createGbufferFramebuffer(flipped, new int[] {0}));
}
programSource.ifPresentOrElse(source -> {
passInfo.framebuffer = renderTargets.createGbufferFramebuffer(flipped, source.getDirectives().getDrawBuffers());
passInfo.blendModeOverride = source.getDirectives().getBlendModeOverride().orElse(programId.getBlendModeOverride());
// Set blend mode override
passInfo.blendModeOverride = switch (pass) {
case GBUFFER_TRANSLUCENT -> null; // Default blending
default -> BlendModeOverride.OFF;
};
passInfo.bufferBlendOverrides = new ArrayList<>();
source.getDirectives().getBufferBlendOverrides().forEach(information -> {
int index = Ints.indexOf(source.getDirectives().getDrawBuffers(), information.getIndex());
if (index > -1) {
passInfo.bufferBlendOverrides.add(new BufferBlendOverride(index, information.getBlendMode()));
}
});
}, () -> {
passInfo.framebuffer = renderTargets.createGbufferFramebuffer(flipped, new int[] {0});
passInfo.blendModeOverride = programId.getBlendModeOverride();
passInfo.bufferBlendOverrides = Collections.emptyList();
});
} else {
passInfo.blendModeOverride = programId.getBlendModeOverride();
passInfo.bufferBlendOverrides = Collections.emptyList();
}
// Set alpha reference
passInfo.alphaReference = switch (pass) {
@@ -2,6 +2,7 @@ package net.coderbot.iris.celeritas;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gl.blending.BlendModeOverride;
import net.coderbot.iris.gl.blending.BufferBlendOverride;
import net.coderbot.iris.pipeline.WorldRenderingPipeline;
import net.coderbot.iris.pipeline.transform.PatchShaderType;
import net.coderbot.iris.shadows.ShadowRenderingState;
@@ -15,6 +16,7 @@ import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
import org.jetbrains.annotations.Nullable;
import java.util.EnumMap;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
@@ -82,11 +84,11 @@ public class IrisCeleritasChunkProgramOverrides {
builder.bindAttribute(attr.getName(), attrIndex++);
}
// Get blend from PassInfo
final CeleritasTerrainPipeline.PassInfo passInfo = pipeline.getPassInfo(pass);
final BlendModeOverride blendOverride = passInfo.blendModeOverride();
final List<BufferBlendOverride> bufferOverrides = passInfo.bufferBlendOverrides();
return builder.link(context -> new IrisCeleritasChunkShaderInterface(((GlObject) context).handle(), context, pipeline, pass.isShadow(), blendOverride, pipeline.getCustomUniforms()));
return builder.link(context -> new IrisCeleritasChunkShaderInterface(((GlObject) context).handle(), context, pipeline, pass.isShadow(), blendOverride, bufferOverrides, pipeline.getCustomUniforms()));
} finally {
vertShader.delete();
if (geomShader != null) geomShader.delete();
@@ -4,6 +4,7 @@ import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.mixins.interfaces.EntityRendererAccessor;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gl.blending.BlendModeOverride;
import net.coderbot.iris.gl.blending.BufferBlendOverride;
import net.coderbot.iris.gl.framebuffer.GlFramebuffer;
import net.coderbot.iris.pipeline.WorldRenderingPipeline;
import net.coderbot.iris.samplers.IrisSamplers;
@@ -16,6 +17,7 @@ import net.coderbot.iris.gl.program.ProgramSamplers;
import net.coderbot.iris.gl.program.ProgramUniforms;
import net.coderbot.iris.shadows.ShadowRenderingState;
import net.coderbot.iris.uniforms.custom.CustomUniforms;
import java.util.List;
import org.embeddedt.embeddium.impl.gl.shader.ShaderBindingContext;
import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformFloat3v;
import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformMatrix3f;
@@ -51,13 +53,15 @@ public class IrisCeleritasChunkShaderInterface implements ChunkShaderInterface {
// Rendering state
private final BlendModeOverride blendModeOverride;
private final List<BufferBlendOverride> bufferBlendOverrides;
private final boolean hasOverrides;
// Stored matrices for inverse and normal matrix computation
private final Matrix4f projectionMatrixInverse = new Matrix4f();
private final Matrix4f modelViewMatrixInverse = new Matrix4f();
private final Matrix3f normalMatrix = new Matrix3f();
public IrisCeleritasChunkShaderInterface(int handle, ShaderBindingContext context, CeleritasTerrainPipeline pipeline, boolean isShadowPass, BlendModeOverride blendModeOverride, CustomUniforms customUniforms) {
public IrisCeleritasChunkShaderInterface(int handle, ShaderBindingContext context, CeleritasTerrainPipeline pipeline, boolean isShadowPass, BlendModeOverride blendModeOverride, List<BufferBlendOverride> bufferBlendOverrides, CustomUniforms customUniforms) {
this.uniformModelViewMatrix = context.bindUniformIfPresent("iris_ModelViewMatrix", GlUniformMatrix4f::new);
this.uniformModelViewMatrixInverse = context.bindUniformIfPresent("iris_ModelViewMatrixInverse", GlUniformMatrix4f::new);
this.uniformProjectionMatrix = context.bindUniformIfPresent("iris_ProjectionMatrix", GlUniformMatrix4f::new);
@@ -66,6 +70,8 @@ public class IrisCeleritasChunkShaderInterface implements ChunkShaderInterface {
this.uniformRegionOffset = context.bindUniformIfPresent("u_RegionOffset", GlUniformFloat3v::new);
this.blendModeOverride = blendModeOverride;
this.bufferBlendOverrides = bufferBlendOverrides;
this.hasOverrides = bufferBlendOverrides != null && !bufferBlendOverrides.isEmpty();
this.customUniforms = customUniforms;
final ProgramUniforms.Builder builder = pipeline.initUniforms(handle);
@@ -94,6 +100,10 @@ public class IrisCeleritasChunkShaderInterface implements ChunkShaderInterface {
blendModeOverride.apply();
}
if (hasOverrides) {
bufferBlendOverrides.forEach(BufferBlendOverride::apply);
}
if (irisProgramUniforms != null) {
irisProgramUniforms.update();
}
@@ -109,7 +119,7 @@ public class IrisCeleritasChunkShaderInterface implements ChunkShaderInterface {
@Override
public void restoreState() {
if (blendModeOverride != null) {
if (blendModeOverride != null || hasOverrides) {
BlendModeOverride.restore();
}
@@ -4,29 +4,41 @@ import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import com.gtnewhorizons.angelica.glsm.states.BlendState;
import lombok.Getter;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL14;
public class BlendModeStorage {
private static final int MAX_DRAW_BUFFERS = 8;
private static boolean originalBlendEnable;
private static final BlendState originalBlend = new BlendState();
@Getter private static boolean blendLocked;
@Getter private static boolean hasDeferredChanges;
private static final int[] bufferOverrideIndices = new int[MAX_DRAW_BUFFERS];
private static final boolean[] bufferOverrideIsDisable = new boolean[MAX_DRAW_BUFFERS];
private static final BlendState[] bufferOverrideStates = new BlendState[MAX_DRAW_BUFFERS];
private static int bufferOverrideCount;
static {
for (int i = 0; i < MAX_DRAW_BUFFERS; i++) {
bufferOverrideStates[i] = new BlendState();
}
}
public static void overrideBlend(BlendState override) {
if (!blendLocked) {
// Only save the previous state if the blend mode wasn't already locked
originalBlendEnable = GL11.glGetBoolean(GL11.GL_BLEND);
originalBlendEnable = GLStateManager.getBlendMode().isEnabled();
originalBlend.set(GLStateManager.getBlendState());
}
bufferOverrideCount = 0;
hasDeferredChanges = false;
blendLocked = false;
if (override == null) {
GL11.glDisable(GL11.GL_BLEND);
GLStateManager.disableBlend();
} else {
GL11.glEnable(GL11.GL_BLEND);
GL14.glBlendFuncSeparate(override.getSrcRgb(), override.getDstRgb(), override.getSrcAlpha(), override.getDstAlpha());
GLStateManager.enableBlend();
GLStateManager.tryBlendFuncSeparate(override.getSrcRgb(), override.getDstRgb(), override.getSrcAlpha(), override.getDstAlpha());
}
blendLocked = true;
@@ -35,7 +47,7 @@ public class BlendModeStorage {
public static void overrideBufferBlend(int index, BlendState override) {
if (!blendLocked) {
// Only save the previous state if the blend mode wasn't already locked
originalBlendEnable = GL11.glGetBoolean(GL11.GL_BLEND);
originalBlendEnable = GLStateManager.getBlendMode().isEnabled();
originalBlend.set(GLStateManager.getBlendState());
}
@@ -46,15 +58,53 @@ public class BlendModeStorage {
RenderSystem.blendFuncSeparatei(index, override.getSrcRgb(), override.getDstRgb(), override.getSrcAlpha(), override.getDstAlpha());
}
if (bufferOverrideCount < MAX_DRAW_BUFFERS) {
final int slot = bufferOverrideCount++;
bufferOverrideIndices[slot] = index;
bufferOverrideIsDisable[slot] = (override == null);
if (override != null) {
bufferOverrideStates[slot].setAll(override.getSrcRgb(), override.getDstRgb(), override.getSrcAlpha(), override.getDstAlpha());
}
}
blendLocked = true;
}
public static void deferBlendModeToggle(boolean enabled) {
originalBlendEnable = enabled;
hasDeferredChanges = true;
}
public static void deferBlendFunc(int srcRgb, int dstRgb, int srcAlpha, int dstAlpha) {
originalBlend.setAll(srcRgb, dstRgb, srcAlpha, dstAlpha);
hasDeferredChanges = true;
}
public static void flushDeferredBlend() {
if (!blendLocked || !hasDeferredChanges) return;
hasDeferredChanges = false;
blendLocked = false;
if (originalBlendEnable) {
GLStateManager.enableBlend();
} else {
GLStateManager.disableBlend();
}
GLStateManager.tryBlendFuncSeparate(
originalBlend.getSrcRgb(), originalBlend.getDstRgb(),
originalBlend.getSrcAlpha(), originalBlend.getDstAlpha());
blendLocked = true;
for (int i = 0; i < bufferOverrideCount; i++) {
final int idx = bufferOverrideIndices[i];
if (bufferOverrideIsDisable[i]) {
RenderSystem.disableBufferBlend(idx);
} else {
final BlendState s = bufferOverrideStates[i];
RenderSystem.enableBufferBlend(idx);
RenderSystem.blendFuncSeparatei(idx, s.getSrcRgb(), s.getDstRgb(), s.getSrcAlpha(), s.getDstAlpha());
}
}
}
public static void restoreBlend() {
@@ -63,6 +113,8 @@ public class BlendModeStorage {
}
blendLocked = false;
hasDeferredChanges = false;
bufferOverrideCount = 0;
if (originalBlendEnable) {
GLStateManager.enableBlend();
@@ -689,7 +689,7 @@ public class ShadowRenderer {
// Render all opaque terrain unless pack requests not to
if (shouldRenderTerrain) {
mc.renderEngine.bindTexture(TextureMap.locationBlocksTexture);
rg.sortAndRender(mc.thePlayer, 0, playerCamera.getPartialTicks());
rg.sortAndRender(mc.renderViewEntity, 0, playerCamera.getPartialTicks());
}
// Reset viewport in case terrain rendering changed it
@@ -746,7 +746,7 @@ public class ShadowRenderer {
// It doesn't matter a ton, since this just means that they won't be sorted in the getNormal rendering pass.
// Just something to watch out for, however...
if (shouldRenderTranslucent) {
rg.sortAndRender(mc.thePlayer, 1, playerCamera.getPartialTicks());
rg.sortAndRender(mc.renderViewEntity, 1, playerCamera.getPartialTicks());
}
// Note: Apparently tripwire isn't rendered in the shadow pass.
@@ -1,7 +1,5 @@
package net.coderbot.iris.shaderpack.loading;
import com.gtnewhorizons.angelica.glsm.states.BlendState;
import net.coderbot.iris.gl.blending.BlendModeFunction;
import net.coderbot.iris.gl.blending.BlendModeOverride;
import java.util.Objects;
@@ -34,11 +32,8 @@ public enum ProgramId {
Entities(ProgramGroup.Gbuffers, "entities", TexturedLit),
EntitiesTrans(ProgramGroup.Gbuffers, "entities_translucent", Entities),
EntitiesGlowing(ProgramGroup.Gbuffers, "entities_glowing", Entities),
ArmorGlint(ProgramGroup.Gbuffers, "armor_glint", Textured,
new BlendModeOverride(new BlendState(BlendModeFunction.SRC_COLOR.getGlId(), BlendModeFunction.ONE.getGlId(), BlendModeFunction.ONE.getGlId(), BlendModeFunction.ZERO.getGlId()))),
// TODO: Figure out why this is needed in 2.x, this worked properly before without needing an override
SpiderEyes(ProgramGroup.Gbuffers, "spidereyes", Textured,
new BlendModeOverride(new BlendState(BlendModeFunction.SRC_ALPHA.getGlId(), BlendModeFunction.ONE.getGlId(), BlendModeFunction.ZERO.getGlId(), BlendModeFunction.ONE.getGlId()))),
ArmorGlint(ProgramGroup.Gbuffers, "armor_glint", Textured),
SpiderEyes(ProgramGroup.Gbuffers, "spidereyes", Textured),
Hand(ProgramGroup.Gbuffers, "hand", TexturedLit),
Weather(ProgramGroup.Gbuffers, "weather", TexturedLit),
@@ -69,4 +69,5 @@ options.total_stars=Star Density
options.total_stars.tooltip=Star Density
options.void_fog=Void Fog
options.void_fog.tooltip=Void Fog
options.hurt_shake=Hurt Screen Shake
options.background.random=Random
@@ -3,6 +3,7 @@ package com.gtnewhorizons.angelica.mixins.early.angelica;
import com.gtnewhorizons.angelica.compat.mojang.Camera;
import com.gtnewhorizons.angelica.mixins.interfaces.EntityRendererAccessor;
import com.gtnewhorizons.angelica.rendering.RenderingState;
import jss.notfine.core.Settings;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.EntityRenderer;
import net.minecraft.client.renderer.texture.DynamicTexture;
@@ -12,8 +13,10 @@ import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
import org.spongepowered.asm.mixin.gen.Invoker;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Constant;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.ModifyArg;
import org.spongepowered.asm.mixin.injection.ModifyConstant;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(EntityRenderer.class)
@@ -45,4 +48,10 @@ public abstract class MixinEntityRenderer implements EntityRendererAccessor {
RenderingState.INSTANCE.setFov(fov);
return fov;
}
@ModifyConstant(method = "hurtCameraEffect", constant = @Constant(floatValue = 14.0F))
private float angelica$hurtCameraEffect(float orig) {
int value = (int) Settings.HURT_SHAKE.option.getStore();
return orig * (value/100F);
}
}
@@ -120,7 +120,7 @@ public abstract class MixinFontRenderer implements FontRendererAccessor, IFontPa
@Inject(method = "<init>", at = @At("TAIL"))
private void angelica$injectBatcher(GameSettings settings, ResourceLocation fontLocation, TextureManager texManager,
boolean unicodeMode, CallbackInfo ci) {
angelica$batcher = new BatchingFontRenderer((FontRenderer) (Object) this, this.charWidth, this.glyphWidth, this.colorCode, this.locationFontTexture);
angelica$batcher = new BatchingFontRenderer((FontRenderer) (Object) this, this.charWidth, this.colorCode, this.locationFontTexture);
}
@Unique
@@ -7,6 +7,7 @@ import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.hudcaching.HUDCaching;
import net.minecraft.client.gui.Gui;
@@ -40,7 +41,9 @@ public class MixinGuiIngameForge_HUDCaching {
ci.cancel();
}
HUDCaching.disableHoloInventory();
if (AngelicaConfig.hudCachingActive) {
HUDCaching.disableHoloInventory();
}
}
@Inject(method = "renderPortal", at = @At("HEAD"), cancellable = true, remap = false)
@@ -13,17 +13,24 @@ public abstract class MixinTextureAtlasSprite implements SpriteExtension {
@Override
public void celeritas$markActive() {
((IPatchedTextureAtlasSprite) this).markNeedsAnimationUpdate();
if (this instanceof IPatchedTextureAtlasSprite patched) {
patched.markNeedsAnimationUpdate();
}
}
@Override
public boolean celeritas$shouldUpdate() {
return ((IPatchedTextureAtlasSprite) this).needsAnimationUpdate();
if (this instanceof IPatchedTextureAtlasSprite patched) {
return patched.needsAnimationUpdate();
}
return false;
}
@ModifyReturnValue(method = {"getMinU", "getInterpolatedU"}, at = @At("RETURN"))
private float celeritas$markActiveOnUVAccess(float original) {
((IPatchedTextureAtlasSprite) this).markNeedsAnimationUpdate();
if (this instanceof IPatchedTextureAtlasSprite patched) {
patched.markNeedsAnimationUpdate();
}
return original;
}
}
@@ -0,0 +1,49 @@
package com.gtnewhorizons.angelica.mixins.early.celeritas.frustum;
import com.gtnewhorizons.angelica.mixins.interfaces.ClippingHelperExt;
import net.minecraft.client.renderer.culling.ClippingHelper;
import org.joml.FrustumIntersection;
import org.joml.Matrix4f;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
@Mixin(ClippingHelper.class)
public class MixinClippingHelper implements ClippingHelperExt {
@Shadow public float[] projectionMatrix;
@Shadow public float[] modelviewMatrix;
@Unique private final FrustumIntersection celeritas$frustumIntersection = new FrustumIntersection();
@Unique private final Matrix4f celeritas$projMatrix = new Matrix4f();
@Unique private final Matrix4f celeritas$mvMatrix = new Matrix4f();
@Override
public FrustumIntersection celeritas$getFrustumIntersection() {
return this.celeritas$frustumIntersection;
}
@Override
public void celeritas$updateFrustumIntersection() {
this.celeritas$projMatrix.set(this.projectionMatrix);
this.celeritas$mvMatrix.set(this.modelviewMatrix);
this.celeritas$frustumIntersection.set(this.celeritas$projMatrix.mul(this.celeritas$mvMatrix));
}
/**
* @author mitchej123
* @reason Replace vanilla frustum check with JOML
*/
@Overwrite
public boolean isBoxInFrustum(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) {
if (Double.isInfinite(minX) || Double.isInfinite(minY) || Double.isInfinite(minZ)
|| Double.isInfinite(maxX) || Double.isInfinite(maxY) || Double.isInfinite(maxZ)) {
return true;
}
return this.celeritas$frustumIntersection.testAab(
(float) minX, (float) minY, (float) minZ,
(float) maxX, (float) maxY, (float) maxZ
);
}
}
@@ -0,0 +1,17 @@
package com.gtnewhorizons.angelica.mixins.early.celeritas.frustum;
import com.gtnewhorizons.angelica.mixins.interfaces.ClippingHelperExt;
import net.minecraft.client.renderer.culling.ClippingHelperImpl;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(ClippingHelperImpl.class)
public class MixinClippingHelperImpl {
@Inject(method = "init", at = @At("RETURN"))
private void celeritas$runUpdateFrustumIntersection(CallbackInfo ci) {
((ClippingHelperExt) this).celeritas$updateFrustumIntersection();
}
}
@@ -1,5 +1,6 @@
package com.gtnewhorizons.angelica.mixins.early.celeritas.frustum;
import com.gtnewhorizons.angelica.mixins.interfaces.ClippingHelperExt;
import net.minecraft.client.renderer.culling.ClippingHelper;
import net.minecraft.client.renderer.culling.Frustrum;
import org.embeddedt.embeddium.impl.render.viewport.Viewport;
@@ -19,7 +20,7 @@ public abstract class MixinFrustrum implements ViewportProvider {
// Shadow frustum subclasses override this via their own ViewportProvider impl.
// This default handles vanilla Frustrum only.
return new Viewport(
this.clippingHelper::isBoxInFrustum,
((ClippingHelperExt) this.clippingHelper).celeritas$getFrustumIntersection()::testAab,
new Vector3d(this.xPosition, this.yPosition, this.zPosition)
);
}
@@ -3,6 +3,9 @@ package com.gtnewhorizons.angelica.mixins.early.rendering;
import com.gtnewhorizons.angelica.AngelicaMod;
import com.gtnewhorizons.angelica.common.BlockError;
import com.gtnewhorizons.angelica.loading.AngelicaTweaker;
import com.gtnewhorizons.angelica.rendering.StateAwareTessellator;
import com.llamalad7.mixinextras.injector.ModifyExpressionValue;
import com.llamalad7.mixinextras.sugar.Local;
import cpw.mods.fml.client.registry.RenderingRegistry;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet;
@@ -11,16 +14,23 @@ import net.coderbot.iris.block_rendering.BlockRenderingSettings;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess;
import org.objectweb.asm.Opcodes;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(RenderBlocks.class)
public abstract class MixinRenderBlocks {
@Shadow
public abstract boolean renderStandardBlockWithColorMultiplier(Block p_147736_1_, int p_147736_2_, int p_147736_3_, int p_147736_4_, float p_147736_5_, float p_147736_6_, float p_147736_7_);
@Unique
private static final ObjectOpenHashSet<String> isbrhExceptionCache = new ObjectOpenHashSet<>();
@@ -36,6 +46,8 @@ public abstract class MixinRenderBlocks {
@Unique
private boolean isRenderingByType = false;
private boolean applyingCeleritasAO = false;
@Inject(method = "renderBlockByRenderType", at = @At("HEAD"))
private void renderingByTypeEnable(CallbackInfoReturnable<Boolean> ci) {
this.isRenderingByType = true;
@@ -84,14 +96,37 @@ public abstract class MixinRenderBlocks {
return handleISBRHException(rb, world, x, y, z, block, modelId);
}
@Redirect(method = "renderStandardBlock", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Minecraft;isAmbientOcclusionEnabled()Z"))
private boolean checkAOEnabled() {
/**
* @author embeddedt
* @reason When vanilla would render with AO, hijack the rendering logic and render using flat lighting instead.
*/
@Inject(method = { "renderStandardBlockWithAmbientOcclusion", "renderStandardBlockWithAmbientOcclusionPartial" }, at = @At("HEAD"), cancellable = true)
private void handleCeleritasAo(Block block, int x, int y, int z, float r, float g, float b, CallbackInfoReturnable<Boolean> cir) {
if ((this.isRenderingByType && Minecraft.isAmbientOcclusionEnabled() && AngelicaMod.options().quality.useCeleritasSmoothLighting) ||
(Iris.enabled && BlockRenderingSettings.INSTANCE.shouldUseSeparateAo())) {
return false; // Force sodium pipeline with Iris or for standard blocks rendered from renderBlockByRenderType when using AO
this.applyingCeleritasAO = true;
try {
cir.setReturnValue(this.renderStandardBlockWithColorMultiplier(block, x, y, z, r, g, b));
} finally {
this.applyingCeleritasAO = false;
}
}
}
return Minecraft.isAmbientOcclusionEnabled();
/* Disable diffuse when celeritas AO is in use */
@ModifyExpressionValue(method = "renderStandardBlockWithColorMultiplier", at = @At(value = "CONSTANT", args = "floatValue=0.5", ordinal = 0))
private float noBottomDiffuse(float original) {
return this.applyingCeleritasAO ? 1.0f : original;
}
@ModifyExpressionValue(method = "renderStandardBlockWithColorMultiplier", at = @At(value = "CONSTANT", args = "floatValue=0.6", ordinal = 0))
private float noXDiffuse(float original) {
return this.applyingCeleritasAO ? 1.0f : original;
}
@ModifyExpressionValue(method = "renderStandardBlockWithColorMultiplier", at = @At(value = "CONSTANT", args = "floatValue=0.8", ordinal = 0))
private float noZDiffuse(float original) {
return this.applyingCeleritasAO ? 1.0f : original;
}
@SuppressWarnings("deprecation")
@@ -113,4 +148,20 @@ public abstract class MixinRenderBlocks {
}
return false;
}
@ModifyExpressionValue(method = { "renderFaceXPos", "renderFaceYPos", "renderFaceZPos",
"renderFaceXNeg", "renderFaceYNeg", "renderFaceZNeg" },
at = @At(value = "FIELD", opcode = Opcodes.GETFIELD, target = "Lnet/minecraft/client/renderer/RenderBlocks;enableAO:Z"))
private boolean applyAOBrightness(boolean original, @Local(ordinal = 0) Tessellator tessellator) {
((StateAwareTessellator)tessellator).angelica$setAppliedAo(this.applyingCeleritasAO);
return original;
}
@Inject(method = { "renderFaceXPos", "renderFaceYPos", "renderFaceZPos",
"renderFaceXNeg", "renderFaceYNeg", "renderFaceZNeg" },
at = @At("RETURN"))
private void resetAOFlag(Block p_147764_1_, double p_147764_2_, double p_147764_4_, double p_147764_6_, IIcon p_147764_8_, CallbackInfo ci,
@Local(ordinal = 0) Tessellator tessellator) {
((StateAwareTessellator)tessellator).angelica$setAppliedAo(false);
}
}
@@ -0,0 +1,43 @@
package com.gtnewhorizons.angelica.mixins.early.rendering;
import com.gtnewhorizons.angelica.rendering.StateAwareTessellator;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import net.minecraft.client.renderer.Tessellator;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(Tessellator.class)
public class MixinTessellator implements StateAwareTessellator {
@Unique
private final IntArrayList vertexStates = new IntArrayList();
@Unique
private boolean appliedAo;
@Inject(method = "addVertex", at = @At("RETURN"))
private void addElementState(CallbackInfo ci) {
int state = 0;
if (appliedAo) {
state |= StateAwareTessellator.RENDERED_WITH_VANILLA_AO;
}
this.vertexStates.add(state);
}
@Inject(method = "reset", at = @At("RETURN"))
private void resetVertexStates(CallbackInfo ci) {
this.vertexStates.clear();
}
@Override
public void angelica$setAppliedAo(boolean flag) {
this.appliedAo = flag;
}
@Override
public int[] angelica$getVertexStates() {
return this.vertexStates.elements();
}
}
@@ -2,7 +2,10 @@ package com.gtnewhorizons.angelica.mixins.early.rendering;
import com.gtnewhorizons.angelica.mixins.interfaces.ITileEntityBoundingBoxCache;
import com.gtnewhorizons.angelica.rendering.TileEntityRenderBoundsRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.world.World;
@@ -20,7 +23,27 @@ public abstract class MixinTileEntity implements ITileEntityBoundingBoxCache {
@Shadow public int yCoord;
@Shadow public int zCoord;
@Shadow public abstract AxisAlignedBB getRenderBoundingBox();
@Shadow(remap = false) public static final AxisAlignedBB INFINITE_EXTENT_AABB = null;
/**
* @author mitchej123
* @reason Less fallback to INFINITE_EXTENT_AABB for blocks like signs,
*/
@Overwrite(remap = false)
@SideOnly(Side.CLIENT)
public AxisAlignedBB getRenderBoundingBox() {
final Block type = getBlockType();
AxisAlignedBB bb = INFINITE_EXTENT_AABB;
if (type == Blocks.enchanting_table) {
bb = AxisAlignedBB.getBoundingBox(xCoord, yCoord, zCoord, xCoord + 1, yCoord + 1, zCoord + 1);
} else if (type == Blocks.chest || type == Blocks.trapped_chest) {
bb = AxisAlignedBB.getBoundingBox(xCoord - 1, yCoord, zCoord - 1, xCoord + 2, yCoord + 2, zCoord + 2);
} else if (type != null && type != Blocks.beacon) {
final AxisAlignedBB cbb = type.getCollisionBoundingBoxFromPool(worldObj, xCoord, yCoord, zCoord);
bb = cbb != null ? cbb : AxisAlignedBB.getBoundingBox(xCoord, yCoord, zCoord, xCoord + 1, yCoord + 1, zCoord + 1);
}
return bb;
}
@Unique private int angelica$cachedBBX = Integer.MIN_VALUE;
@Unique private int angelica$cachedBBY = Integer.MIN_VALUE;
@@ -0,0 +1,98 @@
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizons.angelica.AngelicaExtension;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL30;
import static com.gtnewhorizons.angelica.util.GLSMUtil.resetGLState;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Tests for {@link com.gtnewhorizons.angelica.glsm.states.BooleanState#setUnknownState()}.
* Verifies that per-buffer blend operations (glEnablei/glDisablei) properly invalidate
* the GLSM blend cache so subsequent global blend enable/disable calls are not skipped.
*/
@ExtendWith(AngelicaExtension.class)
class GLSM_BlendUnknownState_UnitTest {
@BeforeEach
void setUp() {
resetGLState();
}
@AfterEach
void tearDown() {
resetGLState();
}
@Test
void testSetUnknownStateForcesCacheBypass() {
// Enable blend via GLSM — both cache and GL should agree
GLStateManager.enableBlend();
assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "GL blend should be enabled");
assertTrue(GLStateManager.getBlendMode().isEnabled(), "GLSM blend cache should be enabled");
// Simulate a per-buffer disable that bypasses the cache (as glDisablei does)
GL30.glDisablei(GL11.GL_BLEND, 0);
GLStateManager.getBlendMode().setUnknownState();
// Cache still says enabled, but GL state for buffer 0 is now disabled
assertTrue(GLStateManager.getBlendMode().isEnabled(), "GLSM cache should still say enabled");
// Re-enable blend via GLSM — without setUnknownState, this would be a no-op
// because the cache thinks blend is already enabled
GLStateManager.enableBlend();
// Per GL spec, glEnable(GL_BLEND) enables blend for ALL draw buffers,
// overriding any per-buffer disables
assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "GL blend should be re-enabled after setUnknownState");
}
@Test
void testDisableBufferBlendInvalidatesCache() {
GLStateManager.enableBlend();
assertTrue(GL11.glIsEnabled(GL11.GL_BLEND));
// Use RenderSystem which should call setUnknownState internally
RenderSystem.disableBufferBlend(0);
// Now re-enable via GLSM — should issue the GL call
GLStateManager.enableBlend();
assertTrue(GL11.glIsEnabled(GL11.GL_BLEND), "Blend should be re-enabled after disableBufferBlend");
}
@Test
void testEnableBufferBlendInvalidatesCache() {
// Start with blend disabled
GLStateManager.disableBlend();
assertFalse(GL11.glIsEnabled(GL11.GL_BLEND));
// Per-buffer enable bypasses cache
RenderSystem.enableBufferBlend(0);
// Disable via GLSM — should issue the GL call despite cache saying disabled
GLStateManager.disableBlend();
assertFalse(GL11.glIsEnabled(GL11.GL_BLEND), "Blend should be disabled after enableBufferBlend + disableBlend");
}
@Test
void testUnknownStateClearedAfterSetEnabled() {
GLStateManager.enableBlend();
// Mark unknown
GLStateManager.getBlendMode().setUnknownState();
// First setEnabled clears the unknown flag
GLStateManager.enableBlend();
// Second setEnabled should use normal caching (no redundant GL call)
// Verify state is consistent
assertTrue(GL11.glIsEnabled(GL11.GL_BLEND));
assertTrue(GLStateManager.getBlendMode().isEnabled());
}
}