SDL GPU backend, TESR Batching/caching API, Tracy Integration (#1993)

This commit is contained in:
Jason Mitchell authored and GitHub committed 2026-08-08 15:53:58 -07:00
1 parent 413df76ad4
commit 8da561d3b6
647 files changed
+60152 -5331

No files matched your search

@@ -0,0 +1,335 @@
package net.coderbot.batchedentityrendering.impl;
import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import it.unimi.dsi.fastutil.objects.Object2IntLinkedOpenHashMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import net.coderbot.batchedentityrendering.impl.ordering.SimpleRenderOrderManager;
import net.coderbot.iris.Iris;
import net.coderbot.iris.pipeline.WorldRenderingPipeline;
import net.coderbot.iris.uniforms.CapturedRenderingState;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
/** Collects geometry into per-RenderLayer buffers during a pass and draws it all at endBatch, one state bracket per layer. Based on Iris's FullyBufferedMultiBufferSource */
public class AngelicaBufferSource implements Groupable {
public static final int SAVED_STATE_BITS = GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT | GL11.GL_CURRENT_BIT | GL11.GL_LIGHTING_BIT | GL11.GL_TEXTURE_BIT;
private static final int NUM_BUFFERS = 32;
public enum GroupIdKind { BLOCK_ENTITY, ENTITY }
public interface LayerDrawHook {
boolean hasDraws(RenderLayer layer);
void drawLayer(RenderLayer layer);
}
private static final Comparator<BufferSegment> OPAQUE_ORDER = Comparator.comparingInt(BufferSegment::getBlockEntityId);
private final SimpleRenderOrderManager renderOrderManager = new SimpleRenderOrderManager();
private final SegmentedBufferBuilder[] builders = new SegmentedBufferBuilder[NUM_BUFFERS];
private final Object2IntLinkedOpenHashMap<RenderLayer> affinities = new Object2IntLinkedOpenHashMap<>(NUM_BUFFERS);
private final Map<RenderLayer, List<BufferSegment>> typeToSegment = new Object2ObjectOpenHashMap<>();
private boolean prepared;
private final List<RenderLayer> order = new ArrayList<>();
private boolean stateSaved;
private boolean anyIdSet;
private GroupIdKind idKind = GroupIdKind.BLOCK_ENTITY;
public AngelicaBufferSource() {
for (int i = 0; i < builders.length; i++) {
builders[i] = new SegmentedBufferBuilder();
}
affinities.defaultReturnValue(-1);
}
public SegmentedBufferBuilder getBuffer(RenderLayer type, int blockEntityId) {
renderOrderManager.begin(type);
int affinity = affinities.getAndMoveToLast(type);
if (affinity == -1) {
if (affinities.size() < builders.length) {
affinity = affinities.size();
} else {
affinity = affinities.removeFirstInt();
}
affinities.put(type, affinity);
}
final SegmentedBufferBuilder builder = builders[affinity];
builder.begin(type, blockEntityId);
return builder;
}
public void declareUse(RenderLayer type) {
renderOrderManager.begin(type);
}
public boolean isEmpty() {
for (SegmentedBufferBuilder builder : builders) {
if (!builder.isEmpty()) return false;
}
return true;
}
private void ensurePrepared() {
if (prepared) return;
prepared = true;
clearSegmentLists();
for (SegmentedBufferBuilder builder : builders) {
final List<BufferSegment> builderSegments = builder.getSegments();
for (int i = 0, n = builderSegments.size(); i < n; i++) {
final BufferSegment segment = builderSegments.get(i);
typeToSegment.computeIfAbsent(segment.getRenderType(), t -> new ArrayList<>()).add(segment);
}
}
order.clear();
final List<RenderLayer> renderOrder = renderOrderManager.getRenderOrder();
for (int i = 0, n = renderOrder.size(); i < n; i++) {
order.add(renderOrder.get(i));
}
renderOrderManager.reset();
for (int i = 0, n = order.size(); i < n; i++) {
final RenderLayer layer = order.get(i);
if (getTransparencyType(layer) != TransparencyType.OPAQUE) continue;
final List<BufferSegment> segments = typeToSegment.get(layer);
if (segments != null) {
segments.sort(OPAQUE_ORDER);
}
}
affinities.clear();
stateSaved = false;
anyIdSet = false;
}
List<RenderLayer> prepare() {
ensurePrepared();
return new ArrayList<>(order);
}
List<BufferSegment> segmentsFor(RenderLayer layer) {
return typeToSegment.get(layer);
}
public void endBatchWithType(TransparencyType type, LayerDrawHook hook) {
ensurePrepared();
int keep = 0;
for (int i = 0, n = order.size(); i < n; i++) {
final RenderLayer layer = order.get(i);
if (getTransparencyType(layer) != type) {
order.set(keep++, layer);
continue;
}
drawLayer(layer, hook);
}
for (int i = order.size() - 1; i >= keep; i--) {
order.remove(i);
}
}
public void endBatch(LayerDrawHook hook) {
ensurePrepared();
for (int i = 0, n = order.size(); i < n; i++) {
drawLayer(order.get(i), hook);
}
order.clear();
finish();
}
public void pauseBatch() {
releaseAttribState();
clearCurrentId();
}
public void discard() {
order.clear();
finish();
}
private void releaseAttribState() {
if (stateSaved) {
GLStateManager.glPopAttrib();
stateSaved = false;
}
}
private void clearCurrentId() {
if (!anyIdSet) return;
if (idKind == GroupIdKind.ENTITY) {
CapturedRenderingState.INSTANCE.setCurrentEntity(-1);
CapturedRenderingState.INSTANCE.setCurrentEntityColor(0f, 0f, 0f, 0f);
} else {
CapturedRenderingState.INSTANCE.setCurrentBlockEntity(0);
}
anyIdSet = false;
}
private void drawLayer(RenderLayer layer, LayerDrawHook hook) {
final List<BufferSegment> segments = typeToSegment.get(layer);
final boolean hasDynamic = segments != null && !segments.isEmpty();
final boolean hasRetained = hook != null && hook.hasDraws(layer);
if (!hasDynamic && !hasRetained) return;
if (!stateSaved) {
stateSaved = true;
GLStateManager.glPushAttrib(SAVED_STATE_BITS);
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
}
layer.startDrawing();
if (hasDynamic) {
anyIdSet = true;
GLStateManager.glPushMatrix();
GLStateManager.glLoadIdentity();
SegmentedBufferBuilder.LayerBuffer bound = null;
final boolean entityKind = idKind == GroupIdKind.ENTITY;
int currentId = Integer.MIN_VALUE;
int currentColor = 0;
boolean colorSet = false;
for (int i = 0, n = segments.size(); i < n; i++) {
final BufferSegment segment = segments.get(i);
if (entityKind && (!colorSet || segment.getEntityColor() != currentColor)) {
colorSet = true;
currentColor = segment.getEntityColor();
setEntityColor(currentColor);
}
if (segment.getBlockEntityId() != currentId) {
currentId = segment.getBlockEntityId();
applyIdAndRebind(currentId);
}
final SegmentedBufferBuilder.LayerBuffer owner = segment.getOwner();
if (owner != bound) {
if (bound != null) bound.finishDraw();
bound = owner;
bound.uploadForDraw();
bound.setupDraw();
}
bound.draw(segment.getFirstVertex(), segment.getVertexCount());
}
if (bound != null) bound.finishDraw();
GLStateManager.glPopMatrix();
}
if (hasRetained) {
anyIdSet = true;
hook.drawLayer(layer);
}
layer.endDrawing();
}
private void clearSegmentLists() {
for (List<BufferSegment> segments : typeToSegment.values()) {
segments.clear();
}
}
private void finish() {
releaseAttribState();
clearCurrentId();
clearSegmentLists();
final long now = System.currentTimeMillis();
final long maxIdle = getTargetClearTime();
for (SegmentedBufferBuilder builder : builders) {
builder.resetAndReclaim(now, maxIdle);
}
prepared = false;
}
public void freeBuffers() {
for (SegmentedBufferBuilder builder : builders) {
builder.freeAll();
}
typeToSegment.clear();
order.clear();
affinities.clear();
renderOrderManager.reset();
prepared = false;
}
public long allocatedBytes() {
long bytes = 0;
for (SegmentedBufferBuilder builder : builders) {
bytes += builder.allocatedBytes();
}
return bytes;
}
private long getTargetClearTime() {
final long sizeInMiB = allocatedBytes() / 1024L / 1024L;
if (sizeInMiB > 5000) {
return 1_000;
} else if (sizeInMiB > 1000) {
return 5_000;
}
return 10_000;
}
public void setIdKind(GroupIdKind kind) {
this.idKind = kind;
}
public void applyIdAndRebind(int id) {
anyIdSet = true;
if (idKind == GroupIdKind.ENTITY) {
CapturedRenderingState.INSTANCE.setCurrentEntity(id);
rebindPass();
} else {
setBlockEntityAndRebind(id);
}
}
public void applyIdNoRebind(int id) {
anyIdSet = true;
if (idKind == GroupIdKind.ENTITY) {
CapturedRenderingState.INSTANCE.setCurrentEntity(id);
} else {
CapturedRenderingState.INSTANCE.setCurrentBlockEntity(id);
}
}
public static void setEntityColor(int packed) {
CapturedRenderingState.INSTANCE.setCurrentEntityColor(
((packed >>> 16) & 0xFF) / 255f, ((packed >>> 8) & 0xFF) / 255f,
(packed & 0xFF) / 255f, (packed >>> 24) / 255f);
}
public static void setBlockEntityAndRebind(int blockEntityId) {
CapturedRenderingState.INSTANCE.setCurrentBlockEntity(blockEntityId);
rebindPass();
}
public static void rebindPass() {
if (Iris.enabled) {
final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable();
if (pipeline != null) {
pipeline.rebindCurrentPass();
}
}
}
static TransparencyType getTransparencyType(RenderLayer type) {
while (type instanceof WrappableRenderType wrappable) {
type = wrappable.unwrap();
}
if (type instanceof BlendingStateHolder holder) {
return holder.getTransparencyType();
}
return TransparencyType.GENERAL_TRANSPARENT;
}
@Override
public void startGroup() {
renderOrderManager.startGroup();
}
@Override
public boolean maybeStartGroup() {
return renderOrderManager.maybeStartGroup();
}
@Override
public void endGroup() {
renderOrderManager.endGroup();
}
}
@@ -0,0 +1,43 @@
package net.coderbot.batchedentityrendering.impl;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormatElement;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.writers.IVertexAttributeWriter;
import net.minecraft.client.renderer.Tessellator;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetFloat;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutFloat;
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.LIGHT_INDEX;
public final class BatchVertexFormats {
public static final VertexFormatElement LIGHT_FLOAT_ELEMENT = new VertexFormatElement(1, VertexFormatElement.Type.FLOAT, VertexFormatElement.Usage.SECONDARY_UV, 2, VertexFlags.BRIGHTNESS_BIT, new FloatLightVertexAttributeWriter());
public static final VertexFormat POSITION_COLOR_TEXTURE_LIGHTF_NORMAL = new VertexFormat(DefaultVertexFormat.POSITION_ELEMENT, DefaultVertexFormat.COLOR_ELEMENT, DefaultVertexFormat.TEXTURE_ELEMENT, LIGHT_FLOAT_ELEMENT, DefaultVertexFormat.NORMAL_ELEMENT);
private BatchVertexFormats() {}
private static final class FloatLightVertexAttributeWriter implements IVertexAttributeWriter {
@Override
public int writeAttribute(long pointer, int[] data, int index) {
final int light = data[index | LIGHT_INDEX];
memPutFloat(pointer, light & 0xFFFF);
memPutFloat(pointer + 4, light >>> 16);
return 8;
}
@Override
public int writeAttribute(long pointer, Tessellator tessellator) {
final int light = tessellator.brightness;
memPutFloat(pointer, light & 0xFFFF);
memPutFloat(pointer + 4, light >>> 16);
return 8;
}
@Override
public int readAttribute(long pointer, Tessellator tessellator) {
tessellator.brightness = (((int) memGetFloat(pointer + 4)) << 16) | (((int) memGetFloat(pointer)) & 0xFFFF);
return 8;
}
}
}
@@ -1,25 +1,45 @@
package net.coderbot.batchedentityrendering.impl;
import com.gtnewhorizons.angelica.compat.toremove.RenderLayer;
import lombok.Getter;
import java.nio.ByteBuffer;
import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
public class BufferSegment {
private final ByteBuffer slice;
@Getter
private final RenderLayer type;
private final int blockEntityId;
private final int entityColor;
private final int firstVertex;
private final int vertexCount;
private final SegmentedBufferBuilder.LayerBuffer owner;
public BufferSegment(ByteBuffer slice, RenderLayer type) {
this.slice = slice;
public BufferSegment(RenderLayer type, int blockEntityId, int entityColor, int firstVertex, int vertexCount, SegmentedBufferBuilder.LayerBuffer owner) {
this.type = type;
}
public ByteBuffer getSlice() {
return slice;
this.blockEntityId = blockEntityId;
this.entityColor = entityColor;
this.firstVertex = firstVertex;
this.vertexCount = vertexCount;
this.owner = owner;
}
public RenderLayer getRenderType() {
return type;
}
public int getBlockEntityId() {
return blockEntityId;
}
public int getEntityColor() {
return entityColor;
}
public int getFirstVertex() {
return firstVertex;
}
public int getVertexCount() {
return vertexCount;
}
public SegmentedBufferBuilder.LayerBuffer getOwner() {
return owner;
}
}
@@ -0,0 +1,217 @@
package net.coderbot.batchedentityrendering.impl;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadView;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
import com.gtnewhorizons.angelica.rendering.tesr.TemplateBuffer;
import com.gtnewhorizons.angelica.rendering.tesr.MeshBuffer;
import com.gtnewhorizons.angelica.rendering.tesr.VertexTransform;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import net.coderbot.iris.uniforms.CapturedRenderingState;
import org.joml.Matrix4fc;
import org.joml.Vector3f;
import org.joml.Vector4fc;
import org.lwjgl.BufferUtils;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0;
public class SegmentedBufferBuilder {
public static final VertexFormat FORMAT = BatchVertexFormats.POSITION_COLOR_TEXTURE_LIGHTF_NORMAL;
static final class LayerBuffer {
final RenderLayer layer;
ByteBuffer buffer;
final MeshBuffer mesh = new MeshBuffer();
int vertexCount;
boolean uploaded;
long lastUsedMs;
LayerBuffer(RenderLayer layer) {
this.layer = layer;
this.buffer = BufferUtils.createByteBuffer(Math.max(layer.getExpectedBufferSize(), 4096));
}
void ensureCapacity(int bytes) {
buffer = MeshBuffer.ensureCapacity(buffer, bytes, true);
}
void uploadForDraw() {
if (uploaded) return;
uploaded = true;
final ByteBuffer view = buffer.duplicate();
view.flip();
mesh.upload(layer.getVertexFormat(), layer.getDrawMode(), view, vertexCount);
}
void setupDraw() {
mesh.bind();
}
void draw(int firstVertex, int count) {
mesh.draw(firstVertex, count);
}
void finishDraw() {
mesh.unbind();
}
void reset() {
buffer.clear();
vertexCount = 0;
uploaded = false;
}
}
private final Map<RenderLayer, LayerBuffer> layerBuffers = new Object2ObjectOpenHashMap<>();
private final List<LayerBuffer> bufferList = new ArrayList<>();
private final List<BufferSegment> segments = new ArrayList<>();
private LayerBuffer current;
private RenderLayer currentType;
private int currentBlockEntityId;
private int currentEntityColor;
private int segmentStartVertex;
private long allocatedBytes;
public void begin(RenderLayer type, int blockEntityId) {
final int entityColor = packEntityColor(CapturedRenderingState.INSTANCE.getCurrentEntityColor());
if (type == currentType && blockEntityId == currentBlockEntityId && entityColor == currentEntityColor && current != null) {
return;
}
endSegment();
LayerBuffer buffer = layerBuffers.get(type);
if (buffer == null) {
buffer = new LayerBuffer(type);
layerBuffers.put(type, buffer);
bufferList.add(buffer);
allocatedBytes += buffer.buffer.capacity();
}
current = buffer;
currentType = type;
currentBlockEntityId = blockEntityId;
currentEntityColor = entityColor;
segmentStartVertex = current.vertexCount;
}
public static int packEntityColor(Vector4fc c) {
return ((int) (c.w() * 255f + 0.5f) << 24) | ((int) (c.x() * 255f + 0.5f) << 16) | ((int) (c.y() * 255f + 0.5f) << 8) | (int) (c.z() * 255f + 0.5f);
}
public void addQuad(ModelQuadView quad) {
if (current == null) {
throw new IllegalStateException("addQuad() without begin()");
}
final VertexFormat format = currentType.getVertexFormat();
ensureCurrentCapacity(format.getVertexSize() * 4);
format.writeQuad(quad, current.buffer);
current.vertexCount += 4;
}
public void addTemplateInstance(TemplateBuffer template, Matrix4fc mv, Vector3f scratch, int colorABGR, int packedLight, Matrix4fc texMatrix) {
if (current == null) {
throw new IllegalStateException("addTemplateInstance() without begin()");
}
final VertexFormat format = currentType.getVertexFormat();
ensureCurrentCapacity(format.getVertexSize() * template.vertexCount);
final ByteBuffer buffer = current.buffer;
final long ptr = memAddress0(buffer) + buffer.position();
final long end = VertexTransform.writeInstance(ptr, format, template, mv, scratch, colorABGR, packedLight, texMatrix);
buffer.position(buffer.position() + (int) (end - ptr));
current.vertexCount += template.vertexCount;
}
private void ensureCurrentCapacity(int bytes) {
final int before = current.buffer.capacity();
current.ensureCapacity(bytes);
allocatedBytes += current.buffer.capacity() - before;
}
private void endSegment() {
if (current != null && current.vertexCount > segmentStartVertex) {
segments.add(new BufferSegment(currentType, currentBlockEntityId, currentEntityColor, segmentStartVertex,
current.vertexCount - segmentStartVertex, current));
}
segmentStartVertex = current == null ? 0 : current.vertexCount;
}
public List<BufferSegment> getSegments() {
endSegment();
currentType = null;
current = null;
return segments;
}
public boolean isEmpty() {
for (int i = 0, n = bufferList.size(); i < n; i++) {
if (bufferList.get(i).vertexCount != 0) return false;
}
return true;
}
public int getVertexCount() {
int total = 0;
for (int i = 0, n = bufferList.size(); i < n; i++) {
total += bufferList.get(i).vertexCount;
}
return total;
}
public void reset() {
for (int i = 0, n = bufferList.size(); i < n; i++) {
bufferList.get(i).reset();
}
segments.clear();
currentType = null;
current = null;
currentBlockEntityId = 0;
segmentStartVertex = 0;
}
public void resetAndReclaim(long nowMs, long maxIdleMs) {
for (int i = bufferList.size() - 1; i >= 0; i--) {
final LayerBuffer lb = bufferList.get(i);
if (lb.vertexCount > 0) {
lb.lastUsedMs = nowMs;
}
lb.reset();
if (nowMs - lb.lastUsedMs > maxIdleMs) {
allocatedBytes -= lb.buffer.capacity();
lb.mesh.delete();
layerBuffers.remove(lb.layer);
bufferList.remove(i);
}
}
segments.clear();
currentType = null;
current = null;
currentBlockEntityId = 0;
segmentStartVertex = 0;
}
public void freeAll() {
for (int i = 0, n = bufferList.size(); i < n; i++) {
bufferList.get(i).mesh.delete();
}
layerBuffers.clear();
bufferList.clear();
segments.clear();
currentType = null;
current = null;
currentBlockEntityId = 0;
segmentStartVertex = 0;
allocatedBytes = 0;
}
public long allocatedBytes() {
return allocatedBytes;
}
public int bufferCount() {
return layerBuffers.size();
}
}
@@ -1,6 +1,6 @@
package net.coderbot.batchedentityrendering.impl;
import com.gtnewhorizons.angelica.compat.toremove.RenderLayer;
import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
public interface WrappableRenderType {
/**
@@ -10,7 +10,7 @@ import de.odysseus.ithaka.digraph.util.fas.SimpleFeedbackArcSetProvider;
import net.coderbot.batchedentityrendering.impl.BlendingStateHolder;
import net.coderbot.batchedentityrendering.impl.TransparencyType;
import net.coderbot.batchedentityrendering.impl.WrappableRenderType;
import com.gtnewhorizons.angelica.compat.toremove.RenderLayer;
import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
import java.util.ArrayList;
import java.util.EnumMap;
@@ -1,6 +1,6 @@
package net.coderbot.batchedentityrendering.impl.ordering;
import com.gtnewhorizons.angelica.compat.toremove.RenderLayer;
import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
public interface RenderOrderManager {
void begin(RenderLayer type);
@@ -1,18 +1,19 @@
package net.coderbot.batchedentityrendering.impl.ordering;
import com.gtnewhorizons.angelica.compat.toremove.RenderLayer;
import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet;
import java.util.LinkedHashSet;
import java.util.ArrayList;
import java.util.List;
public class SimpleRenderOrderManager implements RenderOrderManager {
private final LinkedHashSet<RenderLayer> renderTypes;
public SimpleRenderOrderManager() {
renderTypes = new LinkedHashSet<>();
}
private final ObjectOpenHashSet<RenderLayer> seen = new ObjectOpenHashSet<>();
private final ArrayList<RenderLayer> ordered = new ArrayList<>();
public void begin(RenderLayer type) {
renderTypes.add(type);
if (seen.add(type)) {
ordered.add(type);
}
}
public void startGroup() {
@@ -30,10 +31,11 @@ public class SimpleRenderOrderManager implements RenderOrderManager {
@Override
public void reset() {
renderTypes.clear();
seen.clear();
ordered.clear();
}
public Iterable<RenderLayer> getRenderOrder() {
return renderTypes;
public List<RenderLayer> getRenderOrder() {
return ordered;
}
}
@@ -3,7 +3,7 @@ package net.coderbot.batchedentityrendering.impl.ordering;
import net.coderbot.batchedentityrendering.impl.BlendingStateHolder;
import net.coderbot.batchedentityrendering.impl.TransparencyType;
import net.coderbot.batchedentityrendering.impl.WrappableRenderType;
import com.gtnewhorizons.angelica.compat.toremove.RenderLayer;
import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
import java.util.ArrayList;
import java.util.EnumMap;
+41 -25
View File
@@ -4,9 +4,12 @@ import com.google.common.base.Throwables;
import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager;
import com.gtnewhorizons.angelica.Tags;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.glsm.shader.GlslVulkanPreprocess;
import com.gtnewhorizons.angelica.glsm.shader.SpirvCompiler;
import com.gtnewhorizons.angelica.proxy.ClientProxy;
import com.gtnewhorizons.angelica.rendering.StateAwareTessellator;
import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProviderHolder;
import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager;
import cpw.mods.fml.client.registry.ClientRegistry;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.InputEvent;
@@ -37,6 +40,7 @@ import net.coderbot.iris.shaderpack.option.values.MutableOptionValues;
import net.coderbot.iris.shaderpack.option.values.OptionValues;
import net.coderbot.iris.texture.pbr.PBRTextureManager;
import net.coderbot.iris.uniforms.CapturedRenderingState;
import net.coderbot.iris.uniforms.PerFrameUniformBlockHarvester;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
@@ -67,9 +71,10 @@ import java.util.Properties;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinWorkerThread;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
@@ -89,6 +94,7 @@ public class Iris {
// Cached at class load - config must be loaded before Iris. Do not change at runtime.
public static final boolean enabled = AngelicaConfig.enableIris;
public static final boolean hardcodedCustomUniforms = AngelicaConfig.enableHardcodedCustomUniforms;
private static Path shaderpacksDirectory;
private static ShaderpackDirectoryManager shaderpacksDirectoryManager;
@@ -151,9 +157,14 @@ public class Iris {
private static volatile long lastActivityTime;
private static final AtomicInteger inFlight = new AtomicInteger(0);
private static boolean idleCheckScheduled;
private static final ThreadLocal<Boolean> ON_WORKER = ThreadLocal.withInitial(() -> Boolean.FALSE);
private ShaderTransformExecutor() {}
public static boolean isOnWorker() {
return ON_WORKER.get();
}
private static void noteActivity() {
lastActivityTime = System.nanoTime();
}
@@ -166,18 +177,21 @@ public class Iris {
return executor;
}
executor = new ForkJoinPool(
final AtomicInteger threadCounter = new AtomicInteger();
final ThreadFactory factory = r -> {
final Thread t = new Thread(r, "Shader-Transform-" + threadCounter.getAndIncrement());
t.setDaemon(true);
return t;
};
final ThreadPoolExecutor tpe = new ThreadPoolExecutor(
THREAD_COUNT,
pool -> {
ForkJoinWorkerThread t = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool);
t.setName("Shader-Transform-" + t.getPoolIndex());
t.setDaemon(true);
return t;
},
null, // UncaughtExceptionHandler
true // asyncMode - FIFO, better for independent tasks
);
logger.debug("Created shader transform executor with " + THREAD_COUNT + " threads");
THREAD_COUNT,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(),
factory);
tpe.prestartAllCoreThreads();
executor = tpe;
logger.debug("Created shader transform executor with " + THREAD_COUNT + " prestarted threads");
if (scheduler == null || scheduler.isShutdown()) {
scheduler = Executors.newSingleThreadScheduledExecutor(r -> {
@@ -205,15 +219,9 @@ public class Iris {
}
}
/**
* Ensures the executor exists and begins spinning up worker threads.
* Intended for UI entrypoints (eg. shader settings screen open).
*/
/** Idempotent: ensures the pool is created. {@link #get()} prestarts all workers. */
public static void prepare() {
// Submit empty tasks to warm up all worker threads without blocking the UI thread.
for (int i = 0; i < THREAD_COUNT; i++) {
submitTracked(() -> { });
}
get();
}
/**
@@ -238,9 +246,11 @@ public class Iris {
inFlight.incrementAndGet();
try {
return CompletableFuture.supplyAsync(() -> {
ON_WORKER.set(Boolean.TRUE);
try {
return supplier.get();
} finally {
ON_WORKER.set(Boolean.FALSE);
noteActivity();
inFlight.decrementAndGet();
}
@@ -257,9 +267,11 @@ public class Iris {
inFlight.incrementAndGet();
try {
return CompletableFuture.runAsync(() -> {
ON_WORKER.set(Boolean.TRUE);
try {
runnable.run();
} finally {
ON_WORKER.set(Boolean.FALSE);
noteActivity();
inFlight.decrementAndGet();
}
@@ -297,6 +309,9 @@ public class Iris {
// Clear transformation caches - no longer needed after loading
TransformPatcher.clearCache();
ShaderTransformer.clearCache();
SpirvCompiler.clearCache();
GlslVulkanPreprocess.clearCache();
ShaderManager.clearPrewarmCache();
} else {
// Still active (or in-flight), schedule another check.
final long remainingSeconds = Math.max(1, IDLE_TIMEOUT_SECONDS - idleSeconds + 1);
@@ -402,10 +417,7 @@ public class Iris {
return;
}
// Register the Celeritas shader provider for Iris integration (only when Celeritas is enabled)
if (AngelicaConfig.enableCeleritas) {
IrisShaderProviderHolder.setProvider(new IrisCeleritasShaderProvider());
}
IrisShaderProviderHolder.setProvider(new IrisCeleritasShaderProvider());
// Warm up the threadpool so shader transformations are faster when we need them
ShaderTransformExecutor.warmup();
@@ -856,6 +868,7 @@ public class Iris {
private static WorldRenderingPipeline createPipeline(String dimensionName) {
if (currentPack == null) {
// Completely disables shader-based rendering
PerFrameUniformBlockHarvester.clear();
return new FixedFunctionWorldRenderingPipeline();
}
@@ -863,6 +876,8 @@ public class Iris {
try {
shaderPackLoadId++;
ShaderTransformExecutor.prepare();
PerFrameUniformBlockHarvester.harvest(programs);
long startTime = System.nanoTime();
WorldRenderingPipeline pipeline = new DeferredWorldRenderingPipeline(programs);
long endTime = System.nanoTime();
@@ -872,6 +887,7 @@ public class Iris {
logger.error("Failed to create shader rendering pipeline, disabling shaders!", e);
// TODO: This should be reverted if a dimension change causes shaders to compile again
fallback = true;
PerFrameUniformBlockHarvester.clear();
return new FixedFunctionWorldRenderingPipeline();
}
@@ -163,6 +163,7 @@ public class CeleritasTerrainPipeline {
target.setSource(PatchShaderType.VERTEX, result.get(PatchShaderType.VERTEX));
target.setSource(PatchShaderType.GEOMETRY, result.get(PatchShaderType.GEOMETRY));
target.setSource(PatchShaderType.FRAGMENT, result.get(PatchShaderType.FRAGMENT));
target.setSource(PatchShaderType.COMPUTE, result.get(PatchShaderType.COMPUTE));
}
PatchedShaderPrinter.debugPatchedShaders(sourceName + "_celeritas",
result.get(PatchShaderType.VERTEX), result.get(PatchShaderType.GEOMETRY), result.get(PatchShaderType.FRAGMENT));
@@ -205,4 +206,10 @@ public class CeleritasTerrainPipeline {
public ProgramImages initShadowImages(int programId) {
return createShadowImages.apply(programId);
}
public Optional<String> getShadowVoxelizationComputeSource() {
final PassInfo shadow = passInfoMap.get(IrisTerrainPass.SHADOW);
if (shadow == null) return Optional.empty();
return shadow.sources.get(PatchShaderType.COMPUTE);
}
}
@@ -1,6 +1,7 @@
package net.coderbot.iris.celeritas;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
import com.gtnewhorizons.angelica.mixins.interfaces.EntityRendererAccessor;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gl.blending.BlendModeOverride;
@@ -34,6 +35,12 @@ import java.util.List;
public class IrisCeleritasChunkShaderInterface implements ChunkShaderInterface {
@Nullable
private static final Tracy.ZoneId Z_IRIS_SETUP_FBO = Tracy.zoneId("iris_setup_fbo", Tracy.COLOR_IRIS);
private static final Tracy.ZoneId Z_IRIS_SETUP_UNIFORMS = Tracy.zoneId("iris_setup_uniforms", Tracy.COLOR_IRIS);
private static final Tracy.ZoneId Z_IRIS_SETUP_SAMPLERS = Tracy.zoneId("iris_setup_samplers", Tracy.COLOR_IRIS);
private static final Tracy.ZoneId Z_IRIS_SETUP_IMAGES = Tracy.zoneId("iris_setup_images", Tracy.COLOR_IRIS);
private static final Tracy.ZoneId Z_IRIS_SETUP_CUSTOM = Tracy.zoneId("iris_setup_custom", Tracy.COLOR_IRIS);
private final GlUniformMatrix4f uniformModelViewMatrix;
@Nullable
private final GlUniformMatrix4f uniformModelViewMatrixInverse;
@@ -45,6 +52,8 @@ public class IrisCeleritasChunkShaderInterface implements ChunkShaderInterface {
private final GlUniformMatrix3f uniformNormalMatrix;
@Nullable
private final GlUniformFloat3v uniformRegionOffset;
@Nullable
private final GlUniformMatrix4f uniformLightmapTextureMatrix;
// Iris program state
private final ProgramUniforms irisProgramUniforms;
@@ -57,10 +66,18 @@ public class IrisCeleritasChunkShaderInterface implements ChunkShaderInterface {
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();
private final Matrix4f lastProjection = new Matrix4f();
private final Matrix4f lastModelView = new Matrix4f();
private boolean hasLastProjection;
private boolean hasLastModelView;
private static final Matrix4f sharedProjKey = new Matrix4f();
private static final Matrix4f sharedProjInverse = new Matrix4f();
private static boolean sharedProjValid;
private static final Matrix4f sharedMvKey = new Matrix4f();
private static final Matrix4f sharedMvInverse = new Matrix4f();
private static final Matrix3f sharedNormal = new Matrix3f();
private static boolean sharedMvValid;
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);
@@ -69,6 +86,7 @@ public class IrisCeleritasChunkShaderInterface implements ChunkShaderInterface {
this.uniformProjectionMatrixInverse = context.bindUniformIfPresent("iris_ProjectionMatrixInverse", GlUniformMatrix4f::new);
this.uniformNormalMatrix = context.bindUniformIfPresent("iris_NormalMatrix", GlUniformMatrix3f::new);
this.uniformRegionOffset = context.bindUniformIfPresent("u_RegionOffset", GlUniformFloat3v::new);
this.uniformLightmapTextureMatrix = context.bindUniformIfPresent("iris_LightmapTextureMatrix", GlUniformMatrix4f::new);
this.blendModeOverride = blendModeOverride;
this.bufferBlendOverrides = bufferBlendOverrides;
@@ -84,12 +102,20 @@ public class IrisCeleritasChunkShaderInterface implements ChunkShaderInterface {
@Override
public void setupState(TerrainRenderPass pass) {
if (Tracy.ENABLED) Tracy.beginZone(Z_IRIS_SETUP_FBO);
bindFramebuffer(pass);
if (ShadowRenderingState.areShadowsCurrentlyBeingRendered()) {
GLStateManager.disableCull();
}
// Explicitly set iris_LightmapTextureMatrix rather than relying on CompatUniformManager.
// At high uniform locations in large UBOs, the compat manager's writes may not persist
// through the per-program dirtyUniforms swap in non-GL backends.
if (uniformLightmapTextureMatrix != null) {
uniformLightmapTextureMatrix.set(GLStateManager.getTextures().getTextureUnitMatrix(1));
}
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + IrisSamplers.ALBEDO_TEXTURE_UNIT);
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, Minecraft.getMinecraft().getTextureMapBlocks().getGlTextureId());
@@ -104,18 +130,27 @@ public class IrisCeleritasChunkShaderInterface implements ChunkShaderInterface {
if (hasOverrides) {
bufferBlendOverrides.forEach(BufferBlendOverride::apply);
}
if (Tracy.ENABLED) Tracy.endZone();
if (irisProgramUniforms != null) {
if (Tracy.ENABLED) Tracy.beginZone(Z_IRIS_SETUP_UNIFORMS);
irisProgramUniforms.update();
if (Tracy.ENABLED) Tracy.endZone();
}
if (irisProgramSamplers != null) {
if (Tracy.ENABLED) Tracy.beginZone(Z_IRIS_SETUP_SAMPLERS);
irisProgramSamplers.update();
if (Tracy.ENABLED) Tracy.endZone();
}
if (irisProgramImages != null) {
if (Tracy.ENABLED) Tracy.beginZone(Z_IRIS_SETUP_IMAGES);
irisProgramImages.update();
if (Tracy.ENABLED) Tracy.endZone();
}
if (Tracy.ENABLED) Tracy.beginZone(Z_IRIS_SETUP_CUSTOM);
customUniforms.push(this);
if (Tracy.ENABLED) Tracy.endZone();
}
@Override
@@ -135,34 +170,55 @@ public class IrisCeleritasChunkShaderInterface implements ChunkShaderInterface {
@Override
public void setProjectionMatrix(Matrix4fc matrix) {
if (hasLastProjection && lastProjection.equals(matrix, 0.0f)) {
return;
}
hasLastProjection = true;
lastProjection.set(matrix);
if (uniformProjectionMatrix != null) {
uniformProjectionMatrix.set(matrix);
}
if (uniformProjectionMatrixInverse != null) {
projectionMatrixInverse.set(matrix);
projectionMatrixInverse.invert();
uniformProjectionMatrixInverse.set(projectionMatrixInverse);
if (!sharedProjValid || !sharedProjKey.equals(matrix, 0.0f)) {
sharedProjValid = true;
sharedProjKey.set(matrix);
sharedProjInverse.set(matrix);
sharedProjInverse.invert();
}
uniformProjectionMatrixInverse.set(sharedProjInverse);
}
}
@Override
public void setModelViewMatrix(Matrix4fc modelView) {
if (hasLastModelView && lastModelView.equals(modelView, 0.0f)) {
return;
}
hasLastModelView = true;
lastModelView.set(modelView);
if (uniformModelViewMatrix != null) {
uniformModelViewMatrix.set(modelView);
}
if (uniformModelViewMatrixInverse != null) {
modelViewMatrixInverse.set(modelView);
modelViewMatrixInverse.invert();
uniformModelViewMatrixInverse.set(modelViewMatrixInverse);
}
if (uniformNormalMatrix != null) {
normalMatrix.set(modelView);
normalMatrix.invert();
normalMatrix.transpose();
uniformNormalMatrix.set(normalMatrix);
if (uniformModelViewMatrixInverse != null || uniformNormalMatrix != null) {
if (!sharedMvValid || !sharedMvKey.equals(modelView, 0.0f)) {
sharedMvValid = true;
sharedMvKey.set(modelView);
sharedMvInverse.set(modelView);
sharedMvInverse.invert();
sharedNormal.set(modelView);
sharedNormal.invert();
sharedNormal.transpose();
}
if (uniformModelViewMatrixInverse != null) {
uniformModelViewMatrixInverse.set(sharedMvInverse);
}
if (uniformNormalMatrix != null) {
uniformNormalMatrix.set(sharedNormal);
}
}
}
@@ -206,7 +262,7 @@ public class IrisCeleritasChunkShaderInterface implements ChunkShaderInterface {
}
}
@org.jetbrains.annotations.Nullable
@Nullable
private CeleritasTerrainPipeline getCeleritasTerrainPipeline() {
final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable();
return pipeline != null ? pipeline.getCeleritasTerrainPipeline() : null;
@@ -5,6 +5,7 @@ import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProvider;
import com.gtnewhorizons.angelica.rendering.celeritas.iris.IrisExtendedChunkVertexType;
import net.coderbot.iris.Iris;
import net.coderbot.iris.block_rendering.BlockRenderingSettings;
import net.coderbot.iris.pipeline.WorldRenderingPipeline;
import net.coderbot.iris.shadows.ShadowRenderingState;
import net.minecraft.block.Block;
import org.embeddedt.embeddium.impl.gl.shader.GlProgram;
@@ -65,6 +66,12 @@ public class IrisCeleritasShaderProvider implements IrisShaderProvider {
return BlockRenderingSettings.INSTANCE.getBlockTypeIds();
}
@Override
public void preSubmitShadowGraph(int frame, boolean spectator) {
final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable();
if (pipeline != null) pipeline.preSubmitShadowGraph(frame, spectator);
}
public void deleteShaders() {
overrides.deleteShaders();
}
@@ -73,6 +73,10 @@ public class DHCompat {
return dhPresent && hasRenderingEnabled() && lastIncompatible;
}
public static boolean isPresent() {
return dhPresent;
}
public static float getFarPlane() {
if (!dhPresent) return 0.01f;
return DHCompatInternal.getFarPlane();
@@ -8,7 +8,7 @@ import com.seibel.distanthorizons.api.objects.math.DhApiVec3f;
import com.seibel.distanthorizons.coreapi.DependencyInjection.OverrideInjector;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gl.framebuffer.GlFramebuffer;
import net.coderbot.iris.gl.texture.DepthBufferFormat;
import com.gtnewhorizons.angelica.glsm.texture.DepthBufferFormat;
import net.coderbot.iris.gl.texture.DepthCopyStrategy;
import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline;
import net.coderbot.iris.rendertarget.DepthTexture;
@@ -3,7 +3,7 @@ package net.coderbot.iris.compat.dh;
import com.google.common.primitives.Ints;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.mixins.interfaces.EntityRendererAccessor;
import com.mitchej123.lwjgl.MemoryStack;
import org.lwjgl.BufferUtils;
import com.seibel.distanthorizons.api.interfaces.override.rendering.IDhApiGenericObjectShaderProgram;
import com.seibel.distanthorizons.api.interfaces.render.IDhApiRenderableBoxGroup;
import com.seibel.distanthorizons.api.methods.events.sharedParameterObjects.DhApiRenderParam;
@@ -17,7 +17,7 @@ import net.coderbot.iris.gl.program.ProgramImages;
import net.coderbot.iris.gl.program.ProgramSamplers;
import net.coderbot.iris.gl.program.ProgramUniforms;
import net.coderbot.iris.gl.shader.GlShader;
import net.coderbot.iris.gl.shader.ShaderType;
import com.gtnewhorizons.angelica.glsm.shader.ShaderType;
import net.coderbot.iris.gl.state.FogMode;
import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline;
import net.coderbot.iris.pipeline.PatchedShaderPrinter;
@@ -70,6 +70,11 @@ public class IrisGenericRenderProgram implements IDhApiGenericObjectShaderProgra
id = GLStateManager.glCreateProgram();
GLStateManager.glBindAttribLocation(this.id, 0, "vPosition");
GLStateManager.glBindAttribLocation(this.id, 1, "iris_color");
GLStateManager.glBindAttribLocation(this.id, 2, "aScale");
GLStateManager.glBindAttribLocation(this.id, 3, "aTranslateChunk");
GLStateManager.glBindAttribLocation(this.id, 4, "aTranslateSubChunk");
GLStateManager.glBindAttribLocation(this.id, 5, "aMaterial");
this.bufferBlendOverrides = bufferBlendOverrides;
@@ -187,16 +192,12 @@ public class IrisGenericRenderProgram implements IDhApiGenericObjectShaderProgra
return GLStateManager.glGetUniformLocation(this.id, name);
}
private final FloatBuffer matrixScratch = BufferUtils.createFloatBuffer(16);
public void setUniform(int index, Matrix4f matrix) {
if (index == -1 || matrix == null) return;
try (MemoryStack stack = MemoryStack.stackPush()) {
FloatBuffer buffer = stack.callocFloat(16);
matrix.get(buffer);
buffer.rewind();
GLStateManager.glUniformMatrix4(index, false, buffer);
}
matrix.get(matrixScratch);
GLStateManager.glUniformMatrix4(index, false, matrixScratch);
}
// Override ShaderProgram.bind()
@@ -11,9 +11,9 @@ import net.coderbot.iris.gl.program.ProgramImages;
import net.coderbot.iris.gl.program.ProgramSamplers;
import net.coderbot.iris.gl.program.ProgramUniforms;
import net.coderbot.iris.gl.shader.GlShader;
import net.coderbot.iris.gl.shader.ShaderType;
import com.gtnewhorizons.angelica.glsm.shader.ShaderType;
import net.coderbot.iris.gl.state.FogMode;
import net.coderbot.iris.gl.texture.TextureType;
import com.gtnewhorizons.angelica.glsm.texture.TextureType;
import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline;
import net.coderbot.iris.pipeline.PatchedShaderPrinter;
import net.coderbot.iris.pipeline.transform.PatchShaderType;
@@ -1,6 +1,6 @@
package net.coderbot.iris.fantastic;
import com.gtnewhorizons.angelica.compat.toremove.RenderLayer;
import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
import java.util.function.Function;
public interface WrappingMultiBufferSource {
@@ -1,10 +0,0 @@
package net.coderbot.iris.gl;
public enum GlVersion {
GL_11,
GL_12,
GL_30,
GL_31,
GL_33,
GL_41
}
@@ -1,5 +1,7 @@
package net.coderbot.iris.gl.blending;
import com.gtnewhorizons.angelica.glsm.states.AlphaTestFunction;
public class AlphaTest {
public static final AlphaTest ALWAYS = new AlphaTest(AlphaTestFunction.ALWAYS, 0.0f);
@@ -1,63 +0,0 @@
package net.coderbot.iris.gl.blending;
import org.lwjgl.opengl.GL11;
import java.util.Optional;
public enum AlphaTestFunction {
NEVER(GL11.GL_NEVER, null),
LESS(GL11.GL_LESS, "<"),
EQUAL(GL11.GL_EQUAL, "=="),
LEQUAL(GL11.GL_LEQUAL, "<="),
GREATER(GL11.GL_GREATER, ">"),
NOTEQUAL(GL11.GL_NOTEQUAL, "!="),
GEQUAL(GL11.GL_GEQUAL, ">="),
ALWAYS(GL11.GL_ALWAYS, null);
private final int glId;
private final String expression;
AlphaTestFunction(int glFormat, String expression) {
this.glId = glFormat;
this.expression = expression;
}
public static Optional<AlphaTestFunction> fromGlId(int glId) {
return switch (glId) {
case GL11.GL_NEVER -> Optional.of(NEVER);
case GL11.GL_LESS -> Optional.of(LESS);
case GL11.GL_EQUAL -> Optional.of(EQUAL);
case GL11.GL_LEQUAL -> Optional.of(LEQUAL);
case GL11.GL_GREATER -> Optional.of(GREATER);
case GL11.GL_NOTEQUAL -> Optional.of(NOTEQUAL);
case GL11.GL_GEQUAL -> Optional.of(GEQUAL);
case GL11.GL_ALWAYS -> Optional.of(ALWAYS);
default -> Optional.empty();
};
}
public static Optional<AlphaTestFunction> fromString(String name) {
if ("GL_ALWAYS".equals(name)) {
// shaders.properties states that GL_ALWAYS is the name to use, but I haven't verified that this actually
// matches the implementation... All of the other names do not have the GL_ prefix.
//
// We'll support it here just to be safe, even though just a plain ALWAYS seems more likely to be what it
// parses.
return Optional.of(AlphaTestFunction.ALWAYS);
}
try {
return Optional.of(AlphaTestFunction.valueOf(name));
} catch (IllegalArgumentException e) {
return Optional.empty();
}
}
public int getGlId() {
return glId;
}
public String getExpression() {
return expression;
}
}
@@ -1,5 +1,7 @@
package net.coderbot.iris.gl.blending;
import com.gtnewhorizons.angelica.glsm.states.AlphaTestFunction;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.states.AlphaState;
import lombok.Getter;
@@ -10,7 +10,7 @@ import it.unimi.dsi.fastutil.ints.Int2IntArrayMap;
import it.unimi.dsi.fastutil.ints.Int2IntMap;
import java.nio.IntBuffer;
import net.coderbot.iris.gl.GlResource;
import net.coderbot.iris.gl.texture.DepthBufferFormat;
import com.gtnewhorizons.angelica.glsm.texture.DepthBufferFormat;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
@@ -0,0 +1,90 @@
package net.coderbot.iris.gl.framebuffer;
import net.coderbot.iris.rendertarget.ParityFlipState;
import org.jetbrains.annotations.Nullable;
public class ParityFramebuffer extends GlFramebuffer {
private final ParityFlipState parity;
@Nullable
private GlFramebuffer odd;
public ParityFramebuffer(ParityFlipState parity) {
this.parity = parity;
}
public void setOdd(GlFramebuffer odd) {
this.odd = odd;
}
@Nullable
public GlFramebuffer getOdd() {
return odd;
}
private boolean useOdd() {
return odd != null && parity.isOdd();
}
@Override
public void bind() {
if (useOdd()) {
odd.bind();
} else {
super.bind();
}
}
@Override
public void bindAsReadBuffer() {
if (useOdd()) {
odd.bindAsReadBuffer();
} else {
super.bindAsReadBuffer();
}
}
@Override
public void bindAsDrawBuffer() {
if (useOdd()) {
odd.bindAsDrawBuffer();
} else {
super.bindAsDrawBuffer();
}
}
@Override
public int getId() {
return useOdd() ? odd.getId() : super.getId();
}
@Override
public int getColorAttachment(int index) {
return useOdd() ? odd.getColorAttachment(index) : super.getColorAttachment(index);
}
@Override
public void addDepthAttachment(int texture) {
super.addDepthAttachment(texture);
if (odd != null) {
odd.addDepthAttachment(texture);
}
}
@Override
public void addDepthAttachmentBypass(int texture) {
super.addDepthAttachmentBypass(texture);
if (odd != null) {
odd.addDepthAttachmentBypass(texture);
}
}
@Override
protected void destroyInternal() {
super.destroyInternal();
if (odd != null) {
odd.destroy();
odd = null;
}
}
}
@@ -2,10 +2,10 @@ package net.coderbot.iris.gl.image;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import net.coderbot.iris.gl.texture.InternalTextureFormat;
import net.coderbot.iris.gl.texture.PixelFormat;
import net.coderbot.iris.gl.texture.PixelType;
import net.coderbot.iris.gl.texture.TextureType;
import com.gtnewhorizons.angelica.glsm.texture.InternalTextureFormat;
import com.gtnewhorizons.angelica.glsm.texture.PixelFormat;
import com.gtnewhorizons.angelica.glsm.texture.PixelType;
import com.gtnewhorizons.angelica.glsm.texture.TextureType;
import org.embeddedt.embeddium.impl.gl.GlObject;
import org.embeddedt.embeddium.impl.gl.debug.GLDebug;
import org.lwjgl.opengl.GL11;
@@ -1,6 +1,6 @@
package net.coderbot.iris.gl.image;
import net.coderbot.iris.gl.texture.InternalTextureFormat;
import com.gtnewhorizons.angelica.glsm.texture.InternalTextureFormat;
import java.util.function.IntSupplier;
@@ -1,9 +1,9 @@
package net.coderbot.iris.gl.image;
import net.coderbot.iris.gl.texture.InternalTextureFormat;
import net.coderbot.iris.gl.texture.PixelFormat;
import net.coderbot.iris.gl.texture.PixelType;
import net.coderbot.iris.gl.texture.TextureType;
import com.gtnewhorizons.angelica.glsm.texture.InternalTextureFormat;
import com.gtnewhorizons.angelica.glsm.texture.PixelFormat;
import com.gtnewhorizons.angelica.glsm.texture.PixelType;
import com.gtnewhorizons.angelica.glsm.texture.TextureType;
public record ImageInformation(String name, String samplerName, TextureType target, PixelFormat format,
InternalTextureFormat internalTextureFormat,
@@ -7,10 +7,10 @@ import net.coderbot.iris.gl.sampler.GlSampler;
import net.coderbot.iris.gl.sampler.SamplerHolder;
import net.coderbot.iris.gl.shader.GlShader;
import net.coderbot.iris.gl.shader.ProgramCreator;
import net.coderbot.iris.gl.shader.ShaderType;
import com.gtnewhorizons.angelica.glsm.shader.ShaderType;
import net.coderbot.iris.gl.state.ValueUpdateNotifier;
import net.coderbot.iris.gl.texture.InternalTextureFormat;
import net.coderbot.iris.gl.texture.TextureType;
import com.gtnewhorizons.angelica.glsm.texture.InternalTextureFormat;
import com.gtnewhorizons.angelica.glsm.texture.TextureType;
import org.jetbrains.annotations.Nullable;
import java.util.function.IntSupplier;
@@ -5,7 +5,7 @@ import com.gtnewhorizons.angelica.glsm.RenderSystem;
import net.coderbot.iris.gl.image.ImageBinding;
import net.coderbot.iris.gl.image.ImageHolder;
import net.coderbot.iris.gl.image.ImageLimits;
import net.coderbot.iris.gl.texture.InternalTextureFormat;
import com.gtnewhorizons.angelica.glsm.texture.InternalTextureFormat;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import java.util.ArrayList;
@@ -11,7 +11,7 @@ import net.coderbot.iris.gl.sampler.SamplerHolder;
import net.coderbot.iris.gl.sampler.SamplerLimits;
import net.coderbot.iris.gl.state.ValueUpdateNotifier;
import net.coderbot.iris.gl.texture.TextureAccess;
import net.coderbot.iris.gl.texture.TextureType;
import com.gtnewhorizons.angelica.glsm.texture.TextureType;
import net.coderbot.iris.shaderpack.PackRenderTargetDirectives;
import org.lwjgl.opengl.GL13;
@@ -51,8 +51,8 @@ public class ProgramSamplers {
// in the middle of RenderType setup, bad things will happen.
int activeTexture = GLStateManager.getActiveTextureUnit();
for (SamplerBinding samplerBinding : samplerBindings) {
samplerBinding.update();
for (int i = 0, n = samplerBindings.size(); i < n; i++) {
samplerBindings.get(i).update();
}
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + activeTexture);
@@ -61,8 +61,8 @@ public class ProgramSamplers {
public void removeListeners() {
active = null;
for (ValueUpdateNotifier notifier : notifiersToReset) {
notifier.setListener(null);
for (int i = 0, n = notifiersToReset.size(); i < n; i++) {
notifiersToReset.get(i).setListener(null);
}
}
@@ -18,7 +18,7 @@ import net.coderbot.iris.gl.state.ValueUpdateNotifier;
import net.coderbot.iris.gl.uniform.DynamicLocationalUniformHolder;
import net.coderbot.iris.gl.uniform.Uniform;
import net.coderbot.iris.gl.uniform.UniformHolder;
import net.coderbot.iris.gl.uniform.UniformType;
import com.gtnewhorizons.angelica.glsm.shader.UniformType;
import net.coderbot.iris.gl.uniform.UniformUpdateFrequency;
import net.coderbot.iris.uniforms.SystemTimeUniforms;
import net.minecraft.client.Minecraft;
@@ -51,8 +51,8 @@ public class ProgramUniforms {
}
private void updateStage(ImmutableList<Uniform> uniforms) {
for (Uniform uniform : uniforms) {
uniform.update();
for (int i = 0, n = uniforms.size(); i < n; i++) {
uniforms.get(i).update();
}
}
@@ -107,8 +107,8 @@ public class ProgramUniforms {
public void removeListeners() {
active = null;
for (ValueUpdateNotifier notifier : notifiersToReset) {
notifier.setListener(null);
for (int i = 0, n = notifiersToReset.size(); i < n; i++) {
notifiersToReset.get(i).setListener(null);
}
}
@@ -207,7 +207,7 @@ public class ProgramUniforms {
final UniformType provided = uniformNames.get(name);
final UniformType expected = getExpectedType(type);
if(AngelicaConfig.enableHardcodedCustomUniforms) {
if(Iris.hardcodedCustomUniforms) {
// Legacy Checks from hardcoded custom uniforms
if (provided == null && !name.startsWith("gl_")) {
final String typeName = getTypeName(type);
@@ -2,11 +2,12 @@ package net.coderbot.iris.gl.sampler;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import net.coderbot.iris.gl.state.ValueUpdateNotifier;
import net.coderbot.iris.gl.texture.TextureType;
import com.gtnewhorizons.angelica.glsm.texture.TextureType;
import java.util.function.IntSupplier;
public class SamplerBinding {
private final Runnable updateListener = this::updateSampler;
private final TextureType textureType;
private final int textureUnit;
private final IntSupplier texture;
@@ -25,7 +26,7 @@ public class SamplerBinding {
updateSampler();
if (notifier != null) {
notifier.setListener(this::updateSampler);
notifier.setListener(updateListener);
}
}
@@ -1,7 +1,7 @@
package net.coderbot.iris.gl.sampler;
import net.coderbot.iris.gl.state.ValueUpdateNotifier;
import net.coderbot.iris.gl.texture.TextureType;
import com.gtnewhorizons.angelica.glsm.texture.TextureType;
import java.util.function.IntSupplier;
@@ -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.shader.ShaderType;
import net.coderbot.iris.gl.GlResource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -1,26 +0,0 @@
// This file is based on code from Sodium by JellySquid, licensed under the LGPLv3 license.
package net.coderbot.iris.gl.shader;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL32;
import org.lwjgl.opengl.GL40;
import org.lwjgl.opengl.GL43;
/**
* An enumeration over the supported OpenGL shader types.
*/
public enum ShaderType {
VERTEX(GL20.GL_VERTEX_SHADER),
GEOMETRY(GL32.GL_GEOMETRY_SHADER),
TESSELATION_CONTROL(GL40.GL_TESS_CONTROL_SHADER),
TESSELATION_EVAL(GL40.GL_TESS_EVALUATION_SHADER),
FRAGMENT(GL20.GL_FRAGMENT_SHADER),
COMPUTE(GL43.GL_COMPUTE_SHADER);
public final int id;
ShaderType(int id) {
this.id = id;
}
}
@@ -16,6 +16,8 @@ import net.coderbot.iris.texture.format.TextureFormatLoader;
import net.coderbot.iris.uniforms.VanillaBiomeList;
import net.minecraft.world.biome.BiomeGenBase;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import com.gtnewhorizons.angelica.glsm.backend.BackendManager;
import org.lwjgl.LWJGLUtil;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL20;
@@ -29,13 +31,9 @@ import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class StandardMacros {
private static final Pattern SEMVER_PATTERN = Pattern.compile("(?<major>\\d+)\\.(?<minor>\\d+)\\.*(?<bugfix>\\d*)(.*)");
private static void define(List<StringPair> defines, String key) {
defines.add(new StringPair(key, ""));
}
@@ -87,8 +85,11 @@ public class StandardMacros {
define(standardDefines, "IRIS_HAS_TRANSLUCENCY_SORTING");
define(standardDefines, "MAX_COLOR_BUFFERS", String.valueOf(IrisLimits.MAX_COLOR_BUFFERS));
}
if (BackendManager.RENDER_BACKEND.isSDLGPU()) {
define(standardDefines, "IS_ANGELICA_SDLGPU");
}
if (DHCompat.hasRenderingEnabled()) {
if (DHCompat.isPresent()) {
define(standardDefines, "DISTANT_HORIZONS");
}
@@ -184,44 +185,7 @@ public class StandardMacros {
* @see <a href="https://github.com/sp614x/optifine/blob/9c6a5b5326558ccc57c6490b66b3be3b2dc8cbef/OptiFineDoc/doc/shaders.txt#L705-L707">Optifine Doc for GLSL Version</a>
*/
public static String getGlVersion(int name) {
final String info = GLStateManager.glGetString(name);
Matcher matcher = SEMVER_PATTERN.matcher(Objects.requireNonNull(info));
if (!matcher.matches()) {
throw new IllegalStateException("Could not parse GL version from \"" + info + "\"");
}
String major = group(matcher, "major");
String minor = group(matcher, "minor");
String bugfix = group(matcher, "bugfix");
if (bugfix == null) {
// if bugfix is not there, it is 0
bugfix = "0";
}
if (major == null || minor == null) {
throw new IllegalStateException("Could not parse GL version from \"" + info + "\"");
}
return major + minor + bugfix;
}
/**
* Expanded version of {@link Matcher#group(String)} that does not throw an exception.
* If the argument is incorrect (normally resulting in an exception), it returns null
*
* @param matcher matcher to check the group by
* @param name name of the group
* @return the section of the matcher that is a group, or null, if that matcher does not contain said group
*/
public static String group(Matcher matcher, String name) {
try {
return matcher.group(name);
} catch (IllegalArgumentException | IllegalStateException exception) {
return null;
}
return RenderSystem.parseGlVersionString(GLStateManager.glGetString(name));
}
/**
@@ -231,6 +195,10 @@ public class StandardMacros {
* @see <a href="https://github.com/sp614x/optifine/blob/9c6a5b5326558ccc57c6490b66b3be3b2dc8cbef/OptiFineDoc/doc/shaders.txt#L709-L714">Optifine Doc</a>
*/
public static String getOsString() {
// Force MC_OS_LINUX under SDL_GPU on Mac to avoid shaderpack gates!
if (BackendManager.RENDER_BACKEND.isSDLGPU() && LWJGLUtil.getPlatform() == LWJGLUtil.PLATFORM_MACOSX) {
return "MC_OS_LINUX";
}
return switch (LWJGLUtil.getPlatform()) {
case LWJGLUtil.PLATFORM_MACOSX -> "MC_OS_MAC";
case LWJGLUtil.PLATFORM_LINUX -> "MC_OS_LINUX";
@@ -330,11 +298,10 @@ public class StandardMacros {
* @return List of definitions corresponding to the uniform names prefixed with "MC_"
*/
public static List<String> getIrisDefines() {
List<String> defines = new ArrayList<>();
// All Iris-exclusive uniforms should have a corresponding definition here. Example:
// All Iris-exclusive uniforms should have a corresponding definition here. Example:
// defines.add("MC_UNIFORM_DRAGON_DEATH_PROGRESS");
return defines;
return new ArrayList<>();
}
/**
@@ -1,80 +0,0 @@
package net.coderbot.iris.gl.texture;
import org.jetbrains.annotations.Nullable;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL14;
import org.lwjgl.opengl.GL30;
public enum DepthBufferFormat {
DEPTH(false),
DEPTH16(false),
DEPTH24(false),
DEPTH32(false),
DEPTH32F(false),
DEPTH_STENCIL(true),
DEPTH24_STENCIL8(true),
DEPTH32F_STENCIL8(true);
private final boolean combinedStencil;
DepthBufferFormat(boolean combinedStencil) {
this.combinedStencil = combinedStencil;
}
@Nullable
public static DepthBufferFormat fromGlEnum(int glenum) {
return switch (glenum) {
case GL11.GL_DEPTH_COMPONENT -> DepthBufferFormat.DEPTH;
case GL14.GL_DEPTH_COMPONENT16 -> DepthBufferFormat.DEPTH16;
case GL14.GL_DEPTH_COMPONENT24 -> DepthBufferFormat.DEPTH24;
case GL14.GL_DEPTH_COMPONENT32 -> DepthBufferFormat.DEPTH32;
case GL30.GL_DEPTH_COMPONENT32F -> DepthBufferFormat.DEPTH32F;
case GL30.GL_DEPTH_STENCIL -> DepthBufferFormat.DEPTH_STENCIL;
case GL30.GL_DEPTH24_STENCIL8 -> DepthBufferFormat.DEPTH24_STENCIL8;
case GL30.GL_DEPTH32F_STENCIL8 -> DepthBufferFormat.DEPTH32F_STENCIL8;
default -> null;
};
}
public static DepthBufferFormat fromGlEnumOrDefault(int glenum) {
DepthBufferFormat format = fromGlEnum(glenum);
if (format == null) {
// yolo, just assume it's GL_DEPTH_COMPONENT
return DepthBufferFormat.DEPTH;
}
return format;
}
public int getGlInternalFormat() {
return switch (this) {
case DEPTH -> GL11.GL_DEPTH_COMPONENT;
case DEPTH16 -> GL14.GL_DEPTH_COMPONENT16;
case DEPTH24 -> GL14.GL_DEPTH_COMPONENT24;
case DEPTH32 -> GL14.GL_DEPTH_COMPONENT32;
case DEPTH32F -> GL30.GL_DEPTH_COMPONENT32F;
case DEPTH_STENCIL -> GL30.GL_DEPTH_STENCIL;
case DEPTH24_STENCIL8 -> GL30.GL_DEPTH24_STENCIL8;
case DEPTH32F_STENCIL8 -> GL30.GL_DEPTH32F_STENCIL8;
};
}
public int getGlType() {
return isCombinedStencil() ? GL30.GL_DEPTH_STENCIL : GL11.GL_DEPTH_COMPONENT;
}
public int getGlFormat() {
return switch (this) {
case DEPTH, DEPTH16 -> GL11.GL_UNSIGNED_SHORT;
case DEPTH24, DEPTH32 -> GL11.GL_UNSIGNED_INT;
case DEPTH32F -> GL11.GL_FLOAT;
case DEPTH_STENCIL, DEPTH24_STENCIL8 -> GL30.GL_UNSIGNED_INT_24_8;
case DEPTH32F_STENCIL8 -> GL30.GL_FLOAT_32_UNSIGNED_INT_24_8_REV;
};
}
public boolean isCombinedStencil() {
return combinedStencil;
}
}
@@ -2,12 +2,16 @@ package net.coderbot.iris.gl.texture;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
import net.coderbot.iris.gl.framebuffer.GlFramebuffer;
import org.lwjgl.opengl.GL11;
public interface DepthCopyStrategy {
// FB -> T
class Gl20CopyTexture implements DepthCopyStrategy {
private static final Tracy.ZoneId Z_DEPTH_COPY_BIND = Tracy.zoneId("depthCopyBind", Tracy.COLOR_IRIS);
private static final Tracy.ZoneId Z_DEPTH_COPY_TEX_SUB = Tracy.zoneId("depthCopyTexSub", Tracy.COLOR_IRIS);
private Gl20CopyTexture() {
// private
}
@@ -19,27 +23,39 @@ public interface DepthCopyStrategy {
@Override
public void copy(GlFramebuffer sourceFb, int sourceTexture, GlFramebuffer destFb, int destTexture, int width, int height) {
sourceFb.bindAsReadBuffer();
if (Tracy.ENABLED) Tracy.beginZone(Z_DEPTH_COPY_BIND);
try {
sourceFb.bindAsReadBuffer();
} finally {
if (Tracy.ENABLED) Tracy.endZone();
}
RenderSystem.copyTexSubImage2D(
destTexture,
// target
GL11.GL_TEXTURE_2D,
// level
0,
// xoffset, yoffset
0, 0,
// x, y
0, 0,
// width
width,
// height
height);
if (Tracy.ENABLED) Tracy.beginZone(Z_DEPTH_COPY_TEX_SUB);
try {
RenderSystem.copyTexSubImage2D(
destTexture,
// target
GL11.GL_TEXTURE_2D,
// level
0,
// xoffset, yoffset
0, 0,
// x, y
0, 0,
// width
width,
// height
height);
} finally {
if (Tracy.ENABLED) Tracy.endZone();
}
}
}
// FB -> FB
class Gl30BlitFbCombinedDepthStencil implements DepthCopyStrategy {
private static final Tracy.ZoneId Z_DEPTH_COPY_BLIT = Tracy.zoneId("depthCopyBlit", Tracy.COLOR_IRIS);
private Gl30BlitFbCombinedDepthStencil() {
// private
}
@@ -51,16 +67,23 @@ public interface DepthCopyStrategy {
@Override
public void copy(GlFramebuffer sourceFb, int sourceTexture, GlFramebuffer destFb, int destTexture, int width, int height) {
RenderSystem.blitFramebuffer(sourceFb.getId(), destFb.getId(), 0, 0, width, height,
0, 0, width, height,
GL11.GL_DEPTH_BUFFER_BIT | GL11.GL_STENCIL_BUFFER_BIT,
GL11.GL_NEAREST);
if (Tracy.ENABLED) Tracy.beginZone(Z_DEPTH_COPY_BLIT);
try {
RenderSystem.blitFramebuffer(sourceFb.getId(), destFb.getId(), 0, 0, width, height,
0, 0, width, height,
GL11.GL_DEPTH_BUFFER_BIT | GL11.GL_STENCIL_BUFFER_BIT,
GL11.GL_NEAREST);
} finally {
if (Tracy.ENABLED) Tracy.endZone();
}
}
}
// T -> T
// Fastest
class Gl43CopyImage implements DepthCopyStrategy {
private static final Tracy.ZoneId Z_DEPTH_COPY_IMAGE = Tracy.zoneId("depthCopyImage", Tracy.COLOR_IRIS);
private Gl43CopyImage() {
// private
}
@@ -72,7 +95,12 @@ public interface DepthCopyStrategy {
@Override
public void copy(GlFramebuffer sourceFb, int sourceTexture, GlFramebuffer destFb, int destTexture, int width, int height) {
GLStateManager.glCopyImageSubData(sourceTexture, GL11.GL_TEXTURE_2D, 0, 0, 0, 0, destTexture, GL11.GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1);
if (Tracy.ENABLED) Tracy.beginZone(Z_DEPTH_COPY_IMAGE);
try {
GLStateManager.glCopyImageSubData(sourceTexture, GL11.GL_TEXTURE_2D, 0, 0, 0, 0, destTexture, GL11.GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1);
} finally {
if (Tracy.ENABLED) Tracy.endZone();
}
}
}
@@ -1,5 +1,7 @@
package net.coderbot.iris.gl.texture;
import com.gtnewhorizons.angelica.glsm.texture.TextureType;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import net.coderbot.iris.shaderpack.texture.TextureFilteringData;
@@ -1,142 +0,0 @@
package net.coderbot.iris.gl.texture;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import net.coderbot.iris.gl.GlVersion;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL30;
import org.lwjgl.opengl.GL31;
import org.lwjgl.opengl.GL33;
import org.lwjgl.opengl.GL41;
import java.util.Optional;
public enum InternalTextureFormat {
// Default
// TODO: This technically shouldn't be exposed to shaders since it's not in the specification, it's the default anyways
RGBA(GL11.GL_RGBA, GlVersion.GL_11, PixelFormat.RGBA),
// 8-bit normalized
R8(GL30.GL_R8, GlVersion.GL_30, PixelFormat.RED),
RG8(GL30.GL_RG8, GlVersion.GL_30, PixelFormat.RG),
RGB8(GL11.GL_RGB8, GlVersion.GL_11, PixelFormat.RGB),
RGBA8(GL11.GL_RGBA8, GlVersion.GL_11, PixelFormat.RGBA),
// 8-bit signed normalized
R8_SNORM(GL31.GL_R8_SNORM, GlVersion.GL_31, PixelFormat.RED),
RG8_SNORM(GL31.GL_RG8_SNORM, GlVersion.GL_31, PixelFormat.RG),
RGB8_SNORM(GL31.GL_RGB8_SNORM, GlVersion.GL_31, PixelFormat.RGB),
RGBA8_SNORM(GL31.GL_RGBA8_SNORM, GlVersion.GL_31, PixelFormat.RGBA),
// 16-bit normalized
R16(GL30.GL_R16, GlVersion.GL_30, PixelFormat.RED),
RG16(GL30.GL_RG16, GlVersion.GL_30, PixelFormat.RG),
RGB16(GL11.GL_RGB16, GlVersion.GL_11, PixelFormat.RGB),
RGBA16(GL11.GL_RGBA16, GlVersion.GL_11, PixelFormat.RGBA),
// 16-bit signed normalized
R16_SNORM(GL31.GL_R16_SNORM, GlVersion.GL_31, PixelFormat.RED),
RG16_SNORM(GL31.GL_RG16_SNORM, GlVersion.GL_31, PixelFormat.RG),
RGB16_SNORM(GL31.GL_RGB16_SNORM, GlVersion.GL_31, PixelFormat.RGB),
RGBA16_SNORM(GL31.GL_RGBA16_SNORM, GlVersion.GL_31, PixelFormat.RGBA),
// 16-bit float
R16F(GL30.GL_R16F, GlVersion.GL_30, PixelFormat.RED),
RG16F(GL30.GL_RG16F, GlVersion.GL_30, PixelFormat.RG),
RGB16F(GL30.GL_RGB16F, GlVersion.GL_30, PixelFormat.RGB),
RGBA16F(GL30.GL_RGBA16F, GlVersion.GL_30, PixelFormat.RGBA),
// 32-bit float
R32F(GL30.GL_R32F, GlVersion.GL_30, PixelFormat.RED),
RG32F(GL30.GL_RG32F, GlVersion.GL_30, PixelFormat.RG),
RGB32F(GL30.GL_RGB32F, GlVersion.GL_30, PixelFormat.RGB),
RGBA32F(GL30.GL_RGBA32F, GlVersion.GL_30, PixelFormat.RGBA),
// 8-bit integer
R8I(GL30.GL_R8I, GlVersion.GL_30, PixelFormat.RED_INTEGER),
RG8I(GL30.GL_RG8I, GlVersion.GL_30, PixelFormat.RG_INTEGER),
RGB8I(GL30.GL_RGB8I, GlVersion.GL_30, PixelFormat.RGB_INTEGER),
RGBA8I(GL30.GL_RGBA8I, GlVersion.GL_30, PixelFormat.RGBA_INTEGER),
// 8-bit unsigned integer
R8UI(GL30.GL_R8UI, GlVersion.GL_30, PixelFormat.RED_INTEGER),
RG8UI(GL30.GL_RG8UI, GlVersion.GL_30, PixelFormat.RG_INTEGER),
RGB8UI(GL30.GL_RGB8UI, GlVersion.GL_30, PixelFormat.RGB_INTEGER),
RGBA8UI(GL30.GL_RGBA8UI, GlVersion.GL_30, PixelFormat.RGBA_INTEGER),
// 16-bit integer
R16I(GL30.GL_R16I, GlVersion.GL_30, PixelFormat.RED_INTEGER),
RG16I(GL30.GL_RG16I, GlVersion.GL_30, PixelFormat.RG_INTEGER),
RGB16I(GL30.GL_RGB16I, GlVersion.GL_30, PixelFormat.RGB_INTEGER),
RGBA16I(GL30.GL_RGBA16I, GlVersion.GL_30, PixelFormat.RGBA_INTEGER),
// 16-bit unsigned integer
R16UI(GL30.GL_R16UI, GlVersion.GL_30, PixelFormat.RED_INTEGER),
RG16UI(GL30.GL_RG16UI, GlVersion.GL_30, PixelFormat.RG_INTEGER),
RGB16UI(GL30.GL_RGB16UI, GlVersion.GL_30, PixelFormat.RGB_INTEGER),
RGBA16UI(GL30.GL_RGBA16UI, GlVersion.GL_30, PixelFormat.RGBA_INTEGER),
// 32-bit integer
R32I(GL30.GL_R32I, GlVersion.GL_30, PixelFormat.RED_INTEGER),
RG32I(GL30.GL_RG32I, GlVersion.GL_30, PixelFormat.RG_INTEGER),
RGB32I(GL30.GL_RGB32I, GlVersion.GL_30, PixelFormat.RGB_INTEGER),
RGBA32I(GL30.GL_RGBA32I, GlVersion.GL_30, PixelFormat.RGBA_INTEGER),
// 32-bit unsigned integer
R32UI(GL30.GL_R32UI, GlVersion.GL_30, PixelFormat.RED_INTEGER),
RG32UI(GL30.GL_RG32UI, GlVersion.GL_30, PixelFormat.RG_INTEGER),
RGB32UI(GL30.GL_RGB32UI, GlVersion.GL_30, PixelFormat.RGB_INTEGER),
RGBA32UI(GL30.GL_RGBA32UI, GlVersion.GL_30, PixelFormat.RGBA_INTEGER),
// 2-bit normalized
RGBA2(GL11.GL_RGBA2, GlVersion.GL_11, PixelFormat.RGBA),
// 4-bit normalized
RGBA4(GL11.GL_RGBA4, GlVersion.GL_11, PixelFormat.RGBA),
// Mixed
R3_G3_B2(GL11.GL_R3_G3_B2, GlVersion.GL_11, PixelFormat.RGB),
RGB5_A1(GL11.GL_RGB5_A1, GlVersion.GL_11, PixelFormat.RGBA),
RGB565(GL41.GL_RGB565, GlVersion.GL_41, PixelFormat.RGB),
RGB10_A2(GL11.GL_RGB10_A2, GlVersion.GL_11, PixelFormat.RGBA),
RGB10_A2UI(GL33.GL_RGB10_A2UI, GlVersion.GL_33, PixelFormat.RGBA_INTEGER),
R11F_G11F_B10F(GL30.GL_R11F_G11F_B10F, GlVersion.GL_30, PixelFormat.RGB),
RGB9_E5(GL30.GL_RGB9_E5, GlVersion.GL_30, PixelFormat.RGB);
private final int glFormat;
private final GlVersion minimumGlVersion;
private final PixelFormat expectedPixelFormat;
InternalTextureFormat(int glFormat, GlVersion minimumGlVersion, PixelFormat expectedPixelFormat) {
this.glFormat = glFormat;
this.minimumGlVersion = minimumGlVersion;
this.expectedPixelFormat = expectedPixelFormat;
}
public static Optional<InternalTextureFormat> fromString(String name) {
try {
return Optional.of(InternalTextureFormat.valueOf(name));
} catch (IllegalArgumentException e) {
return Optional.empty();
}
}
public int getGlFormat() {
return glFormat;
}
public PixelFormat getPixelFormat() { return expectedPixelFormat; }
public GlVersion getMinimumGlVersion() {
return minimumGlVersion;
}
public InternalTextureFormat getColorRenderableFallback() {
if (!RenderSystem.supportsSnormFormats()) {
return switch (this) {
case R8_SNORM, RG8_SNORM, RGB8_SNORM, RGBA8_SNORM -> RGBA16F;
case R16_SNORM, RG16_SNORM, RGB16_SNORM, RGBA16_SNORM -> RGBA16F;
default -> this.getPackedFloatFallback();
};
}
return this.getPackedFloatFallback();
}
private InternalTextureFormat getPackedFloatFallback() {
if (!RenderSystem.supportsPackedFloatRenderable()) {
return switch (this) {
case R11F_G11F_B10F, RGB9_E5 -> RGBA16F;
case RGB8 -> RGBA8;
case RGB16 -> RGBA16;
case RGB16F -> RGBA16F;
case RGB32F -> RGBA32F;
default -> this;
};
}
return this;
}
}
@@ -1,53 +0,0 @@
package net.coderbot.iris.gl.texture;
import net.coderbot.iris.gl.GlVersion;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL30;
import java.util.Optional;
public enum PixelFormat {
RED(GL11.GL_RED, GlVersion.GL_11, false),
RG(GL30.GL_RG, GlVersion.GL_30, false),
RGB(GL11.GL_RGB, GlVersion.GL_11, false),
BGR(GL12.GL_BGR, GlVersion.GL_12, false),
RGBA(GL11.GL_RGBA, GlVersion.GL_11, false),
BGRA(GL12.GL_BGRA, GlVersion.GL_12, false),
RED_INTEGER(GL30.GL_RED_INTEGER, GlVersion.GL_30, true),
RG_INTEGER(GL30.GL_RG_INTEGER, GlVersion.GL_30, true),
RGB_INTEGER(GL30.GL_RGB_INTEGER, GlVersion.GL_30, true),
BGR_INTEGER(GL30.GL_BGR_INTEGER, GlVersion.GL_30, true),
RGBA_INTEGER(GL30.GL_RGBA_INTEGER, GlVersion.GL_30, true),
BGRA_INTEGER(GL30.GL_BGRA_INTEGER, GlVersion.GL_30, true);
private final int glFormat;
private final GlVersion minimumGlVersion;
private final boolean isInteger;
PixelFormat(int glFormat, GlVersion minimumGlVersion, boolean isInteger) {
this.glFormat = glFormat;
this.minimumGlVersion = minimumGlVersion;
this.isInteger = isInteger;
}
public static Optional<PixelFormat> fromString(String name) {
try {
return Optional.of(PixelFormat.valueOf(name));
} catch (IllegalArgumentException e) {
return Optional.empty();
}
}
public int getGlFormat() {
return glFormat;
}
public GlVersion getMinimumGlVersion() {
return minimumGlVersion;
}
public boolean isInteger() {
return isInteger;
}
}
@@ -1,55 +0,0 @@
package net.coderbot.iris.gl.texture;
import net.coderbot.iris.gl.GlVersion;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL30;
import java.util.Optional;
public enum PixelType {
BYTE(GL11.GL_BYTE, GlVersion.GL_11),
SHORT(GL11.GL_SHORT, GlVersion.GL_11),
INT(GL11.GL_INT, GlVersion.GL_11),
HALF_FLOAT(GL30.GL_HALF_FLOAT, GlVersion.GL_30),
FLOAT(GL11.GL_FLOAT, GlVersion.GL_11),
UNSIGNED_BYTE(GL11.GL_UNSIGNED_BYTE, GlVersion.GL_11),
UNSIGNED_BYTE_3_3_2(GL12.GL_UNSIGNED_BYTE_3_3_2, GlVersion.GL_12),
UNSIGNED_BYTE_2_3_3_REV(GL12.GL_UNSIGNED_BYTE_2_3_3_REV, GlVersion.GL_12),
UNSIGNED_SHORT(GL11.GL_UNSIGNED_SHORT, GlVersion.GL_11),
UNSIGNED_SHORT_5_6_5(GL12.GL_UNSIGNED_SHORT_5_6_5, GlVersion.GL_12),
UNSIGNED_SHORT_5_6_5_REV(GL12.GL_UNSIGNED_SHORT_5_6_5_REV, GlVersion.GL_12),
UNSIGNED_SHORT_4_4_4_4(GL12.GL_UNSIGNED_SHORT_4_4_4_4, GlVersion.GL_12),
UNSIGNED_SHORT_4_4_4_4_REV(GL12.GL_UNSIGNED_SHORT_4_4_4_4_REV, GlVersion.GL_12),
UNSIGNED_SHORT_5_5_5_1(GL12.GL_UNSIGNED_SHORT_5_5_5_1, GlVersion.GL_12),
UNSIGNED_SHORT_1_5_5_5_REV(GL12.GL_UNSIGNED_SHORT_1_5_5_5_REV, GlVersion.GL_12),
UNSIGNED_INT(GL11.GL_UNSIGNED_INT, GlVersion.GL_11),
UNSIGNED_INT_8_8_8_8(GL12.GL_UNSIGNED_INT_8_8_8_8, GlVersion.GL_12),
UNSIGNED_INT_8_8_8_8_REV(GL12.GL_UNSIGNED_INT_8_8_8_8_REV, GlVersion.GL_12),
UNSIGNED_INT_10_10_10_2(GL12.GL_UNSIGNED_INT_10_10_10_2, GlVersion.GL_12),
UNSIGNED_INT_2_10_10_10_REV(GL12.GL_UNSIGNED_INT_2_10_10_10_REV, GlVersion.GL_12);
private final int glFormat;
private final GlVersion minimumGlVersion;
PixelType(int glFormat, GlVersion minimumGlVersion) {
this.glFormat = glFormat;
this.minimumGlVersion = minimumGlVersion;
}
public static Optional<PixelType> fromString(String name) {
try {
return Optional.of(PixelType.valueOf(name));
} catch (IllegalArgumentException e) {
return Optional.empty();
}
}
public int getGlFormat() {
return glFormat;
}
public GlVersion getMinimumGlVersion() {
return minimumGlVersion;
}
}
@@ -1,5 +1,7 @@
package net.coderbot.iris.gl.texture;
import com.gtnewhorizons.angelica.glsm.texture.TextureType;
import java.util.function.IntSupplier;
public interface TextureAccess {
@@ -1,5 +1,10 @@
package net.coderbot.iris.gl.texture;
import com.gtnewhorizons.angelica.glsm.texture.InternalTextureFormat;
import com.gtnewhorizons.angelica.glsm.texture.PixelFormat;
import com.gtnewhorizons.angelica.glsm.texture.PixelType;
import com.gtnewhorizons.angelica.glsm.texture.TextureType;
import lombok.Getter;
@Getter
@@ -1,42 +0,0 @@
package net.coderbot.iris.gl.texture;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL31;
import java.nio.ByteBuffer;
import java.util.Optional;
public enum TextureType {
TEXTURE_1D(GL11.GL_TEXTURE_1D),
TEXTURE_2D(GL11.GL_TEXTURE_2D),
TEXTURE_3D(GL12.GL_TEXTURE_3D),
TEXTURE_RECTANGLE(GL31.GL_TEXTURE_RECTANGLE);
private final int glType;
TextureType(int glType) {
this.glType = glType;
}
public static Optional<TextureType> fromString(String name) {
try {
return Optional.of(TextureType.valueOf(name));
} catch (IllegalArgumentException e) {
return Optional.empty();
}
}
public int getGlType() {
return glType;
}
public void apply(int texture, int sizeX, int sizeY, int sizeZ, int internalFormat, int format, int pixelType, ByteBuffer pixels) {
switch (this) {
case TEXTURE_1D -> RenderSystem.texImage1D(texture, glType, 0, internalFormat, sizeX, 0, format, pixelType, pixels);
case TEXTURE_2D, TEXTURE_RECTANGLE -> RenderSystem.texImage2D(texture, glType, 0, internalFormat, sizeX, sizeY, 0, format, pixelType, pixels);
case TEXTURE_3D -> RenderSystem.texImage3D(texture, glType, 0, internalFormat, sizeX, sizeY, sizeZ, 0, format, pixelType, pixels);
}
}
}
@@ -1,5 +1,7 @@
package net.coderbot.iris.gl.texture;
import com.gtnewhorizons.angelica.glsm.texture.TextureType;
import java.util.function.IntSupplier;
public class TextureWrapper implements TextureAccess {
@@ -1,5 +1,7 @@
package net.coderbot.iris.gl.uniform;
import com.gtnewhorizons.angelica.glsm.shader.UniformType;
import net.coderbot.iris.gl.state.ValueUpdateNotifier;
import org.joml.Vector2ic;
import org.joml.Vector3ic;
@@ -4,6 +4,7 @@ import com.gtnewhorizons.angelica.glsm.RenderSystem;
import net.coderbot.iris.gl.state.ValueUpdateNotifier;
public class FloatUniform extends Uniform {
private final Runnable updateListener = this::updateValue;
private float cachedValue;
private final FloatSupplier value;
@@ -23,7 +24,7 @@ public class FloatUniform extends Uniform {
updateValue();
if (notifier != null) {
notifier.setListener(this::updateValue);
notifier.setListener(updateListener);
}
}
@@ -6,6 +6,7 @@ import net.coderbot.iris.gl.state.ValueUpdateNotifier;
import java.util.function.IntSupplier;
public class IntUniform extends Uniform {
private final Runnable updateListener = this::updateValue;
private int cachedValue;
private final IntSupplier value;
@@ -25,7 +26,7 @@ public class IntUniform extends Uniform {
updateValue();
if (notifier != null) {
notifier.setListener(this::updateValue);
notifier.setListener(updateListener);
}
}
@@ -1,5 +1,7 @@
package net.coderbot.iris.gl.uniform;
import com.gtnewhorizons.angelica.glsm.shader.UniformType;
import net.minecraft.util.Vec3;
import org.joml.Matrix4f;
import org.joml.Matrix4fc;
@@ -0,0 +1,77 @@
package net.coderbot.iris.gl.uniform;
import com.gtnewhorizons.angelica.glsm.shader.UniformType;
import net.coderbot.iris.gl.state.ValueUpdateNotifier;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.OptionalInt;
import java.util.Set;
public final class ManifestCollectingHolder implements DynamicLocationalUniformHolder {
private final List<String> namesById = new ObjectArrayList<>();
private final Map<String, UniformType> typesByName = new Object2ObjectOpenHashMap<>();
private final List<UniformManifest.Entry> entries = new ArrayList<>();
private final Set<String> dynamicNames = new LinkedHashSet<>();
private final Set<String> externallyManagedNames = new LinkedHashSet<>();
@Override
public OptionalInt location(String name, UniformType type) {
if (typesByName.putIfAbsent(name, type) != null) return OptionalInt.empty();
final int id = namesById.size();
namesById.add(name);
return OptionalInt.of(id);
}
private String nameFor(int location) {
return location >= 0 && location < namesById.size() ? namesById.get(location) : null;
}
@Override
public ManifestCollectingHolder addUniform(UniformUpdateFrequency updateFrequency, Uniform uniform) {
Objects.requireNonNull(uniform);
final String name = nameFor(uniform.getLocation());
if (name == null) return this;
switch (updateFrequency) {
case ONCE, PER_TICK, PER_FRAME -> entries.add(new UniformManifest.Entry(name, typesByName.get(name), updateFrequency));
case CUSTOM -> { }
}
return this;
}
@Override
public ManifestCollectingHolder addDynamicUniform(Uniform uniform, ValueUpdateNotifier notifier) {
Objects.requireNonNull(uniform);
final String name = nameFor(uniform.getLocation());
if (name != null) dynamicNames.add(name);
return this;
}
@Override
public ManifestCollectingHolder externallyManagedUniform(String name, UniformType type) {
externallyManagedNames.add(name);
return this;
}
public UniformManifest build() {
final List<UniformManifest.Entry> grouped = new ArrayList<>(entries.size());
for (UniformUpdateFrequency freq : GROUP_ORDER) {
for (UniformManifest.Entry e : entries) {
if (e.frequency() == freq) grouped.add(e);
}
}
return new UniformManifest(grouped, dynamicNames, externallyManagedNames);
}
private static final UniformUpdateFrequency[] GROUP_ORDER = {
UniformUpdateFrequency.ONCE, UniformUpdateFrequency.PER_TICK, UniformUpdateFrequency.PER_FRAME
};
}
@@ -9,13 +9,13 @@ import java.util.function.Supplier;
public class MatrixFromFloatArrayUniform extends Uniform {
private final FloatBuffer buffer = BufferUtils.createFloatBuffer(16);
private float[] cachedValue;
private final float[] cachedValue = new float[16];
private boolean hasValue;
private final Supplier<float[]> value;
MatrixFromFloatArrayUniform(int location, Supplier<float[]> value) {
super(location);
this.cachedValue = null;
this.value = value;
}
@@ -23,8 +23,9 @@ public class MatrixFromFloatArrayUniform extends Uniform {
public void update() {
float[] newValue = value.get();
if (!Arrays.equals(newValue, cachedValue)) {
cachedValue = Arrays.copyOf(newValue, 16);
if (!hasValue || !Arrays.equals(newValue, cachedValue)) {
hasValue = true;
System.arraycopy(newValue, 0, cachedValue, 0, 16);
buffer.put(cachedValue);
buffer.rewind();
@@ -10,13 +10,13 @@ import java.util.function.Supplier;
public class MatrixUniform extends Uniform {
private final FloatBuffer buffer = BufferUtils.createFloatBuffer(16);
private Matrix4f cachedValue;
private final Matrix4f cachedValue = new Matrix4f();
private boolean hasValue;
private final Supplier<Matrix4fc> value;
MatrixUniform(int location, Supplier<Matrix4fc> value) {
super(location);
this.cachedValue = null;
this.value = value;
}
@@ -26,8 +26,9 @@ public class MatrixUniform extends Uniform {
if( newValue == null ){
throw new RuntimeException("MatrixUniform value is null");
}
if (!newValue.equals(cachedValue)) {
cachedValue = new Matrix4f(newValue);
if (!hasValue || !newValue.equals(cachedValue)) {
hasValue = true;
cachedValue.set(newValue);
cachedValue.get(buffer);
buffer.rewind();
@@ -1,5 +1,7 @@
package net.coderbot.iris.gl.uniform;
import com.gtnewhorizons.angelica.glsm.shader.UniformType;
import net.minecraft.util.Vec3;
import org.joml.Matrix4fc;
import org.joml.Vector2f;
@@ -0,0 +1,38 @@
package net.coderbot.iris.gl.uniform;
import com.gtnewhorizons.angelica.glsm.shader.UniformType;
import java.util.Collections;
import java.util.List;
import java.util.Set;
public final class UniformManifest {
public record Entry(String name, UniformType type, UniformUpdateFrequency frequency) {}
private final List<Entry> entries;
private final Set<String> dynamicNames;
private final Set<String> externallyManagedNames;
UniformManifest(List<Entry> entries, Set<String> dynamicNames, Set<String> externallyManagedNames) {
this.entries = Collections.unmodifiableList(entries);
this.dynamicNames = Collections.unmodifiableSet(dynamicNames);
this.externallyManagedNames = Collections.unmodifiableSet(externallyManagedNames);
}
public List<Entry> entries() {
return entries;
}
public Set<String> dynamicNames() {
return dynamicNames;
}
public Set<String> externallyManagedNames() {
return externallyManagedNames;
}
public boolean isEmpty() {
return entries.isEmpty();
}
}
@@ -1,15 +0,0 @@
package net.coderbot.iris.gl.uniform;
public enum UniformType {
INT,
BOOL,
FLOAT,
MAT3,
MAT4,
VEC2,
VEC2I,
VEC3,
VEC3I,
VEC4,
VEC4I
}
@@ -8,6 +8,7 @@ import org.joml.Vector2ic;
import java.util.function.Supplier;
public class Vector2IntegerJomlUniform extends Uniform {
private final Runnable updateListener = this::updateValue;
private final Vector2i cachedValue;
private final Supplier<Vector2ic> value;
@@ -27,7 +28,7 @@ public class Vector2IntegerJomlUniform extends Uniform {
updateValue();
if (notifier != null) {
notifier.setListener(this::updateValue);
notifier.setListener(updateListener);
}
}
@@ -8,6 +8,7 @@ import org.joml.Vector3ic;
import java.util.function.Supplier;
public class Vector3IntegerJomlUniform extends Uniform {
private final Runnable updateListener = this::updateValue;
private final Vector3i cachedValue;
private final Supplier<Vector3ic> value;
@@ -27,7 +28,7 @@ public class Vector3IntegerJomlUniform extends Uniform {
updateValue();
if (notifier != null) {
notifier.setListener(this::updateValue);
notifier.setListener(updateListener);
}
}
@@ -7,6 +7,7 @@ import java.util.Arrays;
import java.util.function.Supplier;
public class Vector4ArrayUniform extends Uniform {
private final Runnable updateListener = this::updateValue;
private final Supplier<float[]> value;
private float[] cachedValue;
@@ -26,7 +27,7 @@ public class Vector4ArrayUniform extends Uniform {
updateValue();
if (notifier != null) {
notifier.setListener(this::updateValue);
notifier.setListener(updateListener);
}
}
@@ -8,6 +8,7 @@ import org.joml.Vector4ic;
import java.util.function.Supplier;
public class Vector4IntegerJomlUniform extends Uniform {
private final Runnable updateListener = this::updateValue;
private final Vector4i cachedValue;
private final Supplier<Vector4ic> value;
@@ -27,7 +28,7 @@ public class Vector4IntegerJomlUniform extends Uniform {
updateValue();
if (notifier != null) {
notifier.setListener(this::updateValue);
notifier.setListener(updateListener);
}
}
@@ -8,6 +8,7 @@ import org.joml.Vector4fc;
import java.util.function.Supplier;
public class Vector4Uniform extends Uniform {
private final Runnable updateListener = this::updateValue;
private final Vector4f cachedValue;
private final Supplier<Vector4fc> value;
@@ -27,7 +28,7 @@ public class Vector4Uniform extends Uniform {
updateValue();
if (notifier != null) {
notifier.setListener(this::updateValue);
notifier.setListener(updateListener);
}
}
@@ -12,6 +12,7 @@ public class GbufferPrograms {
private static boolean entities;
private static boolean blockEntities;
private static boolean outline;
private static boolean entityLoop;
private static Runnable phaseChangeListener;
static {
@@ -32,6 +33,29 @@ public class GbufferPrograms {
entities = true;
}
public static void beginEntityLoop() {
entityLoop = true;
setPhase(WorldRenderingPhase.ENTITIES);
setBlockEntityDefaults();
}
public static void endEntityLoop() {
entityLoop = false;
setPhase(WorldRenderingPhase.NONE);
}
public static boolean isEntityLoopActive() {
return entityLoop;
}
public static void onEntityRenderBoundary() {
final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable();
if (pipeline != null) {
pipeline.onEntityRenderBoundary();
}
}
public static void endEntities() {
if (!entities) {
throw new IllegalStateException("GbufferPrograms in weird state, tried to call endEntities when entities = false");
@@ -3,6 +3,7 @@ package net.coderbot.iris.pipeline;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import net.coderbot.iris.gl.framebuffer.GlFramebuffer;
import net.minecraft.client.Minecraft;
import net.minecraft.profiler.Profiler;
import org.joml.Vector4f;
import org.lwjgl.opengl.GL11;
@@ -10,13 +11,15 @@ import java.util.Objects;
import java.util.function.IntSupplier;
public class ClearPass {
private final String name;
private final Vector4f color;
private final IntSupplier viewportX;
private final IntSupplier viewportY;
private final GlFramebuffer framebuffer;
private final int clearFlags;
public ClearPass(Vector4f color, IntSupplier viewportX, IntSupplier viewportY, GlFramebuffer framebuffer, int clearFlags) {
public ClearPass(String name, Vector4f color, IntSupplier viewportX, IntSupplier viewportY, GlFramebuffer framebuffer, int clearFlags) {
this.name = name;
this.color = color;
this.viewportX = viewportX;
this.viewportY = viewportY;
@@ -25,6 +28,8 @@ public class ClearPass {
}
public void execute(Vector4f defaultClearColor) {
final Profiler profiler = Minecraft.getMinecraft().mcProfiler;
profiler.startSection(name);
GLStateManager.glViewport(0, 0, viewportX.getAsInt(), viewportY.getAsInt());
framebuffer.bind();
@@ -36,9 +41,7 @@ public class ClearPass {
GLStateManager.glClearColor(color.x, color.y, color.z, color.w);
GLStateManager.glClear(clearFlags);
if (Minecraft.isRunningOnMac) {
GLStateManager.glGetError();
}
profiler.endSection();
}
public GlFramebuffer getFramebuffer() {
@@ -69,9 +69,9 @@ public class ClearPassCreator {
}
// No need to clear the depth buffer, since we're using Minecraft's depth buffer.
clearPasses.add(new ClearPass(clearInfo.getColor(), clearInfo::getWidth, clearInfo::getHeight,
clearPasses.add(new ClearPass(clearPassName("alt", clearBuffers), clearInfo.getColor(), clearInfo::getWidth, clearInfo::getHeight,
renderTargets.createClearFramebuffer(true, clearBuffers), GL11.GL_COLOR_BUFFER_BIT));
clearPasses.add(new ClearPass(clearInfo.getColor(), clearInfo::getWidth, clearInfo::getHeight,
clearPasses.add(new ClearPass(clearPassName("main", clearBuffers), clearInfo.getColor(), clearInfo::getWidth, clearInfo::getHeight,
renderTargets.createClearFramebuffer(false, clearBuffers), GL11.GL_COLOR_BUFFER_BIT));
}
});
@@ -115,14 +115,22 @@ public class ClearPassCreator {
}
// No need to clear the depth buffer, since we're using Minecraft's depth buffer.
clearPasses.add(new ClearPass(clearColor, renderTargets::getResolution, renderTargets::getResolution,
clearPasses.add(new ClearPass(clearPassName("shadow_alt", clearBuffers), clearColor, renderTargets::getResolution, renderTargets::getResolution,
renderTargets.createFramebufferWritingToAlt(clearBuffers), GL11.GL_COLOR_BUFFER_BIT));
clearPasses.add(new ClearPass(clearColor, renderTargets::getResolution, renderTargets::getResolution,
clearPasses.add(new ClearPass(clearPassName("shadow_main", clearBuffers), clearColor, renderTargets::getResolution, renderTargets::getResolution,
renderTargets.createFramebufferWritingToMain(clearBuffers), GL11.GL_COLOR_BUFFER_BIT));
}
});
return ImmutableList.copyOf(clearPasses);
}
private static String clearPassName(String kind, int[] clearBuffers) {
final StringBuilder sb = new StringBuilder("iris_clear_").append(kind);
for (int buffer : clearBuffers) {
sb.append('_').append(buffer);
}
return sb.toString();
}
}
@@ -2,6 +2,8 @@ package net.coderbot.iris.pipeline;
import org.joml.Vector4f;
import java.util.Objects;
public class ClearPassInformation {
private final Vector4f color;
private final int width;
@@ -33,6 +35,11 @@ public class ClearPassInformation {
ClearPassInformation information = (ClearPassInformation) obj;
return information.color.equals(this.color) && information.height == this.height && information.width == this.width;
return Objects.equals(information.color, this.color) && information.height == this.height && information.width == this.width;
}
@Override
public int hashCode() {
return Objects.hash(color, width, height);
}
}
@@ -1,5 +1,6 @@
package net.coderbot.iris.pipeline;
import com.gtnewhorizons.angelica.compat.mojang.NativeImage;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.mixins.interfaces.EntityRendererAccessor;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
@@ -9,7 +10,7 @@ import lombok.Getter;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gl.texture.GlTexture;
import net.coderbot.iris.gl.texture.TextureAccess;
import net.coderbot.iris.gl.texture.TextureType;
import com.gtnewhorizons.angelica.glsm.texture.TextureType;
import net.coderbot.iris.gl.texture.TextureWrapper;
import net.coderbot.iris.rendertarget.NativeImageBackedCustomTexture;
import net.coderbot.iris.rendertarget.NativeImageBackedNoiseTexture;
@@ -33,8 +34,11 @@ import org.lwjgl.opengl.GL11;
import java.io.IOException;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
public class CustomTextureManager {
@Getter private final EnumMap<TextureStage, Object2ObjectMap<String, TextureAccess>> customTextureIdMap = new EnumMap<>(TextureStage.class);
@@ -48,10 +52,14 @@ public class CustomTextureManager {
private final List<AbstractTexture> ownedTextures = new ArrayList<>();
private final List<GlTexture> ownedRawTextures = new ArrayList<>();
private Map<CustomTextureData.PngData, CompletableFuture<NativeImage>> pngDecodeFutures;
public CustomTextureManager(PackDirectives packDirectives,
EnumMap<TextureStage, Object2ObjectMap<String, CustomTextureData>> customTextureDataMap,
Object2ObjectMap<String, CustomTextureData> irisCustomTextureDataMap,
Optional<CustomTextureData> customNoiseTextureData) {
this.pngDecodeFutures = submitPngDecodes(customTextureDataMap, irisCustomTextureDataMap, customNoiseTextureData);
customTextureDataMap.forEach((textureStage, customTextureStageDataMap) -> {
final Object2ObjectMap<String, TextureAccess> customTextureIds = new Object2ObjectOpenHashMap<>();
@@ -93,9 +101,37 @@ public class CustomTextureManager {
});
}
private static Map<CustomTextureData.PngData, CompletableFuture<NativeImage>> submitPngDecodes(
EnumMap<TextureStage, Object2ObjectMap<String, CustomTextureData>> customTextureDataMap,
Object2ObjectMap<String, CustomTextureData> irisCustomTextureDataMap,
Optional<CustomTextureData> customNoiseTextureData) {
final Map<CustomTextureData.PngData, CompletableFuture<NativeImage>> futures = new HashMap<>();
customTextureDataMap.values().forEach(stage -> stage.values().forEach(td -> tryQueueDecode(td, futures)));
irisCustomTextureDataMap.values().forEach(td -> tryQueueDecode(td, futures));
customNoiseTextureData.ifPresent(td -> tryQueueDecode(td, futures));
return futures;
}
private static void tryQueueDecode(CustomTextureData td, Map<CustomTextureData.PngData, CompletableFuture<NativeImage>> futures) {
if (!(td instanceof CustomTextureData.PngData png)) return;
if (futures.containsKey(png)) return;
futures.put(png, Iris.ShaderTransformExecutor.submitTracked(() -> {
try {
return NativeImageBackedCustomTexture.decode(png.getContent());
} catch (IOException e) {
return null;
}
}));
}
private TextureAccess createCustomTexture(CustomTextureData textureData) throws IOException {
if (textureData instanceof CustomTextureData.PngData) {
final AbstractTexture texture = new NativeImageBackedCustomTexture((CustomTextureData.PngData) textureData);
if (textureData instanceof CustomTextureData.PngData png) {
final CompletableFuture<NativeImage> future = pngDecodeFutures != null ? pngDecodeFutures.get(png) : null;
final NativeImage decoded = future != null ? future.join() : NativeImageBackedCustomTexture.decode(png.getContent());
if (decoded == null) {
throw new IOException("Failed to decode PNG (see prior log for cause)");
}
final AbstractTexture texture = new NativeImageBackedCustomTexture(decoded, png.getFilteringData());
ownedTextures.add(texture);
return new TextureWrapper(texture::getGlTextureId, TextureType.TEXTURE_2D);
File diff suppressed because it is too large. Load diff
@@ -11,7 +11,7 @@ import net.coderbot.iris.features.FeatureFlags;
import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability;
import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition;
import net.coderbot.iris.gbuffer_overrides.state.RenderTargetStateListener;
import net.coderbot.iris.gl.texture.TextureType;
import com.gtnewhorizons.angelica.glsm.texture.TextureType;
import net.coderbot.iris.helpers.Tri;
import net.coderbot.iris.shaderpack.CloudSetting;
import net.coderbot.iris.shaderpack.texture.TextureStage;
@@ -103,6 +103,11 @@ public class FixedFunctionWorldRenderingPipeline implements WorldRenderingPipeli
}
@Override
public void rebindCurrentPass() {
// no-op: fixed-function pipeline doesn't manage Pass state
}
@Override
public void beginHand() {
// stub: nothing to do here
@@ -5,11 +5,18 @@ import com.gtnewhorizons.angelica.compat.mojang.Camera;
import com.gtnewhorizons.angelica.compat.mojang.GameModeUtil;
import com.gtnewhorizons.angelica.compat.toremove.MatrixStack;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.glsm.GLDebug;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
import com.gtnewhorizons.angelica.profiling.RenderClassTimings;
import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher;
import com.gtnewhorizons.angelica.rendering.tesr.TesrBatchRenderer;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import com.gtnewhorizons.angelica.rendering.PlayerReflectionCapture;
import com.gtnewhorizons.angelica.rendering.RenderingState;
import com.gtnewhorizons.angelica.rendering.celeritas.AngelicaRenderSectionManager;
import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasWorldRenderer;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import net.coderbot.iris.Iris;
import net.coderbot.iris.compat.dh.DHCompat;
import net.coderbot.iris.gui.option.IrisVideoSettings;
@@ -21,6 +28,7 @@ import net.coderbot.iris.shaderpack.ShadowCullState;
import net.coderbot.iris.shadow.ShadowMatrices;
import net.coderbot.iris.shadows.CullingDataCache;
import net.coderbot.iris.shadows.ShadowCompositeRenderer;
import net.coderbot.iris.shadows.ShadowGraphGate;
import net.coderbot.iris.shadows.ShadowRenderTargets;
import net.coderbot.iris.shadows.frustum.BoxCuller;
import net.coderbot.iris.shadows.frustum.CullEverythingFrustum;
@@ -31,6 +39,7 @@ import net.coderbot.iris.shadows.frustum.fallback.BoxCullingFrustum;
import net.coderbot.iris.shadows.frustum.fallback.NonCullingFrustum;
import net.coderbot.iris.uniforms.CapturedRenderingState;
import net.coderbot.iris.uniforms.CelestialUniforms;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.client.renderer.EntityRenderer;
@@ -43,6 +52,7 @@ import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.profiler.Profiler;
import net.minecraft.tileentity.TileEntity;
import org.embeddedt.embeddium.impl.render.viewport.Viewport;
import org.embeddedt.embeddium.impl.render.viewport.ViewportProvider;
import org.joml.Matrix4f;
import org.joml.Matrix4fc;
@@ -62,13 +72,20 @@ import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.function.BooleanSupplier;
public class ShadowRenderer {
private static final long P_SHADOW_ENTITIES_RENDERED = Tracy.plotHandle("shadow.entitiesRendered");
private static final Tracy.ZoneId Z_GEN_MIPMAP = Tracy.zoneId("genMipmap", Tracy.COLOR_IRIS);
private static final Tracy.ZoneId Z_SHADOW_FRUSTUM = Tracy.zoneId("shadowFrustum", Tracy.COLOR_IRIS);
private static final Tracy.ZoneId Z_SHADOW_VIEWPORT = Tracy.zoneId("shadowViewport", Tracy.COLOR_IRIS);
private static final Tracy.ZoneId Z_SHADOW_MODEL_PARTS = Tracy.zoneId("shadowModelParts", Tracy.COLOR_IRIS);
public static final Matrix4f MODELVIEW = new Matrix4f();
public static final FloatBuffer MODELVIEW_BUFFER = BufferUtils.createFloatBuffer(16);
public static final Matrix4f PROJECTION = new Matrix4f();
public static final List<TileEntity> visibleTileEntities = new ArrayList<>();
public static final List<TileEntity> globalTileEntities = new ArrayList<>();
public static final List<List<TileEntity>> visibleTileEntities = new ArrayList<>();
public static final List<List<TileEntity>> globalTileEntities = new ArrayList<>();
public static boolean ACTIVE = false;
public static Frustrum FRUSTUM;
@@ -89,6 +106,7 @@ public class ShadowRenderer {
private final ShadowCullState packCullingState;
private final ShadowCompositeRenderer compositeRenderer;
private boolean packHasVoxelization;
private boolean playerReflectionCaptureEnabled = true;
private final boolean shouldRenderTerrain;
private final boolean shouldRenderTranslucent;
private final boolean shouldRenderEntities;
@@ -102,26 +120,66 @@ public class ShadowRenderer {
private int renderedShadowEntities = 0;
private int renderedShadowTileEntities = 0;
private Profiler profiler;
private final List<Entity> renderedEntitiesList = new ArrayList<>(64);
private final ObjectArrayList<Entity> renderedEntitiesList = new ObjectArrayList<>(64);
private final MatrixStack shadowModelView = new MatrixStack();
private final CelestialUniforms celestialUniforms;
private final AdvancedShadowCullingFrustum cachedAdvancedFrustum = new AdvancedShadowCullingFrustum();
private static final class FrustumCaches {
final AdvancedShadowCullingFrustum advancedFrustum = new AdvancedShadowCullingFrustum();
BoxCuller boxCuller;
BoxCullingFrustum boxCullingFrustum;
BoxCuller advancedBoxCuller;
double lastBoxCullerDistance = -1;
double lastAdvancedBoxCullerDistance = -1;
}
private static final long SHADOW_RELAY_MAX_AGE_NANOS = 250_000_000L;
public static boolean SHADOW_TERRAIN_RELAID = true;
private static float activeShadowAngle = Float.NaN;
private final FrustumCaches terrainFrustumCaches = new FrustumCaches();
private final FrustumCaches entityFrustumCaches = new FrustumCaches();
private float lastGraphShadowAngle = Float.NaN;
private float relayShadowAngle = Float.NaN;
private FrustumHolder preSubmitFrustumHolder = new FrustumHolder();
private final FrustumCaches preSubmitFrustumCaches = new FrustumCaches();
private boolean preSubmitActive;
private float preSubmittedShadowAngle = Float.NaN;
public void preSubmitGraphUpdate(int frame, boolean spectator) {
final AngelicaRenderSectionManager rsm = CeleritasWorldRenderer.getInstance().getRenderSectionManager();
final float currentShadowAngle = getShadowAngle();
if (ShadowGraphGate.shouldMarkDirty(lastGraphShadowAngle, currentShadowAngle)) {
rsm.markShadowGraphDirty();
lastGraphShadowAngle = currentShadowAngle;
}
if (!rsm.isShadowGraphDirty()) return;
preSubmitFrustumHolder = createShadowFrustum(renderDistanceMultiplier, preSubmitFrustumHolder, preSubmitFrustumCaches);
if (!(preSubmitFrustumHolder.getFrustum() instanceof ViewportProvider provider)) return;
final Vector3d entityPos = Camera.INSTANCE.getEntityPos();
preSubmitFrustumHolder.getFrustum().setPosition(entityPos.x, entityPos.y, entityPos.z);
if (rsm.preSubmitShadowGraphUpdate(provider.sodium$createViewport(), frame, spectator)) {
preSubmittedShadowAngle = lastGraphShadowAngle;
preSubmitActive = true;
}
}
private long lastRelayNanos;
private final Vector3f shadowLightVectorCache = new Vector3f();
private BoxCuller cachedBoxCuller;
private BoxCullingFrustum cachedBoxCullingFrustum;
private BoxCuller cachedAdvancedBoxCuller;
private BoxCuller cachedTileEntityCuller;
private double lastBoxCullerDistance = -1;
private double lastAdvancedBoxCullerDistance = -1;
private double lastTileEntityCullerDistance = -1;
private final boolean shouldRenderDH;
private final float nearPlane, farPlane;
private final BooleanSupplier packUsesShadowtex1;
public ShadowRenderer(ProgramSource shadow, PackDirectives directives, ShadowRenderTargets shadowRenderTargets, ShadowCompositeRenderer compositeRenderer) {
public ShadowRenderer(ProgramSource shadow, PackDirectives directives, ShadowRenderTargets shadowRenderTargets, ShadowCompositeRenderer compositeRenderer, BooleanSupplier packUsesShadowtex1) {
this.profiler = Minecraft.getMinecraft().mcProfiler;
SHADOW_TERRAIN_RELAID = true;
activeShadowAngle = Float.NaN;
final PackShadowDirectives shadowDirectives = directives.getShadowDirectives();
this.nearPlane = shadowDirectives.getNearPlane();
@@ -139,6 +197,7 @@ public class ShadowRenderer {
this.shouldRenderPlayer = shadowDirectives.shouldRenderPlayer();
this.shouldRenderBlockEntities = shadowDirectives.shouldRenderBlockEntities();
this.shouldRenderDH = shadowDirectives.isDhShadowEnabled().orElse(false);
this.packUsesShadowtex1 = packUsesShadowtex1;
this.compositeRenderer = compositeRenderer;
@@ -178,22 +237,28 @@ public class ShadowRenderer {
this.packHasVoxelization = packHasVoxelization || usesImages;
}
public void setPlayerReflectionCaptureEnabled(boolean enabled) {
this.playerReflectionCaptureEnabled = enabled;
}
public static MatrixStack createShadowModelView(float sunPathRotation, float intervalSize) {
// Use entity position for shadow matrix
final Vector3d entityPos = Camera.INSTANCE.getEntityPos();
final float angle = Float.isNaN(activeShadowAngle) ? getShadowAngle() : activeShadowAngle;
// Set up our modelview matrix stack
final MatrixStack modelView = new MatrixStack();
ShadowMatrices.createModelViewMatrix(modelView, getShadowAngle(), intervalSize, sunPathRotation, entityPos.x, entityPos.y, entityPos.z);
ShadowMatrices.createModelViewMatrix(modelView, angle, intervalSize, sunPathRotation, entityPos.x, entityPos.y, entityPos.z);
return modelView;
}
private MatrixStack getShadowModelView() {
private MatrixStack getShadowModelView(float shadowAngle) {
final Vector3d entityPos = Camera.INSTANCE.getEntityPos();
shadowModelView.reset();
ShadowMatrices.createModelViewMatrix(shadowModelView, getShadowAngle(), this.intervalSize, this.sunPathRotation, entityPos.x, entityPos.y, entityPos.z);
ShadowMatrices.createModelViewMatrix(shadowModelView, shadowAngle, this.intervalSize, this.sunPathRotation, entityPos.x, entityPos.y, entityPos.z);
return shadowModelView;
}
@@ -292,11 +357,19 @@ public class ShadowRenderer {
}
private void setupMipmappingForTexture(int texture, int filteringMode) {
RenderSystem.generateMipmaps(texture, GL11.GL_TEXTURE_2D);
if (Tracy.ENABLED) {
Tracy.beginZone(Z_GEN_MIPMAP);
Tracy.zoneValue(texture);
}
try {
RenderSystem.generateMipmaps(texture, GL11.GL_TEXTURE_2D);
} finally {
if (Tracy.ENABLED) Tracy.endZone();
}
RenderSystem.texParameteri(texture, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, filteringMode);
}
private FrustumHolder createShadowFrustum(float renderMultiplier, FrustumHolder holder) {
private FrustumHolder createShadowFrustum(float renderMultiplier, FrustumHolder holder, FrustumCaches caches) {
// TODO: Cull entities / block entities with Advanced Frustum Culling even if voxelization is detected.
String distanceInfo;
String cullingInfo;
@@ -319,7 +392,7 @@ public class ShadowRenderer {
} else {
distanceInfo = distance + " blocks (set by shader pack)";
cullingInfo = "distance only " + reason;
holder.setInfo(getOrCreateBoxCullingFrustum(distance), distanceInfo, cullingInfo);
holder.setInfo(getOrCreateBoxCullingFrustum(distance, caches), distanceInfo, cullingInfo);
}
} else {
BoxCuller boxCuller;
@@ -349,7 +422,7 @@ public class ShadowRenderer {
return holder.setInfo(CULL_EVERYTHING_FRUSTUM, distanceInfo, cullingInfo);
}
boxCuller = getOrCreateAdvancedBoxCuller(distance);
boxCuller = getOrCreateAdvancedBoxCuller(distance, caches);
}
cullingInfo = (hasSafeZone ? "Safe Zone" : "Advanced") + " Frustum Culling enabled";
@@ -367,35 +440,35 @@ public class ShadowRenderer {
shadowLightVectorCache, boxCuller, distanceCuller);
return holder.setInfo(safeZoneFrustum, distanceInfo, cullingInfo);
} else {
cachedAdvancedFrustum.init(RenderingState.INSTANCE.getModelViewMatrix(), projView, shadowLightVectorCache, boxCuller);
return holder.setInfo(cachedAdvancedFrustum, distanceInfo, cullingInfo);
caches.advancedFrustum.init(RenderingState.INSTANCE.getModelViewMatrix(), projView, shadowLightVectorCache, boxCuller);
return holder.setInfo(caches.advancedFrustum, distanceInfo, cullingInfo);
}
}
return holder;
}
private BoxCullingFrustum getOrCreateBoxCullingFrustum(double distance) {
if (cachedBoxCuller == null) {
cachedBoxCuller = new BoxCuller(distance);
cachedBoxCullingFrustum = new BoxCullingFrustum(cachedBoxCuller);
lastBoxCullerDistance = distance;
} else if (lastBoxCullerDistance != distance) {
cachedBoxCuller.setMaxDistance(distance);
lastBoxCullerDistance = distance;
private static BoxCullingFrustum getOrCreateBoxCullingFrustum(double distance, FrustumCaches caches) {
if (caches.boxCuller == null) {
caches.boxCuller = new BoxCuller(distance);
caches.boxCullingFrustum = new BoxCullingFrustum(caches.boxCuller);
caches.lastBoxCullerDistance = distance;
} else if (caches.lastBoxCullerDistance != distance) {
caches.boxCuller.setMaxDistance(distance);
caches.lastBoxCullerDistance = distance;
}
return cachedBoxCullingFrustum;
return caches.boxCullingFrustum;
}
private BoxCuller getOrCreateAdvancedBoxCuller(double distance) {
if (cachedAdvancedBoxCuller == null) {
cachedAdvancedBoxCuller = new BoxCuller(distance);
lastAdvancedBoxCullerDistance = distance;
} else if (lastAdvancedBoxCullerDistance != distance) {
cachedAdvancedBoxCuller.setMaxDistance(distance);
lastAdvancedBoxCullerDistance = distance;
private static BoxCuller getOrCreateAdvancedBoxCuller(double distance, FrustumCaches caches) {
if (caches.advancedBoxCuller == null) {
caches.advancedBoxCuller = new BoxCuller(distance);
caches.lastAdvancedBoxCullerDistance = distance;
} else if (caches.lastAdvancedBoxCullerDistance != distance) {
caches.advancedBoxCuller.setMaxDistance(distance);
caches.lastAdvancedBoxCullerDistance = distance;
}
return cachedAdvancedBoxCuller;
return caches.advancedBoxCuller;
}
private BoxCuller getOrCreateTileEntityCuller(double distance) {
@@ -410,8 +483,6 @@ public class ShadowRenderer {
}
private void setupGlState(Matrix4f projMatrix) {
// Bind shadow framebuffer and set viewport to shadow resolution
targets.getDepthSourceFb().bind();
GLStateManager.glViewport(0, 0, resolution, resolution);
// Set up our projection matrix and load it into the legacy matrix stack
@@ -434,6 +505,9 @@ public class ShadowRenderer {
// Make sure to unload the projection matrix
RenderSystem.restoreProjectionMatrix();
GLStateManager.glDepthFunc(GL11.GL_LEQUAL);
GLStateManager.glClearDepth(1.0);
// Restore main framebuffer and viewport
Minecraft mc = Minecraft.getMinecraft();
mc.getFramebuffer().bindFramebuffer(false);
@@ -441,13 +515,17 @@ public class ShadowRenderer {
}
private void copyPreTranslucentDepth() {
profiler.endStartSection("translucent depth copy");
if (!packUsesShadowtex1.getAsBoolean()) {
return;
}
profiler.endStartSection("iris_shadow_translucent_depth_copy");
targets.copyPreTranslucentDepth();
}
private void renderEntities(EntityRenderer levelRenderer, Frustrum frustum, Object bufferSource, MatrixStack modelView, double cameraX, double cameraY, double cameraZ, float tickDelta) {
profiler.startSection("cull");
profiler.startSection("iris_shadow_cull");
renderedEntitiesList.clear();
@@ -462,31 +540,111 @@ public class ShadowRenderer {
renderedEntitiesList.add(entity);
}
profiler.endStartSection("sort");
profiler.endStartSection("iris_shadow_sort");
renderedEntitiesList.sort(ENTITY_CLASS_COMPARATOR);
renderedEntitiesList.unstableSort(ENTITY_CLASS_COMPARATOR);
profiler.endStartSection("build geometry");
profiler.endStartSection("iris_shadow_build_geometry");
setupEntityShadowState(modelView, cameraX, cameraY, cameraZ);
PlayerReflectionCapture.begin(player);
if (playerReflectionCaptureEnabled) {
PlayerReflectionCapture.begin(player);
}
ModelPartBatcher.INSTANCE.begin(ModelPartBatcher.Mode.ENTITIES, true);
try {
for (Entity entity : renderedEntitiesList) {
RenderManager.instance.renderEntitySimple(entity, tickDelta);
final long start = Tracy.ENABLED ? System.nanoTime() : 0L;
try {
RenderManager.instance.renderEntitySimple(entity, tickDelta);
} finally {
if (Tracy.ENABLED) RenderClassTimings.SHADOW_ENTITY.add(entity.getClass(), System.nanoTime() - start);
}
}
} finally {
flushShadowModelParts();
PlayerReflectionCapture.end();
teardownEntityShadowState();
}
renderedShadowEntities = renderedEntitiesList.size();
if (Tracy.ENABLED) Tracy.plotInt(P_SHADOW_ENTITIES_RENDERED, renderedShadowEntities);
profiler.endSection();
}
private boolean entityFrustumConstrained;
private Frustrum createEntityShadowFrustum(double entityX, double entityY, double entityZ) {
// Shader packs can shrink the entity shadow distance so faraway entities skip the shadow pass
entityFrustumConstrained = false;
if (Tracy.ENABLED) Tracy.beginZone(Z_SHADOW_FRUSTUM);
try {
if (entityShadowDistanceMultiplier == 1.0F || entityShadowDistanceMultiplier < 0.0F) {
entityFrustumHolder.setInfo(terrainFrustumHolder.getFrustum(), terrainFrustumHolder.getDistanceInfo(), terrainFrustumHolder.getCullingInfo());
return entityFrustumHolder.getFrustum();
}
entityFrustumConstrained = true;
entityFrustumHolder = createShadowFrustum(renderDistanceMultiplier * entityShadowDistanceMultiplier, entityFrustumHolder, entityFrustumCaches);
final Frustrum frustum = entityFrustumHolder.getFrustum();
frustum.setPosition(entityX, entityY, entityZ);
return frustum;
} finally {
if (Tracy.ENABLED) Tracy.endZone();
}
}
private void applyEntityShadowViewport(Frustrum entityShadowFrustum) {
if (Tracy.ENABLED) Tracy.beginZone(Z_SHADOW_VIEWPORT);
try {
CeleritasWorldRenderer.getInstance().setCurrentViewport(((ViewportProvider) entityShadowFrustum).sodium$createViewport());
} finally {
if (Tracy.ENABLED) Tracy.endZone();
}
}
private void renderShadowEntitiesAndPlayer(EntityRenderer levelRenderer, Frustrum entityShadowFrustum, MatrixStack modelView, double entityX, double entityY, double entityZ, float tickDelta) {
if (shouldRenderEntities) {
renderEntities(levelRenderer, entityShadowFrustum, null, modelView, entityX, entityY, entityZ, tickDelta);
} else if (shouldRenderPlayer) {
renderPlayerEntity(levelRenderer, entityShadowFrustum, null, modelView, entityX, entityY, entityZ, tickDelta);
}
}
private static boolean voxelizationActive() {
return Iris.getPipelineManager().getPipelineNullable() instanceof DeferredWorldRenderingPipeline deferred && deferred.getShadowVoxelizationCompute() != null;
}
private void renderSolidShadowTerrain(Minecraft mc, RenderGlobal rg, Camera playerCamera) {
// Render all opaque terrain unless pack requests not to
if (shouldRenderTerrain) {
mc.renderEngine.bindTexture(TextureMap.locationBlocksTexture);
rg.sortAndRender(mc.renderViewEntity, 0, playerCamera.getPartialTicks());
}
// Reset viewport in case terrain rendering changed it
GLStateManager.glViewport(0, 0, resolution, resolution);
}
// Saved RenderManager position for shadow pass
private double savedRenderPosX, savedRenderPosY, savedRenderPosZ;
/** Flushes shadow-pass batched model parts while GL_POLYGON_OFFSET_FILL is still enabled. */
private static void flushShadowModelParts() {
if (Tracy.ENABLED) Tracy.beginZone(Z_SHADOW_MODEL_PARTS);
final boolean alphaEnabled = GLStateManager.getAlphaTest().isEnabled();
final int alphaFunc = GLStateManager.getAlphaState().getFunction();
final float alphaRef = GLStateManager.getAlphaState().getReference();
try {
ModelPartBatcher.INSTANCE.flush();
} finally {
if (alphaEnabled) GLStateManager.enableAlphaTest();
else GLStateManager.disableAlphaTest();
GLStateManager.glAlphaFunc(alphaFunc, alphaRef);
if (Tracy.ENABLED) Tracy.endZone();
}
}
private void setupEntityShadowState(MatrixStack modelView, double cameraX, double cameraY, double cameraZ) {
savedRenderPosX = RenderManager.renderPosX;
savedRenderPosY = RenderManager.renderPosY;
@@ -517,7 +675,7 @@ public class ShadowRenderer {
}
private void renderPlayerEntity(EntityRenderer levelRenderer, Frustrum frustum, Object bufferSource, MatrixStack modelView, double cameraX, double cameraY, double cameraZ, float tickDelta) {
profiler.startSection("cull");
profiler.startSection("iris_shadow_cull");
EntityPlayer player = Minecraft.getMinecraft().thePlayer;
@@ -534,11 +692,12 @@ public class ShadowRenderer {
return;
}
profiler.endStartSection("build geometry");
profiler.endStartSection("iris_shadow_build_geometry");
int shadowEntities = 0;
setupEntityShadowState(modelView, cameraX, cameraY, cameraZ);
ModelPartBatcher.INSTANCE.begin(ModelPartBatcher.Mode.ENTITIES, true);
try {
if (player.riddenByEntity != null) {
RenderManager.instance.renderEntitySimple(player.riddenByEntity, tickDelta);
@@ -550,7 +709,9 @@ public class ShadowRenderer {
shadowEntities++;
}
PlayerReflectionCapture.begin(player);
if (playerReflectionCaptureEnabled) {
PlayerReflectionCapture.begin(player);
}
try {
RenderManager.instance.renderEntitySimple(player, tickDelta);
} finally {
@@ -558,6 +719,7 @@ public class ShadowRenderer {
}
shadowEntities++;
} finally {
flushShadowModelParts();
teardownEntityShadowState();
}
@@ -567,9 +729,22 @@ public class ShadowRenderer {
}
private void renderTileEntity(TileEntity tile, double cameraX, double cameraY, double cameraZ, float partialTicks) {
if (tile.getDistanceFrom(cameraX, cameraY, cameraZ) >= tile.getMaxRenderDistanceSquared()) {
final double distSq = tile.getDistanceFrom(cameraX, cameraY, cameraZ);
if (distSq >= tile.getMaxRenderDistanceSquared()) {
return;
}
if (AngelicaConfig.cullShadowTileEntities) {
final int maxD = AngelicaConfig.shadowTileEntityMaxDistance;
if (distSq >= (double) maxD * maxD) {
return;
}
if (AngelicaConfig.shadowSkipInMeshTileEntities) {
final Block block = tile.getBlockType();
if (block != null && block.getRenderType() != -1) {
return;
}
}
}
int brightness = tile.getWorldObj().getLightBrightnessForSkyBlocks(tile.xCoord, tile.yCoord, tile.zCoord, 0);
GLStateManager.setLightmapTextureCoords(GL13.GL_TEXTURE1, (float) brightness % 65536, (float) brightness / 65536);
GLStateManager.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
@@ -582,7 +757,7 @@ public class ShadowRenderer {
}
private void renderTileEntities(Object bufferSource, MatrixStack modelView, double cameraX, double cameraY, double cameraZ, float partialTicks, boolean hasEntityFrustum) {
profiler.startSection("build blockentities");
profiler.startSection("iris_shadow_build_blockentities");
int shadowTileEntities = 0;
BoxCuller culler = null;
@@ -597,26 +772,40 @@ public class ShadowRenderer {
modelView.peek().getModel().get(MODELVIEW_BUFFER);
GLStateManager.glLoadMatrix(MODELVIEW_BUFFER);
TesrBatchRenderer.INSTANCE.beginPass(TesrBatchRenderer.PASS_SHADOW, modelView.peek().getModel(), cameraX, cameraY, cameraZ);
GbufferPrograms.beginBlockEntities();
GbufferPrograms.setBlockEntityDefaults();
ModelPartBatcher.INSTANCE.begin(ModelPartBatcher.Mode.BLOCK_ENTITIES, true);
for (TileEntity tileEntity : visibleTileEntities) {
if (hasEntityFrustum && (culler.isCulled(tileEntity.xCoord - 1, tileEntity.yCoord - 1, tileEntity.zCoord - 1, tileEntity.xCoord + 1, tileEntity.yCoord + 1, tileEntity.zCoord + 1))) {
continue;
for (int b = 0, bn = visibleTileEntities.size(); b < bn; b++) {
final List<TileEntity> bucket = visibleTileEntities.get(b);
for (int i = 0, n = bucket.size(); i < n; i++) {
final TileEntity tileEntity = bucket.get(i);
if (hasEntityFrustum && (culler.isCulled(tileEntity.xCoord - 1, tileEntity.yCoord - 1, tileEntity.zCoord - 1, tileEntity.xCoord + 1, tileEntity.yCoord + 1, tileEntity.zCoord + 1))) {
continue;
}
renderTileEntity(tileEntity, cameraX, cameraY, cameraZ, partialTicks);
shadowTileEntities++;
}
renderTileEntity(tileEntity, cameraX, cameraY, cameraZ, partialTicks);
shadowTileEntities++;
}
for (TileEntity tileEntity : globalTileEntities) {
if (hasEntityFrustum && (culler.isCulled(tileEntity.xCoord - 1, tileEntity.yCoord - 1, tileEntity.zCoord - 1, tileEntity.xCoord + 1, tileEntity.yCoord + 1, tileEntity.zCoord + 1))) {
continue;
for (int b = 0, bn = globalTileEntities.size(); b < bn; b++) {
final List<TileEntity> bucket = globalTileEntities.get(b);
for (int i = 0, n = bucket.size(); i < n; i++) {
final TileEntity tileEntity = bucket.get(i);
if (hasEntityFrustum && (culler.isCulled(tileEntity.xCoord - 1, tileEntity.yCoord - 1, tileEntity.zCoord - 1, tileEntity.xCoord + 1, tileEntity.yCoord + 1, tileEntity.zCoord + 1))) {
continue;
}
renderTileEntity(tileEntity, cameraX, cameraY, cameraZ, partialTicks);
shadowTileEntities++;
}
renderTileEntity(tileEntity, cameraX, cameraY, cameraZ, partialTicks);
shadowTileEntities++;
}
flushShadowModelParts();
TesrBatchRenderer.INSTANCE.flush();
GbufferPrograms.endBlockEntities();
GLStateManager.glPopMatrix();
@@ -633,7 +822,7 @@ public class ShadowRenderer {
// If the profiler is inactive, it will return InactiveProfiler.INSTANCE
this.profiler = Minecraft.getMinecraft().mcProfiler;
profiler.endStartSection("shadows");
profiler.endStartSection("iris_shadows");
ACTIVE = true;
CURRENT_TARGETS = this.targets;
@@ -645,8 +834,32 @@ public class ShadowRenderer {
visibleTileEntities.clear();
globalTileEntities.clear();
final float currentShadowAngle = getShadowAngle();
if (ShadowGraphGate.shouldMarkDirty(lastGraphShadowAngle, currentShadowAngle)) {
CeleritasWorldRenderer.getInstance().getRenderSectionManager().markShadowGraphDirty();
lastGraphShadowAngle = currentShadowAngle;
}
final boolean deferActive = shouldRenderTerrain;
final long frameNanos = System.nanoTime();
final boolean consumePreSubmit = preSubmitActive;
preSubmitActive = false;
final boolean relayTerrain = !deferActive
|| voxelizationActive()
|| !targets.isTerrainSnapshotValid()
|| consumePreSubmit
|| CeleritasWorldRenderer.getInstance().getRenderSectionManager().isShadowGraphDirty()
|| frameNanos - lastRelayNanos >= SHADOW_RELAY_MAX_AGE_NANOS;
if (relayTerrain) {
relayShadowAngle = consumePreSubmit && !CeleritasWorldRenderer.getInstance().getRenderSectionManager().isShadowGraphDirty() ? preSubmittedShadowAngle : currentShadowAngle;
}
activeShadowAngle = relayShadowAngle;
SHADOW_TERRAIN_RELAID = relayTerrain;
// Create our camera
final MatrixStack modelView = getShadowModelView();
final MatrixStack modelView = getShadowModelView(relayShadowAngle);
MODELVIEW.set(modelView.peek().getModel());
final Matrix4f shadowProjection;
@@ -659,15 +872,15 @@ public class ShadowRenderer {
PROJECTION.set(shadowProjection);
profiler.startSection("terrain_setup");
profiler.startSection("iris_shadow_terrain_setup");
if (levelRenderer instanceof CullingDataCache) {
((CullingDataCache) levelRenderer).saveState();
}
profiler.startSection("initialize frustum");
profiler.startSection("iris_shadow_initialize_frustum");
terrainFrustumHolder = createShadowFrustum(renderDistanceMultiplier, terrainFrustumHolder);
terrainFrustumHolder = createShadowFrustum(renderDistanceMultiplier, terrainFrustumHolder, terrainFrustumCaches);
FRUSTUM = terrainFrustumHolder.getFrustum();
// Use the player/entity position for shadow rendering
@@ -681,19 +894,18 @@ public class ShadowRenderer {
profiler.endSection();
// Always schedule a terrain update
// TODO: Only schedule a terrain update if the sun / moon is moving, or the shadow map camera moved.
// We have to ensure that we don't regenerate clouds every frame, since that's what needsUpdate ends up doing.
// This took up to 10% of the frame time before we applied this fix! That's really bad!
// boolean regenerateClouds = levelRenderer.shouldRegenerateClouds();
// ((LevelRenderer) levelRenderer).needsUpdate();
// levelRenderer.setShouldRegenerateClouds(regenerateClouds);
// Mark the shadow graph as needing update before terrain setup
// Modern Celeritas does this to ensure the shadow render lists get populated
com.gtnewhorizons.angelica.rendering.celeritas.CeleritasWorldRenderer.getInstance()
.getRenderSectionManager().markShadowGraphDirty();
// Save the main camera viewport before shadow pass overwrites it.
// clipRenderersByFrustum -> setupTerrain sets currentViewport to the shadow frustum.
// If the shadow pass throws or the main setupTerrain doesn't run after us, the shadow
// viewport would persist and corrupt entity culling in the main pass.
final Viewport savedViewport = CeleritasWorldRenderer.getInstance().getCurrentViewport();
// Pair setupGlState / restoreGlState with try-finally so any throw between them
// (translucent terrain, entity rendering, mipmaps, etc.) still unwinds the
// projection push and the shadow framebuffer binding. Without this, a single
// mid-pass throw strands shadow GL state into the next frame's vanilla rendering.
boolean setupGlStateRan = false;
try {
// Execute the vanilla terrain setup / culling routines using our shadow frustum.
mc.renderGlobal.clipRenderersByFrustum(terrainFrustumHolder.getFrustum(), playerCamera.getPartialTicks());
@@ -702,57 +914,42 @@ public class ShadowRenderer {
// chunks during traversal, and break rendering in concerning ways.
// levelRenderer.setFrameId(levelRenderer.getFrameId() + 1);
profiler.endStartSection("terrain");
setupGlState(PROJECTION);
// Render all opaque terrain unless pack requests not to
if (shouldRenderTerrain) {
mc.renderEngine.bindTexture(TextureMap.locationBlocksTexture);
rg.sortAndRender(mc.renderViewEntity, 0, playerCamera.getPartialTicks());
}
// Reset viewport in case terrain rendering changed it
GLStateManager.glViewport(0, 0, resolution, resolution);
profiler.endStartSection("entities");
setupGlStateRan = true;
// Get the current tick delta. Normally this is the same as client.getTickDelta(), but when the game is paused,
// it is set to a fixed value.
final float tickDelta = CapturedRenderingState.INSTANCE.getTickDelta();
// Create a constrained shadow frustum for entities to avoid rendering faraway entities in the shadow pass,
// if the shader pack has requested it. Otherwise, use the same frustum as for terrain.
boolean hasEntityFrustum = false;
if (entityShadowDistanceMultiplier == 1.0F || entityShadowDistanceMultiplier < 0.0F) {
entityFrustumHolder.setInfo(terrainFrustumHolder.getFrustum(), terrainFrustumHolder.getDistanceInfo(), terrainFrustumHolder.getCullingInfo());
profiler.endStartSection("iris_shadow_terrain");
if (relayTerrain) {
try (GLDebug.Scope s = GLDebug.scope("shadow:terrain")) {
renderSolidShadowTerrain(mc, rg, playerCamera);
}
if (deferActive) {
targets.captureTerrainSnapshot();
lastRelayNanos = frameNanos;
}
} else {
hasEntityFrustum = true;
entityFrustumHolder = createShadowFrustum(renderDistanceMultiplier * entityShadowDistanceMultiplier, entityFrustumHolder);
try (GLDebug.Scope s = GLDebug.scope("shadow:terrain_restore")) {
targets.restoreTerrainSnapshot();
}
}
Frustrum entityShadowFrustum = entityFrustumHolder.getFrustum();
entityShadowFrustum.setPosition(entityX, entityY, entityZ);
// Set viewport for entity visibility checks during shadow pass (matches modern Celeritas)
if (AngelicaConfig.enableCeleritas) {
CeleritasWorldRenderer.getInstance().setCurrentViewport(((ViewportProvider)entityShadowFrustum).sodium$createViewport());
}
// Render nearby entities
if (shouldRenderEntities) {
renderEntities(levelRenderer, entityShadowFrustum, null, modelView, entityX, entityY, entityZ, tickDelta);
} else if (shouldRenderPlayer) {
renderPlayerEntity(levelRenderer, entityShadowFrustum, null, modelView, entityX, entityY, entityZ, tickDelta);
profiler.endStartSection("iris_shadow_entities");
final Frustrum entityShadowFrustum = createEntityShadowFrustum(entityX, entityY, entityZ);
applyEntityShadowViewport(entityShadowFrustum);
try (GLDebug.Scope s = GLDebug.scope("shadow:entities")) {
renderShadowEntitiesAndPlayer(levelRenderer, entityShadowFrustum, modelView, entityX, entityY, entityZ, tickDelta);
}
if (shouldRenderBlockEntities) {
renderTileEntities(null, modelView, entityX, entityY, entityZ, tickDelta, hasEntityFrustum);
try (GLDebug.Scope s = GLDebug.scope("shadow:block_entities")) {
renderTileEntities(null, modelView, entityX, entityY, entityZ, tickDelta, entityFrustumConstrained);
}
}
profiler.endStartSection("draw entities");
profiler.endStartSection("iris_shadow_draw_entities");
// NB: Don't try to draw the translucent parts of entities afterwards. It'll cause problems since some
// shader packs assume that everything drawn afterwards is actually translucent and should cast a colored
@@ -760,13 +957,15 @@ public class ShadowRenderer {
copyPreTranslucentDepth();
profiler.endStartSection("translucent terrain");
profiler.endStartSection("iris_shadow_translucent_terrain");
// TODO (Iris): Prevent these calls from scheduling translucent sorting...
// 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.renderViewEntity, 1, playerCamera.getPartialTicks());
try (GLDebug.Scope s = GLDebug.scope("shadow:translucent")) {
rg.sortAndRender(mc.renderViewEntity, 1, playerCamera.getPartialTicks());
}
}
// Note: Apparently tripwire isn't rendered in the shadow pass.
@@ -776,26 +975,32 @@ public class ShadowRenderer {
// renderBuffersExt.endLevelRendering();
// }
profiler.endStartSection("generate mipmaps");
profiler.endStartSection("iris_shadow_generate_mipmaps");
generateMipmaps();
profiler.endStartSection("restore gl state");
restoreGlState();
profiler.endStartSection("iris_shadow_restore_gl_state");
} finally {
if (setupGlStateRan) {
restoreGlState();
}
if (savedViewport != null) {
CeleritasWorldRenderer.getInstance().setCurrentViewport(savedViewport);
}
}
if (levelRenderer instanceof CullingDataCache) {
((CullingDataCache) levelRenderer).restoreState();
}
profiler.endStartSection("shadowcomp");
profiler.endStartSection("iris_shadowcomp");
if (compositeRenderer != null) compositeRenderer.renderAll();
ACTIVE = false;
CURRENT_TARGETS = null;
profiler.endSection();
profiler.endStartSection("updatechunks");
profiler.endStartSection("culling");
}
public void addDebugText(List<String> messages) {
@@ -8,7 +8,7 @@ import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability;
import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition;
import net.coderbot.iris.gbuffer_overrides.state.RenderTargetStateListener;
import net.coderbot.iris.celeritas.CeleritasTerrainPipeline;
import net.coderbot.iris.gl.texture.TextureType;
import com.gtnewhorizons.angelica.glsm.texture.TextureType;
import net.coderbot.iris.helpers.Tri;
import net.coderbot.iris.shaderpack.CloudSetting;
import net.coderbot.iris.shaderpack.texture.TextureStage;
@@ -21,6 +21,7 @@ import java.util.OptionalInt;
public interface WorldRenderingPipeline {
void beginLevelRendering();
void renderShadows(EntityRenderer levelRenderer, Camera camera);
default void preSubmitShadowGraph(int frame, boolean spectator) {}
void addDebugText(List<String> messages);
OptionalInt getForcedShadowRenderDistanceChunksForDisplay();
@@ -37,6 +38,11 @@ public interface WorldRenderingPipeline {
void onBindTexture(int id);
/** Re-bind the program/framebuffer for the currently-active Pass, if any. */
void rebindCurrentPass();
default void onEntityRenderBoundary() {}
void beginHand();
void beginTranslucents();
@@ -1,8 +1,9 @@
package net.coderbot.iris.pipeline.transform;
import net.coderbot.iris.gl.shader.ShaderType;
import com.gtnewhorizons.angelica.glsm.shader.ShaderType;
import net.coderbot.iris.pipeline.transform.parameter.AttributeParameters;
import org.taumc.glsl.Transformer;
import org.taumc.glsl.grammar.GLSLLexer;
import org.taumc.glsl.grammar.GLSLParser;
import java.util.HashMap;
@@ -29,18 +30,32 @@ class AttributeTransformer {
}
private static void transformCore(Transformer transformer, AttributeParameters parameters) {
CoreTransformHelper.injectMatrixUniforms(transformer);
final boolean instancedVertex = parameters.instanced && parameters.type == ShaderType.VERTEX;
final boolean wantsMvInverse = instancedVertex && transformer.containsCall("gl_ModelViewMatrixInverse");
CoreTransformHelper.injectMatrixUniforms(transformer, instancedVertex);
aliasIfUsed(transformer, "projectionMatrix", "iris_ProjectionMatrix");
aliasIfUsed(transformer, "modelViewMatrix", "iris_ModelViewMatrix");
aliasIfUsed(transformer, "normalMatrix", "iris_NormalMatrix");
if (parameters.type == ShaderType.VERTEX) {
transformer.injectVariable("layout(location = 0) in vec4 iris_Vertex;");
transformer.injectVariable("layout(location = 1) in vec4 iris_Color;");
transformer.injectVariable("layout(location = 2) in vec4 iris_MultiTexCoord0;");
transformer.injectVariable("layout(location = 3) in vec4 iris_MultiTexCoord1;");
if (instancedVertex) {
transformer.injectVariable("vec4 iris_MultiTexCoord1;");
} else {
transformer.injectVariable("layout(location = 3) in vec4 iris_MultiTexCoord1;");
}
transformer.injectVariable("layout(location = 4) in vec3 iris_Normal;");
transformer.rename("gl_Vertex", "iris_Vertex");
transformer.replaceExpression("gl_Color", "(iris_Color * iris_ColorModulator)");
transformer.replaceExpression("gl_Color", instancedVertex ? "(iris_Color * iris_ColorModulator * iris_InstColor)" : "(iris_Color * iris_ColorModulator)");
transformer.rename("gl_Normal", "iris_Normal");
aliasIfUsed(transformer, "vaNormal", "iris_Normal");
if (transformer.containsCall("vaPosition") && !transformer.hasVariable("vaPosition")) {
transformer.replaceExpression("vaPosition", "iris_Vertex.xyz");
}
// ftransform() = gl_ModelViewProjectionMatrix * gl_Vertex
transformer.renameFunctionCall("ftransform", "iris_ftransform");
@@ -69,7 +84,42 @@ class AttributeTransformer {
transformer.rename("gl_MultiTexCoord3", "mc_midTexCoord");
transformer.injectVariable("in vec4 mc_midTexCoord;");
}
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);");
init.append(" iris_NormalMatrix = mat3(normalize(iris_InstMat0.xyz), normalize(iris_InstMat1.xyz), normalize(iris_InstMat2.xyz));");
if (wantsMvInverse) {
init.append(" iris_ModelViewMatrixInverse = inverse(iris_ModelViewMatrix);");
}
init.append(" iris_MultiTexCoord1 = vec4(iris_InstLightmap, 0.0, 1.0); }");
transformer.prependMain(init.toString());
}
}
}
private static void foldConstantAttribute(Transformer transformer, String name, String floatVal, String vec2Val, String vec3Val, String vec4Val) {
final int type = transformer.findType(name);
if (type == 0) {
return;
}
final String replacement = switch (type) {
case GLSLLexer.FLOAT -> floatVal;
case GLSLLexer.VEC2 -> vec2Val;
case GLSLLexer.VEC3 -> vec3Val;
case GLSLLexer.VEC4 -> vec4Val;
default -> throw new IllegalStateException("Unsupported " + name + " type token " + type + " for instanced variant");
};
transformer.removeVariable(name);
transformer.replaceExpression(name, replacement);
}
private static void aliasIfUsed(Transformer transformer, String modernName, String irisName) {
if (transformer.containsCall(modernName) && !transformer.hasVariable(modernName)) {
transformer.rename(modernName, irisName);
}
}
}
@@ -67,5 +67,7 @@ class CeleritasTransformer {
private static void transformShared(Transformer transformer, Parameters parameters) {
transformer.replaceExpression("gl_TextureMatrix[0]", "mat4(1.0)");
CoreTransformHelper.injectMatrixUniforms(transformer);
// Celeritas terrain: texture matrix is always identity, replace uniform with constant
transformer.replaceExpression("iris_TextureMatrix", "mat4(1.0)");
}
}
@@ -1,7 +1,7 @@
package net.coderbot.iris.pipeline.transform;
import com.gtnewhorizons.angelica.glsm.GlslTransformUtils;
import net.coderbot.iris.gl.shader.ShaderType;
import com.gtnewhorizons.angelica.glsm.shader.ShaderType;
import net.coderbot.iris.pipeline.transform.parameter.Parameters;
import org.taumc.glsl.Transformer;
import org.taumc.glsl.grammar.GLSLParser;
@@ -135,7 +135,12 @@ public class CommonTransformer {
+ "gl_ClipDistance[4] = dot(angelica_ClipPlane[4], _cp_ep); "
+ "gl_ClipDistance[5] = dot(angelica_ClipPlane[5], _cp_ep); "
+ "gl_ClipDistance[6] = dot(angelica_ClipPlane[6], _cp_ep); "
+ "gl_ClipDistance[7] = dot(angelica_ClipPlane[7], _cp_ep); } }"
+ "gl_ClipDistance[7] = dot(angelica_ClipPlane[7], _cp_ep); "
+ "} else { "
+ "gl_ClipDistance[0] = 0.0; gl_ClipDistance[1] = 0.0; "
+ "gl_ClipDistance[2] = 0.0; gl_ClipDistance[3] = 0.0; "
+ "gl_ClipDistance[4] = 0.0; gl_ClipDistance[5] = 0.0; "
+ "gl_ClipDistance[6] = 0.0; gl_ClipDistance[7] = 0.0; } }"
);
}
}
@@ -1,6 +1,6 @@
package net.coderbot.iris.pipeline.transform;
import net.coderbot.iris.gl.shader.ShaderType;
import com.gtnewhorizons.angelica.glsm.shader.ShaderType;
import net.coderbot.iris.pipeline.transform.parameter.Parameters;
import org.antlr.v4.runtime.tree.ParseTree;
import org.taumc.glsl.ShaderPrinter;
@@ -1,6 +1,6 @@
package net.coderbot.iris.pipeline.transform;
import net.coderbot.iris.gl.shader.ShaderType;
import com.gtnewhorizons.angelica.glsm.shader.ShaderType;
import net.coderbot.iris.pipeline.transform.parameter.Parameters;
import org.taumc.glsl.Transformer;
@@ -15,11 +15,27 @@ class CoreTransformHelper {
* Handles: ModelView, ModelViewInverse, Projection, ProjectionInverse, NormalMatrix, ModelViewProjectionMatrix, TextureMatrix[0..1], and LightmapTextureMatrix.
*/
static void injectMatrixUniforms(Transformer transformer) {
transformer.injectVariable("uniform mat4 iris_ModelViewMatrix;");
transformer.injectVariable("uniform mat4 iris_ModelViewMatrixInverse;");
injectMatrixUniforms(transformer, false);
}
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("mat4 iris_ModelViewMatrix;");
transformer.injectVariable("mat4 iris_ModelViewMatrixInverse;");
transformer.injectVariable("mat3 iris_NormalMatrix;");
} else {
transformer.injectVariable("uniform mat4 iris_ModelViewMatrix;");
transformer.injectVariable("uniform mat4 iris_ModelViewMatrixInverse;");
transformer.injectVariable("uniform mat3 iris_NormalMatrix;");
}
transformer.injectVariable("uniform mat4 iris_ProjectionMatrix;");
transformer.injectVariable("uniform mat4 iris_ProjectionMatrixInverse;");
transformer.injectVariable("uniform mat3 iris_NormalMatrix;");
transformer.injectVariable("uniform mat4 iris_LightmapTextureMatrix;");
transformer.injectVariable("uniform mat4 iris_TextureMatrix;");
@@ -1,6 +1,6 @@
package net.coderbot.iris.pipeline.transform;
import net.coderbot.iris.gl.shader.ShaderType;
import com.gtnewhorizons.angelica.glsm.shader.ShaderType;
import net.coderbot.iris.pipeline.transform.parameter.Parameters;
import org.taumc.glsl.Transformer;
@@ -70,12 +70,12 @@ public class DHGenericTransformer {
addIfNotExists(transformer, "uCameraPosSubChunk", "uniform vec3 uCameraPosSubChunk;");
addIfNotExists(transformer, "uSkyLight", "uniform int uSkyLight;");
addIfNotExists(transformer, "uBlockLight", "uniform int uBlockLight;");
addIfNotExists(transformer, "iris_color", "in vec4 iris_color;");
addIfNotExists(transformer, "aScale", "in vec3 aScale;");
addIfNotExists(transformer, "aTranslateChunk", "in ivec3 aTranslateChunk;");
addIfNotExists(transformer, "aTranslateSubChunk", "in vec3 aTranslateSubChunk;");
addIfNotExists(transformer, "aMaterial", "in int aMaterial;");
addIfNotExists(transformer, "vPosition", "in vec3 vPosition;");
addIfNotExists(transformer, "iris_color", DH_GENERIC_LOC_COLOR, "in vec4 iris_color;");
addIfNotExists(transformer, "aScale", DH_GENERIC_LOC_SCALE, "in vec3 aScale;");
addIfNotExists(transformer, "aTranslateChunk", DH_GENERIC_LOC_TRANSLATE_CHUNK, "in ivec3 aTranslateChunk;");
addIfNotExists(transformer, "aTranslateSubChunk", DH_GENERIC_LOC_TRANSLATE_SUB_CHUNK, "in vec3 aTranslateSubChunk;");
addIfNotExists(transformer, "aMaterial", DH_GENERIC_LOC_MATERIAL, "in int aMaterial;");
addIfNotExists(transformer, "vPosition", DH_GENERIC_LOC_POSITION, "in vec3 vPosition;");
transformer.injectFunction("const vec3 irisNormals[6] = vec3[](vec3(0,0,-1), vec3(0,0,1), vec3(-1,0,0), vec3(1,0,0), vec3(0,-1,0), vec3(0,1,0));");
transformer.injectFunction(
@@ -100,12 +100,23 @@ public class DHGenericTransformer {
transformer.prependMain("_vert_init();");
}
public static final int DH_GENERIC_LOC_POSITION = 0;
public static final int DH_GENERIC_LOC_COLOR = 1;
public static final int DH_GENERIC_LOC_SCALE = 2;
public static final int DH_GENERIC_LOC_TRANSLATE_CHUNK = 3;
public static final int DH_GENERIC_LOC_TRANSLATE_SUB_CHUNK = 4;
public static final int DH_GENERIC_LOC_MATERIAL = 5;
private static void addIfNotExists(Transformer transformer, String name, String code) {
if (!transformer.hasVariable(name)) {
transformer.injectVariable(code);
}
}
private static void addIfNotExists(Transformer transformer, String name, int location, String code) {
addIfNotExists(transformer, name, "layout (location = " + location + ") " + code);
}
private static void replaceGlMultiTexCoordBounded(Transformer transformer, int from, int to) {
for (int i = from; i <= to; i++) {
transformer.replaceExpression("gl_MultiTexCoord" + i, "vec4(0.0, 0.0, 0.0, 1.0)");
@@ -1,6 +1,6 @@
package net.coderbot.iris.pipeline.transform;
import net.coderbot.iris.gl.shader.ShaderType;
import com.gtnewhorizons.angelica.glsm.shader.ShaderType;
import net.coderbot.iris.pipeline.transform.parameter.Parameters;
import org.taumc.glsl.Transformer;
@@ -0,0 +1,116 @@
package net.coderbot.iris.pipeline.transform;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ParseTree;
import org.taumc.glsl.ShaderParser;
import org.taumc.glsl.grammar.GLSLParser;
import java.util.ArrayList;
import java.util.List;
final class GlslAstHelpers {
private GlslAstHelpers() {}
@SuppressWarnings("unchecked")
static <T extends ParseTree> List<T> collectAll(ParseTree root, Class<T> klass) {
final List<T> out = new ArrayList<>();
walk(root, klass, out);
return out;
}
@SuppressWarnings("unchecked")
static <T extends ParseTree> void walk(ParseTree node, Class<T> klass, List<T> out) {
if (klass.isInstance(node)) out.add((T) node);
for (int i = 0, n = node.getChildCount(); i < n; i++) {
walk(node.getChild(i), klass, out);
}
}
@SuppressWarnings("unchecked")
static <T extends ParserRuleContext> T enclosingOfType(ParseTree node, Class<T> type) {
ParseTree cur = node;
while (cur != null && !type.isInstance(cur)) cur = cur.getParent();
return (T) cur;
}
static void collectInto(ParseTree root, List<? extends ParseTree>[] sinks, Class<?>[] types) {
if (types.length != sinks.length) throw new IllegalArgumentException();
collectIntoWalk(root, sinks, types);
}
@SuppressWarnings("unchecked")
private static void collectIntoWalk(ParseTree node, List<? extends ParseTree>[] sinks, Class<?>[] types) {
for (int i = 0; i < types.length; i++) {
if (types[i].isInstance(node)) ((List<ParseTree>) sinks[i]).add(node);
}
for (int i = 0, n = node.getChildCount(); i < n; i++) collectIntoWalk(node.getChild(i), sinks, types);
}
static String extractCallName(GLSLParser.Postfix_expressionContext expr) {
if (expr.function_call_parameters() == null) return null;
if (expr.postfix_expression() == null) {
return expr.type_specifier() != null ? expr.type_specifier().getText() : null;
}
final GLSLParser.Postfix_expressionContext inner = expr.postfix_expression();
if (inner.primary_expression() == null) return null;
if (inner.primary_expression().variable_identifier() == null) return null;
return inner.primary_expression().variable_identifier().getText();
}
static String firstArgIdentifier(GLSLParser.Postfix_expressionContext expr) {
final List<GLSLParser.Assignment_expressionContext> args = argsOf(expr);
if (args.isEmpty()) return "";
return args.get(0).getText();
}
static String secondArgText(GLSLParser.Postfix_expressionContext expr) {
final List<GLSLParser.Assignment_expressionContext> args = argsOf(expr);
if (args.size() < 2) return null;
return args.get(1).getText();
}
static List<GLSLParser.Assignment_expressionContext> argsOf(GLSLParser.Postfix_expressionContext expr) {
final GLSLParser.Function_call_parametersContext params = expr.function_call_parameters();
if (params == null) return List.of();
return params.assignment_expression();
}
static void replaceNode(ParseTree oldNode, ParseTree newNode) {
if (!(oldNode instanceof ParserRuleContext oldCtx)) return;
if (!(newNode instanceof ParserRuleContext newCtx)) return;
if (!(oldCtx.parent instanceof ParserRuleContext parentCtx)) return;
final int idx = parentCtx.children.indexOf(oldCtx);
if (idx < 0) return;
newCtx.parent = parentCtx;
parentCtx.children.set(idx, newCtx);
}
static boolean deleteStatementContaining(ParseTree expr) {
final GLSLParser.StatementContext stmt = enclosingOfType(expr, GLSLParser.StatementContext.class);
if (stmt == null) return false;
if (!(stmt.parent instanceof ParserRuleContext parent) || parent.children == null) return false;
final var empty = ShaderParser.parseSnippet(";", GLSLParser::statement);
if (empty == null) return parent.children.remove(stmt);
final int idx = parent.children.indexOf(stmt);
if (idx < 0) return false;
empty.parent = parent;
parent.children.set(idx, empty);
return true;
}
static String zeroLiteralFor(String imageGlslType) {
return switch (componentTypeFor(imageGlslType)) {
case "ivec4" -> "ivec4(0)";
case "uvec4" -> "uvec4(0u)";
default -> "vec4(0.0)";
};
}
static String componentTypeFor(String imageGlslType) {
if (imageGlslType == null) return "vec4";
if (imageGlslType.startsWith("iimage")) return "ivec4";
if (imageGlslType.startsWith("uimage")) return "uvec4";
return "vec4";
}
}
@@ -0,0 +1,95 @@
package net.coderbot.iris.pipeline.transform;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.taumc.glsl.ShaderParser;
import org.taumc.glsl.Transformer;
import org.taumc.glsl.grammar.GLSLLexer;
import org.taumc.glsl.grammar.GLSLParser;
import java.util.Map;
final class LocalZeroInitTransformer {
private LocalZeroInitTransformer() {}
static void transformGrouped(Map<PatchShaderType, Transformer> trees) {
for (Transformer t : trees.values()) {
if (t != null) transform(t);
}
}
static void transform(Transformer transformer) {
transformer.mutateTree(tree -> {
for (GLSLParser.Declaration_statementContext stmt :
GlslAstHelpers.collectAll(tree, GLSLParser.Declaration_statementContext.class)) {
initializeStatement(stmt);
}
});
}
private static void initializeStatement(GLSLParser.Declaration_statementContext stmt) {
final GLSLParser.DeclarationContext declaration = stmt.declaration();
if (declaration == null) return;
final GLSLParser.Init_declarator_listContext list = declaration.init_declarator_list();
if (list == null) return;
final GLSLParser.Single_declarationContext single = list.single_declaration();
if (single == null) return;
final GLSLParser.Fully_specified_typeContext type = single.fully_specified_type();
if (type == null || type.type_qualifier() != null) return;
final GLSLParser.Type_specifierContext specifier = type.type_specifier();
if (specifier == null || specifier.array_specifier() != null) return;
final String zero = zeroInitializerFor(specifier.type_specifier_nonarray());
if (zero == null) return;
initializeDeclarator(single.typeless_declaration(), zero);
for (GLSLParser.Typeless_declarationContext declarator : list.typeless_declaration()) {
initializeDeclarator(declarator, zero);
}
}
private static void initializeDeclarator(GLSLParser.Typeless_declarationContext declarator, String zero) {
if (declarator == null) return;
if (declarator.initializer() != null || declarator.array_specifier() != null) return;
final TerminalNode name = declarator.IDENTIFIER();
if (name == null) return;
final GLSLParser.Typeless_declarationContext replacement =
ShaderParser.parseSnippet(name.getText() + " = " + zero, GLSLParser::typeless_declaration);
if (replacement != null) GlslAstHelpers.replaceNode(declarator, replacement);
}
private static String zeroInitializerFor(GLSLParser.Type_specifier_nonarrayContext specifier) {
if (specifier == null || specifier.getChildCount() != 1) return null;
if (!(specifier.getChild(0) instanceof TerminalNode token)) return null;
final String type = switch (token.getSymbol().getType()) {
case GLSLLexer.FLOAT -> "float";
case GLSLLexer.INT -> "int";
case GLSLLexer.UINT -> "uint";
case GLSLLexer.VEC2 -> "vec2";
case GLSLLexer.VEC3 -> "vec3";
case GLSLLexer.VEC4 -> "vec4";
case GLSLLexer.IVEC2 -> "ivec2";
case GLSLLexer.IVEC3 -> "ivec3";
case GLSLLexer.IVEC4 -> "ivec4";
case GLSLLexer.UVEC2 -> "uvec2";
case GLSLLexer.UVEC3 -> "uvec3";
case GLSLLexer.UVEC4 -> "uvec4";
case GLSLLexer.MAT2 -> "mat2";
case GLSLLexer.MAT3 -> "mat3";
case GLSLLexer.MAT4 -> "mat4";
case GLSLLexer.MAT2X2 -> "mat2x2";
case GLSLLexer.MAT2X3 -> "mat2x3";
case GLSLLexer.MAT2X4 -> "mat2x4";
case GLSLLexer.MAT3X2 -> "mat3x2";
case GLSLLexer.MAT3X3 -> "mat3x3";
case GLSLLexer.MAT3X4 -> "mat3x4";
case GLSLLexer.MAT4X2 -> "mat4x2";
case GLSLLexer.MAT4X3 -> "mat4x3";
case GLSLLexer.MAT4X4 -> "mat4x4";
default -> null;
};
return type == null ? null : type + "(0)";
}
}
@@ -1,6 +1,6 @@
package net.coderbot.iris.pipeline.transform;
import net.coderbot.iris.gl.shader.ShaderType;
import com.gtnewhorizons.angelica.glsm.shader.ShaderType;
public enum PatchShaderType {
VERTEX(ShaderType.VERTEX),
@@ -0,0 +1,39 @@
package net.coderbot.iris.pipeline.transform;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import net.coderbot.iris.gl.program.ComputeProgram;
import net.coderbot.iris.uniforms.custom.CustomUniforms;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL42;
public final class PreRasterComputeDispatcher {
public static final int LOC_UNRESOLVED = -2;
private PreRasterComputeDispatcher() {}
public static int dispatch(ComputeProgram compute, RwImageStoreExtractor.RwExtractMode mode, int cachedTargetSizeLoc, int width, int height, CustomUniforms uniforms) {
final int prevProgram = GLStateManager.glGetInteger(GL20.GL_CURRENT_PROGRAM);
compute.use();
uniforms.push(compute);
int targetSizeLoc = cachedTargetSizeLoc;
if (mode == RwImageStoreExtractor.RwExtractMode.COMPOSITE_FSH) {
if (targetSizeLoc == LOC_UNRESOLVED) {
targetSizeLoc = GLStateManager.glGetUniformLocation(compute.getProgramId(), "_vg_target_size");
}
if (targetSizeLoc >= 0) {
GLStateManager.glUniform2i(targetSizeLoc, width, height);
}
}
final int gx, gy, gz;
switch (mode) {
case COMPOSITE_VSH -> { gx = 1; gy = 1; gz = 1; }
case COMPOSITE_FSH -> { gx = (width + 7) / 8; gy = (height + 7) / 8; gz = 1; }
default -> { gx = 1; gy = 1; gz = 1; }
}
GLStateManager.glDispatchCompute(gx, gy, gz);
RenderSystem.memoryBarrier(GL42.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
if (prevProgram != 0) GLStateManager.glUseProgram(prevProgram);
return targetSizeLoc;
}
}
@@ -0,0 +1,804 @@
package net.coderbot.iris.pipeline.transform;
import com.gtnewhorizons.angelica.glsm.GlslTransformUtils;
import net.coderbot.iris.gl.image.ImageInformation;
import com.gtnewhorizons.angelica.glsm.texture.InternalTextureFormat;
import org.antlr.v4.runtime.CommonToken;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.taumc.glsl.ShaderParser;
import org.taumc.glsl.Transformer;
import org.taumc.glsl.grammar.GLSLLexer;
import org.taumc.glsl.grammar.GLSLParser;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.HashSet;
import java.util.Set;
public final class RwImageStoreExtractor {
public enum RwExtractMode { CHUNK, COMPOSITE_VSH, COMPOSITE_FSH }
public static RwExtractMode parseSentinel(String computeSource) {
if (computeSource == null) return null;
if (computeSource.startsWith("// _vg_mode: chunk")) return RwExtractMode.CHUNK;
if (computeSource.startsWith("// _vg_mode: composite-vsh")) return RwExtractMode.COMPOSITE_VSH;
if (computeSource.startsWith("// _vg_mode: composite-fsh")) return RwExtractMode.COMPOSITE_FSH;
return null;
}
public record AttributeSlot(String name, String glslType, int byteOffset, String unpackExpr, boolean liveBranch) {
public AttributeSlot(String name, String glslType, int byteOffset, String unpackExpr) {
this(name, glslType, byteOffset, unpackExpr, true);
}
}
public record Result(String strippedSource, String computeSource, Set<String> writtenImages, RwExtractMode mode) {}
public record ImageDecl(String name, String glslType, String layoutFormat) {}
public static class UnknownAttributeException extends RuntimeException {
public UnknownAttributeException(String msg) { super(msg); }
}
private RwImageStoreExtractor() {}
public static final int VG_VBUF_SSBO_BINDING = 9;
private static final int STRIDE_BYTES = 48;
private static final int STRIDE_UINTS = STRIDE_BYTES / 4;
private static volatile Map<String, ImageInformation> activeCustomImages = Map.of();
public static void setActiveCustomImages(Map<String, ImageInformation> images) {
activeCustomImages = (images == null) ? Map.of() : Map.copyOf(images);
}
private static final Set<String> RW_CALLS = Set.of(
"imageStore",
"imageAtomicAdd", "imageAtomicAnd", "imageAtomicOr", "imageAtomicXor",
"imageAtomicMin", "imageAtomicMax", "imageAtomicExchange", "imageAtomicCompSwap"
);
public static Result tryExtract(String source, PatchShaderType stage, String programName) {
if (source == null) return null;
if (stage != PatchShaderType.VERTEX && stage != PatchShaderType.FRAGMENT) return null;
final ShaderParser.ParsedShader parsed = ShaderParser.parseShader(source);
final GLSLParser.Translation_unitContext root = parsed.full();
final List<GLSLParser.Single_declarationContext> decls = new ArrayList<>();
final List<GLSLParser.Postfix_expressionContext> exprs = new ArrayList<>();
GlslAstHelpers.collectInto(root,
new List[] { decls, exprs },
new Class<?>[] { GLSLParser.Single_declarationContext.class, GLSLParser.Postfix_expressionContext.class });
final Map<String, ImageDecl> declared = collectImageDecls(decls);
final Set<String> writtenImages = new LinkedHashSet<>();
final Set<String> nonWriteonlyImages = new LinkedHashSet<>();
classifyImageCalls(exprs, declared, writtenImages, nonWriteonlyImages);
if (writtenImages.isEmpty()) return null;
final Map<String, String> chunkAttrAstTypes = (stage == PatchShaderType.VERTEX) ? collectChunkAttrAstTypes(decls) : Map.of();
final Set<String> chunkAttrsUsed = (stage == PatchShaderType.VERTEX) ? collectChunkAttrsUsed(decls, root, source) : Set.of();
final RwExtractMode mode = (stage == PatchShaderType.VERTEX) ? (chunkAttrsUsed.isEmpty() ? RwExtractMode.COMPOSITE_VSH : RwExtractMode.CHUNK) : RwExtractMode.COMPOSITE_FSH;
final List<AttributeSlot> attrs = (mode == RwExtractMode.CHUNK) ? collectVertexAttributes(chunkAttrsUsed, chunkAttrAstTypes) : List.of();
final String stripped = buildRasterOutputViaSourceSlicing(source, decls, exprs, writtenImages, declared, mode);
final Transformer tc = new Transformer(root);
applyComputeMutations(tc, writtenImages, declared, chunkAttrsUsed, mode, nonWriteonlyImages);
final String compute = buildComputeOutput(root, mode, writtenImages, nonWriteonlyImages, declared, attrs);
return new Result(stripped, compute, writtenImages, mode);
}
private static Map<String, ImageDecl> collectImageDecls(List<GLSLParser.Single_declarationContext> decls) {
final LinkedHashMap<String, ImageDecl> out = new LinkedHashMap<>();
for (var decl : decls) {
final var ts = decl.fully_specified_type();
if (ts == null || ts.type_specifier() == null || ts.type_specifier().type_specifier_nonarray() == null) continue;
final var nonArray = ts.type_specifier().type_specifier_nonarray();
if (nonArray.getChildCount() == 0) continue;
final var first = nonArray.getChild(0);
if (!(first instanceof TerminalNode tn)) continue;
final int tokenType = tn.getSymbol().getType();
if (!isImageToken(tokenType)) continue;
final var typeless = decl.typeless_declaration();
if (typeless == null || typeless.IDENTIFIER() == null) continue;
final String name = typeless.IDENTIFIER().getText();
final String glslType = tn.getText();
final String layoutFormat = extractLayoutFormat(ts);
out.putIfAbsent(name, new ImageDecl(name, glslType, layoutFormat));
}
return out;
}
private static String extractLayoutFormat(GLSLParser.Fully_specified_typeContext fst) {
if (fst.type_qualifier() == null) return null;
for (var sq : fst.type_qualifier().single_type_qualifier()) {
final var lq = sq.layout_qualifier();
if (lq == null || lq.layout_qualifier_id_list() == null) continue;
for (var id : lq.layout_qualifier_id_list().layout_qualifier_id()) {
if (id.IDENTIFIER() == null) continue;
final String text = id.IDENTIFIER().getText();
if (isImageFormat(text)) return text;
}
}
return null;
}
private static boolean isImageFormat(String s) {
return s.startsWith("rgba") || s.startsWith("rgb") || s.startsWith("rg")
|| s.startsWith("r32") || s.startsWith("r16") || s.startsWith("r8")
|| s.startsWith("r11f") || s.startsWith("r10");
}
private static boolean isImageToken(int t) {
return t == GLSLLexer.IMAGE1D || t == GLSLLexer.IMAGE2D || t == GLSLLexer.IMAGE3D
|| t == GLSLLexer.IIMAGE1D || t == GLSLLexer.IIMAGE2D || t == GLSLLexer.IIMAGE3D
|| t == GLSLLexer.UIMAGE1D || t == GLSLLexer.UIMAGE2D || t == GLSLLexer.UIMAGE3D;
}
private static void classifyImageCalls(List<GLSLParser.Postfix_expressionContext> exprs, Map<String, ImageDecl> declared, Set<String> writtenImages, Set<String> nonWriteonlyImages) {
for (var expr : exprs) {
final String fname = GlslAstHelpers.extractCallName(expr);
if (fname == null) continue;
final String firstArg = GlslAstHelpers.firstArgIdentifier(expr);
if (firstArg.isEmpty() || !declared.containsKey(firstArg)) continue;
if (RW_CALLS.contains(fname)) {
writtenImages.add(firstArg);
if (!"imageStore".equals(fname)) {
nonWriteonlyImages.add(firstArg);
}
} else if ("imageLoad".equals(fname)) {
nonWriteonlyImages.add(firstArg);
}
}
}
private static Set<String> collectChunkAttrsUsed(List<GLSLParser.Single_declarationContext> decls, GLSLParser.Translation_unitContext root, String source) {
final LinkedHashSet<String> out = new LinkedHashSet<>();
for (var decl : decls) {
if (decl.typeless_declaration() == null || decl.typeless_declaration().IDENTIFIER() == null) continue;
final String name = decl.typeless_declaration().IDENTIFIER().getText();
if (CHUNK_VERTEX_ATTRS.containsKey(name)) out.add(name);
}
for (var ref : GlslAstHelpers.collectAll(root, GLSLParser.Variable_identifierContext.class)) {
if (ref.IDENTIFIER() == null) continue;
final String name = ref.IDENTIFIER().getText();
if (CHUNK_VERTEX_ATTRS.containsKey(name)) out.add(name);
}
for (String attr : CHUNK_VERTEX_ATTRS.keySet()) {
if (containsAsToken(source, attr)) out.add(attr);
}
return out;
}
private static boolean containsAsToken(String text, String name) {
int from = 0;
while (true) {
final int idx = text.indexOf(name, from);
if (idx < 0) return false;
final boolean beforeOk = idx == 0 || !isIdentChar(text.charAt(idx - 1));
final int end = idx + name.length();
final boolean afterOk = end >= text.length() || !isIdentChar(text.charAt(end));
if (beforeOk && afterOk) return true;
from = idx + 1;
}
}
private static boolean isIdentChar(char c) {
return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_';
}
private record SourceEdit(int start, int stop, String replacement) {}
private static String buildRasterOutputViaSourceSlicing(String source, List<GLSLParser.Single_declarationContext> decls, List<GLSLParser.Postfix_expressionContext> exprs, Set<String> writtenImages, Map<String, ImageDecl> declared, RwExtractMode mode) {
final List<SourceEdit> edits = new ArrayList<>();
for (var decl : decls) {
if (decl.typeless_declaration() == null || decl.typeless_declaration().IDENTIFIER() == null) continue;
final String name = decl.typeless_declaration().IDENTIFIER().getText();
if (!writtenImages.contains(name)) continue;
final var ext = GlslAstHelpers.enclosingOfType(decl, GLSLParser.External_declarationContext.class);
if (ext == null) continue;
edits.add(rangeOf(ext));
}
for (var expr : exprs) {
final String fname = GlslAstHelpers.extractCallName(expr);
if (fname == null) continue;
final String firstArg = GlslAstHelpers.firstArgIdentifier(expr);
if (!writtenImages.contains(firstArg)) continue;
if (RW_CALLS.contains(fname)) {
final var stmt = GlslAstHelpers.enclosingOfType(expr, GLSLParser.StatementContext.class);
if (stmt != null) edits.add(replaceOf(stmt, ";"));
} else if ("imageLoad".equals(fname)) {
final ImageDecl d = declared.get(firstArg);
if (d == null) continue;
edits.add(replaceOf(expr, GlslAstHelpers.zeroLiteralFor(d.glslType())));
}
}
return applyEdits(source, edits);
}
private static SourceEdit rangeOf(ParserRuleContext ctx) {
return new SourceEdit(ctx.getStart().getStartIndex(), ctx.getStop().getStopIndex() + 1, "");
}
private static SourceEdit replaceOf(ParserRuleContext ctx, String text) {
return new SourceEdit(ctx.getStart().getStartIndex(), ctx.getStop().getStopIndex() + 1, text);
}
private static String applyEdits(String source, List<SourceEdit> edits) {
if (edits.isEmpty()) return source;
edits.sort(Comparator.comparingInt(SourceEdit::start));
final StringBuilder out = new StringBuilder(source.length());
int cursor = 0;
for (SourceEdit e : edits) {
if (e.start() < cursor) continue;
out.append(source, cursor, e.start());
out.append(e.replacement());
cursor = e.stop();
}
if (cursor < source.length()) out.append(source, cursor, source.length());
return out.toString();
}
private static void applyComputeMutations(Transformer tc, Set<String> writtenImages, Map<String, ImageDecl> declared, Set<String> chunkAttrsUsed, RwExtractMode mode, Set<String> nonWriteonlyImages) {
hoistNonConstGlobalInitializers(tc);
renameMainToVgBody(tc);
rewriteImageAtomicsToNonAtomic(tc, declared, writtenImages, nonWriteonlyImages);
for (String name : writtenImages) tc.removeVariable(name);
if (mode == RwExtractMode.CHUNK) {
for (String name : chunkAttrsUsed) tc.removeVariable(name);
stripStorageQualifiers(tc, Set.of("out", "varying"));
} else if (mode == RwExtractMode.COMPOSITE_VSH) {
tc.renameFunctionCall("ftransform", "iris_ftransform");
stripStorageQualifiers(tc, Set.of("in", "attribute", "out", "varying"));
} else if (mode == RwExtractMode.COMPOSITE_FSH) {
stripFragOutputs(tc);
stripStorageQualifiers(tc, Set.of("in", "varying"));
}
stripInterfaceOnlyQualifiers(tc);
}
private static final Set<String> ATOMIC_CALLS = Set.of(
"imageAtomicAdd", "imageAtomicAnd", "imageAtomicOr", "imageAtomicXor",
"imageAtomicMin", "imageAtomicMax", "imageAtomicExchange", "imageAtomicCompSwap"
);
private static void rewriteImageAtomicsToNonAtomic(Transformer tc, Map<String, ImageDecl> declared, Set<String> writtenImages, Set<String> nonWriteonlyImages) {
tc.mutateTree(tree -> {
for (var expr : GlslAstHelpers.collectAll(tree, GLSLParser.Postfix_expressionContext.class)) {
final String fname = GlslAstHelpers.extractCallName(expr);
if (fname == null || !ATOMIC_CALLS.contains(fname)) continue;
final String imgName = GlslAstHelpers.firstArgIdentifier(expr);
if (!writtenImages.contains(imgName)) continue;
final ImageDecl decl = declared.get(imgName);
if (decl == null) continue;
if (!isCallTopLevelStatement(expr)) continue;
final String inlined = buildInlineAtomicEmulation(fname, imgName, GlslAstHelpers.argsOf(expr), decl);
if (inlined == null) continue;
final var replacement = ShaderParser.parseSnippet(inlined, GLSLParser::statement);
if (replacement == null) continue;
if (replaceEnclosingStatement(expr, replacement)) {
nonWriteonlyImages.add(imgName);
}
}
});
}
private static boolean isCallTopLevelStatement(GLSLParser.Postfix_expressionContext expr) {
final GLSLParser.StatementContext stmt = GlslAstHelpers.enclosingOfType(expr, GLSLParser.StatementContext.class);
if (stmt == null) return false;
return stmt.getText().equals(expr.getText() + ";");
}
private static boolean replaceEnclosingStatement(ParseTree expr, ParserRuleContext replacement) {
final GLSLParser.StatementContext stmt = GlslAstHelpers.enclosingOfType(expr, GLSLParser.StatementContext.class);
if (stmt == null) return false;
if (!(stmt.parent instanceof ParserRuleContext parent) || parent.children == null) return false;
final int idx = parent.children.indexOf(stmt);
if (idx < 0) return false;
replacement.parent = parent;
parent.children.set(idx, replacement);
return true;
}
private static String buildInlineAtomicEmulation(String op, String imgName, List<GLSLParser.Assignment_expressionContext> args, ImageDecl decl) {
if (args.size() < 2) return null;
final String idx = args.get(1).getText();
final String glslType = decl.glslType();
final String scalar = scalarFor(glslType);
final String vec = componentVecFor(glslType);
final String vecArgs = vecArgsFor(vec);
final String compute;
switch (op) {
case "imageAtomicAdd" -> {
if (args.size() < 3) return null;
compute = "_vg_prev + " + args.get(2).getText();
}
case "imageAtomicAnd" -> {
if (args.size() < 3) return null;
compute = "_vg_prev & " + args.get(2).getText();
}
case "imageAtomicOr" -> {
if (args.size() < 3) return null;
compute = "_vg_prev | " + args.get(2).getText();
}
case "imageAtomicXor" -> {
if (args.size() < 3) return null;
compute = "_vg_prev ^ " + args.get(2).getText();
}
case "imageAtomicMin" -> {
if (args.size() < 3) return null;
compute = "min(_vg_prev, " + args.get(2).getText() + ")";
}
case "imageAtomicMax" -> {
if (args.size() < 3) return null;
compute = "max(_vg_prev, " + args.get(2).getText() + ")";
}
case "imageAtomicExchange" -> {
if (args.size() < 3) return null;
compute = args.get(2).getText();
}
case "imageAtomicCompSwap" -> {
if (args.size() < 4) return null;
compute = "(_vg_prev == " + args.get(2).getText() + " ? " + args.get(3).getText() + " : _vg_prev)";
}
default -> {
return null;
}
}
return "{ " + scalar + " _vg_prev = imageLoad(" + imgName + ", " + idx + ").x; "
+ "imageStore(" + imgName + ", " + idx + ", " + vec + "(" + compute + vecArgs + ")); }";
}
private static String scalarFor(String glslType) {
if (glslType.startsWith("iimage")) return "int";
if (glslType.startsWith("uimage")) return "uint";
return "float";
}
private static String componentVecFor(String glslType) {
if (glslType.startsWith("iimage")) return "ivec4";
if (glslType.startsWith("uimage")) return "uvec4";
return "vec4";
}
private static String vecArgsFor(String vec) {
return switch (vec) {
case "ivec4" -> ", 0, 0, 0";
case "uvec4" -> ", 0u, 0u, 0u";
default -> ", 0.0, 0.0, 0.0";
};
}
private static void stripStorageQualifiers(Transformer t, Set<String> kill) {
t.mutateTree(tree -> {
for (var sq : GlslAstHelpers.collectAll(tree, GLSLParser.Storage_qualifierContext.class)) {
if (!kill.contains(sq.getText())) continue;
blankLeadingToken(sq);
}
});
}
private static void stripInterfaceOnlyQualifiers(Transformer t) {
t.mutateTree(tree -> {
for (var iq : GlslAstHelpers.collectAll(tree, GLSLParser.Interpolation_qualifierContext.class)) {
blankLeadingToken(iq);
}
for (var sq : GlslAstHelpers.collectAll(tree, GLSLParser.Storage_qualifierContext.class)) {
if (!AUXILIARY_STORAGE_QUALIFIERS.contains(sq.getText())) continue;
blankLeadingToken(sq);
}
});
}
private static final Set<String> AUXILIARY_STORAGE_QUALIFIERS = Set.of("centroid", "sample", "patch");
private static void blankLeadingToken(ParserRuleContext ctx) {
if (ctx.getChildCount() == 0) return;
if (!(ctx.getChild(0) instanceof TerminalNode tn)) return;
if (tn.getSymbol() instanceof CommonToken ct) ct.setText("");
}
private static void hoistNonConstGlobalInitializers(Transformer t) {
final StringBuilder assigns = new StringBuilder();
t.mutateTree(tree -> {
for (var ed : ((GLSLParser.Translation_unitContext) tree).external_declaration()) {
final var decl = ed.declaration();
if (decl == null) continue;
final var singles = GlslAstHelpers.collectAll(decl, GLSLParser.Single_declarationContext.class);
if (singles.isEmpty()) continue;
final var fst = singles.get(0).fully_specified_type();
if (fst == null || (fst.type_qualifier() != null && hasStorageQualifier(fst.type_qualifier()))) continue;
if (hasUnsizedArraySpecifierOutsideInitializer(decl)) continue;
for (var td : GlslAstHelpers.collectAll(decl, GLSLParser.Typeless_declarationContext.class)) {
if (td.IDENTIFIER() == null || td.EQUAL() == null || td.initializer() == null) continue;
assigns.append(td.IDENTIFIER().getText()).append(" = ").append(joinTerminals(td.initializer())).append(";\n");
if (td.EQUAL().getSymbol() instanceof CommonToken ct) ct.setText("");
blankAllTerminals(td.initializer());
}
}
});
if (assigns.length() > 0) t.prependMain("{\n" + assigns + "}\n");
}
private static boolean hasUnsizedArraySpecifierOutsideInitializer(ParserRuleContext decl) {
for (var as : GlslAstHelpers.collectAll(decl, GLSLParser.Array_specifierContext.class)) {
if (GlslAstHelpers.enclosingOfType(as, GLSLParser.InitializerContext.class) != null) continue;
if (as.getText().replace(" ", "").contains("[]")) return true;
}
return false;
}
private static boolean hasStorageQualifier(GLSLParser.Type_qualifierContext tq) {
for (var sq : tq.single_type_qualifier()) {
if (sq.storage_qualifier() != null) return true;
}
return false;
}
private static String joinTerminals(ParseTree node) {
final StringBuilder sb = new StringBuilder();
joinTerminalsWalk(node, sb);
return sb.toString();
}
private static void joinTerminalsWalk(ParseTree node, StringBuilder sb) {
if (node instanceof TerminalNode tn) {
if (sb.length() > 0) sb.append(' ');
sb.append(tn.getText());
return;
}
for (int i = 0; i < node.getChildCount(); i++) joinTerminalsWalk(node.getChild(i), sb);
}
private static void blankAllTerminals(ParseTree node) {
if (node instanceof TerminalNode tn) {
if (tn.getSymbol() instanceof CommonToken ct) ct.setText("");
return;
}
for (int i = 0; i < node.getChildCount(); i++) blankAllTerminals(node.getChild(i));
}
private static void renameMainToVgBody(Transformer t) {
t.mutateTree(tree -> {
for (var fdef : GlslAstHelpers.collectAll(tree, GLSLParser.Function_definitionContext.class)) {
final var id = fdef.function_prototype().IDENTIFIER();
if (id == null) continue;
if (!"main".equals(id.getText())) continue;
if (id.getSymbol() instanceof CommonToken ct) {
ct.setText("_vg_body");
}
return;
}
});
}
private static void stripFragOutputs(Transformer t) {
final LinkedHashSet<String> outVars = new LinkedHashSet<>();
t.mutateTree(tree -> {
for (var decl : GlslAstHelpers.collectAll(tree, GLSLParser.Single_declarationContext.class)) {
final var fst = decl.fully_specified_type();
if (fst == null || fst.type_qualifier() == null) continue;
if (decl.typeless_declaration() == null || decl.typeless_declaration().IDENTIFIER() == null) continue;
boolean isOut = false;
for (var sq : fst.type_qualifier().single_type_qualifier()) {
if (sq.storage_qualifier() != null && sq.storage_qualifier().getText().equals("out")) {
isOut = true;
break;
}
}
if (isOut) outVars.add(decl.typeless_declaration().IDENTIFIER().getText());
}
});
for (String name : outVars) t.removeVariable(name);
t.mutateTree(tree -> {
for (var assign : GlslAstHelpers.collectAll(tree, GLSLParser.Assignment_expressionContext.class)) {
if (assign.unary_expression() == null) continue;
final String lhs = assign.unary_expression().getText();
if (lhs.startsWith("gl_FragData") || lhs.equals("gl_FragColor")) {
GlslAstHelpers.deleteStatementContaining(assign);
}
}
});
}
private static String buildComputeOutput(GLSLParser.Translation_unitContext computeRoot, RwExtractMode mode, Set<String> writtenImages, Set<String> nonWriteonlyImages, Map<String, ImageDecl> declared, List<AttributeSlot> attrs) {
final StringBuilder out = new StringBuilder(8192);
out.append("// _vg_mode: ").append(modeTag(mode)).append('\n');
out.append("#version 460 core\n");
switch (mode) {
case CHUNK -> emitChunkPrelude(out, writtenImages, nonWriteonlyImages, declared, attrs);
case COMPOSITE_VSH -> emitCompositeVshPrelude(out, writtenImages, nonWriteonlyImages, declared);
case COMPOSITE_FSH -> emitCompositeFshPrelude(out, writtenImages, nonWriteonlyImages, declared);
}
out.append('\n');
out.append(GlslTransformUtils.getFormattedShader(computeRoot, ""));
out.append('\n');
emitDispatchMain(out, mode, attrs);
return out.toString();
}
private static String modeTag(RwExtractMode mode) {
return switch (mode) {
case CHUNK -> "chunk";
case COMPOSITE_VSH -> "composite-vsh";
case COMPOSITE_FSH -> "composite-fsh";
};
}
private static void emitImageDecls(StringBuilder out, Set<String> writtenImages, Set<String> nonWriteonlyImages, Map<String, ImageDecl> declared) {
final List<String> sorted = new ArrayList<>(writtenImages);
Collections.sort(sorted);
final Map<String, ImageInformation> infos = activeCustomImages;
for (int i = 0; i < sorted.size(); i++) {
final String name = sorted.get(i);
final ImageDecl d = declared.get(name);
if (d == null) continue;
final InternalTextureFormat fmt = (infos != null && infos.get(name) != null) ? infos.get(name).internalTextureFormat() : null;
final String layoutInner = (fmt != null) ? "binding = " + i + ", " + fmt.name().toLowerCase(Locale.ROOT) : "binding = " + i;
final String qualifier = nonWriteonlyImages.contains(name) ? "" : "writeonly ";
out.append("layout(").append(layoutInner).append(") ").append(qualifier).append("uniform ").append(d.glslType()).append(' ').append(name).append(";\n");
}
}
private static void emitChunkPrelude(StringBuilder out, Set<String> writtenImages, Set<String> nonWriteonlyImages, Map<String, ImageDecl> declared, List<AttributeSlot> attrs) {
out.append("layout(local_size_x = 64) in;\n\n");
emitImageDecls(out, writtenImages, nonWriteonlyImages, declared);
out.append("\nuniform int _vg_startVertex;\n");
out.append("uniform int _vg_vertexCount;\n\n");
out.append("layout(std430, binding = ").append(VG_VBUF_SSBO_BINDING).append(") readonly buffer _VgVbuf { uint data[]; } _vg_vbuf;\n\n");
out.append("vec4 _vg_sink_pos;\n");
out.append("float _vg_sink_psize;\n");
out.append("int _vg_id_global;\n");
out.append("#define gl_Position _vg_sink_pos\n");
out.append("#define gl_PointSize _vg_sink_psize\n");
out.append("#define gl_VertexID _vg_id_global\n");
out.append("#define gl_VertexIndex _vg_id_global\n");
out.append("#define gl_InstanceID 0\n");
out.append("#define gl_InstanceIndex 0\n\n");
emitAttributeGlobals(out, attrs);
out.append('\n');
out.append("int _vg_si8(uint v) { return int(v << 24) >> 24; }\n\n");
out.append("void _vg_unpack(uint id) {\n");
out.append(" uint base = id * ").append(STRIDE_UINTS).append("u;\n");
emitAttributeAssignments(out, attrs);
out.append("}\n\n");
out.append("void _vert_init() {}\n");
}
private static void emitCompositeVshPrelude(StringBuilder out, Set<String> writtenImages, Set<String> nonWriteonlyImages, Map<String, ImageDecl> declared) {
out.append("layout(local_size_x = 64) in;\n\n");
emitImageDecls(out, writtenImages, nonWriteonlyImages, declared);
out.append("\nconst vec4 _vg_quad[4] = vec4[4](\n");
out.append(" vec4(1.0, 1.0, 0.0, 1.0),\n");
out.append(" vec4(0.0, 1.0, 0.0, 1.0),\n");
out.append(" vec4(1.0, 0.0, 0.0, 1.0),\n");
out.append(" vec4(0.0, 0.0, 0.0, 1.0));\n");
out.append("vec4 _vg_gl_vertex;\n");
out.append("int _vg_gl_vertex_id;\n");
out.append("#define gl_Vertex _vg_gl_vertex\n");
out.append("#define gl_VertexID _vg_gl_vertex_id\n");
out.append("uniform mat4 gl_ModelViewProjectionMatrix;\n");
out.append("vec4 iris_ftransform() { return gl_ModelViewProjectionMatrix * gl_Vertex; }\n");
}
private static void emitCompositeFshPrelude(StringBuilder out, Set<String> writtenImages, Set<String> nonWriteonlyImages, Map<String, ImageDecl> declared) {
out.append("layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in;\n\n");
emitImageDecls(out, writtenImages, nonWriteonlyImages, declared);
out.append("\nuniform ivec2 _vg_target_size;\n");
out.append("vec4 _vg_gl_fragcoord_raw;\n");
out.append("#define gl_FragCoord _vg_gl_fragcoord_raw\n");
}
private static void emitVertexDecode(StringBuilder out, List<AttributeSlot> attrs) {
final Set<String> present = new HashSet<>();
for (AttributeSlot slot : attrs) present.add(slot.name());
out.append("#ifdef USE_VERTEX_COMPRESSION\n");
if (present.contains("a_PosId")) {
out.append(" _vert_position = vec3(a_PosId.xyz) * VERT_POS_SCALE + VERT_POS_OFFSET;\n");
out.append(" _draw_id = (a_PosId.w >> 8u) & 0xFFu;\n");
out.append(" _material_params = (a_PosId.w >> 0u) & 0xFFu;\n");
}
if (present.contains("a_TexCoord")) out.append(" _vert_tex_diffuse_coord = a_TexCoord * VERT_TEX_SCALE;\n");
if (present.contains("a_LightCoord")) out.append(" _vert_tex_light_coord = a_LightCoord;\n");
if (present.contains("a_Color")) out.append(" _vert_color = a_Color;\n");
out.append("#else\n");
if (present.contains("a_PosId")) out.append(" _vert_position = a_PosId;\n");
if (present.contains("a_TexCoord")) out.append(" _vert_tex_diffuse_coord = a_TexCoord;\n");
if (present.contains("a_Color")) out.append(" _vert_color = a_Color;\n");
if (present.contains("a_LightCoord")) {
out.append(" uint _vg_draw_params = a_LightCoord & 0xFFFFu;\n");
out.append(" _material_params = _vg_draw_params & 0xFFu;\n");
out.append(" _draw_id = (_vg_draw_params >> 8) & 0xFFu;\n");
out.append(" _vert_tex_light_coord = ivec2((uvec2((a_LightCoord >> 16) & 0xFFFFu) >> uvec2(0, 8)) & uvec2(0xFFu));\n");
}
out.append("#endif\n");
}
private static void emitDispatchMain(StringBuilder out, RwExtractMode mode, List<AttributeSlot> attrs) {
out.append("void main() {\n");
switch (mode) {
case CHUNK -> {
out.append(" int id = _vg_startVertex + int(gl_GlobalInvocationID.x);\n");
out.append(" if (id >= _vg_startVertex + _vg_vertexCount) return;\n");
out.append(" _vg_id_global = id;\n");
out.append(" _vg_unpack(uint(id));\n");
emitVertexDecode(out, attrs);
out.append(" _vg_body();\n");
}
case COMPOSITE_VSH -> {
out.append(" uint vid = gl_GlobalInvocationID.x;\n");
out.append(" if (vid >= 4u) return;\n");
out.append(" _vg_gl_vertex = _vg_quad[vid];\n");
out.append(" _vg_gl_vertex_id = int(vid);\n");
out.append(" _vg_body();\n");
}
case COMPOSITE_FSH -> {
out.append(" ivec2 px = ivec2(gl_GlobalInvocationID.xy);\n");
out.append(" if (px.x >= _vg_target_size.x || px.y >= _vg_target_size.y) return;\n");
out.append(" _vg_gl_fragcoord_raw = vec4(vec2(px) + 0.5, 0.0, 1.0);\n");
out.append(" _vg_body();\n");
}
}
out.append("}\n");
}
private static List<AttributeSlot> collectVertexAttributes(Set<String> chunkAttrsUsed, Map<String, String> chunkAttrAstTypes) {
final List<AttributeSlot> out = new ArrayList<>();
for (String name : chunkAttrsUsed) {
final Map<String, AttributeSlot> variants = CHUNK_VERTEX_ATTRS.get(name);
if (variants == null) continue;
final String astType = chunkAttrAstTypes.get(name);
if (astType != null) {
final AttributeSlot pinned = variants.get(astType);
if (pinned != null) {
out.add(pinned);
continue;
}
}
out.addAll(variants.values());
}
return out;
}
private static Map<String, String> collectChunkAttrAstTypes(List<GLSLParser.Single_declarationContext> decls) {
final LinkedHashMap<String, String> out = new LinkedHashMap<>();
for (var decl : decls) {
if (decl.typeless_declaration() == null || decl.typeless_declaration().IDENTIFIER() == null) continue;
final String name = decl.typeless_declaration().IDENTIFIER().getText();
if (!CHUNK_VERTEX_ATTRS.containsKey(name)) continue;
if (decl.fully_specified_type() == null || decl.fully_specified_type().type_specifier() == null) continue;
final String typeText = decl.fully_specified_type().type_specifier().getText();
out.putIfAbsent(name, typeText);
}
return out;
}
private static void emitAttributeGlobals(StringBuilder out, List<AttributeSlot> attrs) {
final LinkedHashMap<String, List<AttributeSlot>> byName = groupByName(attrs);
for (var e : byName.entrySet()) {
final List<AttributeSlot> variants = e.getValue();
if (variants.size() == 1) {
final AttributeSlot v = variants.get(0);
out.append(v.glslType()).append(' ').append(v.name()).append(";\n");
} else {
final AttributeSlot live = pickLive(variants);
final AttributeSlot dead = pickDead(variants, live);
out.append("#ifdef USE_VERTEX_COMPRESSION\n");
out.append(dead.glslType()).append(' ').append(dead.name()).append(";\n");
out.append("#else\n");
out.append(live.glslType()).append(' ').append(live.name()).append(";\n");
out.append("#endif\n");
}
}
}
private static void emitAttributeAssignments(StringBuilder out, List<AttributeSlot> attrs) {
final LinkedHashMap<String, List<AttributeSlot>> byName = groupByName(attrs);
for (var e : byName.entrySet()) {
final List<AttributeSlot> variants = e.getValue();
if (variants.size() == 1) {
final AttributeSlot v = variants.get(0);
out.append(" ").append(v.name()).append(" = ").append(v.unpackExpr()).append(";\n");
} else {
final AttributeSlot live = pickLive(variants);
final AttributeSlot dead = pickDead(variants, live);
out.append("#ifdef USE_VERTEX_COMPRESSION\n");
out.append(" ").append(dead.name()).append(" = ").append(dead.unpackExpr()).append(";\n");
out.append("#else\n");
out.append(" ").append(live.name()).append(" = ").append(live.unpackExpr()).append(";\n");
out.append("#endif\n");
}
}
}
private static LinkedHashMap<String, List<AttributeSlot>> groupByName(List<AttributeSlot> attrs) {
final LinkedHashMap<String, List<AttributeSlot>> out = new LinkedHashMap<>();
for (AttributeSlot a : attrs) out.computeIfAbsent(a.name(), k -> new ArrayList<>()).add(a);
return out;
}
private static AttributeSlot pickLive(List<AttributeSlot> variants) {
for (AttributeSlot v : variants) if (v.liveBranch()) return v;
return variants.get(0);
}
private static AttributeSlot pickDead(List<AttributeSlot> variants, AttributeSlot live) {
for (AttributeSlot v : variants) if (v != live) return v;
return variants.get(0);
}
static final Map<String, Map<String, AttributeSlot>> CHUNK_VERTEX_ATTRS = buildAttrTable();
private static Map<String, Map<String, AttributeSlot>> buildAttrTable() {
final LinkedHashMap<String, LinkedHashMap<String, AttributeSlot>> m = new LinkedHashMap<>();
addAttr(m, new AttributeSlot("iris_Vertex", "vec4", 0,
"vec4(uintBitsToFloat(_vg_vbuf.data[base + 0u]), uintBitsToFloat(_vg_vbuf.data[base + 1u]), uintBitsToFloat(_vg_vbuf.data[base + 2u]), 1.0)"));
addAttr(m, new AttributeSlot("iris_Color", "vec4", 12,
"vec4(float(_vg_vbuf.data[base + 3u] & 0xFFu), float((_vg_vbuf.data[base + 3u] >> 8) & 0xFFu), float((_vg_vbuf.data[base + 3u] >> 16) & 0xFFu), float((_vg_vbuf.data[base + 3u] >> 24) & 0xFFu)) * (1.0 / 255.0)"));
addAttr(m, new AttributeSlot("iris_MultiTexCoord0", "vec4", 16,
"vec4(uintBitsToFloat(_vg_vbuf.data[base + 4u]), uintBitsToFloat(_vg_vbuf.data[base + 5u]), 0.0, 1.0)"));
addAttr(m, new AttributeSlot("iris_MultiTexCoord1", "vec4", 24,
"vec4(float(_vg_vbuf.data[base + 6u] & 0xFFFFu) * (1.0/16.0), float((_vg_vbuf.data[base + 6u] >> 16) & 0xFFFFu) * (1.0/16.0), 0.0, 1.0)"));
addAttr(m, new AttributeSlot("mc_midTexCoord", "vec4", 28,
"vec4(float(_vg_vbuf.data[base + 7u] & 0xFFFFu), float((_vg_vbuf.data[base + 7u] >> 16) & 0xFFFFu), 0.0, 1.0)"));
addAttr(m, new AttributeSlot("mc_midTexCoord", "vec2", 28,
"vec2(float(_vg_vbuf.data[base + 7u] & 0xFFFFu), float((_vg_vbuf.data[base + 7u] >> 16) & 0xFFFFu))"));
addAttr(m, new AttributeSlot("at_tangent", "vec4", 32,
"vec4(float(_vg_si8(_vg_vbuf.data[base + 8u])) * (1.0/127.0), float(_vg_si8(_vg_vbuf.data[base + 8u] >> 8)) * (1.0/127.0), float(_vg_si8(_vg_vbuf.data[base + 8u] >> 16)) * (1.0/127.0), float(_vg_si8(_vg_vbuf.data[base + 8u] >> 24)) * (1.0/127.0))"));
addAttr(m, new AttributeSlot("iris_Normal", "vec3", 36,
"vec3(float(_vg_si8(_vg_vbuf.data[base + 9u])) * (1.0/127.0), float(_vg_si8(_vg_vbuf.data[base + 9u] >> 8)) * (1.0/127.0), float(_vg_si8(_vg_vbuf.data[base + 9u] >> 16)) * (1.0/127.0))"));
addAttr(m, new AttributeSlot("mc_Entity", "vec4", 40,
"vec4(float(_vg_vbuf.data[base + 10u]), 0.0, 0.0, 0.0)"));
addAttr(m, new AttributeSlot("mc_Entity", "uint", 40,
"_vg_vbuf.data[base + 10u]"));
addAttr(m, new AttributeSlot("at_midBlock", "vec4", 44,
"vec4(float(_vg_si8(_vg_vbuf.data[base + 11u])), float(_vg_si8(_vg_vbuf.data[base + 11u] >> 8)), float(_vg_si8(_vg_vbuf.data[base + 11u] >> 16)), float(_vg_si8(_vg_vbuf.data[base + 11u] >> 24)))"));
addAttr(m, new AttributeSlot("a_PosId", "vec3", 0,
"vec3(uintBitsToFloat(_vg_vbuf.data[base + 0u]), uintBitsToFloat(_vg_vbuf.data[base + 1u]), uintBitsToFloat(_vg_vbuf.data[base + 2u]))"));
addAttr(m, new AttributeSlot("a_Color", "vec4", 12,
"vec4(float(_vg_vbuf.data[base + 3u] & 0xFFu), float((_vg_vbuf.data[base + 3u] >> 8) & 0xFFu), float((_vg_vbuf.data[base + 3u] >> 16) & 0xFFu), float((_vg_vbuf.data[base + 3u] >> 24) & 0xFFu)) * (1.0 / 255.0)"));
addAttr(m, new AttributeSlot("a_TexCoord", "vec2", 16,
"vec2(uintBitsToFloat(_vg_vbuf.data[base + 4u]), uintBitsToFloat(_vg_vbuf.data[base + 5u]))"));
addAttr(m, new AttributeSlot("a_LightCoord", "uint", 24,
"_vg_vbuf.data[base + 6u]"));
addAttr(m, new AttributeSlot("a_PosId", "uvec4", 0,
"uvec4(0u, 0u, 0u, 0u)", false));
addAttr(m, new AttributeSlot("a_LightCoord", "ivec2", 24,
"ivec2(0, 0)", false));
final LinkedHashMap<String, Map<String, AttributeSlot>> immutable = new LinkedHashMap<>();
for (var e : m.entrySet()) immutable.put(e.getKey(), Map.copyOf(e.getValue()));
return Map.copyOf(immutable);
}
private static void addAttr(LinkedHashMap<String, LinkedHashMap<String, AttributeSlot>> m, AttributeSlot slot) {
m.computeIfAbsent(slot.name(), _ -> new LinkedHashMap<>()).put(slot.glslType(), slot);
}
}
@@ -0,0 +1,41 @@
package net.coderbot.iris.pipeline.transform;
import net.coderbot.iris.pipeline.transform.parameter.Parameters;
import org.taumc.glsl.Transformer;
import java.util.List;
import java.util.Map;
final class SamplerAliasDeduplicator {
private record AliasGroup(String canonical, List<String> aliases) {}
private static final List<AliasGroup> GROUPS = List.of(
new AliasGroup("tex", List.of("texture", "gtexture", "textureAtlas")),
new AliasGroup("depthtex0", List.of("gdepthtex")),
new AliasGroup("dhDepthTex0", List.of("dhDepthTex"))
);
private SamplerAliasDeduplicator() {}
static void transformGrouped(Map<PatchShaderType, Transformer> trees, Parameters parameters) {
for (AliasGroup group : GROUPS) {
applyGroup(trees, group);
}
}
private static void applyGroup(Map<PatchShaderType, Transformer> trees, AliasGroup group) {
String canonical = group.canonical();
for (String alias : group.aliases()) {
for (Transformer t : trees.values()) {
if (t == null || t.findType(alias) == 0) continue;
if (t.findType(canonical) != 0) {
t.removeVariable(alias);
t.rename(alias, canonical);
} else {
t.rename(alias, canonical);
}
}
}
}
}
@@ -0,0 +1,156 @@
package net.coderbot.iris.pipeline.transform;
import net.coderbot.iris.gl.image.ImageInformation;
import com.gtnewhorizons.angelica.glsm.GlslTransformUtils;
import com.gtnewhorizons.angelica.glsm.backend.BackendManager;
import com.gtnewhorizons.angelica.glsm.texture.InternalTextureFormat;
import net.coderbot.iris.pipeline.transform.parameter.Parameters;
import org.taumc.glsl.ShaderParser;
import org.taumc.glsl.Transformer;
import org.taumc.glsl.grammar.GLSLLexer;
import org.taumc.glsl.grammar.GLSLParser;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
public final class SamplerToStorageImageRewriter {
public record Candidate(String samplerName, String imageName, String layoutQualifier, int dim, boolean signedInt) {}
private static volatile Set<Candidate> activeCandidates = Set.of();
public static void setActiveCandidates(Set<Candidate> candidates) {
activeCandidates = (candidates == null) ? Set.of() : Set.copyOf(candidates);
}
public static Set<Candidate> activeCandidates() {
return activeCandidates;
}
/** SDL_GPU forbids sampler usage on integer formats */
public static Set<Candidate> buildCandidates(Iterable<ImageInformation> infos) {
if (!BackendManager.RENDER_BACKEND.isSDLGPU()) return Set.of();
final HashSet<Candidate> out = new HashSet<>();
for (ImageInformation info : infos) {
if (info.samplerName() == null || info.samplerName().isEmpty()) continue;
if (!info.format().isInteger()) continue;
final int dim = switch (info.target()) {
case TEXTURE_1D -> 1;
case TEXTURE_2D, TEXTURE_RECTANGLE -> 2;
case TEXTURE_3D -> 3;
};
final InternalTextureFormat fmt = info.internalTextureFormat();
final String layout = fmt.name().toLowerCase(Locale.ROOT);
final boolean signed = fmt.name().endsWith("I") && !fmt.name().endsWith("UI");
out.add(new Candidate(info.samplerName(), info.name(), layout, dim, signed));
}
return out;
}
private SamplerToStorageImageRewriter() {}
public static void transformGrouped(Map<PatchShaderType, Transformer> trees, Parameters parameters) {
final Set<Candidate> candidates = activeCandidates;
if (candidates.isEmpty()) return;
final Set<String> samplerNames = new HashSet<>();
for (Candidate c : candidates) samplerNames.add(c.samplerName());
final Set<String> filtered = collectFilteredSamplers(trees, samplerNames);
for (Candidate c : candidates) {
if (filtered.contains(c.samplerName())) continue;
applyCandidate(trees, c);
}
}
private static void applyCandidate(Map<PatchShaderType, Transformer> trees, Candidate c) {
final int expectedType = c.signedInt
? lexerTypeForISampler(c.dim)
: lexerTypeForUSampler(c.dim);
if (expectedType == 0) return;
for (Transformer t : trees.values()) {
if (t == null) continue;
if (t.findType(c.samplerName) != expectedType) continue;
if (t.findType(c.imageName) != 0) continue;
t.removeVariable(c.samplerName);
final String imageType = (c.signedInt ? "iimage" : "uimage") + c.dim + "D";
t.variable = null;
t.injectVariable("layout(" + c.layoutQualifier + ") readonly uniform " + imageType + " " + c.imageName + ";");
t.rename(c.samplerName, c.imageName);
rewriteTexelFetchToImageLoad(t, c.imageName);
}
}
private static int lexerTypeForUSampler(int dim) {
return switch (dim) {
case 1 -> GLSLLexer.USAMPLER1D;
case 2 -> GLSLLexer.USAMPLER2D;
case 3 -> GLSLLexer.USAMPLER3D;
default -> 0;
};
}
private static int lexerTypeForISampler(int dim) {
return switch (dim) {
case 1 -> GLSLLexer.ISAMPLER1D;
case 2 -> GLSLLexer.ISAMPLER2D;
case 3 -> GLSLLexer.ISAMPLER3D;
default -> 0;
};
}
private static final Set<String> FILTERED_CALL_NAMES = buildFilteredCallNames();
private static Set<String> buildFilteredCallNames() {
final Set<String> modernNames = new HashSet<>(Set.of("texture", "textureLod", "textureGrad", "textureProj", "textureGather", "textureOffset", "textureProjLod"));
final Set<String> names = new HashSet<>(modernNames);
GlslTransformUtils.TEXTURE_RENAMES.forEach((legacy, modern) -> {
if (modernNames.contains(modern)) names.add(legacy);
});
return Set.copyOf(names);
}
private static Set<String> collectFilteredSamplers(Map<PatchShaderType, Transformer> trees, Set<String> samplerNames) {
final Set<String> filtered = new HashSet<>();
if (samplerNames.isEmpty()) return filtered;
for (Transformer t : trees.values()) {
if (t == null) continue;
t.mutateTree(tree -> {
for (GLSLParser.Postfix_expressionContext expr : GlslAstHelpers.collectAll(tree, GLSLParser.Postfix_expressionContext.class)) {
final String fname = GlslAstHelpers.extractCallName(expr);
if (fname == null) continue;
if (!isFilteredCallName(fname)) continue;
final String first = GlslAstHelpers.firstArgIdentifier(expr);
if (samplerNames.contains(first)) filtered.add(first);
}
});
}
return filtered;
}
private static boolean isFilteredCallName(String fname) {
for (String n : FILTERED_CALL_NAMES) if (n.equals(fname)) return true;
return false;
}
private static void rewriteTexelFetchToImageLoad(Transformer transformer, String imageName) {
transformer.mutateTree(tree -> {
final List<GLSLParser.Postfix_expressionContext> all = GlslAstHelpers.collectAll(tree, GLSLParser.Postfix_expressionContext.class);
for (GLSLParser.Postfix_expressionContext expr : all) {
final String fname = GlslAstHelpers.extractCallName(expr);
if (!"texelFetch".equals(fname)) continue;
if (!GlslAstHelpers.firstArgIdentifier(expr).equals(imageName)) continue;
final String secondArg = GlslAstHelpers.secondArgText(expr);
if (secondArg == null) continue;
final String replacement = "imageLoad(" + imageName + ", " + secondArg + ")";
final GLSLParser.Postfix_expressionContext parsed = ShaderParser.parseSnippet(replacement, GLSLParser::postfix_expression);
GlslAstHelpers.replaceNode(expr, parsed);
}
});
}
}
@@ -4,12 +4,11 @@ import com.google.common.base.Stopwatch;
import com.gtnewhorizons.angelica.glsm.CompatShaderTransformer;
import com.gtnewhorizons.angelica.glsm.GlslTransformUtils;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import com.gtnewhorizons.angelica.glsm.backend.BackendManager;
import com.gtnewhorizons.angelica.rendering.celeritas.iris.IrisExtendedChunkVertexType;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gl.shader.ShaderType;
import com.gtnewhorizons.angelica.glsm.shader.ShaderType;
import net.coderbot.iris.pipeline.transform.parameter.AttributeParameters;
import net.coderbot.iris.pipeline.transform.parameter.Parameters;
import org.embeddedt.embeddium.impl.gl.shader.ShaderConstants;
@@ -18,6 +17,7 @@ import org.taumc.glsl.ShaderParser;
import org.taumc.glsl.Transformer;
import org.taumc.glsl.grammar.GLSLLexer;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.HashSet;
import java.util.Map;
@@ -45,14 +45,18 @@ public class ShaderTransformer {
}
private record VersionRequirement(String keyword, int minVersion, BooleanSupplier supported) {}
private record VersionRequirement(String keyword, int minVersion, boolean prefix, BooleanSupplier supported) {
VersionRequirement(String keyword, int minVersion, BooleanSupplier supported) {
this(keyword, minVersion, false, supported);
}
}
// Sorted descending by minVersion for early exit in getRequiredVersion
private static final VersionRequirement[] VERSION_REQUIREMENTS = {
new VersionRequirement("std430", 430, RenderSystem::supportsSSBO),
new VersionRequirement("iimage", 420, RenderSystem::supportsImageLoadStore),
new VersionRequirement("uimage", 420, RenderSystem::supportsImageLoadStore),
new VersionRequirement("iimage", 420, true, RenderSystem::supportsImageLoadStore),
new VersionRequirement("uimage", 420, true, RenderSystem::supportsImageLoadStore),
new VersionRequirement("imageLoad", 420, RenderSystem::supportsImageLoadStore),
new VersionRequirement("imageStore", 420, RenderSystem::supportsImageLoadStore),
@@ -63,6 +67,10 @@ public class ShaderTransformer {
new VersionRequirement("flat", 130, () -> RenderSystem.getMaxGlslVersion() >= 130),
};
static boolean canEmitImageOps() {
return RenderSystem.supportsImageLoadStore() && RenderSystem.getMaxGlslVersion() >= 420;
}
record NegotiationResult(int targetVersion, String profile, String error) {
static NegotiationResult error(String message) {
@@ -101,31 +109,33 @@ public class ShaderTransformer {
}
private static Pattern hoistPattern;
private static Object2IntMap<String> keywordToVersion;
/** By capturing group: a prefix match's text is not the keyword, so it cannot be looked up by name. */
private static int[] hoistGroupVersions;
private static int maxSupportedHoistVersion;
public static void init() {
final StringBuilder patternBuilder = new StringBuilder();
final Object2IntOpenHashMap<String> versionMap = new Object2IntOpenHashMap<>();
final int[] groupVersions = new int[VERSION_REQUIREMENTS.length + 1];
int groupCount = 0;
int maxVersion = 0;
for (VersionRequirement req : VERSION_REQUIREMENTS) {
if (req.supported.getAsBoolean()) {
if (!patternBuilder.isEmpty()) patternBuilder.append('|');
patternBuilder.append("\\b").append(Pattern.quote(req.keyword)).append("\\b");
versionMap.put(req.keyword, req.minVersion);
patternBuilder.append("(\\b").append(Pattern.quote(req.keyword)) .append(req.prefix ? "\\w*" : "\\b").append(')');
groupVersions[++groupCount] = req.minVersion;
maxVersion = Math.max(maxVersion, req.minVersion);
}
}
if (!patternBuilder.isEmpty()) {
hoistPattern = Pattern.compile(patternBuilder.toString());
keywordToVersion = versionMap;
hoistGroupVersions = Arrays.copyOf(groupVersions, groupCount + 1);
}
maxSupportedHoistVersion = maxVersion;
Iris.logger.info("Shader version hoisting: {} feature(s) GLSL {}", versionMap.size(), maxVersion > 0 ? maxVersion : "N/A");
Iris.logger.info("Shader version hoisting: {} feature(s) GLSL {}", groupCount, maxVersion > 0 ? maxVersion : "N/A");
}
private static int getRequiredVersion(String shaderSource, int declaredVersion) {
@@ -136,15 +146,31 @@ public class ShaderTransformer {
final Matcher m = hoistPattern.matcher(shaderSource);
int required = declaredVersion;
while (m.find()) {
final int ver = keywordToVersion.getInt(m.group());
if (ver > required) {
required = ver;
if (required >= maxSupportedHoistVersion) break;
for (int group = 1; group < hoistGroupVersions.length; group++) {
if (m.start(group) < 0) continue;
if (hoistGroupVersions[group] > required) required = hoistGroupVersions[group];
break;
}
if (required >= maxSupportedHoistVersion) break;
}
return required;
}
private record StageHeader(int version, String extensions) {}
private static String finalizeStage(int version, String headerTail, String body, PatchShaderType stage) {
final int required = getRequiredVersion(headerTail + body, version);
if (required > version) {
final NegotiationResult negotiation = negotiateVersion(required, stage);
if (negotiation.isError()) {
throw new RuntimeException("Shader version negotiation failed for " + stage.name() + " after transformation: " + negotiation.error());
}
Iris.logger.debug("Transformed {} requires GLSL {} for injected features, hoisting from {}", stage.name(), required, version);
version = required;
}
return "#version " + version + " core\n" + headerTail + body;
}
private static final class TransformKey<P extends Parameters> {
private final Patch patchType;
private final EnumMap<PatchShaderType, String> inputs;
@@ -298,8 +324,6 @@ public class ShaderTransformer {
versionString = String.valueOf(versionInt);
}
final String profileString = "#version " + versionString + " core\n";
// Pre-parse reserved word renaming
String input = GlslTransformUtils.replaceTexture(compute);
input = GlslTransformUtils.renameReservedWords(input, versionInt);
@@ -309,15 +333,25 @@ public class ShaderTransformer {
doTransform(transformer, patchType, parameters, versionInt);
// SDL_GPU forbids sampler usage on integer formats, so an integer sampler has to become a storage image here
final EnumMap<PatchShaderType, Transformer> computeTypes = new EnumMap<>(PatchShaderType.class);
computeTypes.put(PatchShaderType.COMPUTE, transformer);
if (canEmitImageOps()) {
SamplerToStorageImageRewriter.transformGrouped(computeTypes, parameters);
}
if (BackendManager.RENDER_BACKEND.isSDLGPU()) {
LocalZeroInitTransformer.transformGrouped(computeTypes);
}
// Extract extensions
final var extensions = versionPattern.matcher(GlslTransformUtils.getFormattedShader(parsedShader.pre(), "")).replaceFirst("").trim();
final String finalHeader = profileString + (extensions.isEmpty() ? "" : "\n" + extensions);
final String headerTail = extensions.isEmpty() ? "" : "\n" + extensions;
final StringBuilder formattedShaderBuilder = new StringBuilder();
transformer.mutateTree(tree -> formattedShaderBuilder.append(GlslTransformUtils.getFormattedShader(tree, finalHeader)));
transformer.mutateTree(tree -> formattedShaderBuilder.append(GlslTransformUtils.getFormattedShader(tree, "")));
String formattedShader = GlslTransformUtils.restoreReservedWords(formattedShaderBuilder.toString());
final String formattedShader = GlslTransformUtils.restoreReservedWords(finalizeStage(versionInt, headerTail, formattedShaderBuilder.toString(), PatchShaderType.COMPUTE));
result.put(PatchShaderType.COMPUTE, formattedShader);
@@ -329,7 +363,7 @@ public class ShaderTransformer {
private static <P extends Parameters> Map<PatchShaderType, String> transformInternal(EnumMap<PatchShaderType, String> inputs, Patch patchType, P parameters) {
final EnumMap<PatchShaderType, String> result = new EnumMap<>(PatchShaderType.class);
final EnumMap<PatchShaderType, Transformer> types = new EnumMap<>(PatchShaderType.class);
final EnumMap<PatchShaderType, String> prepatched = new EnumMap<>(PatchShaderType.class);
final EnumMap<PatchShaderType, StageHeader> prepatched = new EnumMap<>(PatchShaderType.class);
final Stopwatch watch = Stopwatch.createStarted();
@@ -353,9 +387,7 @@ public class ShaderTransformer {
int versionInt = Integer.parseInt(versionString);
// Include celeritas header in scan — it's injected post-negotiation but contains uint/uvec3
final String scanSource = (patchType == Patch.CELERITAS_TERRAIN && type == PatchShaderType.VERTEX) ? input + computeCeleritasHeader() : input;
final int requiredVersion = getRequiredVersion(scanSource, versionInt);
final int requiredVersion = getRequiredVersion(input, versionInt);
if (requiredVersion > versionInt) {
Iris.logger.debug("Shader requires GLSL {} for detected features, hoisting from {}", requiredVersion, versionInt);
versionInt = requiredVersion;
@@ -375,10 +407,6 @@ public class ShaderTransformer {
throw new RuntimeException("Shader version negotiation failed for " + type.name() + ": " + negotiation.error());
}
// All stages >= 330 use core profile
final String profile = "core";
final String profileString = "#version " + versionString + " " + profile + "\n";
// Pre-parse reserved word renaming — prevents ANTLR parse failures
input = GlslTransformUtils.replaceTexture(input);
input = GlslTransformUtils.renameReservedWords(input, versionInt);
@@ -394,38 +422,70 @@ public class ShaderTransformer {
final var extensions = versionPattern.matcher(GlslTransformUtils.getFormattedShader(parsedShader.pre(), "")).replaceFirst("").trim();
types.put(type, transformer);
prepatched.put(type, profileString + (extensions.isEmpty() ? "" : "\n" + extensions));
prepatched.put(type, new StageHeader(versionInt, extensions.isEmpty() ? "" : "\n" + extensions));
}
CompatibilityTransformer.transformGrouped(types, parameters);
if (BackendManager.RENDER_BACKEND.isSDLGPU()) {
SamplerAliasDeduplicator.transformGrouped(types, parameters);
}
if (canEmitImageOps()) {
SamplerToStorageImageRewriter.transformGrouped(types, parameters);
}
if (BackendManager.RENDER_BACKEND.isSDLGPU()) {
LocalZeroInitTransformer.transformGrouped(types);
}
for (var entry : types.entrySet()) {
final PatchShaderType shaderType = entry.getKey();
final Transformer transformer = entry.getValue();
String header = prepatched.get(shaderType);
final StageHeader stageHeader = prepatched.get(shaderType);
String headerTail = stageHeader.extensions();
// For Celeritas terrain vertex shaders, inject chunk_vertex.glsl header
if (patchType == Patch.CELERITAS_TERRAIN && shaderType == PatchShaderType.VERTEX) {
header += computeCeleritasHeader();
headerTail += computeCeleritasHeader();
}
final String finalHeader = header;
final StringBuilder formattedShaderBuilder = new StringBuilder();
transformer.mutateTree(tree -> formattedShaderBuilder.append(GlslTransformUtils.getFormattedShader(tree, finalHeader)));
transformer.mutateTree(tree -> formattedShaderBuilder.append(GlslTransformUtils.getFormattedShader(tree, "")));
String formattedShader = GlslTransformUtils.restoreReservedWords(formattedShaderBuilder.toString());
final String formattedShader = GlslTransformUtils.restoreReservedWords( finalizeStage(stageHeader.version(), headerTail, formattedShaderBuilder.toString(), shaderType));
result.put(shaderType, formattedShader);
}
maybeExtractRwImageStores(result, patchType);
watch.stop();
Iris.logger.info("[Load #{}] Transformed shader for {} in {}", Iris.getShaderPackLoadId(), patchType.name(), watch);
return result;
}
private static void maybeExtractRwImageStores(EnumMap<PatchShaderType, String> result, Patch patchType) {
if (!BackendManager.RENDER_BACKEND.isSDLGPU()) return;
if (result.containsKey(PatchShaderType.COMPUTE)) return;
final String vsh = result.get(PatchShaderType.VERTEX);
final String fsh = result.get(PatchShaderType.FRAGMENT);
final RwImageStoreExtractor.Result vshResult = (vsh != null) ? RwImageStoreExtractor.tryExtract(vsh, PatchShaderType.VERTEX, patchType.name()) : null;
final RwImageStoreExtractor.Result fshResult = (fsh != null) ? RwImageStoreExtractor.tryExtract(fsh, PatchShaderType.FRAGMENT, patchType.name()) : null;
if (vshResult != null && fshResult != null) {
throw new RuntimeException("Program " + patchType.name() + " writes images from both VSH and FSH; only one stage may write per program under SDL_GPU");
}
if (vshResult != null) {
result.put(PatchShaderType.VERTEX, vshResult.strippedSource());
result.put(PatchShaderType.COMPUTE, vshResult.computeSource());
Iris.logger.info("[RwImageStoreExtractor] Extracted compute pre-pass for {} (mode={}, written={})", patchType.name(), vshResult.mode(), vshResult.writtenImages());
} else if (fshResult != null) {
result.put(PatchShaderType.FRAGMENT, fshResult.strippedSource());
result.put(PatchShaderType.COMPUTE, fshResult.computeSource());
Iris.logger.info("[RwImageStoreExtractor] Extracted compute pre-pass for {} (mode={}, written={})", patchType.name(), fshResult.mode(), fshResult.writtenImages());
}
}
private static void doTransform(Transformer transformer, Patch patchType, Parameters parameters, int versionInt) {
switch (patchType) {
case CELERITAS_TERRAIN:
CeleritasTransformer.transform(transformer, parameters, versionInt);
// Handle mc_midTexCoord for Celeritas
patchMultiTexCoord3(transformer, parameters);
replaceMidTexCoord(transformer, IrisExtendedChunkVertexType.MID_TEX_SCALE);
replaceMCEntity(transformer, parameters);
@@ -1,7 +1,7 @@
package net.coderbot.iris.pipeline.transform;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import net.coderbot.iris.gl.texture.TextureType;
import com.gtnewhorizons.angelica.glsm.texture.TextureType;
import net.coderbot.iris.helpers.Tri;
import net.coderbot.iris.pipeline.transform.parameter.Parameters;
import net.coderbot.iris.shaderpack.texture.TextureStage;
@@ -1,8 +1,13 @@
package net.coderbot.iris.pipeline.transform;
import com.gtnewhorizons.angelica.glsm.CompatShaderTransformer;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import com.gtnewhorizons.angelica.glsm.backend.BackendManager;
import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks;
import com.gtnewhorizons.angelica.glsm.hooks.ShaderTransformPostProcessor;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability;
import net.coderbot.iris.gl.texture.TextureType;
import com.gtnewhorizons.angelica.glsm.texture.TextureType;
import net.coderbot.iris.helpers.Tri;
import net.coderbot.iris.pipeline.transform.parameter.AttributeParameters;
import net.coderbot.iris.pipeline.transform.parameter.CeleritasTerrainParameters;
@@ -94,9 +99,30 @@ public class TransformPatcher {
// Double-check in case another thread added it while we were transforming
final Map<PatchShaderType, String> existing = cache.get(key);
if (existing != null) {
return existing;
result = existing;
} else {
cache.put(key, result);
}
cache.put(key, result);
}
}
}
if (result != null && RenderSystem.isGLES()) {
for (Map.Entry<PatchShaderType, String> entry : result.entrySet()) {
final String src = entry.getValue();
if (src == null) continue;
final PatchShaderType pType = entry.getKey();
CompatShaderTransformer.prewarm(src, pType.glShaderType.id, pType == PatchShaderType.FRAGMENT);
}
}
if (result != null && BackendManager.RENDER_BACKEND.isSDLGPU()) {
final ShaderTransformPostProcessor processor = GLSMHooks.postTransformProcessor;
if (processor != null) {
for (Map.Entry<PatchShaderType, String> entry : result.entrySet()) {
final String src = entry.getValue();
if (src == null) continue;
processor.onTransformed(src, entry.getKey().glShaderType);
}
}
}
@@ -108,6 +134,10 @@ public class TransformPatcher {
return transform(vertex, geometry, tessControl, tessEval, fragment, new AttributeParameters(Patch.ATTRIBUTES, geometry != null, inputs, scrollGlint));
}
public static Map<PatchShaderType, String> patchAttributesInstanced(String vertex, String geometry, String tessControl, String tessEval, String fragment, InputAvailability inputs, boolean scrollGlint) {
return transform(vertex, geometry, tessControl, tessEval, fragment, new AttributeParameters(Patch.ATTRIBUTES, geometry != null, inputs, scrollGlint, true));
}
public static Map<PatchShaderType, String> patchAttributes(String vertex, String geometry, String tessControl, String tessEval, String fragment, InputAvailability inputs) {
return patchAttributes(vertex, geometry, tessControl, tessEval, fragment, inputs, false);
}
@@ -154,7 +184,14 @@ public class TransformPatcher {
return null;
}
Map<PatchShaderType, String> result = ShaderTransformer.transformCompute(compute, new ComputeParameters(Patch.COMPUTE, stage, textureMap));
return result != null ? result.get(PatchShaderType.COMPUTE) : null;
final String transformed = result != null ? result.get(PatchShaderType.COMPUTE) : null;
if (transformed != null && BackendManager.RENDER_BACKEND.isSDLGPU()) {
final ShaderTransformPostProcessor processor = GLSMHooks.postTransformProcessor;
if (processor != null) {
processor.onTransformed(transformed, PatchShaderType.COMPUTE.glShaderType);
}
}
return transformed;
}
public static void clearCache() {
@@ -8,13 +8,19 @@ public class AttributeParameters extends Parameters {
public final boolean hasGeometry;
public final InputAvailability inputs;
public final boolean scrollGlint;
public final boolean instanced;
// WARNING: adding new fields requires updating hashCode and equals methods!
public AttributeParameters(Patch patch, boolean hasGeometry, InputAvailability inputs, boolean scrollGlint) {
this(patch, hasGeometry, inputs, scrollGlint, false);
}
public AttributeParameters(Patch patch, boolean hasGeometry, InputAvailability inputs, boolean scrollGlint, boolean instanced) {
super(patch, null);
this.hasGeometry = hasGeometry;
this.inputs = inputs;
this.scrollGlint = scrollGlint;
this.instanced = instanced;
}
@Override
@@ -28,6 +34,7 @@ public class AttributeParameters extends Parameters {
int result = super.hashCode();
result = prime * result + (hasGeometry ? 1231 : 1237);
result = prime * result + (scrollGlint ? 1231 : 1237);
result = prime * result + (instanced ? 1231 : 1237);
result = prime * result + ((inputs == null) ? 0 : inputs.hashCode());
return result;
}
@@ -45,6 +52,8 @@ public class AttributeParameters extends Parameters {
return false;
if (scrollGlint != other.scrollGlint)
return false;
if (instanced != other.instanced)
return false;
if (inputs == null) {
if (other.inputs != null)
return false;
@@ -2,7 +2,7 @@ package net.coderbot.iris.pipeline.transform.parameter;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import net.coderbot.iris.gl.blending.AlphaTest;
import net.coderbot.iris.gl.texture.TextureType;
import com.gtnewhorizons.angelica.glsm.texture.TextureType;
import net.coderbot.iris.helpers.Tri;
import net.coderbot.iris.pipeline.transform.Patch;
import net.coderbot.iris.shaderpack.texture.TextureStage;
@@ -1,7 +1,7 @@
package net.coderbot.iris.pipeline.transform.parameter;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import net.coderbot.iris.gl.texture.TextureType;
import com.gtnewhorizons.angelica.glsm.texture.TextureType;
import net.coderbot.iris.helpers.Tri;
import net.coderbot.iris.pipeline.transform.Patch;
import net.coderbot.iris.shaderpack.texture.TextureStage;
@@ -2,8 +2,8 @@ package net.coderbot.iris.pipeline.transform.parameter;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import net.coderbot.iris.gl.blending.AlphaTest;
import net.coderbot.iris.gl.shader.ShaderType;
import net.coderbot.iris.gl.texture.TextureType;
import com.gtnewhorizons.angelica.glsm.shader.ShaderType;
import com.gtnewhorizons.angelica.glsm.texture.TextureType;
import net.coderbot.iris.helpers.Tri;
import net.coderbot.iris.pipeline.transform.Patch;
import net.coderbot.iris.shaderpack.texture.TextureStage;
@@ -2,7 +2,7 @@ package net.coderbot.iris.pipeline.transform.parameter;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import net.coderbot.iris.gl.blending.AlphaTest;
import net.coderbot.iris.gl.texture.TextureType;
import com.gtnewhorizons.angelica.glsm.texture.TextureType;
import net.coderbot.iris.helpers.Tri;
import net.coderbot.iris.pipeline.transform.Patch;
import net.coderbot.iris.shaderpack.texture.TextureStage;
@@ -9,8 +9,8 @@ import net.coderbot.iris.gl.program.ProgramBuilder;
import net.coderbot.iris.gl.program.ProgramSamplers;
import net.coderbot.iris.gl.program.ProgramUniforms;
import net.coderbot.iris.gl.texture.DepthCopyStrategy;
import net.coderbot.iris.gl.texture.InternalTextureFormat;
import net.coderbot.iris.gl.texture.PixelType;
import com.gtnewhorizons.angelica.glsm.texture.InternalTextureFormat;
import com.gtnewhorizons.angelica.glsm.texture.PixelType;
import net.coderbot.iris.gl.uniform.UniformUpdateFrequency;
import net.coderbot.iris.uniforms.SystemTimeUniforms;
import net.minecraft.client.Minecraft;
@@ -3,10 +3,13 @@ package net.coderbot.iris.postprocess;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.gtnewhorizons.angelica.glsm.GLDebug;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import lombok.Getter;
import net.coderbot.iris.Iris;
import net.coderbot.iris.features.FeatureFlags;
import net.coderbot.iris.gl.framebuffer.GlFramebuffer;
import net.coderbot.iris.gl.framebuffer.ViewportData;
@@ -22,7 +25,10 @@ import net.coderbot.iris.gl.texture.TextureAccess;
import net.coderbot.iris.pipeline.PatchedShaderPrinter;
import net.coderbot.iris.pipeline.WorldRenderingPipeline;
import net.coderbot.iris.pipeline.transform.PatchShaderType;
import net.coderbot.iris.pipeline.transform.PreRasterComputeDispatcher;
import net.coderbot.iris.pipeline.transform.RwImageStoreExtractor;
import net.coderbot.iris.pipeline.transform.TransformPatcher;
import org.lwjgl.opengl.GL20;
import net.coderbot.iris.rendertarget.RenderTarget;
import net.coderbot.iris.rendertarget.RenderTargets;
import net.coderbot.iris.samplers.IrisImages;
@@ -39,6 +45,7 @@ import net.coderbot.iris.uniforms.custom.CustomUniforms;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.shader.Framebuffer;
import net.minecraft.profiler.Profiler;
import org.jetbrains.annotations.Nullable;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
@@ -54,6 +61,8 @@ import java.util.concurrent.CompletionException;
import java.util.function.Supplier;
public class CompositeRenderer {
private static final Tracy.ZoneId Z_GEN_MIPMAP = Tracy.zoneId("genMipmap", Tracy.COLOR_IRIS);
private final RenderTargets renderTargets;
private final ImmutableList<Pass> passes;
@@ -66,8 +75,8 @@ public class CompositeRenderer {
@Nullable private final Object2ObjectMap<String, TextureAccess> irisCustomTextures;
@Nullable private final WorldRenderingPipeline pipeline;
private final TextureStage textureStage;
@Getter
private final ImmutableSet<Integer> flippedAtLeastOnceFinal;
@Getter private final ImmutableSet<Integer> flippedAtLeastOnceFinal;
@Getter private int samplerUsage;
public CompositeRenderer(PackDirectives packDirectives, ProgramSource[] sources, ComputeSource[][] computes, RenderTargets renderTargets,
TextureAccess noiseTexture, FrameUpdateNotifier updateNotifier,
@@ -112,6 +121,7 @@ public class CompositeRenderer {
if (source == null || !source.isValid()) {
if (computes[i] != null) {
final ComputeOnlyPass pass = new ComputeOnlyPass();
pass.name = computeOnlyPassName(computes[i], stageName, i);
pass.computes = createComputes(computes[i], flipped, flippedAtLeastOnceSnapshot, context.shadowTargetsSupplier());
passes.add(pass);
}
@@ -119,14 +129,34 @@ public class CompositeRenderer {
}
final Pass pass = new Pass();
pass.name = "iris_" + source.getName();
final ProgramDirectives directives = source.getDirectives();
final long _passStart = System.nanoTime();
Map<PatchShaderType, String> transformed = getTransformed(source, transformFutures, i, stageName);
final long _afterTx = System.nanoTime();
pass.program = createProgramFromTransformed(source, transformed, flipped, flippedAtLeastOnceSnapshot, context.shadowTargetsSupplier());
final long _afterProg = System.nanoTime();
final String preComputeSrc = transformed.get(PatchShaderType.COMPUTE);
if (preComputeSrc != null) {
pass.preRasterMode = RwImageStoreExtractor.parseSentinel(preComputeSrc);
if (pass.preRasterMode != null) {
pass.preRasterCompute = buildPreRasterCompute(source.getName(), preComputeSrc, flipped, flippedAtLeastOnceSnapshot, context.shadowTargetsSupplier());
}
}
pass.computes = createComputes(computes[i], flipped, flippedAtLeastOnceSnapshot, context.shadowTargetsSupplier());
final long _afterComp = System.nanoTime();
final int[] drawBuffers = directives.getDrawBuffers();
final GlFramebuffer framebuffer = renderTargets.createColorFramebuffer(flipped, drawBuffers);
final long _afterFb = System.nanoTime();
Iris.logger.info("[Load #{}] {}[{}] tx={}ms prog={}ms compute={}ms fb={}ms total={}ms",
Iris.getShaderPackLoadId(), stageName, i,
String.format("%.1f", (_afterTx - _passStart) / 1_000_000.0),
String.format("%.1f", (_afterProg - _afterTx) / 1_000_000.0),
String.format("%.1f", (_afterComp - _afterProg) / 1_000_000.0),
String.format("%.1f", (_afterFb - _afterComp) / 1_000_000.0),
String.format("%.1f", (_afterFb - _passStart) / 1_000_000.0));
int passWidth = 0, passHeight = 0;
// Flip the buffers that this shader wrote to, and set pass width and height
@@ -170,6 +200,12 @@ public class CompositeRenderer {
this.passes = passes.build();
this.flippedAtLeastOnceFinal = flippedAtLeastOnce.build();
if (Tracy.ENABLED) {
for (Pass pass : this.passes) {
Tracy.message("passGraph " + stageName + "/" + pass.name + " draw=" + java.util.Arrays.toString(pass.drawBuffers) + " mipmapped=" + pass.mipmappedBuffers + " readsAlt=" + pass.stageReadsFromAlt);
}
}
OpenGlHelper.func_153171_g/*glBindFramebuffer*/(GL30.GL_READ_FRAMEBUFFER, 0);
}
@@ -213,17 +249,29 @@ public class CompositeRenderer {
}
}
private static String computeOnlyPassName(ComputeSource[] computes, String stageName, int index) {
for (ComputeSource compute : computes) {
if (compute != null) {
return "iris_" + compute.getName();
}
}
return "iris_" + stageName + "_compute" + index;
}
private static class Pass {
String name;
int[] drawBuffers;
int viewWidth;
int viewHeight;
Program program;
ComputeProgram[] computes;
@Nullable ComputeProgram preRasterCompute;
@Nullable RwImageStoreExtractor.RwExtractMode preRasterMode;
int preRasterTargetSizeLoc = -2;
GlFramebuffer framebuffer;
ImmutableSet<Integer> stageReadsFromAlt;
ImmutableSet<Integer> mipmappedBuffers;
ViewportData viewportScale;
protected void destroy() {
this.program.destroy();
for (ComputeProgram compute : this.computes) {
@@ -231,6 +279,10 @@ public class CompositeRenderer {
compute.destroy();
}
}
if (this.preRasterCompute != null) {
this.preRasterCompute.destroy();
this.preRasterCompute = null;
}
}
}
@@ -251,49 +303,72 @@ public class CompositeRenderer {
FullScreenQuadRenderer.INSTANCE.begin();
final Profiler profiler = Minecraft.getMinecraft().mcProfiler;
for (Pass renderPass : passes) {
boolean ranCompute = false;
for (ComputeProgram computeProgram : renderPass.computes) {
if (computeProgram != null) {
ranCompute = true;
final Framebuffer main = Minecraft.getMinecraft().getFramebuffer();
computeProgram.use();
this.customUniforms.push(computeProgram);
computeProgram.dispatch(main.framebufferWidth, main.framebufferHeight);
profiler.startSection(renderPass.name);
GLDebug.pushGroup(renderPass.name);
try {
boolean ranCompute = false;
for (ComputeProgram computeProgram : renderPass.computes) {
if (computeProgram != null) {
ranCompute = true;
final Framebuffer main = Minecraft.getMinecraft().getFramebuffer();
computeProgram.use();
this.customUniforms.push(computeProgram);
computeProgram.dispatch(main.framebufferWidth, main.framebufferHeight);
}
}
}
if (ranCompute) {
RenderSystem.memoryBarrier(GL42.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL42.GL_TEXTURE_FETCH_BARRIER_BIT | GL43.GL_SHADER_STORAGE_BARRIER_BIT);
}
Program.unbind();
if (renderPass instanceof ComputeOnlyPass) {
continue;
}
if (!renderPass.mipmappedBuffers.isEmpty()) {
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
for (int index : renderPass.mipmappedBuffers) {
setupMipmapping(CompositeRenderer.this.renderTargets.get(index), renderPass.stageReadsFromAlt.contains(index));
if (ranCompute) {
RenderSystem.memoryBarrier(GL42.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL42.GL_TEXTURE_FETCH_BARRIER_BIT | GL43.GL_SHADER_STORAGE_BARRIER_BIT);
for (int i = 0; i < renderTargets.getRenderTargetCount(); i++) {
renderTargets.get(i).markBothDirty();
}
}
Program.unbind();
if (renderPass instanceof ComputeOnlyPass) {
continue;
}
final ImmutableSet<Integer> readsFromAlt = renderTargets.parityResolve(renderPass.stageReadsFromAlt);
if (!renderPass.mipmappedBuffers.isEmpty()) {
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
for (int index : renderPass.mipmappedBuffers) {
setupMipmapping(CompositeRenderer.this.renderTargets.get(index), readsFromAlt.contains(index));
}
}
final float scaledWidth = renderPass.viewWidth * renderPass.viewportScale.scale();
final float scaledHeight = renderPass.viewHeight * renderPass.viewportScale.scale();
final float viewportX = renderPass.viewWidth * renderPass.viewportScale.viewportX();
final float viewportY = renderPass.viewHeight * renderPass.viewportScale.viewportY();
GLStateManager.glViewport((int) viewportX, (int) viewportY, (int) scaledWidth, (int) scaledHeight);
if (renderPass.preRasterCompute != null && renderPass.preRasterMode != null) {
dispatchPreRasterCompute(renderPass);
}
renderPass.framebuffer.bind();
renderPass.program.use();
this.customUniforms.push(renderPass.program);
FullScreenQuadRenderer.uploadCompositeMatrices();
FullScreenQuadRenderer.INSTANCE.renderQuad();
for (int buffer : renderPass.drawBuffers) {
final boolean writeIsAlt = !readsFromAlt.contains(buffer);
CompositeRenderer.this.renderTargets.get(buffer).markDirty(writeIsAlt);
}
} finally {
GLDebug.popGroup();
profiler.endSection();
}
final float scaledWidth = renderPass.viewWidth * renderPass.viewportScale.scale();
final float scaledHeight = renderPass.viewHeight * renderPass.viewportScale.scale();
final float viewportX = renderPass.viewWidth * renderPass.viewportScale.viewportX();
final float viewportY = renderPass.viewHeight * renderPass.viewportScale.viewportY();
GLStateManager.glViewport((int) viewportX, (int) viewportY, (int) scaledWidth, (int) scaledHeight);
renderPass.framebuffer.bind();
renderPass.program.use();
this.customUniforms.push(renderPass.program);
FullScreenQuadRenderer.uploadCompositeMatrices();
FullScreenQuadRenderer.INSTANCE.renderQuad();
}
FullScreenQuadRenderer.end();
@@ -306,7 +381,8 @@ public class CompositeRenderer {
GLStateManager.glUseProgram(0);
// NB: Unbinding all of these textures is necessary for proper shaderpack reloading.
for (int i = 0; i < SamplerLimits.get().getMaxTextureUnits(); i++) {
final int maxUnit = Math.min(SamplerLimits.get().getMaxTextureUnits() - 1, GLStateManager.getMaxBoundTextureUnit());
for (int i = 0; i <= maxUnit; i++) {
// Unbind all textures that we may have used.
// NB: This is necessary for shader pack reloading to work propely
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + i);
@@ -316,21 +392,26 @@ public class CompositeRenderer {
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
}
private void dispatchPreRasterCompute(Pass pass) {
pass.preRasterTargetSizeLoc = PreRasterComputeDispatcher.dispatch(pass.preRasterCompute, pass.preRasterMode, pass.preRasterTargetSizeLoc, pass.viewWidth, pass.viewHeight, this.customUniforms);
}
private static void setupMipmapping(RenderTarget target, boolean readFromAlt) {
int texture = readFromAlt ? target.getAltTexture() : target.getMainTexture();
// TODO: Only generate the mipmap if a valid mipmap hasn't been generated or if we've written to the buffer
// (since the last mipmap was generated)
//
// NB: We leave mipmapping enabled even if the buffer is written to again, this appears to match the
// behavior of ShadersMod/OptiFine, however I'm not sure if it's desired behavior. It's possible that a
// program could use mipmapped sampling with a stale mipmap, which probably isn't great. However, the
// sampling mode is always reset between frames, so this only persists after the first program to use
// mipmapping on this buffer.
//
// Also note that this only applies to one of the two buffers in a render target buffer pair - making it
// unlikely that this issue occurs in practice with most shader packs.
RenderSystem.generateMipmaps(texture, GL11.GL_TEXTURE_2D);
// Only regen when the sampled side has been written since the last regen.
if (target.isDirty(readFromAlt)) {
if (Tracy.ENABLED) {
Tracy.beginZone(Z_GEN_MIPMAP);
Tracy.zoneValue(texture);
}
try {
RenderSystem.generateMipmaps(texture, GL11.GL_TEXTURE_2D);
} finally {
if (Tracy.ENABLED) Tracy.endZone();
}
target.clearDirty(readFromAlt);
}
int filter = GL11.GL_LINEAR_MIPMAP_LINEAR;
if (target.getInternalFormat().getPixelFormat().isInteger()) {
@@ -354,6 +435,7 @@ public class CompositeRenderer {
Objects.requireNonNull(flipped);
ProgramBuilder builder;
final long _cpStart = System.nanoTime();
try {
builder = ProgramBuilder.begin(source.getName(), vertex, geometry, tessControl, tessEval, fragment,
IrisSamplers.COMPOSITE_RESERVED_TEXTURE_UNITS);
@@ -361,12 +443,60 @@ public class CompositeRenderer {
// TODO: Better error handling
throw new RuntimeException("Shader compilation failed!", e);
}
final long _afterBegin = System.nanoTime();
CommonUniforms.addDynamicUniforms(builder, FogMode.OFF);
this.customUniforms.assignTo(builder);
ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureIds, flippedAtLeastOnceSnapshot);
IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> renderTargets.parityResolve(flipped), renderTargets, true, pipeline);
IrisSamplers.addCustomImages(customTextureSamplerInterceptor, customImages);
IrisSamplers.addCustomTextures(customTextureSamplerInterceptor, irisCustomTextures);
IrisImages.addRenderTargetImages(builder, () -> renderTargets.parityResolve(flipped), renderTargets);
IrisImages.addCustomImages(builder, customImages);
IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, noiseTexture);
samplerUsage |= IrisSamplers.addCompositeSamplers(customTextureSamplerInterceptor, renderTargets);
if (IrisSamplers.hasShadowSamplers(customTextureSamplerInterceptor)) {
samplerUsage |= IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowTargetsSupplier.get(), null, pipeline != null && pipeline.hasFeature(FeatureFlags.SEPARATE_HARDWARE_SAMPLERS));
IrisImages.addShadowColorImages(builder, shadowTargetsSupplier.get(), null);
}
// TODO: Don't duplicate this with FinalPassRenderer
centerDepthSampler.setUsage(builder.addDynamicSampler(centerDepthSampler::getCenterDepthTexture, "iris_centerDepthSmooth"));
final long _afterSamplers = System.nanoTime();
Program build = builder.build();
final long _afterBuild = System.nanoTime();
this.customUniforms.mapholderToPass(builder, build);
final long _afterMapholder = System.nanoTime();
Iris.logger.info("[Load #{}] createProg name={} begin={}ms samplers={}ms build={}ms mapholder={}ms",
Iris.getShaderPackLoadId(), source.getName(),
String.format("%.1f", (_afterBegin - _cpStart) / 1_000_000.0),
String.format("%.1f", (_afterSamplers - _afterBegin) / 1_000_000.0),
String.format("%.1f", (_afterBuild - _afterSamplers) / 1_000_000.0),
String.format("%.1f", (_afterMapholder - _afterBuild) / 1_000_000.0));
return build;
}
private ComputeProgram buildPreRasterCompute(String name, String computeSource, ImmutableSet<Integer> flipped, ImmutableSet<Integer> flippedAtLeastOnceSnapshot, Supplier<ShadowRenderTargets> shadowTargetsSupplier) {
PatchedShaderPrinter.debugPatchedShaders(name + "_pre_compute", null, null, null, computeSource);
final ProgramBuilder builder;
try {
builder = ProgramBuilder.beginCompute(name + "_pre", computeSource, IrisSamplers.COMPOSITE_RESERVED_TEXTURE_UNITS);
} catch (RuntimeException e) {
throw new RuntimeException("Pre-raster compute compilation failed for " + name, e);
}
final ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureIds, flippedAtLeastOnceSnapshot);
CommonUniforms.addDynamicUniforms(builder, FogMode.OFF);
this.customUniforms.assignTo(builder);
IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> flipped, renderTargets, true, pipeline);
IrisSamplers.addCustomImages(customTextureSamplerInterceptor, customImages);
IrisSamplers.addCustomTextures(customTextureSamplerInterceptor, irisCustomTextures);
@@ -382,15 +512,10 @@ public class CompositeRenderer {
IrisImages.addShadowColorImages(builder, shadowTargetsSupplier.get(), null);
}
// TODO: Don't duplicate this with FinalPassRenderer
centerDepthSampler.setUsage(builder.addDynamicSampler(centerDepthSampler::getCenterDepthTexture, "iris_centerDepthSmooth"));
Program build = builder.build();
this.customUniforms.mapholderToPass(builder, build);
return build;
}
final ComputeProgram cp = builder.buildCompute();
this.customUniforms.mapholderToPass(builder, cp);
return cp;
}
private ComputeProgram[] createComputes(ComputeSource[] compute, ImmutableSet<Integer> flipped, ImmutableSet<Integer> flippedAtLeastOnceSnapshot, Supplier<ShadowRenderTargets> shadowTargetsSupplier) {
ComputeProgram[] programs = new ComputeProgram[compute.length];
@@ -418,18 +543,18 @@ public class CompositeRenderer {
this.customUniforms.assignTo(builder);
IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> flipped, renderTargets, true, pipeline);
IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> renderTargets.parityResolve(flipped), renderTargets, true, pipeline);
IrisSamplers.addCustomImages(customTextureSamplerInterceptor, customImages);
IrisSamplers.addCustomTextures(customTextureSamplerInterceptor, irisCustomTextures);
IrisImages.addRenderTargetImages(builder, () -> flipped, renderTargets);
IrisImages.addRenderTargetImages(builder, () -> renderTargets.parityResolve(flipped), renderTargets);
IrisImages.addCustomImages(builder, customImages);
IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, noiseTexture);
IrisSamplers.addCompositeSamplers(customTextureSamplerInterceptor, renderTargets);
samplerUsage |= IrisSamplers.addCompositeSamplers(customTextureSamplerInterceptor, renderTargets);
if (IrisSamplers.hasShadowSamplers(customTextureSamplerInterceptor)) {
IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowTargetsSupplier.get(), null, pipeline != null && pipeline.hasFeature(FeatureFlags.SEPARATE_HARDWARE_SAMPLERS));
samplerUsage |= IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowTargetsSupplier.get(), null, pipeline != null && pipeline.hasFeature(FeatureFlags.SEPARATE_HARDWARE_SAMPLERS));
IrisImages.addShadowColorImages(builder, shadowTargetsSupplier.get(), null);
}
@@ -4,6 +4,7 @@ import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
import it.unimi.dsi.fastutil.ints.IntList;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import net.coderbot.iris.features.FeatureFlags;
@@ -37,6 +38,7 @@ import net.coderbot.iris.uniforms.FrameUpdateNotifier;
import net.coderbot.iris.uniforms.custom.CustomUniforms;
import net.minecraft.client.Minecraft;
import net.minecraft.client.shader.Framebuffer;
import net.minecraft.profiler.Profiler;
import org.jetbrains.annotations.Nullable;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
@@ -52,6 +54,8 @@ import java.util.concurrent.CompletionException;
import java.util.function.Supplier;
public class FinalPassRenderer {
private static final Tracy.ZoneId Z_GEN_MIPMAP = Tracy.zoneId("genMipmap", Tracy.COLOR_IRIS);
private final RenderTargets renderTargets;
@Nullable
@@ -69,6 +73,11 @@ public class FinalPassRenderer {
@Nullable private final Set<GlImage> customImages;
@Nullable private final Object2ObjectMap<String, TextureAccess> irisCustomTextures;
@Nullable private final WorldRenderingPipeline pipeline;
private int samplerUsage;
public int getSamplerUsage() {
return samplerUsage;
}
public FinalPassRenderer(ProgramSet pack, RenderTargets renderTargets, TextureAccess noiseTexture,
FrameUpdateNotifier updateNotifier, ImmutableSet<Integer> flippedBuffers,
@@ -104,6 +113,10 @@ public class FinalPassRenderer {
return pass;
}).orElse(null);
if (Tracy.ENABLED && finalPass != null) {
Tracy.message("passGraph final/" + stageName + " mipmapped=" + finalPass.mipmappedBuffers + " readsAlt=" + finalPass.stageReadsFromAlt);
}
final IntList buffersToBeCleared = pack.getPackDirectives().getRenderTargetDirectives().getBuffersToBeCleared();
// The name of this method might seem a bit odd here, but we want a framebuffer with color attachments that line
@@ -117,30 +130,29 @@ public class FinalPassRenderer {
this.lastColorTextureVersion = ((IRenderTargetExt)main).iris$getColorBufferVersion();
this.colorHolder.addColorAttachment(0, lastColorTextureId);
// TODO: We don't actually fully swap the content, we merely copy it from alt to main
// This works for the most part, but it's not perfect. A better approach would be creating secondary
// framebuffers for every other frame, but that would be a lot more complex...
final ImmutableList.Builder<SwapPass> swapPasses = ImmutableList.builder();
final boolean parityFlip = renderTargets.getParityState() != null && renderTargets.getParityState().isEnabled();
flippedBuffers.forEach((i) -> {
final int target = i;
if (!parityFlip) {
flippedBuffers.forEach((i) -> {
final int target = i;
if (buffersToBeCleared.contains(target)) {
return;
}
if (buffersToBeCleared.contains(target)) {
return;
}
final SwapPass swap = new SwapPass();
final RenderTarget target1 = renderTargets.get(target);
swap.target = target;
swap.width = target1.getWidth();
swap.height = target1.getHeight();
// Non-flipped buffers write to ALT, copy ALT→MAIN to preserve data
swap.from = renderTargets.createColorFramebuffer(ImmutableSet.of(), new int[] {target});
swap.targetTexture = renderTargets.get(target).getMainTexture();
final SwapPass swap = new SwapPass();
final RenderTarget target1 = renderTargets.get(target);
swap.target = target;
swap.width = target1.getWidth();
swap.height = target1.getHeight();
// Non-flipped buffers write to ALT, copy ALT→MAIN to preserve data
swap.from = renderTargets.createColorFramebuffer(ImmutableSet.of(), new int[] {target});
swap.targetTexture = renderTargets.get(target).getMainTexture();
swapPasses.add(swap);
});
swapPasses.add(swap);
});
}
this.swapPasses = swapPasses.build();
@@ -215,6 +227,8 @@ public class FinalPassRenderer {
colorHolder.addColorAttachment(0, lastColorTextureId);
}
final Profiler profiler = Minecraft.getMinecraft().mcProfiler;
profiler.startSection("iris_final_program");
if (this.finalPass != null) {
// If there is a final pass, we use the shader-based full screen quad rendering pathway instead of just copying the color buffer.
@@ -222,8 +236,10 @@ public class FinalPassRenderer {
FullScreenQuadRenderer.INSTANCE.begin();
boolean ranCompute = false;
for (ComputeProgram computeProgram : finalPass.computes) {
if (computeProgram != null) {
ranCompute = true;
computeProgram.use();
this.customUniforms.push(computeProgram);
computeProgram.dispatch(baseWidth, baseHeight);
@@ -232,11 +248,18 @@ public class FinalPassRenderer {
RenderSystem.memoryBarrier(GL42.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL42.GL_TEXTURE_FETCH_BARRIER_BIT | GL43.GL_SHADER_STORAGE_BARRIER_BIT);
if (ranCompute) {
for (int i = 0; i < renderTargets.getRenderTargetCount(); i++) {
renderTargets.get(i).markBothDirty();
}
}
if (!finalPass.mipmappedBuffers.isEmpty()) {
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
final ImmutableSet<Integer> readsFromAlt = renderTargets.parityResolve(finalPass.stageReadsFromAlt);
for (int index : finalPass.mipmappedBuffers) {
setupMipmapping(renderTargets.get(index), finalPass.stageReadsFromAlt.contains(index));
setupMipmapping(renderTargets.get(index), readsFromAlt.contains(index));
}
}
@@ -263,6 +286,7 @@ public class FinalPassRenderer {
RenderSystem.copyTexSubImage2D(main.framebufferTexture, GL11.GL_TEXTURE_2D, 0, 0, 0, 0, 0, baseWidth, baseHeight);
}
profiler.endSection();
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
@@ -271,6 +295,8 @@ public class FinalPassRenderer {
resetRenderTarget(renderTargets.get(i));
}
profiler.startSection("iris_final_swaps");
if (Tracy.ENABLED) Tracy.zoneValue(swapPasses.size());
for (SwapPass swapPass : swapPasses) {
// NB: We need to use bind(), not bindAsReadBuffer()... Previously we used bindAsReadBuffer() here which
// broke TAA on many packs and on many drivers.
@@ -285,6 +311,7 @@ public class FinalPassRenderer {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, swapPass.targetTexture);
GLStateManager.glCopyTexSubImage2D(GL11.GL_TEXTURE_2D, 0, 0, 0, 0, 0, swapPass.width, swapPass.height);
}
profiler.endSection();
// Make sure to reset the viewport to how it was before... Otherwise weird issues could occur.
// Also bind the "main" framebuffer if it isn't already bound.
@@ -293,7 +320,8 @@ public class FinalPassRenderer {
ProgramSamplers.clearActiveSamplers();
GLStateManager.glUseProgram(0);
for (int i = 0; i < SamplerLimits.get().getMaxTextureUnits(); i++) {
final int maxUnit = Math.min(SamplerLimits.get().getMaxTextureUnits() - 1, GLStateManager.getMaxBoundTextureUnit());
for (int i = 0; i <= maxUnit; i++) {
// Unbind all textures that we may have used.
// NB: This is necessary for shader pack reloading to work properly
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + i);
@@ -319,18 +347,18 @@ public class FinalPassRenderer {
private static void setupMipmapping(RenderTarget target, boolean readFromAlt) {
final int texture = readFromAlt ? target.getAltTexture() : target.getMainTexture();
// TODO: Only generate the mipmap if a valid mipmap hasn't been generated or if we've written to the buffer
// (since the last mipmap was generated)
//
// NB: We leave mipmapping enabled even if the buffer is written to again, this appears to match the
// behavior of ShadersMod/OptiFine, however I'm not sure if it's desired behavior. It's possible that a
// program could use mipmapped sampling with a stale mipmap, which probably isn't great. However, the
// sampling mode is always reset between frames, so this only persists after the first program to use
// mipmapping on this buffer.
//
// Also note that this only applies to one of the two buffers in a render target buffer pair - making it
// unlikely that this issue occurs in practice with most shader packs.
RenderSystem.generateMipmaps(texture, GL11.GL_TEXTURE_2D);
if (target.isDirty(readFromAlt)) {
if (Tracy.ENABLED) {
Tracy.beginZone(Z_GEN_MIPMAP);
Tracy.zoneValue(texture);
}
try {
RenderSystem.generateMipmaps(texture, GL11.GL_TEXTURE_2D);
} finally {
if (Tracy.ENABLED) Tracy.endZone();
}
target.clearDirty(readFromAlt);
}
int filter = GL11.GL_LINEAR_MIPMAP_LINEAR;
if (target.getInternalFormat().getPixelFormat().isInteger()) {
@@ -381,21 +409,21 @@ public class FinalPassRenderer {
final ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureIds, flippedAtLeastOnceSnapshot);
CommonUniforms.addDynamicUniforms(builder, FogMode.OFF);
IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> flipped, renderTargets, true, pipeline);
IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> renderTargets.parityResolve(flipped), renderTargets, true, pipeline);
// Bind custom images as samplers BEFORE render target images
IrisSamplers.addCustomImages(customTextureSamplerInterceptor, customImages);
// Bind custom textures (PNG files from shader pack)
IrisSamplers.addCustomTextures(customTextureSamplerInterceptor, irisCustomTextures);
IrisImages.addRenderTargetImages(builder, () -> flipped, renderTargets);
IrisImages.addRenderTargetImages(builder, () -> renderTargets.parityResolve(flipped), renderTargets);
// Bind custom images as image units AFTER render target images
IrisImages.addCustomImages(builder, customImages);
IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, noiseTexture);
IrisSamplers.addCompositeSamplers(customTextureSamplerInterceptor, renderTargets);
samplerUsage |= IrisSamplers.addCompositeSamplers(customTextureSamplerInterceptor, renderTargets);
if (IrisSamplers.hasShadowSamplers(customTextureSamplerInterceptor)) {
IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowTargetsSupplier.get(), null, pipeline != null && pipeline.hasFeature(FeatureFlags.SEPARATE_HARDWARE_SAMPLERS));
samplerUsage |= IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowTargetsSupplier.get(), null, pipeline != null && pipeline.hasFeature(FeatureFlags.SEPARATE_HARDWARE_SAMPLERS));
IrisImages.addShadowColorImages(builder, shadowTargetsSupplier.get(), null);
}
@@ -434,18 +462,18 @@ public class FinalPassRenderer {
customUniforms.assignTo(builder);
CommonUniforms.addDynamicUniforms(builder, FogMode.OFF);
IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> flipped, renderTargets, true, pipeline);
IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> renderTargets.parityResolve(flipped), renderTargets, true, pipeline);
IrisSamplers.addCustomImages(customTextureSamplerInterceptor, customImages);
IrisSamplers.addCustomTextures(customTextureSamplerInterceptor, irisCustomTextures);
IrisImages.addRenderTargetImages(builder, () -> flipped, renderTargets);
IrisImages.addRenderTargetImages(builder, () -> renderTargets.parityResolve(flipped), renderTargets);
IrisImages.addCustomImages(builder, customImages);
IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, noiseTexture);
IrisSamplers.addCompositeSamplers(customTextureSamplerInterceptor, renderTargets);
samplerUsage |= IrisSamplers.addCompositeSamplers(customTextureSamplerInterceptor, renderTargets);
if (IrisSamplers.hasShadowSamplers(customTextureSamplerInterceptor)) {
IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowTargetsSupplier.get(), null, pipeline != null && pipeline.hasFeature(FeatureFlags.SEPARATE_HARDWARE_SAMPLERS));
samplerUsage |= IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowTargetsSupplier.get(), null, pipeline != null && pipeline.hasFeature(FeatureFlags.SEPARATE_HARDWARE_SAMPLERS));
IrisImages.addShadowColorImages(builder, shadowTargetsSupplier.get(), null);
}
@@ -3,7 +3,7 @@ package net.coderbot.iris.rendertarget;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import net.coderbot.iris.gl.GlResource;
import net.coderbot.iris.gl.texture.DepthBufferFormat;
import com.gtnewhorizons.angelica.glsm.texture.DepthBufferFormat;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
@@ -3,6 +3,7 @@ package net.coderbot.iris.rendertarget;
import com.gtnewhorizons.angelica.compat.mojang.NativeImage;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import net.coderbot.iris.shaderpack.texture.CustomTextureData;
import net.coderbot.iris.shaderpack.texture.TextureFilteringData;
import net.minecraft.client.renderer.texture.DynamicTexture;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
@@ -12,23 +13,27 @@ import java.nio.ByteBuffer;
public class NativeImageBackedCustomTexture extends DynamicTexture {
public NativeImageBackedCustomTexture(CustomTextureData.PngData textureData) throws IOException {
super(create(textureData.getContent()));
this(decode(textureData.getContent()), textureData.getFilteringData());
}
public NativeImageBackedCustomTexture(NativeImage image, TextureFilteringData filtering) {
super(image);
// By default, images are unblurred and not clamped.
if (textureData.getFilteringData().shouldBlur()) {
if (filtering.shouldBlur()) {
RenderSystem.texParameteri(getGlTextureId(), GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
RenderSystem.texParameteri(getGlTextureId(), GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
}
if (textureData.getFilteringData().shouldClamp()) {
if (filtering.shouldClamp()) {
RenderSystem.texParameteri(getGlTextureId(), GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
RenderSystem.texParameteri(getGlTextureId(), GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);
}
}
private static NativeImage create(byte[] content) throws IOException {
ByteBuffer buffer = ByteBuffer.allocateDirect(content.length);
public static NativeImage decode(byte[] content) throws IOException {
final ByteBuffer buffer = ByteBuffer.allocateDirect(content.length);
buffer.put(content);
buffer.flip();
@@ -0,0 +1,99 @@
package net.coderbot.iris.rendertarget;
import com.google.common.collect.ImmutableSet;
import it.unimi.dsi.fastutil.ints.IntList;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
public final class ParityFlipState {
private boolean enabled;
private boolean finalized;
private boolean odd;
private ImmutableSet<Integer> parityBuffers = ImmutableSet.of();
private final Map<ImmutableSet<Integer>, ImmutableSet<Integer>> oddSets = new HashMap<>();
private final Function<ImmutableSet<Integer>, ImmutableSet<Integer>> xorParityFn = this::xorParity;
public ParityFlipState(boolean enabled) {
this.enabled = enabled;
}
public boolean isEnabled() {
return enabled;
}
public boolean isFinalized() {
return finalized;
}
public boolean isOdd() {
return odd;
}
public ImmutableSet<Integer> parityBuffers() {
return parityBuffers;
}
public void finalizeParitySet(ImmutableSet<Integer> finalFlipped, IntList buffersToBeCleared) {
finalized = true;
if (!enabled) {
return;
}
final ImmutableSet.Builder<Integer> builder = ImmutableSet.builder();
for (int buffer : finalFlipped) {
if (!buffersToBeCleared.contains(buffer)) {
builder.add(buffer);
}
}
parityBuffers = builder.build();
if (parityBuffers.isEmpty()) {
enabled = false;
}
}
public void onFrameStart() {
if (enabled && finalized) {
odd = !odd;
}
}
public void reset() {
odd = false;
}
public ImmutableSet<Integer> resolve(ImmutableSet<Integer> even) {
if (!odd) {
return even;
}
return oddSets.computeIfAbsent(even, xorParityFn);
}
private ImmutableSet<Integer> xorParity(ImmutableSet<Integer> even) {
final ImmutableSet.Builder<Integer> builder = ImmutableSet.builder();
for (int buffer : even) {
if (!parityBuffers.contains(buffer)) {
builder.add(buffer);
}
}
for (int buffer : parityBuffers) {
if (!even.contains(buffer)) {
builder.add(buffer);
}
}
return builder.build();
}
public boolean affectsAny(int[] drawBuffers) {
if (!enabled) {
return false;
}
for (int buffer : drawBuffers) {
if (parityBuffers.contains(buffer)) {
return true;
}
}
return false;
}
}
@@ -6,9 +6,9 @@ import com.gtnewhorizon.gtnhlib.bytebuf.MemoryStack;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import lombok.Getter;
import net.coderbot.iris.gl.texture.InternalTextureFormat;
import net.coderbot.iris.gl.texture.PixelFormat;
import net.coderbot.iris.gl.texture.PixelType;
import com.gtnewhorizons.angelica.glsm.texture.InternalTextureFormat;
import com.gtnewhorizons.angelica.glsm.texture.PixelFormat;
import com.gtnewhorizons.angelica.glsm.texture.PixelType;
import org.joml.Vector2i;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
@@ -30,6 +30,8 @@ public class RenderTarget {
private boolean isValid;
private final int mainTexture;
private final int altTexture;
private boolean mainDirty = true;
private boolean altDirty = true;
private static final ByteBuffer NULL_BUFFER = null;
@@ -87,6 +89,26 @@ public class RenderTarget {
resizeTexture(mainTexture, width, height);
resizeTexture(altTexture, width, height);
mainDirty = true;
altDirty = true;
}
public void markDirty(boolean isAlt) {
if (isAlt) altDirty = true; else mainDirty = true;
}
public void markBothDirty() {
mainDirty = true;
altDirty = true;
}
public boolean isDirty(boolean isAlt) {
return isAlt ? altDirty : mainDirty;
}
public void clearDirty(boolean isAlt) {
if (isAlt) altDirty = false; else mainDirty = false;
}
public int getMainTexture() {
Loaded 100 of 647 files, more files were not shown because too many files have changed in this diff. Show more