Fix Iris issues with instancing and batching (#2158)

This commit is contained in:
Eclipse-Sol authored and GitHub committed 2026-09-27 17:21:39 -07:00
1 parent 7bb5bfd45c
commit af599f292e
103 files changed
+4691 -535

No files matched your search

@@ -0,0 +1,45 @@
package com.gtnewhorizons.angelica.compat.draconicevolution;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.rendering.tesr.BatchEligibility;
import net.minecraft.client.renderer.entity.RenderItem;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraftforge.client.IItemRenderer.ItemRenderType;
import net.minecraftforge.client.MinecraftForgeClient;
import org.lwjgl.opengl.GL11;
public final class PlacedItemRenderCompat {
private PlacedItemRenderCompat() {}
public static boolean requiresLiveRender(ItemStack stack) {
if (stack == null) return false;
if (MinecraftForgeClient.getItemRenderer(stack, ItemRenderType.ENTITY) != null) return true;
//TODO: Properly optimize this later, right now it's breaking everything.
return stack.getItem() instanceof ItemBlock;
}
public static void render(double x, double y, double z, Runnable draw) {
final boolean inFrame = RenderItem.renderInFrame;
GLStateManager.glPushMatrix();
GLStateManager.glPushAttrib(GL11.GL_ENABLE_BIT);
try {
GLStateManager.glTranslated(x, y, z);
draw.run();
} finally {
RenderItem.renderInFrame = inFrame;
GLStateManager.glPopAttrib();
GLStateManager.glPopMatrix();
}
}
public static byte renderWithBatchState(double x, double y, double z, byte state, Runnable draw) {
BatchEligibility.beginIsolated(state, GLStateManager.drawCalls);
try {
render(x, y, z, draw);
} finally {
state = BatchEligibility.endIsolated(state, GLStateManager.drawCalls);
}
return state;
}
}
@@ -87,17 +87,21 @@ public final class RenderLayer implements BlendingStateHolder {
}
public static RenderLayer tesr(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot, int cull, boolean lit) {
return build(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cull, lit, false);
return tesr(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cull, lit, false);
}
public static RenderLayer tesr(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot, int cull, boolean lit, boolean afterGlint) {
return build(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cull, lit, false, afterGlint);
}
public static RenderLayer tesrNoPass(ResourceLocation texture, TesrMaterial material, int cull, boolean lit) {
return build(texture, material, PassOverride.NONE, 0.0f, 0.0f, ShaderGlint.NO_TINT, cull, lit, true);
return build(texture, material, PassOverride.NONE, 0.0f, 0.0f, ShaderGlint.NO_TINT, cull, lit, true, false);
}
private static RenderLayer build(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot, int cull, boolean lit, boolean noPass) {
private static RenderLayer build(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot, int cull, boolean lit, boolean noPass, boolean afterGlint) {
final DrawState state = DrawState.forMaterial(material, cull, lit, offsetFactor, offsetUnits);
final Hook hook = hookFor(material, noPass ? PassOverride.NONE : pass, glintSlot);
final TransparencyType transparency = transparencyFor(state.getBlend());
final TransparencyType transparency = afterGlint ? TransparencyType.AFTER_GLINT : transparencyFor(state.getBlend());
final RenderLayer candidate = new RenderLayer(null, BatchVertexFormats.POSITION_COLOR_TEXTURE_LIGHTF_NORMAL,
GL11.GL_QUADS, TESR_BUFFER_SIZE, state, texture, material.isUnfilteredAtlas(), transparency, hook,
noPass);
@@ -107,7 +111,7 @@ public final class RenderLayer implements BlendingStateHolder {
+ material.transparency().name().toLowerCase(Locale.ROOT) + (noPass ? "" : pass.nameSuffix())
+ (offsetFactor == 0.0f && offsetUnits == 0.0f ? "" : "_offset" + offsetFactor + "_" + offsetUnits)
+ "_cull" + state.getCull() + (state.isLit() ? "_lit" : "")
+ (glintSlot == ShaderGlint.NO_TINT ? "" : "_tint" + glintSlot);
+ (glintSlot == ShaderGlint.NO_TINT ? "" : "_tint" + glintSlot) + (afterGlint ? "_after_glint" : "");
}
return retained;
}
@@ -0,0 +1,121 @@
package com.gtnewhorizons.angelica.compat.thaumcraft;
import com.gtnewhorizons.angelica.glsm.DisplayListManager;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.ffp.ShaderManager;
import com.gtnewhorizons.angelica.glsm.states.AlphaState;
import net.coderbot.iris.layer.GbufferPrograms;
import net.coderbot.iris.pipeline.WorldRenderingPhase;
import net.coderbot.iris.pipeline.WorldRenderingPipeline;
import net.coderbot.iris.uniforms.ItemIdManager;
import org.joml.Matrix4f;
import org.joml.Vector3f;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import java.util.ArrayList;
import java.util.List;
/** The held scanner's pane, icons and labels must follow translucent world geometry. */
public final class ThaumometerScreen {
private static final List<Capture> pending = new ArrayList<>();
private ThaumometerScreen() {}
public static Capture begin() {
if (DisplayListManager.isRecording()) return null;
final Capture capture = new Capture();
GLStateManager.glNewList(capture.list, GL11.GL_COMPILE);
return capture;
}
public static void finish(Capture capture) {
GLStateManager.glEndList();
pending.add(capture);
}
public static void abort(Capture capture) {
if (DisplayListManager.isRecording()) GLStateManager.glEndList();
GLStateManager.glDeleteLists(capture.list, 1);
}
public static void discard() {
for (Capture capture : pending) GLStateManager.glDeleteLists(capture.list, 1);
pending.clear();
}
public static void render(WorldRenderingPipeline pipeline) {
if (pending.isEmpty()) return;
final WorldRenderingPhase phase = pipeline.getPhase();
final Matrix4f texture = new Matrix4f(GLStateManager.getTextures().getTextureUnitMatrix(0));
final Matrix4f lightmap = new Matrix4f(GLStateManager.getTextures().getTextureUnitMatrix(1));
final float brightnessX = GLStateManager.ctx().lastBrightnessX;
final float brightnessY = GLStateManager.ctx().lastBrightnessY;
final Boolean translucency = GbufferPrograms.beginTranslucencyDeclaration(true);
GLStateManager.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
GLStateManager.glMatrixMode(GL11.GL_PROJECTION);
GLStateManager.glPushMatrix();
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
GLStateManager.glPushMatrix();
ItemIdManager.pushItemId();
try {
pipeline.setPhase(WorldRenderingPhase.HAND_TRANSLUCENT);
GbufferPrograms.setBlockEntityDefaults();
GLStateManager.enableDepthTest();
GLStateManager.glDepthMask(false);
for (Capture capture : pending) capture.replay();
} finally {
ItemIdManager.popItemId();
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
GLStateManager.glPopMatrix();
GLStateManager.setTextureMatrix(0, texture);
GLStateManager.setTextureMatrix(1, lightmap);
GLStateManager.glMatrixMode(GL11.GL_PROJECTION);
GLStateManager.glPopMatrix();
GLStateManager.glPopAttrib();
GLStateManager.setLightmapTextureCoords(GL13.GL_TEXTURE1, brightnessX, brightnessY);
GbufferPrograms.endTranslucencyDeclaration(translucency);
pipeline.setPhase(phase);
discard();
}
}
public static final class Capture {
private final int list = GLStateManager.glGenLists(1);
private final Matrix4f modelView = new Matrix4f(GLStateManager.getModelViewMatrix());
private final Matrix4f projection = new Matrix4f(GLStateManager.getProjectionMatrix());
private final Matrix4f texture = new Matrix4f(GLStateManager.getTextures().getTextureUnitMatrix(0));
private final Matrix4f lightmapMatrix = new Matrix4f(GLStateManager.getTextures().getTextureUnitMatrix(1));
private final float brightnessX = GLStateManager.ctx().lastBrightnessX;
private final float brightnessY = GLStateManager.ctx().lastBrightnessY;
private final Vector3f normal = new Vector3f(ShaderManager.getCurrentNormal());
private final AlphaState alphaState = GLStateManager.getAlphaState().readEffective(new AlphaState());
private final int depthFunction = GLStateManager.getDepthState().getFunc();
private final int itemId = ItemIdManager.getItemId();
private final boolean cull = GLStateManager.getCullState().isEnabled();
private final boolean alpha = GLStateManager.getAlphaTest().isEffectivelyEnabled();
private final boolean lightmap = GLStateManager.getTextures().getTextureUnitStates(1).isEnabled();
private final boolean lighting = GLStateManager.getLightingState().isEnabled();
private void replay() {
GLStateManager.setProjectionMatrix(projection);
GLStateManager.setModelViewMatrix(modelView);
GLStateManager.setTextureMatrix(0, texture);
GLStateManager.setTextureMatrix(1, lightmapMatrix);
GLStateManager.setLightmapTextureCoords(GL13.GL_TEXTURE1, brightnessX, brightnessY);
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
GLStateManager.glNormal3f(normal.x, normal.y, normal.z);
GLStateManager.glDepthFunc(depthFunction);
GLStateManager.glAlphaFunc(alphaState.getFunction(), alphaState.getReference());
ItemIdManager.setItemIdRaw(itemId);
if (cull) GLStateManager.enableCull(); else GLStateManager.disableCull();
if (alpha) GLStateManager.enableAlphaTest(); else GLStateManager.disableAlphaTest();
if (lighting) GLStateManager.enableLighting(); else GLStateManager.disableLighting();
GLStateManager.glActiveTexture(GL13.GL_TEXTURE1);
if (lightmap) GLStateManager.enableTexture(); else GLStateManager.disableTexture();
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
GLStateManager.enableTexture();
GLStateManager.glCallList(list);
}
}
}
@@ -0,0 +1,335 @@
package com.gtnewhorizons.angelica.iris;
import com.gtnewhorizons.angelica.glsm.DisplayListManager;
import com.gtnewhorizons.angelica.glsm.hooks.BatchStateGuard;
import com.gtnewhorizons.angelica.glsm.recording.CommandRecorder;
import com.gtnewhorizons.angelica.glsm.recording.commands.DisplayListCommand;
import com.gtnewhorizons.angelica.shadercompat.ShaderGlint;
import com.gtnewhorizons.angelica.rendering.FallingBlockRendering;
import it.unimi.dsi.fastutil.booleans.BooleanArrayList;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition;
import net.coderbot.iris.layer.GbufferPrograms;
import net.coderbot.iris.pipeline.WorldRenderingPhase;
import net.coderbot.iris.shaderpack.materialmap.NamespacedId;
import net.coderbot.iris.uniforms.CapturedRenderingState;
import net.coderbot.iris.uniforms.EntityIdHelper;
import net.coderbot.iris.uniforms.ItemIdManager;
import net.minecraft.block.Block;
import net.minecraft.entity.Entity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
/**
* Records Java-side rendering scopes alongside cached geometry.
*/
public final class IrisDisplayListState {
private IrisDisplayListState() {}
public static void runProgramTransition(Runnable transition) {
BatchStateGuard.suspend();
try {
runUnrecorded(transition);
} finally {
BatchStateGuard.resume();
}
}
public static void runUnrecorded(Runnable transition) {
final DisplayListManager.RecordMode mode = DisplayListManager.getRecordMode();
if (mode == DisplayListManager.RecordMode.COMPILE) return;
if (mode == DisplayListManager.RecordMode.NONE) {
transition.run();
return;
}
final CommandRecorder recorder = DisplayListManager.pauseRecording();
try {
transition.run();
} finally {
DisplayListManager.resumeRecording(recorder);
}
}
private static void record(DisplayListCommand cmd) {
if (DisplayListManager.isRecording()) {
DisplayListManager.recordStateCommand(cmd);
}
}
public static void recordSpecialCondition(SpecialCondition condition, boolean begin) {
if (DisplayListManager.isRecording()) record(new SpecialConditionCmd(condition, begin));
}
public static void recordGlintSpan(boolean begin) {
if (DisplayListManager.isRecording()) record(new GlintSpanCmd(begin));
}
/** Keep nested items on the entity pass, including its depth and TAA behavior. */
public static void recordOverridePhase(WorldRenderingPhase phase) {
if (DisplayListManager.isRecording()) record(new OverridePhaseCmd(phase));
}
public static void recordPhaseScope(WorldRenderingPhase phase, boolean begin) {
if (DisplayListManager.isRecording()) record(new PhaseScopeCmd(phase, begin));
}
public static void recordNestedEntityScope(boolean begin) {
if (DisplayListManager.isRecording()) record(new NestedEntityScopeCmd(begin));
}
public static void recordTranslucency(Boolean translucent) {
if (DisplayListManager.isRecording()) record(new TranslucencyCmd(translucent));
}
public static void recordTranslucencyScope(Boolean translucent, boolean begin) {
if (DisplayListManager.isRecording()) record(new TranslucencyScopeCmd(translucent, begin));
}
/** Record explicit IDs as well as item identities so replay cannot inherit a previous draw's ID. */
public static void recordItemId(int itemId) {
if (DisplayListManager.isRecording()) {
DisplayListManager.recordStateCommandIfChanged(new ItemIdCmd(itemId));
}
}
public static void recordItem(ItemStack item) {
if (DisplayListManager.isRecording()) {
record(new ItemCmd(item == null ? null : item.copy()));
}
}
public static void recordItem(Item item, int metadata) {
if (DisplayListManager.isRecording()) record(new ItemTypeCmd(item, metadata));
}
public static void recordNamedItem(NamespacedId item) {
if (DisplayListManager.isRecording()) record(new NamedItemCmd(item));
}
public static void recordBlockItem(Block block, int metadata) {
if (DisplayListManager.isRecording()) record(new BlockItemCmd(block, metadata));
}
public static void recordItemScope(boolean push) {
if (DisplayListManager.isRecording()) record(new ItemScopeCmd(push));
}
public static void recordEntity(Entity entity) {
if (DisplayListManager.isRecording()) {
record(new EntityCmd(EntityIdHelper.snapshot(entity)));
}
}
public static void recordEntityScope(boolean push) {
if (DisplayListManager.isRecording()) record(new EntityScopeCmd(push));
}
public static void recordEntityAndItem(int entity, int item) {
if (DisplayListManager.isRecording()) {
DisplayListManager.recordStateCommandIfChanged(new EntityAndItemCmd(entity, item));
}
}
public static void recordNamedEntity(NamespacedId entity) {
if (DisplayListManager.isRecording()) record(new NamedEntityCmd(entity));
}
public static void recordBlockEntity(int id) {
if (DisplayListManager.isRecording()) {
DisplayListManager.recordStateCommandIfChanged(new BlockEntityIdCmd(id));
}
}
public static void recordBlockEntity(Block block, int metadata) {
if (DisplayListManager.isRecording()) record(new BlockEntityCmd(block, metadata));
}
public static void recordBlockEntityScope(boolean push) {
if (DisplayListManager.isRecording()) record(new BlockEntityScopeCmd(push));
}
public static void recordEntityColor(float r, float g, float b, float a) {
if (DisplayListManager.isRecording()) {
DisplayListManager.recordStateCommandIfChanged(new EntityColorCmd(r, g, b, a));
}
}
public static void recordEntityColorScope(boolean push) {
if (DisplayListManager.isRecording()) record(new EntityColorScopeCmd(push));
}
public static void recordBlockEntityAttribute(Block block, int metadata) {
if (DisplayListManager.isRecording()) record(new BlockEntityAttributeCmd(block, metadata));
}
private record BlockEntityAttributeCmd(Block block, int metadata) implements DisplayListCommand {
@Override
public void execute() {
if (block == null) FallingBlockRendering.resetEntityAttribute();
else FallingBlockRendering.setEntityAttribute(block, metadata);
}
}
private record EntityAndItemCmd(int entity, int item) implements DisplayListCommand {
@Override
public void execute() { CapturedRenderingState.INSTANCE.setCurrentEntityAndItem(entity, item); }
}
private record NamedEntityCmd(NamespacedId entity) implements DisplayListCommand {
@Override
public void execute() { CapturedRenderingState.INSTANCE.setCurrentNamedEntity(entity); }
}
private record BlockEntityIdCmd(int id) implements DisplayListCommand {
@Override
public void execute() { CapturedRenderingState.INSTANCE.setCurrentBlockEntity(id); }
}
private record BlockEntityCmd(Block block, int metadata) implements DisplayListCommand {
@Override
public void execute() { CapturedRenderingState.INSTANCE.setCurrentBlockEntity(block, metadata); }
}
private record BlockEntityScopeCmd(boolean push) implements DisplayListCommand {
@Override
public void execute() {
if (push) CapturedRenderingState.INSTANCE.pushCurrentBlockEntity();
else CapturedRenderingState.INSTANCE.popCurrentBlockEntity();
}
}
private record EntityColorCmd(float r, float g, float b, float a) implements DisplayListCommand {
@Override
public void execute() { CapturedRenderingState.INSTANCE.setCurrentEntityColor(r, g, b, a); }
}
private record EntityColorScopeCmd(boolean push) implements DisplayListCommand {
@Override
public void execute() {
if (push) CapturedRenderingState.INSTANCE.pushCurrentEntityColor();
else CapturedRenderingState.INSTANCE.popCurrentEntityColor();
}
}
private record EntityCmd(EntityIdHelper.EntityIdentity identity) implements DisplayListCommand {
@Override
public void execute() {
CapturedRenderingState.INSTANCE.setCurrentEntityAndItem(identity == null ? -1 : identity.resolve(), 0);
}
}
private record EntityScopeCmd(boolean push) implements DisplayListCommand {
@Override
public void execute() {
if (push) CapturedRenderingState.INSTANCE.pushCurrentEntityAndItem();
else CapturedRenderingState.INSTANCE.popCurrentEntityAndItem();
}
}
private record ItemScopeCmd(boolean push) implements DisplayListCommand {
@Override
public void execute() {
if (push) {
CapturedRenderingState.INSTANCE.pushCurrentRenderedItem();
} else {
CapturedRenderingState.INSTANCE.popCurrentRenderedItem();
}
}
}
private record SpecialConditionCmd(SpecialCondition condition, boolean begin) implements DisplayListCommand {
@Override
public void execute() {
if (begin) {
GbufferPrograms.setupSpecialRenderCondition(condition);
} else {
GbufferPrograms.teardownSpecialRenderCondition();
}
}
}
private record GlintSpanCmd(boolean begin) implements DisplayListCommand {
@Override
public void execute() {
if (begin) {
ShaderGlint.beginGlint();
} else {
ShaderGlint.endGlint();
}
}
}
private record OverridePhaseCmd(WorldRenderingPhase phase) implements DisplayListCommand {
@Override
public void execute() {
GbufferPrograms.setOverridePhase(phase);
}
}
private record PhaseScopeCmd(WorldRenderingPhase phase, boolean begin) implements DisplayListCommand {
@Override
public void execute() {
if (begin) GbufferPrograms.pushOverridePhase(phase);
else GbufferPrograms.popOverridePhase();
}
}
private static final BooleanArrayList replayNestedEntityStack = new BooleanArrayList();
private record NestedEntityScopeCmd(boolean begin) implements DisplayListCommand {
@Override
public void execute() {
if (begin) replayNestedEntityStack.push(GbufferPrograms.beginNestedEntityPhase());
else GbufferPrograms.endNestedEntityPhase(replayNestedEntityStack.popBoolean());
}
}
private record TranslucencyCmd(Boolean translucent) implements DisplayListCommand {
@Override
public void execute() {
GbufferPrograms.setTranslucencyDeclaration(translucent);
}
}
private static final ObjectArrayList<Boolean> replayTranslucencyStack = new ObjectArrayList<>();
private record TranslucencyScopeCmd(Boolean translucent, boolean begin) implements DisplayListCommand {
@Override
public void execute() {
if (begin) replayTranslucencyStack.add(GbufferPrograms.beginTranslucencyDeclaration(translucent));
else GbufferPrograms.endTranslucencyDeclaration(replayTranslucencyStack.pop());
}
}
private record ItemIdCmd(int itemId) implements DisplayListCommand {
@Override
public void execute() {
CapturedRenderingState.INSTANCE.setCurrentRenderedItem(itemId);
}
}
private record ItemCmd(ItemStack item) implements DisplayListCommand {
@Override
public void execute() {
ItemIdManager.setItemId(item);
}
}
private record ItemTypeCmd(Item item, int metadata) implements DisplayListCommand {
@Override
public void execute() { CapturedRenderingState.INSTANCE.setCurrentRenderedItem(item, metadata); }
}
private record NamedItemCmd(NamespacedId item) implements DisplayListCommand {
@Override
public void execute() { CapturedRenderingState.INSTANCE.setCurrentNamedItem(item); }
}
private record BlockItemCmd(Block block, int metadata) implements DisplayListCommand {
@Override
public void execute() {
ItemIdManager.setBlockId(block, metadata);
}
}
}
@@ -1,6 +1,7 @@
package com.gtnewhorizons.angelica.iris;
import com.gtnewhorizons.angelica.client.rendering.TextureTracker;
import com.gtnewhorizons.angelica.glsm.GLContextState;
import com.gtnewhorizons.angelica.glsm.hooks.DeferredAlphaHandler;
import com.gtnewhorizons.angelica.glsm.hooks.DeferredBlendHandler;
import com.gtnewhorizons.angelica.glsm.hooks.DeferredDepthColorHandler;
@@ -20,6 +21,7 @@ import net.coderbot.iris.gl.blending.AlphaTestStorage;
import net.coderbot.iris.gl.blending.BlendModeStorage;
import net.coderbot.iris.gl.blending.DepthColorStorage;
import net.coderbot.iris.gl.program.ProgramUniforms;
import net.coderbot.iris.gl.program.Program;
import net.coderbot.iris.gl.state.StateUpdateNotifiers;
import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline;
import net.coderbot.iris.pipeline.WorldRenderingPipeline;
@@ -87,6 +89,18 @@ public class IrisGLSMBridge {
};
}
static void installVanillaStateLayers() {
// Forge initializes mods with the splash screen's shared drawable current.
// Iris overrides belong to the display context used for world rendering.
final GLContextState context = GLStateManager.primaryContext();
context.blendMode.setVanillaLayer(BlendModeStorage.ENABLE_LAYER);
context.blendState.setVanillaLayer(BlendModeStorage.FUNC_LAYER);
context.alphaTest.setVanillaLayer(AlphaTestStorage.ENABLE_LAYER);
context.alphaState.setVanillaLayer(AlphaTestStorage.FUNC_LAYER);
context.depthState.setVanillaLayer(DepthColorStorage.DEPTH_LAYER);
context.colorMask.setVanillaLayer(DepthColorStorage.COLOR_LAYER);
}
public static void register() {
GLSMConfig.expandVertexFormats = Iris.enabled;
IrisSamplers.initRenderer();
@@ -124,12 +138,7 @@ public class IrisGLSMBridge {
}
};
GLStateManager.getBlendMode().setVanillaLayer(BlendModeStorage.ENABLE_LAYER);
GLStateManager.getBlendState().setVanillaLayer(BlendModeStorage.FUNC_LAYER);
GLStateManager.getAlphaTest().setVanillaLayer(AlphaTestStorage.ENABLE_LAYER);
GLStateManager.getAlphaState().setVanillaLayer(AlphaTestStorage.FUNC_LAYER);
GLStateManager.getDepthState().setVanillaLayer(DepthColorStorage.DEPTH_LAYER);
GLStateManager.getColorMask().setVanillaLayer(DepthColorStorage.COLOR_LAYER);
installVanillaStateLayers();
GLSMHooks.alphaHandler = new DeferredAlphaHandler() {
@Override
@@ -270,7 +279,7 @@ public class IrisGLSMBridge {
if (!drp.shouldOverrideShaders()) return;
DepthColorStorage.unlockDepthColor();
if (event.newProgram != 0 && !DepthColorStorage.isOwnedProgram(event.newProgram)) {
if (event.newProgram != 0 && !Program.isManagedBind(event.newProgram) && !DepthColorStorage.isOwnedProgram(event.newProgram)) {
drp.onModProgramOverride();
}
});
@@ -294,12 +303,15 @@ public class IrisGLSMBridge {
GLSMHooks.PROGRAM_CHANGE.addListener(event -> {
if (!Iris.enabled) return;
if (!event.postBind) return;
if (Program.isManagedBind(event.newProgram)) return;
WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable();
if (pipeline instanceof DeferredWorldRenderingPipeline drp) {
DeferredWorldRenderingPipeline.Pass activePass = drp.getActivePassProgram();
if (activePass != null && activePass.getProgram() != null && activePass.getProgram().getProgramId() == event.newProgram) {
final int frame = SystemTimeUniforms.COUNTER.getAsInt();
if (programLastUpdatedFrame.get(event.newProgram) != frame) {
if (programLastUpdatedFrame.get(event.newProgram) != frame
|| !ProgramUniforms.isActiveProgramBound()
|| ProgramUniforms.activeHasDeferredUploads()) {
activePass.getProgram().getUniforms().update();
programLastUpdatedFrame.put(event.newProgram, frame);
}
@@ -215,6 +215,13 @@ public enum Mixins implements IMixins {
)
),
THAUMCRAFT_SCANNER_SCREEN(new MixinBuilder("Render the held Thaumometer screen after world transparency")
.setPhase(Phase.LATE)
.addRequiredMod(TargetedMod.THAUMCRAFT)
.setApplyIf(() -> AngelicaConfig.enableIris)
.addClientMixins("client.thaumcraft.MixinItemThaumometerRenderer")
),
THAUMCRAFT_TESR_JAR_CACHE(new MixinBuilder("Batch TC4 jar liquid via the retained TESR mesh cache")
.setPhase(Phase.LATE)
.setApplyIf(() -> AngelicaConfig.enableTESRJarCache)
@@ -814,6 +821,11 @@ public enum Mixins implements IMixins {
.setApplyIf(() -> AngelicaConfig.enableIris)
.addClientMixins("client.etfuturum.MixinTileEntityNewBeaconRenderer")
),
DRACONIC_PLACED_ITEM_RENDERER(new MixinBuilder("Keep custom placed-item renderers live")
.setPhase(Phase.LATE)
.addRequiredMod(TargetedMod.DRACONIC_EVOLUTION)
.addClientMixins("client.draconicevolution.MixinRenderTilePlacedItem")
),
OPENBLOCKS_TROPHY_ENTITY_GBUFFER(new MixinBuilder("Render OpenBlocks trophies with the entity gbuffer programs")
.setPhase(Phase.LATE)
.addRequiredMod(TargetedMod.OPENBLOCKS)
@@ -16,6 +16,7 @@ public enum TargetedMod implements ITargetMod {
DYNAMIC_SURROUNDINGS_MIST("org.blockartistry.mod.DynSurround.mixinplugin.DynamicSurroundingsEarlyMixins", "dsurround"),
DYNAMIC_SURROUNDINGS_ORIGINAL("org.blockartistry.mod.DynSurround.asm.TransformLoader", "dsurround"),
DRAGON_API("Reika.DragonAPI.Auxiliary.DragonAPIASMHandler", "DragonAPI"),
DRACONIC_EVOLUTION(null, "DraconicEvolution"),
ET_FUTURUM_REQUIEM(null, "etfuturum"),
EXTRAUTILS(null, "ExtraUtilities"),
FARSEEK("farseek.core.FarseekCoreMod", "farseek"),
@@ -2,8 +2,8 @@ package com.gtnewhorizons.angelica.mixins.interfaces;
@SuppressWarnings("unused")
public interface IPatchedTextureAtlasSprite {
void markNeedsAnimationUpdate();
boolean needsAnimationUpdate();
void unmarkNeedsAnimationUpdate();
void updateAnimationsDryRun();
void angelica$markNeedsAnimationUpdate();
boolean angelica$needsAnimationUpdate();
void angelica$unmarkNeedsAnimationUpdate();
void angelica$updateAnimationsDryRun();
}
@@ -2,6 +2,7 @@ package com.gtnewhorizons.angelica.rendering;
import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.iris.IrisDisplayListState;
import it.unimi.dsi.fastutil.ints.Int2IntMap;
import it.unimi.dsi.fastutil.objects.Reference2ObjectMap;
import net.coderbot.iris.block_rendering.BlockMaterialMapping;
@@ -25,13 +26,17 @@ public final class FallingBlockRendering {
}
public static void setEntityAttribute(Block block, int metadata) {
IrisDisplayListState.recordBlockEntityAttribute(block, metadata);
if (!shadersActive()) return;
GLStateManager.glVertexAttrib2s(ProgramCreator.MC_ENTITY, (short) blockMaterialId(block, metadata), (short) 0);
IrisDisplayListState.runUnrecorded(() ->
GLStateManager.glVertexAttrib2s(ProgramCreator.MC_ENTITY, (short) blockMaterialId(block, metadata), (short) 0));
}
public static void resetEntityAttribute() {
IrisDisplayListState.recordBlockEntityAttribute(null, 0);
if (!shadersActive()) return;
GLStateManager.glVertexAttrib2s(ProgramCreator.MC_ENTITY, (short) -1, (short) -1);
IrisDisplayListState.runUnrecorded(() ->
GLStateManager.glVertexAttrib2s(ProgramCreator.MC_ENTITY, (short) -1, (short) -1));
}
private static int blockMaterialId(Block block, int metadata) {
@@ -15,6 +15,7 @@ import com.gtnewhorizons.angelica.rendering.tesr.EntityMaterials;
import com.gtnewhorizons.angelica.rendering.tesr.GlintCapture;
import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher;
import com.gtnewhorizons.angelica.rendering.tesr.TemplateBuffer;
import com.gtnewhorizons.angelica.utils.AnimationsRenderUtils;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import net.minecraft.block.Block;
@@ -107,7 +108,7 @@ public final class DroppedItemInstancer {
return material;
}
public static void icon(ItemStack stack, Tessellator t, float maxU, float minV, float minU, float maxV, int width, int height, float thickness, Operation<Void> original) {
public static void icon(ItemStack stack, boolean afterGlint, Tessellator t, float maxU, float minV, float minU, float maxV, int width, int height, float thickness, Operation<Void> original) {
glintCapture.reset();
glintSeen = false;
final TesrMaterial material = material(stack, true);
@@ -116,10 +117,10 @@ public final class DroppedItemInstancer {
callIcon(ICON_ARGS, original, t, maxU, minV, minU, maxV, width, height, thickness);
return;
}
basePart = batchIcon(material, t, maxU, minV, minU, maxV, width, height, thickness, original);
basePart = batchIcon(material, afterGlint, t, maxU, minV, minU, maxV, width, height, thickness, original);
}
static boolean batchIcon(TesrMaterial material, Tessellator t, float maxU, float minV, float minU, float maxV, int width, int height, float thickness, Operation<Void> original) {
static boolean batchIcon(TesrMaterial material, boolean afterGlint, Tessellator t, float maxU, float minV, float minU, float maxV, int width, int height, float thickness, Operation<Void> original) {
final long drawsBefore = GLStateManager.drawCalls;
if (BatchEligibility.batchingAllowed()) {
final TemplateBuffer template = iconTemplate(ICON_ARGS, maxU, minV, minU, maxV, width, height, thickness, original);
@@ -129,7 +130,7 @@ public final class DroppedItemInstancer {
bail(BailReason.TEMPLATE);
return false;
}
if (ModelPartBatcher.INSTANCE.queueTemplate(template, material)) {
if (ModelPartBatcher.INSTANCE.queueTemplate(template, material, afterGlint)) {
instanced++;
BatchEligibility.onPartQueued();
return true;
@@ -234,6 +235,7 @@ public final class DroppedItemInstancer {
return;
}
if (ModelPartBatcher.INSTANCE.queueTemplate(mesh.template(), material)) {
mesh.sprites().markUsed();
instanced++;
BatchEligibility.onPartQueued();
return;
@@ -311,6 +313,7 @@ public final class DroppedItemInstancer {
blockBackend = new BakedTransformCapture(CAPTURE_BYTES);
}
final TemplateBuffer template;
final AnimationsRenderUtils.SpriteCapture sprites = AnimationsRenderUtils.captureSprites();
GLStateManager.glPushMatrix();
try {
blockBackend.begin();
@@ -321,9 +324,10 @@ public final class DroppedItemInstancer {
}
} finally {
GLStateManager.glPopMatrix();
sprites.close();
}
final Color4 color = GLStateManager.getColor();
final BlockMesh mesh = new BlockMesh(template, color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());
final BlockMesh mesh = new BlockMesh(template, color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha(), sprites);
blocks.put(new BlockMeta(block, meta), mesh);
return mesh;
}
@@ -346,5 +350,6 @@ public final class DroppedItemInstancer {
TemplateBuffer template;
}
private record BlockMesh(TemplateBuffer template, float red, float green, float blue, float alpha) {}
private record BlockMesh(TemplateBuffer template, float red, float green, float blue, float alpha,
AnimationsRenderUtils.SpriteCapture sprites) {}
}
@@ -27,7 +27,7 @@ public final class HeldItemGlint {
private HeldItemGlint() {}
private static boolean batchedGlintGuarded() {
return ModelPartBatcher.INSTANCE.entityPassActive() && ModelPartBatcher.INSTANCE.canCaptureGlint() && canResetStencil();
return ModelPartBatcher.INSTANCE.entityPassActive() && ModelPartBatcher.INSTANCE.canQueueGlint() && canResetStencil();
}
public static boolean needsImmediateBase(ItemStack stack, int pass) {
@@ -46,7 +46,7 @@ public final class HeldItemGlint {
}
public static boolean eligible() {
return AngelicaConfig.enableEntityBatching && GLStateManager.getActiveProgram() == 0 && (boolean) Settings.MODE_GLINT_WORLD.option.getStore() && opaqueTexture(Minecraft.getMinecraft());
return AngelicaConfig.enableEntityBatching && (boolean) Settings.MODE_GLINT_WORLD.option.getStore() && opaqueTexture(Minecraft.getMinecraft());
}
public static boolean begin() {
@@ -3,6 +3,8 @@ package com.gtnewhorizons.angelica.rendering.tesr;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks;
import java.util.ArrayList;
/** Excludes renderers that mix batched model parts with their own draws, which reorders their geometry. */
public final class BatchEligibility {
@@ -19,15 +21,74 @@ public final class BatchEligibility {
private static long bracketExpectedAtStart;
private static int bracketDepth;
private static int parts;
private static boolean uncapturedState;
private static ModelPartBatcher.BailReason allowedBail;
private static final ArrayList<SavedScope> isolatedScopes = new ArrayList<>();
private static int isolatedDepth;
private static final class SavedScope {
int depth, bracketDepth, parts;
boolean allowed, uncapturedState;
ModelPartBatcher.BailReason allowedBail;
long drawsAtStart, expectedDraws, foreignDraws, bracketDrawsAtStart, bracketExpectedAtStart, isolatedDrawsAtStart;
void save(long drawCount) {
depth = BatchEligibility.depth;
allowed = BatchEligibility.allowed;
uncapturedState = BatchEligibility.uncapturedState;
allowedBail = BatchEligibility.allowedBail;
drawsAtStart = BatchEligibility.drawsAtStart;
expectedDraws = BatchEligibility.expectedDraws;
foreignDraws = BatchEligibility.foreignDraws;
bracketDrawsAtStart = BatchEligibility.bracketDrawsAtStart;
bracketExpectedAtStart = BatchEligibility.bracketExpectedAtStart;
bracketDepth = BatchEligibility.bracketDepth;
parts = BatchEligibility.parts;
isolatedDrawsAtStart = drawCount;
}
void restore(long drawCount) {
BatchEligibility.depth = depth;
BatchEligibility.allowed = allowed;
BatchEligibility.uncapturedState = uncapturedState;
BatchEligibility.allowedBail = allowedBail;
BatchEligibility.drawsAtStart = drawsAtStart;
BatchEligibility.expectedDraws = expectedDraws + drawCount - isolatedDrawsAtStart;
BatchEligibility.foreignDraws = foreignDraws;
BatchEligibility.bracketDrawsAtStart = bracketDrawsAtStart;
BatchEligibility.bracketExpectedAtStart = bracketExpectedAtStart;
BatchEligibility.bracketDepth = bracketDepth;
BatchEligibility.parts = parts;
}
}
private BatchEligibility() {}
public static void beginIsolated(byte state, long drawCount) {
if (isolatedDepth == isolatedScopes.size()) isolatedScopes.add(new SavedScope());
isolatedScopes.get(isolatedDepth++).save(drawCount);
depth = 0;
bracketDepth = 0;
begin(state, drawCount);
}
public static byte endIsolated(byte state, long drawCount) {
try {
return end(state, drawCount);
} finally {
isolatedScopes.get(--isolatedDepth).restore(drawCount);
}
}
public static boolean begin(byte state, long drawCount) {
if (depth++ > 0) return allowed;
drawsAtStart = drawCount;
expectedDraws = 0L;
foreignDraws = 0L;
parts = 0;
uncapturedState = false;
allowedBail = null;
bracketDepth = 0;
allowed = state == SAFE;
return allowed;
@@ -37,6 +98,7 @@ public final class BatchEligibility {
if (--depth > 0) return state;
allowed = false;
GLSMHooks.resolvePendingProgram();
if (uncapturedState) return DENIED;
if (parts == 0) return state;
final long foreign = (drawCount - drawsAtStart) - expectedDraws;
if (foreign > 0L) {
@@ -50,6 +112,27 @@ public final class BatchEligibility {
return allowed;
}
static boolean insideRenderer() { return depth != 0; }
static void onUncapturedState() {
if (depth == 0) return;
uncapturedState = true;
allowed = false;
}
static void onBatchFlushed(long draws) {
if (depth != 0) expectedDraws += draws;
}
static void onBail(ModelPartBatcher.BailReason reason) {
if (depth == 0 || !allowed) return;
if (reason == ModelPartBatcher.BailReason.INACTIVE) {
allowed = false;
return;
}
if (allowedBail == null) allowedBail = reason;
}
public static void onPartQueued() {
parts++;
}
@@ -76,6 +159,10 @@ public final class BatchEligibility {
public static void onStateChange(Object renderer, byte state) {
if (state != DENIED) return;
final String name = renderer.getClass().getName();
GLStateManager.warnOnce("tesr-mixed:" + name, "{} draws its own geometry alongside model parts ({} foreign draws) - excluding it from model part batching", name, foreignDraws);
if (uncapturedState) {
GLStateManager.warnOnce("tesr-state:" + name, "{} changes state outside the batch format - keeping its model parts immediate", name);
return;
}
GLStateManager.warnOnce("tesr-mixed:" + name, "{} draws its own geometry alongside model parts ({} foreign draws, first allowed bail: {}) - excluding it from model part batching", name, foreignDraws, allowedBail);
}
}
@@ -0,0 +1,39 @@
package com.gtnewhorizons.angelica.rendering.tesr;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.hooks.BatchStateGuard;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
/** Uncaptured state changes draw the queued batch before the mutation takes effect. */
final class BatchStateFallback {
private static final Runnable FLUSH = BatchStateFallback::flush;
static void install() { BatchStateGuard.flush = FLUSH; }
private static void flush() {
final ModelPartBatcher models = ModelPartBatcher.INSTANCE;
final TesrBatchRenderer tesrs = TesrBatchRenderer.INSTANCE;
if (!models.isActive() && !tesrs.hasPendingGeometry()) return;
// Pass setup may establish defaults after beginPass, before any renderer or queued draw.
if (!models.hasQueuedGeometry() && !tesrs.hasQueuedGeometry() && !BatchEligibility.insideRenderer()) return;
if (models.entityPassActive()) {
final boolean inside = BatchEligibility.insideRenderer();
GLStateManager.warnOnce("batch-fallback-entities:" + inside, "Uncaptured state change {} a renderer flushed the entity batch early",
inside ? "inside" : "between", new Throwable());
}
final int mode = GLStateManager.getMatrixMode().getMode();
final int unit = GLStateManager.getActiveTextureUnit();
BatchEligibility.onUncapturedState();
final long before = GLStateManager.drawCalls;
try {
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
models.flushForStateChange();
tesrs.flushForStateChange();
} finally {
GLStateManager.glMatrixMode(mode);
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + unit);
BatchEligibility.onBatchFlushed(GLStateManager.drawCalls - before);
}
}
}
@@ -47,6 +47,8 @@ final class EntityShadowBatcher {
private long quads;
private long draws;
boolean hasPendingGeometry() { return count != 0; }
long statQuads() { return quads; }
long statDraws() { return draws; }
@@ -59,7 +59,6 @@ public final class GlintCapture {
texture = GLStateManager.getBoundTextureForServerState();
color = currentColor();
light = GLSMConfig.packedLastBrightness();
overlay = currentOverlay();
fragmentLength = FragmentKey.packFromState(fragment);
GLStateManager.getEffectiveBlendState(blend);
blendEnabled = GLStateManager.isEffectiveBlendEnabled();
@@ -71,11 +70,11 @@ public final class GlintCapture {
/**
* Base passes are only copied under the same parent pose. Light and overlay are recorded so the glint can draw the base instances in place when every part still carries them.
*/
boolean beginBase(RetainedTesrGroups groups) {
boolean beginBase(RetainedTesrGroups groups, int overlay) {
if (!open(groups)) return false;
parent.set(GLStateManager.getModelViewMatrix());
light = GLSMConfig.packedLastBrightness();
overlay = currentOverlay();
this.overlay = overlay;
base = true;
return true;
}
@@ -174,7 +173,7 @@ public final class GlintCapture {
boolean copyBase(ModelPartBatcher batcher, RetainedTesrGroups groups) {
if (!baseStillValid(groups) || EntityMaterials.fromCurrentState(false) != EntityMaterials.GLINT || !batcher.prepareArmorGlint()) return false;
final boolean inPlace = sameLightAndOverlay();
final boolean inPlace = sameLightAndOverlay(batcher.currentOverlay());
for (int i = 0; i < used; i++) {
final Range range = ranges.get(i);
batcher.copyArmorGlint(range.columns, range.start, range.end, inPlace);
@@ -184,7 +183,7 @@ public final class GlintCapture {
}
boolean queueBothLayers(ModelPartBatcher batcher, RetainedTesrGroups groups, ResourceLocation glintTexture) {
if (!baseStillValid(groups) || !sameLightAndOverlay() || !batcher.prepareSkippedArmorGlint(glintTexture)) return false;
if (!baseStillValid(groups) || !sameLightAndOverlay(batcher.currentOverlay()) || !batcher.prepareSkippedArmorGlint(glintTexture)) return false;
for (int i = 0; i < used; i++) {
final Range range = ranges.get(i);
batcher.queueArmorGlintLayers(range.columns, range.source, range.start, range.end);
@@ -202,16 +201,12 @@ public final class GlintCapture {
return true;
}
private boolean sameLightAndOverlay() {
return uniformLight && light == GLSMConfig.packedLastBrightness() && overlay == currentOverlay();
private boolean sameLightAndOverlay(int currentOverlay) {
return uniformLight && light == GLSMConfig.packedLastBrightness() && overlay == currentOverlay;
}
private static int currentColor() {
final var c = GLStateManager.getColor();
return AngelicaBufferSource.packAbgr(c.getRed(), c.getGreen(), c.getBlue(), c.getAlpha());
}
private static int currentOverlay() {
return AngelicaBufferSource.packAbgr(GLStateManager.getOverlayR(), GLStateManager.getOverlayG(), GLStateManager.getOverlayB(), GLStateManager.getOverlayA());
}
}
@@ -96,8 +96,7 @@ final class InstancedTemplateRenderer {
for (int j = 0, m = indices.size(); j < m; j++) {
final int i = indices.getInt(j);
final int color = run.source != null ? run.color : data.colors.getInt(i);
final long info = run.source != null ? 0L : data.infos.getLong(i);
InstancedAttribs.writeHead(ptr, data.matrices, i * 16, color, data.overlays.getInt(i), info);
InstancedAttribs.writeHead(ptr, data.matrices, i * 16, color, data.overlays.getInt(i), data.infos.getLong(i));
InstancedAttribs.writeLightmap(ptr + InstancedAttribs.OFFSET_LIGHTMAP, data.lights.getInt(i));
ptr += InstancedAttribs.STRIDE;
}
@@ -178,7 +177,7 @@ final class InstancedTemplateRenderer {
final int color = run.source != null ? run.color : data.colors.getInt(i);
final int light = data.lights.getInt(i);
final int overlay = data.overlays.getInt(i);
final long info = run.source != null ? 0L : data.infos.getLong(i);
final long info = data.infos.getLong(i);
for (int p = 0, n = partCubes.length; p < n; p++) {
final CubeParams cube = partCubes[p];
cube.writeRows(ptr, data.matrices, off, scale);
@@ -10,6 +10,8 @@ import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.glsm.DisplayListManager;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.StateSet;
import com.gtnewhorizons.angelica.glsm.hooks.BatchStateGuard;
import com.gtnewhorizons.angelica.glsm.ffp.CubeParams;
import com.gtnewhorizons.angelica.glsm.ffp.InstancedAttribs;
import com.gtnewhorizons.angelica.glsm.hooks.GLSMConfig;
@@ -33,15 +35,20 @@ import net.coderbot.iris.Iris;
import net.coderbot.iris.layer.GbufferPrograms;
import net.coderbot.iris.layer.PassOverride;
import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline;
import net.coderbot.iris.pipeline.WorldRenderingPhase;
import net.coderbot.iris.uniforms.CapturedRenderingState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.model.ModelBox;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.client.renderer.EntityRenderer;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.entity.Entity;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import net.minecraftforge.client.MinecraftForgeClient;
import org.joml.Matrix4f;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import java.util.Arrays;
import java.util.List;
@@ -75,10 +82,14 @@ public final class ModelPartBatcher {
private static final Tracy.ZoneId Z_ENTITY_LAYER_LOOP = Tracy.zoneId("entityLayerLoop", Tracy.COLOR_CLIENT);
private final AngelicaBufferSource bufferSource = new AngelicaBufferSource();
private final AngelicaBufferSource entitySource = new AngelicaBufferSource();
private final EntityShadowBatcher shadows = new EntityShadowBatcher();
private final RetainedTesrGroups groups = new RetainedTesrGroups(bufferSource);
private final RetainedTesrGroups entityGroups = new RetainedTesrGroups(entitySource);
private final RetainedTesrGroups shadowGroups = new RetainedTesrGroups(bufferSource);
private RetainedTesrGroups activeGroups = groups;
private AngelicaBufferSource activeSource = bufferSource;
private boolean entityTranslucentsHeld;
private boolean shadow;
private final AngelicaTesrMeshCache.GtnhMeshBackend captureBackend = new AngelicaTesrMeshCache.GtnhMeshBackend();
private final Matrix4f identity = new Matrix4f();
@@ -111,17 +122,18 @@ public final class ModelPartBatcher {
public long statArmorLoopSkips() { return armorLoopSkips; }
public long statArmorSectionSkips() { return armorSectionSkips; }
public long statLiveFallbacks() { return liveFallbacks; }
public long statInstancedDraws() { return groups.instancedDraws + shadowGroups.instancedDraws; }
public long statInstancedInstances() { return groups.instancedInstances + shadowGroups.instancedInstances; }
public long statCubeInstances() { return groups.cubeInstances + shadowGroups.cubeInstances; }
public long statRedrawnInstances() { return groups.redrawnInstances + shadowGroups.redrawnInstances; }
public long statTexMatrixRuns() { return groups.texMatrixRuns + shadowGroups.texMatrixRuns; }
public long statInstancedDraws() { return groups.instancedDraws + entityGroups.instancedDraws + shadowGroups.instancedDraws; }
public long statInstancedInstances() { return groups.instancedInstances + entityGroups.instancedInstances + shadowGroups.instancedInstances; }
public long statCubeInstances() { return groups.cubeInstances + entityGroups.cubeInstances + shadowGroups.cubeInstances; }
public long statRedrawnInstances() { return groups.redrawnInstances + entityGroups.redrawnInstances + shadowGroups.redrawnInstances; }
public long statTexMatrixRuns() { return groups.texMatrixRuns + entityGroups.texMatrixRuns + shadowGroups.texMatrixRuns; }
public long statBail(BailReason reason) { return bails[reason.ordinal()]; }
public long statShadowQuads() { return shadows.statQuads(); }
public long statShadowDraws() { return shadows.statDraws(); }
private void bail(BailReason reason) {
bails[reason.ordinal()]++;
BatchEligibility.onBail(reason);
}
private static final class PartTemplate {
@@ -143,13 +155,14 @@ public final class ModelPartBatcher {
int glintSlot;
int cull;
boolean lit;
boolean afterGlint;
boolean matches(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot, int cull, boolean lit) {
boolean matches(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot, int cull, boolean lit, boolean afterGlint) {
return this.texture == texture && this.material == material && pass.equals(this.pass) && this.offsetFactor == offsetFactor
&& this.offsetUnits == offsetUnits && this.glintSlot == glintSlot && this.cull == cull && this.lit == lit;
&& this.offsetUnits == offsetUnits && this.glintSlot == glintSlot && this.cull == cull && this.lit == lit && this.afterGlint == afterGlint;
}
LayerKey set(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot, int cull, boolean lit) {
LayerKey set(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot, int cull, boolean lit, boolean afterGlint) {
this.texture = texture;
this.material = material;
this.pass = pass;
@@ -158,6 +171,7 @@ public final class ModelPartBatcher {
this.glintSlot = glintSlot;
this.cull = cull;
this.lit = lit;
this.afterGlint = afterGlint;
return this;
}
@@ -168,7 +182,7 @@ public final class ModelPartBatcher {
&& Objects.equals(pass, other.pass)
&& Float.floatToIntBits(offsetFactor) == Float.floatToIntBits(other.offsetFactor)
&& Float.floatToIntBits(offsetUnits) == Float.floatToIntBits(other.offsetUnits)
&& glintSlot == other.glintSlot && cull == other.cull && lit == other.lit;
&& glintSlot == other.glintSlot && cull == other.cull && lit == other.lit && afterGlint == other.afterGlint;
}
@Override
@@ -179,6 +193,7 @@ public final class ModelPartBatcher {
h = h * 31 + glintSlot;
h = h * 31 + cull;
h = h * 31 + (lit ? 1 : 0);
h = h * 31 + (afterGlint ? 1 : 0);
return h;
}
}
@@ -213,6 +228,7 @@ public final class ModelPartBatcher {
}
public void begin(Mode mode, boolean shadow) {
BatchStateFallback.install();
this.mode = mode;
this.shadow = shadow;
instancedThisCycle = TesrBatchRenderer.instancedCapable();
@@ -222,39 +238,65 @@ public final class ModelPartBatcher {
shaderPipeline = null;
return;
}
final boolean entityPass = mode == Mode.ENTITIES && !shadow;
if (entityPass && entityTranslucentsHeld) {
discardHeldEntities();
}
active = true;
final long nowMs = System.currentTimeMillis();
mvCaptured = false;
texCaptured = false;
activeGroups = shadow ? shadowGroups : groups;
bufferSource.setIdKind(mode == Mode.ENTITIES ? AngelicaBufferSource.GroupIdKind.ENTITY : AngelicaBufferSource.GroupIdKind.BLOCK_ENTITY);
activeGroups = shadow ? shadowGroups : entityPass ? entityGroups : groups;
activeSource = entityPass ? entitySource : bufferSource;
activeSource.setIdKind(mode == Mode.ENTITIES ? AngelicaBufferSource.GroupIdKind.ENTITY : AngelicaBufferSource.GroupIdKind.BLOCK_ENTITY);
activeGroups.beginPass(identity, 0, 0, 0, instancedThisCycle ? TesrBatchRenderer.INSTANCE.instancedRenderer : null, shaderPipeline);
if (nowMs - lastSweepMs >= SWEEP_INTERVAL_MS) {
lastSweepMs = nowMs;
groups.sweep(nowMs);
entityGroups.sweep(nowMs);
shadowGroups.sweep(nowMs);
sweepTemplates(nowMs);
}
}
public void flush() {
BatchStateGuard.suspend();
try {
flushNow(true);
} finally {
BatchStateGuard.resume();
}
}
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);
}
private void flushNow(boolean allowHold) {
if (!active) return;
active = false;
final boolean hold = allowHold && mode == Mode.ENTITIES && !shadow && MinecraftForgeClient.getRenderPass() == 0
&& shaderPipeline != null && shaderPipeline.shouldSeparateEntityDraws();
if (shadow) {
drawBatches();
drawBatches(false);
} else {
final boolean inEntityLoop = mode == Mode.ENTITIES && Iris.enabled && GbufferPrograms.isEntityLoopActive();
final boolean wrapEntities = mode == Mode.ENTITIES && Iris.enabled && !inEntityLoop;
if (wrapEntities) GbufferPrograms.beginEntities();
else if (inEntityLoop) GbufferPrograms.onEntityRenderBoundary();
try {
shadows.flush(bufferSource);
drawBatches();
shadows.flush(activeSource);
drawBatches(hold);
} finally {
if (wrapEntities) GbufferPrograms.endEntities();
}
}
if (instancedThisCycle) {
if (instancedThisCycle && !hold) {
TesrBatchRenderer.INSTANCE.instancedRenderer.endFrame();
}
if (!TesrBatchRenderer.INSTANCE.hasPendingGeometry()) {
@@ -262,26 +304,87 @@ public final class ModelPartBatcher {
}
}
private void drawBatches() {
private void drawBatches(boolean hold) {
if (Tracy.ENABLED) Tracy.beginZone(Z_ENTITY_LAYER_LOOP);
try {
bufferSource.endBatchWithType(TransparencyType.OPAQUE, activeGroups);
bufferSource.endBatch(activeGroups);
activeSource.endBatchWithType(TransparencyType.OPAQUE, activeGroups);
if (hold) {
activeSource.endBatchWithType(TransparencyType.WATER_MASK, activeGroups);
activeSource.pauseBatch();
entityTranslucentsHeld = true;
} else {
activeSource.endBatch(activeGroups);
}
} finally {
if (Tracy.ENABLED) Tracy.endZone();
}
}
public void flushEntitiesAfterDeferred() {
if (!entityTranslucentsHeld) return;
entityTranslucentsHeld = false;
BatchStateGuard.suspend();
try {
final EntityRenderer entityRenderer = Minecraft.getMinecraft().entityRenderer;
final int deferredDepth = GLStateManager.pushState(StateSet.BATCH);
try {
GLStateManager.glDepthMask(true);
GLStateManager.enableDepthTest();
GLStateManager.enableBlend();
GLStateManager.defaultBlendFunc();
entityRenderer.enableLightmap(0);
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
GLStateManager.glEnable(GL11.GL_TEXTURE_2D);
final boolean wrap = Iris.enabled && GbufferPrograms.getCurrentPhase() == WorldRenderingPhase.NONE;
if (wrap) GbufferPrograms.beginEntities();
try {
entitySource.endBatch(entityGroups);
if (instancedThisCycle) {
TesrBatchRenderer.INSTANCE.instancedRenderer.endFrame();
}
AngelicaBufferSource.rebindPass();
} finally {
if (wrap) GbufferPrograms.endEntities();
entityRenderer.disableLightmap(0);
}
} finally {
GLStateManager.popStateTo(deferredDepth);
}
} finally {
if (Tracy.ENABLED) Tracy.endZone();
BatchStateGuard.resume();
}
}
private void discardHeldEntities() {
entityTranslucentsHeld = false;
entitySource.discard();
}
public boolean isActive() {
return active;
}
boolean hasHeldEntities() {
return entityTranslucentsHeld;
}
boolean hasQueuedGeometry() {
return active && (activeSource.hasPendingLayers() || shadows.hasPendingGeometry());
}
public boolean beginGlintCapture(GlintCapture capture) {
return canCaptureGlint() && capture.begin(activeGroups);
}
public boolean canCaptureGlint() {
return active && instancedThisCycle && shaderPipeline == null && !shadow && BatchEligibility.batchingAllowed() && GLStateManager.getActiveProgram() == 0 && !GLStateManager.isRecordingDisplayList();
return shaderPipeline == null && canQueueGlint();
}
/** Skipped glint blocks queue each layer as its own instanced draw, so a shader pack only needs its pass program current. */
public boolean canQueueGlint() {
return active && instancedThisCycle && !shadow && BatchEligibility.batchingAllowed() && !GLStateManager.isRecordingDisplayList()
&& GLStateManager.getActiveProgram() == (shaderPipeline != null ? shaderPipeline.getActivePassProgramId() : 0);
}
public boolean replayGlint(GlintCapture capture) {
@@ -304,7 +407,7 @@ public final class ModelPartBatcher {
}
public boolean beginArmorCapture(GlintCapture capture) {
return canCaptureGlint() && capture.beginBase(activeGroups);
return canQueueGlint() && capture.beginBase(activeGroups, currentOverlay());
}
public boolean reuseArmorBase(GlintCapture base, GlintCapture glint) {
@@ -324,7 +427,7 @@ public final class ModelPartBatcher {
}
public boolean queueSkippedArmorGlint(GlintCapture base, ResourceLocation glintTexture) {
if (!canCaptureGlint() || GLStateManager.getActiveTextureUnit() != 0 || !GLStateManager.getTextures().getTextureUnitStates(0).isEnabled() || !base.queueBothLayers(this, activeGroups, glintTexture)) return false;
if (!canQueueGlint() || GLStateManager.getActiveTextureUnit() != 0 || !GLStateManager.getTextures().getTextureUnitStates(0).isEnabled() || !base.queueBothLayers(this, activeGroups, glintTexture)) return false;
armorBaseReuses++;
glintPassReuses++;
armorSectionSkips++;
@@ -333,12 +436,13 @@ public final class ModelPartBatcher {
}
public boolean queueSkippedHeldGlint(TemplateBuffer template) {
if (!canCaptureGlint() || GLStateManager.getActiveTextureUnit() != 0 || !activeGroups.canCopyInstances(EntityMaterials.ITEM_GLINT) || !MatrixHelper.isIdentity(GLStateManager.getTextures().getTextureUnitMatrix(0))) return false;
if (!canQueueGlint() || GLStateManager.getActiveTextureUnit() != 0 || !activeGroups.canCopyInstances(EntityMaterials.ITEM_GLINT) || !MatrixHelper.isIdentity(GLStateManager.getTextures().getTextureUnitMatrix(0))) return false;
final boolean offset = GLStateManager.glIsEnabled(GL11.GL_POLYGON_OFFSET_FILL);
final PolygonState polygon = GLStateManager.getPolygonState();
final int cullCode = EntityMaterials.ITEM_GLINT.isNoCull() ? DrawState.DISABLED : DrawState.liveCull();
final RenderLayer layer = layerFor(HeldItemGlint.texture(), EntityMaterials.ITEM_GLINT, PassOverride.NONE, offset ? polygon.getOffsetFactor() : 0, offset ? polygon.getOffsetUnits() : 0, ShaderGlint.NO_TINT, cullCode, false);
activeGroups.queueGlintLayers(template, layer, EntityMaterials.ITEM_GLINT, currentModelView(), GLSMConfig.packedLastBrightness(), VANILLA_GLINT_COLOR, currentOverlay(), HeldItemGlint.firstMatrix(), HeldItemGlint.secondMatrix());
activeGroups.queueGlintLayers(template, layer, EntityMaterials.ITEM_GLINT, currentModelView(), GLSMConfig.packedLastBrightness(), VANILLA_GLINT_COLOR, currentOverlay(), currentEntityInfo(0),
HeldItemGlint.firstMatrix(), HeldItemGlint.secondMatrix());
parts++;
glintPassReuses++;
return true;
@@ -354,8 +458,13 @@ public final class ModelPartBatcher {
return modelView;
}
private static int currentOverlay() {
return AngelicaBufferSource.packAbgr(GLStateManager.getOverlayR(), GLStateManager.getOverlayG(), GLStateManager.getOverlayB(), GLStateManager.getOverlayA());
private long currentEntityInfo(int item) {
return shaderPipeline != null ? InstancedAttribs.packEntityInfo(CapturedRenderingState.INSTANCE.getCurrentRenderedEntity(), CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity(), item) : 0L;
}
int currentOverlay() {
return shaderPipeline != null ? AngelicaBufferSource.packEntityColor(CapturedRenderingState.INSTANCE.getCurrentEntityColor())
: AngelicaBufferSource.packAbgr(GLStateManager.getOverlayR(), GLStateManager.getOverlayG(), GLStateManager.getOverlayB(), GLStateManager.getOverlayA());
}
boolean prepareArmorGlint() {
@@ -438,14 +547,22 @@ public final class ModelPartBatcher {
if (shadow && isDepthEqualDecalState()) {
return true;
}
return queueTemplate(entry.template, entry.cubes, scale, null);
return queueTemplate(entry.template, entry.cubes, scale, null, false);
}
public boolean queueTemplate(TemplateBuffer template, TesrMaterial material) {
return queueTemplate(template, null, 1.0f, material);
return queueTemplate(template, null, 1.0f, material, false);
}
private boolean queueTemplate(TemplateBuffer template, CubeParams[] cubes, float scale, TesrMaterial explicitMaterial) {
public boolean queueTemplate(TemplateBuffer template, TesrMaterial material, boolean afterGlint) {
return queueTemplate(template, null, 1.0f, material, afterGlint);
}
private boolean queueTemplate(TemplateBuffer template, CubeParams[] cubes, float scale, TesrMaterial explicitMaterial, boolean afterGlint) {
if (!active) {
bail(BailReason.INACTIVE);
return false;
}
if (shaderPipeline != null && GLStateManager.getActiveProgram() != shaderPipeline.getActivePassProgramId()) {
bail(BailReason.FOREIGN_PROGRAM);
return false;
@@ -488,15 +605,13 @@ public final class ModelPartBatcher {
final int glintSlot = material.special() == TesrMaterial.SpecialRender.GLINT ? lastBoundGlintSlot : ShaderGlint.NO_TINT;
final int cullCode = material.isNoCull() ? DrawState.DISABLED : DrawState.liveCull();
final boolean lit = DrawState.liveLit(material);
final RenderLayer layer = layerFor(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cullCode, lit);
final RenderLayer layer = layerFor(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cullCode, lit, afterGlint);
// Entities nested inside a TESR (mob spawner, OpenBlocks trophy) run in the block entity pass but carry an entity id
final int entityId = groupId(shaderPipeline != null, mode == Mode.ENTITIES || pass.isEntityPhase(), CapturedRenderingState.INSTANCE.getCurrentRenderedEntity(), CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity());
final Color4 color = GLStateManager.getColor();
final int colorABGR = AngelicaBufferSource.packAbgr(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());
final int overlayABGR = shaderPipeline != null ? AngelicaBufferSource.packEntityColor(CapturedRenderingState.INSTANCE.getCurrentEntityColor())
: AngelicaBufferSource.packAbgr(GLStateManager.getOverlayR(), GLStateManager.getOverlayG(), GLStateManager.getOverlayB(), GLStateManager.getOverlayA());
final long entityInfo = shaderPipeline != null ? InstancedAttribs.packEntityInfo(CapturedRenderingState.INSTANCE.getCurrentRenderedEntity(),
CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity(), CapturedRenderingState.INSTANCE.getCurrentRenderedItem()) : 0L;
final int overlayABGR = currentOverlay();
final long entityInfo = currentEntityInfo(CapturedRenderingState.INSTANCE.getCurrentRenderedItem());
final int packedLight = GLSMConfig.packedLastBrightness();
activeGroups.queue(template, cubes, scale, layer, material, currentModelView(), packedLight, colorABGR, overlayABGR, entityInfo, entityId, texMatrix);
parts++;
@@ -591,19 +706,23 @@ public final class ModelPartBatcher {
}
private RenderLayer layerFor(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot, int cullCode, boolean lit) {
return layerFor(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cullCode, lit, false);
}
private RenderLayer layerFor(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot, int cullCode, boolean lit, boolean afterGlint) {
for (int i = 0; i < RECENT_LAYERS; i++) {
final RenderLayer recent = recentLayers[i];
if (recent != null && recentKeys[i].matches(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cullCode, lit)) {
if (recent != null && recentKeys[i].matches(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cullCode, lit, afterGlint)) {
return lastLayer = recent;
}
}
RenderLayer layer = layers.get(scratchKey.set(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cullCode, lit));
RenderLayer layer = layers.get(scratchKey.set(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cullCode, lit, afterGlint));
if (layer == null) {
layer = RenderLayer.tesr(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cullCode, lit);
layers.put(new LayerKey().set(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cullCode, lit), layer);
layer = RenderLayer.tesr(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cullCode, lit, afterGlint);
layers.put(new LayerKey().set(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cullCode, lit, afterGlint), layer);
}
if (recentKeys[recentNext] == null) recentKeys[recentNext] = new LayerKey();
recentKeys[recentNext].set(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cullCode, lit);
recentKeys[recentNext].set(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cullCode, lit, afterGlint);
recentLayers[recentNext] = layer;
recentNext = (recentNext + 1) % RECENT_LAYERS;
return lastLayer = layer;
@@ -622,14 +741,20 @@ public final class ModelPartBatcher {
public void clear() {
shadows.reset();
groups.clear();
entityGroups.clear();
shadowGroups.clear();
templates.clear();
entitySource.discard();
bufferSource.discard();
bufferSource.freeBuffers();
entitySource.freeBuffers();
activeGroups = groups;
activeSource = bufferSource;
entityTranslucentsHeld = false;
active = false;
shaderPipeline = null;
layers.clear();
scratchKey.set(null, null, null, 0.0f, 0.0f, ShaderGlint.NO_TINT, DrawState.DISABLED, false);
scratchKey.set(null, null, null, 0.0f, 0.0f, ShaderGlint.NO_TINT, DrawState.DISABLED, false, false);
Arrays.fill(recentLayers, null);
recentNext = 0;
lastLayer = null;
@@ -638,7 +763,7 @@ public final class ModelPartBatcher {
}
public String getDebugString() {
final String line = String.format("Parts: %d grp, inst %d, live %d", groups.groupCount() + shadowGroups.groupCount(), parts - lastParts, liveFallbacks - lastLiveFallbacks);
final String line = String.format("Parts: %d grp, inst %d, live %d", groups.groupCount() + entityGroups.groupCount() + shadowGroups.groupCount(), parts - lastParts, liveFallbacks - lastLiveFallbacks);
lastParts = parts;
lastLiveFallbacks = liveFallbacks;
return line;
@@ -4,12 +4,13 @@ import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
import com.gtnewhorizons.angelica.api.tesr.TesrMaterial;
import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.ffp.InstancedAttribs;
import com.gtnewhorizons.angelica.glsm.ffp.CubeParams;
import com.gtnewhorizons.angelica.glsm.ffp.CombinedGlint;
import com.gtnewhorizons.angelica.glsm.ffp.Instancing;
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
import it.unimi.dsi.fastutil.floats.FloatArrayList;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.longs.LongArrayList;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
@@ -181,7 +182,9 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
boolean anchored;
long frameMark = -1;
long lastUsedMs;
int entityColor;
final int entityColor;
final int itemId;
final DrawStateKey state;
final InstanceColumns templateColumns = new InstanceColumns();
final InstanceColumns cubeColumns = new InstanceColumns();
@@ -334,10 +337,13 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
runPoolUsed = 0;
}
Group(RenderLayer layer, TesrMaterial material, int blockEntityId) {
Group(RenderLayer layer, TesrMaterial material, int blockEntityId, DrawStateKey state) {
this.layer = layer;
this.material = material;
this.blockEntityId = blockEntityId;
this.state = state;
this.itemId = state.item;
this.entityColor = state.color;
this.opaque = material.transparency() == TesrMaterial.Transparency.OPAQUE;
this.stream = material.isStream();
this.mergeRuns = material.isDepthEqual() && material.isNoDepthWrite();
@@ -345,7 +351,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
}
}
private final Reference2ObjectOpenHashMap<RenderLayer, Reference2ObjectOpenHashMap<TesrMaterial, Int2ObjectOpenHashMap<Group>>> groups = new Reference2ObjectOpenHashMap<>();
private final Reference2ObjectOpenHashMap<RenderLayer, Reference2ObjectOpenHashMap<TesrMaterial, Object2ObjectOpenHashMap<DrawStateKey, Group>>> groups = new Reference2ObjectOpenHashMap<>();
private final Reference2ObjectOpenHashMap<RenderLayer, ObjectArrayList<Group>> byLayer = new Reference2ObjectOpenHashMap<>();
private static final int RECENT_GROUPS = 4;
private final Group[] recentGroups = new Group[RECENT_GROUPS];
@@ -389,32 +395,66 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
long captureVersion() { return frameMark; }
/** 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;
DrawStateKey set(int entity, int block, int item, int color) {
this.entity = entity;
this.block = block;
this.item = item;
this.color = color;
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;
}
@Override
public boolean equals(Object other) {
return other instanceof DrawStateKey key && matches(key.entity, key.block, key.item, key.color);
}
@Override
public int hashCode() { return ((entity * 31 + block) * 31 + item) * 31 + color; }
}
private final DrawStateKey lookupState = new DrawStateKey();
private Group groupFor(RenderLayer layer, TesrMaterial material, int id) {
final int key = instanceableMaterial(material) ? 0 : id;
final boolean perInstance = instanceableMaterial(material);
final boolean entityKind = !perInstance && source.effectiveIdKind() == AngelicaBufferSource.GroupIdKind.ENTITY;
final CapturedRenderingState captured = CapturedRenderingState.INSTANCE;
final int entity = perInstance ? 0 : entityKind ? id : captured.getCurrentRenderedEntity();
final int block = perInstance ? 0 : entityKind ? captured.getCurrentRenderedBlockEntity() : id;
final int item = perInstance ? 0 : captured.getCurrentRenderedItem();
final int color = perInstance ? 0 : AngelicaBufferSource.packEntityColor(captured.getCurrentEntityColor());
Group group = null;
for (int i = 0; i < RECENT_GROUPS; i++) {
final Group recent = recentGroups[i];
if (recent != null && recent.layer == layer && recent.material == material && recent.blockEntityId == key) {
if (recent != null && recent.layer == layer && recent.material == material && recent.state.matches(entity, block, item, color)) {
group = recent;
break;
}
}
if (group == null) {
Reference2ObjectOpenHashMap<TesrMaterial, Int2ObjectOpenHashMap<Group>> byMaterial = groups.get(layer);
Reference2ObjectOpenHashMap<TesrMaterial, Object2ObjectOpenHashMap<DrawStateKey, Group>> byMaterial = groups.get(layer);
if (byMaterial == null) {
byMaterial = new Reference2ObjectOpenHashMap<>();
groups.put(layer, byMaterial);
}
Int2ObjectOpenHashMap<Group> byId = byMaterial.get(material);
if (byId == null) {
byId = new Int2ObjectOpenHashMap<>();
byMaterial.put(material, byId);
Object2ObjectOpenHashMap<DrawStateKey, Group> byState = byMaterial.get(material);
if (byState == null) {
byState = new Object2ObjectOpenHashMap<>();
byMaterial.put(material, byState);
}
group = byId.get(key);
group = byState.get(lookupState.set(entity, block, item, color));
if (group == null) {
group = new Group(layer, material, key);
final DrawStateKey key = new DrawStateKey().set(entity, block, item, color);
group = new Group(layer, material, perInstance ? 0 : id, key);
group.lastUsedMs = nowMs;
byId.put(key, group);
byState.put(key, group);
byLayer.computeIfAbsent(layer, l -> new ObjectArrayList<>()).add(group);
}
recentGroups[recentGroupNext] = group;
@@ -533,13 +573,13 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
dst.referencedParts += end - start;
}
void queueGlintLayers(TemplateBuffer template, RenderLayer layer, TesrMaterial material, Matrix4f currentMV, int packedLight, int colorABGR, int overlayABGR, Matrix4f first, Matrix4f second) {
void queueGlintLayers(TemplateBuffer template, RenderLayer layer, TesrMaterial material, Matrix4f currentMV, int packedLight, int colorABGR, int overlayABGR, long entityInfo, Matrix4f first, Matrix4f second) {
final Group group = groupFor(layer, material, 0);
touch(group, layer);
final InstanceColumns dst = group.templateColumns;
final int index = dst.size;
final TexRun run = group.openOrExtendRun(dst, first, true, false);
dst.add(template, currentMV, packedLight, colorABGR, overlayABGR, 0L);
dst.add(template, currentMV, packedLight, colorABGR, overlayABGR, entityInfo);
run.last.end = dst.size;
run.parts++;
run.instances++;
@@ -576,7 +616,6 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
}
group.frameMark = frameMark;
group.lastUsedMs = nowMs;
group.entityColor = AngelicaBufferSource.packEntityColor(CapturedRenderingState.INSTANCE.getCurrentEntityColor());
group.hashAcc = 0;
group.clearInstances();
if (!group.anchored || TesrAnchorMath.shouldReanchor(camX, camY, camZ, group.anchorX, group.anchorY, group.anchorZ)) {
@@ -677,7 +716,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
if (!live(group) || !instanceable(group)) continue;
if (group.templateColumns.hasInstances()) {
final boolean fixedFunction = deferred == null && GLStateManager.getActiveProgram() == 0;
drawTemplateRuns(group.templateColumns, group.material.special() == TesrMaterial.SpecialRender.GLINT && fixedFunction, group.material == EntityMaterials.ITEM_GLINT && fixedFunction);
drawTemplateRuns(group.templateColumns, group.material.special() == TesrMaterial.SpecialRender.GLINT && fixedFunction, group.material == EntityMaterials.ITEM_GLINT);
}
if (!cubeAvailable && group.cubeColumns.hasInstances()) {
drawTemplateRuns(group.cubeColumns, group.material == EntityMaterials.GLINT && deferred == null, false);
@@ -810,15 +849,15 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
private static final Matrix4f IDENTITY = new Matrix4f();
static int entityFromInfo(long info) {
return (short) info;
return InstancedAttribs.unpackId(info, 0);
}
static int blockEntityFromInfo(long info) {
return (short) (info >>> 16);
return InstancedAttribs.unpackId(info, 16);
}
private int idFromInfo(long info) {
return source.effectiveIdKind() == AngelicaBufferSource.GroupIdKind.ENTITY ? entityFromInfo(info) : blockEntityFromInfo(info);
static int itemFromInfo(long info) {
return InstancedAttribs.unpackId(info, 32);
}
private void drawInstancesCpu(Group group, InstanceColumns cols) {
@@ -834,14 +873,14 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
final int runEnd = seg.end;
int sub = seg.start;
while (sub < runEnd) {
final long info = head.source != null ? 0L : data.infos.getLong(sub);
final long info = data.infos.getLong(sub);
final int overlay = data.overlays.getInt(sub);
int subEnd = sub;
while (subEnd < runEnd && (head.source != null || data.infos.getLong(subEnd) == info) && data.overlays.getInt(subEnd) == overlay) {
while (subEnd < runEnd && data.infos.getLong(subEnd) == info && data.overlays.getInt(subEnd) == overlay) {
subEnd++;
}
source.applyIdsAndRebind(entityFromInfo(info), blockEntityFromInfo(info), itemFromInfo(info));
AngelicaBufferSource.setEntityColor(overlay);
source.applyIdAndRebind(idFromInfo(info));
int start = sub;
while (start < subEnd) {
final int drawMode = templates.get(start).drawMode;
@@ -895,11 +934,11 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
if (now - group.lastUsedMs <= GROUP_TTL_MS) continue;
group.mesh.delete();
list.remove(i);
final Reference2ObjectOpenHashMap<TesrMaterial, Int2ObjectOpenHashMap<Group>> byMaterial = groups.get(group.layer);
final Reference2ObjectOpenHashMap<TesrMaterial, Object2ObjectOpenHashMap<DrawStateKey, Group>> byMaterial = groups.get(group.layer);
if (byMaterial != null) {
final Int2ObjectOpenHashMap<Group> byId = byMaterial.get(group.material);
final Object2ObjectOpenHashMap<DrawStateKey, Group> byId = byMaterial.get(group.material);
if (byId != null) {
byId.remove(group.blockEntityId);
byId.remove(group.state);
}
}
}
@@ -1020,8 +1059,8 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
private void draw(Group group) {
retainedDraws++;
source.applyIdsAndRebind(group.state.entity, group.state.block, group.state.item);
AngelicaBufferSource.setEntityColor(group.entityColor);
source.applyIdAndRebind(group.blockEntityId);
drawMV.set(baseMV).translate((float) (group.anchorX - camX), (float) (group.anchorY - camY), (float) (group.anchorZ - camZ));
saveMV();
GLStateManager.setModelViewMatrix(drawMV);
@@ -8,6 +8,7 @@ import com.gtnewhorizons.angelica.api.tesr.TesrShader;
import com.gtnewhorizons.angelica.client.font.BatchingFontRenderer;
import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.hooks.BatchStateGuard;
import com.gtnewhorizons.angelica.glsm.StateSet;
import com.gtnewhorizons.angelica.glsm.ffp.InstancedAttribs;
import com.gtnewhorizons.angelica.glsm.ffp.Instancing;
@@ -82,6 +83,7 @@ public final class TesrBatchRenderer {
}
public void beginPass(int passKey, Matrix4f baseMV, double camX, double camY, double camZ) {
BatchStateFallback.install();
if (deferredFlushPending) {
discardDeferred();
}
@@ -158,6 +160,10 @@ public final class TesrBatchRenderer {
return activePass >= 0 || deferredFlushPending;
}
boolean hasQueuedGeometry() {
return hasPendingGeometry() && bufferSource.hasPendingLayers();
}
public void queue(TemplateBuffer template, ResourceLocation texture, TesrMaterial material) {
modelView.set(GLStateManager.getModelViewMatrix());
final int packedLight = currentPackedLight(material);
@@ -174,7 +180,8 @@ public final class TesrBatchRenderer {
? CapturedRenderingState.INSTANCE.getCurrentRenderedEntity()
: CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity();
final long entityInfo = InstancedAttribs.packEntityInfo(CapturedRenderingState.INSTANCE.getCurrentRenderedEntity(), CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity(), CapturedRenderingState.INSTANCE.getCurrentRenderedItem());
retained[activePass].queue(template, layer, material, modelView, packedLight, colorABGR, 0, entityInfo, blockEntityId, captureTextureMatrix());
retained[activePass].queue(template, layer, material, modelView, packedLight, colorABGR,
AngelicaBufferSource.packEntityColor(CapturedRenderingState.INSTANCE.getCurrentEntityColor()), entityInfo, blockEntityId, captureTextureMatrix());
} else {
drawImmediate(template, texture, material, packedLight, colorABGR);
}
@@ -337,6 +344,26 @@ public final class TesrBatchRenderer {
}
public void flush() {
BatchStateGuard.suspend();
try {
flushNow();
} finally {
BatchStateGuard.resume();
}
}
void flushForStateChange() {
final RetainedTesrGroups hook = activePass >= 0 ? retained[activePass] : pendingDeferredHook;
if (!hasPendingGeometry()) return;
activePass = -1;
deferredFlushPending = false;
pendingDeferredHook = null;
bufferSource.endBatch(hook);
instancedRenderer.endFrame();
BatchingFontRenderer.flushDeferredText();
}
private void flushNow() {
final RetainedTesrGroups hook = activePass >= 0 ? retained[activePass] : null;
if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_OPAQUE);
try {
@@ -373,6 +400,15 @@ public final class TesrBatchRenderer {
}
public void flushAfterDeferred() {
BatchStateGuard.suspend();
try {
flushAfterDeferredNow();
} finally {
BatchStateGuard.resume();
}
}
private void flushAfterDeferredNow() {
if (!deferredFlushPending) return;
deferredFlushPending = false;
final RetainedTesrGroups hook = pendingDeferredHook;
@@ -29,12 +29,16 @@ public final class TesrProviderDispatch {
final Object key = provider.angelica$meshKey(te);
if (key == null) return false;
CapturedRenderingState.INSTANCE.setCurrentBlockEntity(resolveBlockEntityId(te));
CapturedRenderingState.INSTANCE.pushCurrentBlockEntity();
CapturedRenderingState.INSTANCE.setCurrentBlockEntity(te == null ? null : te.getBlockType(), te == null ? 0 : te.getBlockMetadata());
GLStateManager.glPushMatrix();
provider.angelica$transform(te, x, y, z);
AngelicaTesrMeshCache.INSTANCE.renderCached(key, provider.angelica$meshDirty(te), provider, te);
GLStateManager.glPopMatrix();
CapturedRenderingState.INSTANCE.setCurrentBlockEntity(0);
try {
provider.angelica$transform(te, x, y, z);
AngelicaTesrMeshCache.INSTANCE.renderCached(key, provider.angelica$meshDirty(te), provider, te);
} finally {
GLStateManager.glPopMatrix();
CapturedRenderingState.INSTANCE.popCurrentBlockEntity();
}
return true;
}
}
@@ -3,6 +3,7 @@ package com.gtnewhorizons.angelica.shadercompat;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks;
import com.gtnewhorizons.angelica.glsm.hooks.GlintColorHandler;
import com.gtnewhorizons.angelica.iris.IrisDisplayListState;
import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher;
import it.unimi.dsi.fastutil.ints.Int2IntLinkedOpenHashMap;
import net.coderbot.iris.pipeline.ShadowRenderer;
@@ -57,12 +58,14 @@ public final class ShaderGlint {
private ShaderGlint() {}
public static void beginGlint() {
if (ShadowRenderer.ACTIVE || !IrisApi.getInstance().isShaderPackInUse()) return;
IrisDisplayListState.recordGlintSpan(true);
// If a glint span is already active, keep the outer span's saved state and
// let the nested render ride on its handler.
if (depth++ > 0) return;
if (ShadowRenderer.ACTIVE || !IrisApi.getInstance().isShaderPackInUse()) return;
swapped = false;
injecting = false;
@@ -74,6 +77,7 @@ public final class ShaderGlint {
}
public static void endGlint() {
IrisDisplayListState.recordGlintSpan(false);
if (depth == 0 || --depth > 0) return;
if (GLSMHooks.glintColorHandler != COLOR_HANDLER) return;
GLSMHooks.glintColorHandler = null;
@@ -2,8 +2,11 @@ package com.gtnewhorizons.angelica.utils;
import java.util.ArrayDeque;
import com.gtnewhorizons.angelica.glsm.DisplayListManager;
import com.gtnewhorizons.angelica.glsm.recording.commands.DisplayListCommand;
import com.gtnewhorizons.angelica.mixins.interfaces.IPatchedTextureAtlasSprite;
import com.gtnewhorizons.angelica.mixins.interfaces.ITexturesCache;
import it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.texture.TextureMap;
@@ -12,6 +15,49 @@ import net.minecraft.world.IBlockAccess;
public class AnimationsRenderUtils {
private static final ThreadLocal<SpriteCapture> SPRITE_CAPTURE = new ThreadLocal<>();
/** Collects visibility notifications while baking a mesh, for replay when that mesh is reused. */
public static final class SpriteCapture implements AutoCloseable {
private final ReferenceOpenHashSet<IPatchedTextureAtlasSprite> sprites = new ReferenceOpenHashSet<>();
private SpriteCapture parent;
private SpriteCapture() {
parent = SPRITE_CAPTURE.get();
SPRITE_CAPTURE.set(this);
}
public void markUsed() {
for (IPatchedTextureAtlasSprite sprite : sprites) sprite.angelica$markNeedsAnimationUpdate();
}
@Override
public void close() {
SPRITE_CAPTURE.set(parent);
if (parent != null) parent.sprites.addAll(sprites);
parent = null;
}
}
public static SpriteCapture captureSprites() {
return new SpriteCapture();
}
public static void recordSpriteUsage(IPatchedTextureAtlasSprite sprite) {
final SpriteCapture capture = SPRITE_CAPTURE.get();
if (capture != null) capture.sprites.add(sprite);
if (DisplayListManager.isRecording()) {
DisplayListManager.recordStateCommandOnce(new SpriteUsage(sprite));
}
}
private record SpriteUsage(IPatchedTextureAtlasSprite sprite) implements DisplayListCommand {
@Override
public void execute() {
sprite.angelica$markNeedsAnimationUpdate();
}
}
public static void markBlockTextureForUpdate(IIcon icon) {
markBlockTextureForUpdate(icon, null);
}
@@ -26,7 +72,7 @@ public class AnimationsRenderUtils {
if (blockAccess instanceof ITexturesCache texturesCache) {
texturesCache.getRenderedTextures().add(textureAtlasSprite);
} else if(textureAtlasSprite instanceof IPatchedTextureAtlasSprite patchedSprite){
patchedSprite.markNeedsAnimationUpdate();
patchedSprite.angelica$markNeedsAnimationUpdate();
}
}
}
@@ -38,7 +84,7 @@ public class AnimationsRenderUtils {
if (stack == null || stack.isEmpty()) {
// icon was used outside of chunk building, it's probably an item in an inventory or something
sprite.markNeedsAnimationUpdate();
sprite.angelica$markNeedsAnimationUpdate();
return;
}
@@ -43,7 +43,7 @@ public class AngelicaBufferSource implements Groupable {
private boolean prepared;
private final List<RenderLayer> order = new ArrayList<>();
private int drawStateDepth = -1;
private boolean anyIdSet;
private boolean irisStateSaved;
private GroupIdKind idKind = GroupIdKind.BLOCK_ENTITY;
public AngelicaBufferSource() {
@@ -65,7 +65,7 @@ public class AngelicaBufferSource implements Groupable {
affinities.put(type, affinity);
}
final SegmentedBufferBuilder builder = builders[affinity];
builder.begin(type, blockEntityId);
builder.begin(type, blockEntityId, effectiveIdKind() == GroupIdKind.ENTITY);
return builder;
}
@@ -73,6 +73,10 @@ public class AngelicaBufferSource implements Groupable {
renderOrderManager.begin(type);
}
public boolean hasPendingLayers() {
return prepared ? !order.isEmpty() : !renderOrderManager.getRenderOrder().isEmpty();
}
public boolean isEmpty() {
for (SegmentedBufferBuilder builder : builders) {
if (!builder.isEmpty()) return false;
@@ -112,7 +116,6 @@ public class AngelicaBufferSource implements Groupable {
}
}
affinities.clear();
anyIdSet = false;
}
List<RenderLayer> prepare() {
@@ -148,9 +151,16 @@ public class AngelicaBufferSource implements Groupable {
public void endBatch(LayerDrawHook hook) {
ensurePrepared();
try {
int lastGlint = -1;
for (int i = 0, n = order.size(); i < n; i++) {
drawLayer(order.get(i), hook);
if (getTransparencyType(order.get(i)) == TransparencyType.DECAL) lastGlint = i;
}
for (int i = 0, n = order.size(); i < n; i++) {
final RenderLayer layer = order.get(i);
if (getTransparencyType(layer) != TransparencyType.AFTER_GLINT) drawLayer(layer, hook);
if (i == lastGlint) drawAfterGlintLayers(hook);
}
if (lastGlint < 0) drawAfterGlintLayers(hook);
} catch (Throwable t) {
discardAfterFailure(t);
throw t;
@@ -159,9 +169,16 @@ public class AngelicaBufferSource implements Groupable {
finish();
}
private void drawAfterGlintLayers(LayerDrawHook hook) {
for (int i = 0, n = order.size(); i < n; i++) {
final RenderLayer layer = order.get(i);
if (getTransparencyType(layer) == TransparencyType.AFTER_GLINT) drawLayer(layer, hook);
}
}
public void pauseBatch() {
restoreDrawState();
clearCurrentId();
restoreIrisState();
}
public void discard() {
@@ -176,13 +193,20 @@ public class AngelicaBufferSource implements Groupable {
}
}
private void clearCurrentId() {
if (!anyIdSet) return;
// A pass can set either kind: nested entities inside a TESR write the entity id during a block entity pass
CapturedRenderingState.INSTANCE.setCurrentEntityAndItem(-1, 0);
CapturedRenderingState.INSTANCE.setCurrentEntityColor(0f, 0f, 0f, 0f);
CapturedRenderingState.INSTANCE.setCurrentBlockEntity(0);
anyIdSet = false;
private void restoreIrisState() {
if (!irisStateSaved) return;
CapturedRenderingState.INSTANCE.popCurrentEntityColor();
CapturedRenderingState.INSTANCE.popCurrentBlockEntity();
CapturedRenderingState.INSTANCE.popCurrentEntityAndItem();
irisStateSaved = false;
}
private void saveIrisState() {
if (irisStateSaved) return;
CapturedRenderingState.INSTANCE.pushCurrentEntityAndItem();
CapturedRenderingState.INSTANCE.pushCurrentBlockEntity();
CapturedRenderingState.INSTANCE.pushCurrentEntityColor();
irisStateSaved = true;
}
public GroupIdKind effectiveIdKind() {
@@ -198,6 +222,7 @@ public class AngelicaBufferSource implements Groupable {
drawStateDepth = GLStateManager.pushState(StateSet.BATCH);
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
}
saveIrisState();
layer.startDrawing();
Throwable failure = null;
try {
@@ -205,7 +230,6 @@ public class AngelicaBufferSource implements Groupable {
drawDynamic(segments);
}
if (hasRetained) {
anyIdSet = true;
hook.drawLayer(layer);
}
} catch (Throwable t) {
@@ -221,7 +245,6 @@ public class AngelicaBufferSource implements Groupable {
}
private void drawDynamic(List<BufferSegment> segments) {
anyIdSet = true;
boolean matrixPushed = false;
SegmentedBufferBuilder.LayerBuffer bound = null;
boolean boundSetup = false;
@@ -230,20 +253,24 @@ public class AngelicaBufferSource implements Groupable {
GLStateManager.glPushMatrix();
matrixPushed = true;
GLStateManager.glLoadIdentity();
final boolean entityKind = effectiveIdKind() == GroupIdKind.ENTITY;
int currentId = Integer.MIN_VALUE;
int currentEntity = Integer.MIN_VALUE;
int currentBlock = Integer.MIN_VALUE;
int currentItem = 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)) {
if (!colorSet || segment.getEntityColor() != currentColor) {
colorSet = true;
currentColor = segment.getEntityColor();
setEntityColor(currentColor);
}
if (segment.getBlockEntityId() != currentId) {
currentId = segment.getBlockEntityId();
applyIdAndRebind(currentId);
if (segment.getEntityId() != currentEntity || segment.getRenderedBlockEntityId() != currentBlock
|| segment.getItemId() != currentItem) {
currentEntity = segment.getEntityId();
currentBlock = segment.getRenderedBlockEntityId();
currentItem = segment.getItemId();
applyIdsAndRebind(currentEntity, currentBlock, currentItem);
}
final SegmentedBufferBuilder.LayerBuffer owner = segment.getOwner();
if (owner != bound) {
@@ -298,7 +325,7 @@ public class AngelicaBufferSource implements Groupable {
failure = RenderFailures.suppress(failure, t);
}
try {
clearCurrentId();
restoreIrisState();
} catch (Throwable t) {
failure = RenderFailures.suppress(failure, t);
}
@@ -328,6 +355,8 @@ public class AngelicaBufferSource implements Groupable {
}
public void freeBuffers() {
restoreDrawState();
restoreIrisState();
for (SegmentedBufferBuilder builder : builders) {
builder.freeAll();
}
@@ -361,14 +390,11 @@ public class AngelicaBufferSource implements Groupable {
this.idKind = kind;
}
public void applyIdAndRebind(int id) {
anyIdSet = true;
if (effectiveIdKind() == GroupIdKind.ENTITY) {
CapturedRenderingState.INSTANCE.setCurrentEntityAndItem(id, 0);
rebindPass();
} else {
setBlockEntityAndRebind(id);
}
public void applyIdsAndRebind(int entityId, int blockEntityId, int itemId) {
saveIrisState();
CapturedRenderingState.INSTANCE.setCurrentEntityAndItem(entityId, itemId);
CapturedRenderingState.INSTANCE.setCurrentBlockEntity(blockEntityId);
rebindPass();
}
public static int packEntityColor(Vector4fc c) {
@@ -387,11 +413,6 @@ public class AngelicaBufferSource implements Groupable {
CapturedRenderingState.INSTANCE.setCurrentEntityColor((abgr & 0xFF) / 255f, ((abgr >>> 8) & 0xFF) / 255f, ((abgr >>> 16) & 0xFF) / 255f, (abgr >>> 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();
@@ -1,18 +1,33 @@
package net.coderbot.batchedentityrendering.impl;
import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
import lombok.Getter;
public class BufferSegment {
private final RenderLayer type;
@Getter
private final int blockEntityId;
@Getter
private final int itemId;
@Getter
private final int entityId;
@Getter
private final int renderedBlockEntityId;
@Getter
private final int entityColor;
@Getter
private final int firstVertex;
@Getter
private final int vertexCount;
@Getter
private final SegmentedBufferBuilder.LayerBuffer owner;
public BufferSegment(RenderLayer type, int blockEntityId, int entityColor, int firstVertex, int vertexCount, SegmentedBufferBuilder.LayerBuffer owner) {
public BufferSegment(RenderLayer type, int blockEntityId, int entityId, int renderedBlockEntityId, int itemId, int entityColor, int firstVertex, int vertexCount, SegmentedBufferBuilder.LayerBuffer owner) {
this.type = type;
this.blockEntityId = blockEntityId;
this.itemId = itemId;
this.entityId = entityId;
this.renderedBlockEntityId = renderedBlockEntityId;
this.entityColor = entityColor;
this.firstVertex = firstVertex;
this.vertexCount = vertexCount;
@@ -23,23 +38,4 @@ public class BufferSegment {
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;
}
}
@@ -74,13 +74,26 @@ public class SegmentedBufferBuilder {
private LayerBuffer current;
private RenderLayer currentType;
private int currentBlockEntityId;
private int currentItemId;
private int currentEntityId;
private int currentRenderedBlockEntityId;
private int currentEntityColor;
private int segmentStartVertex;
private long allocatedBytes;
public void begin(RenderLayer type, int blockEntityId) {
begin(type, blockEntityId, false);
}
public void begin(RenderLayer type, int blockEntityId, boolean entityKind) {
final CapturedRenderingState state = CapturedRenderingState.INSTANCE;
final int entityId = entityKind ? blockEntityId : state.getCurrentRenderedEntity();
final int renderedBlockEntityId = entityKind ? state.getCurrentRenderedBlockEntity() : blockEntityId;
final int entityColor = AngelicaBufferSource.packEntityColor(CapturedRenderingState.INSTANCE.getCurrentEntityColor());
if (type == currentType && blockEntityId == currentBlockEntityId && entityColor == currentEntityColor && current != null) {
final int itemId = CapturedRenderingState.INSTANCE.getCurrentRenderedItem();
if (type == currentType && blockEntityId == currentBlockEntityId && entityId == currentEntityId
&& renderedBlockEntityId == currentRenderedBlockEntityId && itemId == currentItemId
&& entityColor == currentEntityColor && current != null) {
return;
}
endSegment();
@@ -94,6 +107,9 @@ public class SegmentedBufferBuilder {
current = buffer;
currentType = type;
currentBlockEntityId = blockEntityId;
currentItemId = itemId;
currentEntityId = entityId;
currentRenderedBlockEntityId = renderedBlockEntityId;
currentEntityColor = entityColor;
segmentStartVertex = current.vertexCount;
}
@@ -142,7 +158,7 @@ public class SegmentedBufferBuilder {
private void endSegment() {
if (current != null && current.vertexCount > segmentStartVertex) {
segments.add(new BufferSegment(currentType, currentBlockEntityId, currentEntityColor, segmentStartVertex,
segments.add(new BufferSegment(currentType, currentBlockEntityId, currentEntityId, currentRenderedBlockEntityId, currentItemId, currentEntityColor, segmentStartVertex,
current.vertexCount - segmentStartVertex, current));
}
segmentStartVertex = current == null ? 0 : current.vertexCount;
@@ -14,6 +14,10 @@ public enum TransparencyType {
* These *must* be rendered after their corresponding opaque / transparent parts.
*/
DECAL,
/**
* Opaque item passes vanilla draws after an earlier pass's glint, such as a potion's bottle over its glinted liquid.
*/
AFTER_GLINT,
/**
* Water mask, should be drawn after pretty much everything except for translucent terrain and lines.
* Prevents water from appearing inside of boats.
@@ -10,6 +10,12 @@ import org.lwjgl.opengl.GL43;
public final class Program extends GlResource {
private static int managedBindProgram;
public static boolean isManagedBind(int program) {
return program != 0 && managedBindProgram == program;
}
@Getter
private final ProgramUniforms uniforms;
@@ -31,13 +37,23 @@ public final class Program extends GlResource {
public void use() {
RenderSystem.memoryBarrier(GL42.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL42.GL_TEXTURE_FETCH_BARRIER_BIT | GL43.GL_SHADER_STORAGE_BARRIER_BIT);
GLStateManager.glUseProgram(getGlId());
bindManaged(getGlId());
uniforms.update();
samplers.update();
images.update();
}
static void bindManaged(int program) {
final int previousManagedBind = managedBindProgram;
managedBindProgram = program;
try {
GLStateManager.glUseProgram(program);
} finally {
managedBindProgram = previousManagedBind;
}
}
public static void unbind() {
ProgramUniforms.clearActiveUniforms();
ProgramSamplers.clearActiveSamplers();
@@ -1,7 +1,10 @@
package net.coderbot.iris.gl.program;
import com.google.common.collect.ImmutableSet;
import com.gtnewhorizons.angelica.glsm.DisplayListManager;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import com.gtnewhorizons.angelica.glsm.recording.CommandRecorder;
import net.coderbot.iris.gl.image.ImageHolder;
import net.coderbot.iris.gl.sampler.GlSampler;
import net.coderbot.iris.gl.sampler.SamplerHolder;
@@ -54,6 +57,7 @@ public class ProgramBuilder extends ProgramUniforms.Builder implements SamplerHo
shaders.add(fragment);
int programId = ProgramCreator.create(name, shaders.toArray(new GlShader[0]));
initializeFallbackUniforms(programId);
for (GlShader shader : shaders) {
shader.destroy();
@@ -62,6 +66,42 @@ public class ProgramBuilder extends ProgramUniforms.Builder implements SamplerHo
return new ProgramBuilder(name, programId, reservedTextureUnits);
}
/** Initialize alpha and color uniforms to neutral values until the first pass update. */
private static void initializeFallbackUniforms(int programId) {
final int previous = GLStateManager.getActiveProgram();
final CommandRecorder recorder = DisplayListManager.isRecording() ? DisplayListManager.pauseRecording() : null;
try {
Program.bindManaged(programId);
seedUniform1i(programId, "iris_currentAlphaFunc", 7);
seedUniform1f(programId, "iris_currentAlphaTest", -1.0f);
seedUniform1f(programId, "alphaTestRef", -1.0f);
final int modulator = GLStateManager.glGetUniformLocation(programId, "iris_ColorModulator");
if (modulator != -1) {
RenderSystem.uniform4f(modulator, 1.0f, 1.0f, 1.0f, 1.0f);
}
} finally {
try {
Program.bindManaged(previous);
} finally {
if (recorder != null) DisplayListManager.resumeRecording(recorder);
}
}
}
private static void seedUniform1i(int programId, String name, int value) {
final int location = GLStateManager.glGetUniformLocation(programId, name);
if (location != -1) {
RenderSystem.uniform1i(location, value);
}
}
private static void seedUniform1f(int programId, String name, float value) {
final int location = GLStateManager.glGetUniformLocation(programId, name);
if (location != -1) {
RenderSystem.uniform1f(location, value);
}
}
public static ProgramBuilder beginCompute(String name, @Nullable String source, ImmutableSet<Integer> reservedTextureUnits) {
if (!RenderSystem.supportsCompute()) {
throw new IllegalStateException("This PC does not support compute shaders, but it's attempting to be used???");
@@ -3,6 +3,7 @@ package net.coderbot.iris.gl.program;
import com.google.common.collect.ImmutableList;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.DisplayListManager;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import java.nio.IntBuffer;
import java.util.ArrayList;
@@ -11,7 +12,6 @@ import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.OptionalInt;
import java.util.function.Supplier;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gl.state.ValueUpdateNotifier;
@@ -23,7 +23,6 @@ import net.coderbot.iris.gl.uniform.UniformUpdateFrequency;
import net.coderbot.iris.uniforms.SystemTimeUniforms;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.WorldClient;
import org.joml.Vector3i;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.ARBShaderImageLoadStore;
import org.lwjgl.opengl.GL11;
@@ -32,6 +31,7 @@ import org.lwjgl.opengl.GL30;
public class ProgramUniforms {
private static ProgramUniforms active;
private final int program;
private final ImmutableList<Uniform> perTick;
private final ImmutableList<Uniform> perFrame;
private final ImmutableList<Uniform> dynamic;
@@ -40,9 +40,11 @@ public class ProgramUniforms {
private ImmutableList<Uniform> once;
long lastTick = -1;
int lastFrame = -1;
private boolean hasDeferredUploads;
public ProgramUniforms(ImmutableList<Uniform> once, ImmutableList<Uniform> perTick, ImmutableList<Uniform> perFrame,
public ProgramUniforms(int program, ImmutableList<Uniform> once, ImmutableList<Uniform> perTick, ImmutableList<Uniform> perFrame,
ImmutableList<Uniform> dynamic, ImmutableList<ValueUpdateNotifier> notifiersToReset) {
this.program = program;
this.once = once;
this.perTick = perTick;
this.perFrame = perFrame;
@@ -68,11 +70,18 @@ public class ProgramUniforms {
}
public void update() {
// glUseProgram is only recorded during GL_COMPILE
if (DisplayListManager.getRecordMode() == DisplayListManager.RecordMode.COMPILE
|| GLStateManager.getActiveProgram() != program) {
hasDeferredUploads = true;
return;
}
if (active != null) {
active.removeListeners();
}
active = this;
hasDeferredUploads = false;
updateStage(dynamic);
@@ -118,6 +127,19 @@ public class ProgramUniforms {
}
}
public static boolean isActiveProgramBound() {
return active != null && GLStateManager.getActiveProgram() == active.program;
}
public static void markActiveDeferred() {
if (active != null) {
active.hasDeferredUploads = true;
}
}
public static boolean activeHasDeferredUploads() {
return active != null && active.hasDeferredUploads;
}
public static Builder builder(String name, int program) {
return new Builder(name, program);
}
@@ -263,7 +285,7 @@ public class ProgramUniforms {
}
}
return new ProgramUniforms(ImmutableList.copyOf(once.values()), ImmutableList.copyOf(perTick.values()), ImmutableList.copyOf(perFrame.values()),
return new ProgramUniforms(program, ImmutableList.copyOf(once.values()), ImmutableList.copyOf(perTick.values()), ImmutableList.copyOf(perFrame.values()),
ImmutableList.copyOf(dynamic.values()), ImmutableList.copyOf(notifiersToReset));
}
@@ -4,7 +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 final Runnable updateListener = uploadWhileBound(this::updateValue);
private float cachedValue;
private final FloatSupplier value;
@@ -31,8 +31,9 @@ public class FloatUniform extends Uniform {
private void updateValue() {
float newValue = value.getAsFloat();
if (cachedValue != newValue) {
if (dirty || cachedValue != newValue) {
cachedValue = newValue;
dirty = false;
RenderSystem.uniform1f(location, newValue);
}
}
@@ -6,7 +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 final Runnable updateListener = uploadWhileBound(this::updateValue);
private int cachedValue;
private final IntSupplier value;
@@ -33,8 +33,9 @@ public class IntUniform extends Uniform {
private void updateValue() {
int newValue = value.getAsInt();
if (cachedValue != newValue) {
if (dirty || cachedValue != newValue) {
cachedValue = newValue;
dirty = false;
RenderSystem.uniform1i(location, newValue);
}
}
@@ -1,10 +1,13 @@
package net.coderbot.iris.gl.uniform;
import com.gtnewhorizons.angelica.glsm.DisplayListManager;
import net.coderbot.iris.gl.program.ProgramUniforms;
import net.coderbot.iris.gl.state.ValueUpdateNotifier;
public abstract class Uniform {
protected final int location;
protected final ValueUpdateNotifier notifier;
protected boolean dirty = true;
Uniform(int location) {
this(location, null);
@@ -17,6 +20,18 @@ public abstract class Uniform {
public abstract void update();
protected final Runnable uploadWhileBound(Runnable upload) {
return () -> {
if (DisplayListManager.getRecordMode() != DisplayListManager.RecordMode.COMPILE
&& ProgramUniforms.isActiveProgramBound()) {
upload.run();
} else {
dirty = true;
ProgramUniforms.markActiveDeferred();
}
};
}
public final int getLocation() {
return location;
}
@@ -8,7 +8,7 @@ import org.joml.Vector2ic;
import java.util.function.Supplier;
public class Vector2IntegerJomlUniform extends Uniform {
private final Runnable updateListener = this::updateValue;
private final Runnable updateListener = uploadWhileBound(this::updateValue);
private final Vector2i cachedValue;
private final Supplier<Vector2ic> value;
@@ -35,7 +35,8 @@ public class Vector2IntegerJomlUniform extends Uniform {
private void updateValue() {
Vector2ic newValue = value.get();
if (!newValue.equals(cachedValue)) {
if (dirty || !newValue.equals(cachedValue)) {
dirty = false;
cachedValue.set(newValue.x(), newValue.y());
RenderSystem.uniform2i(this.location, cachedValue.x, cachedValue.y);
}
@@ -8,7 +8,7 @@ import org.joml.Vector3ic;
import java.util.function.Supplier;
public class Vector3IntegerJomlUniform extends Uniform {
private final Runnable updateListener = this::updateValue;
private final Runnable updateListener = uploadWhileBound(this::updateValue);
private final Vector3i cachedValue;
private final Supplier<Vector3ic> value;
@@ -35,7 +35,8 @@ public class Vector3IntegerJomlUniform extends Uniform {
private void updateValue() {
Vector3ic newValue = value.get();
if (!newValue.equals(cachedValue)) {
if (dirty || !newValue.equals(cachedValue)) {
dirty = false;
cachedValue.set(newValue.x(), newValue.y(), newValue.z());
RenderSystem.uniform3i(this.location, cachedValue.x(), cachedValue.y(), cachedValue.z());
}
@@ -7,7 +7,7 @@ import java.util.Arrays;
import java.util.function.Supplier;
public class Vector4ArrayUniform extends Uniform {
private final Runnable updateListener = this::updateValue;
private final Runnable updateListener = uploadWhileBound(this::updateValue);
private final Supplier<float[]> value;
private float[] cachedValue;
@@ -34,7 +34,8 @@ public class Vector4ArrayUniform extends Uniform {
private void updateValue() {
float[] newValue = value.get();
if (!Arrays.equals(newValue, cachedValue)) {
if (dirty || !Arrays.equals(newValue, cachedValue)) {
dirty = false;
cachedValue = newValue;
RenderSystem.uniform4f(location, cachedValue[0], cachedValue[1], cachedValue[2], cachedValue[3]);
}
@@ -8,7 +8,7 @@ import org.joml.Vector4ic;
import java.util.function.Supplier;
public class Vector4IntegerJomlUniform extends Uniform {
private final Runnable updateListener = this::updateValue;
private final Runnable updateListener = uploadWhileBound(this::updateValue);
private final Vector4i cachedValue;
private final Supplier<Vector4ic> value;
@@ -35,7 +35,8 @@ public class Vector4IntegerJomlUniform extends Uniform {
private void updateValue() {
Vector4ic newValue = value.get();
if (!newValue.equals(cachedValue)) {
if (dirty || !newValue.equals(cachedValue)) {
dirty = false;
cachedValue.set(newValue.x(), newValue.y(), newValue.z(), newValue.w());
RenderSystem.uniform4i(this.location, cachedValue.x, cachedValue.y, cachedValue.z, cachedValue.w);
}
@@ -8,7 +8,7 @@ import org.joml.Vector4fc;
import java.util.function.Supplier;
public class Vector4Uniform extends Uniform {
private final Runnable updateListener = this::updateValue;
private final Runnable updateListener = uploadWhileBound(this::updateValue);
private final Vector4f cachedValue;
private final Supplier<Vector4fc> value;
@@ -35,7 +35,8 @@ public class Vector4Uniform extends Uniform {
private void updateValue() {
Vector4fc newValue = value.get();
if (!newValue.equals(cachedValue)) {
if (dirty || !newValue.equals(cachedValue)) {
dirty = false;
cachedValue.set(newValue.x(), newValue.y(), newValue.z(), newValue.w());
RenderSystem.uniform4f(location, cachedValue.x(), cachedValue.y(), cachedValue.z(), cachedValue.w());
}
@@ -1,10 +1,12 @@
package net.coderbot.iris.layer;
import lombok.Getter;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.ffp.FfpExtendedAttribs;
import com.gtnewhorizons.angelica.iris.IrisDisplayListState;
import net.coderbot.iris.gl.shader.ProgramCreator;
import net.coderbot.iris.gl.state.StateUpdateNotifiers;
import net.coderbot.iris.pipeline.WorldRenderingPhase;
@@ -179,20 +181,48 @@ public class GbufferPrograms {
}
public static boolean beginNestedEntityPhase() {
IrisDisplayListState.recordNestedEntityScope(true);
if (getCurrentPhase() != WorldRenderingPhase.BLOCK_ENTITIES) {
return false;
}
setOverridePhase(WorldRenderingPhase.ENTITIES);
applyPushOverridePhase(WorldRenderingPhase.ENTITIES);
return true;
}
public static void endNestedEntityPhase(boolean pushed) {
IrisDisplayListState.recordNestedEntityScope(false);
if (pushed) {
setOverridePhase(null);
applyPopOverridePhase();
}
}
public static void setOverridePhase(WorldRenderingPhase phase) {
IrisDisplayListState.recordOverridePhase(phase);
applyOverridePhase(phase);
}
private static final ObjectArrayList<WorldRenderingPhase> phaseStack = new ObjectArrayList<>();
public static void pushOverridePhase(WorldRenderingPhase phase) {
IrisDisplayListState.recordPhaseScope(phase, true);
applyPushOverridePhase(phase);
}
private static void applyPushOverridePhase(WorldRenderingPhase phase) {
phaseStack.add(overridePhase);
applyOverridePhase(phase);
}
public static void popOverridePhase() {
IrisDisplayListState.recordPhaseScope(null, false);
applyPopOverridePhase();
}
private static void applyPopOverridePhase() {
applyOverridePhase(phaseStack.pop());
}
private static void applyOverridePhase(WorldRenderingPhase phase) {
overridePhase = phase;
final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable();
@@ -206,6 +236,7 @@ public class GbufferPrograms {
private static WorldRenderingPhase overridePhase;
public static Boolean beginTranslucencyDeclaration(Boolean translucent) {
IrisDisplayListState.recordTranslucencyScope(translucent, true);
final Boolean previous = declaredTranslucent;
declaredTranslucent = translucent;
applyTranslucencyDeclaration();
@@ -213,11 +244,13 @@ public class GbufferPrograms {
}
public static void endTranslucencyDeclaration(Boolean previous) {
IrisDisplayListState.recordTranslucencyScope(null, false);
declaredTranslucent = previous;
applyTranslucencyDeclaration();
}
public static void setTranslucencyDeclaration(Boolean translucent) {
IrisDisplayListState.recordTranslucency(translucent);
declaredTranslucent = translucent;
applyTranslucencyDeclaration();
}
@@ -233,6 +266,7 @@ public class GbufferPrograms {
}
private static SpecialCondition currentSpecial;
private static final ObjectArrayList<SpecialCondition> specialStack = new ObjectArrayList<>();
public static SpecialCondition getSpecialCondition() {
return currentSpecial;
@@ -243,6 +277,12 @@ public class GbufferPrograms {
}
public static void setupSpecialRenderCondition(SpecialCondition override) {
IrisDisplayListState.recordSpecialCondition(override, true);
specialStack.add(currentSpecial);
applySpecialCondition(override);
}
private static void applySpecialCondition(SpecialCondition override) {
currentSpecial = override;
final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable();
@@ -252,12 +292,8 @@ public class GbufferPrograms {
}
public static void teardownSpecialRenderCondition() {
currentSpecial = null;
final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable();
if (pipeline != null) {
pipeline.setSpecialCondition(null);
}
IrisDisplayListState.recordSpecialCondition(null, false);
applySpecialCondition(specialStack.pop());
}
public static void runPhaseChangeNotifier() {
@@ -13,6 +13,7 @@ public record PassOverride(SpecialCondition special, Boolean translucent, WorldR
public static final PassOverride NONE = new PassOverride(null, null, null);
private static final ObjectArrayList<PassOverride> INTERNED = new ObjectArrayList<>();
private static final ObjectArrayList<Boolean> translucencyStack = new ObjectArrayList<>();
public PassOverride(SpecialCondition special, Boolean translucent) {
this(special, translucent, null);
@@ -38,14 +39,14 @@ public record PassOverride(SpecialCondition special, Boolean translucent, WorldR
public void apply() {
GbufferPrograms.setupSpecialRenderCondition(special);
GbufferPrograms.setTranslucencyDeclaration(translucent);
GbufferPrograms.setOverridePhase(phase);
translucencyStack.add(GbufferPrograms.beginTranslucencyDeclaration(translucent));
GbufferPrograms.pushOverridePhase(phase);
}
public void clear() {
GbufferPrograms.setupSpecialRenderCondition(null);
GbufferPrograms.setTranslucencyDeclaration(null);
GbufferPrograms.setOverridePhase(null);
GbufferPrograms.popOverridePhase();
GbufferPrograms.endTranslucencyDeclaration(translucencyStack.pop());
GbufferPrograms.teardownSpecialRenderCondition();
}
public boolean isEntityPhase() {
@@ -1,5 +1,8 @@
package net.coderbot.iris.pipeline;
import com.gtnewhorizons.angelica.glsm.DisplayListManager;
import com.gtnewhorizons.angelica.iris.IrisDisplayListState;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.primitives.Ints;
@@ -10,10 +13,10 @@ import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformMatrix3f;
import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformMatrix4f;
import org.joml.Matrix3f;
import org.joml.Matrix4fc;
import com.gtnewhorizons.angelica.glsm.backend.BackendManager;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import com.gtnewhorizons.angelica.glsm.ffp.Instancing;
import com.gtnewhorizons.angelica.glsm.hooks.BatchStateGuard;
import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks;
import com.gtnewhorizons.angelica.glsm.hooks.PendingProgramSelection;
import com.gtnewhorizons.angelica.glsm.texture.TextureInfoCache;
@@ -113,7 +116,6 @@ import org.taumc.glsl.ShaderParser;
import org.taumc.glsl.Transformer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumMap;
@@ -837,6 +839,10 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
return shouldRenderParticlesBeforeDeferred;
}
public boolean shouldSeparateEntityDraws() {
return packDirectives.shouldUseSeparateEntityDraws();
}
@Override
public boolean allowConcurrentCompute() {
return allowConcurrentCompute;
@@ -991,6 +997,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
private boolean matchingBlend;
private void requestMatch() {
if (DisplayListManager.getRecordMode() == DisplayListManager.RecordMode.COMPILE) return;
if (GLStateManager.isForeignDraw() || BatchEligibility.batchingAllowed()) {
GLSMHooks.pendingProgramSelection = this;
return;
@@ -1022,6 +1029,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
}
private void matchPass(RenderCondition condition) {
if (DisplayListManager.getRecordMode() == DisplayListManager.RecordMode.COMPILE) return;
currentCondition = condition;
beginPass(table.match(condition, inputs));
}
@@ -1041,6 +1049,10 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
}
public void beginPass(Pass pass) {
IrisDisplayListState.runProgramTransition(() -> beginPassNow(pass));
}
private void beginPassNow(Pass pass) {
if (current == pass) {
return;
}
@@ -1064,9 +1076,11 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
}
private boolean drivingProgram;
private Instancing activeInstancing = Instancing.NONE;
@Override
public void rebindCurrentPass() {
activeInstancing = Instancing.NONE;
GLSMHooks.resolvePendingProgram();
final Pass pass = this.current;
if (pass == null) {
@@ -1353,6 +1367,10 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
}
public void use() {
IrisDisplayListState.runProgramTransition(this::useNow);
}
private void useNow() {
DepthColorStorage.unlockDepthColor();
if (isBeforeTranslucent) {
@@ -1388,11 +1406,12 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
bufferBlendOverrides.forEach(BufferBlendOverride::apply);
}
if (program != null) {
program.use();
if (activeInstancing != Instancing.NONE && program != null) {
DeferredWorldRenderingPipeline.this.bindInstancedVariant(activeInstancing);
} else {
if (program != null) program.use();
DeferredWorldRenderingPipeline.this.customUniforms.push(this);
}
DeferredWorldRenderingPipeline.this.customUniforms.push(this);
}
public void stopUsing() {
@@ -1483,6 +1502,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
@Override
public void bindInstancedVariant(Instancing kind) {
activeInstancing = kind;
final Program variant = current.instancedVariant(kind);
variant.use();
this.customUniforms.push(variant);
@@ -2265,13 +2285,18 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
currentNormalTexture = pbrHolder.getNormalTexture().getGlTextureId();
currentSpecularTexture = pbrHolder.getSpecularTexture().getGlTextureId();
final TextureFormat textureFormat = TextureFormatLoader.getFormat();
if (textureFormat != null) {
textureFormat.setupTextureParameters(PBRType.NORMAL, pbrHolder.getNormalTexture());
textureFormat.setupTextureParameters(PBRType.SPECULAR, pbrHolder.getSpecularTexture());
}
BatchStateGuard.suspend();
try {
final TextureFormat textureFormat = TextureFormatLoader.getFormat();
if (textureFormat != null) {
textureFormat.setupTextureParameters(PBRType.NORMAL, pbrHolder.getNormalTexture());
textureFormat.setupTextureParameters(PBRType.SPECULAR, pbrHolder.getSpecularTexture());
}
PBRTextureManager.notifyPBRTexturesChanged();
PBRTextureManager.notifyPBRTexturesChanged();
} finally {
BatchStateGuard.resume();
}
}
}
@@ -32,11 +32,11 @@ class EntityPatcher {
switch (parameters.type) {
case VERTEX -> {
if (!transformer.hasVariable("iris_Entity")) {
transformer.injectVariable("layout(location = " + InstancedAttribs.LOC_ENTITY + ") in ivec4 iris_Entity;");
}
removeIfDeclared(transformer, "iris_Entity");
transformer.injectVariable("layout(location = " + InstancedAttribs.LOC_ENTITY + ") in uvec4 iris_Entity;");
transformer.injectVariable("flat out ivec3 iris_entityInfo;");
transformer.prependMain("iris_entityInfo = iris_Entity.xyz;");
transformer.prependMain("iris_entityInfo = ivec3(iris_Entity.x == 65535u ? -1 : int(iris_Entity.x), "
+ "iris_Entity.y == 65535u ? -1 : int(iris_Entity.y), iris_Entity.z == 65535u ? -1 : int(iris_Entity.z));");
}
case TESSELATION_CONTROL -> {
transformer.injectVariable("flat out ivec3 iris_entityInfoTCS[];");
@@ -1,8 +1,17 @@
package net.coderbot.iris.uniforms;
import com.gtnewhorizons.angelica.iris.IrisDisplayListState;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.floats.FloatArrayList;
import lombok.Getter;
import lombok.Setter;
import net.coderbot.iris.gl.state.ValueUpdateNotifier;
import net.coderbot.iris.block_rendering.BlockRenderingSettings;
import net.coderbot.iris.shaderpack.materialmap.NamespacedId;
import net.minecraft.block.Block;
import net.minecraft.entity.Entity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import org.joml.Vector4f;
@@ -26,9 +35,13 @@ public class CapturedRenderingState {
@Getter
private int currentRenderedItem = -1;
private Runnable itemIdListener = null;
private final IntArrayList itemStack = new IntArrayList();
private final IntArrayList entityStack = new IntArrayList();
private final IntArrayList blockEntityStack = new IntArrayList();
private final FloatArrayList entityColorStack = new FloatArrayList();
@Getter
private final Vector4f currentEntityColor = new Vector4f();
private final Vector4f currentEntityColor = new Vector4f(0f);
private Runnable entityColorListener = null;
private CapturedRenderingState() {
@@ -47,6 +60,29 @@ public class CapturedRenderingState {
}
public void setCurrentBlockEntity(int entity) {
IrisDisplayListState.recordBlockEntity(entity);
applyCurrentBlockEntity(entity);
}
public void setCurrentBlockEntity(Block block, int metadata) {
IrisDisplayListState.recordBlockEntity(block, metadata);
final var matches = BlockRenderingSettings.INSTANCE.getBlockMetaMatches();
final var meta = matches == null || block == null ? null : matches.get(block);
applyCurrentBlockEntity(meta == null ? 0 : Math.max(0, meta.get(metadata)));
}
public void pushCurrentBlockEntity() {
IrisDisplayListState.recordBlockEntityScope(true);
blockEntityStack.push(currentRenderedBlockEntity);
}
public void popCurrentBlockEntity() {
IrisDisplayListState.recordBlockEntityScope(false);
applyCurrentBlockEntity(blockEntityStack.popInt());
}
private void applyCurrentBlockEntity(int entity) {
if (currentRenderedBlockEntity == entity) return;
this.currentRenderedBlockEntity = entity;
if (this.blockEntityIdListener != null) {
@@ -55,6 +91,7 @@ public class CapturedRenderingState {
}
private void setCurrentEntity(int entity) {
if (currentRenderedEntity == entity) return;
this.currentRenderedEntity = entity;
if (this.entityIdListener != null) {
@@ -66,11 +103,59 @@ public class CapturedRenderingState {
* I should have done this a while ago, better solution to not forget these exist in tandem.
*/
public void setCurrentEntityAndItem(int entity, int item) {
IrisDisplayListState.recordEntityAndItem(entity, item);
setCurrentEntity(entity);
setCurrentRenderedItem(item);
applyCurrentRenderedItem(item);
}
public void setCurrentNamedEntity(NamespacedId entity) {
IrisDisplayListState.recordNamedEntity(entity);
final var ids = BlockRenderingSettings.INSTANCE.getEntityIds();
setCurrentEntity(ids == null ? -1 : ids.applyAsInt(entity));
applyCurrentRenderedItem(0);
}
public void pushCurrentEntityAndItem() {
IrisDisplayListState.recordEntityScope(true);
entityStack.push(currentRenderedEntity);
itemStack.push(currentRenderedItem);
}
public void setCurrentRenderedEntity(Entity entity) {
IrisDisplayListState.recordEntity(entity);
setCurrentEntity(EntityIdHelper.getEntityId(entity));
applyCurrentRenderedItem(0);
}
public void popCurrentEntityAndItem() {
IrisDisplayListState.recordEntityScope(false);
// Restore the playback caller, never the IDs seen while compiling the list.
setCurrentEntity(entityStack.popInt());
applyCurrentRenderedItem(itemStack.popInt());
}
public void setCurrentEntityColor(float r, float g, float b, float a) {
IrisDisplayListState.recordEntityColor(r, g, b, a);
applyCurrentEntityColor(r, g, b, a);
}
public void pushCurrentEntityColor() {
IrisDisplayListState.recordEntityColorScope(true);
entityColorStack.push(currentEntityColor.x);
entityColorStack.push(currentEntityColor.y);
entityColorStack.push(currentEntityColor.z);
entityColorStack.push(currentEntityColor.w);
}
public void popCurrentEntityColor() {
IrisDisplayListState.recordEntityColorScope(false);
final float a = entityColorStack.popFloat(), b = entityColorStack.popFloat();
final float g = entityColorStack.popFloat(), r = entityColorStack.popFloat();
applyCurrentEntityColor(r, g, b, a);
}
private void applyCurrentEntityColor(float r, float g, float b, float a) {
if (currentEntityColor.equals(r, g, b, a)) return;
this.currentEntityColor.set(r, g, b, a);
if (this.entityColorListener != null) {
@@ -79,6 +164,42 @@ public class CapturedRenderingState {
}
public void setCurrentRenderedItem(int item) {
IrisDisplayListState.recordItemId(item);
applyCurrentRenderedItem(item);
}
public void pushCurrentRenderedItem() {
IrisDisplayListState.recordItemScope(true);
itemStack.push(currentRenderedItem);
}
public void setCurrentRenderedItem(ItemStack item) {
IrisDisplayListState.recordItem(item);
applyCurrentRenderedItem(ItemMaterialHelper.getMaterialId(item));
}
public void setCurrentRenderedItem(Item item, int metadata) {
IrisDisplayListState.recordItem(item, metadata);
applyCurrentRenderedItem(ItemMaterialHelper.getMaterialId(item, metadata));
}
public void setCurrentNamedItem(NamespacedId item) {
IrisDisplayListState.recordNamedItem(item);
final var ids = BlockRenderingSettings.INSTANCE.getItemIds();
applyCurrentRenderedItem(ids == null ? 0 : ids.applyAsInt(item));
}
public void setCurrentRenderedBlockItem(Block block, int metadata) {
IrisDisplayListState.recordBlockItem(block, metadata);
applyCurrentRenderedItem(ItemMaterialHelper.getMaterialId(block, metadata));
}
public void popCurrentRenderedItem() {
IrisDisplayListState.recordItemScope(false);
applyCurrentRenderedItem(itemStack.popInt());
}
private void applyCurrentRenderedItem(int item) {
if (this.currentRenderedItem == item) {
return;
}
@@ -55,21 +55,12 @@ public final class EntityIdHelper {
* @return The entity ID, or -1 if no mapping exists
*/
public static int getEntityId(Entity entity) {
Object2IntFunction<NamespacedId> entityIdMap = BlockRenderingSettings.INSTANCE.getEntityIds();
if (entity == null) return -1;
final Object2IntFunction<NamespacedId> entityIdMap = currentEntityIds();
if (entityIdMap == null) {
return -1;
}
// Invalidate caches if the map changed (shader reload)
if (entityIdMap != cachedEntityIdMap) {
entityIdCache.clear();
entityNameCache.clear();
entityNbtCache.clear();
cachedEntityIdMap = entityIdMap;
cachedCurrentPlayerId = entityIdMap.applyAsInt(CURRENT_PLAYER);
cachedConvertingVillagerId = entityIdMap.applyAsInt(CONVERTING_VILLAGER);
}
// Check NBT-conditional match first
final NbtConditionalIdMap<NamespacedId> entityNbtMap = BlockRenderingSettings.INSTANCE.getEntityNbtMap();
if (entityNbtMap != null && !entityNbtMap.isEmpty() && entity.worldObj != null) {
@@ -100,7 +91,7 @@ public final class EntityIdHelper {
}
// Normal entity type lookup
final int normalId = getNormalEntityId(entity, entityIdMap);
final int normalId = getNormalEntityId(entity.getClass(), getCachedEntityName(entity), entityIdMap);
// Check for special entity type overrides
final int specialId = getSpecialEntityId(entity);
@@ -111,6 +102,52 @@ public final class EntityIdHelper {
return normalId;
}
/** A display list retains the entity's material identity without retaining its world. */
public record EntityIdentity(Class<?> type, NamespacedId registeredName, boolean currentPlayer,
boolean convertingVillager, NBTTagCompound nbt) {
public int resolve() {
final Object2IntFunction<NamespacedId> ids = currentEntityIds();
if (ids == null) return -1;
final NbtConditionalIdMap<NamespacedId> conditions = BlockRenderingSettings.INSTANCE.getEntityNbtMap();
if (nbt != null && registeredName != null && conditions != null && !conditions.isEmpty()
&& conditions.hasConditions(registeredName)) {
final int conditional = conditions.resolve(registeredName, nbt);
if (conditional != -1) return conditional;
}
final int special = currentPlayer ? cachedCurrentPlayerId
: convertingVillager ? cachedConvertingVillagerId : -1;
return special != -1 ? special : getNormalEntityId(type, registeredName, ids);
}
}
public static EntityIdentity snapshot(Entity entity) {
if (entity == null) return null;
NBTTagCompound nbt = null;
if (entity.worldObj != null) {
nbt = new NBTTagCompound();
entity.writeToNBT(nbt);
// Entity serializers can attach live item tags to the output compound.
nbt = (NBTTagCompound) nbt.copy();
}
final String registeredName = EntityList.getEntityString(entity);
return new EntityIdentity(entity.getClass(), registeredName == null ? null : new NamespacedId(registeredName),
entity instanceof EntityPlayer && entity == Minecraft.getMinecraft().renderViewEntity,
entity instanceof EntityZombie zombie && zombie.isConverting(), nbt);
}
private static Object2IntFunction<NamespacedId> currentEntityIds() {
final Object2IntFunction<NamespacedId> ids = BlockRenderingSettings.INSTANCE.getEntityIds();
if (ids != cachedEntityIdMap) {
entityIdCache.clear();
entityNameCache.clear();
entityNbtCache.clear();
cachedEntityIdMap = ids;
cachedCurrentPlayerId = ids == null ? -1 : ids.applyAsInt(CURRENT_PLAYER);
cachedConvertingVillagerId = ids == null ? -1 : ids.applyAsInt(CONVERTING_VILLAGER);
}
return ids;
}
/**
* Check if the entity should use a special hardcoded entity ID.
*/
@@ -134,10 +171,7 @@ public final class EntityIdHelper {
* Get the normal entity ID based on entity type, with caching.
* Uses Class<?> as cache key for fast reference-equality lookups.
*/
private static int getNormalEntityId(Entity entity, Object2IntFunction<NamespacedId> entityIdMap) {
// Use entity class as cache key
Class<?> entityClass = entity.getClass();
private static int getNormalEntityId(Class<?> entityClass, NamespacedId entityName, Object2IntFunction<NamespacedId> entityIdMap) {
// Check cache first
int cached = entityIdCache.getInt(entityClass);
if (cached != Integer.MIN_VALUE) {
@@ -145,7 +179,7 @@ public final class EntityIdHelper {
}
// Cache miss, store for next lookup
int resolvedId = resolveEntityId(entity, entityClass, entityIdMap);
int resolvedId = resolveEntityId(entityClass, entityName, entityIdMap);
entityIdCache.put(entityClass, resolvedId);
return resolvedId;
@@ -158,11 +192,10 @@ public final class EntityIdHelper {
* 3. Fully qualified class name (e.g., "net.minecraft.entity.effect.EntityLightningBolt")
* 4. Special hardcoded cases (e.g., "minecraft:lightning_bolt")
*/
private static int resolveEntityId(Entity entity, Class<?> entityClass, Object2IntFunction<NamespacedId> entityIdMap) {
private static int resolveEntityId(Class<?> entityClass, NamespacedId entityType, Object2IntFunction<NamespacedId> entityIdMap) {
// Try registered entity name first (most common)
String entityType = EntityList.getEntityString(entity);
if (entityType != null) {
return entityIdMap.applyAsInt(new NamespacedId(entityType));
return entityIdMap.applyAsInt(entityType);
}
String simpleClassName = entityClass.getSimpleName();
@@ -173,7 +206,7 @@ public final class EntityIdHelper {
id = entityIdMap.applyAsInt(new NamespacedId(className));
}
if (id == -1 && entity instanceof EntityLightningBolt) {
if (id == -1 && EntityLightningBolt.class.isAssignableFrom(entityClass)) {
// Shaderpacks use "minecraft:lightning_bolt" so we should continue to provide it here
// Even if we can just use EntityLightningBolt
id = entityIdMap.applyAsInt(LIGHTNING_BOLT_ID);
@@ -188,12 +221,13 @@ public final class EntityIdHelper {
private static NamespacedId getCachedEntityName(Entity entity) {
Class<?> entityClass = entity.getClass();
NamespacedId cached = entityNameCache.get(entityClass);
if (cached != null) {
if (cached != null || entityNameCache.containsKey(entityClass)) {
return cached;
}
String entityType = EntityList.getEntityString(entity);
if (entityType == null) {
entityNameCache.put(entityClass, null);
return null;
}
@@ -10,6 +10,14 @@ import net.minecraft.item.ItemStack;
* Helper class to manage the currentRenderedItem ID uniform.
*/
public class ItemIdManager {
public static void pushItemId() {
CapturedRenderingState.INSTANCE.pushCurrentRenderedItem();
}
public static void popItemId() {
CapturedRenderingState.INSTANCE.popCurrentRenderedItem();
}
/**
* Set the item ID for an armor piece or held item.
* If the ItemStack is null/empty, resets to 0.
@@ -18,20 +26,14 @@ public class ItemIdManager {
* @param itemStack The armor or item being rendered
*/
public static void setItemId(ItemStack itemStack) {
if (itemStack == null || itemStack.getItem() == null) {
CapturedRenderingState.INSTANCE.setCurrentRenderedItem(0);
return;
}
int id = ItemMaterialHelper.getMaterialId(itemStack);
CapturedRenderingState.INSTANCE.setCurrentRenderedItem(id);
CapturedRenderingState.INSTANCE.setCurrentRenderedItem(itemStack);
}
/**
* Set the item ID for a Block rendered outside of terrain.
*/
public static void setBlockId(Block block, int metadata) {
CapturedRenderingState.INSTANCE.setCurrentRenderedItem(ItemMaterialHelper.getMaterialId(block, metadata));
CapturedRenderingState.INSTANCE.setCurrentRenderedBlockItem(block, metadata);
}
/**