POM Support (#1927)

Co-authored-by: Jason Mitchell <[email protected]>
This commit is contained in:
Eclipse-SolandJason Mitchell authored and GitHub committed 2026-09-03 22:28:20 -07:00
1 parent 0dfffca88e
commit ffc324bab6
38 files changed
+1920 -166

No files matched your search

@@ -61,13 +61,17 @@ public class NativeImage extends BufferedImage {
// final int width = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, level, GL11.GL_TEXTURE_WIDTH);
// final int height = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, level, GL11.GL_TEXTURE_HEIGHT);
final IntBuffer buffer = MemoryUtilities.memAllocInt(size);
final int pixels = width * height;
final IntBuffer buffer = MemoryUtilities.memAllocInt(pixels);
try {
GLStateManager.glGetTexImage(GL11.GL_TEXTURE_2D, level, format.glFormat, GL12.GL_UNSIGNED_INT_8_8_8_8_REV, buffer);
int[] data = new int[size];
buffer.get(data);
int[] data = new int[pixels];
buffer.get(data, 0, pixels);
for (int i = 0; i < pixels; i++) {
data[i] = swapRedBlue(data[i]);
}
setRGB(0, 0, width, height, data, 0, width);
} finally {
MemoryUtilities.memFree(buffer);
@@ -90,7 +94,7 @@ public class NativeImage extends BufferedImage {
}
public static int getR(int i) {
return i >> 0 & 255;
return i & 255;
}
public static int getG(int i) {
@@ -102,11 +106,15 @@ public class NativeImage extends BufferedImage {
}
public int getPixelRGBA(int x, int y) {
return getRGB(x, y);
return swapRedBlue(getRGB(x, y));
}
public void setPixelRGBA(int x, int y, int rgb) {
setRGB(x, y, rgb);
setRGB(x, y, swapRedBlue(rgb));
}
private static int swapRedBlue(int c) {
return (c & 0xFF00FF00) | ((c >>> 16) & 0xFF) | ((c & 0xFF) << 16);
}
@@ -0,0 +1,315 @@
package com.gtnewhorizons.angelica.iris;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.ffp.FfpExtendedAttribs;
import com.gtnewhorizons.angelica.glsm.hooks.ImmediateExtendedAttribHandler;
import com.gtnewhorizons.angelica.rendering.items.ItemRenderListManager;
import com.gtnewhorizons.angelica.rendering.tesr.TesrBatchRenderer;
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
import net.coderbot.iris.Iris;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.ITextureObject;
import net.minecraft.client.renderer.texture.TextureMap;
import net.coderbot.iris.vertices.IrisQuadView;
import net.coderbot.iris.vertices.NormI8;
import net.coderbot.iris.vertices.NormalHelper;
import org.joml.Vector3f;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetFloat;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutFloat;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutInt;
/**
* Supplies per-quad {@code mc_midTexCoord} + {@code at_tangent} for immediate-mode draws so parallax/POM shader packs
* reconstruct sprite bounds correctly.
*/
public final class ImmediateExtendedAttribs implements ImmediateExtendedAttribHandler {
private static final int VERTEX_SIZE = 8;
private static final int X = 0, Y = 1, Z = 2, U = 3, V = 4;
private static final float UV_EPS = 1.0e-5f;
private static final float POM_SUPPRESS_EPS = 1.0e-4f;
private static final float POM_MAX_TILE_EXTENT = 0.125f;
private static final int WANTS_MID = 1;
private static final int WANTS_TANGENT = 2;
private static final int NEUTRAL_TANGENT = NormI8.pack(1.0f, 0.0f, 0.0f, 1.0f);
private static volatile int currentProgramWants = 0;
private static final Int2IntOpenHashMap programWantsExtCache = new Int2IntOpenHashMap();
public static void onProgramBound(int program) {
if (program == 0) {
currentProgramWants = 0;
return;
}
int wants;
if (programWantsExtCache.containsKey(program)) {
wants = programWantsExtCache.get(program);
} else {
wants = 0;
if (GLStateManager.glGetAttribLocation(program, "mc_midTexCoord") >= 0) wants |= WANTS_MID;
if (GLStateManager.glGetAttribLocation(program, "at_tangent") >= 0) wants |= WANTS_TANGENT;
programWantsExtCache.put(program, wants);
}
currentProgramWants = wants;
}
public static void onProgramDeleted(int program) {
programWantsExtCache.remove(program);
}
public static void onShaderPackChanged() {
currentProgramWants = 0;
programWantsExtCache.clear();
ItemRenderListManager.clearCache();
FfpExtendedAttribs.reset();
TesrBatchRenderer.INSTANCE.clearRetained();
}
private final Vector3f normal = new Vector3f();
private final QuadView quad = new QuadView();
private final PackedQuadView packedQuad = new PackedQuadView();
private boolean limitTileExtent = true;
private boolean needTangent = true;
@Override
public boolean wantsExtended() {
return Iris.enabled && currentProgramWants != 0 && GLStateManager.getActiveProgram() != 0;
}
@Override
public boolean wantsTangent() {
return (currentProgramWants & WANTS_TANGENT) != 0;
}
@Override
public boolean wantsExtendedCapture() {
return Iris.enabled && Iris.getCurrentPack().isPresent();
}
@Override
public void build(int[] rawBuffer, int vertexCount, int vertsPerPrim, int normalIntIndex, long dstAddr, int dstStride) {
final boolean smooth = normalIntIndex >= 0;
limitTileExtent = isAtlasNotBound();
needTangent = wantsTangent();
long ptr = dstAddr;
for (int v = 0; v < vertexCount; v += vertsPerPrim) {
quad.setup(rawBuffer, v, normalIntIndex);
if (vertsPerPrim == 4) {
writeQuadExt(quad, ptr, dstStride);
} else {
writeTriExt(quad, smooth, ptr, dstStride);
}
ptr += (long) dstStride * vertsPerPrim;
}
}
@Override
public void buildPacked(long srcBase, int stride, int posOffset, int texOffset, int normalOffset,
int vertexCount, int vertsPerPrim, long dstAddr, int dstStride) {
final boolean smooth = normalOffset >= 0;
limitTileExtent = isAtlasNotBound();
needTangent = wantsTangent();
long ptr = dstAddr;
for (int v = 0; v < vertexCount; v += vertsPerPrim) {
packedQuad.setup(srcBase + (long) v * stride, stride, posOffset, texOffset, normalOffset);
if (vertsPerPrim == 4) {
writeQuadExt(packedQuad, ptr, dstStride);
} else {
writeTriExt(packedQuad, smooth, ptr, dstStride);
}
ptr += (long) dstStride * vertsPerPrim;
}
}
private void writeQuadExt(IrisQuadView quad, long dstAddr, int dstStride) {
final float u0 = quad.u(0), u1 = quad.u(1), u2 = quad.u(2), u3 = quad.u(3);
final float v0 = quad.v(0), v1 = quad.v(1), v2 = quad.v(2), v3 = quad.v(3);
final float umin = min4(u0, u1, u2, u3), umax = max4(u0, u1, u2, u3);
final float vmin = min4(v0, v1, v2, v3), vmax = max4(v0, v1, v2, v3);
final boolean tileable = formsRectAxisQuad(u0, u1, u2, u3) && formsRectAxisQuad(v0, v1, v2, v3)
&& (!limitTileExtent || ((umax - umin) <= POM_MAX_TILE_EXTENT && (vmax - vmin) <= POM_MAX_TILE_EXTENT));
final int tangent;
if (needTangent) {
NormalHelper.computeFaceNormal(normal, quad);
tangent = NormalHelper.computeTangent(normal.x, normal.y, normal.z, quad);
} else {
tangent = NEUTRAL_TANGENT;
}
long ptr = dstAddr;
if (!tileable) {
for (int i = 0; i < 4; i++) {
memPutFloat(ptr, quad.u(i) + POM_SUPPRESS_EPS);
memPutFloat(ptr + 4, quad.v(i) + POM_SUPPRESS_EPS);
memPutInt(ptr + 8, tangent);
ptr += dstStride;
}
return;
}
final float midU = (umin + umax) * 0.5f;
final float midV = (vmin + vmax) * 0.5f;
for (int i = 0; i < 4; i++) {
memPutFloat(ptr, midU);
memPutFloat(ptr + 4, midV);
memPutInt(ptr + 8, tangent);
ptr += dstStride;
}
}
private void writeTriExt(NormalSource view, boolean smooth, long dstAddr, int dstStride) {
final float u0 = view.u(0), u1 = view.u(1), u2 = view.u(2);
final float v0 = view.v(0), v1 = view.v(1), v2 = view.v(2);
final float umin = Math.min(u0, Math.min(u1, u2)), umax = Math.max(u0, Math.max(u1, u2));
final float vmin = Math.min(v0, Math.min(v1, v2)), vmax = Math.max(v0, Math.max(v1, v2));
final boolean tileable = formsRectAxis(u0, u1, u2) && formsRectAxis(v0, v1, v2)
&& (!limitTileExtent || ((umax - umin) <= POM_MAX_TILE_EXTENT && (vmax - vmin) <= POM_MAX_TILE_EXTENT));
if (!tileable) {
writeTriSuppressed(view, dstAddr, dstStride);
return;
}
final float midU = (umin + umax) * 0.5f;
final float midV = (vmin + vmax) * 0.5f;
long ptr = dstAddr;
if (smooth) {
for (int i = 0; i < 3; i++) {
final int n = view.packedNormal(i);
final int tangent = needTangent
? NormalHelper.computeTangentSmooth(NormI8.unpackX(n), NormI8.unpackY(n), NormI8.unpackZ(n), view)
: NEUTRAL_TANGENT;
memPutFloat(ptr, midU);
memPutFloat(ptr + 4, midV);
memPutInt(ptr + 8, tangent);
ptr += dstStride;
}
} else {
final int tangent;
if (needTangent) {
NormalHelper.computeFaceNormalTri(normal, view);
tangent = NormalHelper.computeTangent(normal.x, normal.y, normal.z, view);
} else {
tangent = NEUTRAL_TANGENT;
}
for (int i = 0; i < 3; i++) {
memPutFloat(ptr, midU);
memPutFloat(ptr + 4, midV);
memPutInt(ptr + 8, tangent);
ptr += dstStride;
}
}
}
private void writeTriSuppressed(NormalSource view, long dstAddr, int dstStride) {
final int tangent;
if (needTangent) {
NormalHelper.computeFaceNormalTri(normal, view);
tangent = NormalHelper.computeTangent(normal.x, normal.y, normal.z, view);
} else {
tangent = NEUTRAL_TANGENT;
}
long ptr = dstAddr;
for (int i = 0; i < 3; i++) {
memPutFloat(ptr, view.u(i) + POM_SUPPRESS_EPS);
memPutFloat(ptr + 4, view.v(i) + POM_SUPPRESS_EPS);
memPutInt(ptr + 8, tangent);
ptr += dstStride;
}
}
private static boolean formsRectAxis(float a, float b, float c) {
final boolean ab = Math.abs(a - b) <= UV_EPS;
final boolean ac = Math.abs(a - c) <= UV_EPS;
final boolean bc = Math.abs(b - c) <= UV_EPS;
return (ab || ac || bc) && !(ab && ac && bc);
}
private static boolean formsRectAxisQuad(float a, float b, float c, float d) {
final float lo = min4(a, b, c, d), hi = max4(a, b, c, d);
if (hi - lo <= UV_EPS) return false;
return atEdge(a, lo, hi) && atEdge(b, lo, hi) && atEdge(c, lo, hi) && atEdge(d, lo, hi);
}
private static boolean atEdge(float x, float lo, float hi) {
return Math.abs(x - lo) <= UV_EPS || Math.abs(x - hi) <= UV_EPS;
}
private static boolean isAtlasNotBound() {
final int tex = GLStateManager.getBoundTextureForServerState(0);
if (tex <= 0) return true;
final Minecraft mc = Minecraft.getMinecraft();
if (mc == null || mc.getTextureManager() == null) return true;
final ITextureObject blocks = mc.getTextureManager().getTexture(TextureMap.locationBlocksTexture);
if (blocks != null && blocks.getGlTextureId() == tex) return false;
final ITextureObject items = mc.getTextureManager().getTexture(TextureMap.locationItemsTexture);
return items == null || items.getGlTextureId() != tex;
}
private static float min4(float a, float b, float c, float d) {
return Math.min(Math.min(a, b), Math.min(c, d));
}
private static float max4(float a, float b, float c, float d) {
return Math.max(Math.max(a, b), Math.max(c, d));
}
private interface NormalSource extends IrisQuadView {
int packedNormal(int i);
}
private static final class QuadView implements NormalSource {
private int[] raw;
private int base;
private int normalIndex;
void setup(int[] raw, int firstVertex, int normalIndex) {
this.raw = raw;
this.base = firstVertex;
this.normalIndex = normalIndex;
}
@Override public float x(int i) { return Float.intBitsToFloat(raw[(base + i) * VERTEX_SIZE + X]); }
@Override public float y(int i) { return Float.intBitsToFloat(raw[(base + i) * VERTEX_SIZE + Y]); }
@Override public float z(int i) { return Float.intBitsToFloat(raw[(base + i) * VERTEX_SIZE + Z]); }
@Override public float u(int i) { return Float.intBitsToFloat(raw[(base + i) * VERTEX_SIZE + U]); }
@Override public float v(int i) { return Float.intBitsToFloat(raw[(base + i) * VERTEX_SIZE + V]); }
@Override public int packedNormal(int i) { return raw[(base + i) * VERTEX_SIZE + normalIndex]; }
}
private static final class PackedQuadView implements NormalSource {
private long base;
private int stride;
private int posOffset;
private int texOffset;
private int normalOffset;
void setup(long base, int stride, int posOffset, int texOffset, int normalOffset) {
this.base = base;
this.stride = stride;
this.posOffset = posOffset;
this.texOffset = texOffset;
this.normalOffset = normalOffset;
}
@Override public float x(int i) { return memGetFloat(base + (long) i * stride + posOffset); }
@Override public float y(int i) { return memGetFloat(base + (long) i * stride + posOffset + 4); }
@Override public float z(int i) { return memGetFloat(base + (long) i * stride + posOffset + 8); }
@Override public float u(int i) { return memGetFloat(base + (long) i * stride + texOffset); }
@Override public float v(int i) { return memGetFloat(base + (long) i * stride + texOffset + 4); }
@Override public int packedNormal(int i) { return memGetInt(base + (long) i * stride + normalOffset); }
}
}
@@ -67,6 +67,10 @@ public class IrisGLSMBridge {
StateUpdateNotifiers.colorModulatorNotifier = listener -> colorModulatorListener = listener;
}
public static void installImmediateExtendedHandler() {
GLSMHooks.immediateExtendedHandler = new ImmediateExtendedAttribs();
}
public static void installPostTransformHook() {
if (GLSMHooks.postTransformProcessor != null) return;
GLSMHooks.postTransformProcessor = new ShaderTransformPostProcessor() {
@@ -298,6 +302,14 @@ public class IrisGLSMBridge {
}
});
GLSMHooks.PROGRAM_CHANGE.addListener(event -> {
if (Iris.enabled && event.postBind) {
ImmediateExtendedAttribs.onProgramBound(event.newProgram);
}
});
GLSMHooks.PROGRAM_DELETE.addListener(event -> ImmediateExtendedAttribs.onProgramDeleted(event.program));
GLSMHooks.PROGRAM_CHANGE.addListener(event -> {
if (!Iris.enabled) return;
if (event.postBind) return;
@@ -97,6 +97,12 @@ import net.coderbot.iris.client.IrisDebugScreenHandler;
public final class ClientProxy extends CommonProxy {
/**
* So you don't need to be in a dev env to have access to the commands.
* Do not commit with this set to true.
*/
private static final boolean FORCE_DEBUG_MODE = false;
public static BlockError blockError;
public static final ManagedEnum<AnimationMode> animationsMode = new ManagedEnum<>(AnimationMode.VISIBLE_ONLY);
private static final Logger LOGGER = LogManager.getLogger("Angelica");
@@ -136,6 +142,7 @@ public final class ClientProxy extends CommonProxy {
ModelRegistry.registerModid(MOD_ID);
blockError = new BlockError();
if (AngelicaConfig.enableIris) {
IrisGLSMBridge.installImmediateExtendedHandler();
Iris.warmupShaderTransforms();
}
}
@@ -190,7 +197,7 @@ public final class ClientProxy extends CommonProxy {
}
// Debug tooling
if (!AngelicaClientTweaker.isObfEnv()) {
if (FORCE_DEBUG_MODE || !AngelicaClientTweaker.isObfEnv()) {
ClientCommandHandler.instance.registerCommand(new AngelicaCommand());
FMLCommonHandler.instance().bus().register(FlybyRunner.INSTANCE);
@@ -45,6 +45,7 @@ import com.gtnewhorizons.angelica.compat.cubicchunks.CubicChunksAPI;
import com.gtnewhorizons.angelica.dynamiclights.DynamicLights;
import com.gtnewhorizons.angelica.dynamiclights.IDynamicLightWorldRenderer;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.ffp.FfpExtendedAttribs;
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
import com.gtnewhorizons.angelica.mixins.interfaces.ITileEntityBoundingBoxCache;
import com.gtnewhorizons.angelica.mixins.interfaces.OverridesShouldRenderInPass;
@@ -168,6 +169,7 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
TesrBatchRenderer.INSTANCE.clearRetained();
ModelPartBatcher.INSTANCE.clear();
GpuCulling.onWorldUnload();
FfpExtendedAttribs.reset();
BopFogBlend.invalidate();
FogBiomeCache.invalidate();
super.unloadWorld();
@@ -31,7 +31,11 @@ import com.gtnewhorizon.gtnhlib.client.renderer.vao.IVertexArrayObject;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.IndexBuffer;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.VAOManager;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks;
import com.gtnewhorizons.angelica.glsm.hooks.ImmediateExtendedAttribHandler;
import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap;
import lombok.Data;
@@ -39,6 +43,13 @@ import lombok.NoArgsConstructor;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.IReloadableResourceManager;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL15;
import java.nio.ByteBuffer;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memCalloc;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memFree;
public class ItemRenderListManager {
// Least used element is at position 0. This is in theory slightly faster.
@@ -102,18 +113,21 @@ public class ItemRenderListManager {
public static void registerReloadListener(){
IReloadableResourceManager resourceManager = (IReloadableResourceManager) Minecraft.getMinecraft()
.getResourceManager();
resourceManager.registerReloadListener(_ -> {
for (CachedVBO value : vboCache.values()) {
value.delete();
}
vboCache.clear();
});
resourceManager.registerReloadListener(_ -> clearCache());
}
public static void clearCache() {
for (CachedVBO value : vboCache.values()) {
value.delete();
}
vboCache.clear();
}
public static final class CachedVBO {
private final IVertexArrayObject vertexBuffer;
private final IndexBuffer ebo;
private int expiry;
private int extVbo = 0;
public CachedVBO() {
this.ebo = new IndexBuffer();
@@ -126,6 +140,59 @@ public class ItemRenderListManager {
private void allocate(DirectTessellator tessellator) {
tessellator.allocateToVBO(vertexBuffer, ebo);
attachExtAttribs(tessellator);
}
private void attachExtAttribs(DirectTessellator tessellator) {
final ImmediateExtendedAttribHandler handler = GLSMHooks.immediateExtendedHandler;
final VertexFormat format = tessellator.getVertexFormat();
final int vertexCount = tessellator.getVertexCount();
final int extPrim = handler == null ? 0 : ImmediateExtendedAttribHandler.extPrimVerts(tessellator.getDrawMode(), vertexCount);
final boolean capture = handler != null && format != null && format.hasTexture()
&& extPrim != 0
&& (extVbo != 0 || handler.wantsExtendedCapture());
if (!capture) {
detachExtAttribs();
return;
}
final int extStride = ImmediateExtendedAttribHandler.EXT_STRIDE;
final int stride = format.getVertexSize();
final int texOffset = ImmediateExtendedAttribHandler.texOffset(format);
final int normalOffset = ImmediateExtendedAttribHandler.normalOffset(format);
final ByteBuffer packed = tessellator.getWriteBuffer();
final long srcBase = memAddress0(packed) + packed.position();
final ByteBuffer ext = memCalloc(vertexCount, extStride);
handler.buildPacked(srcBase, stride, 0, texOffset, normalOffset, vertexCount, extPrim, memAddress0(ext), extStride);
final boolean firstAttach = extVbo == 0;
if (firstAttach) {
extVbo = GLStateManager.glGenBuffers();
}
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, extVbo);
ext.position(0).limit(vertexCount * extStride);
GLStateManager.glBufferData(GL15.GL_ARRAY_BUFFER, ext, GL15.GL_STATIC_DRAW);
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
memFree(ext);
if (firstAttach) {
vertexBuffer.bind();
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, extVbo);
ImmediateExtendedAttribHandler.setupExtAttribPointers(0L, extStride);
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
vertexBuffer.unbind();
}
}
private void detachExtAttribs() {
if (extVbo == 0) return;
vertexBuffer.bind();
GLStateManager.glDisableVertexAttribArray(ImmediateExtendedAttribHandler.LOC_MID_TEX);
GLStateManager.glDisableVertexAttribArray(ImmediateExtendedAttribHandler.LOC_TANGENT);
vertexBuffer.unbind();
GLStateManager.glDeleteBuffers(extVbo);
extVbo = 0;
}
private void render(int elapsedTicks) {
@@ -136,6 +203,10 @@ public class ItemRenderListManager {
private void delete() {
vertexBuffer.delete();
// EBO gets deleted by vertexBuffer.delete()
if (extVbo != 0) {
GLStateManager.glDeleteBuffers(extVbo);
extVbo = 0;
}
}
}
@@ -2,6 +2,9 @@ package com.gtnewhorizons.angelica.rendering.tesr;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.hooks.ImmediateExtendedAttribHandler;
import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks;
import com.gtnewhorizons.angelica.glsm.ffp.FfpExtendedAttribs;
import com.gtnewhorizons.angelica.glsm.ffp.InstancedAttribs;
import com.gtnewhorizons.angelica.glsm.ffp.VAOManager;
import com.gtnewhorizons.angelica.glsm.streaming.OrphanStreamingBuffer;
@@ -17,6 +20,8 @@ import org.lwjgl.opengl.GL15;
import java.nio.ByteBuffer;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memCalloc;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memFree;
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.COLOR_INDEX;
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.NORMAL_INDEX;
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.TEX_X_INDEX;
@@ -34,6 +39,7 @@ final class InstancedTemplateRenderer {
private static final class TemplateMesh {
int vao;
int vbo;
int extVbo;
int vertexCount;
int drawMode;
long lastUsedMs;
@@ -96,6 +102,10 @@ final class InstancedTemplateRenderer {
int draws = 0;
long recordOffset = ringBase;
final int ringId = uploadBufferId;
final ImmediateExtendedAttribHandler extHandler = GLSMHooks.immediateExtendedHandler;
if (extHandler != null && extHandler.wantsExtended()) {
FfpExtendedAttribs.setNeutralCurrentValues();
}
GLStateManager.instancedFfpDrawActive = true;
for (int b = 0, n = liveBuckets.size(); b < n; b++) {
final Bucket bucket = liveBuckets.get(b);
@@ -179,6 +189,13 @@ final class InstancedTemplateRenderer {
GLStateManager.glVertexAttribPointer(4, 3, GL11.GL_BYTE, true, TEMPLATE_STRIDE, NORMAL_INDEX * 4L);
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
mesh.extVbo = buildExt(template);
if (mesh.extVbo != 0) {
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, mesh.extVbo);
ImmediateExtendedAttribHandler.setupExtAttribPointers(0L, ImmediateExtendedAttribHandler.EXT_STRIDE);
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
}
for (int loc = InstancedAttribs.LOC_MATRIX_COL0; loc <= InstancedAttribs.LOC_LIGHTMAP; loc++) {
GLStateManager.glEnableVertexAttribArray(loc);
GLStateManager.glVertexAttribDivisor(loc, 1);
@@ -188,6 +205,25 @@ final class InstancedTemplateRenderer {
return mesh;
}
private static int buildExt(TemplateBuffer template) {
final ImmediateExtendedAttribHandler handler = GLSMHooks.immediateExtendedHandler;
if (handler == null || !handler.wantsExtendedCapture()) return 0;
final int extPrim = ImmediateExtendedAttribHandler.extPrimVerts(template.drawMode, template.vertexCount);
if (extPrim == 0) return 0;
final int extStride = ImmediateExtendedAttribHandler.EXT_STRIDE;
final ByteBuffer ext = memCalloc(template.vertexCount, extStride);
handler.build(template.data, template.vertexCount, extPrim,
ImmediateExtendedAttribHandler.RAW_NORMAL_INDEX, memAddress0(ext), extStride);
final int extVbo = GLStateManager.glGenBuffers();
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, extVbo);
ext.position(0).limit(template.vertexCount * extStride);
GLStateManager.glBufferData(GL15.GL_ARRAY_BUFFER, ext, GL15.GL_STATIC_DRAW);
memFree(ext);
return extVbo;
}
void endFrame() {
if (ringUsedThisFrame && persistentRing != null) {
persistentRing.postDraw();
@@ -215,6 +251,7 @@ final class InstancedTemplateRenderer {
private static void delete(TemplateMesh mesh) {
GLStateManager.glDeleteBuffers(mesh.vbo);
if (mesh.extVbo != 0) GLStateManager.glDeleteBuffers(mesh.extVbo);
GLStateManager.glDeleteVertexArrays(mesh.vao);
}
@@ -250,8 +250,8 @@ public class ColorizeBlock {
}
colorMap = wrapBlockMap(colorMap);
for (String idString : idList.split("\\s+")) {
BlockStateMatcher blockMatcher = BlockAPI.createMatcher(new PropertiesFile(logger, resource), idString);
if (blockMatcher != null) {
for (BlockStateMatcher blockMatcher : BlockAPI
.createMatchers(new PropertiesFile(logger, resource), idString)) {
List<BlockStateMatcher> maps = blockColorMaps
.computeIfAbsent(blockMatcher.getBlock(), k -> new ArrayList<>());
blockMatcher.setData(colorMap);
@@ -13,6 +13,7 @@ import java.util.function.Consumer;
import com.github.bsideup.jabel.Desugar;
import net.minecraft.block.Block;
import net.minecraft.client.resources.IResourcePack;
import net.minecraft.util.IIcon;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.IBlockAccess;
@@ -25,6 +26,7 @@ import com.prupe.mcpatcher.mal.block.RenderBlocksUtils;
import com.prupe.mcpatcher.mal.block.RenderPassAPI;
import com.prupe.mcpatcher.mal.resource.BlendMethod;
import com.prupe.mcpatcher.mal.resource.ResourceList;
import com.prupe.mcpatcher.mal.resource.ResourceLocationWithSource;
import com.prupe.mcpatcher.mal.resource.TexturePackAPI;
import com.prupe.mcpatcher.mal.resource.TexturePackChangeHandler;
import com.prupe.mcpatcher.mal.tile.TileLoader;
@@ -128,8 +130,14 @@ public class CTMUtils {
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)) {
final List<ResourceLocation> ctmResources = new ArrayList<>();
for (String subdir : new String[] { TexturePackAPI.MCPATCHER_SUBDIR, TexturePackAPI.OPTIFINE_SUBDIR }) {
ctmResources.addAll(ResourceList.getInstance()
.listResources(subdir + "ctm", ".properties", true));
}
final Map<String, Map<IResourcePack, Integer>> packPriority = new HashMap<>();
ctmResources.sort((a, b) -> packPriorityOf(packPriority, b) - packPriorityOf(packPriority, a));
for (ResourceLocation resource : ctmResources) {
registerOverrideWithoutLock(newOverrides, TileOverride.create(resource, tileLoader));
}
for (Consumer<Overrides> callback : ctmRegistrationCallbacks) {
@@ -294,9 +302,7 @@ public class CTMUtils {
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);
registerTileWithoutLock(overrides, name, override);
registered = true;
}
}
@@ -306,6 +312,30 @@ public class CTMUtils {
}
}
private static void registerTileWithoutLock(Overrides overrides, String name, TileOverride override) {
overrides.tile.computeIfAbsent(name, k -> new ArrayList<>())
.add(override);
logger.fine("using %s for tile %s", override, name);
}
private static Map<IResourcePack, Integer> getPackPriority(String namespace) {
final List<IResourcePack> packs = TexturePackAPI.getResourcePacks(namespace);
final Map<IResourcePack, Integer> priority = new IdentityHashMap<>(packs.size());
for (int i = 0; i < packs.size(); i++) {
priority.put(packs.get(i), i);
}
return priority;
}
private static int packPriorityOf(Map<String, Map<IResourcePack, Integer>> byDomain, ResourceLocation resource) {
if (!(resource instanceof ResourceLocationWithSource source)) return -1;
final Integer rank = byDomain
.computeIfAbsent(resource.getResourceDomain(), CTMUtils::getPackPriority)
.get(source.getSource());
return rank == null ? -1 : rank;
}
private static void setBlankResourceWithoutLock() {
RenderBlocksUtils.blankIcon = tileLoader.getIcon(RenderPassAPI.instance.getBlankResource());
}
@@ -33,11 +33,15 @@ public abstract class TileOverride implements Comparable<TileOverride> {
private static final MCLogger logger = MCLogger.getLogger(MCLogger.Category.CONNECTED_TEXTURES, "CTM");
private static int nextRegistrationOrder;
public final PropertiesFile properties;
private final String baseFilename;
protected final TileLoader tileLoader;
protected final int renderPass;
private final int weight;
private boolean lostScope;
private final int registrationOrder = nextRegistrationOrder++;
private final List<BlockStateMatcher> matchBlocks;
private final Set<String> matchTiles;
private final BlockFaceMatcher faceMatcher;
@@ -274,19 +278,21 @@ public abstract class TileOverride implements Comparable<TileOverride> {
// nothing
} else if (token.matches("\\d+-\\d+")) {
for (int id : MCPatcherUtils.parseIntegerList(token, 0, 65535)) {
BlockStateMatcher matcher = BlockAPI.createMatcher(properties, id + defaultMetadata);
if (matcher == null) {
properties.warning("unknown block id %d", id);
List<BlockStateMatcher> matchers = BlockAPI.createMatchers(properties, id + defaultMetadata);
if (matchers.isEmpty()) {
properties.fine("unknown block id %d", id);
lostScope = true;
} else {
blocks.add(matcher);
blocks.addAll(matchers);
}
}
} else {
BlockStateMatcher matcher = BlockAPI.createMatcher(properties, token + defaultMetadata);
if (matcher == null) {
properties.warning("unknown block %s", token);
List<BlockStateMatcher> matchers = BlockAPI.createMatchers(properties, token + defaultMetadata);
if (matchers.isEmpty()) {
properties.fine("unknown block %s", token);
lostScope = true;
} else {
blocks.add(matcher);
blocks.addAll(matchers);
}
}
}
@@ -334,7 +340,11 @@ public abstract class TileOverride implements Comparable<TileOverride> {
public final void registerIcons() {
icons = new IIcon[tileNames.size()];
for (int i = 0; i < icons.length; i++) {
icons[i] = tileLoader.getIcon(tileNames.get(i));
final ResourceLocation tileName = tileNames.get(i);
icons[i] = tileLoader.getIcon(tileName);
if (icons[i] == null && tileName != null) {
properties.warning("tile %s did not resolve to an icon, tile %d will not render", tileName, i);
}
}
}
@@ -368,11 +378,11 @@ public abstract class TileOverride implements Comparable<TileOverride> {
if (result != 0) {
return result;
}
if (o instanceof TileOverride) {
return baseFilename.compareTo(((TileOverride) o).baseFilename);
} else {
return -1;
result = Boolean.compare(lostScope, o.lostScope);
if (result != 0) {
return result;
}
return Integer.compare(registrationOrder, o.registrationOrder);
}
final boolean shouldConnect(RenderBlockState renderBlockState, IIcon icon, int relativeDirection) {
@@ -4,15 +4,20 @@ import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
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 net.coderbot.iris.shaderpack.materialmap.BlockEntry;
import net.coderbot.iris.shaderpack.materialmap.FlatteningMap;
import net.coderbot.iris.shaderpack.materialmap.NamespacedId;
import net.minecraft.block.Block;
import com.prupe.mcpatcher.MCPatcherUtils;
import com.prupe.mcpatcher.mal.resource.PropertiesFile;
import com.prupe.mcpatcher.mal.resource.TexturePackAPI;
import cpw.mods.fml.common.registry.FMLControlledNamespacedRegistry;
import cpw.mods.fml.common.registry.GameData;
@@ -64,7 +69,7 @@ public class BlockAPI {
return blocks;
}
public static BlockStateMatcher createMatcher(PropertiesFile source, String matchString) {
public static List<BlockStateMatcher> createMatchers(PropertiesFile source, String matchString) {
Map<String, String> propertyMap = new HashMap<>();
String namespace = null;
String blockName = null;
@@ -90,7 +95,7 @@ public class BlockAPI {
appendThis = true;
} else {
source.warning("invalid token '%s' in %s", source, s, matchString);
return null;
return Collections.emptyList();
}
if (appendThis) {
metaString.append(':');
@@ -103,19 +108,73 @@ public class BlockAPI {
}
if (MCPatcherUtils.isNullOrEmpty(blockName)) {
source.warning("cannot parse namespace/block name from %s", matchString);
return null;
return Collections.emptyList();
}
Block block = GameData.getBlockRegistry()
.getObject(namespace + ':' + blockName);
if (block == null) {
source.warning("unknown block %s:%s", namespace, blockName);
return null;
final Block block = GameData.getBlockRegistry()
.getRaw(namespace + ':' + blockName);
if (block != null) {
return Collections.singletonList(
new BlockStateMatcher(
metaString.toString(),
block,
metadata.toString()
.trim()));
}
return new BlockStateMatcher(
metaString.toString(),
block,
metadata.toString()
.trim());
if (!TexturePackAPI.DEFAULT_NAMESPACE.equals(namespace)) {
source.fine("unknown block %s:%s", namespace, blockName);
return Collections.emptyList();
}
final List<BlockEntry> entries = FlatteningMap.toLegacy(blockName, propertyMap);
if (entries == null) {
source.fine("unknown block %s:%s", namespace, blockName);
return Collections.emptyList();
}
if (!propertyMap.isEmpty() && entries.equals(FlatteningMap.toLegacy(blockName, Collections.emptyMap()))) {
source.fine("block %s has no 1.7.10 equivalent for %s, ignoring this match", blockName, propertyMap);
return Collections.emptyList();
}
final String explicitMetadata = metadata.toString()
.trim();
final List<BlockStateMatcher> matchers = new ArrayList<>(entries.size());
for (BlockEntry entry : entries) {
final NamespacedId id = entry.id();
final Block legacy = GameData.getBlockRegistry()
.getRaw(id.getNamespace() + ':' + id.getName());
final String entryMetadata = intersectMetadata(explicitMetadata, entry.metas());
if (entryMetadata == null) {
continue;
}
matchers.add(new BlockStateMatcher(metaString.toString(), legacy, entryMetadata));
}
if (matchers.isEmpty()) {
source.fine("unknown block %s:%s", namespace, blockName);
}
return matchers;
}
private static String intersectMetadata(String explicitMetadata, Set<Integer> entryMetas) {
if (MCPatcherUtils.isNullOrEmpty(explicitMetadata)) {
if (entryMetas.isEmpty()) {
return "";
}
final StringBuilder sb = new StringBuilder();
for (int meta : entryMetas) {
sb.append(' ')
.append(meta);
}
return sb.toString()
.trim();
}
final StringBuilder sb = new StringBuilder();
for (int meta : MCPatcherUtils.parseIntegerList(explicitMetadata, 0, 15)) {
if (entryMetas.isEmpty() || entryMetas.contains(meta)) {
sb.append(' ')
.append(meta);
}
}
return sb.length() == 0 ? null
: sb.toString()
.trim();
}
}
@@ -43,6 +43,7 @@ public class TexturePackAPI {
public static final String DEFAULT_NAMESPACE = "minecraft";
public static final String MCPATCHER_SUBDIR = "mcpatcher/";
public static final String OPTIFINE_SUBDIR = "optifine/";
public static final ResourceLocation ITEMS_PNG = new ResourceLocation("textures/atlas/items.png");
private static final String ASSETS = "assets/";
@@ -204,6 +205,11 @@ public class TexturePackAPI {
return null;
}
private static String subdirOf(ResourceLocation baseResource) {
return baseResource != null && baseResource.getResourcePath()
.startsWith(OPTIFINE_SUBDIR) ? OPTIFINE_SUBDIR : MCPATCHER_SUBDIR;
}
public static ResourceLocation parseResourceLocation(ResourceLocation baseResource, String path) {
if (MCPatcherUtils.isNullOrEmpty(path)) {
return null;
@@ -232,8 +238,8 @@ public class TexturePackAPI {
ResourceLocation resource;
if (path.startsWith("~/")) {
// Relative to namespace mcpatcher dir:
// ~/path -> assets/(namespace of base file)/mcpatcher/path
resource = new ResourceLocation(baseResource.getResourceDomain(), MCPATCHER_SUBDIR + path.substring(2));
// ~/path -> assets/(namespace of base file)/(mcpatcher|optifine)/path
resource = new ResourceLocation(baseResource.getResourceDomain(), subdirOf(baseResource) + path.substring(2));
} else if (path.startsWith("./")) {
// Relative to properties file:
// ./path -> (dir of base file)/path
@@ -8,6 +8,7 @@ import com.gtnewhorizons.angelica.glsm.RenderSystem;
import com.gtnewhorizons.angelica.glsm.backend.BackendManager;
import com.gtnewhorizons.angelica.glsm.shader.GlslVulkanPreprocess;
import com.gtnewhorizons.angelica.glsm.shader.SpirvCompiler;
import com.gtnewhorizons.angelica.iris.ImmediateExtendedAttribs;
import com.gtnewhorizons.angelica.iris.IrisGLSMBridge;
import com.gtnewhorizons.angelica.proxy.ClientProxy;
import com.gtnewhorizons.angelica.rendering.StateAwareTessellator;
@@ -802,6 +803,9 @@ public class Iris {
// Load the new shaderpack
loadShaderpack();
// Drop the stale program probe and cached item geometry
ImmediateExtendedAttribs.onShaderPackChanged();
// Very important - we need to re-create the pipeline straight away.
// https://github.com/IrisShaders/Iris/issues/1330
if (Minecraft.getMinecraft().theWorld != null) {
@@ -5,6 +5,7 @@ package net.coderbot.iris.gl.shader;
import com.gtnewhorizons.angelica.glsm.GLDebug;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import com.gtnewhorizons.angelica.glsm.hooks.ImmediateExtendedAttribHandler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.lwjgl.opengl.GL11;
@@ -15,10 +16,10 @@ public class ProgramCreator {
private static final Logger LOGGER = LogManager.getLogger("ProgramCreator");
public static final int MC_ENTITY = 11;
public static final int MC_MID_TEX_COORD = 12;
public static final int AT_TANGENT = 13;
public static final int AT_MIDBLOCK = 14;
public static final int MC_ENTITY = ImmediateExtendedAttribHandler.LOC_MC_ENTITY;
public static final int MC_MID_TEX_COORD = ImmediateExtendedAttribHandler.LOC_MID_TEX;
public static final int AT_TANGENT = ImmediateExtendedAttribHandler.LOC_TANGENT;
public static final int AT_MIDBLOCK = ImmediateExtendedAttribHandler.LOC_MIDBLOCK;
public static int create(String name, GlShader... shaders) {
int program = GLStateManager.glCreateProgram();
@@ -4,6 +4,7 @@ import lombok.Getter;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.ffp.FfpExtendedAttribs;
import com.gtnewhorizons.angelica.glsm.states.AlphaState;
import com.gtnewhorizons.angelica.glsm.states.BlendState;
import net.coderbot.iris.gl.shader.ProgramCreator;
@@ -240,8 +241,7 @@ public class GbufferPrograms {
public static void setBlockEntityDefaults() {
GLStateManager.glVertexAttrib2s(ProgramCreator.MC_ENTITY, (short)-1, (short)-1);
GLStateManager.glVertexAttrib2f(ProgramCreator.MC_MID_TEX_COORD, 0.5f, 0.5f);
GLStateManager.glVertexAttrib4f(ProgramCreator.AT_TANGENT, 1.0f, 0.0f, 0.0f, 1.0f);
FfpExtendedAttribs.setNeutralCurrentValues();
GLStateManager.glVertexAttrib4f(ProgramCreator.AT_MIDBLOCK, 0.0f, 0.0f, 0.0f, 0.0f);
}
@@ -87,7 +87,6 @@ class AttributeTransformer {
if (instancedVertex) {
foldConstantAttribute(transformer, "mc_Entity", "-1.0", "vec2(-1.0, -1.0)", "vec3(-1.0, -1.0, 0.0)", "vec4(-1.0, -1.0, 0.0, 1.0)");
foldConstantAttribute(transformer, "mc_midTexCoord", "0.5", "vec2(0.5, 0.5)", "vec3(0.5, 0.5, 0.0)", "vec4(0.5, 0.5, 0.0, 1.0)");
final StringBuilder init = new StringBuilder(256);
init.append("{ iris_ModelViewMatrix = mat4(iris_InstMat0, iris_InstMat1, iris_InstMat2, iris_InstMat3);");
@@ -1,5 +1,6 @@
package net.coderbot.iris.pipeline.transform;
import com.gtnewhorizons.angelica.glsm.ffp.InstancedAttribs;
import org.taumc.glsl.Transformer;
import java.util.HashMap;
@@ -20,12 +21,12 @@ class CoreTransformHelper {
static void injectMatrixUniforms(Transformer transformer, boolean instancedVertex) {
if (instancedVertex) {
transformer.injectVariable("layout(location = 7) in vec4 iris_InstMat0;");
transformer.injectVariable("layout(location = 8) in vec4 iris_InstMat1;");
transformer.injectVariable("layout(location = 9) in vec4 iris_InstMat2;");
transformer.injectVariable("layout(location = 10) in vec4 iris_InstMat3;");
transformer.injectVariable("layout(location = 11) in vec4 iris_InstColor;");
transformer.injectVariable("layout(location = 12) in vec2 iris_InstLightmap;");
transformer.injectVariable("layout(location = " + InstancedAttribs.LOC_MATRIX_COL0 + ") in vec4 iris_InstMat0;");
transformer.injectVariable("layout(location = " + InstancedAttribs.LOC_MATRIX_COL1 + ") in vec4 iris_InstMat1;");
transformer.injectVariable("layout(location = " + InstancedAttribs.LOC_MATRIX_COL2 + ") in vec4 iris_InstMat2;");
transformer.injectVariable("layout(location = " + InstancedAttribs.LOC_MATRIX_COL3 + ") in vec4 iris_InstMat3;");
transformer.injectVariable("layout(location = " + InstancedAttribs.LOC_COLOR + ") in vec4 iris_InstColor;");
transformer.injectVariable("layout(location = " + InstancedAttribs.LOC_LIGHTMAP + ") in vec2 iris_InstLightmap;");
transformer.injectVariable("mat4 iris_ModelViewMatrix;");
transformer.injectVariable("mat4 iris_ModelViewMatrixInverse;");
transformer.injectVariable("mat3 iris_NormalMatrix;");
@@ -89,7 +89,7 @@ public class PBRAtlasTexture extends AutoClosableAbstractTexture {
}
if (AngelicaConfig.enablePBRDebug) {
TextureExporter.exportTextures("pbr_debug/atlas", id.getResourceDomain() + "_" + id.getResourcePath().replaceAll("/", "_"), glId, mipLevel, atlasWidth, atlasHeight);
TextureExporter.exportTextures("pbr_debug/atlas", id.getResourceDomain() + "_" + id.getResourcePath().replace("/", "_") + ".png", glId, mipLevel, atlasWidth, atlasHeight);
}
}
@@ -2,10 +2,10 @@ package net.coderbot.iris.texture.pbr.loader;
import com.google.common.collect.Lists;
import com.gtnewhorizons.angelica.compat.mojang.NativeImage;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.glsm.texture.TextureInfo;
import com.gtnewhorizons.angelica.glsm.texture.TextureInfoCache;
import com.gtnewhorizons.angelica.mixins.interfaces.ISpriteExt;
import me.jellysquid.mods.sodium.client.gui.SodiumGameOptions;
import net.coderbot.iris.Iris;
import net.coderbot.iris.texture.format.TextureFormat;
import net.coderbot.iris.texture.format.TextureFormatLoader;
@@ -17,10 +17,13 @@ import net.coderbot.iris.texture.pbr.PBRSpriteHolder;
import net.coderbot.iris.texture.pbr.PBRType;
import net.coderbot.iris.texture.pbr.TextureAtlasSpriteExtension;
import net.coderbot.iris.texture.util.ImageManipulationUtil;
import net.coderbot.iris.texture.util.TextureExporter;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.renderer.texture.TextureUtil;
import net.minecraft.client.resources.IResource;
import net.minecraft.client.resources.IResourceManager;
import net.minecraft.client.resources.data.AnimationFrame;
import net.minecraft.client.resources.data.AnimationMetadataSection;
import net.minecraft.util.ResourceLocation;
import org.apache.commons.lang3.tuple.Pair;
@@ -28,7 +31,11 @@ import org.apache.commons.lang3.tuple.Pair;
import javax.annotation.Nullable;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
public class AtlasPBRLoader implements PBRTextureLoader<TextureMap> {
public static final ChannelMipmapGenerator LINEAR_MIPMAP_GENERATOR = new ChannelMipmapGenerator(
@@ -84,6 +91,45 @@ public class AtlasPBRLoader implements PBRTextureLoader<TextureMap> {
pbrTextureConsumer.acceptSpecularTexture(specularAtlas);
}
}
if (AngelicaConfig.enablePBRDebug && (normalAtlas != null || specularAtlas != null)) {
TextureExporter.exportTextures("pbr_debug/atlas", "base_atlas.png", texMap.getGlTextureId(), mipLevel, atlasWidth, atlasHeight);
}
}
@Nullable
private static NativeImage padAnisotropic(NativeImage image, int frameWidth, int frameHeight) {
final int width = image.getWidth();
final int height = image.getHeight();
final int frames = (frameWidth == width && frameHeight > 0) ? height / frameHeight : 0;
if (frames < 1) {
return null;
}
final int paddedWidth = frameWidth + 16;
final int paddedHeight = frameHeight + 16;
final int framePixels = paddedWidth * paddedHeight;
final NativeImage padded = new NativeImage(paddedWidth, paddedHeight * frames, false);
final int[] frame = new int[framePixels];
for (int f = 0; f < frames; f++) {
Arrays.fill(frame, 0);
image.getRGB(0, f * frameHeight, frameWidth, frameHeight, frame, 0, frameWidth);
TextureUtil.prepareAnisotropicData(frame, frameWidth, frameHeight, 8);
padded.setRGB(0, f * paddedHeight, paddedWidth, paddedHeight, frame, 0, paddedWidth);
}
return padded;
}
private static AnimationMetadataSection withFrameSize(AnimationMetadataSection src, int frameWidth, int frameHeight) {
final List<AnimationFrame> frames = new ArrayList<>(src.getFrameCount());
for (int f = 0; f < src.getFrameCount(); f++) {
frames.add(new AnimationFrame(src.getFrameIndex(f), src.frameHasTime(f) ? src.getFrameTimeSingle(f) : -1));
}
return new AnimationMetadataSection(frames,
src.getFrameWidth() != -1 ? frameWidth : -1,
src.getFrameHeight() != -1 ? frameHeight : -1,
src.getFrameTime());
}
protected static int fetchAtlasMipLevel(TextureMap texMap) {
@@ -104,18 +150,15 @@ public class AtlasPBRLoader implements PBRTextureLoader<TextureMap> {
NativeImage nativeImage = NativeImage.read(resource.getInputStream());
AnimationMetadataSection animationMetadata = (AnimationMetadataSection) resource.getMetadata("animation");
if (animationMetadata == null) {
final IResource resourceOriginal = resourceManager.getResource(imageLocation);
animationMetadata = (AnimationMetadataSection) resourceOriginal.getMetadata("animation");
if (animationMetadata == null) {
animationMetadata = new AnimationMetadataSection(Lists.newArrayList(), -1, -1, -1);
}
animationMetadata = new AnimationMetadataSection(Lists.newArrayList(), -1, -1, -1);
}
final Pair<Integer, Integer> frameSize = this.getFrameSize(nativeImage.getWidth(), nativeImage.getHeight(), animationMetadata);
int frameWidth = frameSize.getLeft();
int frameHeight = frameSize.getRight();
final int targetFrameWidth = sprite.getIconWidth();
final int targetFrameHeight = sprite.getIconHeight();
final int spritePadding = sprite.useAnisotropicFiltering ? 16 : 0;
final int targetFrameWidth = sprite.getIconWidth() - spritePadding;
final int targetFrameHeight = sprite.getIconHeight() - spritePadding;
if (frameWidth != targetFrameWidth || frameHeight != targetFrameHeight) {
final int imageWidth = nativeImage.getWidth();
final int imageHeight = nativeImage.getHeight();
@@ -139,15 +182,8 @@ public class AtlasPBRLoader implements PBRTextureLoader<TextureMap> {
frameWidth = targetFrameWidth;
frameHeight = targetFrameHeight;
if (!animationMetadata.equals(new AnimationMetadataSection(Lists.newArrayList(), -1, -1, -1))) {
final int internalFrameWidth = animationMetadata.frameHeight;
final int internalFrameHeight = animationMetadata.frameWidth;
if (internalFrameWidth != -1) {
animationMetadata.frameWidth = frameWidth;
}
if (internalFrameHeight != -1) {
animationMetadata.frameHeight = frameHeight;
}
if (animationMetadata.getFrameWidth() != -1 || animationMetadata.getFrameHeight() != -1) {
animationMetadata = withFrameSize(animationMetadata, frameWidth, frameHeight);
}
}
@@ -156,7 +192,15 @@ public class AtlasPBRLoader implements PBRTextureLoader<TextureMap> {
final int x = sprite.getOriginX();
final int y = sprite.getOriginY();
pbrSprite = new PBRTextureAtlasSprite(pbrSpriteInfo, animationMetadata, atlasWidth, atlasHeight, x, y, nativeImage, texMap, mipLevel);
boolean padInLoadSprite = sprite.useAnisotropicFiltering;
if (padInLoadSprite) {
final NativeImage padded = padAnisotropic(nativeImage, frameWidth, frameHeight);
if (padded != null) {
nativeImage = padded;
padInLoadSprite = false;
}
}
pbrSprite = new PBRTextureAtlasSprite(pbrSpriteInfo, animationMetadata, atlasWidth, atlasHeight, x, y, nativeImage, padInLoadSprite, mipLevel);
syncAnimation(sprite, pbrSprite);
} catch (FileNotFoundException e) {
//
@@ -217,12 +261,10 @@ public class AtlasPBRLoader implements PBRTextureLoader<TextureMap> {
public static class PBRTextureAtlasSprite extends TextureAtlasSprite implements CustomMipmapGenerator.Provider {
// This feels super janky
protected PBRTextureAtlasSprite(TextureAtlasSpriteInfo info, AnimationMetadataSection animationMetaDataSection, int atlasWidth, int atlasHeight, int x, int y, NativeImage nativeImage, TextureMap texMap, int miplevel) {
protected PBRTextureAtlasSprite(TextureAtlasSpriteInfo info, AnimationMetadataSection animationMetaDataSection, int atlasWidth, int atlasHeight, int x, int y, NativeImage nativeImage, boolean useAnisotropicFiltering, int miplevel) {
super(info.name().toString());
super.loadSprite(Objects.requireNonNull(getMipmapGenerator(info, atlasWidth, atlasHeight)).generateMipLevels(nativeImage, miplevel), animationMetaDataSection, useAnisotropicFiltering);
super.initSprite(atlasWidth, atlasHeight, x, y, false);
final boolean useAnisotropicFiltering = texMap.anisotropicFiltering > 1
|| SodiumGameOptions.needsForcedSpritePadding();
super.loadSprite(getMipmapGenerator(info, atlasWidth, atlasHeight).generateMipLevels(nativeImage, miplevel), animationMetaDataSection, useAnisotropicFiltering);
}
@Override