Depth peel translucent block entity batches and flush them before blended immediate draws

This commit is contained in:
Ruling-0 committed 2026-11-08 13:09:00 -06:00
1 parent 3c6b7e0fe9
commit 6a6b1d14e9
12 files changed
+796 -48

No files matched your search

@@ -66,6 +66,7 @@ import com.gtnewhorizons.angelica.render.WeatherRenderer;
import com.gtnewhorizons.angelica.rendering.culling.GpuTerrainCuller;
import com.gtnewhorizons.angelica.rendering.tesr.AngelicaTesrMeshCache;
import com.gtnewhorizons.angelica.rendering.tesr.GlowReplayExclusions;
import com.gtnewhorizons.angelica.rendering.tesr.ImmediateDrawOrder;
import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher;
import com.gtnewhorizons.angelica.rendering.tesr.PendingTesrDraws;
import com.gtnewhorizons.angelica.rendering.tesr.SectionBuiltBlockEntity;
@@ -75,6 +76,7 @@ import com.gtnewhorizons.angelica.rendering.tesr.TesrAttribution;
import com.gtnewhorizons.angelica.rendering.tesr.TesrBatchRenderer;
import com.gtnewhorizons.angelica.rendering.tesr.TesrLifecycle;
import com.gtnewhorizons.angelica.rendering.tesr.TesrProviderDispatch;
import com.gtnewhorizons.angelica.rendering.tesr.TranslucentPeel;
import com.gtnewhorizons.angelica.rendering.translucency.TranslucencyLayers;
import com.gtnewhorizons.angelica.rendering.translucency.TranslucentLayer;
import net.coderbot.iris.Iris;
@@ -555,6 +557,8 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
TileEntityRendererDispatcher.staticPlayerZ);
ModelPartBatcher.INSTANCE.begin(ModelPartBatcher.Mode.BLOCK_ENTITIES);
PendingTesrDraws.beginPass();
ImmediateDrawOrder.beginPass();
TranslucentPeel.beginPass();
int count = 0;
if (pass == 0) {
teRenderContext.set(partialTicks, pass);
@@ -611,7 +615,9 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
if (Tracy.ENABLED) Tracy.endZone();
}
}
ImmediateDrawOrder.endPass();
PendingTesrDraws.endPass();
TranslucentPeel.flush();
if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_MODEL_PARTS);
try {
ModelPartBatcher.INSTANCE.flush();
@@ -750,6 +756,7 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
}
}
PendingTesrDraws.beforeTileEntity(tileEntity);
TranslucentPeel.beforeBlockEntity();
try {
final long start = Tracy.ENABLED ? System.nanoTime() : 0L;
final boolean attribute = Tracy.ENABLED && TesrAttribution.currentRenderable == null;
@@ -31,6 +31,7 @@ final class BatchStateFallback {
final long before = GLSMDraws.drawCalls;
try {
GLSMMatrices.glMatrixMode(GL11.GL_MODELVIEW);
if (models.hasQueuedGeometry() || tesrs.hasQueuedGeometry()) TranslucentPeel.flush();
models.flushForStateChange();
tesrs.flushForStateChange();
} finally {
@@ -0,0 +1,49 @@
package com.gtnewhorizons.angelica.rendering.tesr;
import com.gtnewhorizons.angelica.glsm.GLSMBlend;
import com.gtnewhorizons.angelica.glsm.GLSMMatrices;
import com.gtnewhorizons.angelica.glsm.GLSMTextures;
import com.gtnewhorizons.angelica.glsm.hooks.BatchStateGuard;
import com.gtnewhorizons.angelica.proxy.ClientProxy;
import net.minecraft.client.renderer.Tessellator;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
/// Draws what the batchers have queued before a blended `glBegin`, display list, Tessellator or unbatched template draw
/// of a block entity, which would otherwise land under batched geometry dispatched before it. Vertex array and buffer
/// draws are not hooked.
public final class ImmediateDrawOrder {
private static final Runnable FLUSH = ImmediateDrawOrder::flush;
private ImmediateDrawOrder() {}
public static void beginPass() {
if (!ClientProxy.options().performance.translucencyMode.sorts() || TesrBatchRenderer.deferredPipeline() != null) return;
BatchStateGuard.drawFlush = FLUSH;
}
public static void endPass() {
BatchStateGuard.drawFlush = null;
}
static void flush() {
if (!GLSMBlend.getBlendMode().isEnabled()) return;
// A Tessellator draw triggers this from inside Tessellator.draw, and pending draws use the Tessellator
if (!Tessellator.instance.isDrawing) PendingTesrDraws.flush();
final ModelPartBatcher models = ModelPartBatcher.INSTANCE;
final TesrBatchRenderer tesrs = TesrBatchRenderer.INSTANCE;
if (!models.hasQueuedGeometry() && !tesrs.hasQueuedGeometry()) return;
final int mode = GLSMMatrices.getMatrixMode().getMode();
final int unit = GLSMTextures.getActiveTextureUnit();
try {
GLSMMatrices.glMatrixMode(GL11.GL_MODELVIEW);
TranslucentPeel.flush();
models.flushForStateChange();
tesrs.flushAndContinue();
} finally {
GLSMMatrices.glMatrixMode(mode);
GLSMTextures.glActiveTexture(GL13.GL_TEXTURE0 + unit);
}
}
}
@@ -144,6 +144,14 @@ final class InstancedTemplateRenderer {
* Draws a base run's recorded template upload again, every instance in one color.
*/
int redrawTemplates(TexRun base, int colorABGR) {
return redrawTemplates(base, true, colorABGR);
}
int replayTemplates(TexRun run) {
return redrawTemplates(run, false, 0);
}
private int redrawTemplates(TexRun base, boolean constantColor, int colorABGR) {
long recordOffset = base.uploadOffset;
neutralizeExtendedAttribs();
GLSMPrograms.setFfpInstancing(Instancing.TEMPLATE);
@@ -153,9 +161,9 @@ final class InstancedTemplateRenderer {
bindRingTo(mesh.vao, TEMPLATE_FLAGS);
InstancedAttribs.pointTemplate(recordOffset);
GLSMBuffers.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
setConstantColor(colorABGR);
if (constantColor) setConstantColor(colorABGR);
GLSMDraws.glDrawArraysInstanced(mesh.drawMode, 0, mesh.vertexCount, count);
GLSMVertexInput.glEnableVertexAttribArray(InstancedAttribs.LOC_COLOR);
if (constantColor) GLSMVertexInput.glEnableVertexAttribArray(InstancedAttribs.LOC_COLOR);
recordOffset += (long) count * InstancedAttribs.STRIDE;
}
GLSMPrograms.setFfpInstancing(Instancing.NONE);
@@ -220,15 +228,23 @@ final class InstancedTemplateRenderer {
}
void redrawCubes(long offset, int instances, int colorABGR) {
redrawCubes(offset, instances, true, colorABGR);
}
void replayCubes(long offset, int instances) {
redrawCubes(offset, instances, false, 0);
}
private void redrawCubes(long offset, int instances, boolean constantColor, int colorABGR) {
neutralizeExtendedAttribs();
bindRingTo(UnitCubeMesh.vao(), UnitCubeMesh.VERTEX_FLAGS);
CubeInstancedAttribs.pointInstanceAttribs(offset);
GLSMBuffers.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
setConstantColor(colorABGR);
if (constantColor) setConstantColor(colorABGR);
GLSMPrograms.setFfpInstancing(Instancing.CUBE);
GLSMDraws.glDrawArraysInstanced(GL11.GL_QUADS, 0, UnitCubeMesh.VERTEX_COUNT, instances);
GLSMPrograms.setFfpInstancing(Instancing.NONE);
GLSMVertexInput.glEnableVertexAttribArray(InstancedAttribs.LOC_COLOR);
if (constantColor) GLSMVertexInput.glEnableVertexAttribArray(InstancedAttribs.LOC_COLOR);
GLSMVertexInput.glBindVertexArray(0);
}
@@ -329,13 +329,39 @@ public final class ModelPartBatcher {
}
}
void queueShadows() {
if (active && mode == Mode.BLOCK_ENTITIES && !shadow) shadows.flush(activeSource);
}
void drawOpaque() {
if (active && mode == Mode.BLOCK_ENTITIES && !shadow) activeSource.endBatchWithType(TransparencyType.OPAQUE, activeGroups);
}
boolean beginPeel() {
if (!active || mode != Mode.BLOCK_ENTITIES || shadow) return false;
if (!activeSource.hasPendingLayers()) return false;
activeSource.openDrawState();
return true;
}
void drawPeeled(boolean replay) {
activeGroups.setPeelReplay(!replay, replay);
activeSource.drawPending(activeGroups);
}
void endPeel() {
if (!active || mode != Mode.BLOCK_ENTITIES || shadow) return;
activeGroups.setPeelReplay(false, false);
activeSource.discard();
}
void flushForStateChange() {
if (!active) return;
flushNow(false);
active = true;
mvCaptured = false;
texCaptured = false;
activeGroups.beginPass(identity, 0, 0, 0, instancedThisCycle ? TesrBatchRenderer.INSTANCE.instancedRenderer : null, shaderPipeline);
activeGroups.continuePass(identity, 0, 0, 0, instancedThisCycle ? TesrBatchRenderer.INSTANCE.instancedRenderer : null, shaderPipeline);
}
private void flushNow(boolean allowHold) {
@@ -860,6 +886,7 @@ public final class ModelPartBatcher {
return result;
}
case DRAW_NOW_EXPECTED -> {
BatchStateGuard.beforeDraw();
BatchEligibility.beginExpectedDraws(GLSMDraws.drawCalls);
try {
return TessellatorStreamingDrawer.draw(tess);
@@ -868,6 +895,7 @@ public final class ModelPartBatcher {
}
}
default -> {
BatchStateGuard.beforeDraw();
return TessellatorStreamingDrawer.draw(tess);
}
}
@@ -66,6 +66,13 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
private final TemplateBuffer[] budgetSeen = new TemplateBuffer[PROMOTE_MAX_TEMPLATES];
private double camX, camY, camZ;
private long frameMark;
/// `frameMark` advances per segment, so limits measured in frames count passes here.
private long passMark;
private int segment;
private boolean peelRecording;
private boolean peelReplaying;
private final ObjectArrayList<Group> deferredPromotions = new ObjectArrayList<>();
private final ObjectArrayList<DepthEqualSet> deferredSwitches = new ObjectArrayList<>();
GlintCapture glintCapture;
long rebakes;
@@ -437,6 +444,11 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
}
}
private static final class SegmentGroups {
final ObjectArrayList<Group> groups = new ObjectArrayList<>();
long frameMark = -1;
}
static final class Group {
final RenderLayer layer;
final TesrMaterial material;
@@ -451,6 +463,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
final Anchor anchor = new Anchor();
boolean anchored;
long frameMark = -1;
long passMark = -1;
long lastUsedMs;
final int entityColor;
final int itemId;
@@ -623,6 +636,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
private final Reference2ObjectOpenHashMap<RenderLayer, Reference2ObjectOpenHashMap<TesrMaterial, Object2ObjectOpenHashMap<DrawStateKey, Group>>> groups = new Reference2ObjectOpenHashMap<>();
private final Reference2ObjectOpenHashMap<RenderLayer, ObjectArrayList<Group>> byLayer = new Reference2ObjectOpenHashMap<>();
private final Reference2ObjectOpenHashMap<RenderLayer, SegmentGroups> segmentGroups = new Reference2ObjectOpenHashMap<>();
private long openScope;
private DepthEqualSet openDepthEqualSet;
private final ObjectArrayList<Group> openWriters = new ObjectArrayList<>();
@@ -648,6 +662,18 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
}
void beginPass(Matrix4f base, double camX, double camY, double camZ, InstancedTemplateRenderer instancedRenderer, TesrInstancingPipeline deferred) {
startSegment(base, camX, camY, camZ, instancedRenderer, deferred);
passMark++;
segment = 0;
}
void continuePass(Matrix4f base, double camX, double camY, double camZ, InstancedTemplateRenderer instancedRenderer, TesrInstancingPipeline deferred) {
startSegment(base, camX, camY, camZ, instancedRenderer, deferred);
// Baked groups are keyed by segment, so a group split by a flush keeps one mesh per side instead of rebaking
segment++;
}
private void startSegment(Matrix4f base, double camX, double camY, double camZ, InstancedTemplateRenderer instancedRenderer, TesrInstancingPipeline deferred) {
if (glintCapture != null) glintCapture.invalidate();
glintCapture = null;
baseMV.set(base);
@@ -670,27 +696,28 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
/** Mutable lookup avoids allocating a key for each queued model part. Stored keys are never mutated. */
private static final class DrawStateKey {
int entity, block, item, color;
int entity, block, item, color, segment;
DrawStateKey set(int entity, int block, int item, int color) {
DrawStateKey set(int entity, int block, int item, int color, int segment) {
this.entity = entity;
this.block = block;
this.item = item;
this.color = color;
this.segment = segment;
return this;
}
boolean matches(int entity, int block, int item, int color) {
return this.entity == entity && this.block == block && this.item == item && this.color == color;
boolean matches(int entity, int block, int item, int color, int segment) {
return this.entity == entity && this.block == block && this.item == item && this.color == color && this.segment == segment;
}
@Override
public boolean equals(Object other) {
return other instanceof DrawStateKey key && matches(key.entity, key.block, key.item, key.color);
return other instanceof DrawStateKey key && matches(key.entity, key.block, key.item, key.color, key.segment);
}
@Override
public int hashCode() { return ((entity * 31 + block) * 31 + item) * 31 + color; }
public int hashCode() { return (((entity * 31 + block) * 31 + item) * 31 + color) * 31 + segment; }
}
private final DrawStateKey lookupState = new DrawStateKey();
@@ -729,7 +756,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
}
group = byState.get(lookupState);
if (group == null) {
final DrawStateKey key = new DrawStateKey().set(lookupState.entity, lookupState.block, lookupState.item, lookupState.color);
final DrawStateKey key = new DrawStateKey().set(lookupState.entity, lookupState.block, lookupState.item, lookupState.color, lookupState.segment);
group = new Group(layer, material, perInstance ? 0 : id, key);
group.lastUsedMs = nowMs;
byState.put(key, group);
@@ -746,13 +773,13 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
private void keyLookup(boolean perInstance, int id) {
if (perInstance) {
lookupState.set(0, 0, 0, 0);
lookupState.set(0, 0, 0, 0, 0);
return;
}
final CapturedRenderingState captured = CapturedRenderingState.INSTANCE;
final boolean entityKind = source.effectiveIdKind() == AngelicaBufferSource.GroupIdKind.ENTITY;
lookupState.set(entityKind ? id : captured.getCurrentRenderedEntity(), entityKind ? captured.getCurrentRenderedBlockEntity() : id,
captured.getCurrentRenderedItem(), AngelicaBufferSource.packEntityColor(captured.getCurrentEntityColor()));
captured.getCurrentRenderedItem(), AngelicaBufferSource.packEntityColor(captured.getCurrentEntityColor()), segment);
}
void forceStreaming(RenderLayer layer, TesrMaterial material, int blockEntityId) {
@@ -866,6 +893,8 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
resetPromotion(group);
}
}
// touch recorded this geometry as stream segments, but it draws with the baked columns
TranslucentPeel.queued(layer, this, group);
}
toAnchorRelative(group, currentMV);
final Matrix4f bakedTexMatrix = atlasSlot != null ? atlasSlot.uvMatrix : texMatrix;
@@ -991,7 +1020,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
adoptAnchor(group, set);
} else if (set.anchorFrame < 0) {
set.anchor.set(group.anchor);
set.anchorFrame = frameMark;
set.anchorFrame = passMark;
for (int i = 0, n = set.members.size(); i < n; i++) {
final Group member = set.members.get(i);
if (member.frameMark == frameMark && !member.queuedThisFrame) adoptAnchor(member, set);
@@ -1023,13 +1052,13 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
}
private void refresh(DepthEqualSet set) {
if (set.checkedFrame == frameMark) return;
set.checkedFrame = frameMark;
if (set.anchorFrame != frameMark && set.anchor.stale(camX, camY, camZ)) set.anchor.moveTo(camX, camY, camZ);
set.anchorFrame = frameMark;
if (set.checkedFrame == passMark) return;
set.checkedFrame = passMark;
if (set.anchorFrame != passMark && set.anchor.stale(camX, camY, camZ)) set.anchor.moveTo(camX, camY, camZ);
set.anchorFrame = passMark;
if ((set.streamMembers > 0 || set.instanced) && set.instanced != allCanInstance(set)) {
set.instanced = !set.instanced;
set.effectiveFrame = frameMark - 1;
set.effectiveFrame = passMark - 1;
}
}
@@ -1152,7 +1181,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
if (group.frameMark != frameMark) {
final DepthEqualSet set = activeDepthEqualSet(group);
if (set != null) refresh(set);
if (frameMark - group.frameMark > IDLE_RESET_FRAMES) {
if (passMark - group.passMark > IDLE_RESET_FRAMES) {
resetPromotion(group);
} else if (promoted(group)) {
final boolean pinned = set != null && set.streamMembers > 0;
@@ -1171,12 +1200,14 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
}
}
if (set != null) {
if (frameMark > set.effectiveFrame) adopt(group, set.instanced);
if (passMark > set.effectiveFrame) adopt(group, set.instanced);
} else if (group.stream && !group.streamPath) {
resetPromotion(group);
}
group.queuedThisFrame = false;
group.frameMark = frameMark;
group.passMark = passMark;
addToSegment(group);
group.lastUsedMs = nowMs;
group.dirty = false;
group.clearInstances();
@@ -1189,12 +1220,37 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
}
source.declareUse(layer);
}
if (drawsInstanced(group)) {
TranslucentPeel.queuedUnordered(layer);
} else if (group.streamPath) {
TranslucentPeel.queued(layer, source, layer);
} else {
TranslucentPeel.queued(layer, this, group);
}
}
private void addToSegment(Group group) {
SegmentGroups entry = segmentGroups.get(group.layer);
if (entry == null) {
entry = new SegmentGroups();
segmentGroups.put(group.layer, entry);
}
if (entry.frameMark != frameMark) {
entry.groups.clear();
entry.frameMark = frameMark;
}
entry.groups.add(group);
}
private ObjectArrayList<Group> segmentGroups(RenderLayer layer) {
final SegmentGroups entry = segmentGroups.get(layer);
return entry != null && entry.frameMark == frameMark ? entry.groups : null;
}
private void switchSetNextFrame(DepthEqualSet set, boolean instanced) {
if (set.instanced == instanced) return;
set.instanced = instanced;
set.effectiveFrame = frameMark;
set.effectiveFrame = passMark;
}
private static DepthEqualSet activeDepthEqualSet(Group group) {
@@ -1205,7 +1261,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
private boolean allStable(DepthEqualSet set) {
for (int i = 0, n = set.members.size(); i < n; i++) {
final Group member = set.members.get(i);
if (member.streamPath && frameMark - member.frameMark <= IDLE_RESET_FRAMES && (member.probe == null || member.probe.stableProbes < DEMOTE_AFTER_STABLE_PROBES)) return false;
if (member.streamPath && passMark - member.passMark <= IDLE_RESET_FRAMES && (member.probe == null || member.probe.stableProbes < DEMOTE_AFTER_STABLE_PROBES)) return false;
}
return true;
}
@@ -1230,7 +1286,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
@Override
public boolean hasDraws(RenderLayer layer) {
final ObjectArrayList<Group> list = byLayer.get(layer);
final ObjectArrayList<Group> list = segmentGroups(layer);
if (list == null) return false;
for (int i = 0, n = list.size(); i < n; i++) {
if (live(list.get(i))) return true;
@@ -1241,7 +1297,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
@Override
public void drawLayer(RenderLayer layer) {
if (glintCapture != null) glintCapture.invalidate();
final ObjectArrayList<Group> list = byLayer.get(layer);
final ObjectArrayList<Group> list = segmentGroups(layer);
if (list == null) return;
boolean matrixAvailable = true;
boolean cubeAvailable = true;
@@ -1374,6 +1430,10 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
}
private void drawRetained(Group group) {
if (peelReplaying) {
draw(group);
return;
}
final InstanceColumns cols = group.templateColumns;
final Snapshot snapshot = group.snapshot;
boolean instanceChanged = false;
@@ -1394,9 +1454,13 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
if (instanceChanged && !group.stream && !group.streamPath && rebakesTooOften(group) && withinTemplateBudget(cols.templates)) {
final DepthEqualSet set = activeDepthEqualSet(group);
if (set != null) {
if (set.streamMembers == 0 && allCanInstance(set)) switchSetNextFrame(set, true);
if (set.streamMembers == 0 && allCanInstance(set)) {
if (peelRecording) deferredSwitches.add(set);
else switchSetNextFrame(set, true);
}
} else if (canInstance(group) || group.opaque && templatesMatchLayerDrawMode(group)) {
promote(group);
if (peelRecording) deferredPromotions.add(group);
else promote(group);
}
}
}
@@ -1439,6 +1503,21 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
return ++group.promoteWindowRebakes >= PROMOTE_AFTER_REBAKES;
}
void setPeelReplay(boolean recording, boolean replaying) {
peelRecording = recording;
peelReplaying = replaying;
// Promoting deletes the mesh the peel replays draw, so promotions wait until the peel ends
if (recording || replaying) return;
for (int i = 0, n = deferredPromotions.size(); i < n; i++) promote(deferredPromotions.get(i));
for (int i = 0, n = deferredSwitches.size(); i < n; i++) switchSetNextFrame(deferredSwitches.get(i), true);
deferredPromotions.clear();
deferredSwitches.clear();
}
private boolean replays(TexRun run) {
return peelReplaying && run.uploadPass == frameMark && instanced.canRedraw(run.uploadRingEpoch, run.uploadBuffer);
}
private void drawTemplateRuns(InstanceColumns cols, boolean combineGlint, boolean itemStencil) {
for (int r = 0, n = cols.runs.size(); r < n; r++) {
final TexRun run = cols.runs.get(r);
@@ -1457,9 +1536,13 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
if (canRedraw(run)) {
instancedDraws += instanced.redrawTemplates(run.sourceRun, run.color);
redrawnInstances += run.parts;
} else if (replays(run)) {
instancedDraws += instanced.replayTemplates(run);
redrawnInstances += run.parts;
} else {
instancedDraws += instanced.drawTemplates(cols, run, nowMs, run.glintBase);
if (run.glintBase) recordUpload(run);
final boolean record = run.glintBase || peelRecording;
instancedDraws += instanced.drawTemplates(cols, run, nowMs, record);
if (record) recordUpload(run);
}
instancedInstances += run.parts;
} finally {
@@ -1480,9 +1563,12 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
if (canRedraw(run)) {
instanced.redrawCubes(run.sourceRun.uploadOffset, run.instances, run.color);
redrawnInstances += run.instances;
} else if (replays(run)) {
instanced.replayCubes(run.uploadOffset, run.instances);
redrawnInstances += run.instances;
} else {
run.uploadOffset = instanced.drawCubes(cols, run);
if (run.glintBase) recordUpload(run);
if (run.glintBase || peelRecording) recordUpload(run);
}
instancedDraws++;
cubeInstances += run.instances;
@@ -1638,6 +1724,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
}
}
byLayer.clear();
segmentGroups.clear();
groups.clear();
openScope = 0;
openDepthEqualSet = null;
@@ -83,6 +83,9 @@ public final class TesrBatchRenderer {
private RetainedTesrGroups pendingDeferredHook;
private final Matrix4f modelView = new Matrix4f();
private final Matrix4f passBase = new Matrix4f();
private double passCamX, passCamY, passCamZ;
private InstancedTemplateRenderer passInstanced;
private final Matrix4f identity = new Matrix4f();
private final Vector3f scratchVec = new Vector3f();
@@ -113,7 +116,12 @@ public final class TesrBatchRenderer {
bufferSource.capturePassLighting();
BatchDrawDefaults.capturePassFramebuffer();
final DeferredWorldRenderingPipeline deferred = deferredPipeline();
retained[passKey].beginPass(baseMV, camX, camY, camZ, instancedCapable() ? instancedRenderer : null, deferred);
passBase.set(baseMV);
passCamX = camX;
passCamY = camY;
passCamZ = camZ;
passInstanced = instancedCapable() ? instancedRenderer : null;
retained[passKey].beginPass(baseMV, camX, camY, camZ, passInstanced, deferred);
if (passKey == PASS_MAIN_0) {
instancedRenderer.releaseRetired();
final long now = System.currentTimeMillis();
@@ -410,6 +418,37 @@ public final class TesrBatchRenderer {
BatchingFontRenderer.flushDeferredText();
}
void drawOpaque() {
if (activePass >= 0) bufferSource.endBatchWithType(TransparencyType.OPAQUE, retained[activePass]);
}
boolean beginPeel() {
if (activePass < 0) return false;
if (!bufferSource.hasPendingLayers()) return false;
bufferSource.openDrawState();
return true;
}
void drawPeeled(boolean replay) {
retained[activePass].setPeelReplay(!replay, replay);
bufferSource.drawPending(retained[activePass]);
}
void endPeel() {
if (activePass < 0) return;
retained[activePass].setPeelReplay(false, false);
bufferSource.discard();
}
void flushAndContinue() {
if (activePass < 0) return;
final RetainedTesrGroups hook = retained[activePass];
bufferSource.endBatchWithType(TransparencyType.OPAQUE, hook);
bufferSource.endBatch(hook);
BatchingFontRenderer.flushDeferredText();
hook.continuePass(passBase, passCamX, passCamY, passCamZ, passInstanced, null);
}
private void flushNow() {
final RetainedTesrGroups hook = activePass >= 0 ? retained[activePass] : null;
if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_OPAQUE);
@@ -622,6 +661,7 @@ public final class TesrBatchRenderer {
try {
layer.startDrawing();
layerStarted = true;
BatchStateGuard.beforeDraw();
immediateMesh.upload(format, template.drawMode, immediateScratch, vertexCount);
immediateMesh.render();
} catch (Throwable t) {
@@ -10,6 +10,8 @@ public final class TesrLifecycle {
public static void reset() {
TesrBatchRenderer.INSTANCE.clearRetained();
TranslucentPeel.destroy();
ImmediateDrawOrder.endPass();
ModelPartBatcher.INSTANCE.clear();
EntityTextureAtlas.INSTANCE.clear();
DroppedItemInstancer.forgetItemDraws();
@@ -0,0 +1,363 @@
package com.gtnewhorizons.angelica.rendering.tesr;
import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
import com.gtnewhorizons.angelica.glsm.DepthPeel;
import com.gtnewhorizons.angelica.glsm.GLSMAttribStack;
import com.gtnewhorizons.angelica.glsm.GLSMDepthStencilAlpha;
import com.gtnewhorizons.angelica.glsm.GLSMFramebuffer;
import com.gtnewhorizons.angelica.glsm.GLSMQueries;
import com.gtnewhorizons.angelica.glsm.GLSMRasterizer;
import com.gtnewhorizons.angelica.glsm.GLSMTextures;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import com.gtnewhorizons.angelica.glsm.StateSet;
import com.gtnewhorizons.angelica.glsm.hooks.BatchStateGuard;
import com.gtnewhorizons.angelica.glsm.texture.DepthBufferFormat;
import com.gtnewhorizons.angelica.glsm.texture.TextureInfoCache;
import com.gtnewhorizons.angelica.proxy.ClientProxy;
import com.gtnewhorizons.angelica.rendering.translucency.TranslucencyLayers;
import me.jellysquid.mods.sodium.client.gui.options.named.TranslucencyMode;
import net.coderbot.batchedentityrendering.impl.TransparencyType;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gl.framebuffer.GlFramebuffer;
import net.coderbot.iris.rendertarget.IRenderTargetExt;
import net.minecraft.client.Minecraft;
import net.minecraft.client.shader.Framebuffer;
import net.minecraftforge.client.MinecraftForgeClient;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL14;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL30;
import org.lwjgl.opengl.GL33;
import java.nio.ByteBuffer;
import static com.gtnewhorizons.angelica.glsm.backend.BackendManager.RENDER_BACKEND;
/// Depth peels the translucent geometry the block entity batchers have queued ([DepthPeel]), since batches group it by
/// layer and material rather than by depth. A flush whose translucent geometry comes from one block entity in one
/// batch that keeps submission order is not peeled.
///
/// Each of the first [#SLOTS_PER_PASS] peeled flushes of a pass keeps its own peel count, and later ones peel
/// [#MAX_PEELS]. Occlusion queries, read back frames later without stalling, lower a count one peel at a time while
/// its last peel draws nothing and reset it when the rest pass draws.
public final class TranslucentPeel {
private static final int MAX_PEELS = 4;
private static final int SLOTS_PER_PASS = 32;
private static int width;
private static int height;
private static int depthVersion = -1;
private static DepthBufferFormat depthFormat;
private static Target[] peels;
private static Target sceneDepth;
private static StateSet clearState;
private static final Slot[] slots = new Slot[2 * SLOTS_PER_PASS];
private static int passFlushes;
private static boolean replay;
private static Object firstSource;
private static Object firstBatch;
private static int firstBlockEntity;
private static int blockEntity;
private static boolean mixed;
private TranslucentPeel() {}
static boolean enabled() {
return ClientProxy.options().performance.translucencyMode == TranslucencyMode.FANCY && Iris.enabled
&& TesrBatchRenderer.deferredPipeline() == null;
}
public static void beginPass() {
passFlushes = 0;
resetBatches();
}
public static void beforeBlockEntity() {
blockEntity++;
}
/// `source` and `batch` identify one draw: an `AngelicaBufferSource` and a layer, or [RetainedTesrGroups] and a
/// group.
public static void queued(RenderLayer layer, Object source, Object batch) {
if (mixed || layer.getTransparencyType() == TransparencyType.OPAQUE) return;
if (firstBatch == null) {
firstSource = source;
firstBatch = batch;
firstBlockEntity = blockEntity;
} else if (batch != firstBatch || source != firstSource || blockEntity != firstBlockEntity) {
mixed = true;
}
}
public static void queuedUnordered(RenderLayer layer) {
if (layer.getTransparencyType() != TransparencyType.OPAQUE) mixed = true;
}
private static void resetBatches() {
firstSource = null;
firstBatch = null;
mixed = false;
}
public static void flush() {
final ModelPartBatcher models = ModelPartBatcher.INSTANCE;
final TesrBatchRenderer tesrs = TesrBatchRenderer.INSTANCE;
BatchStateGuard.suspend();
try {
models.drawOpaque();
tesrs.drawOpaque();
} finally {
BatchStateGuard.resume();
}
if (!enabled()) {
if (peels != null) destroy();
return;
}
models.queueShadows();
final boolean peeling = mixed;
resetBatches();
if (!peeling) return;
BatchStateGuard.suspend();
try {
final boolean modelsQueued = models.beginPeel();
final boolean tesrsQueued = tesrs.beginPeel();
if (modelsQueued || tesrsQueued) peel(modelsQueued, tesrsQueued);
} finally {
try {
tesrs.endPeel();
} finally {
try {
models.endPeel();
} finally {
BatchStateGuard.resume();
}
}
}
}
private static void draw(boolean models, boolean tesrs) {
if (models) ModelPartBatcher.INSTANCE.drawPeeled(replay);
if (tesrs) TesrBatchRenderer.INSTANCE.drawPeeled(replay);
replay = true;
}
private static void peel(boolean models, boolean tesrs) {
replay = false;
final int target = GLSMFramebuffer.getDrawFramebuffer();
final int read = GLSMFramebuffer.getReadFramebuffer();
if (!syncSize() || target != Minecraft.getMinecraft().getFramebuffer().framebufferObject && target != TranslucencyLayers.INSTANCE.openFramebuffer()) {
GLSMFramebuffer.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, target);
GLSMFramebuffer.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, read);
draw(models, tesrs);
return;
}
final int unit = GLSMTextures.getActiveTextureUnit();
final int previousPeelTexture = GLSMTextures.getTextures().getTextureUnitBindings(DepthPeel.TEXTURE_UNIT).getBinding();
final int previousSceneTexture = GLSMTextures.getTextures().getTextureUnitBindings(DepthPeel.SCENE_TEXTURE_UNIT).getBinding();
final Slot slot = slot(passFlushes++);
final int count = slot != null ? slot.update() : MAX_PEELS;
final boolean query = slot != null && slot.beginQueries(count);
boolean completed = false;
try {
blitDepth(target, sceneDepth.framebuffer.getId());
bindTexture(DepthPeel.SCENE_TEXTURE_UNIT, sceneDepth.depth);
Target bound = sceneDepth;
for (int i = 0; i < count; i++) {
final Target current = peels[i % 2];
clearDepth(current);
current.framebuffer.bind();
bindTexture(DepthPeel.TEXTURE_UNIT, bound.depth);
GLSMTextures.glActiveTexture(GL13.GL_TEXTURE0 + unit);
DepthPeel.setPass(DepthPeel.Pass.DEPTH, i == 0);
if (query) slot.begin(i);
draw(models, tesrs);
if (query) slot.end();
GLSMFramebuffer.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, target);
bindTexture(DepthPeel.TEXTURE_UNIT, current.depth);
GLSMTextures.glActiveTexture(GL13.GL_TEXTURE0 + unit);
DepthPeel.setPass(DepthPeel.Pass.COLOR, false);
draw(models, tesrs);
bound = current;
}
DepthPeel.setPass(DepthPeel.Pass.REST, false);
if (query) slot.begin(count);
draw(models, tesrs);
if (query) slot.end();
if (DepthPeel.skippedApplicationDraws()) {
DepthPeel.setPass(DepthPeel.Pass.APPLICATION, false);
draw(models, tesrs);
}
completed = true;
} finally {
if (!completed && slot != null) slot.abandon();
DepthPeel.setPass(DepthPeel.Pass.OFF, false);
bindTexture(DepthPeel.TEXTURE_UNIT, previousPeelTexture);
bindTexture(DepthPeel.SCENE_TEXTURE_UNIT, previousSceneTexture);
GLSMTextures.glActiveTexture(GL13.GL_TEXTURE0 + unit);
GLSMFramebuffer.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, target);
GLSMFramebuffer.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, read);
}
}
private static Slot slot(int flush) {
if (flush >= SLOTS_PER_PASS) return null;
final int index = (MinecraftForgeClient.getRenderPass() == 1 ? SLOTS_PER_PASS : 0) + flush;
if (slots[index] == null) slots[index] = new Slot();
return slots[index];
}
private static void clearDepth(Target target) {
if (clearState == null) clearState = StateSet.forMask(GL11.GL_DEPTH_BUFFER_BIT | GL11.GL_SCISSOR_BIT);
final int saved = GLSMAttribStack.pushState(clearState);
try {
GLSMRasterizer.disableScissorTest();
GLSMDepthStencilAlpha.glDepthMask(true);
GLSMDepthStencilAlpha.glClearDepth(0.0);
target.framebuffer.bind();
GLSMFramebuffer.glClear(GL11.GL_DEPTH_BUFFER_BIT);
} finally {
GLSMAttribStack.popStateTo(saved);
}
}
private static void blitDepth(int from, int to) {
GLSMFramebuffer.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, from);
GLSMFramebuffer.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, to);
GLSMFramebuffer.glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL11.GL_DEPTH_BUFFER_BIT, GL11.GL_NEAREST);
}
private static void bindTexture(int unit, int texture) {
GLSMTextures.glActiveTexture(GL13.GL_TEXTURE0 + unit);
GLSMTextures.glBindTexture(GL11.GL_TEXTURE_2D, texture);
}
private static boolean syncSize() {
final Framebuffer main = Minecraft.getMinecraft().getFramebuffer();
final IRenderTargetExt ext = (IRenderTargetExt) main;
if (peels != null && main.framebufferWidth == width && main.framebufferHeight == height && ext.iris$getDepthBufferVersion() == depthVersion) return true;
destroyTargets();
width = main.framebufferWidth;
height = main.framebufferHeight;
depthVersion = ext.iris$getDepthBufferVersion();
final int mainDepth = ext.iris$getDepthTextureId();
if (width <= 0 || height <= 0 || mainDepth <= 0) return false;
depthFormat = DepthBufferFormat.fromGlEnumOrDefault(TextureInfoCache.INSTANCE.getInfo(mainDepth).getInternalFormat());
sceneDepth = new Target(depthFormat.getGlInternalFormat(), depthFormat.getGlType(), depthFormat.getGlFormat());
peels = new Target[] { Target.float32(), Target.float32() };
return true;
}
public static void destroy() {
destroyTargets();
for (int i = 0; i < slots.length; i++) {
if (slots[i] != null) slots[i].delete();
slots[i] = null;
}
}
private static void destroyTargets() {
if (peels != null) for (Target target : peels) target.destroy();
if (sceneDepth != null) sceneDepth.destroy();
peels = null;
sceneDepth = null;
}
private static final class Slot {
private int count = MAX_PEELS;
private final int[] queries = new int[MAX_PEELS + 1];
private int issued = -1;
private boolean querying;
int update() {
if (issued < 0) return count;
for (int i = 0; i <= issued; i++) {
if (GLSMQueries.glGetQueryObjecti(queries[i], GL15.GL_QUERY_RESULT_AVAILABLE) == 0) return count;
}
int drawn = issued;
for (int i = 0; i < issued; i++) {
if (GLSMQueries.glGetQueryObjecti(queries[i], GL15.GL_QUERY_RESULT) == 0) {
drawn = i;
break;
}
}
if (drawn == issued && GLSMQueries.glGetQueryObjecti(queries[issued], GL15.GL_QUERY_RESULT) != 0) {
count = MAX_PEELS;
} else if (drawn < count) {
count = Math.max(1, count - 1);
}
issued = -1;
return count;
}
boolean beginQueries(int peels) {
if (issued >= 0 || RENDER_BACKEND.isSDLGPU()) return false;
if (queries[0] == 0) {
try {
for (int i = 0; i < queries.length; i++) queries[i] = GLSMQueries.glGenQueries();
} catch (UnsupportedOperationException e) {
return false;
}
}
issued = peels;
return true;
}
void begin(int peel) {
GLSMQueries.glBeginQuery(GL33.GL_ANY_SAMPLES_PASSED, queries[peel]);
querying = true;
}
void end() {
querying = false;
GLSMQueries.glEndQuery(GL33.GL_ANY_SAMPLES_PASSED);
}
void abandon() {
if (querying) end();
issued = -1;
}
void delete() {
if (queries[0] == 0) return;
for (int query : queries) GLSMQueries.glDeleteQueries(query);
}
}
private static final class Target {
final int depth;
final GlFramebuffer framebuffer = new GlFramebuffer();
Target(int internalFormat, int format, int type) {
depth = texture(internalFormat, format, type);
framebuffer.addDepthAttachment(depth);
framebuffer.noDrawBuffers();
RenderSystem.readBuffer(framebuffer.getId(), GL11.GL_NONE);
}
static Target float32() {
return new Target(GL30.GL_DEPTH_COMPONENT32F, GL11.GL_DEPTH_COMPONENT, GL11.GL_FLOAT);
}
private static int texture(int internalFormat, int format, int type) {
final int previous = GLSMQueries.glGetInteger(GL11.GL_TEXTURE_BINDING_2D);
final int texture = GLSMTextures.glGenTextures();
GLSMTextures.glBindTexture(GL11.GL_TEXTURE_2D, texture);
GLSMTextures.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST);
GLSMTextures.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);
GLSMTextures.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
GLSMTextures.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);
GLSMTextures.glTexParameteri(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_COMPARE_MODE, GL11.GL_NONE);
GLSMTextures.glTexImage2D(GL11.GL_TEXTURE_2D, 0, internalFormat, width, height, 0, format, type, (ByteBuffer) null);
GLSMTextures.glBindTexture(GL11.GL_TEXTURE_2D, previous);
return texture;
}
void destroy() {
framebuffer.destroy();
GLSMTextures.glDeleteTextures(depth);
}
}
}
@@ -173,6 +173,10 @@ public final class TranslucencyLayers {
return open != null;
}
public int openFramebuffer() {
return open != null ? layers[open.ordinal()].framebuffer.getId() : 0;
}
public void bindOpenLayer() {
(replayingGlows ? glowDepth : layers[open.ordinal()]).framebuffer.bind();
}