mirror of
https://github.com/GTNewHorizons/Angelica.git
synced 2026-11-25 06:34:27 +00:00
SDL GPU backend, TESR Batching/caching API, Tracy Integration (#1993)
This commit is contained in:
1 parent
413df76ad4
commit
8da561d3b6
647 files changed
+60152
-5331
No files matched your search
@@ -1,5 +1,7 @@
|
||||
package com.gtnewhorizons.angelica;
|
||||
|
||||
import com.gtnewhorizons.angelica.config.SystemProperties;
|
||||
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
|
||||
import com.gtnewhorizons.angelica.proxy.CommonProxy;
|
||||
import cpw.mods.fml.common.Mod;
|
||||
import cpw.mods.fml.common.SidedProxy;
|
||||
@@ -29,7 +31,8 @@ public class AngelicaMod {
|
||||
|
||||
public static final String MOD_ID = "angelica";
|
||||
public static final Logger LOGGER = LogManager.getLogger("Angelica");
|
||||
public static final boolean lwjglDebug = Boolean.getBoolean("org.lwjgl.util.Debug");
|
||||
public static final boolean lwjglDebug = SystemProperties.LWJGL_DEBUG;
|
||||
public static final boolean tracyEnabled = Tracy.ENABLED;
|
||||
|
||||
@SidedProxy(
|
||||
clientSide = "com.gtnewhorizons.angelica.proxy.ClientProxy",
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.gtnewhorizons.angelica.api.tesr;
|
||||
|
||||
import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher;
|
||||
import net.minecraft.client.model.ModelRenderer;
|
||||
|
||||
/** For parts that override {@code ModelRenderer.render} */
|
||||
public final class ModelPartBatch {
|
||||
|
||||
private ModelPartBatch() {}
|
||||
|
||||
/** @return false if it cannot be batched */
|
||||
public static boolean partDraw(ModelRenderer part, float scale) {
|
||||
return ModelPartBatcher.partDraw(part, scale, null);
|
||||
}
|
||||
|
||||
public static boolean partDraw(ModelRenderer part, float scale, ModelPartMeshBuilder builder) {
|
||||
return ModelPartBatcher.partDraw(part, scale, builder);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.gtnewhorizons.angelica.api.tesr;
|
||||
|
||||
import net.minecraft.client.model.ModelRenderer;
|
||||
import net.minecraft.client.renderer.Tessellator;
|
||||
|
||||
/** Geometry for a part that keeps it outside {@code cubeList} */
|
||||
@FunctionalInterface
|
||||
public interface ModelPartMeshBuilder {
|
||||
|
||||
void angelica$buildPart(Tessellator tess, ModelRenderer part, float scale);
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package com.gtnewhorizons.angelica.api.tesr;
|
||||
|
||||
import lombok.AccessLevel;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Getter;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/** Per-bucket render attributes. Interned: equal settings build the same instance. */
|
||||
@Getter
|
||||
@Accessors(fluent = true)
|
||||
@AllArgsConstructor(access = AccessLevel.PRIVATE)
|
||||
@EqualsAndHashCode
|
||||
public final class TesrMaterial {
|
||||
|
||||
public enum Transparency { OPAQUE, TRANSLUCENT, ADDITIVE, ADDITIVE_ALPHA, GLINT }
|
||||
|
||||
public enum SpecialRender { NONE, BEACON_BEAM, GLINT }
|
||||
|
||||
private static final ConcurrentHashMap<TesrMaterial, TesrMaterial> INTERNED = new ConcurrentHashMap<>();
|
||||
|
||||
public static final TesrMaterial CURRENT_STATE = intern(new TesrMaterial(false, 0, 0, 0, 0, false, 0, 0, false, false, false, false, false, 0, false, Transparency.OPAQUE, SpecialRender.NONE, null));
|
||||
|
||||
private static TesrMaterial intern(TesrMaterial material) {
|
||||
final TesrMaterial existing = INTERNED.putIfAbsent(material, material);
|
||||
return existing == null ? material : existing;
|
||||
}
|
||||
|
||||
private final boolean hasColor;
|
||||
private final float colorRed, colorGreen, colorBlue, colorAlpha;
|
||||
private final boolean hasLightmap;
|
||||
private final float lightmapX, lightmapY;
|
||||
private final boolean isNoCull;
|
||||
private final boolean isUnlit;
|
||||
private final boolean isNoDepthWrite;
|
||||
private final boolean isDepthOnly;
|
||||
private final boolean isStream;
|
||||
private final float cutoutAlpha;
|
||||
private final boolean isDepthEqual;
|
||||
private final Transparency transparency;
|
||||
private final SpecialRender special;
|
||||
private final TesrShader shader;
|
||||
|
||||
public static Builder builder() {
|
||||
return new Builder();
|
||||
}
|
||||
|
||||
public static final class Builder {
|
||||
private boolean hasColor;
|
||||
private float red, green, blue, alpha;
|
||||
private boolean hasLightmap;
|
||||
private float lightmapX, lightmapY;
|
||||
private boolean noCull;
|
||||
private boolean unlit;
|
||||
private boolean noDepthWrite;
|
||||
private boolean depthOnly;
|
||||
private boolean stream;
|
||||
private float cutoutAlpha;
|
||||
private boolean depthEqual;
|
||||
private Transparency transparency = Transparency.OPAQUE;
|
||||
private SpecialRender special = SpecialRender.NONE;
|
||||
private TesrShader shader;
|
||||
|
||||
public Builder color(float red, float green, float blue, float alpha) {
|
||||
this.hasColor = true;
|
||||
this.red = red;
|
||||
this.green = green;
|
||||
this.blue = blue;
|
||||
this.alpha = alpha;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder lightmap(float x, float y) {
|
||||
this.hasLightmap = true;
|
||||
this.lightmapX = x;
|
||||
this.lightmapY = y;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder noCull() {
|
||||
this.noCull = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Disables FFP lighting */
|
||||
public Builder unlit() {
|
||||
this.unlit = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder noDepthWrite() {
|
||||
this.noDepthWrite = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Depth prepass: writes depth only, no color. Mutually exclusive with noDepthWrite */
|
||||
public Builder depthOnly() {
|
||||
this.depthOnly = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Changes every frame, not cached */
|
||||
public Builder stream() {
|
||||
this.stream = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Discards pixels with alpha at or below threshold - hard-edged cutout, no blending. ALPHA_TEST GREATER */
|
||||
public Builder cutout(float threshold) {
|
||||
this.cutoutAlpha = threshold;
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Draws only where geometry already exists at the same depth; for decal/overlay passes. GL_EQUAL depth */
|
||||
public Builder depthEqual() {
|
||||
this.depthEqual = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Standard alpha blending (glass, liquids). SRC_ALPHA, ONE_MINUS_SRC_ALPHA */
|
||||
public Builder translucent() {
|
||||
this.transparency = Transparency.TRANSLUCENT;
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Additive glow; alpha ignored. ONE, ONE */
|
||||
public Builder additive() {
|
||||
this.transparency = Transparency.ADDITIVE;
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Additive glow scaled by alpha. SRC_ALPHA, ONE */
|
||||
public Builder additiveAlpha() {
|
||||
this.transparency = Transparency.ADDITIVE_ALPHA;
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Vanilla enchantment glint blend. SRC_COLOR, ONE */
|
||||
public Builder glint() {
|
||||
this.transparency = Transparency.GLINT;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder special(SpecialRender special) {
|
||||
this.special = special;
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Custom shader around this material's batched draws; see {@link TesrShaders#register} */
|
||||
public Builder shader(TesrShader shader) {
|
||||
this.shader = shader;
|
||||
return this;
|
||||
}
|
||||
|
||||
public TesrMaterial build() {
|
||||
if (special != SpecialRender.NONE && shader != null) {
|
||||
throw new IllegalStateException("special() and shader() are mutually exclusive");
|
||||
}
|
||||
return intern(new TesrMaterial(hasColor, red, green, blue, alpha, hasLightmap, lightmapX, lightmapY, noCull, unlit, noDepthWrite, depthOnly, stream, cutoutAlpha, depthEqual, transparency, special, shader));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.gtnewhorizons.angelica.api.tesr;
|
||||
|
||||
/** Emits local-space geometry into the sink's buckets. Prefer implementing {@link TesrMeshProvider}. */
|
||||
@FunctionalInterface
|
||||
public interface TesrMeshBuilder {
|
||||
|
||||
void angelica$build(TesrMeshSink sink);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.gtnewhorizons.angelica.api.tesr;
|
||||
|
||||
import com.gtnewhorizons.angelica.rendering.tesr.AngelicaTesrMeshCache;
|
||||
|
||||
/** TESR mesh cache entry points. Render thread only. */
|
||||
public final class TesrMeshCache {
|
||||
|
||||
private TesrMeshCache() {}
|
||||
|
||||
public static void renderCached(Object key, TesrMeshBuilder builder) {
|
||||
AngelicaTesrMeshCache.INSTANCE.renderCached(key, builder);
|
||||
}
|
||||
|
||||
/** Manual invalidate ande force rebuild on next render */
|
||||
public static void invalidate(Object key) {
|
||||
AngelicaTesrMeshCache.INSTANCE.invalidate(key);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.gtnewhorizons.angelica.api.tesr;
|
||||
|
||||
import com.gtnewhorizons.angelica.glsm.GLStateManager;
|
||||
import net.minecraft.tileentity.TileEntity;
|
||||
|
||||
/**
|
||||
* Implemented by a TileEntitySpecialRenderer to opt into Angelica's mesh cache/batch
|
||||
*
|
||||
* Use a compile-only dependency and guard with {@code @Optional.Interface(iface = "com.gtnewhorizons.angelica.api.tesr.TesrMeshProvider", modid = "angelica|tesr")}
|
||||
* and mark {@link #angelica$build} {@code @Optional.Method(modid = "angelica|tesr")}
|
||||
*/
|
||||
public interface TesrMeshProvider {
|
||||
|
||||
/** Stable identity key for the mesh variant, null falls back to the vanilla render path this frame */
|
||||
Object angelica$meshKey(TileEntity te);
|
||||
|
||||
/** True if the cached mesh must be rebuilt */
|
||||
default boolean angelica$meshDirty(TileEntity te) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Per-instance transform, defaults to TE position */
|
||||
default void angelica$transform(TileEntity te, double x, double y, double z) {
|
||||
GLStateManager.glTranslated(x, y, z);
|
||||
}
|
||||
|
||||
/** Build and cache the mesh */
|
||||
void angelica$build(TesrMeshSink sink, TileEntity te);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.gtnewhorizons.angelica.api.tesr;
|
||||
|
||||
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
|
||||
import net.minecraft.client.renderer.Tessellator;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
|
||||
/** Capture-time sink. draw() captures instead of drawing */
|
||||
public interface TesrMeshSink {
|
||||
|
||||
Tessellator angelica$bucket(VertexFormat format, ResourceLocation texture, TesrMaterial material);
|
||||
|
||||
default Tessellator angelica$bucket(VertexFormat format, ResourceLocation texture) {
|
||||
return angelica$bucket(format, texture, TesrMaterial.CURRENT_STATE);
|
||||
}
|
||||
|
||||
default Tessellator angelica$bucket(VertexFormat format) {
|
||||
return angelica$bucket(format, null, TesrMaterial.CURRENT_STATE);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.gtnewhorizons.angelica.api.tesr;
|
||||
|
||||
import lombok.AccessLevel;
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
/** A registered mod-owned GL program; see {@link TesrShaders#register} */
|
||||
@Getter
|
||||
@Accessors(fluent = true)
|
||||
@RequiredArgsConstructor(access = AccessLevel.PACKAGE)
|
||||
public final class TesrShader {
|
||||
|
||||
private final String name;
|
||||
private final Runnable bind;
|
||||
private final Runnable release;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.gtnewhorizons.angelica.api.tesr;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public final class TesrShaders {
|
||||
|
||||
private static final ConcurrentHashMap<String, TesrShader> REGISTRY = new ConcurrentHashMap<>();
|
||||
|
||||
private TesrShaders() {}
|
||||
|
||||
/** Registers a GL program under a unique name and returns its handle, wraps draws of any {@link TesrMaterial} referencing it */
|
||||
public static TesrShader register(String name, Runnable bind, Runnable release) {
|
||||
final int colon = name.indexOf(':');
|
||||
if (colon <= 0 || colon == name.length() - 1 || name.indexOf(':', colon + 1) >= 0) {
|
||||
throw new IllegalArgumentException("TESR shader name must be namespace:path, got '" + name + "'");
|
||||
}
|
||||
Objects.requireNonNull(bind, "bind");
|
||||
Objects.requireNonNull(release, "release");
|
||||
final TesrShader shader = new TesrShader(name, bind, release);
|
||||
if (REGISTRY.putIfAbsent(name, shader) != null) {
|
||||
throw new IllegalStateException("TESR shader '" + name + "' already registered");
|
||||
}
|
||||
return shader;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
/** TESR mesh cache/batch API (Render thread only) */
|
||||
@API(owner = "angelica", provides = "angelica|tesr", apiVersion = "1")
|
||||
package com.gtnewhorizons.angelica.api.tesr;
|
||||
|
||||
import cpw.mods.fml.common.API;
|
||||
@@ -12,9 +12,14 @@ import static com.gtnewhorizons.angelica.client.font.ColorCodeUtils.SECTION_X_PA
|
||||
import com.gtnewhorizons.angelica.config.AngelicaConfig;
|
||||
import com.gtnewhorizons.angelica.config.FontConfig;
|
||||
import com.gtnewhorizons.angelica.hudcaching.HUDCaching;
|
||||
import com.gtnewhorizons.angelica.AngelicaMod;
|
||||
import com.gtnewhorizons.angelica.glsm.GLStateManager;
|
||||
import com.gtnewhorizons.angelica.glsm.RenderSystem;
|
||||
import com.gtnewhorizons.angelica.glsm.streaming.PersistentStreamingBuffer;
|
||||
import com.gtnewhorizons.angelica.glsm.streaming.StreamingUploader;
|
||||
import com.gtnewhorizons.angelica.mixins.interfaces.FontRendererAccessor;
|
||||
import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher;
|
||||
import com.gtnewhorizons.angelica.rendering.tesr.TesrBatchRenderer;
|
||||
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
|
||||
import lombok.Setter;
|
||||
import net.coderbot.iris.gl.program.Program;
|
||||
@@ -32,6 +37,7 @@ import org.lwjgl.opengl.GL20;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.FloatBuffer;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.Objects;
|
||||
|
||||
@@ -133,10 +139,18 @@ public class BatchingFontRenderer {
|
||||
private static int vbo;
|
||||
private static IndexBuffer ebo;
|
||||
|
||||
private static final int RING_CAPACITY = 2 * 1024 * 1024;
|
||||
private static PersistentStreamingBuffer streamRing;
|
||||
private static boolean streamingInitialized;
|
||||
private static int pendingBuffer;
|
||||
private static int pendingBase;
|
||||
private static int vaoBuffer = -1;
|
||||
private static int vaoBase = -1;
|
||||
|
||||
private int batchDepth = 0;
|
||||
|
||||
private int vertexDataPos = 0;
|
||||
private int idxWriterIndex = 0;
|
||||
private static int vertexDataPos = 0;
|
||||
private static int idxWriterIndex = 0;
|
||||
|
||||
private final ObjectArrayList<FontDrawCmd> batchCommands = ObjectArrayList.wrap(new FontDrawCmd[64], 0);
|
||||
private final ObjectArrayList<FontDrawCmd> batchCommandPool = ObjectArrayList.wrap(new FontDrawCmd[64], 0);
|
||||
@@ -144,6 +158,24 @@ public class BatchingFontRenderer {
|
||||
private int blendSrcRGB = GL11.GL_SRC_ALPHA;
|
||||
private int blendDstRGB = GL11.GL_ONE_MINUS_SRC_ALPHA;
|
||||
|
||||
private static final class DeferredTextSegment {
|
||||
final Matrix4f mvp = new Matrix4f();
|
||||
BatchingFontRenderer owner;
|
||||
int cmdStart;
|
||||
int cmdEnd;
|
||||
}
|
||||
|
||||
// 16-bit EBO index range
|
||||
private static final int QUAD_BUDGET = 65536 / 4;
|
||||
|
||||
private static int deferredVertexPos;
|
||||
private static int deferredIdxPos;
|
||||
|
||||
private int deferredCmdWatermark;
|
||||
private static final ObjectArrayList<DeferredTextSegment> deferredSegments = ObjectArrayList.wrap(new DeferredTextSegment[16], 0);
|
||||
private static final ObjectArrayList<DeferredTextSegment> deferredSegmentPool = ObjectArrayList.wrap(new DeferredTextSegment[16], 0);
|
||||
private boolean deferCurrentBatch;
|
||||
|
||||
|
||||
private void allocateBuffers() {
|
||||
populateEBO(rawCapacity / VERTEX_SIZE);
|
||||
@@ -174,6 +206,36 @@ public class BatchingFontRenderer {
|
||||
|
||||
}
|
||||
|
||||
private static void initStreaming() {
|
||||
if (streamingInitialized) return;
|
||||
streamingInitialized = true;
|
||||
streamRing = PersistentStreamingBuffer.createOrNull(RING_CAPACITY);
|
||||
}
|
||||
|
||||
public static void endFrame() {
|
||||
if (streamRing != null) {
|
||||
streamRing.postDraw();
|
||||
}
|
||||
}
|
||||
|
||||
private static void uploadVertexData(int limitPos) {
|
||||
initStreaming();
|
||||
vertexData.position(0);
|
||||
vertexData.limit(limitPos);
|
||||
if (streamRing != null) {
|
||||
final int firstVertex = streamRing.upload(vertexData, VERTEX_SIZE);
|
||||
if (firstVertex >= 0) {
|
||||
pendingBuffer = streamRing.getBufferId();
|
||||
pendingBase = firstVertex * VERTEX_SIZE;
|
||||
return;
|
||||
}
|
||||
}
|
||||
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo);
|
||||
vboCapacity = StreamingUploader.upload(vertexData, vboCapacity);
|
||||
pendingBuffer = vbo;
|
||||
pendingBase = 0;
|
||||
}
|
||||
|
||||
private void ensureCapacity() {
|
||||
if (vertexDataPos + (4 * VERTEX_SIZE) > rawCapacity) {
|
||||
rawCapacity *= 2;
|
||||
@@ -236,7 +298,8 @@ public class BatchingFontRenderer {
|
||||
}
|
||||
|
||||
private void pushDrawCmd(int startIdx, int idxCount, ResourceLocation texture, boolean isUnicode) {
|
||||
if (!batchCommands.isEmpty()) {
|
||||
// Never coalesce into a command below the watermark - it belongs to a sealed deferred segment.
|
||||
if (batchCommands.size() > deferredCmdWatermark) {
|
||||
final FontDrawCmd lastCmd = batchCommands.get(batchCommands.size() - 1);
|
||||
final int prevEndVtx = lastCmd.startVtx + lastCmd.idxCount;
|
||||
if (prevEndVtx == startIdx && lastCmd.texture == texture) {
|
||||
@@ -322,6 +385,101 @@ public class BatchingFontRenderer {
|
||||
}
|
||||
}
|
||||
|
||||
public void beginDeferredBatch() {
|
||||
deferCurrentBatch = batchDepth == 0 && TesrBatchRenderer.INSTANCE.hasActivePass() || ModelPartBatcher.INSTANCE.isActive();
|
||||
if (deferCurrentBatch && deferredIdxPos / 6 > QUAD_BUDGET / 2) {
|
||||
flushDeferredText();
|
||||
}
|
||||
beginBatch();
|
||||
}
|
||||
|
||||
public void endDeferredBatch() {
|
||||
if (deferCurrentBatch && batchDepth == 1) {
|
||||
deferCurrentBatch = false;
|
||||
batchDepth = 0;
|
||||
deferBatch();
|
||||
} else {
|
||||
endBatch();
|
||||
}
|
||||
}
|
||||
|
||||
private void deferBatch() {
|
||||
if (batchCommands.size() == deferredCmdWatermark || vertexDataPos == deferredVertexPos) {
|
||||
truncateBatchToWatermark();
|
||||
return;
|
||||
}
|
||||
if (idxWriterIndex / 6 > QUAD_BUDGET) {
|
||||
flushBatch();
|
||||
return;
|
||||
}
|
||||
final DeferredTextSegment segment = deferredSegmentPool.isEmpty() ? new DeferredTextSegment() : deferredSegmentPool.pop();
|
||||
segment.owner = this;
|
||||
segment.cmdStart = deferredCmdWatermark;
|
||||
segment.cmdEnd = batchCommands.size();
|
||||
GLStateManager.getProjectionMatrix().mul(GLStateManager.getModelViewMatrix(), segment.mvp);
|
||||
deferredSegments.add(segment);
|
||||
deferredCmdWatermark = batchCommands.size();
|
||||
deferredVertexPos = vertexDataPos;
|
||||
deferredIdxPos = idxWriterIndex;
|
||||
}
|
||||
|
||||
public static void flushDeferredText() {
|
||||
if (deferredSegments.isEmpty()) return;
|
||||
|
||||
uploadVertexData(deferredVertexPos);
|
||||
|
||||
final int prevProgram = GLStateManager.glGetInteger(GL20.GL_CURRENT_PROGRAM);
|
||||
final boolean isTextureEnabledBefore = GLStateManager.glIsEnabled(GL11.GL_TEXTURE_2D);
|
||||
final boolean isBlendEnabledBefore = GLStateManager.glIsEnabled(GL11.GL_BLEND);
|
||||
final int boundTextureBefore = GLStateManager.glGetInteger(GL11.GL_TEXTURE_BINDING_2D);
|
||||
|
||||
final boolean depthTestBefore = GLStateManager.getDepthTest().isEnabled();
|
||||
final boolean depthMaskBefore = GLStateManager.getDepthState().isEnabled();
|
||||
|
||||
deferredSegments.get(0).owner.setupFontDrawState();
|
||||
GLStateManager.glDepthMask(false);
|
||||
flushLastTexture = DUMMY_RESOURCE_LOCATION;
|
||||
flushTextureChanged = false;
|
||||
try (MemoryStack stack = stackPush()) {
|
||||
final FloatBuffer mvpBuf = stack.mallocFloat(16);
|
||||
for (int i = 0, n = deferredSegments.size(); i < n; i++) {
|
||||
final DeferredTextSegment segment = deferredSegments.get(i);
|
||||
mvpBuf.clear();
|
||||
segment.mvp.get(mvpBuf);
|
||||
GLStateManager.glUniformMatrix4(segment.owner.mvpMatrixLocation, false, mvpBuf);
|
||||
drawCommands(segment.owner.batchCommands.elements(), segment.cmdStart, segment.cmdEnd, segment.owner);
|
||||
}
|
||||
}
|
||||
restoreFontDrawState(prevProgram, isTextureEnabledBefore, isBlendEnabledBefore, boundTextureBefore);
|
||||
restoreDepth(depthTestBefore, depthMaskBefore);
|
||||
|
||||
discardDeferredText();
|
||||
}
|
||||
|
||||
public static void discardDeferredText() {
|
||||
if (deferredSegments.isEmpty()) return;
|
||||
for (int i = 0, n = deferredSegments.size(); i < n; i++) {
|
||||
final DeferredTextSegment segment = deferredSegments.get(i);
|
||||
segment.owner.clearDeferredCommands();
|
||||
segment.owner = null;
|
||||
}
|
||||
deferredSegmentPool.addAll(deferredSegments);
|
||||
deferredSegments.clear();
|
||||
deferredVertexPos = 0;
|
||||
deferredIdxPos = 0;
|
||||
vertexDataPos = 0;
|
||||
idxWriterIndex = 0;
|
||||
}
|
||||
|
||||
private void clearDeferredCommands() {
|
||||
if (deferredCmdWatermark == 0) return;
|
||||
for (int i = 0; i < deferredCmdWatermark; i++) {
|
||||
batchCommandPool.add(batchCommands.get(i));
|
||||
}
|
||||
batchCommands.removeElements(0, deferredCmdWatermark);
|
||||
deferredCmdWatermark = 0;
|
||||
}
|
||||
|
||||
private static final Matrix4f scratchMvp = new Matrix4f();
|
||||
private int fontAAModeLast = -1;
|
||||
private int fontAAStrengthLast = -1;
|
||||
@@ -336,27 +494,42 @@ public class BatchingFontRenderer {
|
||||
}
|
||||
|
||||
private void flushBatchInner() {
|
||||
if (vertexDataPos == 0) {
|
||||
clearBatch();
|
||||
final int cmdCount = batchCommands.size();
|
||||
if (vertexDataPos == deferredVertexPos || cmdCount == deferredCmdWatermark) {
|
||||
truncateBatchToWatermark();
|
||||
return;
|
||||
}
|
||||
|
||||
// Upload first (to reduce stalls)
|
||||
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo);
|
||||
vertexData.limit(vertexDataPos);
|
||||
vboCapacity = StreamingUploader.upload(vertexData, vboCapacity);
|
||||
uploadVertexData(vertexDataPos);
|
||||
|
||||
final int prevProgram = GLStateManager.glGetInteger(GL20.GL_CURRENT_PROGRAM);
|
||||
|
||||
// Sort&Draw
|
||||
batchCommands.sort(FontDrawCmd.DRAW_ORDER_COMPARATOR);
|
||||
Arrays.sort(batchCommands.elements(), deferredCmdWatermark, cmdCount, FontDrawCmd.DRAW_ORDER_COMPARATOR);
|
||||
|
||||
final boolean isTextureEnabledBefore = GLStateManager.glIsEnabled(GL11.GL_TEXTURE_2D);
|
||||
final boolean isBlendEnabledBefore = GLStateManager.glIsEnabled(GL11.GL_BLEND);
|
||||
final int boundTextureBefore = GLStateManager.glGetInteger(GL11.GL_TEXTURE_BINDING_2D);
|
||||
boolean textureChanged = false;
|
||||
final boolean depthTestBefore = GLStateManager.getDepthTest().isEnabled();
|
||||
final boolean depthMaskBefore = GLStateManager.getDepthState().isEnabled();
|
||||
|
||||
ResourceLocation lastTexture = DUMMY_RESOURCE_LOCATION;
|
||||
setupFontDrawState();
|
||||
try (MemoryStack stack = stackPush()) {
|
||||
final FloatBuffer mvpBuf = stack.mallocFloat(16);
|
||||
GLStateManager.getProjectionMatrix().mul(GLStateManager.getModelViewMatrix(), scratchMvp);
|
||||
scratchMvp.get(mvpBuf);
|
||||
GLStateManager.glUniformMatrix4(mvpMatrixLocation, false, mvpBuf);
|
||||
}
|
||||
|
||||
flushLastTexture = DUMMY_RESOURCE_LOCATION;
|
||||
flushTextureChanged = false;
|
||||
drawCommands(batchCommands.elements(), deferredCmdWatermark, cmdCount, this);
|
||||
restoreFontDrawState(prevProgram, isTextureEnabledBefore, isBlendEnabledBefore, boundTextureBefore);
|
||||
restoreDepth(depthTestBefore, depthMaskBefore);
|
||||
|
||||
truncateBatchToWatermark();
|
||||
}
|
||||
|
||||
private void setupFontDrawState() {
|
||||
GLStateManager.enableTexture();
|
||||
GLStateManager.enableAlphaTest();
|
||||
GLStateManager.enableBlend();
|
||||
@@ -373,85 +546,88 @@ public class BatchingFontRenderer {
|
||||
GLStateManager.glUniform1f(AAStrength, FontConfig.fontAAStrength / 120.f);
|
||||
}
|
||||
GLStateManager.glUniform1f(alphaTestRefLocation, GLStateManager.getAlphaState().getReference());
|
||||
try (MemoryStack stack = stackPush()) {
|
||||
final FloatBuffer mvpBuf = stack.mallocFloat(16);
|
||||
GLStateManager.getProjectionMatrix().mul(GLStateManager.getModelViewMatrix(), scratchMvp);
|
||||
scratchMvp.get(mvpBuf);
|
||||
GLStateManager.glUniformMatrix4(mvpMatrixLocation, false, mvpBuf);
|
||||
}
|
||||
|
||||
if (fontVAO == 0) {
|
||||
fontVAO = GLStateManager.glGenVertexArrays();
|
||||
|
||||
GLStateManager.glBindVertexArray(fontVAO);
|
||||
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo);
|
||||
|
||||
ebo.bind();
|
||||
|
||||
// position
|
||||
GLStateManager.glVertexAttribPointer(0, 2, GL11.GL_FLOAT, false, VERTEX_SIZE, 0);
|
||||
GLStateManager.glEnableVertexAttribArray(0);
|
||||
|
||||
// texcoords
|
||||
GLStateManager.glVertexAttribPointer(1, 2, GL11.GL_FLOAT, false, VERTEX_SIZE, 8);
|
||||
GLStateManager.glEnableVertexAttribArray(1);
|
||||
|
||||
// color
|
||||
GLStateManager.glVertexAttribPointer(2, 4, GL11.GL_UNSIGNED_BYTE, true, VERTEX_SIZE, 16);
|
||||
GLStateManager.glEnableVertexAttribArray(2);
|
||||
|
||||
// tex bounds
|
||||
GLStateManager.glVertexAttribPointer(3, 4, GL11.GL_FLOAT, false, VERTEX_SIZE, 20);
|
||||
GLStateManager.glEnableVertexAttribArray(3);
|
||||
} else {
|
||||
GLStateManager.glBindVertexArray(fontVAO);
|
||||
}
|
||||
|
||||
GLStateManager.glBindVertexArray(fontVAO);
|
||||
if (vaoBuffer != pendingBuffer || vaoBase != pendingBase) {
|
||||
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, pendingBuffer);
|
||||
|
||||
// Use plain for loop to avoid allocations
|
||||
final FontDrawCmd[] cmdsData = batchCommands.elements();
|
||||
final int cmdsSize = batchCommands.size();
|
||||
for (int i = 0; i < cmdsSize; i++) {
|
||||
GLStateManager.glVertexAttribPointer(0, 2, GL11.GL_FLOAT, false, VERTEX_SIZE, pendingBase);
|
||||
GLStateManager.glVertexAttribPointer(1, 2, GL11.GL_FLOAT, false, VERTEX_SIZE, pendingBase + 8);
|
||||
GLStateManager.glVertexAttribPointer(2, 4, GL11.GL_UNSIGNED_BYTE, true, VERTEX_SIZE, pendingBase + 16);
|
||||
GLStateManager.glVertexAttribPointer(3, 4, GL11.GL_FLOAT, false, VERTEX_SIZE, pendingBase + 20);
|
||||
|
||||
vaoBuffer = pendingBuffer;
|
||||
vaoBase = pendingBase;
|
||||
}
|
||||
}
|
||||
|
||||
private static ResourceLocation flushLastTexture;
|
||||
private static boolean flushTextureChanged;
|
||||
|
||||
private static void drawCommands(FontDrawCmd[] cmdsData, int from, int to, BatchingFontRenderer owner) {
|
||||
for (int i = from; i < to; i++) {
|
||||
final FontDrawCmd cmd = cmdsData[i];
|
||||
if (!Objects.equals(lastTexture, cmd.texture)) {
|
||||
if (lastTexture == null) {
|
||||
if (!Objects.equals(flushLastTexture, cmd.texture)) {
|
||||
if (flushLastTexture == null) {
|
||||
GLStateManager.glEnable(GL11.GL_TEXTURE_2D);
|
||||
} else if (cmd.texture == null) {
|
||||
GLStateManager.glDisable(GL11.GL_TEXTURE_2D);
|
||||
}
|
||||
if (cmd.texture != null) {
|
||||
((FontRendererAccessor) underlying).angelica$bindTexture(cmd.texture);
|
||||
textureChanged = true;
|
||||
((FontRendererAccessor) owner.underlying).angelica$bindTexture(cmd.texture);
|
||||
flushTextureChanged = true;
|
||||
}
|
||||
lastTexture = cmd.texture;
|
||||
flushLastTexture = cmd.texture;
|
||||
}
|
||||
GLStateManager.glDrawElements(GL11.GL_TRIANGLES, cmd.idxCount, GL11.GL_UNSIGNED_SHORT, (long) cmd.startVtx * 2L);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static void restoreFontDrawState(int prevProgram, boolean textureEnabledBefore, boolean blendEnabledBefore, int boundTextureBefore) {
|
||||
GLStateManager.glUseProgram(prevProgram);
|
||||
|
||||
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
|
||||
GLStateManager.glBindVertexArray(0);
|
||||
|
||||
if (isTextureEnabledBefore) {
|
||||
GLStateManager.glEnable(GL11.GL_TEXTURE_2D);
|
||||
if (textureEnabledBefore) {
|
||||
GLStateManager.glEnable(GL11.GL_TEXTURE_2D);
|
||||
}
|
||||
if (!isBlendEnabledBefore) {
|
||||
if (!blendEnabledBefore) {
|
||||
GLStateManager.disableBlend();
|
||||
}
|
||||
if (textureChanged) {
|
||||
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, boundTextureBefore);
|
||||
if (flushTextureChanged) {
|
||||
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, boundTextureBefore);
|
||||
}
|
||||
|
||||
clearBatch();
|
||||
}
|
||||
|
||||
private void clearBatch() {
|
||||
// Clear for the next batch
|
||||
batchCommandPool.addAll(batchCommands);
|
||||
batchCommands.clear();
|
||||
vertexDataPos = 0;
|
||||
idxWriterIndex = 0;
|
||||
private static void restoreDepth(boolean testBefore, boolean maskBefore) {
|
||||
if (testBefore != GLStateManager.getDepthTest().isEnabled()) {
|
||||
if (testBefore) GLStateManager.enableDepthTest(); else GLStateManager.disableDepthTest();
|
||||
}
|
||||
if (maskBefore != GLStateManager.getDepthState().isEnabled()) {
|
||||
GLStateManager.glDepthMask(maskBefore);
|
||||
}
|
||||
}
|
||||
|
||||
private void truncateBatchToWatermark() {
|
||||
for (int i = batchCommands.size() - 1; i >= deferredCmdWatermark; i--) {
|
||||
batchCommandPool.add(batchCommands.get(i));
|
||||
}
|
||||
batchCommands.size(deferredCmdWatermark);
|
||||
vertexDataPos = deferredVertexPos;
|
||||
idxWriterIndex = deferredIdxPos;
|
||||
}
|
||||
|
||||
// === Actual text mesh generation
|
||||
|
||||
@@ -3,6 +3,8 @@ package com.gtnewhorizons.angelica.commands;
|
||||
// Debug commands adapted from Beddium by Ven and FalsePattern
|
||||
|
||||
import com.gtnewhorizons.angelica.debug.ChunkDebugMinimap;
|
||||
import com.gtnewhorizons.angelica.debug.flyby.FlybyRoute;
|
||||
import com.gtnewhorizons.angelica.debug.flyby.FlybyRunner;
|
||||
import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasDebugScreenHandler;
|
||||
import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasWorldRenderer;
|
||||
import net.minecraft.command.CommandBase;
|
||||
@@ -17,7 +19,7 @@ import java.util.List;
|
||||
|
||||
public class AngelicaCommand extends CommandBase {
|
||||
|
||||
private static final List<String> SUBCOMMANDS = Arrays.asList("wireframe", "fog", "minimap", "help");
|
||||
private static final List<String> SUBCOMMANDS = Arrays.asList("wireframe", "fog", "minimap", "flyby", "help");
|
||||
|
||||
@Override
|
||||
public String getCommandName() {
|
||||
@@ -26,12 +28,12 @@ public class AngelicaCommand extends CommandBase {
|
||||
|
||||
@Override
|
||||
public String getCommandUsage(ICommandSender sender) {
|
||||
return "/angelica <wireframe|fog|minimap|help>";
|
||||
return "/angelica <wireframe|fog|minimap|flyby|help>";
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getRequiredPermissionLevel() {
|
||||
return 0; // Available to all players (client-side only)
|
||||
return 2; // op
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -39,6 +41,14 @@ public class AngelicaCommand extends CommandBase {
|
||||
if (args.length == 1) {
|
||||
return getListOfStringsMatchingLastWord(args, SUBCOMMANDS.toArray(new String[0]));
|
||||
}
|
||||
if (args.length == 2 && "flyby".equalsIgnoreCase(args[0])) {
|
||||
final List<String> options = new ArrayList<>();
|
||||
for (FlybyRoute route : FlybyRoute.values()) {
|
||||
options.add(route.id());
|
||||
}
|
||||
options.add("cancel");
|
||||
return getListOfStringsMatchingLastWord(args, options.toArray(new String[0]));
|
||||
}
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
@@ -53,6 +63,7 @@ public class AngelicaCommand extends CommandBase {
|
||||
case "wireframe" -> handleWireframe(sender);
|
||||
case "fog" -> handleFog(sender);
|
||||
case "minimap" -> handleMinimap(sender);
|
||||
case "flyby" -> handleFlyby(sender, args);
|
||||
default -> sendHelp(sender);
|
||||
}
|
||||
}
|
||||
@@ -77,11 +88,62 @@ public class AngelicaCommand extends CommandBase {
|
||||
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.AQUA + "[Angelica] " + EnumChatFormatting.WHITE + "Chunk debug minimap: " + state));
|
||||
}
|
||||
|
||||
private void handleFlyby(ICommandSender sender, String[] args) {
|
||||
if (args.length >= 2 && "cancel".equalsIgnoreCase(args[1])) {
|
||||
FlybyRunner.INSTANCE.cancel();
|
||||
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.AQUA + "[Angelica] " + EnumChatFormatting.WHITE + "Flyby cancelled"));
|
||||
return;
|
||||
}
|
||||
|
||||
if (args.length < 2) {
|
||||
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.AQUA + "[Angelica] " + EnumChatFormatting.WHITE + "Usage: /angelica flyby <" + FlybyRoute.ids() + "|cancel> [length] [blocksPerTick]"));
|
||||
for (FlybyRoute r : FlybyRoute.values()) {
|
||||
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.GRAY + " " + r.id() + " - default " + r.defaultLength() + " " + r.lengthUnit()));
|
||||
}
|
||||
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.GRAY + " current: " + FlybyRunner.INSTANCE.describe()));
|
||||
return;
|
||||
}
|
||||
|
||||
final FlybyRoute route = FlybyRoute.byId(args[1]);
|
||||
if (route == null) {
|
||||
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "[Angelica] Unknown route '" + args[1] + "', expected one of " + FlybyRoute.ids()));
|
||||
return;
|
||||
}
|
||||
|
||||
int length = 0;
|
||||
if (args.length >= 3) {
|
||||
try {
|
||||
length = Integer.parseInt(args[2]);
|
||||
} catch (NumberFormatException e) {
|
||||
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "[Angelica] Not a length: " + args[2]));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
double speed = 0.0D;
|
||||
if (args.length >= 4) {
|
||||
try {
|
||||
speed = Double.parseDouble(args[3]);
|
||||
} catch (NumberFormatException e) {
|
||||
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "[Angelica] Not a speed: " + args[3]));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
FlybyRunner.INSTANCE.start(route, length, 0, speed);
|
||||
final int used = length > 0 ? length : route.defaultLength();
|
||||
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.AQUA + "[Angelica] " + EnumChatFormatting.WHITE
|
||||
+ "Flyby started: " + route.id() + " for " + used + " " + route.lengthUnit()
|
||||
+ " at " + route.speedOr(speed) + " b/t"
|
||||
+ " (" + route.toTicks(used, speed) + " ticks)"));
|
||||
}
|
||||
|
||||
private void sendHelp(ICommandSender sender) {
|
||||
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.AQUA + "[Angelica] Debug Commands:"));
|
||||
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.GRAY + " /angelica wireframe" + EnumChatFormatting.WHITE + " - Toggle wireframe rendering"));
|
||||
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.GRAY + " /angelica fog" + EnumChatFormatting.WHITE + " - Toggle fog debug on F3"));
|
||||
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.GRAY + " /angelica minimap" + EnumChatFormatting.WHITE + " - Toggle chunk debug overlay"));
|
||||
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.GRAY + " /angelica flyby <" + FlybyRoute.ids() + ">" + EnumChatFormatting.WHITE + " - Run a deterministic benchmark route"));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -5,6 +5,7 @@ import org.apache.logging.log4j.Logger;
|
||||
import org.lwjgl.opengl.ARBDebugOutput;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
|
||||
import com.gtnewhorizons.angelica.config.SystemProperties;
|
||||
import com.gtnewhorizons.angelica.glsm.GLStateManager;
|
||||
|
||||
/**
|
||||
@@ -15,8 +16,6 @@ import com.gtnewhorizons.angelica.glsm.GLStateManager;
|
||||
public class DriverCompatabilityCheck {
|
||||
private static final Logger LOGGER = LogManager.getLogger("Angelica");
|
||||
|
||||
private static final boolean DISABLE_NVIDIA_WORKAROUND = Boolean.getBoolean("angelica.disableNvidiaWorkaround");
|
||||
|
||||
/**
|
||||
* Should be called after GL context is created and GLStateManager is initialized.
|
||||
*/
|
||||
@@ -30,7 +29,7 @@ public class DriverCompatabilityCheck {
|
||||
LOGGER.info("OpenGL Version: {}", version);
|
||||
|
||||
if (vendor != null && vendor.contains("NVIDIA")) {
|
||||
if (DISABLE_NVIDIA_WORKAROUND) {
|
||||
if (SystemProperties.DISABLE_NVIDIA_WORKAROUND) {
|
||||
LOGGER.info("NVIDIA workaround disabled via -Dangelica.disableNvidiaWorkaround=true");
|
||||
} else {
|
||||
applyNvidiaWorkaround();
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
package com.gtnewhorizons.angelica.compat.bop;
|
||||
|
||||
public final class BopFogBlend {
|
||||
|
||||
public static final int NO_FOG = -1;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface ColorSource {
|
||||
/** Packed 0xRRGGBB, or {@link #NO_FOG}. */
|
||||
int fogColour(int x, int y, int z);
|
||||
}
|
||||
|
||||
private static Object cachedWorld;
|
||||
private static int cachedGeneration;
|
||||
private static int cachedX, cachedY, cachedZ, cachedDistance;
|
||||
private static float interiorR, interiorG, interiorB, interiorWeight;
|
||||
|
||||
private BopFogBlend() {}
|
||||
|
||||
public static void invalidate() {
|
||||
cachedWorld = null;
|
||||
}
|
||||
|
||||
public static void accumulate(Object world, int generation, ColorSource source, double posX, double posZ,
|
||||
int playerX, int playerY, int playerZ, int distance, float[] out) {
|
||||
|
||||
out[0] = 0;
|
||||
out[1] = 0;
|
||||
out[2] = 0;
|
||||
out[3] = 0;
|
||||
|
||||
final double xDiffLow = 1 - (posX - playerX);
|
||||
final double xDiffHigh = posX - playerX;
|
||||
final double zDiffLow = 1 - (posZ - playerZ);
|
||||
final double zDiffHigh = posZ - playerZ;
|
||||
|
||||
if (distance <= 0) {
|
||||
cell(source, 0, 0, xDiffLow, xDiffHigh, zDiffLow, zDiffHigh, playerX, playerY, playerZ, distance, out);
|
||||
return;
|
||||
}
|
||||
|
||||
if (world != cachedWorld || generation != cachedGeneration || playerX != cachedX || playerY != cachedY
|
||||
|| playerZ != cachedZ || distance != cachedDistance) {
|
||||
recomputeInterior(source, playerX, playerY, playerZ, distance);
|
||||
cachedWorld = world;
|
||||
cachedGeneration = generation;
|
||||
cachedX = playerX;
|
||||
cachedY = playerY;
|
||||
cachedZ = playerZ;
|
||||
cachedDistance = distance;
|
||||
}
|
||||
|
||||
out[0] = interiorR;
|
||||
out[1] = interiorG;
|
||||
out[2] = interiorB;
|
||||
out[3] = interiorWeight;
|
||||
|
||||
for (int z = -distance; z <= distance; ++z) {
|
||||
cell(source, -distance, z, xDiffLow, xDiffHigh, zDiffLow, zDiffHigh, playerX, playerY, playerZ, distance, out);
|
||||
cell(source, distance, z, xDiffLow, xDiffHigh, zDiffLow, zDiffHigh, playerX, playerY, playerZ, distance, out);
|
||||
}
|
||||
for (int x = -distance + 1; x <= distance - 1; ++x) {
|
||||
cell(source, x, -distance, xDiffLow, xDiffHigh, zDiffLow, zDiffHigh, playerX, playerY, playerZ, distance, out);
|
||||
cell(source, x, distance, xDiffLow, xDiffHigh, zDiffLow, zDiffHigh, playerX, playerY, playerZ, distance, out);
|
||||
}
|
||||
}
|
||||
|
||||
private static void recomputeInterior(ColorSource source, int playerX, int playerY, int playerZ, int distance) {
|
||||
float r = 0, g = 0, b = 0, weight = 0;
|
||||
for (int x = -distance + 1; x <= distance - 1; ++x) {
|
||||
for (int z = -distance + 1; z <= distance - 1; ++z) {
|
||||
final int colour = source.fogColour(playerX + x, playerY, playerZ + z);
|
||||
if (colour == NO_FOG) continue;
|
||||
r += (colour & 0xFF0000) >> 16;
|
||||
g += (colour & 0x00FF00) >> 8;
|
||||
b += colour & 0x0000FF;
|
||||
weight += 1;
|
||||
}
|
||||
}
|
||||
interiorR = r;
|
||||
interiorG = g;
|
||||
interiorB = b;
|
||||
interiorWeight = weight;
|
||||
}
|
||||
|
||||
private static void cell(ColorSource source, int x, int z, double xDiffLow, double xDiffHigh, double zDiffLow,
|
||||
double zDiffHigh, int playerX, int playerY, int playerZ, int distance, float[] out) {
|
||||
|
||||
final int colour = source.fogColour(playerX + x, playerY, playerZ + z);
|
||||
if (colour == NO_FOG) return;
|
||||
|
||||
float rPart = (colour & 0xFF0000) >> 16;
|
||||
float gPart = (colour & 0x00FF00) >> 8;
|
||||
float bPart = colour & 0x0000FF;
|
||||
float weightPart = 1;
|
||||
|
||||
if (x == -distance) {
|
||||
rPart *= xDiffLow;
|
||||
gPart *= xDiffLow;
|
||||
bPart *= xDiffLow;
|
||||
weightPart *= xDiffLow;
|
||||
} else if (x == distance) {
|
||||
rPart *= xDiffHigh;
|
||||
gPart *= xDiffHigh;
|
||||
bPart *= xDiffHigh;
|
||||
weightPart *= xDiffHigh;
|
||||
}
|
||||
|
||||
if (z == -distance) {
|
||||
rPart *= zDiffLow;
|
||||
gPart *= zDiffLow;
|
||||
bPart *= zDiffLow;
|
||||
weightPart *= zDiffLow;
|
||||
} else if (z == distance) {
|
||||
rPart *= zDiffHigh;
|
||||
gPart *= zDiffHigh;
|
||||
bPart *= zDiffHigh;
|
||||
weightPart *= zDiffHigh;
|
||||
}
|
||||
|
||||
out[0] += rPart;
|
||||
out[1] += gPart;
|
||||
out[2] += bPart;
|
||||
out[3] += weightPart;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.gtnewhorizons.angelica.compat.bop;
|
||||
|
||||
import biomesoplenty.client.fog.IBiomeFog;
|
||||
import net.minecraft.world.World;
|
||||
import net.minecraft.world.biome.BiomeGenBase;
|
||||
|
||||
public final class BopFogColorSource implements BopFogBlend.ColorSource {
|
||||
|
||||
public static final BopFogColorSource INSTANCE = new BopFogColorSource();
|
||||
|
||||
private World world;
|
||||
|
||||
private BopFogColorSource() {}
|
||||
|
||||
public BopFogColorSource forWorld(World world) {
|
||||
this.world = world;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int fogColour(int x, int y, int z) {
|
||||
final BiomeGenBase biome = FogBiomeCache.get(world, x, z);
|
||||
if (!(biome instanceof IBiomeFog fog)) return BopFogBlend.NO_FOG;
|
||||
return fog.getFogColour(x, y, z) & 0xFFFFFF;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.gtnewhorizons.angelica.compat.bop;
|
||||
|
||||
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
|
||||
import net.minecraft.world.World;
|
||||
import net.minecraft.world.biome.BiomeGenBase;
|
||||
|
||||
public final class FogBiomeCache {
|
||||
|
||||
private static final int MAX_ENTRIES = 16384;
|
||||
|
||||
private static final Long2ObjectOpenHashMap<BiomeGenBase> CACHE = new Long2ObjectOpenHashMap<>();
|
||||
private static World lastWorld;
|
||||
private static int generation;
|
||||
|
||||
private FogBiomeCache() {}
|
||||
|
||||
public static int generation() {
|
||||
return generation;
|
||||
}
|
||||
|
||||
public static BiomeGenBase get(World world, int x, int z) {
|
||||
if (world != lastWorld) {
|
||||
CACHE.clear();
|
||||
lastWorld = world;
|
||||
generation++;
|
||||
}
|
||||
final long key = ((long) x << 32) | (z & 0xFFFFFFFFL);
|
||||
BiomeGenBase biome = CACHE.get(key);
|
||||
if (biome == null) {
|
||||
biome = world.getBiomeGenForCoords(x, z);
|
||||
if (world.getChunkProvider().chunkExists(x >> 4, z >> 4)) {
|
||||
if (CACHE.size() >= MAX_ENTRIES) CACHE.clear();
|
||||
CACHE.put(key, biome);
|
||||
generation++;
|
||||
}
|
||||
}
|
||||
return biome;
|
||||
}
|
||||
}
|
||||
+116
-7
@@ -1,16 +1,25 @@
|
||||
package com.gtnewhorizons.angelica.compat.toremove;
|
||||
package com.gtnewhorizons.angelica.compat.mojang;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
|
||||
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat;
|
||||
|
||||
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
|
||||
import com.gtnewhorizons.angelica.api.tesr.TesrMaterial;
|
||||
import com.gtnewhorizons.angelica.api.tesr.TesrShader;
|
||||
import it.unimi.dsi.fastutil.Hash;
|
||||
import it.unimi.dsi.fastutil.objects.ObjectOpenCustomHashSet;
|
||||
import lombok.Getter;
|
||||
import net.coderbot.batchedentityrendering.impl.BatchVertexFormats;
|
||||
import net.coderbot.batchedentityrendering.impl.BlendingStateHolder;
|
||||
import net.coderbot.batchedentityrendering.impl.TransparencyType;
|
||||
import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition;
|
||||
import net.coderbot.iris.layer.GbufferPrograms;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
@@ -59,6 +68,72 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
|
||||
return TRANSLUCENT;
|
||||
}
|
||||
|
||||
private static MultiPhaseParameters.Builder tesrMaterialPhases(ResourceLocation texture, TesrMaterial material) {
|
||||
final MultiPhaseParameters.Builder b = MultiPhaseParameters.builder();
|
||||
if (texture != null) {
|
||||
b.texture(new RenderPhase.Texture(texture, false, false));
|
||||
}
|
||||
if (material.isNoCull()) {
|
||||
b.cull(DISABLE_CULLING);
|
||||
}
|
||||
if (material.isUnlit()) {
|
||||
b.texturing(NO_FFP_LIGHTING);
|
||||
}
|
||||
if (material.isNoDepthWrite()) {
|
||||
b.writeMaskState(COLOR_MASK);
|
||||
}
|
||||
if (material.isDepthOnly()) {
|
||||
b.writeMaskState(DEPTH_MASK);
|
||||
}
|
||||
if (material.cutoutAlpha() > 0) {
|
||||
b.alpha(new RenderPhase.Alpha(material.cutoutAlpha()));
|
||||
}
|
||||
if (material.isDepthEqual()) {
|
||||
b.depthTest(EQUAL_DEPTH_TEST);
|
||||
}
|
||||
switch (material.transparency()) {
|
||||
case TRANSLUCENT -> b.transparency(TRANSLUCENT_TRANSPARENCY);
|
||||
case ADDITIVE -> b.transparency(ADDITIVE_TRANSPARENCY);
|
||||
case ADDITIVE_ALPHA -> b.transparency(LIGHTNING_TRANSPARENCY);
|
||||
case GLINT -> b.transparency(GLINT_TRANSPARENCY);
|
||||
case OPAQUE -> {}
|
||||
}
|
||||
switch (material.special()) {
|
||||
case GLINT -> b.shader(SPECIAL_GLINT);
|
||||
case BEACON_BEAM -> b.shader(SPECIAL_BEACON_BEAM);
|
||||
case NONE -> {
|
||||
final TesrShader shader = material.shader();
|
||||
if (shader != null) {
|
||||
b.shader(new RenderPhase.Shader("angelica_tesr_shader_" + shader.name(), shader.bind(), shader.release()));
|
||||
}
|
||||
}
|
||||
}
|
||||
return b;
|
||||
}
|
||||
|
||||
private static final RenderPhase.Shader SPECIAL_GLINT = new RenderPhase.Shader("angelica_special_glint",
|
||||
() -> GbufferPrograms.setupSpecialRenderCondition(SpecialCondition.GLINT),
|
||||
GbufferPrograms::teardownSpecialRenderCondition);
|
||||
private static final RenderPhase.Shader SPECIAL_BEACON_BEAM = new RenderPhase.Shader("angelica_special_beacon_beam",
|
||||
() -> GbufferPrograms.setupSpecialRenderCondition(SpecialCondition.BEACON_BEAM),
|
||||
GbufferPrograms::teardownSpecialRenderCondition);
|
||||
|
||||
public static RenderLayer tesr(ResourceLocation texture, TesrMaterial material) {
|
||||
final MultiPhaseParameters.Builder b = tesrMaterialPhases(texture, material).shadeModel(SMOOTH_SHADE_MODEL).lightmap(ENABLE_LIGHTMAP);
|
||||
if (material.transparency() == TesrMaterial.Transparency.TRANSLUCENT) {
|
||||
b.target(TRANSLUCENT_TARGET);
|
||||
}
|
||||
final boolean sortsTranslucent = material.transparency() != TesrMaterial.Transparency.OPAQUE;
|
||||
return of("angelica_tesr_" + material.transparency().name().toLowerCase(Locale.ROOT),
|
||||
BatchVertexFormats.POSITION_COLOR_TEXTURE_LIGHTF_NORMAL, GL11.GL_QUADS, 65536, true, sortsTranslucent, b.build(false));
|
||||
}
|
||||
|
||||
public static RenderLayer tesrNoPass(ResourceLocation texture, TesrMaterial material) {
|
||||
return of("angelica_tesr_nopass_" + material.transparency().name().toLowerCase(Locale.ROOT),
|
||||
BatchVertexFormats.POSITION_COLOR_TEXTURE_LIGHTF_NORMAL, GL11.GL_QUADS, 65536, true, false,
|
||||
tesrMaterialPhases(texture, material).build(false));
|
||||
}
|
||||
|
||||
public static RenderLayer getOutline(ResourceLocation texture, RenderPhase.Cull cull) {
|
||||
return of("outline", DefaultVertexFormat.POSITION_COLOR_TEXTURE, 7, 256, RenderLayer.MultiPhaseParameters.builder().texture(new RenderPhase.Texture(texture, false, false)).cull(cull).depthTest(ALWAYS_DEPTH_TEST).alpha(ONE_TENTH_ALPHA).fog(NO_FOG).target(OUTLINE_TARGET).build(RenderLayer.OutlineMode.IS_OUTLINE));
|
||||
}
|
||||
@@ -67,17 +142,32 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
|
||||
return this.drawMode;
|
||||
}
|
||||
|
||||
static final class MultiPhase extends RenderLayer {
|
||||
public ResourceLocation getTextureId() {
|
||||
return null;
|
||||
}
|
||||
|
||||
static final class MultiPhase extends RenderLayer implements BlendingStateHolder {
|
||||
private static final ObjectOpenCustomHashSet<MultiPhase> CACHE;
|
||||
private final MultiPhaseParameters phases;
|
||||
private final int hash;
|
||||
private final Optional<RenderLayer> affectedOutline;
|
||||
|
||||
@Override
|
||||
public TransparencyType getTransparencyType() {
|
||||
return phases.transparency.getTransparencyType();
|
||||
}
|
||||
|
||||
private MultiPhase(String name, VertexFormat vertexFormat, int drawMode, int expectedBufferSize, boolean hasCrumbling, boolean translucent, MultiPhaseParameters phases) {
|
||||
super(name, vertexFormat, drawMode, expectedBufferSize, () -> {
|
||||
phases.phases.forEach(RenderPhase::startDrawing);
|
||||
final ImmutableList<RenderPhase> p = phases.phases;
|
||||
for (int i = 0, n = p.size(); i < n; i++) {
|
||||
p.get(i).startDrawing();
|
||||
}
|
||||
}, () -> {
|
||||
phases.phases.forEach(RenderPhase::endDrawing);
|
||||
final ImmutableList<RenderPhase> p = phases.phases;
|
||||
for (int i = 0, n = p.size(); i < n; i++) {
|
||||
p.get(i).endDrawing();
|
||||
}
|
||||
});
|
||||
this.phases = phases;
|
||||
this.affectedOutline = phases.outlineMode == RenderLayer.OutlineMode.AFFECTS_OUTLINE ? phases.texture.getId().map((arg2) -> {
|
||||
@@ -95,6 +185,11 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
|
||||
return this.affectedOutline;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResourceLocation getTextureId() {
|
||||
return phases.texture.getId().orElse(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(@Nullable Object object) {
|
||||
return this == object;
|
||||
@@ -148,10 +243,11 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
|
||||
private final RenderPhase.Target target;
|
||||
private final RenderPhase.Texturing texturing;
|
||||
private final RenderPhase.WriteMaskState writeMaskState;
|
||||
private final RenderPhase.Shader shader;
|
||||
private final OutlineMode outlineMode;
|
||||
private final ImmutableList<RenderPhase> phases;
|
||||
|
||||
private MultiPhaseParameters(RenderPhase.Texture texture, RenderPhase.Transparency transparency, RenderPhase.DiffuseLighting diffuseLighting, RenderPhase.ShadeModel shadeModel, RenderPhase.Alpha alpha, RenderPhase.DepthTest depthTest, RenderPhase.Cull cull, RenderPhase.Lightmap lightmap, RenderPhase.Fog fog, RenderPhase.Layering layering, RenderPhase.Target target, RenderPhase.Texturing texturing, RenderPhase.WriteMaskState writeMaskState, OutlineMode outlineMode) {
|
||||
private MultiPhaseParameters(RenderPhase.Texture texture, RenderPhase.Transparency transparency, RenderPhase.DiffuseLighting diffuseLighting, RenderPhase.ShadeModel shadeModel, RenderPhase.Alpha alpha, RenderPhase.DepthTest depthTest, RenderPhase.Cull cull, RenderPhase.Lightmap lightmap, RenderPhase.Fog fog, RenderPhase.Layering layering, RenderPhase.Target target, RenderPhase.Texturing texturing, RenderPhase.WriteMaskState writeMaskState, RenderPhase.Shader shader, OutlineMode outlineMode) {
|
||||
this.texture = texture;
|
||||
this.transparency = transparency;
|
||||
this.diffuseLighting = diffuseLighting;
|
||||
@@ -165,8 +261,9 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
|
||||
this.target = target;
|
||||
this.texturing = texturing;
|
||||
this.writeMaskState = writeMaskState;
|
||||
this.shader = shader;
|
||||
this.outlineMode = outlineMode;
|
||||
this.phases = ImmutableList.of(this.texture, this.transparency, this.diffuseLighting, this.shadeModel, this.alpha, this.depthTest, this.cull, this.lightmap, this.fog, this.layering, this.target, this.texturing, this.writeMaskState);
|
||||
this.phases = ImmutableList.of(this.texture, this.transparency, this.diffuseLighting, this.shadeModel, this.alpha, this.depthTest, this.cull, this.lightmap, this.fog, this.layering, this.target, this.texturing, this.writeMaskState, this.shader);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -209,6 +306,7 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
|
||||
private RenderPhase.Target target;
|
||||
private RenderPhase.Texturing texturing;
|
||||
private RenderPhase.WriteMaskState writeMaskState;
|
||||
private RenderPhase.Shader shader;
|
||||
|
||||
private Builder() {
|
||||
this.texture = RenderPhase.NO_TEXTURE ;
|
||||
@@ -224,6 +322,7 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
|
||||
this.target = RenderPhase.MAIN_TARGET;
|
||||
this.texturing = RenderPhase.DEFAULT_TEXTURING;
|
||||
this.writeMaskState = RenderPhase.ALL_MASK;
|
||||
this.shader = RenderPhase.NO_SHADER;
|
||||
}
|
||||
|
||||
public Builder texture(RenderPhase.Texture texture) {
|
||||
@@ -276,12 +375,22 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder writeMaskState(RenderPhase.WriteMaskState writeMaskState) {
|
||||
this.writeMaskState = writeMaskState;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder shader(RenderPhase.Shader shader) {
|
||||
this.shader = shader;
|
||||
return this;
|
||||
}
|
||||
|
||||
public MultiPhaseParameters build(boolean affectsOutline) {
|
||||
return this.build(affectsOutline ? RenderLayer.OutlineMode.AFFECTS_OUTLINE : RenderLayer.OutlineMode.NONE);
|
||||
}
|
||||
|
||||
public MultiPhaseParameters build(OutlineMode outlineMode) {
|
||||
return new MultiPhaseParameters(this.texture, this.transparency, this.diffuseLighting, this.shadeModel, this.alpha, this.depthTest, this.cull, this.lightmap, this.fog, this.layering, this.target, this.texturing, this.writeMaskState, outlineMode);
|
||||
return new MultiPhaseParameters(this.texture, this.transparency, this.diffuseLighting, this.shadeModel, this.alpha, this.depthTest, this.cull, this.lightmap, this.fog, this.layering, this.target, this.texturing, this.writeMaskState, this.shader, outlineMode);
|
||||
}
|
||||
}
|
||||
}
|
||||
+30
-39
@@ -1,7 +1,7 @@
|
||||
package com.gtnewhorizons.angelica.compat.toremove;
|
||||
package com.gtnewhorizons.angelica.compat.mojang;
|
||||
|
||||
import com.gtnewhorizons.angelica.AngelicaMod;
|
||||
import com.gtnewhorizons.angelica.glsm.GLStateManager;
|
||||
import net.coderbot.batchedentityrendering.impl.TransparencyType;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.renderer.texture.TextureManager;
|
||||
import net.minecraft.client.renderer.texture.TextureMap;
|
||||
@@ -17,7 +17,7 @@ public abstract class RenderPhase {
|
||||
protected final String name;
|
||||
protected Runnable beginAction;
|
||||
private final Runnable endAction;
|
||||
protected static final Transparency NO_TRANSPARENCY = new Transparency("no_transparency", GLStateManager::disableBlend, () -> {
|
||||
protected static final Transparency NO_TRANSPARENCY = new Transparency("no_transparency", TransparencyType.OPAQUE, GLStateManager::disableBlend, () -> {
|
||||
});
|
||||
protected static final Transparency ADDITIVE_TRANSPARENCY = new Transparency("additive_transparency", () -> {
|
||||
GLStateManager.enableBlend();
|
||||
@@ -33,14 +33,14 @@ public abstract class RenderPhase {
|
||||
GLStateManager.disableBlend();
|
||||
GLStateManager.defaultBlendFunc();
|
||||
});
|
||||
protected static final Transparency GLINT_TRANSPARENCY = new Transparency("glint_transparency", () -> {
|
||||
protected static final Transparency GLINT_TRANSPARENCY = new Transparency("glint_transparency", TransparencyType.DECAL, () -> {
|
||||
GLStateManager.enableBlend();
|
||||
GLStateManager.tryBlendFuncSeparate(GL11.GL_SRC_COLOR, GL11.GL_ONE, GL11.GL_ZERO, GL11.GL_ONE);
|
||||
}, () -> {
|
||||
GLStateManager.disableBlend();
|
||||
GLStateManager.defaultBlendFunc();
|
||||
});
|
||||
protected static final Transparency CRUMBLING_TRANSPARENCY = new Transparency("crumbling_transparency", () -> {
|
||||
protected static final Transparency CRUMBLING_TRANSPARENCY = new Transparency("crumbling_transparency", TransparencyType.DECAL, () -> {
|
||||
GLStateManager.enableBlend();
|
||||
GLStateManager.tryBlendFuncSeparate(GL11.GL_DST_COLOR, GL11.GL_SRC_COLOR, GL11.GL_ONE, GL11.GL_ZERO);
|
||||
}, () -> {
|
||||
@@ -63,6 +63,7 @@ public abstract class RenderPhase {
|
||||
protected static final Texture BLOCK_ATLAS_TEXTURE;
|
||||
protected static final Texture NO_TEXTURE;
|
||||
protected static final Texturing DEFAULT_TEXTURING;
|
||||
protected static final Texturing NO_FFP_LIGHTING;
|
||||
protected static final Lightmap ENABLE_LIGHTMAP;
|
||||
protected static final Lightmap DISABLE_LIGHTMAP;
|
||||
protected static final DiffuseLighting ENABLE_DIFFUSE_LIGHTING;
|
||||
@@ -82,6 +83,7 @@ public abstract class RenderPhase {
|
||||
protected static final Target MAIN_TARGET;
|
||||
protected static final Target OUTLINE_TARGET;
|
||||
protected static final Target TRANSLUCENT_TARGET;
|
||||
protected static final Shader NO_SHADER = new Shader("no_shader", () -> {}, () -> {});
|
||||
|
||||
public RenderPhase(String name, Runnable beginAction, Runnable endAction) {
|
||||
this.name = name;
|
||||
@@ -128,6 +130,7 @@ public abstract class RenderPhase {
|
||||
DEFAULT_TEXTURING = new Texturing("default_texturing", () -> {
|
||||
}, () -> {
|
||||
});
|
||||
NO_FFP_LIGHTING = new Texturing("no_ffp_lighting", GLStateManager::disableLighting, GLStateManager::enableLighting);
|
||||
ENABLE_LIGHTMAP = new Lightmap(true);
|
||||
DISABLE_LIGHTMAP = new Lightmap(false);
|
||||
ENABLE_DIFFUSE_LIGHTING = new DiffuseLighting(true);
|
||||
@@ -144,35 +147,23 @@ public abstract class RenderPhase {
|
||||
NO_FOG = new Fog("no_fog", () -> {
|
||||
}, () -> {
|
||||
});
|
||||
FOG = new Fog("fog", () -> {
|
||||
// Unclear what this should do
|
||||
// BackgroundRenderer.setFogBlack(), also levelFogColor()
|
||||
AngelicaMod.LOGGER.debug("Fog - Not setting level fog color");
|
||||
GLStateManager.enableFog();
|
||||
}, GLStateManager::disableFog);
|
||||
FOG = new Fog("fog", GLStateManager::enableFog, GLStateManager::disableFog);
|
||||
BLACK_FOG = new Fog("black_fog", () -> {
|
||||
GLStateManager.fogColor(0.0F, 0.0F, 0.0F, 1.0F);
|
||||
GLStateManager.enableFog();
|
||||
}, () -> {
|
||||
// Unclear what this should do
|
||||
// BackgroundRenderer.setFogBlack(), also levelFogColor()
|
||||
AngelicaMod.LOGGER.debug("Fog - Not setting level fog color");
|
||||
GLStateManager.disableFog();
|
||||
});
|
||||
}, GLStateManager::disableFog);
|
||||
MAIN_TARGET = new Target("main_target", () -> {
|
||||
}, () -> {
|
||||
});
|
||||
OUTLINE_TARGET = new Target("outline_target", () -> {
|
||||
// TODO: Sodium
|
||||
AngelicaMod.LOGGER.debug("NOT enabling the entity outline framebuffer");
|
||||
// TODO: Sodium - entity outline framebuffer
|
||||
//MinecraftClient.getInstance().worldRenderer.getEntityOutlinesFramebuffer().beginWrite(false);
|
||||
}, () -> {
|
||||
Minecraft.getMinecraft().getFramebuffer().bindFramebuffer(false);
|
||||
});
|
||||
TRANSLUCENT_TARGET = new Target("translucent_target", () -> {
|
||||
if (Minecraft.isFancyGraphicsEnabled()) {
|
||||
// TODO: Sodium
|
||||
AngelicaMod.LOGGER.debug("NOT enabling the translucent framebuffer");
|
||||
// TODO: Sodium - translucent framebuffer
|
||||
// MinecraftClient.getInstance().worldRenderer.getTranslucentFramebuffer().beginWrite(false);
|
||||
}
|
||||
|
||||
@@ -342,24 +333,7 @@ public abstract class RenderPhase {
|
||||
|
||||
public static class Lightmap extends Toggleable {
|
||||
public Lightmap(boolean lightmap) {
|
||||
super("lightmap", () -> {
|
||||
if (lightmap) {
|
||||
// TODO: Sodium - LightmapTextureManager
|
||||
AngelicaMod.LOGGER.debug("Lightmap - enable (not implemented)");
|
||||
// throw new RuntimeException("Not Implemented Yet");
|
||||
// MinecraftClient.getInstance().gameRenderer.getLightmapTextureManager().enable();
|
||||
|
||||
}
|
||||
|
||||
}, () -> {
|
||||
if (lightmap) {
|
||||
// TODO: Sodium - LightmapTextureManager
|
||||
AngelicaMod.LOGGER.debug("Lightmap - disable (not implemented)");
|
||||
// throw new RuntimeException("Not Implemented Yet");
|
||||
// MinecraftClient.getInstance().gameRenderer.getLightmapTextureManager().disable();
|
||||
}
|
||||
|
||||
}, lightmap);
|
||||
super("lightmap", () -> {}, () -> {}, lightmap);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -396,6 +370,12 @@ public abstract class RenderPhase {
|
||||
}
|
||||
|
||||
|
||||
public static class Shader extends RenderPhase {
|
||||
public Shader(String name, Runnable bind, Runnable release) {
|
||||
super(name, bind, release);
|
||||
}
|
||||
}
|
||||
|
||||
public static class Texturing extends RenderPhase {
|
||||
public Texturing(String string, Runnable runnable, Runnable runnable2) {
|
||||
super(string, runnable, runnable2);
|
||||
@@ -538,8 +518,19 @@ public abstract class RenderPhase {
|
||||
|
||||
|
||||
public static class Transparency extends RenderPhase {
|
||||
private final TransparencyType transparencyType;
|
||||
|
||||
public Transparency(String string, Runnable runnable, Runnable runnable2) {
|
||||
this(string, TransparencyType.GENERAL_TRANSPARENT, runnable, runnable2);
|
||||
}
|
||||
|
||||
public Transparency(String string, TransparencyType transparencyType, Runnable runnable, Runnable runnable2) {
|
||||
super(string, runnable, runnable2);
|
||||
this.transparencyType = transparencyType;
|
||||
}
|
||||
|
||||
public TransparencyType getTransparencyType() {
|
||||
return transparencyType;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
package com.gtnewhorizons.angelica.compat.thaumcraft;
|
||||
|
||||
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat;
|
||||
import com.gtnewhorizons.angelica.api.tesr.TesrMaterial;
|
||||
import com.gtnewhorizons.angelica.api.tesr.TesrMeshBuilder;
|
||||
import com.gtnewhorizons.angelica.api.tesr.TesrMeshSink;
|
||||
import com.gtnewhorizons.angelica.glsm.GLStateManager;
|
||||
import com.gtnewhorizons.angelica.rendering.tesr.AngelicaTesrMeshCache;
|
||||
import net.minecraft.client.renderer.RenderBlocks;
|
||||
import net.minecraft.client.renderer.Tessellator;
|
||||
import net.minecraft.client.renderer.texture.TextureMap;
|
||||
import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher;
|
||||
import net.minecraft.tileentity.TileEntity;
|
||||
import net.minecraft.util.IIcon;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import org.lwjgl.opengl.GL13;
|
||||
import thaumcraft.api.aspects.Aspect;
|
||||
import thaumcraft.common.blocks.BlockJar;
|
||||
import thaumcraft.common.config.ConfigBlocks;
|
||||
import thaumcraft.common.tiles.TileJarFillable;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public final class Tc4JarMeshes {
|
||||
|
||||
private static final double MIN_X = 0.25, MIN_Y = 0.0625, MIN_Z = 0.25, MAX_X = 0.75, MAX_Z = 0.75;
|
||||
private static final double OFF_X = -0.5, OFF_Y = 0.0, OFF_Z = -0.5;
|
||||
|
||||
private record LiquidKey(int color, int level64) {}
|
||||
|
||||
private static final class Holder {
|
||||
final Object cacheKey = new Object();
|
||||
final TesrMaterial material;
|
||||
|
||||
Holder(int color) {
|
||||
this.material = TesrMaterial.builder()
|
||||
.color(((color >> 16) & 0xFF) / 255f, ((color >> 8) & 0xFF) / 255f, (color & 0xFF) / 255f, 1f)
|
||||
.noCull().unlit().build();
|
||||
}
|
||||
}
|
||||
|
||||
private static final Map<LiquidKey, Holder> HOLDERS = new HashMap<>();
|
||||
private static final RenderBlocks FALLBACK_RENDER_BLOCKS = new RenderBlocks();
|
||||
|
||||
private static final ResourceLocation LABEL_TEXTURE = new ResourceLocation("thaumcraft", "textures/models/label.png");
|
||||
private static final TesrMaterial LABEL_MATERIAL = TesrMaterial.builder().color(1f, 1f, 1f, 1f).translucent().cutout(1f / 255f).noCull().build();
|
||||
private static final TesrMaterial TAG_MATERIAL = TesrMaterial.builder().color(0.1f, 0.1f, 0.1f, 0.8f).translucent().cutout(1f / 255f).noCull().unlit().build();
|
||||
private static final Object LABEL_KEY = new Object();
|
||||
private static final Map<Aspect, Object> TAG_KEYS = new HashMap<>();
|
||||
|
||||
private static final TesrMeshBuilder LABEL_BUILDER = sink -> {
|
||||
final Tessellator t = sink.angelica$bucket(DefaultVertexFormat.POSITION_TEXTURE_NORMAL, LABEL_TEXTURE, LABEL_MATERIAL);
|
||||
t.setNormal(0f, 0f, 1f);
|
||||
t.addVertexWithUV(-0.25, 0.25, 0.0, 0.0, 1.0);
|
||||
t.addVertexWithUV(0.25, 0.25, 0.0, 1.0, 1.0);
|
||||
t.addVertexWithUV(0.25, -0.25, 0.0, 1.0, 0.0);
|
||||
t.addVertexWithUV(-0.25, -0.25, 0.0, 0.0, 0.0);
|
||||
};
|
||||
|
||||
private static final TagBuilder TAG_BUILDER = new TagBuilder();
|
||||
|
||||
private static final class TagBuilder implements TesrMeshBuilder {
|
||||
private Aspect aspect;
|
||||
|
||||
@Override
|
||||
public void angelica$build(TesrMeshSink sink) {
|
||||
final Tessellator t = sink.angelica$bucket(DefaultVertexFormat.POSITION_TEXTURE_NORMAL, aspect.getImage(), TAG_MATERIAL);
|
||||
t.setNormal(0f, 0f, 1f);
|
||||
t.addVertexWithUV(-8.0, 8.0, 0.0, 0.0, 1.0);
|
||||
t.addVertexWithUV(8.0, 8.0, 0.0, 1.0, 1.0);
|
||||
t.addVertexWithUV(8.0, -8.0, 0.0, 1.0, 0.0);
|
||||
t.addVertexWithUV(-8.0, -8.0, 0.0, 0.0, 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
public static void renderLabelBacking(TileEntity te) {
|
||||
applyBrightness(jarBrightness(te));
|
||||
AngelicaTesrMeshCache.INSTANCE.renderCached(LABEL_KEY, LABEL_BUILDER);
|
||||
}
|
||||
|
||||
public static void renderLabelTag(Aspect aspect, TileEntity te) {
|
||||
applyBrightness(jarBrightness(te));
|
||||
final Object key = TAG_KEYS.computeIfAbsent(aspect, k -> new Object());
|
||||
TAG_BUILDER.aspect = aspect;
|
||||
AngelicaTesrMeshCache.INSTANCE.renderCached(key, TAG_BUILDER);
|
||||
}
|
||||
|
||||
private static int jarBrightness(TileEntity te) {
|
||||
if (te == null || te.getWorldObj() == null) return 200;
|
||||
return Math.max(200, ConfigBlocks.blockJar.getMixedBrightnessForBlock(te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord));
|
||||
}
|
||||
|
||||
private static void applyBrightness(int bright) {
|
||||
GLStateManager.setLightmapTextureCoords(GL13.GL_TEXTURE1, bright % 65536, (float) (bright / 65536));
|
||||
}
|
||||
|
||||
private Tc4JarMeshes() {}
|
||||
|
||||
public static RenderBlocks fallbackRenderBlocks() {
|
||||
return FALLBACK_RENDER_BLOCKS;
|
||||
}
|
||||
|
||||
public static boolean renderLiquid(TileJarFillable te) {
|
||||
if (TileEntityRendererDispatcher.instance.field_147553_e == null) {
|
||||
return true;
|
||||
}
|
||||
final BlockJar jar = (BlockJar) ConfigBlocks.blockJar;
|
||||
final IIcon icon = jar.iconLiquid;
|
||||
if (icon == null || te.maxAmount <= 0) {
|
||||
return false;
|
||||
}
|
||||
final int level64 = Math.round(te.amount * 64f / te.maxAmount);
|
||||
if (level64 <= 0) {
|
||||
return true;
|
||||
}
|
||||
final int color = te.aspect != null ? te.aspect.getColor() : 0xFFFFFF;
|
||||
|
||||
applyBrightness(jarBrightness(te));
|
||||
|
||||
final Holder holder = HOLDERS.computeIfAbsent(new LiquidKey(color, level64), k -> new Holder(k.color()));
|
||||
GLStateManager.glPushMatrix();
|
||||
GLStateManager.glRotatef(180.0f, 1.0f, 0.0f, 0.0f);
|
||||
BUILDER.material = holder.material;
|
||||
BUILDER.level64 = level64;
|
||||
BUILDER.icon = icon;
|
||||
AngelicaTesrMeshCache.INSTANCE.renderCached(holder.cacheKey, BUILDER);
|
||||
GLStateManager.glPopMatrix();
|
||||
return true;
|
||||
}
|
||||
|
||||
private static final Builder BUILDER = new Builder();
|
||||
|
||||
private static final class Builder implements TesrMeshBuilder {
|
||||
private TesrMaterial material;
|
||||
private int level64;
|
||||
private IIcon icon;
|
||||
|
||||
@Override
|
||||
public void angelica$build(TesrMeshSink sink) {
|
||||
build(sink, material, level64, icon);
|
||||
}
|
||||
}
|
||||
|
||||
private static void build(TesrMeshSink sink, TesrMaterial material, int level64, IIcon icon) {
|
||||
final Tessellator t = sink.angelica$bucket(DefaultVertexFormat.POSITION_TEXTURE_NORMAL, TextureMap.locationBlocksTexture, material);
|
||||
final double maxY = MIN_Y + level64 / 64f * 0.625f;
|
||||
|
||||
final double x1 = OFF_X + MIN_X, x2 = OFF_X + MAX_X;
|
||||
final double y1 = OFF_Y + MIN_Y, y2 = OFF_Y + maxY;
|
||||
final double z1 = OFF_Z + MIN_Z, z2 = OFF_Z + MAX_Z;
|
||||
|
||||
// Horizontal faces
|
||||
double u1 = icon.getInterpolatedU(MIN_X * 16.0);
|
||||
double u2 = icon.getInterpolatedU(MAX_X * 16.0);
|
||||
double v1 = icon.getInterpolatedV(MIN_Z * 16.0);
|
||||
double v2 = icon.getInterpolatedV(MAX_Z * 16.0);
|
||||
// YNeg
|
||||
t.addVertexWithUV(x1, y1, z2, u1, v2);
|
||||
t.addVertexWithUV(x1, y1, z1, u1, v1);
|
||||
t.addVertexWithUV(x2, y1, z1, u2, v1);
|
||||
t.addVertexWithUV(x2, y1, z2, u2, v2);
|
||||
// YPos
|
||||
t.addVertexWithUV(x2, y2, z2, u2, v2);
|
||||
t.addVertexWithUV(x2, y2, z1, u2, v1);
|
||||
t.addVertexWithUV(x1, y2, z1, u1, v1);
|
||||
t.addVertexWithUV(x1, y2, z2, u1, v2);
|
||||
|
||||
// Z faces
|
||||
v1 = icon.getInterpolatedV(16.0 - maxY * 16.0);
|
||||
v2 = icon.getInterpolatedV(16.0 - MIN_Y * 16.0);
|
||||
// ZNeg
|
||||
t.addVertexWithUV(x1, y2, z1, u2, v1);
|
||||
t.addVertexWithUV(x2, y2, z1, u1, v1);
|
||||
t.addVertexWithUV(x2, y1, z1, u1, v2);
|
||||
t.addVertexWithUV(x1, y1, z1, u2, v2);
|
||||
// ZPos
|
||||
t.addVertexWithUV(x1, y2, z2, u1, v1);
|
||||
t.addVertexWithUV(x1, y1, z2, u1, v2);
|
||||
t.addVertexWithUV(x2, y1, z2, u2, v2);
|
||||
t.addVertexWithUV(x2, y2, z2, u2, v1);
|
||||
|
||||
// X faces
|
||||
u1 = icon.getInterpolatedU(MIN_Z * 16.0);
|
||||
u2 = icon.getInterpolatedU(MAX_Z * 16.0);
|
||||
// XNeg
|
||||
t.addVertexWithUV(x1, y2, z2, u2, v1);
|
||||
t.addVertexWithUV(x1, y2, z1, u1, v1);
|
||||
t.addVertexWithUV(x1, y1, z1, u1, v2);
|
||||
t.addVertexWithUV(x1, y1, z2, u2, v2);
|
||||
// XPos
|
||||
t.addVertexWithUV(x2, y1, z2, u1, v2);
|
||||
t.addVertexWithUV(x2, y1, z1, u2, v2);
|
||||
t.addVertexWithUV(x2, y2, z1, u2, v1);
|
||||
t.addVertexWithUV(x2, y2, z2, u1, v1);
|
||||
}
|
||||
}
|
||||
@@ -1,19 +1,23 @@
|
||||
package com.gtnewhorizons.angelica.config;
|
||||
|
||||
import com.gtnewhorizon.gtnhlib.config.Config;
|
||||
import com.gtnewhorizons.angelica.rendering.culling.GpuCulling;
|
||||
|
||||
@Config(modid = "angelica", filename = "angelica-modules")
|
||||
public class AngelicaConfig {
|
||||
@Config.Comment("Enable Celeritas terrain rendering")
|
||||
@Config.DefaultBoolean(true)
|
||||
@Config.RequiresMcRestart
|
||||
public static boolean enableCeleritas;
|
||||
|
||||
@Config.Comment("Enable multi-threaded chunk building for improved performance [Requires Celeritas]")
|
||||
@Config.Comment("Enable multi-threaded chunk building for improved performance")
|
||||
@Config.DefaultBoolean(true)
|
||||
@Config.RequiresWorldRestart
|
||||
public static boolean enableThreadedChunkBuilding;
|
||||
|
||||
@Config.Comment({
|
||||
"GPU-driven chunk culling mode (requires compute shader support):",
|
||||
" CPU_ONLY - Compute culling off; CPU emitter handles culling.",
|
||||
" COMPUTE - GPU compute frustum cull."
|
||||
})
|
||||
@Config.DefaultEnum("CPU_ONLY")
|
||||
public static GpuCullingMode gpuCullingMode;
|
||||
|
||||
@Config.Comment("Number of chunk builder threads. 0 = auto-detect, -1 = use single-threaded fallback")
|
||||
@Config.DefaultInt(0)
|
||||
@Config.RangeInt(min = -1, max = 16)
|
||||
@@ -38,7 +42,7 @@ public class AngelicaConfig {
|
||||
@Config.Ignore()
|
||||
public static boolean enableTestBlocks;
|
||||
|
||||
@Config.Comment("Enable Iris Shaders [Requires Celeritas]")
|
||||
@Config.Comment("Enable Iris Shaders")
|
||||
@Config.DefaultBoolean(true)
|
||||
@Config.RequiresMcRestart
|
||||
public static boolean enableIris;
|
||||
@@ -112,6 +116,51 @@ public class AngelicaConfig {
|
||||
@Config.RequiresMcRestart
|
||||
public static boolean enableFontRenderer;
|
||||
|
||||
@Config.Comment("Collapse vanilla sign text into a single batched draw per sign (requires font batching)")
|
||||
@Config.DefaultBoolean(true)
|
||||
@Config.RequiresMcRestart
|
||||
public static boolean enableTESRSignCache;
|
||||
|
||||
@Config.Comment("Cache the vanilla chest mesh and share it across chests")
|
||||
@Config.DefaultBoolean(true)
|
||||
@Config.RequiresMcRestart
|
||||
public static boolean enableTESRChestCache;
|
||||
|
||||
@Config.Comment("Batch and instance living-entity model parts on FFP-managed passes")
|
||||
@Config.DefaultBoolean(true)
|
||||
@Config.RequiresMcRestart
|
||||
public static boolean enableEntityBatching;
|
||||
|
||||
@Config.Comment("Skip the end-of-frame shader buffer copy by ping-ponging buffers. Disable if a shader pack misrenders.")
|
||||
@Config.DefaultBoolean(true)
|
||||
@Config.RequiresMcRestart
|
||||
public static boolean shaderParityFlip;
|
||||
|
||||
@Config.Comment("Skip the end-of-frame glFlush before the buffer swap [Experimental]")
|
||||
@Config.DefaultBoolean(false)
|
||||
@Config.RequiresMcRestart
|
||||
public static boolean skipEndOfFrameFlush;
|
||||
|
||||
@Config.Comment("Cache the vanilla skull mesh per skull type/player skin and batch skull draws")
|
||||
@Config.DefaultBoolean(true)
|
||||
@Config.RequiresMcRestart
|
||||
public static boolean enableTESRSkullCache;
|
||||
|
||||
@Config.Comment("Cache the Thaumcraft jar liquid and batch jar draws")
|
||||
@Config.DefaultBoolean(true)
|
||||
@Config.RequiresMcRestart
|
||||
public static boolean enableTESRJarCache;
|
||||
|
||||
@Config.Comment("Cache the vanilla beacon beam mesh and batch beam draws")
|
||||
@Config.DefaultBoolean(true)
|
||||
@Config.RequiresMcRestart
|
||||
public static boolean enableTESRBeaconCache;
|
||||
|
||||
@Config.Comment("Route tile-entity renderers implementing TesrMeshProvider through the batched mesh cache")
|
||||
@Config.DefaultBoolean(true)
|
||||
@Config.RequiresMcRestart
|
||||
public static boolean enableTESRProviderDispatch;
|
||||
|
||||
@Config.Comment("Enable full RGB color support (16.7M colors) using &#RRGGBB syntax in text")
|
||||
@Config.DefaultBoolean(true)
|
||||
public static boolean enableRGBColors;
|
||||
@@ -160,11 +209,6 @@ public class AngelicaConfig {
|
||||
@Config.RequiresMcRestart
|
||||
public static boolean speedupAnimations;
|
||||
|
||||
@Config.Comment("Optimize Texture Loading. [From Hodgepodge]")
|
||||
@Config.DefaultBoolean(true)
|
||||
@Config.RequiresMcRestart
|
||||
public static boolean optimizeTextureLoading;
|
||||
|
||||
@Config.Comment("Fix RenderBlockFluid reading the block type from the world access multiple times")
|
||||
@Config.DefaultBoolean(true)
|
||||
@Config.RequiresMcRestart
|
||||
@@ -278,6 +322,7 @@ public class AngelicaConfig {
|
||||
|
||||
@Config.Comment("Register HardcodedCustomUniforms in Iris Shaders. May help with compatibility in certain shader packs")
|
||||
@Config.DefaultBoolean(false)
|
||||
@Config.RequiresMcRestart
|
||||
public static boolean enableHardcodedCustomUniforms;
|
||||
|
||||
@Config.Comment("Modern MC_VERSION to try if shader pack has no 1.7.10 section. 0 = default (260101)")
|
||||
@@ -289,6 +334,19 @@ public class AngelicaConfig {
|
||||
@Config.DefaultBoolean(true)
|
||||
public static boolean defineIsIris;
|
||||
|
||||
@Config.Comment("Cull tile entities in the Iris shadow pass.")
|
||||
@Config.DefaultBoolean(true)
|
||||
public static boolean cullShadowTileEntities;
|
||||
|
||||
@Config.Comment("Max distance (blocks) a tile entity is re-drawn into the shadow pass when cullShadowTileEntities is on")
|
||||
@Config.DefaultInt(32)
|
||||
@Config.RangeInt(min = 8, max = 256)
|
||||
public static int shadowTileEntityMaxDistance;
|
||||
|
||||
@Config.Comment({"Skip tile entities whose block already renders in the terrain mesh (getRenderType() != -1) from the shadow pass"})
|
||||
@Config.DefaultBoolean(true)
|
||||
public static boolean shadowSkipInMeshTileEntities;
|
||||
|
||||
@Config.Comment("ASM transformer exclusion narrowing for mod compatibility. Disable per-mod if narrowing causes class loading issues.")
|
||||
public static TransformerCompat transformerCompat = new TransformerCompat();
|
||||
|
||||
@@ -366,4 +424,22 @@ public class AngelicaConfig {
|
||||
@Config.DefaultBoolean(true)
|
||||
@Config.RequiresMcRestart
|
||||
public static boolean entityModernDamageOverlay;
|
||||
|
||||
public enum GLProfile { AUTO, CORE, ES }
|
||||
|
||||
@Config.Comment("GL context profile: AUTO (probes Core first), CORE (desktop only), ES (GLES 3.2 only). Also settable via -Dangelica.glProfile=auto|core|es.")
|
||||
@Config.DefaultEnum("AUTO")
|
||||
@Config.RequiresMcRestart
|
||||
public static GLProfile glProfile;
|
||||
|
||||
public static void applyGpuCullingMode() {
|
||||
GpuCulling.setMode(gpuCullingMode == null ? GpuCullingMode.CPU_ONLY : gpuCullingMode);
|
||||
}
|
||||
|
||||
public static GLProfile getEffectiveGlProfile() {
|
||||
final String sys = SystemProperties.GL_PROFILE.trim().toUpperCase();
|
||||
if ("GLES".equals(sys)) return GLProfile.ES;
|
||||
if (sys.isEmpty()) return glProfile;
|
||||
try { return GLProfile.valueOf(sys); } catch (IllegalArgumentException e) { return glProfile; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.gtnewhorizons.angelica.config;
|
||||
|
||||
import me.jellysquid.mods.sodium.client.gui.options.named.NamedState;
|
||||
|
||||
public enum GpuCullingMode implements NamedState {
|
||||
CPU_ONLY(false, "options.angelica.gpuCullingMode.cpu_only"),
|
||||
COMPUTE (true, "options.angelica.gpuCullingMode.compute");
|
||||
|
||||
private final boolean compute;
|
||||
private final String key;
|
||||
|
||||
GpuCullingMode(boolean compute, String key) {
|
||||
this.compute = compute;
|
||||
this.key = key;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getKey() {
|
||||
return key;
|
||||
}
|
||||
|
||||
public boolean computeEnabled() { return compute; }
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package com.gtnewhorizons.angelica.debug.flyby;
|
||||
|
||||
/**
|
||||
* A deterministic camera path, expressed relative to the position the player held when the run was started.
|
||||
* <p>
|
||||
* Moving routes are measured in blocks rather than tick.
|
||||
*/
|
||||
public enum FlybyRoute {
|
||||
/**
|
||||
* Straight line path, 512 blocks (32 chunks) by default.
|
||||
*/
|
||||
STRAIGHT("straight", Kind.STRAIGHT, 0.5D, 0.0D, 512),
|
||||
|
||||
/**
|
||||
* Stationary rotation, 720 degrees by default.
|
||||
*/
|
||||
PAN("pan", Kind.ROTATE, 0.0D, 1.5D, 720),
|
||||
|
||||
/**
|
||||
* Closed square: four legs of {@code length} blocks joined by four 90-degree turns, ending where it started.
|
||||
*/
|
||||
CIRCUIT("circuit", Kind.SQUARE, 0.5D, 4.0D, 128),
|
||||
|
||||
/** Fixed vantage, no motion, measured in ticks. */
|
||||
STATIC("static", Kind.STILL, 0.0D, 0.0D, 600);
|
||||
|
||||
public enum Kind { STRAIGHT, ROTATE, SQUARE, STILL }
|
||||
|
||||
public static final int CIRCUIT_LEGS = 4;
|
||||
public static final double CIRCUIT_TURN_DEGREES = 90.0D;
|
||||
|
||||
private final String id;
|
||||
private final Kind kind;
|
||||
private final double blocksPerTick;
|
||||
private final double degreesPerTick;
|
||||
private final int defaultLength;
|
||||
|
||||
FlybyRoute(String id, Kind kind, double blocksPerTick, double degreesPerTick, int defaultLength) {
|
||||
this.id = id;
|
||||
this.kind = kind;
|
||||
this.blocksPerTick = blocksPerTick;
|
||||
this.degreesPerTick = degreesPerTick;
|
||||
this.defaultLength = defaultLength;
|
||||
}
|
||||
|
||||
public String id() {
|
||||
return this.id;
|
||||
}
|
||||
|
||||
public Kind kind() {
|
||||
return this.kind;
|
||||
}
|
||||
|
||||
public double blocksPerTick() {
|
||||
return this.blocksPerTick;
|
||||
}
|
||||
|
||||
public double degreesPerTick() {
|
||||
return this.degreesPerTick;
|
||||
}
|
||||
|
||||
public int defaultLength() {
|
||||
return this.defaultLength;
|
||||
}
|
||||
|
||||
public String lengthUnit() {
|
||||
return switch (this.kind) {
|
||||
case STRAIGHT -> "blocks";
|
||||
case SQUARE -> "blocks per leg";
|
||||
case ROTATE -> "degrees";
|
||||
case STILL -> "ticks";
|
||||
};
|
||||
}
|
||||
|
||||
public double speedOr(double override) {
|
||||
return override > 0.0D ? override : this.blocksPerTick;
|
||||
}
|
||||
|
||||
public int legTicks(int length, double speed) {
|
||||
return (int) Math.ceil(length / this.speedOr(speed));
|
||||
}
|
||||
|
||||
public int turnTicks() {
|
||||
return (int) Math.ceil(CIRCUIT_TURN_DEGREES / this.degreesPerTick);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a run length in {@link #lengthUnit()} into ticks at {@code speed} blocks per tick.
|
||||
*/
|
||||
public int toTicks(int length, double speed) {
|
||||
if (length <= 0) length = this.defaultLength;
|
||||
return switch (this.kind) {
|
||||
case STRAIGHT -> this.legTicks(length, speed);
|
||||
case ROTATE -> (int) Math.ceil(length / this.degreesPerTick);
|
||||
case SQUARE -> CIRCUIT_LEGS * (this.legTicks(length, speed) + this.turnTicks());
|
||||
case STILL -> length;
|
||||
};
|
||||
}
|
||||
|
||||
public static FlybyRoute byId(String id) {
|
||||
for (FlybyRoute route : values()) {
|
||||
if (route.id.equalsIgnoreCase(id)) {
|
||||
return route;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static String ids() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (FlybyRoute route : values()) {
|
||||
if (sb.length() > 0) sb.append('|');
|
||||
sb.append(route.id);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,431 @@
|
||||
package com.gtnewhorizons.angelica.debug.flyby;
|
||||
|
||||
import com.gtnewhorizons.angelica.config.SystemProperties;
|
||||
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
|
||||
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
|
||||
import cpw.mods.fml.common.gameevent.TickEvent;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.entity.EntityClientPlayerMP;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.util.ChatComponentText;
|
||||
import net.minecraft.util.EnumChatFormatting;
|
||||
import net.minecraft.world.WorldServer;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/** Flies a deterministic camera path */
|
||||
public final class FlybyRunner {
|
||||
public static final FlybyRunner INSTANCE = new FlybyRunner();
|
||||
|
||||
private static final Logger LOGGER = LogManager.getLogger("Angelica/Flyby");
|
||||
private static final long[] NO_FRAMES = new long[0];
|
||||
private static final double[] NO_PATH = new double[0];
|
||||
private static final float[] NO_YAW = new float[0];
|
||||
private static final byte[] NO_PHASE = new byte[0];
|
||||
private static final int MAX_RECORDED_FRAMES = 200_000;
|
||||
private static final long FIXED_TIME_OF_DAY = 6000L;
|
||||
|
||||
private enum State { IDLE, WAITING, WARMUP, RUNNING, SETTLE, EXITING, DONE }
|
||||
|
||||
private static final int EXIT_TICKS = 20;
|
||||
private static final int SETTLE_TICKS = 40;
|
||||
|
||||
private State state = State.IDLE;
|
||||
private FlybyRoute route;
|
||||
private int warmupTicks;
|
||||
private int runLength;
|
||||
private double speed;
|
||||
private int runTicks;
|
||||
private int tick;
|
||||
private boolean waitForTracy;
|
||||
private boolean exitWhenDone;
|
||||
private boolean startedFromProperties;
|
||||
private volatile boolean freezeRequested;
|
||||
|
||||
private double originX, originY, originZ;
|
||||
private float originYaw, originPitch;
|
||||
|
||||
private double[] pathX = NO_PATH;
|
||||
private double[] pathZ = NO_PATH;
|
||||
private float[] pathYaw = NO_YAW;
|
||||
private byte[] pathLeg = NO_PHASE;
|
||||
private byte[] pathTurning = NO_PHASE;
|
||||
|
||||
private long plotLeg;
|
||||
private long plotTurning;
|
||||
private int lastPhase = -1;
|
||||
|
||||
private long[] frameTimesNs = NO_FRAMES;
|
||||
private int frameCount;
|
||||
private boolean framesTruncated;
|
||||
private long lastFrameNs;
|
||||
private long runStartNs;
|
||||
|
||||
private FlybyRunner() {}
|
||||
|
||||
public void startFromProperties() {
|
||||
final String id = SystemProperties.FLYBY_ROUTE;
|
||||
if (id == null || id.isEmpty()) return;
|
||||
|
||||
final FlybyRoute configured = FlybyRoute.byId(id);
|
||||
if (configured == null) {
|
||||
LOGGER.error("Unknown flyby route '{}', expected one of {}", id, FlybyRoute.ids());
|
||||
return;
|
||||
}
|
||||
|
||||
this.startedFromProperties = true;
|
||||
this.start(configured, SystemProperties.FLYBY_LENGTH, SystemProperties.FLYBY_WARMUP_TICKS, SystemProperties.FLYBY_SPEED);
|
||||
this.waitForTracy = SystemProperties.FLYBY_WAIT_FOR_TRACY;
|
||||
this.exitWhenDone = SystemProperties.FLYBY_EXIT_WHEN_DONE;
|
||||
LOGGER.info("Flyby started from properties: route={} warmup={} length={} {} ({} ticks) waitForTracy={} exitWhenDone={}",
|
||||
configured.id(), this.warmupTicks, this.runLength, configured.lengthUnit(), this.runTicks,
|
||||
this.waitForTracy, this.exitWhenDone);
|
||||
}
|
||||
|
||||
public void start(FlybyRoute route, int length, int warmupTicks, double speed) {
|
||||
this.route = route;
|
||||
this.speed = speed;
|
||||
this.runLength = length > 0 ? length : route.defaultLength();
|
||||
this.runTicks = route.toTicks(this.runLength, speed);
|
||||
this.warmupTicks = Math.max(0, warmupTicks);
|
||||
this.tick = 0;
|
||||
this.frameCount = 0;
|
||||
this.framesTruncated = false;
|
||||
this.waitForTracy = false;
|
||||
this.exitWhenDone = false;
|
||||
this.state = State.WAITING;
|
||||
}
|
||||
|
||||
public boolean isActive() {
|
||||
return this.state != State.IDLE && this.state != State.DONE;
|
||||
}
|
||||
|
||||
public String describe() {
|
||||
if (this.route == null) return "idle";
|
||||
return this.route.id() + " " + this.state + " tick " + this.tick + "/" + this.runTicks;
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public void onClientTick(TickEvent.ClientTickEvent event) {
|
||||
if (event.phase != TickEvent.Phase.END || this.state == State.IDLE || this.state == State.DONE) return;
|
||||
|
||||
final Minecraft mc = Minecraft.getMinecraft();
|
||||
final EntityClientPlayerMP player = mc.thePlayer;
|
||||
if (player == null || mc.theWorld == null) return;
|
||||
|
||||
switch (this.state) {
|
||||
case WAITING -> {
|
||||
if (this.waitForTracy && !Tracy.isConnected()) return;
|
||||
this.begin(mc, player);
|
||||
}
|
||||
case WARMUP -> {
|
||||
this.applyPosition(player, 0);
|
||||
if (++this.tick >= this.warmupTicks) {
|
||||
this.tick = 0;
|
||||
this.beginMeasuring();
|
||||
}
|
||||
}
|
||||
case RUNNING -> {
|
||||
this.applyPosition(player, this.tick);
|
||||
this.emitPhase(this.tick);
|
||||
if (++this.tick > this.runTicks) {
|
||||
this.finish(mc, player);
|
||||
}
|
||||
}
|
||||
case SETTLE -> {
|
||||
this.holdPosition(player);
|
||||
if (++this.tick >= SETTLE_TICKS) {
|
||||
this.teardown(mc, player);
|
||||
}
|
||||
}
|
||||
case EXITING -> {
|
||||
if (++this.tick >= EXIT_TICKS) {
|
||||
this.state = State.DONE;
|
||||
LOGGER.info("Flyby complete, shutting down so the capture can finalise");
|
||||
mc.shutdown();
|
||||
}
|
||||
}
|
||||
default -> { }
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public void onRenderTick(TickEvent.RenderTickEvent event) {
|
||||
if (event.phase != TickEvent.Phase.END || this.state != State.RUNNING) return;
|
||||
|
||||
final long now = System.nanoTime();
|
||||
if (this.lastFrameNs != 0L) {
|
||||
if (this.frameCount < this.frameTimesNs.length) {
|
||||
this.frameTimesNs[this.frameCount++] = now - this.lastFrameNs;
|
||||
} else {
|
||||
this.framesTruncated = true;
|
||||
}
|
||||
}
|
||||
this.lastFrameNs = now;
|
||||
}
|
||||
|
||||
private void begin(Minecraft mc, EntityClientPlayerMP player) {
|
||||
this.originX = player.posX;
|
||||
this.originY = player.posY;
|
||||
this.originZ = player.posZ;
|
||||
this.originPitch = player.rotationPitch;
|
||||
|
||||
this.originYaw = Math.round(player.rotationYaw / 90.0F) * 90.0F;
|
||||
if (this.originYaw != player.rotationYaw) {
|
||||
LOGGER.info("Flyby snapped heading {} -> {}", player.rotationYaw, this.originYaw);
|
||||
}
|
||||
|
||||
this.buildPath();
|
||||
this.freezeTimeAndWeather(mc);
|
||||
|
||||
this.state = this.warmupTicks > 0 ? State.WARMUP : State.RUNNING;
|
||||
this.tick = 0;
|
||||
if (this.state == State.RUNNING) this.beginMeasuring();
|
||||
|
||||
LOGGER.info("Flyby {} starting at {} {} {} yaw {}", this.route.id(),
|
||||
this.originX, this.originY, this.originZ, this.originYaw);
|
||||
}
|
||||
|
||||
private void buildPath() {
|
||||
final int n = this.runTicks + 1;
|
||||
this.pathX = new double[n];
|
||||
this.pathZ = new double[n];
|
||||
this.pathYaw = new float[n];
|
||||
this.pathLeg = new byte[n];
|
||||
this.pathTurning = new byte[n];
|
||||
|
||||
double x = this.originX;
|
||||
double z = this.originZ;
|
||||
double yaw = this.originYaw;
|
||||
|
||||
final double effectiveSpeed = this.route.speedOr(this.speed);
|
||||
final int legTicks = this.route.kind() == FlybyRoute.Kind.SQUARE ? this.route.legTicks(this.runLength, this.speed) : 0;
|
||||
final int turnTicks = this.route.kind() == FlybyRoute.Kind.SQUARE ? this.route.turnTicks() : 0;
|
||||
final int segment = legTicks + turnTicks;
|
||||
|
||||
final double cornerStep = turnTicks > 0 ? FlybyRoute.CIRCUIT_TURN_DEGREES / turnTicks : 0.0D;
|
||||
final double sweepStep = this.runTicks > 0 ? (double) this.runLength / this.runTicks : 0.0D;
|
||||
|
||||
for (int i = 0; i < n; i++) {
|
||||
this.pathX[i] = x;
|
||||
this.pathZ[i] = z;
|
||||
this.pathYaw[i] = (float) yaw;
|
||||
|
||||
double advance = 0.0D;
|
||||
double turn = 0.0D;
|
||||
|
||||
switch (this.route.kind()) {
|
||||
case STRAIGHT -> advance = effectiveSpeed;
|
||||
case ROTATE -> turn = sweepStep;
|
||||
case SQUARE -> {
|
||||
if (segment > 0 && (i % segment) < legTicks) {
|
||||
advance = effectiveSpeed;
|
||||
} else {
|
||||
turn = cornerStep;
|
||||
this.pathTurning[i] = 1;
|
||||
}
|
||||
this.pathLeg[i] = (byte) Math.min(FlybyRoute.CIRCUIT_LEGS - 1, segment > 0 ? i / segment : 0);
|
||||
}
|
||||
case STILL -> { }
|
||||
}
|
||||
if (this.route.kind() == FlybyRoute.Kind.ROTATE) this.pathTurning[i] = 1;
|
||||
|
||||
if (advance != 0.0D) {
|
||||
final double yawRad = Math.toRadians(yaw);
|
||||
x += -Math.sin(yawRad) * advance;
|
||||
z += Math.cos(yawRad) * advance;
|
||||
}
|
||||
yaw += turn;
|
||||
}
|
||||
}
|
||||
|
||||
private void emitPhase(int index) {
|
||||
if (!Tracy.ENABLED || index >= this.pathLeg.length) return;
|
||||
|
||||
final int leg = this.pathLeg[index];
|
||||
final int turning = this.pathTurning[index];
|
||||
Tracy.plotInt(this.plotLeg, leg);
|
||||
Tracy.plotInt(this.plotTurning, turning);
|
||||
|
||||
final int phase = (leg << 1) | turning;
|
||||
if (phase != this.lastPhase) {
|
||||
this.lastPhase = phase;
|
||||
Tracy.message("flyby " + (turning != 0 ? "turn" : "leg") + " " + leg);
|
||||
}
|
||||
}
|
||||
|
||||
private void beginMeasuring() {
|
||||
this.state = State.RUNNING;
|
||||
this.plotLeg = Tracy.plotHandle("flyby.leg");
|
||||
this.plotTurning = Tracy.plotHandle("flyby.turning");
|
||||
this.lastPhase = -1;
|
||||
this.frameTimesNs = new long[Math.min(MAX_RECORDED_FRAMES, Math.max(1024, this.runTicks * 20))];
|
||||
this.frameCount = 0;
|
||||
this.lastFrameNs = 0L;
|
||||
this.runStartNs = System.nanoTime();
|
||||
Tracy.message("flyby start route=" + this.route.id()
|
||||
+ " length=" + this.runLength + this.route.lengthUnit()
|
||||
+ " speed=" + this.route.speedOr(this.speed) + "b/t"
|
||||
+ " ticks=" + this.runTicks
|
||||
+ " sdlgpu=" + SystemProperties.USE_SDL_GPU);
|
||||
}
|
||||
|
||||
private void holdPosition(EntityClientPlayerMP player) {
|
||||
final int last = this.pathX.length - 1;
|
||||
if (last < 0) return;
|
||||
|
||||
player.motionX = 0.0D;
|
||||
player.motionY = 0.0D;
|
||||
player.motionZ = 0.0D;
|
||||
player.ySize = 0.0F;
|
||||
|
||||
player.prevPosX = player.lastTickPosX = this.pathX[last];
|
||||
player.prevPosY = player.lastTickPosY = this.originY;
|
||||
player.prevPosZ = player.lastTickPosZ = this.pathZ[last];
|
||||
player.prevRotationYaw = player.rotationYaw = this.pathYaw[last];
|
||||
player.prevRotationYawHead = player.rotationYawHead = this.pathYaw[last];
|
||||
player.prevRotationPitch = player.rotationPitch = this.originPitch;
|
||||
player.setPosition(this.pathX[last], this.originY, this.pathZ[last]);
|
||||
}
|
||||
|
||||
private void applyPosition(EntityClientPlayerMP player, int index) {
|
||||
final int i = Math.min(index, this.pathX.length - 1);
|
||||
final int prev = Math.max(0, i - 1);
|
||||
|
||||
final double x = this.pathX[i];
|
||||
final double z = this.pathZ[i];
|
||||
final double prevX = this.pathX[prev];
|
||||
final double prevZ = this.pathZ[prev];
|
||||
final float yaw = this.pathYaw[i];
|
||||
final float prevYaw = this.pathYaw[prev];
|
||||
|
||||
player.motionX = 0.0D;
|
||||
player.motionY = 0.0D;
|
||||
player.motionZ = 0.0D;
|
||||
player.ySize = 0.0F;
|
||||
|
||||
player.prevPosX = player.lastTickPosX = prevX;
|
||||
player.prevPosY = player.lastTickPosY = this.originY;
|
||||
player.prevPosZ = player.lastTickPosZ = prevZ;
|
||||
|
||||
player.prevRotationYaw = prevYaw;
|
||||
player.rotationYaw = yaw;
|
||||
player.prevRotationYawHead = prevYaw;
|
||||
player.rotationYawHead = yaw;
|
||||
player.prevRotationPitch = player.rotationPitch = this.originPitch;
|
||||
|
||||
player.setPosition(x, this.originY, z);
|
||||
}
|
||||
|
||||
/** Requests the freeze; the write happens on the server thread in {@link #onServerTick}. */
|
||||
private void freezeTimeAndWeather(Minecraft mc) {
|
||||
final MinecraftServer server = mc.getIntegratedServer();
|
||||
if (server == null) {
|
||||
LOGGER.warn("Flyby: not singleplayer, cannot freeze time/weather - results may not be comparable");
|
||||
return;
|
||||
}
|
||||
|
||||
this.freezeRequested = true;
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public void onServerTick(TickEvent.ServerTickEvent event) {
|
||||
if (event.phase != TickEvent.Phase.END || !this.freezeRequested) return;
|
||||
this.freezeRequested = false;
|
||||
|
||||
final MinecraftServer server = MinecraftServer.getServer();
|
||||
if (server == null) return;
|
||||
|
||||
for (WorldServer world : server.worldServers) {
|
||||
if (world == null) continue;
|
||||
|
||||
if (world.getGameRules().getGameRuleBooleanValue("doDaylightCycle")) {
|
||||
world.getGameRules().setOrCreateGameRule("doDaylightCycle", "false");
|
||||
LOGGER.warn("Flyby: doDaylightCycle was on, disabled it");
|
||||
}
|
||||
if (world.getWorldInfo().isRaining() || world.getWorldInfo().isThundering()) {
|
||||
LOGGER.warn("Flyby: weather was active, clearing it");
|
||||
world.getWorldInfo().setRaining(false);
|
||||
world.getWorldInfo().setThundering(false);
|
||||
}
|
||||
world.getWorldInfo().setRainTime(Integer.MAX_VALUE);
|
||||
world.getWorldInfo().setThunderTime(Integer.MAX_VALUE);
|
||||
|
||||
if (world.getWorldTime() % 24000L != FIXED_TIME_OF_DAY) {
|
||||
LOGGER.info("Flyby: freezing time at {}", FIXED_TIME_OF_DAY);
|
||||
world.setWorldTime(FIXED_TIME_OF_DAY);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void finish(Minecraft mc, EntityClientPlayerMP player) {
|
||||
this.state = State.SETTLE;
|
||||
this.tick = 0;
|
||||
final long elapsedNs = System.nanoTime() - this.runStartNs;
|
||||
Tracy.message("flyby end route=" + this.route.id() + " frames=" + this.frameCount);
|
||||
|
||||
final String summary = this.summarise(elapsedNs, player);
|
||||
LOGGER.info(summary);
|
||||
if (mc.thePlayer != null) {
|
||||
mc.thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.AQUA + "[Angelica] " + EnumChatFormatting.WHITE + summary));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void teardown(Minecraft mc, EntityClientPlayerMP player) {
|
||||
Tracy.message("flyby teardown");
|
||||
|
||||
this.returnToOrigin(player);
|
||||
|
||||
this.tick = 0;
|
||||
this.state = this.exitWhenDone ? State.EXITING : State.DONE;
|
||||
}
|
||||
|
||||
private void returnToOrigin(EntityClientPlayerMP player) {
|
||||
player.motionX = 0.0D;
|
||||
player.motionY = 0.0D;
|
||||
player.motionZ = 0.0D;
|
||||
player.ySize = 0.0F;
|
||||
player.setPositionAndRotation(this.originX, this.originY, this.originZ, this.originYaw, this.originPitch);
|
||||
player.lastTickPosX = this.originX;
|
||||
player.lastTickPosY = this.originY;
|
||||
player.lastTickPosZ = this.originZ;
|
||||
LOGGER.info("Flyby returned to origin {} {} {}", this.originX, this.originY, this.originZ);
|
||||
}
|
||||
|
||||
private String summarise(long elapsedNs, EntityClientPlayerMP player) {
|
||||
final StringBuilder sb = new StringBuilder(192);
|
||||
sb.append("Flyby ").append(this.route.id())
|
||||
.append(": ").append(this.frameCount).append(" frames in ")
|
||||
.append(String.format("%.2fs", elapsedNs / 1_000_000_000.0D));
|
||||
|
||||
if (this.frameCount > 0) {
|
||||
final long[] sorted = Arrays.copyOf(this.frameTimesNs, this.frameCount);
|
||||
Arrays.sort(sorted);
|
||||
long total = 0L;
|
||||
for (long ns : sorted) total += ns;
|
||||
sb.append(String.format(", avg %.2fms, p50 %.2fms, p99 %.2fms, max %.2fms",
|
||||
total / (double) this.frameCount / 1e6D,
|
||||
sorted[this.frameCount / 2] / 1e6D,
|
||||
sorted[Math.min(this.frameCount - 1, (int) (this.frameCount * 0.99D))] / 1e6D,
|
||||
sorted[this.frameCount - 1] / 1e6D));
|
||||
}
|
||||
if (this.framesTruncated) sb.append(" (frame samples truncated)");
|
||||
|
||||
sb.append(String.format(", end position %.6f %.6f %.6f", player.posX, player.posY, player.posZ));
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public void cancel() {
|
||||
if (this.isActive()) {
|
||||
LOGGER.info("Flyby cancelled");
|
||||
this.state = State.DONE;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean startedFromProperties() {
|
||||
return this.startedFromProperties;
|
||||
}
|
||||
}
|
||||
@@ -587,18 +587,22 @@ public class DynamicLights {
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static int getLuminanceFromEntityItem(@NotNull EntityItem item, int stackLuminance) {
|
||||
if (stackLuminance <= 0) return 0;
|
||||
if (item.isBurning()) return 15;
|
||||
// TODO only have certain items not glow in water?
|
||||
if (item.isInsideOfMaterial(Material.water)) return 0;
|
||||
return stackLuminance;
|
||||
}
|
||||
|
||||
public static int getLuminanceFromEntity(@NotNull Entity entity) {
|
||||
if (entity instanceof EntityItem item) {
|
||||
return getLuminanceFromEntityItem(item, getLuminanceFromItemStack(item.getEntityItem()));
|
||||
}
|
||||
|
||||
if (entity.isBurning()) return 15;
|
||||
|
||||
final boolean inWater = entity.isInsideOfMaterial(Material.water);
|
||||
|
||||
// TODO only have certain items not glow in water?
|
||||
if (inWater) return 0;
|
||||
|
||||
if (entity instanceof EntityItem item) {
|
||||
return getLuminanceFromItemStack(item.getEntityItem());
|
||||
}
|
||||
if (entity.isInsideOfMaterial(Material.water)) return 0;
|
||||
|
||||
int luminance = 0;
|
||||
if (entity instanceof EntityLivingBase living) {
|
||||
|
||||
Whitespace-only changes.
@@ -4,8 +4,13 @@ import com.gtnewhorizons.angelica.client.rendering.TextureTracker;
|
||||
import com.gtnewhorizons.angelica.glsm.hooks.DeferredAlphaHandler;
|
||||
import com.gtnewhorizons.angelica.glsm.hooks.DeferredBlendHandler;
|
||||
import com.gtnewhorizons.angelica.glsm.hooks.DeferredDepthColorHandler;
|
||||
import com.gtnewhorizons.angelica.glsm.hooks.GLSMConfig;
|
||||
import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks;
|
||||
import com.gtnewhorizons.angelica.glsm.hooks.ShaderWorkSubmitter;
|
||||
import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager;
|
||||
import net.coderbot.iris.Iris;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Supplier;
|
||||
import net.coderbot.iris.gbuffer_overrides.state.StateTracker;
|
||||
import net.coderbot.iris.gl.blending.AlphaTestStorage;
|
||||
import net.coderbot.iris.gl.blending.BlendModeStorage;
|
||||
@@ -16,6 +21,8 @@ import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline;
|
||||
import net.coderbot.iris.pipeline.WorldRenderingPipeline;
|
||||
import net.coderbot.iris.samplers.IrisSamplers;
|
||||
import net.coderbot.iris.texture.pbr.PBRTextureManager;
|
||||
import net.coderbot.iris.uniforms.SystemTimeUniforms;
|
||||
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
|
||||
|
||||
public class IrisGLSMBridge {
|
||||
|
||||
@@ -28,7 +35,9 @@ public class IrisGLSMBridge {
|
||||
private static Runnable fogDensityListener = null;
|
||||
private static Runnable colorModulatorListener = null;
|
||||
|
||||
private static final Int2IntOpenHashMap programLastUpdatedFrame = new Int2IntOpenHashMap();
|
||||
static {
|
||||
programLastUpdatedFrame.defaultReturnValue(-1);
|
||||
StateUpdateNotifiers.alphaFuncNotifier = listener -> alphaFuncListener = listener;
|
||||
StateUpdateNotifiers.alphaTestNotifier = listener -> alphaTestListener = listener;
|
||||
StateUpdateNotifiers.blendFuncNotifier = listener -> blendFuncListener = listener;
|
||||
@@ -40,7 +49,23 @@ public class IrisGLSMBridge {
|
||||
}
|
||||
|
||||
public static void register() {
|
||||
GLSMConfig.expandVertexFormats = Iris.enabled;
|
||||
IrisSamplers.initRenderer();
|
||||
GLSMHooks.shaderWorkSubmitter = new ShaderWorkSubmitter() {
|
||||
@Override
|
||||
public <T> CompletableFuture<T> submit(Supplier<T> work) {
|
||||
return Iris.ShaderTransformExecutor.submitTracked(work);
|
||||
}
|
||||
};
|
||||
GLSMHooks.postTransformProcessor = (src, shaderType) -> {
|
||||
if (Iris.ShaderTransformExecutor.isOnWorker()) {
|
||||
ShaderManager.prewarmSpirv(src, shaderType.id);
|
||||
} else {
|
||||
Iris.ShaderTransformExecutor.submitTracked(() -> {
|
||||
ShaderManager.prewarmSpirv(src, shaderType.id);
|
||||
});
|
||||
}
|
||||
};
|
||||
GLSMHooks.blendHandler = new DeferredBlendHandler() {
|
||||
@Override
|
||||
public boolean isBlendLocked() {
|
||||
@@ -171,6 +196,8 @@ public class IrisGLSMBridge {
|
||||
|
||||
if (DepthColorStorage.isOwnedProgram(event.newProgram)) {
|
||||
DepthColorStorage.unlockDepthColor();
|
||||
} else {
|
||||
drp.onModProgramOverride();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -181,10 +208,15 @@ public class IrisGLSMBridge {
|
||||
if (pipeline instanceof DeferredWorldRenderingPipeline drp) {
|
||||
DeferredWorldRenderingPipeline.Pass activePass = drp.getActivePassProgram();
|
||||
if (activePass != null && activePass.getProgram() != null && activePass.getProgram().getProgramId() == event.newProgram) {
|
||||
activePass.getProgram().getUniforms().update();
|
||||
final int frame = SystemTimeUniforms.COUNTER.getAsInt();
|
||||
if (programLastUpdatedFrame.get(event.newProgram) != frame) {
|
||||
activePass.getProgram().getUniforms().update();
|
||||
programLastUpdatedFrame.put(event.newProgram, frame);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
GLSMHooks.PROGRAM_DELETE.addListener(event -> programLastUpdatedFrame.remove(event.program));
|
||||
}
|
||||
}
|
||||
@@ -8,10 +8,12 @@ import com.gtnewhorizon.gtnhmixins.builders.ITransformers;
|
||||
import com.gtnewhorizons.angelica.config.AngelicaConfig;
|
||||
import com.gtnewhorizons.angelica.config.CompatConfig;
|
||||
import com.gtnewhorizons.angelica.config.FontConfig;
|
||||
import com.gtnewhorizons.angelica.config.SystemProperties;
|
||||
import com.gtnewhorizons.angelica.glsm.loading.DependencyVerifier;
|
||||
import com.gtnewhorizons.angelica.glsm.loading.EcosystemNarrowRules;
|
||||
import com.gtnewhorizons.angelica.loading.fml.compat.CompatHandlers;
|
||||
import com.gtnewhorizons.angelica.lwjgl3.MissingDependencySdl;
|
||||
import com.gtnewhorizons.angelica.sdlgpu.SDLGPUGate;
|
||||
import com.gtnewhorizons.angelica.mixins.Mixins;
|
||||
import com.gtnewhorizons.retrofuturabootstrap.SharedConfig;
|
||||
import cpw.mods.fml.relauncher.FMLLaunchHandler;
|
||||
@@ -79,13 +81,21 @@ public final class AngelicaClientTweaker implements IFMLLoadingPlugin, IEarlyMix
|
||||
ctx.updateLoggers();
|
||||
|
||||
// Debug features
|
||||
AngelicaConfig.enableTestBlocks = Boolean.getBoolean("angelica.enableTestBlocks");
|
||||
AngelicaConfig.enableTestBlocks = SystemProperties.ENABLE_TEST_BLOCKS;
|
||||
|
||||
} catch (ConfigException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
verifyDependencies();
|
||||
|
||||
if (SystemProperties.USE_SDL_GPU) {
|
||||
if (SDLGPUGate.isSDLGPUAvailable()) {
|
||||
LOGGER.info("SDL GPU window mode enabled");
|
||||
} else {
|
||||
LOGGER.warn("angelica.sdlgpu.enable=true but SDL GPU dependencies not available, falling back to GL");
|
||||
}
|
||||
}
|
||||
|
||||
// Register a scoped redirector early so classes prematurely loaded by other coremods during discovery/injectData
|
||||
// (e.g. Mycelium using HookLoader.class.getName()) still get GL calls redirected to GLSM. Only targets specific mod
|
||||
// packages to avoid interfering with mixin delegation on game classes. AngelicaLateTweaker removes this registration once
|
||||
@@ -108,7 +118,7 @@ public final class AngelicaClientTweaker implements IFMLLoadingPlugin, IEarlyMix
|
||||
for (String exclusion : EcosystemNarrowRules.LWJGL3IFY_EXCLUSIONS_SHARED) {
|
||||
handle.exclusions().add(exclusion);
|
||||
}
|
||||
handle.exclusions().add("com.gtnewhorizons.angelica.vulkan");
|
||||
handle.exclusions().add("com.gtnewhorizons.angelica.sdlgpu");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -204,9 +214,7 @@ public final class AngelicaClientTweaker implements IFMLLoadingPlugin, IEarlyMix
|
||||
final boolean rfbLoaded = Launch.blackboard.getOrDefault("angelica.rfbPluginLoaded", Boolean.FALSE) == Boolean.TRUE;
|
||||
if (!rfbLoaded) {
|
||||
tweaks.add("com.gtnewhorizons.angelica.loading.fml.tweakers.AngelicaLateTweaker");
|
||||
if (AngelicaConfig.enableCeleritas) {
|
||||
tweaks.add("com.gtnewhorizons.angelica.loading.fml.tweakers.CeleritasLateTweaker");
|
||||
}
|
||||
tweaks.add("com.gtnewhorizons.angelica.loading.fml.tweakers.CeleritasLateTweaker");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+9
-1
@@ -9,6 +9,7 @@ import org.intellij.lang.annotations.Pattern;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.jar.Attributes;
|
||||
import java.util.jar.Manifest;
|
||||
|
||||
/** RfbClassTransformer wrapper for {@link AngelicaRedirector} */
|
||||
@@ -26,6 +27,13 @@ public class RFBAngelicaRedirector implements RfbClassTransformer {
|
||||
return "redirector";
|
||||
}
|
||||
|
||||
private static final Attributes.Name LWJGL3_AWARE = new Attributes.Name("Lwjgl3ify-Aware");
|
||||
|
||||
/** We sort before lwjgl3ify:redirect, so an aware caller's descriptors are still org.lwjgl here and stay that way. */
|
||||
private static boolean isLwjgl3Aware(@Nullable Manifest manifest) {
|
||||
return manifest != null && "true".equals(manifest.getMainAttributes().getValue(LWJGL3_AWARE));
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull String @Nullable [] sortAfter() {
|
||||
return new String[] {"*", "mixin:mixin"};
|
||||
@@ -55,7 +63,7 @@ public class RFBAngelicaRedirector implements RfbClassTransformer {
|
||||
public boolean transformClassIfNeeded(@NotNull ExtensibleClassLoader classLoader,
|
||||
@NotNull RfbClassTransformer.Context context, @Nullable Manifest manifest,
|
||||
@NotNull String className, @NotNull ClassNodeHandle classNode) {
|
||||
final boolean changed = inner.transformClassNode(className, classNode.getNode());
|
||||
final boolean changed = inner.transformClassNode(className, classNode.getNode(), isLwjgl3Aware(manifest));
|
||||
if (changed) {
|
||||
classNode.computeMaxs();
|
||||
AngelicaClassDump.dumpRFBClass(className, classNode, this);
|
||||
|
||||
@@ -1,21 +1,20 @@
|
||||
package com.gtnewhorizons.angelica.loading.shared;
|
||||
|
||||
import com.gtnewhorizon.gtnhlib.asm.ASMUtil;
|
||||
import com.gtnewhorizons.angelica.config.SystemProperties;
|
||||
import com.gtnewhorizons.retrofuturabootstrap.api.ClassNodeHandle;
|
||||
|
||||
public class AngelicaClassDump {
|
||||
|
||||
private static final boolean DUMP_CLASS = Boolean.getBoolean("angelica.dumpClass");
|
||||
|
||||
public static void dumpClass(String className, byte[] originalBytes, byte[] transformedBytes, Object transformer) {
|
||||
if (DUMP_CLASS) {
|
||||
if (SystemProperties.DUMP_CLASS) {
|
||||
ASMUtil.saveAsRawClassFile(originalBytes, className + "_PRE", transformer);
|
||||
ASMUtil.saveAsRawClassFile(transformedBytes, className + "_POST", transformer);
|
||||
}
|
||||
}
|
||||
|
||||
public static void dumpRFBClass(String className, ClassNodeHandle classNode, Object transformer) {
|
||||
if (DUMP_CLASS) {
|
||||
if (SystemProperties.DUMP_CLASS) {
|
||||
final byte[] originalBytes = classNode.getOriginalBytes();
|
||||
final byte[] transformedBytes = classNode.computeBytes();
|
||||
ASMUtil.saveAsRawClassFile(originalBytes, className + "_PRE", transformer);
|
||||
|
||||
+5
@@ -37,4 +37,9 @@ public final class AngelicaRedirector {
|
||||
public boolean transformClassNode(String transformedName, ClassNode cn) {
|
||||
return core.transformClassNode(transformedName, cn);
|
||||
}
|
||||
|
||||
/** @return Was the class changed? */
|
||||
public boolean transformClassNode(String transformedName, ClassNode cn, boolean lwjgl3Aware) {
|
||||
return core.transformClassNode(transformedName, cn, lwjgl3Aware);
|
||||
}
|
||||
}
|
||||
+2
-4
@@ -2,7 +2,7 @@ package com.gtnewhorizons.angelica.loading.shared.transformers;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.gtnewhorizon.gtnhlib.asm.ClassConstantPoolParser;
|
||||
import net.minecraft.launchwrapper.Launch;
|
||||
import com.gtnewhorizons.angelica.config.SystemProperties;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
@@ -16,8 +16,6 @@ import org.objectweb.asm.tree.InsnNode;
|
||||
import org.objectweb.asm.tree.MethodInsnNode;
|
||||
import org.objectweb.asm.tree.MethodNode;
|
||||
|
||||
import java.lang.invoke.MethodHandle;
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
@@ -27,7 +25,7 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public final class CeleritasBlockTransform implements Opcodes {
|
||||
|
||||
private static final boolean LOG_SPAM = Boolean.getBoolean("angelica.redirectorLogspam");
|
||||
private static final boolean LOG_SPAM = SystemProperties.REDIRECTOR_LOGSPAM;
|
||||
private static final Logger LOGGER = LogManager.getLogger("CeleritasBlockTransformer");
|
||||
private static final String BlockClass = "net/minecraft/block/Block";
|
||||
private static final String ThreadedBlockData = "com/gtnewhorizons/angelica/client/rendering/ThreadedBlockData";
|
||||
|
||||
@@ -6,6 +6,9 @@ import com.gtnewhorizons.angelica.AngelicaMod;
|
||||
import com.gtnewhorizons.angelica.api.BlockLightProvider;
|
||||
import com.gtnewhorizons.angelica.config.AngelicaConfig;
|
||||
import com.gtnewhorizons.angelica.config.CompatConfig;
|
||||
import com.gtnewhorizons.angelica.config.SystemProperties;
|
||||
import com.gtnewhorizons.angelica.glsm.CaptureGate;
|
||||
import com.gtnewhorizons.angelica.sdlgpu.SDLGPUGate;
|
||||
import jss.notfine.config.MCPatcherForgeConfig;
|
||||
import jss.notfine.config.NotFineConfig;
|
||||
import lombok.Getter;
|
||||
@@ -25,6 +28,14 @@ public enum Mixins implements IMixins {
|
||||
)
|
||||
),
|
||||
|
||||
ANGELICA_CHAT_CACHE(new MixinBuilder()
|
||||
.setPhase(Phase.EARLY)
|
||||
.addClientMixins(
|
||||
"angelica.chat.MixinChatLine"
|
||||
, "angelica.chat.MixinGuiNewChat"
|
||||
)
|
||||
),
|
||||
|
||||
ANGELICA(new MixinBuilder()
|
||||
.setPhase(Phase.EARLY)
|
||||
.addClientMixins(
|
||||
@@ -37,6 +48,7 @@ public enum Mixins implements IMixins {
|
||||
, "angelica.MixinMinecraft_FrameHook"
|
||||
, "angelica.MixinMinecraft_IconifyGuard"
|
||||
, "angelica.MixinMinecraftServer"
|
||||
, "angelica.MixinSimpleReloadableResourceManager"
|
||||
, "angelica.bugfixes.MixinItemRenderer_EdgeDepth"
|
||||
, "angelica.bugfixes.MixinModelCreeper_AuraBodyInflate"
|
||||
, "angelica.bugfixes.MixinModelSkeleton_LegPelvisZFight"
|
||||
@@ -76,6 +88,18 @@ public enum Mixins implements IMixins {
|
||||
)
|
||||
),
|
||||
|
||||
ANGELICA_SDL_GPU_DISPLAY(new MixinBuilder("SDL-GPU-aware Display.create path")
|
||||
.setPhase(Phase.EARLY)
|
||||
.setApplyIf(() -> SystemProperties.USE_SDL_GPU && SDLGPUGate.isSDLGPUAvailable())
|
||||
.addClientMixins("sdlgpu.MixinForgeHooksClient_SDLGPUDisplay")
|
||||
),
|
||||
|
||||
ANGELICA_SDL_GPU_SHADOW_VOXEL_PREPASS(new MixinBuilder("Voxelization compute pre-pass before shadow raster (SDL_GPU)")
|
||||
.setPhase(Phase.EARLY)
|
||||
.setApplyIf(() -> SystemProperties.USE_SDL_GPU && SDLGPUGate.isSDLGPUAvailable())
|
||||
.addClientMixins("sdlgpu.MixinDefaultChunkRenderer_ShadowVoxelization")
|
||||
),
|
||||
|
||||
ANGELICA_VBO_CLOUDS(
|
||||
new MixinBuilder()
|
||||
.setApplyIf(() -> AngelicaConfig.enableVBOClouds)
|
||||
@@ -113,13 +137,102 @@ public enum Mixins implements IMixins {
|
||||
)
|
||||
),
|
||||
|
||||
ANGELICA_TESR_SIGN_CACHE(new MixinBuilder()
|
||||
.setPhase(Phase.EARLY)
|
||||
.setApplyIf(() -> AngelicaConfig.enableFontRenderer && AngelicaConfig.enableTESRSignCache)
|
||||
.addClientMixins(
|
||||
"angelica.tesr.MixinTileEntitySignRenderer"
|
||||
)
|
||||
),
|
||||
|
||||
ANGELICA_TESR_CHEST_CACHE(new MixinBuilder()
|
||||
.setPhase(Phase.EARLY)
|
||||
.setApplyIf(() -> AngelicaConfig.enableTESRChestCache)
|
||||
.addClientMixins(
|
||||
"angelica.tesr.MixinTileEntityChestRenderer",
|
||||
"angelica.tesr.MixinTileEntityEnderChestRenderer"
|
||||
)
|
||||
),
|
||||
|
||||
ANGELICA_TESR_SKULL_CACHE(new MixinBuilder()
|
||||
.setPhase(Phase.EARLY)
|
||||
.setApplyIf(() -> AngelicaConfig.enableTESRSkullCache)
|
||||
.addClientMixins(
|
||||
"angelica.tesr.MixinTileEntitySkullRenderer"
|
||||
)
|
||||
),
|
||||
|
||||
ANGELICA_ENTITY_BATCHING(new MixinBuilder()
|
||||
.setPhase(Phase.EARLY)
|
||||
.setApplyIf(() -> AngelicaConfig.enableEntityBatching)
|
||||
.addClientMixins(
|
||||
"angelica.entity.MixinModelRenderer",
|
||||
"angelica.entity.MixinRenderGlobal_EntityBatch",
|
||||
"angelica.entity.MixinTextureManager"
|
||||
)
|
||||
),
|
||||
|
||||
ANGELICA_SKIP_END_FRAME_FLUSH(new MixinBuilder("Skip the end-of-frame glFlush before the buffer swap")
|
||||
.setPhase(Phase.EARLY)
|
||||
.setApplyIf(() -> AngelicaConfig.skipEndOfFrameFlush)
|
||||
.addClientMixins(
|
||||
"angelica.MixinMinecraft_SkipEndFrameFlush"
|
||||
)
|
||||
),
|
||||
|
||||
THAUMCRAFT_TESR_JAR_CACHE(new MixinBuilder("Batch TC4 jar liquid via the retained TESR mesh cache")
|
||||
.setPhase(Phase.LATE)
|
||||
.setApplyIf(() -> AngelicaConfig.enableTESRJarCache)
|
||||
.addRequiredMod(TargetedMod.THAUMCRAFT)
|
||||
.addClientMixins(
|
||||
"client.thaumcraft.MixinTileJarRenderer"
|
||||
)
|
||||
),
|
||||
|
||||
ANGELICA_TESR_BEACON_CACHE(new MixinBuilder("Batch the vanilla beacon beam via the retained TESR mesh cache")
|
||||
.setPhase(Phase.EARLY)
|
||||
.setApplyIf(() -> AngelicaConfig.enableTESRBeaconCache)
|
||||
.addClientMixins(
|
||||
"angelica.tesr.MixinTileEntityBeaconRenderer"
|
||||
)
|
||||
),
|
||||
|
||||
ANGELICA_TESR_PROVIDER_DISPATCH(new MixinBuilder("Route TesrMeshProvider renderers through the batched mesh cache")
|
||||
.setPhase(Phase.EARLY)
|
||||
.setApplyIf(() -> AngelicaConfig.enableTESRProviderDispatch)
|
||||
.addClientMixins(
|
||||
"angelica.tesr.MixinTileEntityRendererDispatcher"
|
||||
)
|
||||
),
|
||||
|
||||
ANGELICA_TRACY(new MixinBuilder("Tracy profiler zones from vanilla Profiler sections")
|
||||
.setPhase(Phase.EARLY)
|
||||
.setApplyIf(() -> AngelicaMod.tracyEnabled)
|
||||
.addCommonMixins(
|
||||
"angelica.tracy.MixinProfiler_Tracy"
|
||||
, "angelica.tracy.MixinNetHandlerPlayServer_Tracy"
|
||||
, "angelica.tracy.MixinMinecraftServer_Tracy"
|
||||
)
|
||||
.addClientMixins(
|
||||
"angelica.tracy.MixinMinecraft_Tracy"
|
||||
, "angelica.tracy.MixinRenderGlobal_Tracy"
|
||||
)
|
||||
),
|
||||
|
||||
ANGELICA_ENABLE_DEBUG(new MixinBuilder()
|
||||
.setPhase(Phase.EARLY)
|
||||
.setApplyIf(() -> AngelicaMod.lwjglDebug)
|
||||
.addClientMixins(
|
||||
"angelica.debug.MixinSplashProgress"
|
||||
)
|
||||
),
|
||||
ANGELICA_DEBUG_MARKERS(new MixinBuilder("RenderDoc/RGP debug groups + object labels")
|
||||
.setPhase(Phase.EARLY)
|
||||
.setApplyIf(() -> AngelicaMod.lwjglDebug || CaptureGate.enabledAtStartup())
|
||||
.addClientMixins(
|
||||
"angelica.debug.MixinProfiler"
|
||||
, "angelica.debug.MixinSplashProgress"
|
||||
, "angelica.debug.MixinTextureManager"
|
||||
, "celeritas.debug.MixinGLDebug"
|
||||
)
|
||||
),
|
||||
ANGELICA_DYNAMIC_LIGHTS(new MixinBuilder()
|
||||
@@ -168,7 +281,6 @@ public enum Mixins implements IMixins {
|
||||
|
||||
ANGELICA_DEFERRED_TESSELLATOR_BATCH(new MixinBuilder("Deferred tessellator batching for particles to reduce draw calls")
|
||||
.setPhase(Phase.EARLY)
|
||||
.setApplyIf(() -> AngelicaConfig.enableCeleritas)
|
||||
.addClientMixins("angelica.particles.MixinEffectRenderer_DeferredBatch")),
|
||||
|
||||
// Not compatible with the lwjgl debug callbacks, so disable if that's enabled
|
||||
@@ -208,7 +320,6 @@ public enum Mixins implements IMixins {
|
||||
|
||||
RENDERING_INFRASTRUCTURE(new MixinBuilder()
|
||||
.setPhase(Phase.EARLY)
|
||||
.setApplyIf(() -> AngelicaConfig.enableCeleritas)
|
||||
.addClientMixins(
|
||||
"rendering.MixinBlock"
|
||||
, "rendering.MixinBlockFluidBase"
|
||||
@@ -239,11 +350,11 @@ public enum Mixins implements IMixins {
|
||||
|
||||
CELERITAS(new MixinBuilder()
|
||||
.setPhase(Phase.EARLY)
|
||||
.setApplyIf(() -> AngelicaConfig.enableCeleritas)
|
||||
.addClientMixins(
|
||||
"celeritas.terrain.MixinChunkProviderClient"
|
||||
, "celeritas.terrain.MixinMinecraft_ChunkUpdates"
|
||||
, "celeritas.terrain.MixinRenderGlobal"
|
||||
, "celeritas.terrain.MixinRenderListManager"
|
||||
, "celeritas.terrain.MixinRenderSectionManager"
|
||||
, "celeritas.terrain.MixinWorldClient"
|
||||
, "celeritas.frustum.MixinClippingHelper"
|
||||
@@ -260,6 +371,10 @@ public enum Mixins implements IMixins {
|
||||
, "celeritas.biome_blending.MixinBlockLiquid"
|
||||
, "celeritas.threading.MixinForgeHooksClient"
|
||||
, "celeritas.terrain.MixinChunk"
|
||||
, "celeritas.terrain.MixinRenderRegion"
|
||||
, "celeritas.terrain.MixinSectionRenderDataStorage"
|
||||
, "celeritas.terrain.MixinDefaultChunkRenderer"
|
||||
, "celeritas.terrain.MixinDefaultChunkShaderInterface"
|
||||
)
|
||||
),
|
||||
|
||||
@@ -267,7 +382,7 @@ public enum Mixins implements IMixins {
|
||||
.setPhase(Phase.EARLY)
|
||||
.setApplyIf(() -> {
|
||||
BlockLightProvider.freezeMixinConfig();
|
||||
return AngelicaConfig.enableCeleritas && BlockLightProvider.coloredLightEnabled();
|
||||
return BlockLightProvider.coloredLightEnabled();
|
||||
})
|
||||
.addClientMixins(
|
||||
"celeritas.light.MixinQuadLightData",
|
||||
@@ -373,7 +488,6 @@ public enum Mixins implements IMixins {
|
||||
|
||||
ANGELICA_TEXTURE(new MixinBuilder()
|
||||
.setPhase(Phase.EARLY)
|
||||
.setApplyIf(() -> AngelicaConfig.enableIris || AngelicaConfig.enableCeleritas)
|
||||
.addClientMixins(
|
||||
"angelica.textures.MixinTextureAtlasSprite"
|
||||
, "angelica.textures.MixinTextureUtil"
|
||||
@@ -426,7 +540,6 @@ public enum Mixins implements IMixins {
|
||||
FARSEEK_WORLDSLICE_COMPAT(new MixinBuilder("Let Farseek resolve celeritas' WorldSlice so Streams' water renders properly")
|
||||
.setPhase(Phase.LATE)
|
||||
.addRequiredMod(TargetedMod.FARSEEK)
|
||||
.setApplyIf(() -> AngelicaConfig.enableCeleritas)
|
||||
.addClientMixins("client.farseek.MixinFarseekIBlockAccessValue")),
|
||||
|
||||
SECURITYCRAFT_COMPAT(new MixinBuilder("Fix reflection in SecurityCraft for compat with Angelica")
|
||||
@@ -475,11 +588,6 @@ public enum Mixins implements IMixins {
|
||||
.setApplyIf(() -> AngelicaConfig.speedupAnimations)
|
||||
.addClientMixins("angelica.textures.ic2.MixinRenderLiquidCell")),
|
||||
|
||||
OPTIMIZE_TEXTURE_LOADING(new MixinBuilder()
|
||||
.setPhase(Phase.EARLY)
|
||||
.addClientMixins("angelica.textures.MixinTextureUtil_OptimizeMipmap")
|
||||
.setApplyIf(() -> AngelicaConfig.optimizeTextureLoading)),
|
||||
|
||||
REPLACE_FFP(new MixinBuilder()
|
||||
.setPhase(Phase.EARLY)
|
||||
.setApplyIf(() -> AngelicaConfig.replaceFFPUploads)
|
||||
@@ -538,6 +646,12 @@ public enum Mixins implements IMixins {
|
||||
"MixinRenderBlocks"
|
||||
))
|
||||
),
|
||||
BOP_FOG_BIOME_CACHE(new MixinBuilder()
|
||||
.setPhase(Phase.LATE)
|
||||
.addRequiredMod(TargetedMod.BIOMES_O_PLENTY)
|
||||
.addClientMixins("client.biomesoplenty.MixinFogHandlerBiomeCache")
|
||||
),
|
||||
|
||||
NOTFINE_BOP_FOG(new MixinBuilder()
|
||||
.setPhase(Phase.LATE)
|
||||
.setApplyIf(() -> AngelicaConfig.enableNotFineFeatures)
|
||||
@@ -634,16 +748,6 @@ public enum Mixins implements IMixins {
|
||||
"MixinWorldRenderer"
|
||||
))
|
||||
),
|
||||
MCPATCHER_FORGE_RENDERPASS_DISPLAYLIST(new MixinBuilder("RenderPass display list allocation increase")
|
||||
.setPhase(Phase.EARLY)
|
||||
.setApplyIf(() -> NotFineConfig.renderPass && !AngelicaConfig.enableCeleritas)
|
||||
.addClientMixins("mcpatcherforge.renderpass.MixinRenderGlobal_DisplayLists")
|
||||
),
|
||||
MCPATCHER_FORGE_RENDERPASS_FEATURES(new MixinBuilder("RenderPass rendering features")
|
||||
.setPhase(Phase.EARLY)
|
||||
.setApplyIf(() -> NotFineConfig.renderPass && !AngelicaConfig.enableCeleritas)
|
||||
.addClientMixins("mcpatcherforge.renderpass.MixinRenderGlobal_Features")
|
||||
),
|
||||
MCPATCHER_FORGE_CUSTOM_COLORS(new MixinBuilder()
|
||||
.setPhase(Phase.EARLY)
|
||||
.setApplyIf(() -> AngelicaConfig.enableMCPatcherForgeFeatures && MCPatcherForgeConfig.CustomColors.enabled)
|
||||
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.gtnewhorizons.angelica.mixins.interfaces;
|
||||
|
||||
public interface ChatLineFormattedAccessor {
|
||||
String angelica$getFormatted(long epoch);
|
||||
|
||||
void angelica$setFormatted(String formatted, long epoch);
|
||||
}
|
||||
+2
@@ -6,4 +6,6 @@ public interface ITileEntityBoundingBoxCache {
|
||||
AxisAlignedBB angelica$getCachedRenderBoundingBox();
|
||||
|
||||
byte angelica$boundsClass();
|
||||
|
||||
byte angelica$passClass();
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
package com.gtnewhorizons.angelica.mixins.interfaces;
|
||||
|
||||
public interface RenderListManagerAccessor {
|
||||
boolean angelica$hasOcclusionFutureInFlight();
|
||||
}
|
||||
+3
@@ -2,10 +2,13 @@ package com.gtnewhorizons.angelica.mixins.interfaces;
|
||||
|
||||
import it.unimi.dsi.fastutil.longs.Long2ReferenceMap;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.RenderSection;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegionManager;
|
||||
|
||||
import java.util.concurrent.ConcurrentLinkedDeque;
|
||||
|
||||
public interface RenderSectionManagerAccessor {
|
||||
Long2ReferenceMap<RenderSection> angelica$getSectionByPosition();
|
||||
ConcurrentLinkedDeque<Runnable> angelica$getAsyncSubmittedTasks();
|
||||
RenderRegionManager angelica$getRegions();
|
||||
float angelica$getSearchDistance();
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.gtnewhorizons.angelica.mixins.interfaces;
|
||||
|
||||
import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion;
|
||||
|
||||
public interface SectionRenderDataStorageRegionAccessor {
|
||||
RenderRegion angelica$getRegion();
|
||||
void angelica$setRegion(RenderRegion region);
|
||||
|
||||
int angelica$getPassIndex();
|
||||
void angelica$setPassIndex(int passIndex);
|
||||
|
||||
/** Per-section meta slot indexed by localSectionIndex; null when the backend has no GPU culling. */
|
||||
int[] angelica$getSlotCache();
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.gtnewhorizons.angelica.profiling;
|
||||
|
||||
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
|
||||
import it.unimi.dsi.fastutil.objects.Reference2IntMap;
|
||||
import it.unimi.dsi.fastutil.objects.Reference2IntMaps;
|
||||
import it.unimi.dsi.fastutil.objects.Reference2IntOpenHashMap;
|
||||
import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap;
|
||||
import net.minecraft.client.Minecraft;
|
||||
|
||||
public final class BailClassCounts {
|
||||
public static final BailClassCounts MATERIAL = new BailClassCounts("tesr.bailCls.mat.", "BailMat");
|
||||
public static final BailClassCounts TEMPLATE = new BailClassCounts("tesr.bailCls.tmpl.", "BailTmpl");
|
||||
|
||||
private final String plotPrefix;
|
||||
private final String label;
|
||||
private final Reference2IntOpenHashMap<Class<?>> counts = new Reference2IntOpenHashMap<>();
|
||||
private final Reference2ObjectOpenHashMap<Class<?>, String> plotNames = new Reference2ObjectOpenHashMap<>();
|
||||
private String debugLine = "";
|
||||
|
||||
private BailClassCounts(String plotPrefix, String label) {
|
||||
this.plotPrefix = plotPrefix;
|
||||
this.label = label;
|
||||
}
|
||||
|
||||
public void add(Class<?> cls) {
|
||||
counts.addTo(cls == null ? Object.class : cls, 1);
|
||||
}
|
||||
|
||||
public void flushFrame(boolean plot) {
|
||||
if (counts.isEmpty()) {
|
||||
debugLine = "";
|
||||
return;
|
||||
}
|
||||
final boolean debugScreen = Minecraft.getMinecraft().gameSettings.showDebugInfo;
|
||||
if (!plot && !debugScreen) {
|
||||
debugLine = "";
|
||||
counts.clear();
|
||||
return;
|
||||
}
|
||||
Class<?> a = null, b = null, c = null;
|
||||
int an = 0, bn = 0, cn = 0;
|
||||
final var it = Reference2IntMaps.fastIterator(counts);
|
||||
while (it.hasNext()) {
|
||||
final Reference2IntMap.Entry<Class<?>> entry = it.next();
|
||||
final int v = entry.getIntValue();
|
||||
if (plot) Tracy.plotInt(plotName(entry.getKey()), v);
|
||||
if (v > an) {
|
||||
c = b; cn = bn;
|
||||
b = a; bn = an;
|
||||
a = entry.getKey(); an = v;
|
||||
} else if (v > bn) {
|
||||
c = b; cn = bn;
|
||||
b = entry.getKey(); bn = v;
|
||||
} else if (v > cn) {
|
||||
c = entry.getKey(); cn = v;
|
||||
}
|
||||
}
|
||||
if (!debugScreen) {
|
||||
debugLine = "";
|
||||
} else {
|
||||
final StringBuilder sb = new StringBuilder(label).append(": ");
|
||||
appendEntry(sb, a, an);
|
||||
if (b != null) appendEntry(sb.append(", "), b, bn);
|
||||
if (c != null) appendEntry(sb.append(", "), c, cn);
|
||||
debugLine = sb.toString();
|
||||
}
|
||||
counts.clear();
|
||||
}
|
||||
|
||||
private String plotName(Class<?> cls) {
|
||||
String name = plotNames.get(cls);
|
||||
if (name == null) {
|
||||
name = plotPrefix + cls.getSimpleName();
|
||||
plotNames.put(cls, name);
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
private void appendEntry(StringBuilder sb, Class<?> cls, int count) {
|
||||
sb.append(cls.getSimpleName()).append(" x").append(count);
|
||||
}
|
||||
|
||||
public String debugLine() {
|
||||
return debugLine;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.gtnewhorizons.angelica.profiling;
|
||||
|
||||
import com.gtnewhorizons.angelica.glsm.backend.BackendManager;
|
||||
import com.gtnewhorizons.angelica.glsm.backend.RenderBackend;
|
||||
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
|
||||
import org.lwjgl.opengl.GL32;
|
||||
|
||||
public final class GpuFrameLagMeter {
|
||||
private static final int RING = 8;
|
||||
private static final long[] syncs = new long[RING];
|
||||
private static final long[] submitNs = new long[RING];
|
||||
private static int head;
|
||||
private static int tail;
|
||||
private static final long P_GPU_LAG_NS = Tracy.plotHandle("gpuLagNs");
|
||||
|
||||
private GpuFrameLagMeter() {}
|
||||
|
||||
public static void onFrame() {
|
||||
if (!Tracy.ENABLED) return;
|
||||
final RenderBackend rb = BackendManager.RENDER_BACKEND;
|
||||
while (tail != head) {
|
||||
final int slot = tail % RING;
|
||||
final int status = rb.clientWaitSync(syncs[slot], 0, 0);
|
||||
if (status != GL32.GL_ALREADY_SIGNALED && status != GL32.GL_CONDITION_SATISFIED) {
|
||||
if (status == GL32.GL_WAIT_FAILED) {
|
||||
rb.deleteSync(syncs[slot]);
|
||||
tail++;
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
Tracy.plotInt(P_GPU_LAG_NS, System.nanoTime() - submitNs[slot]);
|
||||
rb.deleteSync(syncs[slot]);
|
||||
tail++;
|
||||
}
|
||||
if (head - tail < RING) {
|
||||
final long sync = rb.fenceSync(GL32.GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
|
||||
if (sync != 0) {
|
||||
syncs[head % RING] = sync;
|
||||
submitNs[head % RING] = System.nanoTime();
|
||||
head++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.gtnewhorizons.angelica.profiling;
|
||||
|
||||
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
|
||||
import it.unimi.dsi.fastutil.objects.Reference2IntOpenHashMap;
|
||||
import it.unimi.dsi.fastutil.objects.Reference2LongMap;
|
||||
import it.unimi.dsi.fastutil.objects.Reference2LongMaps;
|
||||
import it.unimi.dsi.fastutil.objects.Reference2LongOpenHashMap;
|
||||
import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap;
|
||||
import net.minecraft.client.Minecraft;
|
||||
|
||||
public final class RenderClassTimings {
|
||||
public static final RenderClassTimings ENTITY = new RenderClassTimings("entity.cls.", "Entity");
|
||||
public static final RenderClassTimings SHADOW_ENTITY = new RenderClassTimings("shadow.entity.cls.", "ShadowEntity");
|
||||
public static final RenderClassTimings TESR = new RenderClassTimings("tesr.cls.", "TESR");
|
||||
|
||||
private static final long PLOT_THRESHOLD_NS = 20_000L;
|
||||
|
||||
private final String plotPrefix;
|
||||
private final String label;
|
||||
private final Reference2LongOpenHashMap<Class<?>> nanos = new Reference2LongOpenHashMap<>();
|
||||
private final Reference2IntOpenHashMap<Class<?>> counts = new Reference2IntOpenHashMap<>();
|
||||
private final Reference2ObjectOpenHashMap<Class<?>, String> plotNames = new Reference2ObjectOpenHashMap<>();
|
||||
private String debugLine = "";
|
||||
|
||||
private RenderClassTimings(String plotPrefix, String label) {
|
||||
this.plotPrefix = plotPrefix;
|
||||
this.label = label;
|
||||
}
|
||||
|
||||
public void add(Class<?> cls, long ns) {
|
||||
nanos.addTo(cls, ns);
|
||||
counts.addTo(cls, 1);
|
||||
}
|
||||
|
||||
public void flushFrame(boolean plot) {
|
||||
if (nanos.isEmpty()) {
|
||||
debugLine = "";
|
||||
return;
|
||||
}
|
||||
final boolean debugScreen = Minecraft.getMinecraft().gameSettings.showDebugInfo;
|
||||
if (!plot && !debugScreen) {
|
||||
debugLine = "";
|
||||
nanos.clear();
|
||||
counts.clear();
|
||||
return;
|
||||
}
|
||||
Class<?> a = null, b = null, c = null;
|
||||
long an = 0, bn = 0, cn = 0;
|
||||
final var it = Reference2LongMaps.fastIterator(nanos);
|
||||
while (it.hasNext()) {
|
||||
final Reference2LongMap.Entry<Class<?>> entry = it.next();
|
||||
final long v = entry.getLongValue();
|
||||
if (plot && v >= PLOT_THRESHOLD_NS) {
|
||||
Tracy.plotInt(plotName(entry.getKey()), v);
|
||||
}
|
||||
if (v > an) {
|
||||
c = b; cn = bn;
|
||||
b = a; bn = an;
|
||||
a = entry.getKey(); an = v;
|
||||
} else if (v > bn) {
|
||||
c = b; cn = bn;
|
||||
b = entry.getKey(); bn = v;
|
||||
} else if (v > cn) {
|
||||
c = entry.getKey(); cn = v;
|
||||
}
|
||||
}
|
||||
if (a == null || !debugScreen) {
|
||||
debugLine = "";
|
||||
} else {
|
||||
final StringBuilder sb = new StringBuilder(label).append(": ");
|
||||
appendEntry(sb, a, an);
|
||||
if (b != null) appendEntry(sb.append(", "), b, bn);
|
||||
if (c != null) appendEntry(sb.append(", "), c, cn);
|
||||
debugLine = sb.toString();
|
||||
}
|
||||
nanos.clear();
|
||||
counts.clear();
|
||||
}
|
||||
|
||||
private String plotName(Class<?> cls) {
|
||||
String name = plotNames.get(cls);
|
||||
if (name == null) {
|
||||
name = plotPrefix + cls.getSimpleName();
|
||||
plotNames.put(cls, name);
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
private void appendEntry(StringBuilder sb, Class<?> cls, long ns) {
|
||||
sb.append(cls.getSimpleName()).append(' ').append(ns / 1000).append("us x").append(counts.getInt(cls));
|
||||
}
|
||||
|
||||
public String debugLine() {
|
||||
return debugLine;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
package com.gtnewhorizons.angelica.profiling;
|
||||
|
||||
import com.gtnewhorizons.angelica.dynamiclights.DynamicLights;
|
||||
import com.gtnewhorizons.angelica.glsm.CaptureGate;
|
||||
import com.gtnewhorizons.angelica.glsm.DisplayListManager;
|
||||
import com.gtnewhorizons.angelica.glsm.GLStateManager;
|
||||
import com.gtnewhorizons.angelica.rendering.culling.GpuIndirectMultiDrawEmitter;
|
||||
import com.gtnewhorizons.angelica.glsm.ffp.ShaderManager;
|
||||
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
|
||||
import com.gtnewhorizons.angelica.glsm.profiling.TracyBackend;
|
||||
import com.gtnewhorizons.angelica.glsm.streaming.TessellatorStreamingDrawer;
|
||||
import com.gtnewhorizons.angelica.rendering.AngelicaRenderQueue;
|
||||
import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasWorldRenderer;
|
||||
import com.gtnewhorizons.angelica.rendering.celeritas.TerrainDrawStats;
|
||||
import com.gtnewhorizons.angelica.rendering.culling.GpuCulling;
|
||||
import com.gtnewhorizons.angelica.rendering.voxelization.SdlShadowVoxelizationSink;
|
||||
import com.gtnewhorizons.angelica.rendering.tesr.AngelicaTesrMeshCache;
|
||||
import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher;
|
||||
import com.gtnewhorizons.angelica.rendering.tesr.TesrBatchRenderer;
|
||||
import net.coderbot.iris.pipeline.ShadowRenderer;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.renderer.WorldRenderer;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.SharedQuadIndexBuffer;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.multidraw.IndirectMultiDrawEmitter;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegionManager;
|
||||
|
||||
public final class TracyFramePlots {
|
||||
private static long lastChunkUpdates;
|
||||
private static long lastDrawCalls, lastTexBindMisses, lastProgramSwitches, lastListPlaybacks;
|
||||
private static long lastStreamedBytes, lastStreamDraws, lastOrphanFallbacks, lastStreamContiguous;
|
||||
private static long lastSectionMetaBytes, lastRingWraps, lastVariantSwitches;
|
||||
private static long lastTesrRebuilds, lastTesrRetainedDraws, lastTesrInstDraws, lastTesrInstInstances;
|
||||
private static long lastTesrStreamedInstances, lastTesrPromotions, lastTesrCacheHits, lastTesrCacheMisses;
|
||||
private static long lastBatcherParts, lastBatcherLiveFallbacks;
|
||||
private static final long[] lastBails = new long[ModelPartBatcher.BailReason.VALUES.length];
|
||||
private static long lastSectionsUploaded, lastBytesUploaded;
|
||||
private static int lastCullSubmitted;
|
||||
|
||||
private static final long P_ALLOC_RATE = Tracy.plotHandle("allocRate", TracyBackend.PLOT_FORMAT_MEMORY);
|
||||
private static final long P_HEAP_USED = Tracy.plotHandle("heapUsed", TracyBackend.PLOT_FORMAT_MEMORY);
|
||||
private static final long P_CHUNK_UPDATES = Tracy.plotHandle("chunkUpdates");
|
||||
private static final long P_ENTITIES_RENDERED = Tracy.plotHandle("entitiesRendered");
|
||||
private static final long P_ENTITIES_TOTAL = Tracy.plotHandle("entitiesTotal");
|
||||
|
||||
private static final long P_GL_DRAW_CALLS = Tracy.plotHandle("gl.drawCalls");
|
||||
private static final long P_GL_TEX_BIND_MISSES = Tracy.plotHandle("gl.texBindMisses");
|
||||
private static final long P_GL_PROGRAM_SWITCHES = Tracy.plotHandle("gl.programSwitches");
|
||||
private static final long P_GL_LIST_PLAYBACKS = Tracy.plotHandle("gl.listPlaybacks");
|
||||
private static final long P_GL_STREAMED_BYTES = Tracy.plotHandle("gl.streamedBytes", TracyBackend.PLOT_FORMAT_MEMORY);
|
||||
private static final long P_GL_STREAM_DRAWS = Tracy.plotHandle("gl.streamDraws");
|
||||
private static final long P_GL_ORPHAN_FALLBACKS = Tracy.plotHandle("gl.orphanFallbacks");
|
||||
private static final long P_GL_STREAM_CONTIGUOUS = Tracy.plotHandle("gl.streamContiguous");
|
||||
private static final long P_GL_RING_WRAPS = Tracy.plotHandle("gl.ringWraps");
|
||||
private static final long P_GL_SECTION_META_BYTES = Tracy.plotHandle("gl.sectionMetaBytes", TracyBackend.PLOT_FORMAT_MEMORY);
|
||||
|
||||
private static final long P_SHADOW_RELAY_FRAMES = Tracy.plotHandle("shadow.relayFrames");
|
||||
|
||||
private static final long P_TERRAIN_DRAW_COMMANDS = Tracy.plotHandle("terrain.drawCommands");
|
||||
private static final long P_TERRAIN_REGIONS_DRAWN = Tracy.plotHandle("terrain.regionsDrawn");
|
||||
private static final long P_VOX_ENCODERS = Tracy.plotHandle("voxelization.encoders");
|
||||
private static final long P_VOX_DISPATCHES = Tracy.plotHandle("voxelization.dispatches");
|
||||
private static final long P_VOX_REGIONS = Tracy.plotHandle("voxelization.regions");
|
||||
private static final long P_DRAW_ARENA_GROWTHS = Tracy.plotHandle("draw.arenaGrowths");
|
||||
private static final long P_DRAW_INDEX_BUFFER_GROWTHS = Tracy.plotHandle("draw.indexBufferGrowths");
|
||||
|
||||
private static final long P_CULL_COMMANDS_SUBMITTED = Tracy.plotHandle("cull.commandsSubmitted");
|
||||
private static final long P_CULL_REGIONS_DRAWN = Tracy.plotHandle("cull.regionsDrawn");
|
||||
private static final long P_CULL_MAX_REGION_COMMANDS = Tracy.plotHandle("cull.maxRegionCommands");
|
||||
|
||||
private static final long P_FFP_PRE_DRAW_CALLS = Tracy.plotHandle("ffp.preDrawCalls");
|
||||
private static final long P_FFP_BLOCK_WRITES = Tracy.plotHandle("ffp.blockWrites");
|
||||
private static final long P_FFP_BLOCK_SKIPS = Tracy.plotHandle("ffp.blockSkips");
|
||||
private static final long P_FFP_STAGED_MATRICES = Tracy.plotHandle("ffp.stagedMatrices");
|
||||
private static final long P_FFP_STAGED_LIGHTING = Tracy.plotHandle("ffp.stagedLighting");
|
||||
private static final long P_FFP_STAGED_FRAGMENT = Tracy.plotHandle("ffp.stagedFragment");
|
||||
private static final long P_FFP_STAGED_COLOR = Tracy.plotHandle("ffp.stagedColor");
|
||||
private static final long P_FFP_STAGED_NORMAL = Tracy.plotHandle("ffp.stagedNormal");
|
||||
private static final long P_FFP_STAGED_TEX_COORD = Tracy.plotHandle("ffp.stagedTexCoord");
|
||||
private static final long P_FFP_STAGED_LIGHTMAP = Tracy.plotHandle("ffp.stagedLightmap");
|
||||
private static final long P_FFP_STAGED_TEX_GEN = Tracy.plotHandle("ffp.stagedTexGen");
|
||||
private static final long P_FFP_STAGED_CLIP_PLANES = Tracy.plotHandle("ffp.stagedClipPlanes");
|
||||
private static final long P_FFP_STAGED_MISC = Tracy.plotHandle("ffp.stagedMisc");
|
||||
private static final long P_FFP_PROGRAMS = Tracy.plotHandle("ffp.programs");
|
||||
private static final long P_FFP_VARIANT_SWITCHES = Tracy.plotHandle("ffp.variantSwitches");
|
||||
|
||||
private static final long P_TESR_REBUILDS = Tracy.plotHandle("tesr.rebuilds");
|
||||
private static final long P_TESR_RETAINED_DRAWS = Tracy.plotHandle("tesr.retainedDraws");
|
||||
private static final long P_TESR_INSTANCED_DRAWS = Tracy.plotHandle("tesr.instancedDraws");
|
||||
private static final long P_TESR_INSTANCED_INSTANCES = Tracy.plotHandle("tesr.instancedInstances");
|
||||
private static final long P_TESR_STREAMED_INSTANCES = Tracy.plotHandle("tesr.streamedInstances");
|
||||
private static final long P_TESR_VOLATILE_PROMOTIONS = Tracy.plotHandle("tesr.volatilePromotions");
|
||||
private static final long P_TESR_RETAINED_BYTES = Tracy.plotHandle("tesr.retainedBytes", TracyBackend.PLOT_FORMAT_MEMORY);
|
||||
private static final long P_TESR_BUFFER_SOURCE_BYTES = Tracy.plotHandle("tesr.bufferSourceBytes", TracyBackend.PLOT_FORMAT_MEMORY);
|
||||
private static final long P_TESR_CACHE_HITS = Tracy.plotHandle("tesr.cacheHits");
|
||||
private static final long P_TESR_CACHE_MISSES = Tracy.plotHandle("tesr.cacheMisses");
|
||||
private static final long P_TESR_MODEL_PARTS = Tracy.plotHandle("tesr.modelParts");
|
||||
private static final long P_TESR_LIVE_FALLBACKS = Tracy.plotHandle("tesr.liveFallbacks");
|
||||
private static final long[] P_TESR_BAILS = bailHandles();
|
||||
|
||||
private static final long P_MESH_UPLOADED_SECTIONS = Tracy.plotHandle("mesh.uploadedSections");
|
||||
private static final long P_MESH_UPLOADED_BYTES = Tracy.plotHandle("mesh.uploadedBytes", TracyBackend.PLOT_FORMAT_MEMORY);
|
||||
private static final long P_MESH_META_SLOTS = Tracy.plotHandle("mesh.metaSlots");
|
||||
private static final long P_MT_QUEUE_DEPTH = Tracy.plotHandle("mtQueue.depth");
|
||||
private static final long P_MT_QUEUE_TASKS = Tracy.plotHandle("mtQueue.tasksRan");
|
||||
private static final long P_MT_QUEUE_LONGEST_US = Tracy.plotHandle("mtQueue.longestTaskUs");
|
||||
|
||||
private static final long P_QUEUE_DEPTH = Tracy.plotHandle("queue.depth");
|
||||
private static final long P_QUEUE_TASKS_RAN = Tracy.plotHandle("queue.tasksRan");
|
||||
private static final long P_QUEUE_TIME_NS = Tracy.plotHandle("queue.timeNs");
|
||||
|
||||
private static final long P_DYN_LIGHT_SOURCES = Tracy.plotHandle("dyn.lightSources");
|
||||
private static final long P_DYN_UPDATES = Tracy.plotHandle("dyn.updates");
|
||||
private static final long P_DYN_PENDING_REBUILDS = Tracy.plotHandle("dyn.pendingRebuilds");
|
||||
|
||||
private static long[] bailHandles() {
|
||||
final ModelPartBatcher.BailReason[] reasons = ModelPartBatcher.BailReason.VALUES;
|
||||
final long[] out = new long[reasons.length];
|
||||
for (int i = 0; i < reasons.length; i++) out[i] = Tracy.plotHandle(reasons[i].plotName);
|
||||
return out;
|
||||
}
|
||||
|
||||
private TracyFramePlots() {}
|
||||
|
||||
public static void onFrame(Minecraft mc) {
|
||||
if (!Tracy.ENABLED) return;
|
||||
|
||||
final boolean plots = CaptureGate.markersThisFrame;
|
||||
|
||||
Tracy.plotAllocRate(P_ALLOC_RATE);
|
||||
Tracy.plotGcStats();
|
||||
if (plots) {
|
||||
final Runtime runtime = Runtime.getRuntime();
|
||||
Tracy.plotInt(P_HEAP_USED, runtime.totalMemory() - runtime.freeMemory());
|
||||
}
|
||||
final int chunksUpdated = WorldRenderer.chunksUpdated;
|
||||
Tracy.plotInt(P_CHUNK_UPDATES, chunksUpdated - lastChunkUpdates);
|
||||
lastChunkUpdates = chunksUpdated;
|
||||
if (mc.renderGlobal != null) {
|
||||
Tracy.plotInt(P_ENTITIES_RENDERED, mc.renderGlobal.countEntitiesRendered);
|
||||
}
|
||||
if (mc.theWorld != null) {
|
||||
Tracy.plotInt(P_ENTITIES_TOTAL, mc.theWorld.loadedEntityList.size());
|
||||
}
|
||||
|
||||
lastDrawCalls = delta(P_GL_DRAW_CALLS, GLStateManager.drawCalls, lastDrawCalls);
|
||||
lastTexBindMisses = delta(P_GL_TEX_BIND_MISSES, GLStateManager.texBindMisses, lastTexBindMisses);
|
||||
lastProgramSwitches = delta(P_GL_PROGRAM_SWITCHES, GLStateManager.programSwitches, lastProgramSwitches);
|
||||
lastListPlaybacks = delta(P_GL_LIST_PLAYBACKS, DisplayListManager.listPlaybacks, lastListPlaybacks);
|
||||
lastStreamedBytes = delta(P_GL_STREAMED_BYTES, TessellatorStreamingDrawer.streamedBytes, lastStreamedBytes);
|
||||
lastStreamDraws = delta(P_GL_STREAM_DRAWS, TessellatorStreamingDrawer.streamDraws, lastStreamDraws);
|
||||
lastOrphanFallbacks = delta(P_GL_ORPHAN_FALLBACKS, TessellatorStreamingDrawer.orphanFallbacks, lastOrphanFallbacks);
|
||||
lastStreamContiguous = delta(P_GL_STREAM_CONTIGUOUS, TessellatorStreamingDrawer.streamContiguous, lastStreamContiguous);
|
||||
lastRingWraps = delta(P_GL_RING_WRAPS, TessellatorStreamingDrawer.ringWraps(), lastRingWraps);
|
||||
lastSectionMetaBytes = delta(P_GL_SECTION_META_BYTES, GpuIndirectMultiDrawEmitter.sectionMetaBytes, lastSectionMetaBytes);
|
||||
Tracy.plotInt(P_SHADOW_RELAY_FRAMES, ShadowRenderer.SHADOW_TERRAIN_RELAID ? 1 : 0);
|
||||
Tracy.plotInt(P_TERRAIN_DRAW_COMMANDS, TerrainDrawStats.takeCommandsSubmitted());
|
||||
Tracy.plotInt(P_TERRAIN_REGIONS_DRAWN, TerrainDrawStats.takeRegionsDrawn());
|
||||
Tracy.plotInt(P_DRAW_ARENA_GROWTHS, IndirectMultiDrawEmitter.takeArenaGrowths());
|
||||
Tracy.plotInt(P_DRAW_INDEX_BUFFER_GROWTHS, SharedQuadIndexBuffer.takeGrowths());
|
||||
Tracy.plotInt(P_VOX_ENCODERS, SdlShadowVoxelizationSink.takeEncoders());
|
||||
Tracy.plotInt(P_VOX_DISPATCHES, SdlShadowVoxelizationSink.takeDispatches());
|
||||
Tracy.plotInt(P_VOX_REGIONS, SdlShadowVoxelizationSink.takeRegions());
|
||||
Tracy.plotInt(P_CULL_REGIONS_DRAWN, GpuIndirectMultiDrawEmitter.takeRegionsDrawn());
|
||||
Tracy.plotInt(P_CULL_MAX_REGION_COMMANDS, GpuIndirectMultiDrawEmitter.takeMaxRegionCommands());
|
||||
final int submitted = GpuIndirectMultiDrawEmitter.commandsSubmitted();
|
||||
Tracy.plotInt(P_CULL_COMMANDS_SUBMITTED, submitted - lastCullSubmitted);
|
||||
lastCullSubmitted = submitted;
|
||||
|
||||
final ShaderManager ffp = ShaderManager.getInstance();
|
||||
Tracy.plotInt(P_FFP_PRE_DRAW_CALLS, ffp.statLastFramePreDrawCalls());
|
||||
Tracy.plotInt(P_FFP_BLOCK_WRITES, ffp.statLastFrameBlockWrites());
|
||||
Tracy.plotInt(P_FFP_BLOCK_SKIPS, ffp.statLastFrameBlockSkips());
|
||||
Tracy.plotInt(P_FFP_STAGED_MATRICES, ffp.statLastFrameStagedMatrices());
|
||||
Tracy.plotInt(P_FFP_STAGED_LIGHTING, ffp.statLastFrameStagedLighting());
|
||||
Tracy.plotInt(P_FFP_STAGED_FRAGMENT, ffp.statLastFrameStagedFragment());
|
||||
Tracy.plotInt(P_FFP_STAGED_COLOR, ffp.statLastFrameStagedColor());
|
||||
Tracy.plotInt(P_FFP_STAGED_NORMAL, ffp.statLastFrameStagedNormal());
|
||||
Tracy.plotInt(P_FFP_STAGED_TEX_COORD, ffp.statLastFrameStagedTexCoord());
|
||||
Tracy.plotInt(P_FFP_STAGED_LIGHTMAP, ffp.statLastFrameStagedLightmap());
|
||||
Tracy.plotInt(P_FFP_STAGED_TEX_GEN, ffp.statLastFrameStagedTexGen());
|
||||
Tracy.plotInt(P_FFP_STAGED_CLIP_PLANES, ffp.statLastFrameStagedClipPlanes());
|
||||
Tracy.plotInt(P_FFP_STAGED_MISC, ffp.statLastFrameStagedMisc());
|
||||
Tracy.plotInt(P_FFP_PROGRAMS, ffp.statProgramCount());
|
||||
lastVariantSwitches = delta(P_FFP_VARIANT_SWITCHES, ShaderManager.variantSwitches, lastVariantSwitches);
|
||||
|
||||
final TesrBatchRenderer tesr = TesrBatchRenderer.INSTANCE;
|
||||
final ModelPartBatcher batcher = ModelPartBatcher.INSTANCE;
|
||||
|
||||
lastTesrRebuilds = delta(P_TESR_REBUILDS, tesr.statRebuilds(), lastTesrRebuilds);
|
||||
lastTesrRetainedDraws = delta(P_TESR_RETAINED_DRAWS, tesr.statRetainedDraws(), lastTesrRetainedDraws);
|
||||
lastTesrInstDraws = delta(P_TESR_INSTANCED_DRAWS, tesr.statInstancedDraws(), lastTesrInstDraws);
|
||||
lastTesrInstInstances = delta(P_TESR_INSTANCED_INSTANCES, tesr.statInstancedInstances(), lastTesrInstInstances);
|
||||
lastTesrStreamedInstances = delta(P_TESR_STREAMED_INSTANCES, tesr.statStreamedInstances(), lastTesrStreamedInstances);
|
||||
lastTesrPromotions = delta(P_TESR_VOLATILE_PROMOTIONS, tesr.statVolatilePromotions(), lastTesrPromotions);
|
||||
if (plots) {
|
||||
Tracy.plotInt(P_TESR_RETAINED_BYTES, tesr.statRetainedBytes());
|
||||
Tracy.plotInt(P_TESR_BUFFER_SOURCE_BYTES, tesr.statBufferSourceBytes());
|
||||
}
|
||||
lastTesrCacheHits = delta(P_TESR_CACHE_HITS, AngelicaTesrMeshCache.cacheHits, lastTesrCacheHits);
|
||||
lastTesrCacheMisses = delta(P_TESR_CACHE_MISSES, AngelicaTesrMeshCache.cacheMisses, lastTesrCacheMisses);
|
||||
lastBatcherParts = delta(P_TESR_MODEL_PARTS, batcher.statParts(), lastBatcherParts);
|
||||
lastBatcherLiveFallbacks = delta(P_TESR_LIVE_FALLBACKS, batcher.statLiveFallbacks(), lastBatcherLiveFallbacks);
|
||||
for (final ModelPartBatcher.BailReason reason : ModelPartBatcher.BailReason.VALUES) {
|
||||
final int i = reason.ordinal();
|
||||
lastBails[i] = delta(P_TESR_BAILS[i], batcher.statBail(reason), lastBails[i]);
|
||||
}
|
||||
|
||||
lastSectionsUploaded = delta(P_MESH_UPLOADED_SECTIONS, RenderRegionManager.getSectionsUploaded(), lastSectionsUploaded);
|
||||
lastBytesUploaded = delta(P_MESH_UPLOADED_BYTES, RenderRegionManager.getBytesUploaded(), lastBytesUploaded);
|
||||
Tracy.plotInt(P_MESH_META_SLOTS, GpuCulling.sectionMeta().getHighWaterMark());
|
||||
Tracy.plotInt(P_MT_QUEUE_DEPTH, AngelicaRenderQueue.getQueueDepth());
|
||||
Tracy.plotInt(P_MT_QUEUE_TASKS, AngelicaRenderQueue.getLastFrameTasksRan());
|
||||
Tracy.plotInt(P_MT_QUEUE_LONGEST_US, AngelicaRenderQueue.getLastFrameLongestTaskNs() / 1000);
|
||||
final CeleritasWorldRenderer cwr = CeleritasWorldRenderer.getInstanceOrNull();
|
||||
if (plots && cwr != null && cwr.isActive()) {
|
||||
cwr.getRenderSectionManager().tracyPlots();
|
||||
}
|
||||
|
||||
Tracy.plotInt(P_QUEUE_DEPTH, AngelicaRenderQueue.getQueueDepth());
|
||||
Tracy.plotInt(P_QUEUE_TASKS_RAN, AngelicaRenderQueue.getLastFrameTasksRan());
|
||||
Tracy.plotInt(P_QUEUE_TIME_NS, AngelicaRenderQueue.getLastFrameTimeNs());
|
||||
|
||||
if (DynamicLights.isEnabled()) {
|
||||
final DynamicLights dl = DynamicLights.get();
|
||||
Tracy.plotInt(P_DYN_LIGHT_SOURCES, dl.getLightSourcesCount());
|
||||
Tracy.plotInt(P_DYN_UPDATES, dl.getLastUpdateCount());
|
||||
if (DynamicLights.FrustumCullingEnabled) {
|
||||
Tracy.plotInt(P_DYN_PENDING_REBUILDS, dl.getChunkRebuildManager().getPendingCount());
|
||||
}
|
||||
}
|
||||
|
||||
RenderClassTimings.ENTITY.flushFrame(plots);
|
||||
RenderClassTimings.SHADOW_ENTITY.flushFrame(plots);
|
||||
RenderClassTimings.TESR.flushFrame(plots);
|
||||
BailClassCounts.MATERIAL.flushFrame(plots);
|
||||
BailClassCounts.TEMPLATE.flushFrame(plots);
|
||||
}
|
||||
|
||||
private static long delta(long handle, long now, long last) {
|
||||
Tracy.plotInt(handle, now - last);
|
||||
return now;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.gtnewhorizons.angelica.proxy;
|
||||
|
||||
import com.gtnewhorizons.angelica.rendering.culling.GpuCulling;
|
||||
import static com.gtnewhorizons.angelica.AngelicaMod.MOD_ID;
|
||||
|
||||
import java.lang.management.ManagementFactory;
|
||||
@@ -41,9 +42,11 @@ import com.gtnewhorizons.angelica.compat.bettercrashes.BetterCrashesCompat;
|
||||
import com.gtnewhorizons.angelica.compat.mojang.CompatMathHelper;
|
||||
import com.gtnewhorizons.angelica.config.AngelicaConfig;
|
||||
import com.gtnewhorizons.angelica.rendering.TileEntityRenderBoundsRegistry;
|
||||
import com.gtnewhorizons.angelica.rendering.tesr.AngelicaTesrMeshCache;
|
||||
import com.gtnewhorizons.angelica.config.CompatConfig;
|
||||
import com.gtnewhorizons.angelica.config.ConfigMigrator;
|
||||
import com.gtnewhorizons.angelica.debug.F3Direction;
|
||||
import com.gtnewhorizons.angelica.debug.flyby.FlybyRunner;
|
||||
import com.gtnewhorizons.angelica.debug.FrametimeGraph;
|
||||
import com.gtnewhorizons.angelica.debug.TPSGraph;
|
||||
import com.gtnewhorizons.angelica.dynamiclights.DynamicLights;
|
||||
@@ -111,6 +114,7 @@ public final class ClientProxy extends CommonProxy {
|
||||
FMLCommonHandler.instance().bus().register(this);
|
||||
MinecraftForge.EVENT_BUS.register(this);
|
||||
MinecraftForge.EVENT_BUS.register(new EmissiveTextureAutoloader());
|
||||
MinecraftForge.EVENT_BUS.register(new AngelicaTesrMeshCache.ReloadListener());
|
||||
ModelRegistry.registerModid(MOD_ID);
|
||||
blockError = new BlockError();
|
||||
}
|
||||
@@ -122,12 +126,8 @@ public final class ClientProxy extends CommonProxy {
|
||||
if (AngelicaConfig.enableHudCaching) {
|
||||
HUDCaching.init();
|
||||
}
|
||||
if (AngelicaConfig.enableCeleritas) {
|
||||
CeleritasSetup.ensureInitialized();
|
||||
MinecraftForge.EVENT_BUS.register(CeleritasDebugScreenHandler.INSTANCE);
|
||||
} else {
|
||||
LOGGER.info("Celeritas is disabled, skipping initialization from init()");
|
||||
}
|
||||
CeleritasSetup.ensureInitialized();
|
||||
MinecraftForge.EVENT_BUS.register(CeleritasDebugScreenHandler.INSTANCE);
|
||||
if (AngelicaConfig.enableIris) {
|
||||
IrisGLSMBridge.register();
|
||||
MinecraftForge.EVENT_BUS.register(IrisDebugScreenHandler.INSTANCE);
|
||||
@@ -149,6 +149,7 @@ public final class ClientProxy extends CommonProxy {
|
||||
if (AngelicaConfig.enableZoom) {
|
||||
Zoom.init();
|
||||
}
|
||||
AngelicaConfig.applyGpuCullingMode();
|
||||
if (AngelicaConfig.enableDynamicLights) {
|
||||
EntityLightConfig.init(new java.io.File(mc.mcDataDir, "config"));
|
||||
}
|
||||
@@ -157,9 +158,12 @@ public final class ClientProxy extends CommonProxy {
|
||||
BlockRenderListManager.registerReloadListener();
|
||||
}
|
||||
|
||||
// Register debug commands in dev environment only
|
||||
// Debug tooling
|
||||
if (!AngelicaClientTweaker.isObfEnv()) {
|
||||
ClientCommandHandler.instance.registerCommand(new AngelicaCommand());
|
||||
|
||||
FMLCommonHandler.instance().bus().register(FlybyRunner.INSTANCE);
|
||||
FlybyRunner.INSTANCE.startFromProperties();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -167,7 +171,7 @@ public final class ClientProxy extends CommonProxy {
|
||||
public void postInit(FMLPostInitializationEvent event) {
|
||||
super.postInit(event);
|
||||
|
||||
if (ModStatus.isLotrLoaded && AngelicaConfig.enableCeleritas && CompatConfig.fixLotr) {
|
||||
if (ModStatus.isLotrLoaded && CompatConfig.fixLotr) {
|
||||
try {
|
||||
final Class<?> lotrRendering = Class.forName("lotr.common.coremod.LOTRReplacedMethods$BlockRendering");
|
||||
ReflectionHelper.setPrivateValue(lotrRendering, null, new ConcurrentHashMap<>(), "naturalBlockClassTable");
|
||||
@@ -190,23 +194,22 @@ public final class ClientProxy extends CommonProxy {
|
||||
LOGGER.info("World loaded - Enabling GLSM Cache");
|
||||
}
|
||||
|
||||
if (AngelicaConfig.enableCeleritas) {
|
||||
ChunkTaskRegistry.reset();
|
||||
ChunkTaskRegistry.registerProvider(DefaultChunkTaskProvider.INSTANCE);
|
||||
ChunkTaskRegistry.registerProvider(ThreadedChunkTaskProvider.INSTANCE);
|
||||
ChunkTaskRegistry.reset();
|
||||
ChunkTaskRegistry.registerProvider(DefaultChunkTaskProvider.INSTANCE);
|
||||
ChunkTaskRegistry.registerProvider(ThreadedChunkTaskProvider.INSTANCE);
|
||||
|
||||
// Register all blocks. Because blockids are unique to a world, this must be done each load
|
||||
GameData.getBlockRegistry().typeSafeIterable().forEach(o -> {
|
||||
AngelicaBlockSafetyRegistry.canBlockRenderOffThread(o, true, true);
|
||||
AngelicaBlockSafetyRegistry.canBlockRenderOffThread(o, false, true);
|
||||
});
|
||||
}
|
||||
// Register all blocks. Because blockids are unique to a world, this must be done each load
|
||||
GameData.getBlockRegistry().typeSafeIterable().forEach(o -> {
|
||||
AngelicaBlockSafetyRegistry.canBlockRenderOffThread(o, true, true);
|
||||
AngelicaBlockSafetyRegistry.canBlockRenderOffThread(o, false, true);
|
||||
});
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public void onWorldUnload(WorldEvent.Unload event) {
|
||||
if (!event.world.isRemote) return;
|
||||
DynamicLights.get().removeAllLightSources();
|
||||
GpuCulling.onWorldUnload();
|
||||
}
|
||||
|
||||
float lastIntegratedTickTime;
|
||||
|
||||
@@ -277,9 +277,10 @@ public class PanoramaRenderer {
|
||||
GLStateManager.glBindVertexArray(0);
|
||||
blitProgram.unbind();
|
||||
|
||||
GLStateManager.enableDepthTest();
|
||||
GLStateManager.enableCull();
|
||||
GLStateManager.disableDepthTest();
|
||||
GLStateManager.disableCull();
|
||||
GLStateManager.enableBlend();
|
||||
GLStateManager.enableTexture();
|
||||
}
|
||||
|
||||
private void drawCubeFaces(int panoramaTimer, float partialTicks, ResourceLocation[] panoramaPaths, Minecraft mc) {
|
||||
|
||||
@@ -43,7 +43,7 @@ public final class SelectionBoxRenderer {
|
||||
private SelectionBoxRenderer() {}
|
||||
|
||||
public static void init() {
|
||||
final boolean needsGS = GLStateManager.wideLineEmulationEnabled;
|
||||
final boolean needsGS = GLStateManager.wideLineEmulationEnabled && GLStateManager.supportsGeometryShaders();
|
||||
|
||||
final GlShader vs = ShaderLoader.loadShader(ShaderType.VERTEX, "angelica:selection_box.vert.glsl", ShaderConstants.EMPTY);
|
||||
final GlShader fs = ShaderLoader.loadShader(ShaderType.FRAGMENT, "angelica:selection_box.frag.glsl", ShaderConstants.EMPTY);
|
||||
|
||||
@@ -15,6 +15,7 @@ public class AngelicaRenderQueue {
|
||||
// Metrics
|
||||
private static volatile int lastFrameTasksRan = 0;
|
||||
private static volatile long lastFrameTimeNs = 0;
|
||||
private static volatile long lastFrameLongestTaskNs = 0;
|
||||
|
||||
public static int getQueueDepth() {
|
||||
return TASKS.size();
|
||||
@@ -28,9 +29,14 @@ public class AngelicaRenderQueue {
|
||||
return lastFrameTimeNs;
|
||||
}
|
||||
|
||||
public static void recordFrameStats(int tasksRan, long timeNs) {
|
||||
public static long getLastFrameLongestTaskNs() {
|
||||
return lastFrameLongestTaskNs;
|
||||
}
|
||||
|
||||
public static void recordFrameStats(int tasksRan, long timeNs, long longestTaskNs) {
|
||||
lastFrameTasksRan = tasksRan;
|
||||
lastFrameTimeNs = timeNs;
|
||||
lastFrameLongestTaskNs = longestTaskNs;
|
||||
}
|
||||
|
||||
private static final Executor EXECUTOR = (runnable) -> {
|
||||
|
||||
+76
@@ -1,6 +1,7 @@
|
||||
package com.gtnewhorizons.angelica.rendering;
|
||||
|
||||
import it.unimi.dsi.fastutil.objects.Reference2ByteOpenHashMap;
|
||||
import net.minecraft.launchwrapper.Launch;
|
||||
import net.minecraft.tileentity.TileEntity;
|
||||
import net.minecraft.util.AxisAlignedBB;
|
||||
|
||||
@@ -16,12 +17,25 @@ public final class TileEntityRenderBoundsRegistry {
|
||||
public static final byte INFINITE = 2;
|
||||
public static final byte DYNAMIC = 3;
|
||||
|
||||
public static final byte PASS0_ONLY = 1;
|
||||
public static final byte PASS_OVERRIDES = 2;
|
||||
|
||||
private static final byte NOT_OVERRIDDEN = 1;
|
||||
private static final byte OVERRIDDEN = 2;
|
||||
|
||||
private static final Reference2ByteOpenHashMap<Class<? extends TileEntity>> classRegistry = new Reference2ByteOpenHashMap<>();
|
||||
private static final Reference2ByteOpenHashMap<Class<? extends TileEntity>> passClassRegistry = new Reference2ByteOpenHashMap<>();
|
||||
private static final Reference2ByteOpenHashMap<Class<? extends TileEntity>> distanceOverrideRegistry = new Reference2ByteOpenHashMap<>();
|
||||
|
||||
private static final Set<String> dynamicClassNames = ConcurrentHashMap.newKeySet();
|
||||
|
||||
private static final String[] SHOULD_RENDER_IN_PASS_NAMES = { "shouldRenderInPass" };
|
||||
private static String[] distanceFromNames;
|
||||
|
||||
static {
|
||||
classRegistry.defaultReturnValue(UNKNOWN);
|
||||
passClassRegistry.defaultReturnValue(UNKNOWN);
|
||||
distanceOverrideRegistry.defaultReturnValue(UNKNOWN);
|
||||
}
|
||||
|
||||
private TileEntityRenderBoundsRegistry() {}
|
||||
@@ -60,9 +74,71 @@ public final class TileEntityRenderBoundsRegistry {
|
||||
return result;
|
||||
}
|
||||
|
||||
public static boolean overridesMethod(Class<?> clazz, Class<?> base, String[] candidateNames, Class<?>... params) {
|
||||
for (String name : candidateNames) {
|
||||
try {
|
||||
return clazz.getMethod(name, params).getDeclaringClass() != base;
|
||||
} catch (NoSuchMethodException ignored) {
|
||||
} catch (Throwable t) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static String[] distanceFromNames() {
|
||||
String[] names = distanceFromNames;
|
||||
if (names == null) {
|
||||
String resolved;
|
||||
try {
|
||||
resolved = Boolean.TRUE.equals(Launch.blackboard.get("fml.deobfuscatedEnvironment")) ? "getDistanceFrom" : "func_145835_a";
|
||||
} catch (Throwable t) {
|
||||
resolved = "getDistanceFrom";
|
||||
}
|
||||
distanceFromNames = names = new String[] { resolved };
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
public static byte classifyPass(TileEntity te) {
|
||||
final Class<? extends TileEntity> clazz = te.getClass();
|
||||
synchronized (passClassRegistry) {
|
||||
final byte cached = passClassRegistry.getByte(clazz);
|
||||
if (cached != UNKNOWN) return cached;
|
||||
}
|
||||
|
||||
final byte result = overridesMethod(clazz, TileEntity.class, SHOULD_RENDER_IN_PASS_NAMES, int.class)
|
||||
? PASS_OVERRIDES : PASS0_ONLY;
|
||||
|
||||
synchronized (passClassRegistry) {
|
||||
passClassRegistry.put(clazz, result);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static boolean overridesGetDistanceFrom(Class<? extends TileEntity> clazz) {
|
||||
synchronized (distanceOverrideRegistry) {
|
||||
final byte cached = distanceOverrideRegistry.getByte(clazz);
|
||||
if (cached != UNKNOWN) return cached == OVERRIDDEN;
|
||||
}
|
||||
|
||||
final boolean overrides = overridesMethod(clazz, TileEntity.class, distanceFromNames(), double.class, double.class, double.class);
|
||||
|
||||
synchronized (distanceOverrideRegistry) {
|
||||
distanceOverrideRegistry.put(clazz, overrides ? OVERRIDDEN : NOT_OVERRIDDEN);
|
||||
}
|
||||
return overrides;
|
||||
}
|
||||
|
||||
public static void clear() {
|
||||
synchronized (classRegistry) {
|
||||
classRegistry.clear();
|
||||
}
|
||||
synchronized (passClassRegistry) {
|
||||
passClassRegistry.clear();
|
||||
}
|
||||
synchronized (distanceOverrideRegistry) {
|
||||
distanceOverrideRegistry.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package com.gtnewhorizons.angelica.rendering.celeritas;
|
||||
|
||||
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
|
||||
import net.minecraft.tileentity.TileEntity;
|
||||
import net.minecraft.util.AxisAlignedBB;
|
||||
import it.unimi.dsi.fastutil.floats.FloatArrayList;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.data.MinecraftBuiltRenderSectionData;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class AngelicaBuiltRenderSectionData extends MinecraftBuiltRenderSectionData<TextureAtlasSprite, TileEntity> {
|
||||
public static final float[] EMPTY_BOUNDS = new float[0];
|
||||
|
||||
public float[] culledBlockEntityBounds = EMPTY_BOUNDS;
|
||||
|
||||
public double maxTeRenderDistSq = Double.POSITIVE_INFINITY;
|
||||
|
||||
public int cullEpoch = -1;
|
||||
public int cullVerdict;
|
||||
|
||||
public static void packSectionLocalBounds(FloatArrayList out, AxisAlignedBB aabb, int originX, int originY, int originZ) {
|
||||
out.add((float) (aabb.minX - originX));
|
||||
out.add((float) (aabb.minY - originY));
|
||||
out.add((float) (aabb.minZ - originZ));
|
||||
out.add((float) (aabb.maxX - originX));
|
||||
out.add((float) (aabb.maxY - originY));
|
||||
out.add((float) (aabb.maxZ - originZ));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (!super.equals(o)) return false;
|
||||
final AngelicaBuiltRenderSectionData other = (AngelicaBuiltRenderSectionData) o;
|
||||
return maxTeRenderDistSq == other.maxTeRenderDistSq && Arrays.equals(culledBlockEntityBounds, other.culledBlockEntityBounds);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = 31 * super.hashCode() + Arrays.hashCode(culledBlockEntityBounds);
|
||||
return 31 * result + Double.hashCode(maxTeRenderDistSq);
|
||||
}
|
||||
}
|
||||
+2
@@ -12,6 +12,7 @@ import com.gtnewhorizons.angelica.rendering.celeritas.iris.IrisExtendedChunkVert
|
||||
import com.gtnewhorizons.angelica.rendering.celeritas.light.LightDataCache;
|
||||
import com.gtnewhorizons.angelica.rendering.celeritas.light.VanillaDiffuseProvider;
|
||||
import com.gtnewhorizons.angelica.rendering.celeritas.world.WorldSlice;
|
||||
import it.unimi.dsi.fastutil.floats.FloatArrayList;
|
||||
import lombok.Getter;
|
||||
import net.coderbot.iris.block_rendering.BlockRenderingSettings;
|
||||
import net.coderbot.iris.vertices.ExtendedDataHelper;
|
||||
@@ -52,6 +53,7 @@ public class AngelicaChunkBuildContext extends ChunkBuildContext {
|
||||
private final SmoothLightPipeline smoothLightPipeline;
|
||||
private final FlatLightPipeline flatLightPipeline;
|
||||
private final QuadLightData quadLightData = new QuadLightData();
|
||||
@Getter private final FloatArrayList teBoundsScratch = new FloatArrayList();
|
||||
private final VertexArrayQuadView quadView;
|
||||
private final boolean hasColoredLight;
|
||||
private final float[] tintResult = new float[3];
|
||||
|
||||
+56
-10
@@ -1,6 +1,7 @@
|
||||
package com.gtnewhorizons.angelica.rendering.celeritas;
|
||||
|
||||
import com.gtnewhorizon.gtnhlib.blockpos.BlockPos;
|
||||
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
|
||||
import com.gtnewhorizons.angelica.rendering.AngelicaRenderQueue;
|
||||
import com.gtnewhorizons.angelica.rendering.StateAwareTessellator;
|
||||
import com.gtnewhorizons.angelica.rendering.TileEntityRenderBoundsRegistry;
|
||||
@@ -9,6 +10,7 @@ import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProviderHold
|
||||
import com.gtnewhorizons.angelica.rendering.celeritas.iris.BlockRenderContext;
|
||||
import com.gtnewhorizons.angelica.rendering.celeritas.iris.ContextAwareChunkVertexEncoder;
|
||||
import com.prupe.mcpatcher.mal.block.RenderBlocksUtils;
|
||||
import it.unimi.dsi.fastutil.floats.FloatArrayList;
|
||||
import it.unimi.dsi.fastutil.objects.Reference2ReferenceMap;
|
||||
import net.coderbot.iris.block_rendering.BlockMaterialMapping;
|
||||
import net.coderbot.iris.block_rendering.BlockRenderingSettings;
|
||||
@@ -17,10 +19,10 @@ import net.coderbot.iris.vertices.ExtendedDataHelper;
|
||||
import net.minecraft.block.Block;
|
||||
import net.minecraft.block.BlockDoublePlant;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import net.minecraft.world.World;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.renderer.RenderBlocks;
|
||||
import net.minecraft.client.renderer.Tessellator;
|
||||
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
|
||||
import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher;
|
||||
import net.minecraft.crash.CrashReport;
|
||||
import net.minecraft.crash.CrashReportCategory;
|
||||
@@ -35,7 +37,6 @@ import org.embeddedt.embeddium.impl.render.chunk.compile.ChunkBuildContext;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.compile.ChunkBuildOutput;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.compile.tasks.ChunkBuilderTask;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.data.BuiltSectionMeshParts;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.data.MinecraftBuiltRenderSectionData;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.occlusion.SectionVisibilityBuilder;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.terrain.material.Material;
|
||||
@@ -51,6 +52,10 @@ import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask<ChunkBuildOutput> {
|
||||
private static final Tracy.ZoneId Z_MESH_SECTION = Tracy.zoneId("meshSection");
|
||||
private static final Tracy.ZoneId Z_MESH_DEFERRED = Tracy.zoneId("meshDeferred");
|
||||
private static final Tracy.ZoneId Z_MESH_FINALIZE = Tracy.zoneId("meshFinalize");
|
||||
|
||||
protected final RenderSection render;
|
||||
protected final int buildTime;
|
||||
protected final Vector3d camera;
|
||||
@@ -88,7 +93,7 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask<C
|
||||
@Override
|
||||
public ChunkBuildOutput execute(ChunkBuildContext context, CancellationToken cancellationToken) {
|
||||
final AngelicaChunkBuildContext buildContext = (AngelicaChunkBuildContext) context;
|
||||
final MinecraftBuiltRenderSectionData<TextureAtlasSprite, TileEntity> renderData = new MinecraftBuiltRenderSectionData<>();
|
||||
final AngelicaBuiltRenderSectionData renderData = new AngelicaBuiltRenderSectionData();
|
||||
final SectionVisibilityBuilder occluder = new SectionVisibilityBuilder();
|
||||
|
||||
final ChunkBuildBuffers buffers = buildContext.buffers;
|
||||
@@ -109,6 +114,7 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask<C
|
||||
final SmoothBiomeColorCache biomeColorCache = getBiomeColorCache();
|
||||
|
||||
onEnterExecute();
|
||||
if (Tracy.ENABLED) Tracy.beginZone(Z_MESH_SECTION);
|
||||
|
||||
final Tessellator tessellator = getTessellator();
|
||||
((StateAwareTessellator)tessellator).angelica$setCeleritasMeshing(true);
|
||||
@@ -122,12 +128,16 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask<C
|
||||
final BlockRenderContext blockRenderContext = buildContext.getBlockRenderContext();
|
||||
|
||||
final NbtConditionalIdMap<Block> teMap = BlockRenderingSettings.INSTANCE.getBlockNbtMap();
|
||||
final net.minecraft.world.World mcWorld = Minecraft.getMinecraft().theWorld;
|
||||
final World mcWorld = Minecraft.getMinecraft().theWorld;
|
||||
final long currentTick = mcWorld != null ? mcWorld.getTotalWorldTime() : 0L;
|
||||
|
||||
final boolean threaded = isThreaded();
|
||||
final List<DeferredBlock> deferredBlocks = threaded ? new ArrayList<>() : null;
|
||||
|
||||
final FloatArrayList culledBounds = buildContext.getTeBoundsScratch();
|
||||
culledBounds.clear();
|
||||
double maxTeRenderDistSq = 0;
|
||||
|
||||
final RenderBlocks renderBlocks = new RenderBlocks(region);
|
||||
|
||||
for (int y = minY; y < maxY; y++) {
|
||||
@@ -151,11 +161,11 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask<C
|
||||
final TileEntity tileEntity = region.getTileEntity(x, y, z);
|
||||
if (tileEntity != null && TileEntityRendererDispatcher.instance.hasSpecialRenderer(tileEntity)) {
|
||||
final boolean isGlobal;
|
||||
AxisAlignedBB aabb = null;
|
||||
final byte boundsClass = TileEntityRenderBoundsRegistry.classify(tileEntity);
|
||||
if (boundsClass == TileEntityRenderBoundsRegistry.INFINITE || boundsClass == TileEntityRenderBoundsRegistry.DYNAMIC) {
|
||||
isGlobal = true;
|
||||
} else {
|
||||
AxisAlignedBB aabb;
|
||||
try {
|
||||
aabb = tileEntity.getRenderBoundingBox();
|
||||
} catch (Throwable t) {
|
||||
@@ -169,7 +179,23 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask<C
|
||||
isGlobal = true;
|
||||
}
|
||||
}
|
||||
(isGlobal ? renderData.globalBlockEntities : renderData.culledBlockEntities).add(tileEntity);
|
||||
if (isGlobal) {
|
||||
renderData.globalBlockEntities.add(tileEntity);
|
||||
} else {
|
||||
renderData.culledBlockEntities.add(tileEntity);
|
||||
AngelicaBuiltRenderSectionData.packSectionLocalBounds(culledBounds, aabb, minX, minY, minZ);
|
||||
double teDistSq;
|
||||
if (TileEntityRenderBoundsRegistry.overridesGetDistanceFrom(tileEntity.getClass())) {
|
||||
teDistSq = Double.POSITIVE_INFINITY;
|
||||
} else {
|
||||
try {
|
||||
teDistSq = tileEntity.getMaxRenderDistanceSquared();
|
||||
} catch (Throwable t) {
|
||||
teDistSq = Double.POSITIVE_INFINITY;
|
||||
}
|
||||
}
|
||||
if (teDistSq > maxTeRenderDistSq) maxTeRenderDistSq = teDistSq;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -213,18 +239,37 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask<C
|
||||
|
||||
// Process deferred blocks on main thread if any
|
||||
if (deferredBlocks != null && !deferredBlocks.isEmpty()) {
|
||||
processDeferredBlocks(deferredBlocks, buildContext, buffers, region, minX, minY, minZ, teMap, currentTick);
|
||||
if (Tracy.ENABLED) Tracy.beginZone(Z_MESH_DEFERRED);
|
||||
try {
|
||||
processDeferredBlocks(deferredBlocks, buildContext, buffers, region, minX, minY, minZ, teMap, currentTick);
|
||||
} finally {
|
||||
if (Tracy.ENABLED) Tracy.endZone();
|
||||
}
|
||||
}
|
||||
|
||||
final Reference2ReferenceMap<TerrainRenderPass, BuiltSectionMeshParts> meshes =
|
||||
BuiltSectionMeshParts.groupFromBuildBuffers(buffers,
|
||||
if (Tracy.ENABLED) Tracy.beginZone(Z_MESH_FINALIZE);
|
||||
final Reference2ReferenceMap<TerrainRenderPass, BuiltSectionMeshParts> meshes;
|
||||
try {
|
||||
meshes = BuiltSectionMeshParts.groupFromBuildBuffers(buffers,
|
||||
(float) camera.x - minX, (float) camera.y - minY, (float) camera.z - minZ);
|
||||
renderData.visibilityData = occluder.computeVisibilityEncoding();
|
||||
} finally {
|
||||
if (Tracy.ENABLED) Tracy.endZone();
|
||||
}
|
||||
|
||||
if (!meshes.isEmpty()) {
|
||||
renderData.hasBlockGeometry = true;
|
||||
if (Tracy.ENABLED) {
|
||||
long meshBytes = 0;
|
||||
for (BuiltSectionMeshParts parts : meshes.values()) {
|
||||
if (parts.vertexBuffer() != null) meshBytes += parts.vertexBuffer().getLength();
|
||||
}
|
||||
Tracy.zoneValue(meshBytes);
|
||||
}
|
||||
}
|
||||
|
||||
renderData.visibilityData = occluder.computeVisibilityEncoding();
|
||||
renderData.culledBlockEntityBounds = culledBounds.isEmpty() ? AngelicaBuiltRenderSectionData.EMPTY_BOUNDS : culledBounds.toFloatArray();
|
||||
renderData.maxTeRenderDistSq = maxTeRenderDistSq;
|
||||
|
||||
SmoothBiomeColorCache.clearActiveCache();
|
||||
tessellator.setTranslation(0, 0, 0);
|
||||
@@ -240,6 +285,7 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask<C
|
||||
} finally {
|
||||
((StateAwareTessellator)tessellator).angelica$setCeleritasMeshing(false);
|
||||
SmoothBiomeColorCache.clearActiveCache();
|
||||
if (Tracy.ENABLED) Tracy.endZone();
|
||||
onExitExecute();
|
||||
}
|
||||
}
|
||||
|
||||
+104
-28
@@ -1,11 +1,14 @@
|
||||
package com.gtnewhorizons.angelica.rendering.celeritas;
|
||||
|
||||
import com.gtnewhorizons.angelica.AngelicaMod;
|
||||
import com.gtnewhorizons.angelica.glsm.GLStateManager;
|
||||
import com.gtnewhorizons.angelica.glsm.RenderSystem;
|
||||
import com.gtnewhorizons.angelica.glsm.backend.BackendManager;
|
||||
import com.gtnewhorizons.angelica.rendering.culling.GpuIndirectMultiDrawEmitter;
|
||||
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
|
||||
import com.gtnewhorizons.angelica.proxy.ClientProxy;
|
||||
import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProvider;
|
||||
import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProviderHolder;
|
||||
import com.gtnewhorizons.angelica.rendering.culling.GpuCulling;
|
||||
import me.jellysquid.mods.sodium.client.gui.options.named.MultiDrawMode;
|
||||
import org.embeddedt.embeddium.impl.gl.device.CommandList;
|
||||
import org.embeddedt.embeddium.impl.gl.device.RenderDevice;
|
||||
@@ -14,8 +17,14 @@ import org.embeddedt.embeddium.impl.gl.shader.GlShader;
|
||||
import org.embeddedt.embeddium.impl.gl.shader.ShaderConstants;
|
||||
import org.embeddedt.embeddium.impl.gl.shader.ShaderParser;
|
||||
import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
|
||||
import org.embeddedt.embeddium.impl.gl.tessellation.GlPrimitiveType;
|
||||
import org.embeddedt.embeddium.impl.gl.tessellation.GlTessellation;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.DefaultChunkRenderer;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.RenderPassConfiguration;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataStorage;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.lists.ChunkRenderList;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.multidraw.DrawCommandSink;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.multidraw.DirectMultiDrawEmitter;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.multidraw.IndirectMultiDrawEmitter;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.multidraw.MultiDrawEmitter;
|
||||
@@ -26,6 +35,7 @@ import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderTextureSlot;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.shader.DefaultChunkShaderInterface;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
|
||||
import org.embeddedt.embeddium.impl.render.shader.ShaderLoader;
|
||||
import org.embeddedt.embeddium.impl.render.viewport.CameraTransform;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
|
||||
import java.util.ArrayList;
|
||||
@@ -33,12 +43,18 @@ import java.util.List;
|
||||
|
||||
class AngelicaChunkRenderer extends DefaultChunkRenderer {
|
||||
private static final int BLOCK_TEXTURE_UNIT = 0;
|
||||
private static final Tracy.ZoneId Z_CHUNK_BEGIN = Tracy.zoneId("chunkBegin", Tracy.COLOR_TERRAIN);
|
||||
private static final Tracy.ZoneId Z_CHUNK_REGION_FIRST = Tracy.zoneId("chunkRegionFirst", Tracy.COLOR_TERRAIN);
|
||||
private static final Tracy.ZoneId Z_CHUNK_REGION = Tracy.zoneId("chunkRegion", Tracy.COLOR_TERRAIN);
|
||||
private static final Tracy.ZoneId Z_CHUNK_ASSEMBLE_REGION = Tracy.zoneId("chunkAssembleRegion", Tracy.COLOR_TERRAIN);
|
||||
private static final Tracy.ZoneId Z_CHUNK_EXECUTE_BATCH = Tracy.zoneId("chunkExecuteBatch", Tracy.COLOR_TERRAIN);
|
||||
|
||||
private GlProgram<? extends ChunkShaderInterface> irisProgram;
|
||||
private boolean usingIrisProgram;
|
||||
private int rgssSampler;
|
||||
private boolean rgssSamplerResolved;
|
||||
private boolean rgssSamplerBound;
|
||||
private int regionIndex;
|
||||
|
||||
public AngelicaChunkRenderer(RenderDevice device, RenderPassConfiguration<?> renderPassConfiguration) {
|
||||
super(device, renderPassConfiguration, createEmitter());
|
||||
@@ -50,16 +66,28 @@ class AngelicaChunkRenderer extends DefaultChunkRenderer {
|
||||
}
|
||||
|
||||
private static MultiDrawEmitter createEmitter() {
|
||||
MultiDrawMode mode = ClientProxy.options().advanced.multiDrawMode;
|
||||
final MultiDrawMode configured = ClientProxy.options().advanced.multiDrawMode;
|
||||
final MultiDrawMode mode = MultiDrawModeResolver.resolve();
|
||||
|
||||
if (mode == MultiDrawMode.INDIRECT) {
|
||||
boolean supported = GLStateManager.capabilities != null && (GLStateManager.capabilities.OpenGL43 || GLStateManager.capabilities.GL_ARB_multi_draw_indirect);
|
||||
if (!supported) {
|
||||
if (mode != configured) {
|
||||
if (mode == MultiDrawMode.INDIRECT) {
|
||||
AngelicaMod.LOGGER.info("Backend requires indirect draw; {} -> INDIRECT", configured);
|
||||
} else {
|
||||
AngelicaMod.LOGGER.warn("Indirect multi-draw not supported (requires GL 4.3 / ARB_multi_draw_indirect), falling back to Direct");
|
||||
mode = MultiDrawMode.DIRECT;
|
||||
}
|
||||
}
|
||||
|
||||
if (BackendManager.RENDER_BACKEND.isIndirectRequired() && mode != MultiDrawMode.INDIRECT) {
|
||||
throw new IllegalStateException("Indirect multi-draw was required by the backend but resolved mode is " + mode);
|
||||
}
|
||||
|
||||
final GpuCulling.Availability availability = GpuCulling.availability();
|
||||
if (availability == GpuCulling.Availability.AVAILABLE) {
|
||||
AngelicaMod.LOGGER.info("Compute-driven chunk culling available, mode={}", GpuCulling.mode());
|
||||
return new GpuIndirectMultiDrawEmitter(GpuCulling.culler(), GpuCulling.sectionMeta());
|
||||
}
|
||||
AngelicaMod.LOGGER.warn("GPU culling unavailable ({}); terrain will use CPU culling", availability);
|
||||
|
||||
return switch (mode) {
|
||||
case DIRECT -> new DirectMultiDrawEmitter();
|
||||
case INDIRECT -> new IndirectMultiDrawEmitter();
|
||||
@@ -74,27 +102,33 @@ class AngelicaChunkRenderer extends DefaultChunkRenderer {
|
||||
|
||||
@Override
|
||||
protected void begin(TerrainRenderPass pass) {
|
||||
final IrisShaderProvider provider = IrisShaderProviderHolder.getProvider();
|
||||
this.regionIndex = 0;
|
||||
if (Tracy.ENABLED) Tracy.beginZone(Z_CHUNK_BEGIN);
|
||||
try {
|
||||
final IrisShaderProvider provider = IrisShaderProviderHolder.getProvider();
|
||||
|
||||
// Check if Iris shaders are active and we have an override
|
||||
if (provider != null && provider.isShadersEnabled()) {
|
||||
final GlProgram<? extends ChunkShaderInterface> override = provider.getShaderOverride(pass);
|
||||
if (override != null) {
|
||||
pass.startDrawing();
|
||||
override.bind();
|
||||
override.getInterface().setupState(pass);
|
||||
this.activeProgram = (GlProgram<ChunkShaderInterface>) override;
|
||||
this.irisProgram = override;
|
||||
this.usingIrisProgram = true;
|
||||
return;
|
||||
// Check if Iris shaders are active and we have an override
|
||||
if (provider != null && provider.isShadersEnabled()) {
|
||||
final GlProgram<? extends ChunkShaderInterface> override = provider.getShaderOverride(pass);
|
||||
if (override != null) {
|
||||
pass.startDrawing();
|
||||
override.bind();
|
||||
override.getInterface().setupState(pass);
|
||||
this.activeProgram = (GlProgram<ChunkShaderInterface>) override;
|
||||
this.irisProgram = override;
|
||||
this.usingIrisProgram = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fall back to default shader
|
||||
this.usingIrisProgram = false;
|
||||
this.irisProgram = null;
|
||||
super.begin(pass);
|
||||
bindRgssSampler();
|
||||
// Fall back to default shader
|
||||
this.usingIrisProgram = false;
|
||||
this.irisProgram = null;
|
||||
super.begin(pass);
|
||||
bindRgssSampler();
|
||||
} finally {
|
||||
if (Tracy.ENABLED) Tracy.endZone();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -155,10 +189,6 @@ class AngelicaChunkRenderer extends DefaultChunkRenderer {
|
||||
|
||||
@Override
|
||||
protected GlProgram<ChunkShaderInterface> createShader(String path, ChunkShaderOptions options) {
|
||||
if (this.enableLegacyGLPatches) {
|
||||
return super.createShader(path, options);
|
||||
}
|
||||
|
||||
final ShaderConstants constants = options.constants();
|
||||
final List<GlShader> loadedShaders = new ArrayList<>();
|
||||
|
||||
@@ -179,6 +209,52 @@ class AngelicaChunkRenderer extends DefaultChunkRenderer {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void drawRegion(ChunkShaderInterface shader, CommandList commandList, RenderRegion region,
|
||||
CameraTransform camera, long timestamp) {
|
||||
if (Tracy.ENABLED) Tracy.beginZone(regionIndex == 0 ? Z_CHUNK_REGION_FIRST : Z_CHUNK_REGION);
|
||||
try {
|
||||
regionIndex++;
|
||||
super.drawRegion(shader, commandList, region, camera, timestamp);
|
||||
} finally {
|
||||
if (Tracy.ENABLED) Tracy.endZone();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void assembleRegion(DrawCommandSink sink, RenderRegion region, SectionRenderDataStorage storage,
|
||||
ChunkRenderList renderList, CameraTransform occlusionCamera,
|
||||
TerrainRenderPass renderPass, boolean useBlockFaceCulling) {
|
||||
if (getEmitter() instanceof GpuIndirectMultiDrawEmitter gpu && gpu.isComputeActiveThisPass()) {
|
||||
gpu.prepareRegion(region);
|
||||
return;
|
||||
}
|
||||
|
||||
if (Tracy.ENABLED) Tracy.beginZone(Z_CHUNK_ASSEMBLE_REGION);
|
||||
try {
|
||||
super.assembleRegion(sink, region, storage, renderList, occlusionCamera, renderPass, useBlockFaceCulling);
|
||||
} finally {
|
||||
if (Tracy.ENABLED) Tracy.endZone();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void executeBatch(CommandList commandList, GlTessellation tessellation, GlPrimitiveType primitiveType) {
|
||||
if (Tracy.ENABLED) {
|
||||
final MultiDrawEmitter emitter = getEmitter();
|
||||
// The compute path reports itself through GpuIndirectMultiDrawEmitter; counting it here too double-counts.
|
||||
if (!(emitter instanceof GpuIndirectMultiDrawEmitter gpu && gpu.isComputeActiveThisPass())) {
|
||||
TerrainDrawStats.recordBatch(emitter.getPendingCommandCount());
|
||||
}
|
||||
Tracy.beginZone(Z_CHUNK_EXECUTE_BATCH);
|
||||
}
|
||||
try {
|
||||
super.executeBatch(commandList, tessellation, primitiveType);
|
||||
} finally {
|
||||
if (Tracy.ENABLED) Tracy.endZone();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean useBlockFaceCulling() {
|
||||
return IrisShaderProviderHolder.shouldUseFaceCulling();
|
||||
|
||||
+96
-11
@@ -3,6 +3,9 @@ package com.gtnewhorizons.angelica.rendering.celeritas;
|
||||
import com.cardinalstar.cubicchunks.world.ICubicWorld;
|
||||
import com.gtnewhorizons.angelica.compat.ModStatus;
|
||||
import com.gtnewhorizons.angelica.compat.cubicchunks.CubicChunksAPI;
|
||||
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
|
||||
import com.gtnewhorizons.angelica.glsm.profiling.TracyBackend;
|
||||
import com.gtnewhorizons.angelica.mixins.interfaces.RenderListManagerAccessor;
|
||||
import com.gtnewhorizons.angelica.mixins.interfaces.RenderSectionManagerAccessor;
|
||||
import com.gtnewhorizons.angelica.proxy.ClientProxy;
|
||||
import com.gtnewhorizons.angelica.rendering.AngelicaRenderQueue;
|
||||
@@ -40,6 +43,20 @@ import java.util.concurrent.locks.LockSupport;
|
||||
import java.util.function.BooleanSupplier;
|
||||
|
||||
public class AngelicaRenderSectionManager extends RenderSectionManager {
|
||||
private static final long P_MESH_REGIONS = Tracy.plotHandle("mesh.regions");
|
||||
private static final long P_MESH_VISIBLE_CHUNKS = Tracy.plotHandle("mesh.visibleChunks");
|
||||
private static final long P_SHADOW_REGIONS = Tracy.plotHandle("shadow.regions");
|
||||
private static final long P_SHADOW_VISIBLE_CHUNKS = Tracy.plotHandle("shadow.visibleChunks");
|
||||
private static final long P_MESH_SCHEDULED_JOBS = Tracy.plotHandle("mesh.scheduledJobs");
|
||||
private static final long P_MESH_BUSY_THREADS = Tracy.plotHandle("mesh.busyThreads");
|
||||
private static final long P_MESH_DEVICE_USED = Tracy.plotHandle("mesh.deviceUsed", TracyBackend.PLOT_FORMAT_MEMORY);
|
||||
private static final long P_MESH_DEVICE_ALLOCATED = Tracy.plotHandle("mesh.deviceAllocated", TracyBackend.PLOT_FORMAT_MEMORY);
|
||||
|
||||
private static final Tracy.ZoneId Z_BIOME_REBUILDS = Tracy.zoneId("biomeRebuilds", Tracy.COLOR_TERRAIN);
|
||||
private static final Tracy.ZoneId Z_GRAPH_SEARCH = Tracy.zoneId("graphSearch", Tracy.COLOR_TERRAIN);
|
||||
private static final Tracy.ZoneId Z_SECTION_UPLOAD = Tracy.zoneId("sectionUpload", Tracy.COLOR_TERRAIN);
|
||||
private static final Tracy.ZoneId Z_SHADOW_GRAPH_WAIT = Tracy.zoneId("shadowGraphWait", Tracy.COLOR_TERRAIN);
|
||||
|
||||
private boolean initialCameraSectionReady = false;
|
||||
|
||||
private final WorldClient world;
|
||||
@@ -91,6 +108,9 @@ public class AngelicaRenderSectionManager extends RenderSectionManager {
|
||||
|
||||
@Override
|
||||
public void update(Viewport positionedViewport, int frame, boolean spectator) {
|
||||
if (isInShadowPass() && !needsUpdate()) {
|
||||
return;
|
||||
}
|
||||
if (!isInShadowPass() && !initialCameraSectionReady) {
|
||||
var origin = positionedViewport.getChunkCoord();
|
||||
long key = PositionUtil.packSection(origin.x(), origin.y(), origin.z());
|
||||
@@ -179,24 +199,47 @@ public class AngelicaRenderSectionManager extends RenderSectionManager {
|
||||
if (this.biomeRebuildColumns.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
final int sectionCountY = this.world.getHeight() >> 4;
|
||||
for (final LongIterator it = this.biomeRebuildColumns.iterator(); it.hasNext(); ) {
|
||||
final long column = it.nextLong();
|
||||
final int cx = PositionUtil.unpackChunkX(column);
|
||||
final int cz = PositionUtil.unpackChunkZ(column);
|
||||
for (int cy = 0; cy < sectionCountY; cy++) {
|
||||
this.sectionCache.invalidate(cx, cy, cz);
|
||||
this.scheduleRebuild(cx, cy, cz, false);
|
||||
if (Tracy.ENABLED) Tracy.beginZone(Z_BIOME_REBUILDS);
|
||||
try {
|
||||
final int sectionCountY = this.world.getHeight() >> 4;
|
||||
for (final LongIterator it = this.biomeRebuildColumns.iterator(); it.hasNext(); ) {
|
||||
final long column = it.nextLong();
|
||||
final int cx = PositionUtil.unpackChunkX(column);
|
||||
final int cz = PositionUtil.unpackChunkZ(column);
|
||||
for (int cy = 0; cy < sectionCountY; cy++) {
|
||||
this.sectionCache.invalidate(cx, cy, cz);
|
||||
this.scheduleRebuild(cx, cy, cz, false);
|
||||
}
|
||||
}
|
||||
this.biomeRebuildColumns.clear();
|
||||
} finally {
|
||||
if (Tracy.ENABLED) Tracy.endZone();
|
||||
}
|
||||
this.biomeRebuildColumns.clear();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateChunks(boolean updateImmediately) {
|
||||
if (isInShadowPass()) {
|
||||
return;
|
||||
}
|
||||
this.sectionCache.cleanup();
|
||||
this.flushBiomeRebuilds();
|
||||
super.updateChunks(updateImmediately);
|
||||
if (Tracy.ENABLED) Tracy.beginZone(Z_GRAPH_SEARCH);
|
||||
try {
|
||||
super.updateChunks(updateImmediately);
|
||||
} finally {
|
||||
if (Tracy.ENABLED) Tracy.endZone();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void uploadChunks() {
|
||||
if (Tracy.ENABLED) Tracy.beginZone(Z_SECTION_UPLOAD);
|
||||
try {
|
||||
super.uploadChunks();
|
||||
} finally {
|
||||
if (Tracy.ENABLED) Tracy.endZone();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -224,6 +267,20 @@ public class AngelicaRenderSectionManager extends RenderSectionManager {
|
||||
}
|
||||
}
|
||||
|
||||
public boolean preSubmitShadowGraphUpdate(Viewport viewport, int frame, boolean spectator) {
|
||||
if (this.shadowRenderListManager == null || !this.shadowRenderListManager.isNeedsUpdate()) return false;
|
||||
if (((RenderListManagerAccessor) this.shadowRenderListManager).angelica$hasOcclusionFutureInFlight()) return false;
|
||||
|
||||
final RenderSectionManagerAccessor self = (RenderSectionManagerAccessor) this;
|
||||
final int targetQueueSize = shouldRespectUpdateTaskQueueSizeLimit() ? (int) Math.min(Integer.MAX_VALUE, (long) getBuilder().getTargetQueueSize() * 10) : Integer.MAX_VALUE;
|
||||
this.shadowRenderListManager.startGraphUpdate(viewport, frame, self.angelica$getRegions().getRegionIdsLength(), self.angelica$getSearchDistance(), shouldUseOcclusionCulling(viewport, spectator), targetQueueSize);
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean isShadowGraphDirty() {
|
||||
return this.shadowRenderListManager != null && this.shadowRenderListManager.isNeedsUpdate();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<String> getDebugStrings() {
|
||||
List<String> list = new ArrayList<>(super.getDebugStrings());
|
||||
@@ -252,7 +309,12 @@ public class AngelicaRenderSectionManager extends RenderSectionManager {
|
||||
public void renderLayer(ChunkRenderMatrices matrices, TerrainRenderPass pass, CameraTransform occlusionCamera, CameraTransform camera) {
|
||||
// Shadow pass graph update is async - must wait for it to complete before rendering
|
||||
if (IrisShaderProviderHolder.isShadowPass()) {
|
||||
finishAllGraphUpdates();
|
||||
if (Tracy.ENABLED) Tracy.beginZone(Z_SHADOW_GRAPH_WAIT);
|
||||
try {
|
||||
finishAllGraphUpdates();
|
||||
} finally {
|
||||
if (Tracy.ENABLED) Tracy.endZone();
|
||||
}
|
||||
}
|
||||
super.renderLayer(matrices, pass, occlusionCamera, camera);
|
||||
}
|
||||
@@ -277,4 +339,27 @@ public class AngelicaRenderSectionManager extends RenderSectionManager {
|
||||
LockSupport.parkNanos("Wait", 100000L);
|
||||
}
|
||||
}
|
||||
|
||||
public void tracyPlots() {
|
||||
int regions = 0;
|
||||
for (var it = this.getRenderLists().iterator(); it.hasNext(); it.next()) {
|
||||
regions++;
|
||||
}
|
||||
Tracy.plotInt(P_MESH_REGIONS, regions);
|
||||
Tracy.plotInt(P_MESH_VISIBLE_CHUNKS, this.getVisibleChunkCount());
|
||||
if (this.shadowRenderListManager != null) {
|
||||
int shadowRegions = 0, shadowSections = 0;
|
||||
for (var it = this.shadowRenderListManager.getRenderLists().iterator(); it.hasNext(); ) {
|
||||
shadowSections += it.next().getSectionsWithGeometryCount();
|
||||
shadowRegions++;
|
||||
}
|
||||
Tracy.plotInt(P_SHADOW_REGIONS, shadowRegions);
|
||||
Tracy.plotInt(P_SHADOW_VISIBLE_CHUNKS, shadowSections);
|
||||
}
|
||||
Tracy.plotInt(P_MESH_SCHEDULED_JOBS, this.getBuilder().getScheduledJobCount());
|
||||
Tracy.plotInt(P_MESH_BUSY_THREADS, this.getBuilder().getBusyThreadCount());
|
||||
final var mem = this.getDeviceMemoryStats();
|
||||
Tracy.plotInt(P_MESH_DEVICE_USED, mem.deviceUsed + mem.indexUsed);
|
||||
Tracy.plotInt(P_MESH_DEVICE_ALLOCATED, mem.deviceAllocated + mem.indexAllocated);
|
||||
}
|
||||
}
|
||||
+52
-6
@@ -2,12 +2,18 @@ package com.gtnewhorizons.angelica.rendering.celeritas;
|
||||
|
||||
import com.gtnewhorizons.angelica.Tags;
|
||||
import com.gtnewhorizons.angelica.config.AngelicaConfig;
|
||||
import com.gtnewhorizons.angelica.config.SystemProperties;
|
||||
import com.gtnewhorizons.angelica.dynamiclights.DynamicLights;
|
||||
import com.gtnewhorizons.angelica.glsm.GLStateManager;
|
||||
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
|
||||
import com.gtnewhorizons.angelica.profiling.BailClassCounts;
|
||||
import com.gtnewhorizons.angelica.profiling.RenderClassTimings;
|
||||
import static com.gtnewhorizons.angelica.glsm.backend.BackendManager.RENDER_BACKEND;
|
||||
import com.gtnewhorizons.angelica.glsm.ffp.ShaderManager;
|
||||
import com.gtnewhorizons.angelica.glsm.streaming.TessellatorStreamingDrawer;
|
||||
import com.gtnewhorizons.angelica.glsm.states.FogState;
|
||||
import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher;
|
||||
import com.gtnewhorizons.angelica.rendering.tesr.TesrBatchRenderer;
|
||||
import cpw.mods.fml.common.eventhandler.EventPriority;
|
||||
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
|
||||
import net.minecraft.client.Minecraft;
|
||||
@@ -15,12 +21,19 @@ import net.minecraft.util.EnumChatFormatting;
|
||||
import net.minecraftforge.client.event.RenderGameOverlayEvent;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class CeleritasDebugScreenHandler {
|
||||
public static final CeleritasDebugScreenHandler INSTANCE = new CeleritasDebugScreenHandler();
|
||||
|
||||
/** Toggle for fog debug display on F3 screen */
|
||||
public static boolean showFogDebug = false;
|
||||
|
||||
private static final long REBUILD_INTERVAL_NS = 500_000_000L;
|
||||
private List<String> cachedRight;
|
||||
private long lastBuildNanos;
|
||||
|
||||
@SubscribeEvent(priority = EventPriority.LOW)
|
||||
public void onRenderGameOverlayTextEvent(RenderGameOverlayEvent.Text event) {
|
||||
final Minecraft mc = Minecraft.getMinecraft();
|
||||
@@ -42,15 +55,48 @@ public class CeleritasDebugScreenHandler {
|
||||
event.left.add(getDynamicLightsDebugString());
|
||||
}
|
||||
|
||||
event.right.add("");
|
||||
event.right.add(EnumChatFormatting.GREEN + "Angelica " + Tags.VERSION + " [Celeritas Renderer] [" + RENDER_BACKEND.getName() + "]");
|
||||
event.right.addAll(renderer.getDebugStrings());
|
||||
final long now = System.nanoTime();
|
||||
if (cachedRight == null || now - lastBuildNanos >= REBUILD_INTERVAL_NS) {
|
||||
cachedRight = buildRightLines(renderer);
|
||||
lastBuildNanos = now;
|
||||
}
|
||||
event.right.addAll(cachedRight);
|
||||
}
|
||||
|
||||
private static List<String> buildRightLines(CeleritasWorldRenderer renderer) {
|
||||
final List<String> lines = new ArrayList<>();
|
||||
lines.add("");
|
||||
lines.add(EnumChatFormatting.GREEN + "Angelica " + Tags.VERSION + " [Celeritas Renderer] [" + RENDER_BACKEND.getName() + "]");
|
||||
lines.addAll(renderer.getDebugStrings());
|
||||
final ShaderManager sm = ShaderManager.getInstance();
|
||||
if (sm != null) {
|
||||
event.right.add(sm.getDebugInfo());
|
||||
lines.add(sm.getDebugInfo());
|
||||
}
|
||||
lines.add(TessellatorStreamingDrawer.getDebugInfo());
|
||||
lines.add(TesrBatchRenderer.INSTANCE.getDebugSummaryLine());
|
||||
final String transferInfo = RENDER_BACKEND.getTransferDebugInfo();
|
||||
if (transferInfo != null) {
|
||||
lines.add(transferInfo);
|
||||
}
|
||||
if (SystemProperties.DEBUG_F3_DETAIL) {
|
||||
lines.addAll(TesrBatchRenderer.INSTANCE.getDebugDetailStrings());
|
||||
lines.add(ModelPartBatcher.INSTANCE.getDebugString());
|
||||
if (Tracy.ENABLED) {
|
||||
addIfPresent(lines, RenderClassTimings.TESR.debugLine());
|
||||
addIfPresent(lines, RenderClassTimings.ENTITY.debugLine());
|
||||
addIfPresent(lines, RenderClassTimings.SHADOW_ENTITY.debugLine());
|
||||
addIfPresent(lines, BailClassCounts.MATERIAL.debugLine());
|
||||
addIfPresent(lines, BailClassCounts.TEMPLATE.debugLine());
|
||||
}
|
||||
}
|
||||
lines.add("");
|
||||
return lines;
|
||||
}
|
||||
|
||||
private static void addIfPresent(List<String> lines, String line) {
|
||||
if (!line.isEmpty()) {
|
||||
lines.add(line);
|
||||
}
|
||||
event.right.add(TessellatorStreamingDrawer.getDebugInfo());
|
||||
event.right.add("");
|
||||
}
|
||||
|
||||
public static String getFogDebugString() {
|
||||
|
||||
@@ -11,7 +11,7 @@ public class CeleritasSetup {
|
||||
private static boolean initialized = false;
|
||||
|
||||
public static void ensureInitialized() {
|
||||
if (!initialized && AngelicaConfig.enableCeleritas) {
|
||||
if (!initialized) {
|
||||
GLRenderDevice.VANILLA_STATE_RESETTER = () -> GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
|
||||
ChunkBiomeDataChangedEvent.BUS.addListener(CeleritasSetup::onChunkBiomeDataChanged);
|
||||
AngelicaClientTweaker.LOGGER.debug("Celeritas init");
|
||||
|
||||
+300
-141
@@ -1,6 +1,7 @@
|
||||
package com.gtnewhorizons.angelica.rendering.celeritas;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Comparator;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
@@ -8,11 +9,15 @@ import java.util.List;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.multiplayer.WorldClient;
|
||||
import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher;
|
||||
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.tileentity.TileEntity;
|
||||
import net.minecraft.util.AxisAlignedBB;
|
||||
import net.minecraftforge.client.MinecraftForgeClient;
|
||||
|
||||
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
|
||||
import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.embeddedt.embeddium.impl.gl.device.CommandList;
|
||||
@@ -24,7 +29,11 @@ import org.embeddedt.embeddium.impl.render.chunk.lists.SortedRenderLists;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkMeshFormats;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexType;
|
||||
import org.embeddedt.embeddium.impl.render.terrain.SimpleWorldRenderer;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
|
||||
import org.embeddedt.embeddium.impl.render.viewport.CameraTransform;
|
||||
import org.embeddedt.embeddium.impl.render.viewport.Viewport;
|
||||
import org.embeddedt.embeddium.impl.render.viewport.frustum.SimpleFrustum;
|
||||
import org.joml.FrustumIntersection;
|
||||
import org.joml.Matrix4f;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
|
||||
@@ -33,16 +42,29 @@ import com.gtnewhorizons.angelica.compat.cubicchunks.CubicChunksAPI;
|
||||
import com.gtnewhorizons.angelica.dynamiclights.DynamicLights;
|
||||
import com.gtnewhorizons.angelica.dynamiclights.IDynamicLightWorldRenderer;
|
||||
import com.gtnewhorizons.angelica.glsm.GLStateManager;
|
||||
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
|
||||
import com.gtnewhorizons.angelica.mixins.interfaces.ITileEntityBoundingBoxCache;
|
||||
import com.gtnewhorizons.angelica.profiling.RenderClassTimings;
|
||||
import com.gtnewhorizons.angelica.proxy.ClientProxy;
|
||||
import com.gtnewhorizons.angelica.rendering.RenderingState;
|
||||
import com.gtnewhorizons.angelica.rendering.TileEntityRenderBoundsRegistry;
|
||||
import com.gtnewhorizons.angelica.rendering.culling.GpuCulling;
|
||||
import com.gtnewhorizons.angelica.rendering.tesr.AngelicaTesrMeshCache;
|
||||
import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher;
|
||||
import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProvider;
|
||||
import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProviderHolder;
|
||||
import com.gtnewhorizons.angelica.rendering.tesr.TesrAttribution;
|
||||
import com.gtnewhorizons.angelica.rendering.tesr.TesrBatchRenderer;
|
||||
import net.coderbot.iris.pipeline.ShadowRenderer;
|
||||
|
||||
public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, AngelicaRenderSectionManager, BlockRenderLayer, TileEntity, CeleritasWorldRenderer.TileEntityRenderContext> implements IDynamicLightWorldRenderer {
|
||||
private static final Logger LOGGER = LogManager.getLogger("Angelica");
|
||||
|
||||
private static final Tracy.ZoneId Z_TESR_COLLECT = Tracy.zoneId("tesrCollect", Tracy.COLOR_CLIENT);
|
||||
private static final Tracy.ZoneId Z_TESR_DISPATCH = Tracy.zoneId("tesrDispatch", Tracy.COLOR_CLIENT);
|
||||
private static final Tracy.ZoneId Z_TESR_MODEL_PARTS = Tracy.zoneId("tesrModelParts", Tracy.COLOR_CLIENT);
|
||||
private static final Tracy.ZoneId Z_TESR_RENDER_TE = Tracy.zoneId("tesrRenderTE", Tracy.COLOR_CLIENT);
|
||||
|
||||
private final Minecraft mc;
|
||||
private static CeleritasWorldRenderer instance;
|
||||
|
||||
@@ -52,13 +74,19 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
|
||||
private final TileEntityRenderContext teRenderContext = new TileEntityRenderContext();
|
||||
private boolean useEntityCulling = true;
|
||||
|
||||
private FrustumIntersection teFrustum;
|
||||
private CameraTransform teTransform;
|
||||
private int teCullEpoch;
|
||||
private double teCamX, teCamY, teCamZ;
|
||||
|
||||
// the volume of a section multiplied by the number of sections to be checked at most
|
||||
private static final double MAX_ENTITY_CHECK_VOLUME = 16 * 16 * 16 * 15;
|
||||
|
||||
private final ObjectArrayList<TileEntity> frameTEs = new ObjectArrayList<>();
|
||||
private final ObjectArrayList<TileEntity> frameOverride = new ObjectArrayList<>();
|
||||
|
||||
// For sorting transparent TESRs
|
||||
private final RenderSectionOrderer renderSectionOrderer = new RenderSectionOrderer();
|
||||
private final TileEntityOrderer tileEntityOrderer = new TileEntityOrderer();
|
||||
private final ArrayList<RenderSection> sortedRenderSections = new ArrayList<>();
|
||||
private final ArrayList<TileEntity> sortedTileEntities = new ArrayList<>();
|
||||
|
||||
private CeleritasWorldRenderer(Minecraft mc) {
|
||||
@@ -100,10 +128,14 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
|
||||
@Override
|
||||
protected void unloadWorld() {
|
||||
DynamicLights.setActiveRenderer(null);
|
||||
this.sortedRenderSections.clear();
|
||||
this.frameTEs.clear();
|
||||
this.frameOverride.clear();
|
||||
this.sortedTileEntities.clear();
|
||||
ShadowRenderer.visibleTileEntities.clear();
|
||||
ShadowRenderer.globalTileEntities.clear();
|
||||
TesrBatchRenderer.INSTANCE.clearRetained();
|
||||
ModelPartBatcher.INSTANCE.clear();
|
||||
GpuCulling.onWorldUnload();
|
||||
super.unloadWorld();
|
||||
}
|
||||
|
||||
@@ -130,21 +162,32 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
|
||||
}
|
||||
}
|
||||
|
||||
private final Matrix4f mainPassModelView = new Matrix4f();
|
||||
private ChunkRenderMatrices mainPassMatrices;
|
||||
private ChunkRenderMatrices shadowPassMatrices;
|
||||
|
||||
@Override
|
||||
protected ChunkRenderMatrices createChunkRenderMatrices() {
|
||||
final boolean shadowPass = renderSectionManager.isInShadowPass();
|
||||
final Matrix4f projection = shadowPass ? ShadowRenderer.PROJECTION : RenderingState.INSTANCE.getProjectionMatrix();
|
||||
Matrix4f modelView = shadowPass ? ShadowRenderer.MODELVIEW : RenderingState.INSTANCE.getModelViewMatrix();
|
||||
if (!shadowPass) {
|
||||
// Minecraft's setupCameraTransform bakes translate(0, -eyeHeight, 0) into the modelview.
|
||||
// Chunk rendering passes eye position to drawChunkLayer so vertices arrive at
|
||||
// the shader as (vert_world - eye).
|
||||
final Entity view = mc.renderViewEntity;
|
||||
if (view != null) {
|
||||
modelView = new Matrix4f(modelView).translate(0f, view.getEyeHeight(), 0f);
|
||||
if (renderSectionManager.isInShadowPass()) {
|
||||
ChunkRenderMatrices matrices = shadowPassMatrices;
|
||||
if (matrices == null) {
|
||||
matrices = shadowPassMatrices = new ChunkRenderMatrices(ShadowRenderer.PROJECTION, ShadowRenderer.MODELVIEW);
|
||||
}
|
||||
return matrices;
|
||||
}
|
||||
return new ChunkRenderMatrices(projection, modelView);
|
||||
// Minecraft's setupCameraTransform bakes translate(0, -eyeHeight, 0) into the modelview.
|
||||
// Chunk rendering passes eye position to drawChunkLayer so vertices arrive at
|
||||
// the shader as (vert_world - eye).
|
||||
mainPassModelView.set(RenderingState.INSTANCE.getModelViewMatrix());
|
||||
final Entity view = mc.renderViewEntity;
|
||||
if (view != null) {
|
||||
mainPassModelView.translate(0f, view.getEyeHeight(), 0f);
|
||||
}
|
||||
ChunkRenderMatrices matrices = mainPassMatrices;
|
||||
if (matrices == null) {
|
||||
matrices = mainPassMatrices = new ChunkRenderMatrices(RenderingState.INSTANCE.getProjectionMatrix(), mainPassModelView);
|
||||
}
|
||||
return matrices;
|
||||
}
|
||||
|
||||
private ChunkVertexType chooseVertexType() {
|
||||
@@ -169,11 +212,16 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
|
||||
|
||||
@Override
|
||||
protected void renderBlockEntityList(List<TileEntity> list, TileEntityRenderContext context) {
|
||||
for (TileEntity tileEntity : list) {
|
||||
renderTE(tileEntity, context.pass, context.partialTicks);
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
final TileEntity te = list.get(i);
|
||||
if (isTileEntityVisible(te)) {
|
||||
frameTEs.add(te);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private CameraState lastMainCameraState;
|
||||
|
||||
@Override
|
||||
public void setupTerrain(Viewport viewport, CameraState cameraState, int frame, boolean spectator, boolean updateChunksImmediately) {
|
||||
var transform = viewport.getTransform();
|
||||
@@ -186,6 +234,14 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
|
||||
|
||||
this.useEntityCulling = ClientProxy.options().performance.useEntityCulling;
|
||||
|
||||
if (renderSectionManager.isInShadowPass()) {
|
||||
if (lastMainCameraState != null) {
|
||||
cameraState = lastMainCameraState;
|
||||
}
|
||||
} else {
|
||||
lastMainCameraState = cameraState;
|
||||
}
|
||||
|
||||
super.setupTerrain(viewport, cameraState, frame, spectator, updateChunksImmediately);
|
||||
|
||||
// Process deferred dynamic light chunk rebuilds with frustum culling
|
||||
@@ -193,9 +249,12 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
|
||||
DynamicLights.get().processChunkRebuilds(viewport);
|
||||
}
|
||||
|
||||
// Collect tile entities for shadow pass rendering
|
||||
if (renderSectionManager.isInShadowPass() && IrisShaderProviderHolder.isActive()) {
|
||||
collectTileEntitiesForShadow();
|
||||
if (renderSectionManager.isInShadowPass()) {
|
||||
if (IrisShaderProviderHolder.isActive()) {
|
||||
collectTileEntitiesForShadow();
|
||||
}
|
||||
} else if (IrisShaderProviderHolder.isActive()) {
|
||||
IrisShaderProviderHolder.getProvider().preSubmitShadowGraph(frame, spectator);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -203,6 +262,10 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
|
||||
this.currentViewport = viewport;
|
||||
}
|
||||
|
||||
public Viewport getCurrentViewport() {
|
||||
return this.currentViewport;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private void collectTileEntitiesForShadow() {
|
||||
final SortedRenderLists renderLists = renderSectionManager.getRenderLists();
|
||||
@@ -228,7 +291,9 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
|
||||
final var context = renderSection.getBuiltContext();
|
||||
if (context instanceof MinecraftBuiltRenderSectionData<?, ?> mcData) {
|
||||
final var culledEntities = (List<TileEntity>) mcData.culledBlockEntities;
|
||||
ShadowRenderer.visibleTileEntities.addAll(culledEntities);
|
||||
if (!culledEntities.isEmpty()) {
|
||||
ShadowRenderer.visibleTileEntities.add(culledEntities);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -237,18 +302,37 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
|
||||
final var context = renderSection.getBuiltContext();
|
||||
if (context instanceof MinecraftBuiltRenderSectionData<?, ?> mcData) {
|
||||
final var globalEntities = (List<TileEntity>) mcData.globalBlockEntities;
|
||||
ShadowRenderer.globalTileEntities.addAll(globalEntities);
|
||||
if (!globalEntities.isEmpty()) {
|
||||
ShadowRenderer.globalTileEntities.add(globalEntities);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private CameraTransform cachedCameraTransform;
|
||||
private double cachedCamX, cachedCamY, cachedCamZ;
|
||||
|
||||
@Override
|
||||
public void drawChunkLayer(BlockRenderLayer renderLayer, double x, double y, double z) {
|
||||
if (DEBUG_WIREFRAME_MODE) {
|
||||
GLStateManager.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_LINE);
|
||||
}
|
||||
|
||||
super.drawChunkLayer(renderLayer, x, y, z);
|
||||
final ChunkRenderMatrices matrices = createChunkRenderMatrices();
|
||||
final Collection<TerrainRenderPass> passes = this.renderSectionManager.getRenderPassConfiguration().vanillaRenderStages().get(renderLayer);
|
||||
if (passes != null && !passes.isEmpty()) {
|
||||
CameraTransform realCamera = cachedCameraTransform;
|
||||
if (realCamera == null || cachedCamX != x || cachedCamY != y || cachedCamZ != z) {
|
||||
realCamera = cachedCameraTransform = new CameraTransform(x, y, z);
|
||||
cachedCamX = x;
|
||||
cachedCamY = y;
|
||||
cachedCamZ = z;
|
||||
}
|
||||
final CameraTransform occlusionCamera = this.getLastViewport().getTransform();
|
||||
for (final TerrainRenderPass pass : passes) {
|
||||
this.renderSectionManager.renderLayer(matrices, pass, occlusionCamera, realCamera);
|
||||
}
|
||||
}
|
||||
|
||||
if (DEBUG_WIREFRAME_MODE) {
|
||||
GLStateManager.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_FILL);
|
||||
@@ -257,117 +341,216 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
|
||||
GLStateManager.glColor4f(1, 1, 1, 1);
|
||||
}
|
||||
|
||||
private int renderCulledTileEntities(TileEntityRenderContext renderContext) {
|
||||
int count = 0;
|
||||
sortedTileEntities.clear();
|
||||
SortedRenderLists renderLists = renderSectionManager.getRenderLists();
|
||||
Iterator<ChunkRenderList> renderListIterator = renderLists.iterator();
|
||||
|
||||
while (renderListIterator.hasNext()) {
|
||||
var renderList = renderListIterator.next();
|
||||
|
||||
var renderRegion = renderList.getRegion();
|
||||
var renderSectionIterator = renderList.sectionsWithEntitiesIterator();
|
||||
|
||||
if (renderSectionIterator == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
while (renderSectionIterator.hasNext()) {
|
||||
var renderSectionId = renderSectionIterator.nextByteAsInt();
|
||||
var renderSection = renderRegion.getSection(renderSectionId);
|
||||
|
||||
if (renderSection == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
var context = renderSection.getBuiltContext();
|
||||
|
||||
if (!(context instanceof MinecraftBuiltRenderSectionData<?, ?> mcData)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// noinspection unchecked
|
||||
var blockEntities = (List<TileEntity>) mcData.culledBlockEntities;
|
||||
|
||||
if (blockEntities.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (TileEntity te : blockEntities) {
|
||||
if (te.shouldRenderInPass(renderContext.pass)) sortedTileEntities.add(te);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sortedTileEntities.sort(tileEntityOrderer.setLastCameraState(lastCameraState));
|
||||
this.renderBlockEntityList(sortedTileEntities, renderContext);
|
||||
|
||||
return sortedTileEntities.size();
|
||||
}
|
||||
|
||||
private int renderGlobalTileEntities(TileEntityRenderContext renderContext) {
|
||||
int count = 0;
|
||||
sortedRenderSections.clear();
|
||||
sortedRenderSections.addAll(renderSectionManager.getSectionsWithGlobalEntities());
|
||||
sortedRenderSections.sort(renderSectionOrderer.setLastCameraState(lastCameraState));
|
||||
for (var renderSection : sortedRenderSections) {
|
||||
sortedTileEntities.clear();
|
||||
var builtContext = renderSection.getBuiltContext();
|
||||
|
||||
if (!(builtContext instanceof MinecraftBuiltRenderSectionData<?, ?> mcData)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// noinspection unchecked
|
||||
var blockEntities = (List<TileEntity>) mcData.globalBlockEntities;
|
||||
|
||||
if (blockEntities.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (TileEntity te : blockEntities) {
|
||||
if (te.shouldRenderInPass(renderContext.pass)) sortedTileEntities.add(te);
|
||||
}
|
||||
|
||||
count += sortedTileEntities.size();
|
||||
|
||||
sortedTileEntities.sort(tileEntityOrderer.setLastCameraState(lastCameraState));
|
||||
this.renderBlockEntityList(sortedTileEntities, renderContext);
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
public int renderBlockEntities(float partialTicks) {
|
||||
AngelicaTesrMeshCache.INSTANCE.tick();
|
||||
final int pass = MinecraftForgeClient.getRenderPass();
|
||||
teRenderContext.set(partialTicks, pass);
|
||||
if (pass == 0 || !ClientProxy.options().performance.translucencySorting) {
|
||||
return super.renderBlockEntities(teRenderContext);
|
||||
}
|
||||
|
||||
TesrBatchRenderer.INSTANCE.beginPass(
|
||||
pass == 0 ? TesrBatchRenderer.PASS_MAIN_0 : TesrBatchRenderer.PASS_MAIN_1,
|
||||
GLStateManager.getModelViewMatrix(),
|
||||
TileEntityRendererDispatcher.staticPlayerX,
|
||||
TileEntityRendererDispatcher.staticPlayerY,
|
||||
TileEntityRendererDispatcher.staticPlayerZ);
|
||||
ModelPartBatcher.INSTANCE.begin(ModelPartBatcher.Mode.BLOCK_ENTITIES);
|
||||
int count = 0;
|
||||
count += this.renderCulledTileEntities(teRenderContext);
|
||||
count += this.renderGlobalTileEntities(teRenderContext);
|
||||
if (pass == 0) {
|
||||
teRenderContext.set(partialTicks, pass);
|
||||
final Viewport viewport = this.currentViewport;
|
||||
this.teTransform = viewport != null ? viewport.getTransform() : null;
|
||||
this.teFrustum = viewport != null && ClientProxy.options().performance.sectionGatedTesrCulling && viewport.getFrustum() instanceof SimpleFrustum simpleFrustum ? simpleFrustum.frustumIntersection() : null;
|
||||
this.teCullEpoch++;
|
||||
this.teCamX = TileEntityRendererDispatcher.staticPlayerX;
|
||||
this.teCamY = TileEntityRendererDispatcher.staticPlayerY;
|
||||
this.teCamZ = TileEntityRendererDispatcher.staticPlayerZ;
|
||||
frameTEs.clear();
|
||||
frameOverride.clear();
|
||||
if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_COLLECT);
|
||||
try {
|
||||
super.renderBlockEntities(teRenderContext);
|
||||
} finally {
|
||||
if (Tracy.ENABLED) Tracy.endZone();
|
||||
}
|
||||
this.teFrustum = null;
|
||||
this.teTransform = null;
|
||||
if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_DISPATCH);
|
||||
try {
|
||||
for (int i = 0; i < frameTEs.size(); i++) {
|
||||
final TileEntity te = frameTEs.get(i);
|
||||
if (((ITileEntityBoundingBoxCache) te).angelica$passClass() == TileEntityRenderBoundsRegistry.PASS0_ONLY) {
|
||||
dispatchTE(te, partialTicks);
|
||||
count++;
|
||||
continue;
|
||||
}
|
||||
frameOverride.add(te);
|
||||
if (te.shouldRenderInPass(0)) {
|
||||
dispatchTE(te, partialTicks);
|
||||
count++;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (Tracy.ENABLED) Tracy.endZone();
|
||||
}
|
||||
} else {
|
||||
if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_DISPATCH);
|
||||
try {
|
||||
sortedTileEntities.clear();
|
||||
for (int i = 0; i < frameOverride.size(); i++) {
|
||||
final TileEntity te = frameOverride.get(i);
|
||||
if (te.shouldRenderInPass(pass)) {
|
||||
sortedTileEntities.add(te);
|
||||
}
|
||||
}
|
||||
if (sortedTileEntities.size() > 1 && ClientProxy.options().performance.translucencySorting) {
|
||||
sortedTileEntities.sort(tileEntityOrderer.setLastCameraState(lastCameraState));
|
||||
}
|
||||
for (int i = 0; i < sortedTileEntities.size(); i++) {
|
||||
dispatchTE(sortedTileEntities.get(i), partialTicks);
|
||||
}
|
||||
count = sortedTileEntities.size();
|
||||
} finally {
|
||||
if (Tracy.ENABLED) Tracy.endZone();
|
||||
}
|
||||
}
|
||||
if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_MODEL_PARTS);
|
||||
try {
|
||||
ModelPartBatcher.INSTANCE.flush();
|
||||
} finally {
|
||||
if (Tracy.ENABLED) Tracy.endZone();
|
||||
}
|
||||
TesrBatchRenderer.INSTANCE.flush();
|
||||
return count;
|
||||
}
|
||||
|
||||
private void renderTE(TileEntity tileEntity, int pass, float partialTicks) {
|
||||
if (!tileEntity.shouldRenderInPass(pass)) {
|
||||
return;
|
||||
@Override
|
||||
protected int renderSectionBlockEntities(RenderSection section, List<TileEntity> blockEntities, boolean culled, TileEntityRenderContext renderContext) {
|
||||
if (culled) {
|
||||
if (section.getBuiltContext() instanceof AngelicaBuiltRenderSectionData angelicaData) {
|
||||
if (TeDistanceMath.distSqToSection(teCamX, teCamY, teCamZ,
|
||||
section.getOriginX(), section.getOriginY(), section.getOriginZ()) >= angelicaData.maxTeRenderDistSq) {
|
||||
return 0;
|
||||
}
|
||||
if (teFrustum != null) {
|
||||
return collectGatedSectionBlockEntities(section, angelicaData, blockEntities);
|
||||
}
|
||||
}
|
||||
|
||||
int count = 0;
|
||||
for (int i = 0; i < blockEntities.size(); i++) {
|
||||
final TileEntity te = blockEntities.get(i);
|
||||
if (isTileEntityVisible(te)) {
|
||||
frameTEs.add(te);
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
int count = 0;
|
||||
for (int i = 0; i < blockEntities.size(); i++) {
|
||||
final TileEntity te = blockEntities.get(i);
|
||||
if (!(te.getDistanceFrom(teCamX, teCamY, teCamZ) < te.getMaxRenderDistanceSquared())) continue;
|
||||
if (isTileEntityVisible(te)) {
|
||||
frameTEs.add(te);
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
private int collectGatedSectionBlockEntities(RenderSection section, AngelicaBuiltRenderSectionData angelicaData, List<TileEntity> blockEntities) {
|
||||
final CameraTransform t = this.teTransform;
|
||||
final float ox = (section.getOriginX() - t.intX) - t.fracX;
|
||||
final float oy = (section.getOriginY() - t.intY) - t.fracY;
|
||||
final float oz = (section.getOriginZ() - t.intZ) - t.fracZ;
|
||||
|
||||
final int verdict = sectionVerdict(angelicaData, ox, oy, oz);
|
||||
if (verdict >= 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (verdict == FrustumIntersection.INSIDE) {
|
||||
frameTEs.addAll(blockEntities);
|
||||
return blockEntities.size();
|
||||
}
|
||||
|
||||
final float[] bounds = angelicaData.culledBlockEntityBounds;
|
||||
if (bounds.length != blockEntities.size() * 6) {
|
||||
throw new IllegalStateException("culledBlockEntityBounds desync: " + bounds.length + " floats for " + blockEntities.size() + " tile entities");
|
||||
}
|
||||
|
||||
int count = 0;
|
||||
for (int i = 0, b = 0; i < blockEntities.size(); i++, b += 6) {
|
||||
if (teFrustum.testAab(ox + bounds[b], oy + bounds[b + 1], oz + bounds[b + 2],
|
||||
ox + bounds[b + 3], oy + bounds[b + 4], oz + bounds[b + 5])) {
|
||||
frameTEs.add(blockEntities.get(i));
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
private int sectionVerdict(AngelicaBuiltRenderSectionData angelicaData, float ox, float oy, float oz) {
|
||||
if (angelicaData.cullEpoch == this.teCullEpoch) {
|
||||
return angelicaData.cullVerdict;
|
||||
}
|
||||
final int verdict = this.teFrustum.intersectAab(ox, oy, oz, ox + 16.0f, oy + 16.0f, oz + 16.0f);
|
||||
angelicaData.cullEpoch = this.teCullEpoch;
|
||||
angelicaData.cullVerdict = verdict;
|
||||
return verdict;
|
||||
}
|
||||
|
||||
private boolean isTileEntityVisible(TileEntity tileEntity) {
|
||||
final ITileEntityBoundingBoxCache teCache = (ITileEntityBoundingBoxCache) tileEntity;
|
||||
|
||||
final byte boundsClass = teCache.angelica$boundsClass();
|
||||
if (boundsClass != TileEntityRenderBoundsRegistry.INFINITE) {
|
||||
final AxisAlignedBB aabb = boundsClass == TileEntityRenderBoundsRegistry.DYNAMIC ? tileEntity.getRenderBoundingBox() : teCache.angelica$getCachedRenderBoundingBox();
|
||||
if (aabb != null && !this.currentViewport.isBoxVisible(aabb.minX, aabb.minY, aabb.minZ, aabb.maxX, aabb.maxY, aabb.maxZ)) {
|
||||
return;
|
||||
}
|
||||
return aabb == null || isAabbVisible(aabb);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean isAabbVisible(AxisAlignedBB aabb) {
|
||||
final FrustumIntersection frustum = this.teFrustum;
|
||||
if (frustum == null) {
|
||||
return this.currentViewport.isBoxVisible(aabb.minX, aabb.minY, aabb.minZ, aabb.maxX, aabb.maxY, aabb.maxZ);
|
||||
}
|
||||
final CameraTransform t = this.teTransform;
|
||||
return frustum.testAab(
|
||||
(float) (aabb.minX - t.intX) - t.fracX,
|
||||
(float) (aabb.minY - t.intY) - t.fracY,
|
||||
(float) (aabb.minZ - t.intZ) - t.fracZ,
|
||||
(float) (aabb.maxX - t.intX) - t.fracX,
|
||||
(float) (aabb.maxY - t.intY) - t.fracY,
|
||||
(float) (aabb.maxZ - t.intZ) - t.fracZ);
|
||||
}
|
||||
|
||||
private final Reference2ObjectOpenHashMap<Class<?>, Class<?>> teLabelClasses = new Reference2ObjectOpenHashMap<>();
|
||||
|
||||
private Class<?> teLabelClass(TileEntity tileEntity) {
|
||||
final Class<?> teClass = tileEntity.getClass();
|
||||
Class<?> label = teLabelClasses.get(teClass);
|
||||
if (label == null) {
|
||||
final TileEntitySpecialRenderer renderer = TileEntityRendererDispatcher.instance.getSpecialRenderer(tileEntity);
|
||||
label = renderer != null ? renderer.getClass() : teClass;
|
||||
teLabelClasses.put(teClass, label);
|
||||
}
|
||||
return label;
|
||||
}
|
||||
|
||||
private void dispatchTE(TileEntity tileEntity, float partialTicks) {
|
||||
try {
|
||||
TileEntityRendererDispatcher.instance.renderTileEntity(tileEntity, partialTicks);
|
||||
final long start = Tracy.ENABLED ? System.nanoTime() : 0L;
|
||||
final boolean attribute = Tracy.ENABLED && TesrAttribution.currentRenderable == null;
|
||||
if (attribute) TesrAttribution.currentRenderable = tileEntity.getClass();
|
||||
if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_RENDER_TE);
|
||||
try {
|
||||
TileEntityRendererDispatcher.instance.renderTileEntity(tileEntity, partialTicks);
|
||||
} finally {
|
||||
if (Tracy.ENABLED) Tracy.endZone();
|
||||
if (attribute) TesrAttribution.currentRenderable = null;
|
||||
if (Tracy.ENABLED) RenderClassTimings.TESR.add(teLabelClass(tileEntity), System.nanoTime() - start);
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
if (tileEntity.isInvalid()) {
|
||||
LOGGER.warn("Suppressed exception rendering invalid TileEntity {} at ({}, {}, {})", tileEntity.getClass().getName(), tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord, e);
|
||||
@@ -413,30 +596,6 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
|
||||
}
|
||||
}
|
||||
|
||||
private static class RenderSectionOrderer implements Comparator<RenderSection> {
|
||||
|
||||
public CameraState lastCameraState;
|
||||
|
||||
public RenderSectionOrderer() {
|
||||
super();
|
||||
}
|
||||
|
||||
public RenderSectionOrderer setLastCameraState(CameraState lastCameraState) {
|
||||
this.lastCameraState = lastCameraState;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compare(RenderSection render1, RenderSection render2) {
|
||||
final float x = (float) this.lastCameraState.x();
|
||||
final float y = (float) this.lastCameraState.y();
|
||||
final float z = (float) this.lastCameraState.z();
|
||||
final float d1 = render1.getSquaredDistance(x, y, z);
|
||||
final float d2 = render2.getSquaredDistance(x, y, z);
|
||||
return Float.compare(d2, d1);
|
||||
}
|
||||
}
|
||||
|
||||
private static class TileEntityOrderer implements Comparator<TileEntity> {
|
||||
public CameraState lastCameraState;
|
||||
|
||||
|
||||
+4
-36
@@ -9,8 +9,7 @@ import org.embeddedt.embeddium.impl.gl.device.MultiDrawBatch;
|
||||
import org.embeddedt.embeddium.impl.gl.tessellation.GlIndexType;
|
||||
import org.embeddedt.embeddium.impl.gl.tessellation.GlPrimitiveType;
|
||||
import org.embeddedt.embeddium.impl.gl.tessellation.GlTessellation;
|
||||
import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataUnsafe;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.multidraw.DrawCommandSink;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.multidraw.MultiDrawEmitter;
|
||||
|
||||
public record IndividualDrawEmitter(MultiDrawBatch batch) implements MultiDrawEmitter {
|
||||
@@ -19,29 +18,13 @@ public record IndividualDrawEmitter(MultiDrawBatch batch) implements MultiDrawEm
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("IntegerMultiplicationImplicitCastToLong")
|
||||
public void addDrawCommands(long pMeshData, int mask, int indexPointerMask) {
|
||||
var batch = this.batch;
|
||||
final var pBaseVertex = batch.pBaseVertex;
|
||||
final var pElementCount = batch.pElementCount;
|
||||
final var pElementPointer = batch.pElementPointer;
|
||||
|
||||
int size = batch.size;
|
||||
|
||||
for (int facing = 0; facing < ModelQuadFacing.COUNT; facing++) {
|
||||
LWJGL.memPutInt(pBaseVertex + (size << 2), SectionRenderDataUnsafe.getVertexOffset(pMeshData, facing));
|
||||
LWJGL.memPutInt(pElementCount + (size << 2), SectionRenderDataUnsafe.getElementCount(pMeshData, facing));
|
||||
LWJGL.memPutAddress(pElementPointer + (size << 3), SectionRenderDataUnsafe.getIndexOffset(pMeshData, facing) & indexPointerMask);
|
||||
|
||||
size += (mask >> facing) & 1;
|
||||
}
|
||||
|
||||
batch.size = size;
|
||||
public DrawCommandSink getCommandSink() {
|
||||
return this.batch;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void executeBatch(CommandList commandList, GlTessellation tessellation, GlPrimitiveType primitiveType) {
|
||||
try (DrawCommandList _ = commandList.beginTessellating(tessellation)) {
|
||||
try (DrawCommandList ignored = commandList.beginTessellating(tessellation)) {
|
||||
final int mode = primitiveType.getId();
|
||||
final int type = GlIndexType.UNSIGNED_INT.getFormatId();
|
||||
|
||||
@@ -54,21 +37,6 @@ public record IndividualDrawEmitter(MultiDrawBatch batch) implements MultiDrawEm
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getIndexBufferSize() {
|
||||
return this.batch.getIndexBufferSize();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
return this.batch.isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
this.batch.clear();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete() {
|
||||
this.batch.delete();
|
||||
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.gtnewhorizons.angelica.rendering.celeritas;
|
||||
|
||||
import com.gtnewhorizons.angelica.glsm.GLStateManager;
|
||||
import com.gtnewhorizons.angelica.glsm.backend.BackendManager;
|
||||
import com.gtnewhorizons.angelica.proxy.ClientProxy;
|
||||
import me.jellysquid.mods.sodium.client.gui.options.named.MultiDrawMode;
|
||||
import org.lwjgl.opengl.ContextCapabilities;
|
||||
|
||||
public final class MultiDrawModeResolver {
|
||||
|
||||
private MultiDrawModeResolver() {}
|
||||
|
||||
public static boolean indirectSupported() {
|
||||
final ContextCapabilities caps = GLStateManager.capabilities;
|
||||
return caps != null && (caps.OpenGL43 || caps.GL_ARB_multi_draw_indirect);
|
||||
}
|
||||
|
||||
public static MultiDrawMode resolve() {
|
||||
final MultiDrawMode configured = ClientProxy.options().advanced.multiDrawMode;
|
||||
if (configured != MultiDrawMode.INDIRECT && BackendManager.RENDER_BACKEND.isIndirectRequired()) {
|
||||
return MultiDrawMode.INDIRECT;
|
||||
}
|
||||
if (configured == MultiDrawMode.INDIRECT && !indirectSupported()) {
|
||||
return MultiDrawMode.DIRECT;
|
||||
}
|
||||
return configured;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.gtnewhorizons.angelica.rendering.celeritas;
|
||||
|
||||
/** Decides when the section-age uniform upload can be skipped */
|
||||
public final class SectionAgeMath {
|
||||
|
||||
public static final long STEP_NANOS = 100_000_000L;
|
||||
|
||||
private SectionAgeMath() {}
|
||||
|
||||
public static long quantize(long timestampNanos) {
|
||||
return timestampNanos - Math.floorMod(timestampNanos, STEP_NANOS);
|
||||
}
|
||||
|
||||
public static long[] newState() {
|
||||
return new long[] { Long.MIN_VALUE, Long.MIN_VALUE, 0L };
|
||||
}
|
||||
|
||||
public static boolean canSkip(long[] state, long newestLoadTime, long quantizedTimestamp) {
|
||||
return state[0] == newestLoadTime && (state[2] == 1L || state[1] == quantizedTimestamp);
|
||||
}
|
||||
|
||||
public static void record(long[] state, long newestLoadTime, long quantizedTimestamp, boolean allSaturated) {
|
||||
state[0] = newestLoadTime;
|
||||
state[1] = quantizedTimestamp;
|
||||
state[2] = allSaturated ? 1L : 0L;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.gtnewhorizons.angelica.rendering.celeritas;
|
||||
|
||||
public final class TeDistanceMath {
|
||||
private TeDistanceMath() {}
|
||||
|
||||
public static double distSqToSection(double camX, double camY, double camZ, int ox, int oy, int oz) {
|
||||
final double dx = axisDist(camX, ox);
|
||||
final double dy = axisDist(camY, oy);
|
||||
final double dz = axisDist(camZ, oz);
|
||||
return dx * dx + dy * dy + dz * dz;
|
||||
}
|
||||
|
||||
private static double axisDist(double cam, int min) {
|
||||
if (cam < min) return min - cam;
|
||||
final double max = min + 16;
|
||||
if (cam > max) return cam - max;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.gtnewhorizons.angelica.rendering.celeritas;
|
||||
|
||||
public final class TerrainDrawStats {
|
||||
private static int commandsSubmitted;
|
||||
private static int regionsDrawn;
|
||||
|
||||
private TerrainDrawStats() {
|
||||
}
|
||||
|
||||
public static void recordBatch(int commandCount) {
|
||||
commandsSubmitted += commandCount;
|
||||
regionsDrawn++;
|
||||
}
|
||||
|
||||
public static int takeCommandsSubmitted() {
|
||||
final int n = commandsSubmitted;
|
||||
commandsSubmitted = 0;
|
||||
return n;
|
||||
}
|
||||
|
||||
public static int takeRegionsDrawn() {
|
||||
final int n = regionsDrawn;
|
||||
regionsDrawn = 0;
|
||||
return n;
|
||||
}
|
||||
}
|
||||
+2
@@ -27,4 +27,6 @@ public interface IrisShaderProvider {
|
||||
|
||||
/** Block render layer overrides from shader pack */
|
||||
@Nullable Map<Block, BlockRenderLayer> getBlockTypeIds();
|
||||
|
||||
default void preSubmitShadowGraph(int frame, boolean spectator) {}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.gtnewhorizons.angelica.rendering.culling;
|
||||
|
||||
import org.joml.Matrix4fc;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
|
||||
public final class FrustumExtractor {
|
||||
|
||||
public static final int UBO_SIZE_BYTES = 160;
|
||||
public static final int PLANE_COUNT = 6;
|
||||
|
||||
private static final int PLANE_STRIDE = 16;
|
||||
private static final int CONTROL_OFFSET = 96;
|
||||
private static final int CAMERA_WORLD_OFFSET = 112;
|
||||
private static final int BATCH_OFFSET = 128;
|
||||
private static final int PYR_OFFSET = 144;
|
||||
|
||||
private FrustumExtractor() {}
|
||||
|
||||
public static ByteBuffer allocateUboByteBuffer() {
|
||||
return ByteBuffer.allocateDirect(UBO_SIZE_BYTES).order(ByteOrder.nativeOrder());
|
||||
}
|
||||
|
||||
public static void writeStd140(Matrix4fc mvp, int visibleCount, int indexPointerMask, ByteBuffer out) {
|
||||
final float r0x = mvp.m00(), r0y = mvp.m10(), r0z = mvp.m20(), r0w = mvp.m30();
|
||||
final float r1x = mvp.m01(), r1y = mvp.m11(), r1z = mvp.m21(), r1w = mvp.m31();
|
||||
final float r2x = mvp.m02(), r2y = mvp.m12(), r2z = mvp.m22(), r2w = mvp.m32();
|
||||
final float r3x = mvp.m03(), r3y = mvp.m13(), r3z = mvp.m23(), r3w = mvp.m33();
|
||||
|
||||
writePlane(out, 0 * PLANE_STRIDE, r3x + r0x, r3y + r0y, r3z + r0z, r3w + r0w);
|
||||
writePlane(out, 1 * PLANE_STRIDE, r3x - r0x, r3y - r0y, r3z - r0z, r3w - r0w);
|
||||
writePlane(out, 2 * PLANE_STRIDE, r3x + r1x, r3y + r1y, r3z + r1z, r3w + r1w);
|
||||
writePlane(out, 3 * PLANE_STRIDE, r3x - r1x, r3y - r1y, r3z - r1z, r3w - r1w);
|
||||
writePlane(out, 4 * PLANE_STRIDE, r3x + r2x, r3y + r2y, r3z + r2z, r3w + r2w);
|
||||
writePlane(out, 5 * PLANE_STRIDE, r3x - r2x, r3y - r2y, r3z - r2z, r3w - r2w);
|
||||
|
||||
out.putInt(CONTROL_OFFSET + 0, visibleCount);
|
||||
out.putInt(CONTROL_OFFSET + 4, indexPointerMask);
|
||||
out.putInt(CONTROL_OFFSET + 8, 0);
|
||||
out.putInt(CONTROL_OFFSET + 12, 0);
|
||||
out.putInt(BATCH_OFFSET, 0);
|
||||
}
|
||||
|
||||
public static void patchBatchEntryBase(int entryBase, ByteBuffer out) {
|
||||
out.putInt(BATCH_OFFSET, entryBase);
|
||||
}
|
||||
|
||||
/** Small exact integers, so the float round trip through the UBO is lossless. */
|
||||
public static void patchPrimitiveRatio(int verticesPerPrimitive, int elementsPerPrimitive, ByteBuffer out) {
|
||||
out.putFloat(PYR_OFFSET + 8, (float) verticesPerPrimitive);
|
||||
out.putFloat(PYR_OFFSET + 12, (float) elementsPerPrimitive);
|
||||
}
|
||||
|
||||
public static void patchControl(int visibleCount, int indexPointerMask, ByteBuffer out) {
|
||||
out.putInt(CONTROL_OFFSET + 0, visibleCount);
|
||||
out.putInt(CONTROL_OFFSET + 4, indexPointerMask);
|
||||
}
|
||||
|
||||
public static void patchBypassFrustum(boolean bypass, ByteBuffer out) {
|
||||
out.putInt(CONTROL_OFFSET + 8, bypass ? 1 : 0);
|
||||
}
|
||||
|
||||
public static void patchCameraWorld(float x, float y, float z, ByteBuffer out) {
|
||||
out.putFloat(CAMERA_WORLD_OFFSET + 0, x);
|
||||
out.putFloat(CAMERA_WORLD_OFFSET + 4, y);
|
||||
out.putFloat(CAMERA_WORLD_OFFSET + 8, z);
|
||||
}
|
||||
|
||||
private static void writePlane(ByteBuffer out, int offset, float a, float b, float c, float d) {
|
||||
final float invLen = 1.0f / (float) Math.sqrt(a * a + b * b + c * c);
|
||||
out.putFloat(offset + 0, a * invLen);
|
||||
out.putFloat(offset + 4, b * invLen);
|
||||
out.putFloat(offset + 8, c * invLen);
|
||||
out.putFloat(offset + 12, d * invLen);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.gtnewhorizons.angelica.rendering.culling;
|
||||
|
||||
import com.gtnewhorizons.angelica.config.GpuCullingMode;
|
||||
import com.gtnewhorizons.angelica.glsm.GLStateManager;
|
||||
import com.gtnewhorizons.angelica.glsm.RenderSystem;
|
||||
import com.gtnewhorizons.angelica.glsm.backend.BackendManager;
|
||||
import com.gtnewhorizons.angelica.glsm.backend.RenderBackend;
|
||||
import com.gtnewhorizons.angelica.rendering.celeritas.MultiDrawModeResolver;
|
||||
import me.jellysquid.mods.sodium.client.gui.options.named.MultiDrawMode;
|
||||
import org.lwjgl.opengl.ContextCapabilities;
|
||||
|
||||
public final class GpuCulling {
|
||||
|
||||
private GpuCulling() {}
|
||||
|
||||
private static final SectionMetaBuffer SECTION_META = new SectionMetaBuffer();
|
||||
|
||||
private static GpuDrivenChunkCuller culler;
|
||||
|
||||
private static volatile GpuCullingMode activeMode = GpuCullingMode.CPU_ONLY;
|
||||
|
||||
public static GpuCullingMode mode() {
|
||||
return activeMode;
|
||||
}
|
||||
|
||||
public static void setMode(GpuCullingMode mode) {
|
||||
activeMode = mode;
|
||||
}
|
||||
|
||||
public enum Availability {
|
||||
AVAILABLE,
|
||||
NO_BACKEND_COMPUTE,
|
||||
MULTI_DRAW_NOT_INDIRECT,
|
||||
NO_GL42,
|
||||
NO_SSBO,
|
||||
NO_MULTI_DRAW_INDIRECT
|
||||
}
|
||||
|
||||
public static Availability availability() {
|
||||
final RenderBackend backend = BackendManager.RENDER_BACKEND;
|
||||
if (!backend.supportsGpuDrivenCulling()) return Availability.NO_BACKEND_COMPUTE;
|
||||
if (MultiDrawModeResolver.resolve() != MultiDrawMode.INDIRECT) return Availability.MULTI_DRAW_NOT_INDIRECT;
|
||||
|
||||
if (backend.isSDLGPU()) return Availability.AVAILABLE;
|
||||
|
||||
final ContextCapabilities caps = GLStateManager.capabilities;
|
||||
if (caps == null || !caps.OpenGL42) return Availability.NO_GL42;
|
||||
if (!RenderSystem.supportsSSBO()) return Availability.NO_SSBO;
|
||||
if (!RenderSystem.supportsMultiDrawIndirect()) return Availability.NO_MULTI_DRAW_INDIRECT;
|
||||
return Availability.AVAILABLE;
|
||||
}
|
||||
|
||||
public static boolean isAvailable() {
|
||||
return availability() == Availability.AVAILABLE;
|
||||
}
|
||||
|
||||
public static SectionMetaBuffer sectionMeta() {
|
||||
return SECTION_META;
|
||||
}
|
||||
|
||||
public static GpuDrivenChunkCuller culler() {
|
||||
if (culler == null) culler = new GpuDrivenChunkCuller();
|
||||
return culler;
|
||||
}
|
||||
|
||||
public static void onWorldUnload() {
|
||||
SECTION_META.reset();
|
||||
}
|
||||
|
||||
public static void shutdown() {
|
||||
if (culler != null) {
|
||||
culler.shutdown();
|
||||
culler = null;
|
||||
}
|
||||
SECTION_META.shutdown();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package com.gtnewhorizons.angelica.rendering.culling;
|
||||
|
||||
import com.gtnewhorizons.angelica.glsm.GLStateManager;
|
||||
import com.gtnewhorizons.angelica.glsm.RenderSystem;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.embeddedt.embeddium.impl.gl.shader.GlProgram;
|
||||
import org.embeddedt.embeddium.impl.gl.shader.GlShader;
|
||||
import org.embeddedt.embeddium.impl.gl.shader.ShaderConstants;
|
||||
import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
|
||||
import org.embeddedt.embeddium.impl.render.shader.ShaderLoader;
|
||||
import org.lwjgl.opengl.GL15;
|
||||
import org.lwjgl.opengl.GL31;
|
||||
import org.lwjgl.opengl.GL42;
|
||||
import org.lwjgl.opengl.GL43;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
|
||||
public final class GpuDrivenChunkCuller {
|
||||
private static final Logger LOG = LogManager.getLogger("Angelica-Culling");
|
||||
private static final String COMPUTE_SHADER_RESOURCE = "angelica:culling/chunk_cull.csh";
|
||||
|
||||
public static final int VISIBLE_ENTRY_BYTES = 8; // uvec2 per visible section
|
||||
static final int INDIRECT_COMMAND_BYTES = 20; // count, instCount, firstIdx, baseVtx, baseInst
|
||||
static final int FACINGS_PER_SECTION = 7;
|
||||
static final int LOCAL_SIZE_X = 64;
|
||||
private static final int INITIAL_META_SECTIONS = 4096;
|
||||
|
||||
static final int VISIBLE_SSBO_BINDING = 0;
|
||||
static final int META_SSBO_BINDING = 1;
|
||||
static final int INDIRECT_SSBO_BINDING = 2;
|
||||
static final int FRUSTUM_UBO_BINDING = 0;
|
||||
|
||||
private boolean ready;
|
||||
private boolean disabled;
|
||||
|
||||
private GlProgram<Void> program;
|
||||
private int metaSsboGlId;
|
||||
private int frustumUboGlId;
|
||||
|
||||
private int metaCapacityBytes;
|
||||
|
||||
public boolean ensureReady() {
|
||||
if (ready) return true;
|
||||
if (disabled) return false;
|
||||
if (!RenderSystem.supportsCompute()) {
|
||||
disabled = true;
|
||||
LOG.info("GpuDrivenChunkCuller disabled: GL_ARB_compute_shader not supported");
|
||||
return false;
|
||||
}
|
||||
final GlShader cs = ShaderLoader.loadShader(ShaderType.COMPUTE, COMPUTE_SHADER_RESOURCE, ShaderConstants.EMPTY);
|
||||
try {
|
||||
program = GlProgram.builder("chunk_cull").attachShader(cs).link(ctx -> null);
|
||||
} finally {
|
||||
cs.delete();
|
||||
}
|
||||
metaSsboGlId = GLStateManager.glGenBuffers();
|
||||
frustumUboGlId = GLStateManager.glGenBuffers();
|
||||
|
||||
GLStateManager.glBindBuffer(GL31.GL_UNIFORM_BUFFER, frustumUboGlId);
|
||||
GLStateManager.glBufferData(GL31.GL_UNIFORM_BUFFER, FrustumExtractor.UBO_SIZE_BYTES, GL15.GL_STREAM_DRAW);
|
||||
|
||||
metaCapacityBytes = SectionMetaBuffer.BYTES_PER_SECTION * INITIAL_META_SECTIONS;
|
||||
GLStateManager.glBindBuffer(GL43.GL_SHADER_STORAGE_BUFFER, metaSsboGlId);
|
||||
GLStateManager.glBufferData(GL43.GL_SHADER_STORAGE_BUFFER, ByteBuffer.allocateDirect(metaCapacityBytes).order(ByteOrder.nativeOrder()), GL15.GL_DYNAMIC_DRAW);
|
||||
|
||||
ready = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean uploadSectionMeta(ByteBuffer metaBytes) {
|
||||
if (!ready || metaBytes == null || metaBytes.remaining() == 0) return false;
|
||||
final int needed = metaBytes.remaining();
|
||||
GLStateManager.glBindBuffer(GL43.GL_SHADER_STORAGE_BUFFER, metaSsboGlId);
|
||||
if (needed > metaCapacityBytes) {
|
||||
final int newCap = Math.max(needed, Math.max(metaCapacityBytes * 2, SectionMetaBuffer.BYTES_PER_SECTION * INITIAL_META_SECTIONS));
|
||||
GLStateManager.glBufferData(GL43.GL_SHADER_STORAGE_BUFFER, newCap, GL15.GL_DYNAMIC_DRAW);
|
||||
metaCapacityBytes = newCap;
|
||||
}
|
||||
GLStateManager.glBufferSubData(GL43.GL_SHADER_STORAGE_BUFFER, 0L, metaBytes);
|
||||
return true;
|
||||
}
|
||||
|
||||
public void uploadFrustum(ByteBuffer frustumUboBytes) {
|
||||
if (!ready || frustumUboBytes == null) return;
|
||||
GLStateManager.glBindBuffer(GL31.GL_UNIFORM_BUFFER, frustumUboGlId);
|
||||
GLStateManager.glBufferSubData(GL31.GL_UNIFORM_BUFFER, 0L, frustumUboBytes);
|
||||
}
|
||||
|
||||
public void dispatch(int visibleSsboGlId, int indirectSsboGlId, int visibleCount) {
|
||||
if (!ready || visibleCount <= 0) return;
|
||||
final int previousProgram = GLStateManager.getActiveProgram();
|
||||
final int prevSsbo0 = RenderSystem.getIndexedBufferBinding(GL43.GL_SHADER_STORAGE_BUFFER, VISIBLE_SSBO_BINDING);
|
||||
final int prevSsbo1 = RenderSystem.getIndexedBufferBinding(GL43.GL_SHADER_STORAGE_BUFFER, META_SSBO_BINDING);
|
||||
final int prevSsbo2 = RenderSystem.getIndexedBufferBinding(GL43.GL_SHADER_STORAGE_BUFFER, INDIRECT_SSBO_BINDING);
|
||||
final int prevUbo = RenderSystem.getIndexedBufferBinding(GL31.GL_UNIFORM_BUFFER, FRUSTUM_UBO_BINDING);
|
||||
GLStateManager.glUseProgram(program.handle());
|
||||
RenderSystem.bindBufferBase(GL43.GL_SHADER_STORAGE_BUFFER, VISIBLE_SSBO_BINDING, visibleSsboGlId);
|
||||
RenderSystem.bindBufferBase(GL43.GL_SHADER_STORAGE_BUFFER, META_SSBO_BINDING, metaSsboGlId);
|
||||
RenderSystem.bindBufferBase(GL43.GL_SHADER_STORAGE_BUFFER, INDIRECT_SSBO_BINDING, indirectSsboGlId);
|
||||
RenderSystem.bindBufferBase(GL31.GL_UNIFORM_BUFFER, FRUSTUM_UBO_BINDING, frustumUboGlId);
|
||||
|
||||
final int groups = (visibleCount + LOCAL_SIZE_X - 1) / LOCAL_SIZE_X;
|
||||
GLStateManager.glDispatchCompute(groups, 1, 1);
|
||||
GLStateManager.glMemoryBarrier(GL43.GL_SHADER_STORAGE_BARRIER_BIT | GL42.GL_COMMAND_BARRIER_BIT);
|
||||
|
||||
RenderSystem.bindBufferBase(GL43.GL_SHADER_STORAGE_BUFFER, VISIBLE_SSBO_BINDING, prevSsbo0);
|
||||
RenderSystem.bindBufferBase(GL43.GL_SHADER_STORAGE_BUFFER, META_SSBO_BINDING, prevSsbo1);
|
||||
RenderSystem.bindBufferBase(GL43.GL_SHADER_STORAGE_BUFFER, INDIRECT_SSBO_BINDING, prevSsbo2);
|
||||
RenderSystem.bindBufferBase(GL31.GL_UNIFORM_BUFFER, FRUSTUM_UBO_BINDING, prevUbo);
|
||||
GLStateManager.glUseProgram(previousProgram);
|
||||
}
|
||||
|
||||
public synchronized void shutdown() {
|
||||
if (program != null) { program.delete(); program = null; }
|
||||
if (metaSsboGlId != 0) { GLStateManager.glDeleteBuffers(metaSsboGlId); metaSsboGlId = 0; }
|
||||
if (frustumUboGlId != 0) { GLStateManager.glDeleteBuffers(frustumUboGlId); frustumUboGlId = 0; }
|
||||
ready = false;
|
||||
disabled = true;
|
||||
}
|
||||
}
|
||||
+382
@@ -0,0 +1,382 @@
|
||||
package com.gtnewhorizons.angelica.rendering.culling;
|
||||
|
||||
import com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities;
|
||||
import com.gtnewhorizons.angelica.glsm.GLStateManager;
|
||||
import com.gtnewhorizons.angelica.glsm.backend.BackendManager;
|
||||
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
|
||||
import it.unimi.dsi.fastutil.objects.Reference2LongOpenHashMap;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.embeddedt.embeddium.impl.gl.device.CommandList;
|
||||
import org.embeddedt.embeddium.impl.gl.device.DrawCommandList;
|
||||
import org.embeddedt.embeddium.impl.gl.tessellation.GlPrimitiveType;
|
||||
import org.embeddedt.embeddium.impl.gl.tessellation.GlTessellation;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.multidraw.DrawCommandSink;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.multidraw.IndirectMultiDrawEmitter;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.multidraw.MultiDrawEmitter;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
import org.lwjgl.opengl.GL15;
|
||||
import org.lwjgl.opengl.GL40;
|
||||
import org.lwjgl.opengl.GL43;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
|
||||
public final class GpuIndirectMultiDrawEmitter implements MultiDrawEmitter {
|
||||
|
||||
private static final Logger LOG = LogManager.getLogger("Angelica-Culling");
|
||||
|
||||
private static final int ENTRY_BYTES = GpuDrivenChunkCuller.VISIBLE_ENTRY_BYTES;
|
||||
|
||||
private final GpuDrivenChunkCuller culler;
|
||||
private final SectionMetaBuffer sectionMeta;
|
||||
|
||||
private ByteBuffer visibleStaging;
|
||||
private ByteBuffer visibleStagingView;
|
||||
private int stagingCapacityEntries;
|
||||
|
||||
private int visibleSsboGlId;
|
||||
private int indirectSsboGlId;
|
||||
private int gpuCapacityEntries;
|
||||
|
||||
private static final class PassState {
|
||||
int entryBase;
|
||||
int entryCount;
|
||||
int indexPointerMask;
|
||||
int maxElementCount;
|
||||
boolean dispatched;
|
||||
final Reference2LongOpenHashMap<RenderRegion> regionRanges = new Reference2LongOpenHashMap<>();
|
||||
final Reference2LongOpenHashMap<RenderRegion> regionEntryRanges = new Reference2LongOpenHashMap<>();
|
||||
|
||||
PassState() {
|
||||
regionRanges.defaultReturnValue(-1L);
|
||||
regionEntryRanges.defaultReturnValue(-1L);
|
||||
}
|
||||
|
||||
void reset(int mask, int base) {
|
||||
entryBase = base;
|
||||
entryCount = 0;
|
||||
indexPointerMask = mask;
|
||||
maxElementCount = 0;
|
||||
dispatched = false;
|
||||
regionRanges.clear();
|
||||
regionEntryRanges.clear();
|
||||
}
|
||||
}
|
||||
|
||||
private final PassState primaryPass = new PassState();
|
||||
private final PassState secondPass = new PassState();
|
||||
private PassState buildPass = primaryPass;
|
||||
private PassState current = primaryPass;
|
||||
private boolean secondPrepared;
|
||||
private int totalAppendedEntries;
|
||||
@Getter private boolean computeActiveThisPass;
|
||||
|
||||
private int currentDrawStart;
|
||||
private int currentDrawCount;
|
||||
private int currentEntryStart;
|
||||
private int currentEntryCount;
|
||||
private RenderRegion currentRegion;
|
||||
|
||||
@Setter private ByteBuffer frustumUboBytes;
|
||||
|
||||
private IndirectMultiDrawEmitter cpuFallback;
|
||||
|
||||
public static long sectionMetaBytes;
|
||||
|
||||
private static int commandsSubmitted;
|
||||
private static int regionsDrawn;
|
||||
private static int maxRegionCommands;
|
||||
public static int commandsSubmitted() { return commandsSubmitted; }
|
||||
public static int takeRegionsDrawn() { final int n = regionsDrawn; regionsDrawn = 0; return n; }
|
||||
public static int takeMaxRegionCommands() { final int n = maxRegionCommands; maxRegionCommands = 0; return n; }
|
||||
|
||||
private final SectionMetaBuffer.Sink uploadSectionMetaSink;
|
||||
|
||||
public GpuIndirectMultiDrawEmitter(GpuDrivenChunkCuller culler, SectionMetaBuffer sectionMeta) {
|
||||
this.culler = culler;
|
||||
this.sectionMeta = sectionMeta;
|
||||
this.uploadSectionMetaSink = buf -> {
|
||||
final int bytes = buf.remaining();
|
||||
if (!culler.uploadSectionMeta(buf)) return false;
|
||||
if (Tracy.ENABLED) sectionMetaBytes += bytes;
|
||||
return true;
|
||||
};
|
||||
}
|
||||
|
||||
public void beginCullPass(int indexPointerMask) {
|
||||
this.computeActiveThisPass = GpuCulling.mode().computeEnabled();
|
||||
this.totalAppendedEntries = 0;
|
||||
this.secondPrepared = false;
|
||||
primaryPass.reset(indexPointerMask, 0);
|
||||
this.buildPass = primaryPass;
|
||||
this.current = primaryPass;
|
||||
this.currentDrawStart = 0;
|
||||
this.currentDrawCount = 0;
|
||||
this.currentEntryStart = 0;
|
||||
this.currentEntryCount = 0;
|
||||
if (computeActiveThisPass && cpuFallback != null) {
|
||||
cpuFallback.getCommandSink().clear();
|
||||
}
|
||||
}
|
||||
|
||||
private IndirectMultiDrawEmitter cpuFallback() {
|
||||
if (cpuFallback == null) cpuFallback = new IndirectMultiDrawEmitter();
|
||||
return cpuFallback;
|
||||
}
|
||||
|
||||
public void beginCombinedPasses(int firstMask, int secondMask) {
|
||||
beginCullPass(firstMask);
|
||||
secondPass.reset(secondMask, 0);
|
||||
}
|
||||
|
||||
public void startSecondPass() {
|
||||
primaryPass.entryCount = totalAppendedEntries - primaryPass.entryBase;
|
||||
secondPass.entryBase = totalAppendedEntries;
|
||||
this.buildPass = secondPass;
|
||||
this.current = secondPass;
|
||||
}
|
||||
|
||||
public void finishCombinedBuild() {
|
||||
secondPass.entryCount = totalAppendedEntries - secondPass.entryBase;
|
||||
this.secondPrepared = true;
|
||||
this.buildPass = primaryPass;
|
||||
this.current = primaryPass;
|
||||
}
|
||||
|
||||
public boolean selectPreparedSecondPass() {
|
||||
if (!secondPrepared || !computeActiveThisPass) return false;
|
||||
this.current = secondPass;
|
||||
this.currentDrawStart = 0;
|
||||
this.currentDrawCount = 0;
|
||||
this.currentEntryStart = 0;
|
||||
this.currentEntryCount = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
public void reserveSections(int count) {
|
||||
if (count > 0) ensureStagingCapacity(totalAppendedEntries + count);
|
||||
}
|
||||
|
||||
public int appendSection(int slot, int facingMask, int outputBase) {
|
||||
if ((outputBase & ~0x00FFFFFF) != 0) {
|
||||
throw new IllegalStateException("packed outputBase overflow: " + outputBase + " (max " + 0x00FFFFFF + ")");
|
||||
}
|
||||
if (totalAppendedEntries >= stagingCapacityEntries) ensureStagingCapacity(totalAppendedEntries + 1);
|
||||
final int idx = totalAppendedEntries;
|
||||
final int off = idx * ENTRY_BYTES;
|
||||
visibleStaging.putInt(off + 0, slot);
|
||||
visibleStaging.putInt(off + 4, (outputBase << 8) | (facingMask & 0xFF));
|
||||
totalAppendedEntries = idx + 1;
|
||||
buildPass.entryCount = totalAppendedEntries - buildPass.entryBase;
|
||||
visibleStagingView.limit(totalAppendedEntries * ENTRY_BYTES);
|
||||
return idx;
|
||||
}
|
||||
|
||||
public void recordRegion(RenderRegion region, int drawStart, int drawCount, int entryStart, int entryCount, int maxElementCount) {
|
||||
if (drawCount <= 0) return;
|
||||
buildPass.regionRanges.put(region, (((long) drawStart) << 32) | (drawCount & 0xFFFFFFFFL));
|
||||
buildPass.regionEntryRanges.put(region, (((long) entryStart) << 32) | (entryCount & 0xFFFFFFFFL));
|
||||
if (maxElementCount > buildPass.maxElementCount) buildPass.maxElementCount = maxElementCount;
|
||||
}
|
||||
|
||||
public void prepareRegion(RenderRegion region) {
|
||||
currentRegion = region;
|
||||
final long packed = current.regionRanges.getLong(region);
|
||||
if (packed < 0L) {
|
||||
currentDrawStart = 0;
|
||||
currentDrawCount = 0;
|
||||
} else {
|
||||
currentDrawStart = (int) (packed >>> 32);
|
||||
currentDrawCount = (int) (packed & 0xFFFFFFFFL);
|
||||
}
|
||||
final long entryPacked = current.regionEntryRanges.getLong(region);
|
||||
if (entryPacked < 0L) {
|
||||
currentEntryStart = 0;
|
||||
currentEntryCount = 0;
|
||||
} else {
|
||||
currentEntryStart = (int) (entryPacked >>> 32);
|
||||
currentEntryCount = (int) (entryPacked & 0xFFFFFFFFL);
|
||||
}
|
||||
}
|
||||
|
||||
public void syncSectionMetaIfDirty() {
|
||||
culler.ensureReady();
|
||||
sectionMeta.syncIfDirty(uploadSectionMetaSink);
|
||||
}
|
||||
|
||||
public void endPass() {
|
||||
currentDrawStart = 0;
|
||||
currentDrawCount = 0;
|
||||
currentEntryStart = 0;
|
||||
currentEntryCount = 0;
|
||||
if (current == secondPass) secondPrepared = false;
|
||||
}
|
||||
|
||||
public void dispatchPreparedPasses() {
|
||||
if (!computeActiveThisPass || totalAppendedEntries == 0) return;
|
||||
if (!needsDispatch(primaryPass) && (!secondPrepared || !needsDispatch(secondPass))) return;
|
||||
if (!culler.ensureReady()) return;
|
||||
if (frustumUboBytes == null) {
|
||||
LOG.warn("GpuIndirectMultiDrawEmitter: frustum UBO not set before dispatch; skipping cull");
|
||||
return;
|
||||
}
|
||||
|
||||
ensureGpuBuffers(totalAppendedEntries);
|
||||
visibleStagingView.position(0).limit(totalAppendedEntries * ENTRY_BYTES);
|
||||
GLStateManager.glBindBuffer(GL43.GL_SHADER_STORAGE_BUFFER, visibleSsboGlId);
|
||||
GLStateManager.glBufferSubData(GL43.GL_SHADER_STORAGE_BUFFER, 0L, visibleStagingView);
|
||||
|
||||
BackendManager.RENDER_BACKEND.beginComputeDispatchBatch();
|
||||
try {
|
||||
dispatchPass(primaryPass);
|
||||
if (secondPrepared) dispatchPass(secondPass);
|
||||
} finally {
|
||||
BackendManager.RENDER_BACKEND.endComputeDispatchBatch();
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean needsDispatch(PassState r) {
|
||||
return !r.dispatched && r.entryCount > 0;
|
||||
}
|
||||
|
||||
private void dispatchPass(PassState r) {
|
||||
if (!needsDispatch(r)) return;
|
||||
FrustumExtractor.patchControl(r.entryCount, r.indexPointerMask, frustumUboBytes);
|
||||
FrustumExtractor.patchBatchEntryBase(r.entryBase, frustumUboBytes);
|
||||
culler.uploadFrustum(frustumUboBytes);
|
||||
culler.dispatch(visibleSsboGlId, indirectSsboGlId, r.entryCount);
|
||||
r.dispatched = true;
|
||||
}
|
||||
|
||||
private void ensureGpuBuffers(int maxVisible) {
|
||||
if (visibleSsboGlId == 0) visibleSsboGlId = GLStateManager.glGenBuffers();
|
||||
if (indirectSsboGlId == 0) indirectSsboGlId = GLStateManager.glGenBuffers();
|
||||
if (maxVisible <= gpuCapacityEntries) return;
|
||||
final int newCap = Math.max(maxVisible, Math.max(gpuCapacityEntries * 2, 64));
|
||||
GLStateManager.glBindBuffer(GL43.GL_SHADER_STORAGE_BUFFER, visibleSsboGlId);
|
||||
GLStateManager.glBufferData(GL43.GL_SHADER_STORAGE_BUFFER, (long) newCap * ENTRY_BYTES, GL15.GL_STREAM_DRAW);
|
||||
GLStateManager.glBindBuffer(GL43.GL_SHADER_STORAGE_BUFFER, indirectSsboGlId);
|
||||
final int indirectBytes = newCap * GpuDrivenChunkCuller.FACINGS_PER_SECTION * GpuDrivenChunkCuller.INDIRECT_COMMAND_BYTES;
|
||||
GLStateManager.glBufferData(GL43.GL_SHADER_STORAGE_BUFFER, ByteBuffer.allocateDirect(indirectBytes).order(ByteOrder.nativeOrder()), GL15.GL_STREAM_DRAW);
|
||||
gpuCapacityEntries = newCap;
|
||||
}
|
||||
|
||||
private void ensureStagingCapacity(int needed) {
|
||||
if (visibleStaging != null && needed <= stagingCapacityEntries) return;
|
||||
final int newCap = Math.max(needed, Math.max(stagingCapacityEntries * 2, 64));
|
||||
final ByteBuffer next = MemoryUtilities.memAlloc(newCap * ENTRY_BYTES).order(ByteOrder.nativeOrder());
|
||||
if (visibleStaging != null) {
|
||||
visibleStaging.position(0).limit(totalAppendedEntries * ENTRY_BYTES);
|
||||
next.put(visibleStaging);
|
||||
MemoryUtilities.memFree(visibleStaging);
|
||||
}
|
||||
next.position(0);
|
||||
next.limit(newCap * ENTRY_BYTES);
|
||||
visibleStaging = next;
|
||||
visibleStagingView = visibleStaging.duplicate().order(ByteOrder.nativeOrder());
|
||||
stagingCapacityEntries = newCap;
|
||||
}
|
||||
|
||||
private final DrawCommandSink computeSink = new DrawCommandSink() {
|
||||
@Override
|
||||
public void clear() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return currentDrawCount;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getIndexBufferSize() {
|
||||
return current.maxElementCount;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void push(int baseVertex, int elementCount, long indexOffset) {
|
||||
}
|
||||
};
|
||||
|
||||
@Override
|
||||
public DrawCommandSink getCommandSink() {
|
||||
return computeActiveThisPass ? computeSink : cpuFallback().getCommandSink();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean batchesWholePass() {
|
||||
return !computeActiveThisPass && cpuFallback().batchesWholePass();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beginPass(CommandList commandList, int sectionCount) {
|
||||
if (!computeActiveThisPass) cpuFallback().beginPass(commandList, sectionCount);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void finishAssembly(CommandList commandList) {
|
||||
if (!computeActiveThisPass) cpuFallback().finishAssembly(commandList);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void selectDrawRange(int firstCommand, int commandCount) {
|
||||
if (!computeActiveThisPass) cpuFallback().selectDrawRange(firstCommand, commandCount);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getPendingCommandCount() {
|
||||
return computeActiveThisPass ? currentDrawCount : cpuFallback().getPendingCommandCount();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPassFinished(CommandList commandList) {
|
||||
if (!computeActiveThisPass) cpuFallback().onPassFinished(commandList);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void executeBatch(CommandList commandList, GlTessellation tessellation, GlPrimitiveType primitiveType) {
|
||||
if (!computeActiveThisPass) {
|
||||
cpuFallback().executeBatch(commandList, tessellation, primitiveType);
|
||||
return;
|
||||
}
|
||||
if (currentDrawCount == 0) return;
|
||||
dispatchPreparedPasses();
|
||||
if (!current.dispatched) return;
|
||||
|
||||
if (Tracy.ENABLED) {
|
||||
commandsSubmitted += currentDrawCount;
|
||||
regionsDrawn++;
|
||||
if (currentDrawCount > maxRegionCommands) maxRegionCommands = currentDrawCount;
|
||||
}
|
||||
|
||||
final long offsetBytes = (long) currentDrawStart * GpuDrivenChunkCuller.INDIRECT_COMMAND_BYTES;
|
||||
GLStateManager.glBindBuffer(GL40.GL_DRAW_INDIRECT_BUFFER, indirectSsboGlId);
|
||||
try (DrawCommandList ignored = commandList.beginTessellating(tessellation)) {
|
||||
GLStateManager.glMultiDrawElementsIndirect(primitiveType.getId(), GL11.GL_UNSIGNED_INT, offsetBytes, currentDrawCount, 0);
|
||||
}
|
||||
GLStateManager.glBindBuffer(GL40.GL_DRAW_INDIRECT_BUFFER, 0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete() {
|
||||
if (visibleStaging != null) {
|
||||
MemoryUtilities.memFree(visibleStaging);
|
||||
visibleStaging = null;
|
||||
visibleStagingView = null;
|
||||
stagingCapacityEntries = 0;
|
||||
}
|
||||
if (visibleSsboGlId != 0) { GLStateManager.glDeleteBuffers(visibleSsboGlId); visibleSsboGlId = 0; }
|
||||
if (indirectSsboGlId != 0) { GLStateManager.glDeleteBuffers(indirectSsboGlId); indirectSsboGlId = 0; }
|
||||
gpuCapacityEntries = 0;
|
||||
currentRegion = null;
|
||||
frustumUboBytes = null;
|
||||
primaryPass.regionRanges.clear();
|
||||
primaryPass.regionEntryRanges.clear();
|
||||
secondPass.regionRanges.clear();
|
||||
secondPass.regionEntryRanges.clear();
|
||||
if (cpuFallback != null) cpuFallback.delete();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.gtnewhorizons.angelica.rendering.culling;
|
||||
|
||||
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
|
||||
|
||||
/** Stable index assignment for TerrainRenderPass instances. Keyed by pass name. */
|
||||
public final class RenderPassIndex {
|
||||
public static final int MAX_PASSES = 8;
|
||||
|
||||
private static final Object2IntOpenHashMap<String> INDICES = new Object2IntOpenHashMap<>(MAX_PASSES);
|
||||
static { INDICES.defaultReturnValue(-1); }
|
||||
|
||||
private static int nextIndex;
|
||||
|
||||
private RenderPassIndex() {}
|
||||
|
||||
public static synchronized int indexOf(TerrainRenderPass pass) {
|
||||
final String name = pass.name();
|
||||
final int existing = INDICES.getInt(name);
|
||||
if (existing >= 0) return existing;
|
||||
if (nextIndex >= MAX_PASSES) {
|
||||
throw new IllegalStateException("RenderPassIndex: more than " + MAX_PASSES + " distinct TerrainRenderPass names; bump MAX_PASSES and the pass-bit budget in SectionMetaBuffer.sectionKey. Registered: " + INDICES);
|
||||
}
|
||||
final int assigned = nextIndex++;
|
||||
INDICES.put(name, assigned);
|
||||
return assigned;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
package com.gtnewhorizons.angelica.rendering.culling;
|
||||
|
||||
import com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities;
|
||||
import it.unimi.dsi.fastutil.ints.IntArrayList;
|
||||
import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.ChunkPrimitiveType;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataUnsafe;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
|
||||
public final class SectionMetaBuffer {
|
||||
private static final int INITIAL_CAPACITY = 16384;
|
||||
public static final int BYTES_PER_SECTION = 64;
|
||||
public static final int FACING_COUNT = 7;
|
||||
public static final int POST_COUNT = FACING_COUNT + 1;
|
||||
|
||||
public static final int OFFSET_SLICE_MASK = 12;
|
||||
public static final int OFFSET_POSTS = 16;
|
||||
public static final int OFFSET_FIRST_INDEX_BASE = 48;
|
||||
|
||||
private final Long2IntOpenHashMap keyToSlot = new Long2IntOpenHashMap();
|
||||
private final IntArrayList freeSlots = new IntArrayList();
|
||||
private ByteBuffer mirror;
|
||||
private ByteBuffer mirrorView;
|
||||
private int capacity;
|
||||
private int highWaterMark;
|
||||
private boolean dirty;
|
||||
|
||||
public SectionMetaBuffer() {
|
||||
this.keyToSlot.defaultReturnValue(-1);
|
||||
}
|
||||
|
||||
private static long sectionKey(int passIndex, int sectionOriginX, int sectionOriginY, int sectionOriginZ) {
|
||||
final long p = ((long) passIndex) & 0x7L;
|
||||
final long sx = ((long)(sectionOriginX >> 4)) & 0x3FFFFFL;
|
||||
final long sy = ((long)(sectionOriginY >> 4)) & 0xFFFFL;
|
||||
final long sz = ((long)(sectionOriginZ >> 4)) & 0x7FFFFFL;
|
||||
return (p << 61) | (sx << 39) | (sy << 23) | sz;
|
||||
}
|
||||
|
||||
public synchronized int update(int passIndex, int regionOriginX, int regionOriginY, int regionOriginZ, int localSectionIndex,
|
||||
long dataPtr, SectionRenderDataUnsafe.Strategy layout, ChunkPrimitiveType primitiveType) {
|
||||
if (dataPtr == 0L) return -1;
|
||||
final int sectionOriginX = regionOriginX + (((localSectionIndex >> 5) & 0x07) << 4);
|
||||
final int sectionOriginY = regionOriginY + (((localSectionIndex ) & 0x03) << 4);
|
||||
final int sectionOriginZ = regionOriginZ + (((localSectionIndex >> 2) & 0x07) << 4);
|
||||
final long key = sectionKey(passIndex, sectionOriginX, sectionOriginY, sectionOriginZ);
|
||||
int slot = keyToSlot.get(key);
|
||||
if (slot < 0) {
|
||||
slot = allocateSlot();
|
||||
keyToSlot.put(key, slot);
|
||||
}
|
||||
writeSlot(slot, sectionOriginX, sectionOriginY, sectionOriginZ, dataPtr, layout, primitiveType);
|
||||
dirty = true;
|
||||
return slot;
|
||||
}
|
||||
|
||||
public synchronized void remove(int passIndex, int regionOriginX, int regionOriginY, int regionOriginZ, int localSectionIndex) {
|
||||
if (mirror == null) return;
|
||||
final int sectionOriginX = regionOriginX + (((localSectionIndex >> 5) & 0x07) << 4);
|
||||
final int sectionOriginY = regionOriginY + (((localSectionIndex ) & 0x03) << 4);
|
||||
final int sectionOriginZ = regionOriginZ + (((localSectionIndex >> 2) & 0x07) << 4);
|
||||
final long key = sectionKey(passIndex, sectionOriginX, sectionOriginY, sectionOriginZ);
|
||||
final int slot = keyToSlot.remove(key);
|
||||
if (slot < 0) return;
|
||||
zeroSlot(slot);
|
||||
freeSlots.add(slot);
|
||||
dirty = true;
|
||||
}
|
||||
|
||||
private int allocateSlot() {
|
||||
if (!freeSlots.isEmpty()) {
|
||||
return freeSlots.removeInt(freeSlots.size() - 1);
|
||||
}
|
||||
if (mirror == null) {
|
||||
grow(INITIAL_CAPACITY);
|
||||
} else if (highWaterMark >= capacity) {
|
||||
grow(capacity * 2);
|
||||
}
|
||||
return highWaterMark++;
|
||||
}
|
||||
|
||||
private void grow(int newCapacity) {
|
||||
final int newSize = newCapacity * BYTES_PER_SECTION;
|
||||
final ByteBuffer next = MemoryUtilities.memAlloc(newSize).order(ByteOrder.nativeOrder());
|
||||
if (mirror != null) {
|
||||
mirror.position(0).limit(highWaterMark * BYTES_PER_SECTION);
|
||||
next.put(mirror);
|
||||
mirrorView = null;
|
||||
MemoryUtilities.memFree(mirror);
|
||||
}
|
||||
next.position(0);
|
||||
next.limit(newSize);
|
||||
mirror = next;
|
||||
mirrorView = mirror.duplicate().order(ByteOrder.nativeOrder());
|
||||
capacity = newCapacity;
|
||||
}
|
||||
|
||||
private void writeSlot(int slot, int sectionOriginX, int sectionOriginY, int sectionOriginZ, long dataPtr, SectionRenderDataUnsafe.Strategy layout, ChunkPrimitiveType primitiveType) {
|
||||
final int base = slot * BYTES_PER_SECTION;
|
||||
mirror.putInt(base + 0, sectionOriginX);
|
||||
mirror.putInt(base + 4, sectionOriginY);
|
||||
mirror.putInt(base + 8, sectionOriginZ);
|
||||
mirror.putInt(base + OFFSET_SLICE_MASK, SectionRenderDataUnsafe.getSliceMask(dataPtr));
|
||||
for (int facing = 0; facing < FACING_COUNT; facing++) {
|
||||
mirror.putInt(base + OFFSET_POSTS + facing * 4, layout.getVertexOffset(dataPtr, facing));
|
||||
}
|
||||
mirror.putInt(base + OFFSET_POSTS + FACING_COUNT * 4, layout.getRunVertexEnd(dataPtr, FACING_COUNT - 1, primitiveType));
|
||||
mirror.putInt(base + OFFSET_FIRST_INDEX_BASE, layout.getIndexOffset(dataPtr, 0) / 4);
|
||||
mirror.putInt(base + 52, 0);
|
||||
mirror.putInt(base + 56, 0);
|
||||
mirror.putInt(base + 60, 0);
|
||||
}
|
||||
|
||||
private void zeroSlot(int slot) {
|
||||
final int base = slot * BYTES_PER_SECTION;
|
||||
for (int i = 0; i < BYTES_PER_SECTION; i += 4) {
|
||||
mirror.putInt(base + i, 0);
|
||||
}
|
||||
}
|
||||
|
||||
synchronized int lookupSlot(int passIndex, int sectionOriginX, int sectionOriginY, int sectionOriginZ) {
|
||||
return keyToSlot.get(sectionKey(passIndex, sectionOriginX, sectionOriginY, sectionOriginZ));
|
||||
}
|
||||
|
||||
synchronized boolean isDirty() { return dirty; }
|
||||
synchronized void clearDirty() { dirty = false; }
|
||||
synchronized int getCapacity() { return capacity; }
|
||||
public synchronized int getHighWaterMark() { return highWaterMark; }
|
||||
|
||||
public synchronized ByteBuffer getMirrorForReadOnly() { return mirrorView; }
|
||||
|
||||
@FunctionalInterface
|
||||
public interface Sink {
|
||||
boolean accept(ByteBuffer mirror);
|
||||
}
|
||||
|
||||
public synchronized boolean syncIfDirty(Sink sink) {
|
||||
if (!dirty) return false;
|
||||
if (mirror == null || highWaterMark == 0 || mirrorView == null) {
|
||||
dirty = false;
|
||||
return false;
|
||||
}
|
||||
final int activeBytes = highWaterMark * BYTES_PER_SECTION;
|
||||
mirrorView.position(0).limit(activeBytes);
|
||||
if (!sink.accept(mirrorView)) return false;
|
||||
dirty = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
public synchronized void reset() {
|
||||
mirrorView = null;
|
||||
if (mirror != null) {
|
||||
MemoryUtilities.memFree(mirror);
|
||||
mirror = null;
|
||||
}
|
||||
keyToSlot.clear();
|
||||
freeSlots.clear();
|
||||
capacity = 0;
|
||||
highWaterMark = 0;
|
||||
dirty = false;
|
||||
}
|
||||
|
||||
public synchronized void shutdown() { reset(); }
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
package com.gtnewhorizons.angelica.rendering.tesr;
|
||||
|
||||
import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator;
|
||||
import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager;
|
||||
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
|
||||
import com.gtnewhorizons.angelica.api.tesr.TesrMeshBuilder;
|
||||
import com.gtnewhorizons.angelica.api.tesr.TesrMeshProvider;
|
||||
import com.gtnewhorizons.angelica.api.tesr.TesrMeshSink;
|
||||
import com.gtnewhorizons.angelica.api.tesr.TesrMaterial;
|
||||
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
|
||||
import com.gtnewhorizons.angelica.rendering.tesr.TemplateBuffer;
|
||||
import com.gtnewhorizons.angelica.rendering.tesr.TesrBatchRenderer;
|
||||
import com.gtnewhorizons.angelica.rendering.tesr.VertexTransform;
|
||||
import it.unimi.dsi.fastutil.objects.ObjectIterator;
|
||||
import it.unimi.dsi.fastutil.objects.Reference2ObjectMap;
|
||||
import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap;
|
||||
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
|
||||
import net.minecraft.client.renderer.Tessellator;
|
||||
import net.minecraft.tileentity.TileEntity;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import net.minecraftforge.client.event.TextureStitchEvent;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.LongSupplier;
|
||||
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0;
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memFree;
|
||||
|
||||
public final class AngelicaTesrMeshCache {
|
||||
|
||||
public static final long LRU_TIMEOUT_MS = 60_000L;
|
||||
|
||||
public static final AngelicaTesrMeshCache INSTANCE = new AngelicaTesrMeshCache(new GtnhMeshBackend(), System::currentTimeMillis);
|
||||
private static final Logger LOG = LogManager.getLogger("AngelicaTesrMeshCache");
|
||||
|
||||
public static long cacheHits;
|
||||
public static long cacheMisses;
|
||||
|
||||
private final MeshBackend backend;
|
||||
private final LongSupplier clock;
|
||||
private final ReplaySink replaySink;
|
||||
private final Reference2ObjectOpenHashMap<Object, Entry> entries = new Reference2ObjectOpenHashMap<>();
|
||||
private boolean warnedEmptyCapture;
|
||||
|
||||
|
||||
public interface MeshBackend {
|
||||
Tessellator beginCapture(VertexFormat format);
|
||||
|
||||
TemplateBuffer endCaptureToTemplate();
|
||||
}
|
||||
|
||||
public interface ReplaySink {
|
||||
void queue(TemplateBuffer template, ResourceLocation texture, TesrMaterial material);
|
||||
}
|
||||
|
||||
private static final class Bucket {
|
||||
final ResourceLocation texture;
|
||||
final TesrMaterial material;
|
||||
final TemplateBuffer template;
|
||||
|
||||
Bucket(ResourceLocation texture, TesrMaterial material, TemplateBuffer template) {
|
||||
this.texture = texture;
|
||||
this.material = material;
|
||||
this.template = template;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Entry {
|
||||
final List<Bucket> buckets = new ArrayList<>();
|
||||
long version;
|
||||
long lastUsedMs;
|
||||
}
|
||||
|
||||
private static final Tracy.ZoneId Z_TESR_CAPTURE = Tracy.zoneId("tesrCapture", Tracy.COLOR_CLIENT);
|
||||
|
||||
AngelicaTesrMeshCache(MeshBackend backend, LongSupplier clock) {
|
||||
this(backend, clock, (template, texture, material) -> TesrBatchRenderer.INSTANCE.queue(template, texture, material));
|
||||
}
|
||||
|
||||
AngelicaTesrMeshCache(MeshBackend backend, LongSupplier clock, ReplaySink replaySink) {
|
||||
this.backend = backend;
|
||||
this.clock = clock;
|
||||
this.replaySink = replaySink;
|
||||
}
|
||||
|
||||
public void renderCached(Object key, boolean dirty, TesrMeshProvider provider, TileEntity te) {
|
||||
Entry entry = entries.get(key);
|
||||
if (entry == null || dirty) {
|
||||
if (Tracy.ENABLED) cacheMisses++;
|
||||
entry = capture(key, entry, sink -> provider.angelica$build(sink, te));
|
||||
} else {
|
||||
if (Tracy.ENABLED) cacheHits++;
|
||||
}
|
||||
replay(entry);
|
||||
entry.lastUsedMs = clock.getAsLong();
|
||||
}
|
||||
|
||||
public void renderCached(Object key, TesrMeshBuilder builder) {
|
||||
Entry entry = entries.get(key);
|
||||
if (entry == null) {
|
||||
if (Tracy.ENABLED) cacheMisses++;
|
||||
entry = capture(key, null, builder);
|
||||
} else {
|
||||
if (Tracy.ENABLED) cacheHits++;
|
||||
}
|
||||
replay(entry);
|
||||
entry.lastUsedMs = clock.getAsLong();
|
||||
}
|
||||
|
||||
public void invalidate(Object key) {
|
||||
final Entry entry = entries.remove(key);
|
||||
if (entry != null) {
|
||||
entry.buckets.clear();
|
||||
}
|
||||
}
|
||||
|
||||
private Entry capture(Object key, Entry existing, TesrMeshBuilder builder) {
|
||||
if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_CAPTURE);
|
||||
try {
|
||||
return captureInner(key, existing, builder);
|
||||
} finally {
|
||||
if (Tracy.ENABLED) Tracy.endZone();
|
||||
}
|
||||
}
|
||||
|
||||
private Entry captureInner(Object key, Entry existing, TesrMeshBuilder builder) {
|
||||
Entry entry = existing;
|
||||
if (entry == null) {
|
||||
entry = new Entry();
|
||||
entries.put(key, entry);
|
||||
} else {
|
||||
entry.buckets.clear();
|
||||
}
|
||||
final CaptureSink sink = new CaptureSink(entry);
|
||||
builder.angelica$build(sink);
|
||||
sink.close();
|
||||
if (entry.buckets.isEmpty() && sink.openedAnyBucket && !warnedEmptyCapture) {
|
||||
warnedEmptyCapture = true;
|
||||
LOG.debug("Capture produced 0 vertices across all buckets for {}", key.getClass().getName());
|
||||
}
|
||||
entry.version++;
|
||||
return entry;
|
||||
}
|
||||
|
||||
private final class CaptureSink implements TesrMeshSink {
|
||||
private final Entry entry;
|
||||
private ResourceLocation openTexture;
|
||||
private TesrMaterial openMaterial;
|
||||
private boolean open;
|
||||
boolean openedAnyBucket;
|
||||
|
||||
CaptureSink(Entry entry) {
|
||||
this.entry = entry;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Tessellator angelica$bucket(VertexFormat format, ResourceLocation texture, TesrMaterial material) {
|
||||
close();
|
||||
openTexture = texture;
|
||||
openMaterial = material != null ? material : TesrMaterial.CURRENT_STATE;
|
||||
open = true;
|
||||
openedAnyBucket = true;
|
||||
return backend.beginCapture(format);
|
||||
}
|
||||
|
||||
void close() {
|
||||
if (open) {
|
||||
final TemplateBuffer template = backend.endCaptureToTemplate();
|
||||
if (template != null) {
|
||||
entry.buckets.add(new Bucket(openTexture, openMaterial, template));
|
||||
}
|
||||
open = false;
|
||||
openTexture = null;
|
||||
openMaterial = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void replay(Entry entry) {
|
||||
final List<Bucket> buckets = entry.buckets;
|
||||
for (int i = 0, n = buckets.size(); i < n; i++) {
|
||||
final Bucket b = buckets.get(i);
|
||||
replaySink.queue(b.template, b.texture, b.material);
|
||||
}
|
||||
}
|
||||
|
||||
public static final class ReloadListener {
|
||||
@SubscribeEvent
|
||||
public void onTextureStitchPost(TextureStitchEvent.Post event) {
|
||||
INSTANCE.clear();
|
||||
}
|
||||
}
|
||||
|
||||
public void tick() {
|
||||
evict(clock.getAsLong());
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
entries.clear();
|
||||
}
|
||||
|
||||
public int size() {
|
||||
return entries.size();
|
||||
}
|
||||
|
||||
void evict(long nowMs) {
|
||||
if (entries.isEmpty()) return;
|
||||
final ObjectIterator<Reference2ObjectMap.Entry<Object, Entry>> it = entries.reference2ObjectEntrySet().fastIterator();
|
||||
while (it.hasNext()) {
|
||||
final Entry entry = it.next().getValue();
|
||||
if (entry.lastUsedMs + LRU_TIMEOUT_MS < nowMs) {
|
||||
entry.buckets.clear();
|
||||
it.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
long version(Object key) {
|
||||
final Entry entry = entries.get(key);
|
||||
return entry == null ? -1 : entry.version;
|
||||
}
|
||||
|
||||
boolean hasEntry(Object key) {
|
||||
return entries.containsKey(key);
|
||||
}
|
||||
|
||||
static final class GtnhMeshBackend implements MeshBackend {
|
||||
private DirectTessellator direct;
|
||||
|
||||
@Override
|
||||
public Tessellator beginCapture(VertexFormat format) {
|
||||
direct = TessellatorManager.startCapturingDirect(format);
|
||||
direct.startDrawingQuads();
|
||||
direct.draw();
|
||||
return direct;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TemplateBuffer endCaptureToTemplate() {
|
||||
final int vertexCount = direct.getVertexCount();
|
||||
if (vertexCount == 0) {
|
||||
TessellatorManager.stopCapturingDirect();
|
||||
direct = null;
|
||||
return null;
|
||||
}
|
||||
final int drawMode = direct.getDrawMode();
|
||||
final VertexFormat format = direct.getVertexFormat();
|
||||
final ByteBuffer copy = direct.allocateBufferCopy();
|
||||
final int[] data = VertexTransform.decode(memAddress0(copy), format, vertexCount, drawMode);
|
||||
memFree(copy);
|
||||
TessellatorManager.stopCapturingDirect();
|
||||
direct = null;
|
||||
return new TemplateBuffer(data, vertexCount, drawMode);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package com.gtnewhorizons.angelica.rendering.tesr;
|
||||
|
||||
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat;
|
||||
import com.gtnewhorizons.angelica.api.tesr.TesrMaterial;
|
||||
import com.gtnewhorizons.angelica.api.tesr.TesrMeshBuilder;
|
||||
import com.gtnewhorizons.angelica.glsm.GLStateManager;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.renderer.Tessellator;
|
||||
import net.minecraft.tileentity.TileEntityBeacon;
|
||||
import net.minecraft.util.MathHelper;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
|
||||
public final class BeaconBeamMeshes {
|
||||
|
||||
private static final ResourceLocation BEACON_TEXTURE = new ResourceLocation("textures/entity/beacon_beam.png");
|
||||
|
||||
private static final TesrMaterial INNER = TesrMaterial.builder()
|
||||
.color(1f, 1f, 1f, 1f).lightmap(240f, 240f).unlit().noCull().cutout(0.1f).stream()
|
||||
.special(TesrMaterial.SpecialRender.BEACON_BEAM).build();
|
||||
private static final TesrMaterial OUTER = TesrMaterial.builder()
|
||||
.color(1f, 1f, 1f, 32f / 255f).lightmap(240f, 240f).unlit().noCull().cutout(0.1f)
|
||||
.translucent().noDepthWrite().stream()
|
||||
.special(TesrMaterial.SpecialRender.BEACON_BEAM).build();
|
||||
|
||||
private static final Object INNER_KEY = new Object();
|
||||
private static final Object OUTER_KEY = new Object();
|
||||
|
||||
private static final double INNER_RADIUS = 0.2;
|
||||
private static final double BEAM_HEIGHT = 256.0;
|
||||
private static final double INNER_V_TOP = BEAM_HEIGHT * (0.5 / INNER_RADIUS);
|
||||
|
||||
private static final TesrMeshBuilder INNER_BUILDER = sink -> {
|
||||
final Tessellator t = sink.angelica$bucket(DefaultVertexFormat.POSITION_TEXTURE, BEACON_TEXTURE, INNER);
|
||||
final double[] cx = new double[4];
|
||||
final double[] cz = new double[4];
|
||||
|
||||
final double[] angles = {3 * Math.PI / 4, Math.PI / 4, 5 * Math.PI / 4, 7 * Math.PI / 4};
|
||||
for (int i = 0; i < 4; i++) {
|
||||
cx[i] = Math.cos(angles[i]) * INNER_RADIUS;
|
||||
cz[i] = Math.sin(angles[i]) * INNER_RADIUS;
|
||||
}
|
||||
sideQuad(t, cx[0], cz[0], cx[1], cz[1], INNER_V_TOP);
|
||||
sideQuad(t, cx[3], cz[3], cx[2], cz[2], INNER_V_TOP);
|
||||
sideQuad(t, cx[1], cz[1], cx[3], cz[3], INNER_V_TOP);
|
||||
sideQuad(t, cx[2], cz[2], cx[0], cz[0], INNER_V_TOP);
|
||||
};
|
||||
|
||||
private static final TesrMeshBuilder OUTER_BUILDER = sink -> {
|
||||
final Tessellator t = sink.angelica$bucket(DefaultVertexFormat.POSITION_TEXTURE, BEACON_TEXTURE, OUTER);
|
||||
final double r = 0.3;
|
||||
sideQuad(t, -r, -r, r, -r, BEAM_HEIGHT);
|
||||
sideQuad(t, r, r, -r, r, BEAM_HEIGHT);
|
||||
sideQuad(t, r, -r, r, r, BEAM_HEIGHT);
|
||||
sideQuad(t, -r, r, -r, -r, BEAM_HEIGHT);
|
||||
};
|
||||
|
||||
private static void sideQuad(Tessellator t, double x0, double z0, double x1, double z1, double vTop) {
|
||||
t.addVertexWithUV(x0, BEAM_HEIGHT, z0, 1.0, vTop);
|
||||
t.addVertexWithUV(x0, 0.0, z0, 1.0, 0.0);
|
||||
t.addVertexWithUV(x1, 0.0, z1, 0.0, 0.0);
|
||||
t.addVertexWithUV(x1, BEAM_HEIGHT, z1, 0.0, vTop);
|
||||
}
|
||||
|
||||
private BeaconBeamMeshes() {}
|
||||
|
||||
public static boolean render(TileEntityBeacon beacon, double x, double y, double z, float partialTicks) {
|
||||
final float f1 = beacon.func_146002_i();
|
||||
GLStateManager.glAlphaFunc(GL11.GL_GREATER, 0.1f);
|
||||
if (f1 <= 0.0f) {
|
||||
return true;
|
||||
}
|
||||
if (f1 < 1.0f) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Minecraft.getMinecraft().getTextureManager().bindTexture(BEACON_TEXTURE);
|
||||
GLStateManager.glTexParameterf(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_REPEAT);
|
||||
GLStateManager.glTexParameterf(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_REPEAT);
|
||||
|
||||
final float f2 = (float) beacon.getWorldObj().getTotalWorldTime() + partialTicks;
|
||||
final float f3 = -f2 * 0.2f - MathHelper.floor_float(-f2 * 0.1f);
|
||||
final double d3 = f2 * 0.025 * -1.5;
|
||||
|
||||
GLStateManager.glMatrixMode(GL11.GL_TEXTURE);
|
||||
GLStateManager.glPushMatrix();
|
||||
GLStateManager.glLoadIdentity();
|
||||
GLStateManager.glTranslatef(0f, f3 - 1f, 0f);
|
||||
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
|
||||
try {
|
||||
GLStateManager.glPushMatrix();
|
||||
GLStateManager.glTranslated(x + 0.5, y, z + 0.5);
|
||||
GLStateManager.glRotatef((float) -Math.toDegrees(d3), 0f, 1f, 0f);
|
||||
AngelicaTesrMeshCache.INSTANCE.renderCached(INNER_KEY, INNER_BUILDER);
|
||||
GLStateManager.glPopMatrix();
|
||||
|
||||
GLStateManager.glPushMatrix();
|
||||
GLStateManager.glTranslated(x + 0.5, y, z + 0.5);
|
||||
AngelicaTesrMeshCache.INSTANCE.renderCached(OUTER_KEY, OUTER_BUILDER);
|
||||
GLStateManager.glPopMatrix();
|
||||
} finally {
|
||||
GLStateManager.glMatrixMode(GL11.GL_TEXTURE);
|
||||
GLStateManager.glPopMatrix();
|
||||
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package com.gtnewhorizons.angelica.rendering.tesr;
|
||||
|
||||
import com.gtnewhorizon.gtnhlib.client.renderer.MatrixHelper;
|
||||
import com.gtnewhorizons.angelica.api.tesr.TesrMaterial;
|
||||
import com.gtnewhorizons.angelica.glsm.GLStateManager;
|
||||
import com.gtnewhorizons.angelica.glsm.states.BlendState;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
|
||||
public final class EntityMaterials {
|
||||
|
||||
static final TesrMaterial CUTOUT = TesrMaterial.builder().cutout(0.1f).stream().build();
|
||||
static final TesrMaterial CUTOUT_HALF = TesrMaterial.builder().cutout(0.5f).stream().build();
|
||||
static final TesrMaterial SOLID = TesrMaterial.builder().stream().build();
|
||||
static final TesrMaterial TRANSLUCENT = TesrMaterial.builder().translucent().cutout(1f / 255f).noDepthWrite().stream().build();
|
||||
static final TesrMaterial TRANSLUCENT_DEPTH_WRITE = TesrMaterial.builder().translucent().cutout(1f / 255f).stream().build();
|
||||
static final TesrMaterial ADDITIVE = TesrMaterial.builder().additive().stream().build();
|
||||
static final TesrMaterial ADDITIVE_NO_DEPTH_WRITE = TesrMaterial.builder().additive().noDepthWrite().stream().build();
|
||||
static final TesrMaterial ADDITIVE_ALPHA = TesrMaterial.builder().additiveAlpha().stream().build();
|
||||
static final TesrMaterial ADDITIVE_ALPHA_NO_DEPTH_WRITE = TesrMaterial.builder().additiveAlpha().noDepthWrite().stream().build();
|
||||
static final TesrMaterial OVERLAY = TesrMaterial.builder().translucent().depthEqual().stream().build();
|
||||
static final TesrMaterial GLINT = TesrMaterial.builder().glint().depthEqual().noDepthWrite().unlit().stream()
|
||||
.special(TesrMaterial.SpecialRender.GLINT).build();
|
||||
|
||||
private EntityMaterials() {}
|
||||
|
||||
static TesrMaterial fromCurrentState() {
|
||||
final boolean textured = GLStateManager.getTextures().getTextureUnitStates(0).isEnabled();
|
||||
final boolean texAnimated = textured && !MatrixHelper.isIdentity(GLStateManager.getTextures().getTextureUnitMatrix(0));
|
||||
final BlendState blend = GLStateManager.getBlendState();
|
||||
return fromState(textured, texAnimated,
|
||||
GLStateManager.getBlendMode().isEnabled(), blend.getSrcRgb(), blend.getDstRgb(),
|
||||
GLStateManager.getAlphaTest().isEnabled(),
|
||||
GLStateManager.getAlphaState().getFunction(), GLStateManager.getAlphaState().getReference(),
|
||||
GLStateManager.getDepthState().getFunc(), GLStateManager.getDepthState().isEnabled());
|
||||
}
|
||||
|
||||
static TesrMaterial fromState(boolean textured, boolean blend, int srcRgb, int dstRgb, boolean alphaTest, int alphaFunc, float alphaRef, int depthFunc, boolean depthMask) {
|
||||
return fromState(textured, false, blend, srcRgb, dstRgb, alphaTest, alphaFunc, alphaRef, depthFunc, depthMask);
|
||||
}
|
||||
|
||||
static TesrMaterial fromState(boolean textured, boolean texAnimated, boolean blend, int srcRgb, int dstRgb, boolean alphaTest, int alphaFunc, float alphaRef, int depthFunc, boolean depthMask) {
|
||||
if (!textured) {
|
||||
if (blend && depthFunc == GL11.GL_EQUAL && srcRgb == GL11.GL_SRC_ALPHA && dstRgb == GL11.GL_ONE_MINUS_SRC_ALPHA) {
|
||||
return OVERLAY;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (texAnimated) {
|
||||
if (blend && !depthMask && depthFunc == GL11.GL_EQUAL && srcRgb == GL11.GL_SRC_COLOR && dstRgb == GL11.GL_ONE) {
|
||||
return GLINT;
|
||||
}
|
||||
if (blend && (depthFunc == GL11.GL_LEQUAL || depthFunc == GL11.GL_LESS)) {
|
||||
if (srcRgb == GL11.GL_ONE && dstRgb == GL11.GL_ONE) {
|
||||
return depthMask ? ADDITIVE : ADDITIVE_NO_DEPTH_WRITE;
|
||||
}
|
||||
if (srcRgb == GL11.GL_SRC_ALPHA && dstRgb == GL11.GL_ONE) {
|
||||
return depthMask ? ADDITIVE_ALPHA : ADDITIVE_ALPHA_NO_DEPTH_WRITE;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (depthFunc != GL11.GL_LEQUAL && depthFunc != GL11.GL_LESS) {
|
||||
return null;
|
||||
}
|
||||
if (!blend) {
|
||||
if (!alphaTest) return SOLID;
|
||||
if (alphaFunc == GL11.GL_GREATER && Math.abs(alphaRef - 0.1f) < 1e-4f) return CUTOUT;
|
||||
if (alphaFunc == GL11.GL_GREATER && Math.abs(alphaRef - 0.5f) < 1e-4f) return CUTOUT_HALF;
|
||||
return null;
|
||||
}
|
||||
if (srcRgb == GL11.GL_SRC_ALPHA && dstRgb == GL11.GL_ONE_MINUS_SRC_ALPHA) {
|
||||
return depthMask ? TRANSLUCENT_DEPTH_WRITE : TRANSLUCENT;
|
||||
}
|
||||
if (srcRgb == GL11.GL_ONE && dstRgb == GL11.GL_ONE) {
|
||||
return depthMask ? ADDITIVE : ADDITIVE_NO_DEPTH_WRITE;
|
||||
}
|
||||
if (srcRgb == GL11.GL_SRC_ALPHA && dstRgb == GL11.GL_ONE) {
|
||||
return depthMask ? ADDITIVE_ALPHA : ADDITIVE_ALPHA_NO_DEPTH_WRITE;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+232
@@ -0,0 +1,232 @@
|
||||
package com.gtnewhorizons.angelica.rendering.tesr;
|
||||
|
||||
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags;
|
||||
import com.gtnewhorizons.angelica.glsm.GLStateManager;
|
||||
import com.gtnewhorizons.angelica.glsm.ffp.InstancedAttribs;
|
||||
import com.gtnewhorizons.angelica.glsm.ffp.VAOManager;
|
||||
import com.gtnewhorizons.angelica.glsm.streaming.OrphanStreamingBuffer;
|
||||
import com.gtnewhorizons.angelica.glsm.streaming.PersistentStreamingBuffer;
|
||||
import it.unimi.dsi.fastutil.floats.FloatArrayList;
|
||||
import it.unimi.dsi.fastutil.ints.IntArrayList;
|
||||
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
|
||||
import it.unimi.dsi.fastutil.objects.ObjectIterator;
|
||||
import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
import org.lwjgl.opengl.GL15;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0;
|
||||
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.COLOR_INDEX;
|
||||
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.NORMAL_INDEX;
|
||||
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.TEX_X_INDEX;
|
||||
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.VERTEX_SIZE;
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutFloat;
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutInt;
|
||||
|
||||
final class InstancedTemplateRenderer {
|
||||
|
||||
static final long TEMPLATE_TTL_MS = AngelicaTesrMeshCache.LRU_TIMEOUT_MS;
|
||||
|
||||
private static final int TEMPLATE_STRIDE = VERTEX_SIZE * 4;
|
||||
private static final int TEMPLATE_FLAGS = VertexFlags.COLOR_BIT | VertexFlags.TEXTURE_BIT | VertexFlags.NORMAL_BIT;
|
||||
|
||||
private static final class TemplateMesh {
|
||||
int vao;
|
||||
int vbo;
|
||||
int vertexCount;
|
||||
int drawMode;
|
||||
long lastUsedMs;
|
||||
}
|
||||
|
||||
private static final class Bucket {
|
||||
TemplateMesh mesh;
|
||||
final IntArrayList indices = new IntArrayList();
|
||||
}
|
||||
|
||||
private final Reference2ObjectOpenHashMap<TemplateBuffer, TemplateMesh> meshes = new Reference2ObjectOpenHashMap<>();
|
||||
private final Reference2ObjectOpenHashMap<TemplateBuffer, Bucket> buckets = new Reference2ObjectOpenHashMap<>();
|
||||
private final ObjectArrayList<Bucket> bucketPool = new ObjectArrayList<>();
|
||||
private final ObjectArrayList<Bucket> liveBuckets = new ObjectArrayList<>();
|
||||
private final float[] matScratch = new float[16];
|
||||
|
||||
private PersistentStreamingBuffer persistentRing;
|
||||
private OrphanStreamingBuffer orphanRing;
|
||||
private boolean ringInitialized;
|
||||
private boolean ringUsedThisFrame;
|
||||
private int uploadBufferId;
|
||||
private ByteBuffer staging;
|
||||
|
||||
int drawGroup(ObjectArrayList<TemplateBuffer> templates, FloatArrayList matrices, IntArrayList lights, IntArrayList colors, int count, long nowMs) {
|
||||
for (int i = 0; i < count; i++) {
|
||||
final TemplateBuffer template = templates.get(i);
|
||||
Bucket bucket = buckets.get(template);
|
||||
if (bucket == null) {
|
||||
bucket = bucketPool.isEmpty() ? new Bucket() : bucketPool.pop();
|
||||
bucket.mesh = meshFor(template, nowMs);
|
||||
buckets.put(template, bucket);
|
||||
liveBuckets.add(bucket);
|
||||
}
|
||||
bucket.indices.add(i);
|
||||
}
|
||||
|
||||
staging = MeshBuffer.ensureCapacity(staging, count * InstancedAttribs.STRIDE, false);
|
||||
final long base = memAddress0(staging);
|
||||
long ptr = base;
|
||||
for (int b = 0, n = liveBuckets.size(); b < n; b++) {
|
||||
final IntArrayList indices = liveBuckets.get(b).indices;
|
||||
for (int j = 0, m = indices.size(); j < m; j++) {
|
||||
final int i = indices.getInt(j);
|
||||
matrices.getElements(i * 16, matScratch, 0, 16);
|
||||
for (int k = 0; k < 16; k++) {
|
||||
memPutFloat(ptr + k * 4L, matScratch[k]);
|
||||
}
|
||||
memPutInt(ptr + InstancedAttribs.OFFSET_COLOR, colors.getInt(i));
|
||||
final int light = lights.getInt(i);
|
||||
memPutFloat(ptr + InstancedAttribs.OFFSET_LIGHTMAP, light & 0xFFFF);
|
||||
memPutFloat(ptr + InstancedAttribs.OFFSET_LIGHTMAP + 4, (light >>> 16) & 0xFFFF);
|
||||
ptr += InstancedAttribs.STRIDE;
|
||||
}
|
||||
}
|
||||
staging.position(0);
|
||||
staging.limit((int) (ptr - base));
|
||||
final long ringBase = uploadInstances(staging);
|
||||
staging.clear();
|
||||
|
||||
int draws = 0;
|
||||
long recordOffset = ringBase;
|
||||
final int ringId = uploadBufferId;
|
||||
GLStateManager.instancedFfpDrawActive = true;
|
||||
for (int b = 0, n = liveBuckets.size(); b < n; b++) {
|
||||
final Bucket bucket = liveBuckets.get(b);
|
||||
final TemplateMesh mesh = bucket.mesh;
|
||||
GLStateManager.glBindVertexArray(mesh.vao);
|
||||
VAOManager.setCurrentVertexFlags(TEMPLATE_FLAGS);
|
||||
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, ringId);
|
||||
pointInstanceAttribs(recordOffset);
|
||||
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
|
||||
GLStateManager.glDrawArraysInstanced(mesh.drawMode, 0, mesh.vertexCount, bucket.indices.size());
|
||||
draws++;
|
||||
recordOffset += (long) bucket.indices.size() * InstancedAttribs.STRIDE;
|
||||
bucket.indices.clear();
|
||||
bucket.mesh = null;
|
||||
bucketPool.add(bucket);
|
||||
}
|
||||
GLStateManager.instancedFfpDrawActive = false;
|
||||
GLStateManager.glBindVertexArray(0);
|
||||
liveBuckets.clear();
|
||||
buckets.clear();
|
||||
return draws;
|
||||
}
|
||||
|
||||
private static void pointInstanceAttribs(long base) {
|
||||
for (int c = 0; c < 4; c++) {
|
||||
GLStateManager.glVertexAttribPointer(InstancedAttribs.LOC_MATRIX_COL0 + c, 4, GL11.GL_FLOAT, false,
|
||||
InstancedAttribs.STRIDE, base + c * 16L);
|
||||
}
|
||||
GLStateManager.glVertexAttribPointer(InstancedAttribs.LOC_COLOR, 4, GL11.GL_UNSIGNED_BYTE, true,
|
||||
InstancedAttribs.STRIDE, base + InstancedAttribs.OFFSET_COLOR);
|
||||
GLStateManager.glVertexAttribPointer(InstancedAttribs.LOC_LIGHTMAP, 2, GL11.GL_FLOAT, false,
|
||||
InstancedAttribs.STRIDE, base + InstancedAttribs.OFFSET_LIGHTMAP);
|
||||
}
|
||||
|
||||
private long uploadInstances(ByteBuffer data) {
|
||||
if (!ringInitialized) {
|
||||
ringInitialized = true;
|
||||
persistentRing = PersistentStreamingBuffer.createOrNull(PersistentStreamingBuffer.DEFAULT_CAPACITY);
|
||||
}
|
||||
ringUsedThisFrame = true;
|
||||
if (persistentRing != null) {
|
||||
final int index = persistentRing.upload(data, InstancedAttribs.STRIDE);
|
||||
if (index >= 0) {
|
||||
uploadBufferId = persistentRing.getBufferId();
|
||||
return (long) index * InstancedAttribs.STRIDE;
|
||||
}
|
||||
}
|
||||
if (orphanRing == null) orphanRing = new OrphanStreamingBuffer();
|
||||
orphanRing.upload(data);
|
||||
uploadBufferId = orphanRing.getBufferId();
|
||||
return 0;
|
||||
}
|
||||
|
||||
private TemplateMesh meshFor(TemplateBuffer template, long nowMs) {
|
||||
TemplateMesh mesh = meshes.get(template);
|
||||
if (mesh == null) {
|
||||
mesh = build(template);
|
||||
meshes.put(template, mesh);
|
||||
}
|
||||
mesh.lastUsedMs = nowMs;
|
||||
return mesh;
|
||||
}
|
||||
|
||||
private static TemplateMesh build(TemplateBuffer template) {
|
||||
final TemplateMesh mesh = new TemplateMesh();
|
||||
mesh.vertexCount = template.vertexCount;
|
||||
mesh.drawMode = template.drawMode;
|
||||
mesh.vao = GLStateManager.glGenVertexArrays();
|
||||
GLStateManager.glBindVertexArray(mesh.vao);
|
||||
mesh.vbo = GLStateManager.glGenBuffers();
|
||||
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, mesh.vbo);
|
||||
GLStateManager.glBufferData(GL15.GL_ARRAY_BUFFER, template.data, GL15.GL_STATIC_DRAW);
|
||||
|
||||
GLStateManager.glEnableVertexAttribArray(0);
|
||||
GLStateManager.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, TEMPLATE_STRIDE, 0L);
|
||||
GLStateManager.glEnableVertexAttribArray(1);
|
||||
GLStateManager.glVertexAttribPointer(1, 4, GL11.GL_UNSIGNED_BYTE, true, TEMPLATE_STRIDE, COLOR_INDEX * 4L);
|
||||
GLStateManager.glEnableVertexAttribArray(2);
|
||||
GLStateManager.glVertexAttribPointer(2, 2, GL11.GL_FLOAT, false, TEMPLATE_STRIDE, TEX_X_INDEX * 4L);
|
||||
GLStateManager.glEnableVertexAttribArray(4);
|
||||
GLStateManager.glVertexAttribPointer(4, 3, GL11.GL_BYTE, true, TEMPLATE_STRIDE, NORMAL_INDEX * 4L);
|
||||
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
|
||||
|
||||
for (int loc = InstancedAttribs.LOC_MATRIX_COL0; loc <= InstancedAttribs.LOC_LIGHTMAP; loc++) {
|
||||
GLStateManager.glEnableVertexAttribArray(loc);
|
||||
GLStateManager.glVertexAttribDivisor(loc, 1);
|
||||
}
|
||||
VAOManager.setCurrentVertexFlags(TEMPLATE_FLAGS);
|
||||
GLStateManager.glBindVertexArray(0);
|
||||
return mesh;
|
||||
}
|
||||
|
||||
void endFrame() {
|
||||
if (ringUsedThisFrame && persistentRing != null) {
|
||||
persistentRing.postDraw();
|
||||
}
|
||||
ringUsedThisFrame = false;
|
||||
}
|
||||
|
||||
void sweep(long now) {
|
||||
if (meshes.isEmpty()) return;
|
||||
final ObjectIterator<TemplateMesh> it = meshes.values().iterator();
|
||||
while (it.hasNext()) {
|
||||
final TemplateMesh mesh = it.next();
|
||||
if (now - mesh.lastUsedMs <= TEMPLATE_TTL_MS) continue;
|
||||
delete(mesh);
|
||||
it.remove();
|
||||
}
|
||||
}
|
||||
|
||||
void clear() {
|
||||
for (final TemplateMesh mesh : meshes.values()) {
|
||||
delete(mesh);
|
||||
}
|
||||
meshes.clear();
|
||||
}
|
||||
|
||||
private static void delete(TemplateMesh mesh) {
|
||||
GLStateManager.glDeleteBuffers(mesh.vbo);
|
||||
GLStateManager.glDeleteVertexArrays(mesh.vao);
|
||||
}
|
||||
|
||||
int meshCount() {
|
||||
return meshes.size();
|
||||
}
|
||||
|
||||
long meshBytes() {
|
||||
long bytes = 0;
|
||||
for (final TemplateMesh mesh : meshes.values()) {
|
||||
bytes += (long) mesh.vertexCount * TEMPLATE_STRIDE;
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.gtnewhorizons.angelica.rendering.tesr;
|
||||
|
||||
import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer;
|
||||
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
|
||||
import com.gtnewhorizons.angelica.glsm.GLStateManager;
|
||||
import org.lwjgl.BufferUtils;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
/** Equivalent of modern's VertexBuffer: a mesh uploaded once and drawn many times */
|
||||
public final class MeshBuffer {
|
||||
|
||||
private VertexBuffer vbo;
|
||||
private int vao;
|
||||
|
||||
public void upload(VertexFormat format, int drawMode, ByteBuffer data, int vertexCount) {
|
||||
upload(format, drawMode, data, vertexCount, false);
|
||||
}
|
||||
|
||||
public void upload(VertexFormat format, int drawMode, ByteBuffer data, int vertexCount, boolean dynamic) {
|
||||
if (vbo == null || vbo.getDrawMode() != drawMode) {
|
||||
if (vbo != null) vbo.delete();
|
||||
vbo = new VertexBuffer(format, drawMode);
|
||||
}
|
||||
if (dynamic) {
|
||||
vbo.uploadDynamic(data, vertexCount);
|
||||
} else {
|
||||
vbo.uploadStream(data, vertexCount);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isUploaded() {
|
||||
return vbo != null;
|
||||
}
|
||||
|
||||
public void bind() {
|
||||
if (vao == 0) {
|
||||
vao = GLStateManager.glGenVertexArrays();
|
||||
}
|
||||
GLStateManager.glBindVertexArray(vao);
|
||||
vbo.setupState();
|
||||
}
|
||||
|
||||
public void draw(int first, int count) {
|
||||
vbo.draw(first, count);
|
||||
}
|
||||
|
||||
public void unbind() {
|
||||
vbo.cleanupState();
|
||||
GLStateManager.glBindVertexArray(0);
|
||||
}
|
||||
|
||||
public void render() {
|
||||
bind();
|
||||
vbo.draw();
|
||||
unbind();
|
||||
}
|
||||
|
||||
public void delete() {
|
||||
if (vbo != null) {
|
||||
vbo.delete();
|
||||
vbo = null;
|
||||
}
|
||||
if (vao != 0) {
|
||||
GLStateManager.glDeleteVertexArrays(vao);
|
||||
vao = 0;
|
||||
}
|
||||
}
|
||||
|
||||
public static ByteBuffer ensureCapacity(ByteBuffer buffer, int bytes, boolean preserve) {
|
||||
if (buffer == null) {
|
||||
return BufferUtils.createByteBuffer(Integer.highestOneBit(Math.max(bytes - 1, 1)) << 1);
|
||||
}
|
||||
if (preserve) {
|
||||
if (buffer.remaining() >= bytes) return buffer;
|
||||
int newCapacity = buffer.capacity() * 2;
|
||||
while (newCapacity - buffer.position() < bytes) newCapacity *= 2;
|
||||
final ByteBuffer grown = BufferUtils.createByteBuffer(newCapacity);
|
||||
buffer.flip();
|
||||
grown.put(buffer);
|
||||
return grown;
|
||||
}
|
||||
if (buffer.capacity() >= bytes) return buffer;
|
||||
return BufferUtils.createByteBuffer(Integer.highestOneBit(Math.max(bytes - 1, 1)) << 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,385 @@
|
||||
package com.gtnewhorizons.angelica.rendering.tesr;
|
||||
|
||||
import com.gtnewhorizon.gtnhlib.client.renderer.MatrixHelper;
|
||||
import com.gtnewhorizon.gtnhlib.client.renderer.cel.api.util.ColorABGR;
|
||||
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat;
|
||||
import com.gtnewhorizons.angelica.AngelicaMod;
|
||||
import com.gtnewhorizons.angelica.api.tesr.ModelPartMeshBuilder;
|
||||
import com.gtnewhorizons.angelica.api.tesr.TesrMaterial;
|
||||
import com.gtnewhorizons.angelica.client.font.BatchingFontRenderer;
|
||||
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.hooks.GLSMConfig;
|
||||
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
|
||||
import com.gtnewhorizons.angelica.glsm.states.BlendState;
|
||||
import com.gtnewhorizons.angelica.glsm.states.Color4;
|
||||
import com.gtnewhorizons.angelica.profiling.BailClassCounts;
|
||||
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
|
||||
import it.unimi.dsi.fastutil.objects.ObjectIterator;
|
||||
import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap;
|
||||
import it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet;
|
||||
import net.coderbot.batchedentityrendering.impl.AngelicaBufferSource;
|
||||
import net.coderbot.batchedentityrendering.impl.TransparencyType;
|
||||
import net.coderbot.iris.Iris;
|
||||
import net.coderbot.iris.layer.GbufferPrograms;
|
||||
import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline;
|
||||
import net.coderbot.iris.uniforms.CapturedRenderingState;
|
||||
import net.minecraft.client.model.ModelBox;
|
||||
import net.minecraft.client.model.ModelRenderer;
|
||||
import net.minecraft.client.renderer.Tessellator;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import org.joml.Matrix4f;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
public final class ModelPartBatcher {
|
||||
|
||||
public static final ModelPartBatcher INSTANCE = new ModelPartBatcher();
|
||||
|
||||
public enum Mode { ENTITIES, BLOCK_ENTITIES }
|
||||
|
||||
public enum BailReason {
|
||||
INACTIVE("tesr.bail.inactive"),
|
||||
RECORDING("tesr.bail.recording"),
|
||||
MATERIAL("tesr.bail.material"),
|
||||
TEXTURE("tesr.bail.texture"),
|
||||
TEMPLATE("tesr.bail.template"),
|
||||
HURT_FLASH("tesr.bail.hurtFlash"),
|
||||
FOREIGN_PROGRAM("tesr.bail.foreignProgram");
|
||||
|
||||
public static final BailReason[] VALUES = values();
|
||||
public final String plotName;
|
||||
|
||||
BailReason(String plotName) {
|
||||
this.plotName = plotName;
|
||||
}
|
||||
}
|
||||
|
||||
private static final long SWEEP_INTERVAL_MS = 5_000L;
|
||||
|
||||
private final AngelicaBufferSource bufferSource = new AngelicaBufferSource();
|
||||
private final RetainedTesrGroups groups = new RetainedTesrGroups(bufferSource);
|
||||
private final RetainedTesrGroups shadowGroups = new RetainedTesrGroups(bufferSource);
|
||||
private RetainedTesrGroups activeGroups = groups;
|
||||
private boolean shadow;
|
||||
private final AngelicaTesrMeshCache.GtnhMeshBackend captureBackend = new AngelicaTesrMeshCache.GtnhMeshBackend();
|
||||
private final Matrix4f identity = new Matrix4f();
|
||||
private final Matrix4f modelView = new Matrix4f();
|
||||
private final Matrix4f texMatrixScratch = new Matrix4f();
|
||||
private int lastMvGeneration;
|
||||
private boolean mvCaptured;
|
||||
private boolean active;
|
||||
private Mode mode = Mode.BLOCK_ENTITIES;
|
||||
private boolean instancedThisCycle;
|
||||
private DeferredWorldRenderingPipeline shaderPipeline;
|
||||
private long lastSweepMs;
|
||||
|
||||
long parts;
|
||||
long liveFallbacks;
|
||||
private final long[] bails = new long[BailReason.VALUES.length];
|
||||
private long lastParts, lastLiveFallbacks;
|
||||
|
||||
public long statParts() { return parts; }
|
||||
public long statLiveFallbacks() { return liveFallbacks; }
|
||||
public long statBail(BailReason reason) { return bails[reason.ordinal()]; }
|
||||
|
||||
private void bail(BailReason reason) {
|
||||
bails[reason.ordinal()]++;
|
||||
}
|
||||
|
||||
private static final class PartTemplate {
|
||||
TemplateBuffer template;
|
||||
float scale;
|
||||
long lastUsedMs;
|
||||
boolean emptyVanillaPart;
|
||||
boolean forceStream;
|
||||
}
|
||||
|
||||
private final Reference2ObjectOpenHashMap<ModelRenderer, PartTemplate> templates = new Reference2ObjectOpenHashMap<>();
|
||||
|
||||
private static final class LayerKey {
|
||||
ResourceLocation texture;
|
||||
TesrMaterial material;
|
||||
|
||||
LayerKey set(ResourceLocation texture, TesrMaterial material) {
|
||||
this.texture = texture;
|
||||
this.material = material;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (!(o instanceof LayerKey other)) return false;
|
||||
return Objects.equals(texture, other.texture) && Objects.equals(material, other.material);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hashCode(texture) * 31 + Objects.hashCode(material);
|
||||
}
|
||||
}
|
||||
|
||||
private final Object2ObjectOpenHashMap<LayerKey, RenderLayer> layers = new Object2ObjectOpenHashMap<>();
|
||||
private final LayerKey scratchKey = new LayerKey();
|
||||
private ResourceLocation lastLayerTexture;
|
||||
private TesrMaterial lastLayerMaterial;
|
||||
private RenderLayer lastLayer;
|
||||
|
||||
private static ResourceLocation lastBoundLocation;
|
||||
private static int lastBoundGlId = -1;
|
||||
|
||||
private ModelPartBatcher() {}
|
||||
|
||||
public static void onTextureBind(ResourceLocation location, int glId) {
|
||||
lastBoundLocation = location;
|
||||
lastBoundGlId = glId;
|
||||
}
|
||||
|
||||
public void begin(Mode mode) {
|
||||
begin(mode, false);
|
||||
}
|
||||
|
||||
public void begin(Mode mode, boolean shadow) {
|
||||
this.mode = mode;
|
||||
this.shadow = shadow;
|
||||
instancedThisCycle = TesrBatchRenderer.instancedCapable();
|
||||
shaderPipeline = TesrBatchRenderer.deferredPipeline();
|
||||
if (!AngelicaConfig.enableEntityBatching || !(instancedThisCycle || shaderPipeline != null)) {
|
||||
active = false;
|
||||
shaderPipeline = null;
|
||||
return;
|
||||
}
|
||||
active = true;
|
||||
mvCaptured = false;
|
||||
activeGroups = shadow ? shadowGroups : groups;
|
||||
bufferSource.setIdKind(mode == Mode.ENTITIES ? AngelicaBufferSource.GroupIdKind.ENTITY : AngelicaBufferSource.GroupIdKind.BLOCK_ENTITY);
|
||||
activeGroups.beginPass(identity, 0, 0, 0, instancedThisCycle ? TesrBatchRenderer.INSTANCE.instancedRenderer : null, shaderPipeline);
|
||||
final long now = System.currentTimeMillis();
|
||||
if (now - lastSweepMs >= SWEEP_INTERVAL_MS) {
|
||||
lastSweepMs = now;
|
||||
groups.sweep(now);
|
||||
shadowGroups.sweep(now);
|
||||
sweepTemplates(now);
|
||||
}
|
||||
}
|
||||
|
||||
public void flush() {
|
||||
if (!active) return;
|
||||
active = false;
|
||||
if (shadow) {
|
||||
bufferSource.endBatchWithType(TransparencyType.OPAQUE, activeGroups);
|
||||
bufferSource.endBatch(activeGroups);
|
||||
if (instancedThisCycle) {
|
||||
TesrBatchRenderer.INSTANCE.instancedRenderer.endFrame();
|
||||
}
|
||||
BatchingFontRenderer.flushDeferredText();
|
||||
return;
|
||||
}
|
||||
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 {
|
||||
bufferSource.endBatchWithType(TransparencyType.OPAQUE, activeGroups);
|
||||
bufferSource.endBatch(activeGroups);
|
||||
} finally {
|
||||
if (wrapEntities) GbufferPrograms.endEntities();
|
||||
}
|
||||
if (instancedThisCycle) {
|
||||
TesrBatchRenderer.INSTANCE.instancedRenderer.endFrame();
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isActive() {
|
||||
return active;
|
||||
}
|
||||
|
||||
public static boolean partDraw(ModelRenderer part, float scale, ModelPartMeshBuilder builder) {
|
||||
final ModelPartBatcher r = INSTANCE;
|
||||
if (!r.active) {
|
||||
r.bail(BailReason.INACTIVE);
|
||||
return false;
|
||||
}
|
||||
if (DisplayListManager.isRecording()) {
|
||||
r.bail(BailReason.RECORDING);
|
||||
return false;
|
||||
}
|
||||
if (!r.queuePart(part, scale, builder)) {
|
||||
r.liveFallbacks++;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean queuePart(ModelRenderer part, float scale, ModelPartMeshBuilder builder) {
|
||||
if (shaderPipeline != null) {
|
||||
if (GLStateManager.getActiveProgram() != shaderPipeline.getActivePassProgramId()) {
|
||||
bail(BailReason.FOREIGN_PROGRAM);
|
||||
return false;
|
||||
}
|
||||
} else if (GLStateManager.getOverlayA() != 0.0f) {
|
||||
bail(BailReason.HURT_FLASH);
|
||||
return false;
|
||||
}
|
||||
final PartTemplate entry = templateFor(part, scale, builder);
|
||||
if (entry.emptyVanillaPart) {
|
||||
return true;
|
||||
}
|
||||
if (shadow && isDepthEqualDecalState()) {
|
||||
return true;
|
||||
}
|
||||
final TesrMaterial material = EntityMaterials.fromCurrentState();
|
||||
if (material == null) {
|
||||
bail(BailReason.MATERIAL);
|
||||
if (Tracy.ENABLED) {
|
||||
BailClassCounts.MATERIAL.add(TesrAttribution.currentRenderable);
|
||||
logMaterialBail();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
final ResourceLocation texture;
|
||||
if (material == EntityMaterials.OVERLAY) {
|
||||
texture = null;
|
||||
} else {
|
||||
if (GLStateManager.getBoundTextureForServerState() != lastBoundGlId) {
|
||||
bail(BailReason.TEXTURE);
|
||||
return false;
|
||||
}
|
||||
texture = lastBoundLocation;
|
||||
if (texture == null) {
|
||||
bail(BailReason.TEXTURE);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
final TemplateBuffer template = entry.template;
|
||||
if (template == null) {
|
||||
bail(BailReason.TEMPLATE);
|
||||
if (Tracy.ENABLED) BailClassCounts.TEMPLATE.add(TesrAttribution.currentRenderable);
|
||||
return false;
|
||||
}
|
||||
|
||||
Matrix4f texMatrix = null;
|
||||
if (texture != null) {
|
||||
final Matrix4f unitMatrix = GLStateManager.getTextures().getTextureUnitMatrix(0);
|
||||
if (!MatrixHelper.isIdentity(unitMatrix)) {
|
||||
texMatrix = texMatrixScratch.set(unitMatrix);
|
||||
if (material.isDepthEqual()) {
|
||||
entry.forceStream = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
final RenderLayer layer = layerFor(texture, material);
|
||||
final int entityId = mode == Mode.ENTITIES ? Math.max(0, CapturedRenderingState.INSTANCE.getCurrentRenderedEntity()) : CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity();
|
||||
final Color4 color = GLStateManager.getColor();
|
||||
final int colorABGR = ColorABGR.pack(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());
|
||||
final int packedLight = ((int) GLSMConfig.lastBrightnessY << 16) | ((int) GLSMConfig.lastBrightnessX & 0xFFFF);
|
||||
final int mvGen = GLStateManager.getMvGeneration();
|
||||
if (!mvCaptured || mvGen != lastMvGeneration) {
|
||||
modelView.set(GLStateManager.getModelViewMatrix());
|
||||
lastMvGeneration = mvGen;
|
||||
mvCaptured = true;
|
||||
}
|
||||
activeGroups.queue(template, layer, material, modelView, packedLight, colorABGR, entityId, texMatrix, entry.forceStream);
|
||||
parts++;
|
||||
return true;
|
||||
}
|
||||
|
||||
private final ReferenceOpenHashSet<Class<?>> loggedMaterialBails = new ReferenceOpenHashSet<>();
|
||||
|
||||
private void logMaterialBail() {
|
||||
final Class<?> cls = TesrAttribution.currentRenderable;
|
||||
if (cls == null || !loggedMaterialBails.add(cls)) return;
|
||||
final boolean textured = GLStateManager.getTextures().getTextureUnitStates(0).isEnabled();
|
||||
final BlendState blendState = GLStateManager.getBlendState();
|
||||
AngelicaMod.LOGGER.info("TESR MATERIAL bail: cls={} shadow={} textured={} texAnimated={} blend={} src={} dst={} alphaTest={} alphaFunc={} alphaRef={} depthFunc={} depthMask={}",
|
||||
cls.getName(), shadow, textured,
|
||||
textured && !MatrixHelper.isIdentity(GLStateManager.getTextures().getTextureUnitMatrix(0)),
|
||||
GLStateManager.getBlendMode().isEnabled(), blendState.getSrcRgb(), blendState.getDstRgb(),
|
||||
GLStateManager.getAlphaTest().isEnabled(),
|
||||
GLStateManager.getAlphaState().getFunction(), GLStateManager.getAlphaState().getReference(),
|
||||
GLStateManager.getDepthState().getFunc(), GLStateManager.getDepthState().isEnabled());
|
||||
}
|
||||
|
||||
private static boolean isDepthEqualDecalState() {
|
||||
return GLStateManager.getDepthState().getFunc() == GL11.GL_EQUAL && !GLStateManager.getDepthState().isEnabled();
|
||||
}
|
||||
|
||||
private PartTemplate templateFor(ModelRenderer part, float scale, ModelPartMeshBuilder builder) {
|
||||
PartTemplate entry = templates.get(part);
|
||||
if (entry == null || entry.scale != scale) {
|
||||
entry = capture(part, scale, entry, builder);
|
||||
}
|
||||
entry.lastUsedMs = lastSweepMs;
|
||||
return entry;
|
||||
}
|
||||
|
||||
private PartTemplate capture(ModelRenderer part, float scale, PartTemplate reuse, ModelPartMeshBuilder builder) {
|
||||
final PartTemplate entry = reuse != null ? reuse : new PartTemplate();
|
||||
entry.scale = scale;
|
||||
entry.template = null;
|
||||
entry.emptyVanillaPart = false;
|
||||
final List<ModelBox> boxes = part.cubeList;
|
||||
if (builder != null) {
|
||||
final Tessellator tess = captureBackend.beginCapture(DefaultVertexFormat.POSITION_TEXTURE_NORMAL);
|
||||
try {
|
||||
builder.angelica$buildPart(tess, part, scale);
|
||||
} finally {
|
||||
entry.template = captureBackend.endCaptureToTemplate();
|
||||
}
|
||||
} else if (boxes != null && !boxes.isEmpty()) {
|
||||
final Tessellator tess = captureBackend.beginCapture(DefaultVertexFormat.POSITION_TEXTURE_NORMAL);
|
||||
for (int i = 0, n = boxes.size(); i < n; i++) {
|
||||
boxes.get(i).render(tess, scale);
|
||||
}
|
||||
entry.template = captureBackend.endCaptureToTemplate();
|
||||
} else {
|
||||
entry.emptyVanillaPart = part.getClass() == ModelRenderer.class;
|
||||
}
|
||||
templates.put(part, entry);
|
||||
return entry;
|
||||
}
|
||||
|
||||
private RenderLayer layerFor(ResourceLocation texture, TesrMaterial material) {
|
||||
if (texture == lastLayerTexture && material == lastLayerMaterial) {
|
||||
return lastLayer;
|
||||
}
|
||||
RenderLayer layer = layers.get(scratchKey.set(texture, material));
|
||||
if (layer == null) {
|
||||
layer = RenderLayer.tesr(texture, material);
|
||||
layers.put(new LayerKey().set(texture, material), layer);
|
||||
}
|
||||
lastLayerTexture = texture;
|
||||
lastLayerMaterial = material;
|
||||
lastLayer = layer;
|
||||
return layer;
|
||||
}
|
||||
|
||||
private void sweepTemplates(long now) {
|
||||
if (templates.isEmpty()) return;
|
||||
final ObjectIterator<PartTemplate> it = templates.values().iterator();
|
||||
while (it.hasNext()) {
|
||||
if (now - it.next().lastUsedMs > AngelicaTesrMeshCache.LRU_TIMEOUT_MS) {
|
||||
it.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
groups.clear();
|
||||
shadowGroups.clear();
|
||||
templates.clear();
|
||||
bufferSource.freeBuffers();
|
||||
active = false;
|
||||
}
|
||||
|
||||
public String getDebugString() {
|
||||
final String line = String.format("Parts: %d grp, inst %d, live %d", groups.groupCount() + shadowGroups.groupCount(), parts - lastParts, liveFallbacks - lastLiveFallbacks);
|
||||
lastParts = parts;
|
||||
lastLiveFallbacks = liveFallbacks;
|
||||
return line;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.gtnewhorizons.angelica.rendering.tesr;
|
||||
|
||||
import net.minecraft.client.model.ModelBox;
|
||||
import net.minecraft.client.model.ModelRenderer;
|
||||
import net.minecraft.client.renderer.Tessellator;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public final class ModelPartMesher {
|
||||
|
||||
private ModelPartMesher() {}
|
||||
|
||||
public static void emitPart(Tessellator t, ModelRenderer part, float scale) {
|
||||
t.setTranslation(
|
||||
part.offsetX + part.rotationPointX * scale,
|
||||
part.offsetY + part.rotationPointY * scale,
|
||||
part.offsetZ + part.rotationPointZ * scale);
|
||||
emitPartLocal(t, part, scale);
|
||||
t.setTranslation(0, 0, 0);
|
||||
}
|
||||
|
||||
public static void emitPartLocal(Tessellator t, ModelRenderer part, float scale) {
|
||||
final List<ModelBox> boxes = part.cubeList;
|
||||
for (int i = 0, n = boxes.size(); i < n; i++) {
|
||||
boxes.get(i).render(t, scale);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.gtnewhorizons.angelica.rendering.tesr;
|
||||
|
||||
import com.gtnewhorizons.angelica.glsm.GLStateManager;
|
||||
import net.coderbot.iris.Iris;
|
||||
import net.coderbot.iris.pipeline.WorldRenderingPipeline;
|
||||
|
||||
public final class PassRebindGate {
|
||||
|
||||
private static int lastProgramGen = -1;
|
||||
private static int lastFbGen = -1;
|
||||
|
||||
private PassRebindGate() {}
|
||||
|
||||
public static void rebindIfDirty() {
|
||||
if (!Iris.enabled) return;
|
||||
if (GLStateManager.getProgramGeneration() == lastProgramGen
|
||||
&& GLStateManager.getDrawFramebufferGeneration() == lastFbGen) {
|
||||
return;
|
||||
}
|
||||
final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable();
|
||||
if (pipeline != null) {
|
||||
pipeline.rebindCurrentPass();
|
||||
}
|
||||
lastProgramGen = GLStateManager.getProgramGeneration();
|
||||
lastFbGen = GLStateManager.getDrawFramebufferGeneration();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,535 @@
|
||||
package com.gtnewhorizons.angelica.rendering.tesr;
|
||||
|
||||
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.profiling.Tracy;
|
||||
import it.unimi.dsi.fastutil.floats.FloatArrayList;
|
||||
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
|
||||
import it.unimi.dsi.fastutil.ints.IntArrayList;
|
||||
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
|
||||
import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap;
|
||||
import net.coderbot.batchedentityrendering.impl.AngelicaBufferSource;
|
||||
import net.coderbot.batchedentityrendering.impl.SegmentedBufferBuilder;
|
||||
import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline;
|
||||
import net.coderbot.iris.uniforms.CapturedRenderingState;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import org.joml.Matrix4f;
|
||||
import org.joml.Vector3f;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.function.LongSupplier;
|
||||
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0;
|
||||
|
||||
final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
|
||||
|
||||
static final int PROMOTE_AFTER_REBUILDS = 3;
|
||||
static final int DEMOTE_AFTER_STABLE_FRAMES = 4;
|
||||
static final long IDLE_RESET_FRAMES = 100;
|
||||
static final long GROUP_TTL_MS = AngelicaTesrMeshCache.LRU_TIMEOUT_MS;
|
||||
|
||||
private static final Tracy.ZoneId Z_TESR_REBUILD = Tracy.zoneId("tesrRebuild", Tracy.COLOR_CLIENT);
|
||||
|
||||
private final AngelicaBufferSource source;
|
||||
private final LongSupplier clock;
|
||||
private long nowMs;
|
||||
private final Matrix4f baseMV = new Matrix4f();
|
||||
private final Matrix4f baseMVInv = new Matrix4f();
|
||||
private final Matrix4f scratchMat = new Matrix4f();
|
||||
private final Vector3f scratchVec = new Vector3f();
|
||||
private final Matrix4f drawMV = new Matrix4f();
|
||||
private final Matrix4f savedMV = new Matrix4f();
|
||||
private boolean mvSaved;
|
||||
private final float[] matScratch = new float[16];
|
||||
private double camX, camY, camZ;
|
||||
private long frameMark;
|
||||
|
||||
long rebuilds;
|
||||
long retainedDraws;
|
||||
long streamPromotions;
|
||||
long streamedInstances;
|
||||
long instancedDraws;
|
||||
long instancedInstances;
|
||||
|
||||
private InstancedTemplateRenderer instanced;
|
||||
private boolean instancedActive;
|
||||
private DeferredWorldRenderingPipeline deferred;
|
||||
private final MeshBuffer fallbackMesh = new MeshBuffer();
|
||||
private ByteBuffer fallbackScratch;
|
||||
|
||||
static final class Group {
|
||||
final RenderLayer layer;
|
||||
final TesrMaterial material;
|
||||
final int blockEntityId;
|
||||
final boolean opaque;
|
||||
final boolean stream;
|
||||
Class<?> renderableClass;
|
||||
int rebuildsWindow;
|
||||
long anchorX, anchorY, anchorZ;
|
||||
boolean anchored;
|
||||
long frameMark = -1;
|
||||
long lastUsedMs;
|
||||
int entityColor;
|
||||
|
||||
final ObjectArrayList<TemplateBuffer> instTemplates = new ObjectArrayList<>();
|
||||
final FloatArrayList instMatrices = new FloatArrayList();
|
||||
final IntArrayList instLights = new IntArrayList();
|
||||
final IntArrayList instColors = new IntArrayList();
|
||||
final ObjectArrayList<Matrix4f> instTexMatrices = new ObjectArrayList<>();
|
||||
private final ObjectArrayList<Matrix4f> texMatrixPool = new ObjectArrayList<>();
|
||||
private int texMatrixPoolUsed;
|
||||
long hashAcc;
|
||||
int count;
|
||||
|
||||
long builtHash;
|
||||
int builtCount = -1;
|
||||
int builtVertexCount;
|
||||
boolean streaming;
|
||||
int consecutiveRebuilds;
|
||||
long frameHash;
|
||||
long prevFrameHash;
|
||||
int stableFrames;
|
||||
final MeshBuffer mesh = new MeshBuffer();
|
||||
ByteBuffer scratch;
|
||||
int meshBytes;
|
||||
|
||||
void addTexMatrix(Matrix4f src) {
|
||||
if (src == null) {
|
||||
instTexMatrices.add(null);
|
||||
return;
|
||||
}
|
||||
if (texMatrixPoolUsed == texMatrixPool.size()) {
|
||||
texMatrixPool.add(new Matrix4f());
|
||||
}
|
||||
instTexMatrices.add(texMatrixPool.get(texMatrixPoolUsed++).set(src));
|
||||
}
|
||||
|
||||
void clearInstances() {
|
||||
instTemplates.clear();
|
||||
instMatrices.clear();
|
||||
instLights.clear();
|
||||
instColors.clear();
|
||||
instTexMatrices.clear();
|
||||
texMatrixPoolUsed = 0;
|
||||
}
|
||||
|
||||
Group(RenderLayer layer, TesrMaterial material, int blockEntityId) {
|
||||
this.layer = layer;
|
||||
this.material = material;
|
||||
this.blockEntityId = blockEntityId;
|
||||
this.opaque = material.transparency() == TesrMaterial.Transparency.OPAQUE;
|
||||
this.stream = material.isStream();
|
||||
this.streaming = stream;
|
||||
}
|
||||
}
|
||||
|
||||
private final Reference2ObjectOpenHashMap<RenderLayer, Reference2ObjectOpenHashMap<TesrMaterial, Int2ObjectOpenHashMap<Group>>> groups = new Reference2ObjectOpenHashMap<>();
|
||||
private final Reference2ObjectOpenHashMap<RenderLayer, ObjectArrayList<Group>> byLayer = new Reference2ObjectOpenHashMap<>();
|
||||
|
||||
RetainedTesrGroups(AngelicaBufferSource source) {
|
||||
this(source, System::currentTimeMillis);
|
||||
}
|
||||
|
||||
RetainedTesrGroups(AngelicaBufferSource source, LongSupplier clock) {
|
||||
this.source = source;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
void beginPass(Matrix4f base, double camX, double camY, double camZ) {
|
||||
beginPass(base, camX, camY, camZ, null, null);
|
||||
}
|
||||
|
||||
void beginPass(Matrix4f base, double camX, double camY, double camZ, InstancedTemplateRenderer instancedRenderer) {
|
||||
beginPass(base, camX, camY, camZ, instancedRenderer, null);
|
||||
}
|
||||
|
||||
void beginPass(Matrix4f base, double camX, double camY, double camZ, InstancedTemplateRenderer instancedRenderer, DeferredWorldRenderingPipeline deferred) {
|
||||
baseMV.set(base);
|
||||
baseMVInv.set(base).invert();
|
||||
this.camX = camX;
|
||||
this.camY = camY;
|
||||
this.camZ = camZ;
|
||||
this.instanced = instancedRenderer;
|
||||
this.instancedActive = instancedRenderer != null;
|
||||
this.deferred = instancedRenderer != null ? deferred : null;
|
||||
frameMark++;
|
||||
nowMs = clock.getAsLong();
|
||||
}
|
||||
|
||||
private Group groupFor(RenderLayer layer, TesrMaterial material, int blockEntityId) {
|
||||
Reference2ObjectOpenHashMap<TesrMaterial, Int2ObjectOpenHashMap<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);
|
||||
}
|
||||
Group group = byId.get(blockEntityId);
|
||||
if (group == null) {
|
||||
group = new Group(layer, material, blockEntityId);
|
||||
group.lastUsedMs = nowMs;
|
||||
byId.put(blockEntityId, group);
|
||||
byLayer.computeIfAbsent(layer, l -> new ObjectArrayList<>()).add(group);
|
||||
}
|
||||
if (group.renderableClass == null) {
|
||||
group.renderableClass = TesrAttribution.currentRenderable;
|
||||
}
|
||||
return group;
|
||||
}
|
||||
|
||||
void forceStreaming(RenderLayer layer, TesrMaterial material, int blockEntityId) {
|
||||
promote(groupFor(layer, material, blockEntityId));
|
||||
}
|
||||
|
||||
void queue(TemplateBuffer template, RenderLayer layer, TesrMaterial material, Matrix4f currentMV, int packedLight, int colorABGR, int blockEntityId, Matrix4f texMatrix, boolean forceStream) {
|
||||
final Group group = groupFor(layer, material, blockEntityId);
|
||||
if (group.frameMark != frameMark) {
|
||||
if (frameMark - group.frameMark > IDLE_RESET_FRAMES) {
|
||||
group.streaming = group.stream;
|
||||
group.consecutiveRebuilds = 0;
|
||||
group.stableFrames = 0;
|
||||
group.builtCount = -1;
|
||||
} else if (group.streaming && group.opaque && !group.stream) {
|
||||
if (group.frameHash == group.prevFrameHash) {
|
||||
if (++group.stableFrames >= DEMOTE_AFTER_STABLE_FRAMES) {
|
||||
group.streaming = false;
|
||||
group.consecutiveRebuilds = 0;
|
||||
group.stableFrames = 0;
|
||||
group.builtCount = -1;
|
||||
}
|
||||
} else {
|
||||
group.stableFrames = 0;
|
||||
}
|
||||
group.prevFrameHash = group.frameHash;
|
||||
group.frameHash = 0;
|
||||
}
|
||||
group.frameMark = frameMark;
|
||||
group.lastUsedMs = nowMs;
|
||||
group.entityColor = SegmentedBufferBuilder.packEntityColor(CapturedRenderingState.INSTANCE.getCurrentEntityColor());
|
||||
group.count = 0;
|
||||
group.hashAcc = 0;
|
||||
group.clearInstances();
|
||||
if (!group.anchored || TesrAnchorMath.shouldReanchor(camX, camY, camZ, group.anchorX, group.anchorY, group.anchorZ)) {
|
||||
group.anchorX = TesrAnchorMath.anchorCoord(camX);
|
||||
group.anchorY = TesrAnchorMath.anchorCoord(camY);
|
||||
group.anchorZ = TesrAnchorMath.anchorCoord(camZ);
|
||||
group.anchored = true;
|
||||
group.builtCount = -1;
|
||||
}
|
||||
source.declareUse(layer);
|
||||
}
|
||||
if (group.stream) {
|
||||
final boolean instanceable = !forceStream && instancedActive && (deferred == null || material.shader() == null);
|
||||
if (instanceable && (texMatrix == null || template.drawMode != layer.getDrawMode())) {
|
||||
group.count++;
|
||||
group.instTemplates.add(template);
|
||||
currentMV.get(matScratch);
|
||||
group.instMatrices.addElements(group.instMatrices.size(), matScratch);
|
||||
group.instLights.add(packedLight);
|
||||
group.instColors.add(colorABGR);
|
||||
return;
|
||||
}
|
||||
if (template.drawMode == layer.getDrawMode()) {
|
||||
source.getBuffer(layer, blockEntityId).addTemplateInstance(template, currentMV, scratchVec, colorABGR, packedLight, texMatrix);
|
||||
streamedInstances++;
|
||||
return;
|
||||
}
|
||||
}
|
||||
scratchMat.set(baseMVInv).mul(currentMV);
|
||||
TesrAnchorMath.toAnchorRelative(scratchMat, camX, camY, camZ, group.anchorX, group.anchorY, group.anchorZ);
|
||||
long hash = TesrAnchorMath.instanceHash(System.identityHashCode(template), scratchMat, packedLight, colorABGR);
|
||||
if (texMatrix != null) {
|
||||
hash += TesrAnchorMath.texMatrixHash(texMatrix);
|
||||
}
|
||||
if (group.streaming && template.drawMode == layer.getDrawMode()) {
|
||||
group.frameHash += hash;
|
||||
source.getBuffer(layer, blockEntityId).addTemplateInstance(template, currentMV, scratchVec, colorABGR, packedLight, texMatrix);
|
||||
streamedInstances++;
|
||||
return;
|
||||
}
|
||||
group.hashAcc += hash;
|
||||
group.count++;
|
||||
group.instTemplates.add(template);
|
||||
scratchMat.get(matScratch);
|
||||
group.instMatrices.addElements(group.instMatrices.size(), matScratch);
|
||||
group.instLights.add(packedLight);
|
||||
group.instColors.add(colorABGR);
|
||||
group.addTexMatrix(texMatrix);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasDraws(RenderLayer layer) {
|
||||
final ObjectArrayList<Group> list = byLayer.get(layer);
|
||||
if (list == null) return false;
|
||||
for (int i = 0, n = list.size(); i < n; i++) {
|
||||
final Group group = list.get(i);
|
||||
if (group.frameMark == frameMark && group.count > 0) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void drawLayer(RenderLayer layer) {
|
||||
final ObjectArrayList<Group> list = byLayer.get(layer);
|
||||
if (list == null) return;
|
||||
boolean variantResolved = false;
|
||||
boolean variantAvailable = false;
|
||||
boolean variantBound = false;
|
||||
for (int i = 0, n = list.size(); i < n; i++) {
|
||||
final Group group = list.get(i);
|
||||
if (group.frameMark != frameMark || group.count == 0) continue;
|
||||
if (group.stream && instancedActive && (deferred == null || group.material.shader() == null)) {
|
||||
restoreMV();
|
||||
if (deferred == null) {
|
||||
instancedDraws += instanced.drawGroup(group.instTemplates, group.instMatrices, group.instLights, group.instColors, group.count, nowMs);
|
||||
instancedInstances += group.count;
|
||||
continue;
|
||||
}
|
||||
if (!variantResolved) {
|
||||
variantResolved = true;
|
||||
variantAvailable = deferred.hasTesrInstancedVariant();
|
||||
}
|
||||
if (variantAvailable) {
|
||||
applyGroupRenderState(group);
|
||||
if (!variantBound) {
|
||||
variantBound = true;
|
||||
deferred.rebindCurrentPass();
|
||||
deferred.bindTesrInstancedVariant();
|
||||
}
|
||||
instancedDraws += instanced.drawGroup(group.instTemplates, group.instMatrices, group.instLights, group.instColors, group.count, nowMs);
|
||||
instancedInstances += group.count;
|
||||
} else {
|
||||
drawGroupCpuFallback(group);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
variantBound = false;
|
||||
if (group.builtCount != group.count || group.builtHash != group.hashAcc || !group.mesh.isUploaded()) {
|
||||
if (group.mesh.isUploaded()) {
|
||||
group.consecutiveRebuilds++;
|
||||
}
|
||||
rebuild(group);
|
||||
} else {
|
||||
group.consecutiveRebuilds = 0;
|
||||
}
|
||||
draw(group);
|
||||
if (group.consecutiveRebuilds >= PROMOTE_AFTER_REBUILDS && !group.streaming && group.opaque) {
|
||||
promote(group);
|
||||
}
|
||||
}
|
||||
restoreMV();
|
||||
if (variantBound) {
|
||||
deferred.rebindCurrentPass();
|
||||
}
|
||||
}
|
||||
|
||||
private void applyGroupRenderState(Group group) {
|
||||
AngelicaBufferSource.setEntityColor(group.entityColor);
|
||||
source.applyIdNoRebind(group.blockEntityId);
|
||||
}
|
||||
|
||||
private static final Matrix4f IDENTITY = new Matrix4f();
|
||||
|
||||
private void drawGroupCpuFallback(Group group) {
|
||||
AngelicaBufferSource.setEntityColor(group.entityColor);
|
||||
source.applyIdAndRebind(group.blockEntityId);
|
||||
saveMV();
|
||||
GLStateManager.setModelViewMatrix(IDENTITY);
|
||||
final VertexFormat format = group.layer.getVertexFormat();
|
||||
int start = 0;
|
||||
while (start < group.count) {
|
||||
final int drawMode = group.instTemplates.get(start).drawMode;
|
||||
int end = start;
|
||||
int totalVerts = 0;
|
||||
while (end < group.count && group.instTemplates.get(end).drawMode == drawMode) {
|
||||
totalVerts += group.instTemplates.get(end).vertexCount;
|
||||
end++;
|
||||
}
|
||||
fallbackScratch = MeshBuffer.ensureCapacity(fallbackScratch, format.getVertexSize() * totalVerts, false);
|
||||
fallbackScratch.clear();
|
||||
final long base = memAddress0(fallbackScratch);
|
||||
long ptr = base;
|
||||
for (int i = start; i < end; i++) {
|
||||
group.instMatrices.getElements(i * 16, matScratch, 0, 16);
|
||||
scratchMat.set(matScratch);
|
||||
ptr = VertexTransform.writeInstance(ptr, format, group.instTemplates.get(i), scratchMat, scratchVec, group.instColors.getInt(i), group.instLights.getInt(i), null);
|
||||
}
|
||||
fallbackScratch.position((int) (ptr - base));
|
||||
fallbackScratch.flip();
|
||||
fallbackMesh.upload(format, drawMode, fallbackScratch, totalVerts);
|
||||
fallbackMesh.render();
|
||||
streamedInstances += end - start;
|
||||
start = end;
|
||||
}
|
||||
}
|
||||
|
||||
private void promote(Group group) {
|
||||
group.streaming = true;
|
||||
streamPromotions++;
|
||||
group.count = 0;
|
||||
group.hashAcc = 0;
|
||||
group.frameHash = 0;
|
||||
group.prevFrameHash = 0;
|
||||
group.stableFrames = 0;
|
||||
group.builtCount = -1;
|
||||
group.clearInstances();
|
||||
group.mesh.delete();
|
||||
group.meshBytes = 0;
|
||||
}
|
||||
|
||||
void sweep(long now) {
|
||||
for (final ObjectArrayList<Group> list : byLayer.values()) {
|
||||
for (int i = list.size() - 1; i >= 0; i--) {
|
||||
final Group group = list.get(i);
|
||||
if (now - group.lastUsedMs <= GROUP_TTL_MS) continue;
|
||||
group.mesh.delete();
|
||||
list.remove(i);
|
||||
final Reference2ObjectOpenHashMap<TesrMaterial, Int2ObjectOpenHashMap<Group>> byMaterial = groups.get(group.layer);
|
||||
if (byMaterial != null) {
|
||||
final Int2ObjectOpenHashMap<Group> byId = byMaterial.get(group.material);
|
||||
if (byId != null) {
|
||||
byId.remove(group.blockEntityId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void clear() {
|
||||
for (final ObjectArrayList<Group> list : byLayer.values()) {
|
||||
for (int i = 0, n = list.size(); i < n; i++) {
|
||||
list.get(i).mesh.delete();
|
||||
}
|
||||
}
|
||||
byLayer.clear();
|
||||
groups.clear();
|
||||
fallbackMesh.delete();
|
||||
fallbackScratch = null;
|
||||
}
|
||||
|
||||
int groupCount() {
|
||||
int count = 0;
|
||||
for (final ObjectArrayList<Group> list : byLayer.values()) {
|
||||
count += list.size();
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
int streamingGroupCount() {
|
||||
int count = 0;
|
||||
for (final ObjectArrayList<Group> list : byLayer.values()) {
|
||||
for (int i = 0, n = list.size(); i < n; i++) {
|
||||
if (list.get(i).streaming) count++;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
long retainedBytes() {
|
||||
long bytes = 0;
|
||||
for (final ObjectArrayList<Group> list : byLayer.values()) {
|
||||
for (int i = 0, n = list.size(); i < n; i++) {
|
||||
final Group group = list.get(i);
|
||||
bytes += group.meshBytes;
|
||||
if (group.scratch != null) bytes += group.scratch.capacity();
|
||||
}
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
private void rebuild(Group group) {
|
||||
rebuilds++;
|
||||
group.rebuildsWindow++;
|
||||
if (Tracy.ENABLED) {
|
||||
Tracy.beginZone(Z_TESR_REBUILD);
|
||||
Tracy.zoneText(attribution(group));
|
||||
}
|
||||
try {
|
||||
rebuildInner(group);
|
||||
} finally {
|
||||
if (Tracy.ENABLED) Tracy.endZone();
|
||||
}
|
||||
}
|
||||
|
||||
void collectRebuilders(ObjectArrayList<Group> out) {
|
||||
for (final ObjectArrayList<Group> list : byLayer.values()) {
|
||||
for (int i = 0, n = list.size(); i < n; i++) {
|
||||
final Group group = list.get(i);
|
||||
if (group.rebuildsWindow > 0) out.add(group);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static String attribution(Group group) {
|
||||
final StringBuilder sb = new StringBuilder();
|
||||
if (group.renderableClass != null) {
|
||||
sb.append(group.renderableClass.getSimpleName());
|
||||
} else {
|
||||
sb.append("id").append(group.blockEntityId);
|
||||
}
|
||||
final ResourceLocation tex = group.layer.getTextureId();
|
||||
if (tex != null) {
|
||||
final String path = tex.getResourcePath();
|
||||
sb.append(' ').append(path, path.lastIndexOf('/') + 1, path.length());
|
||||
}
|
||||
sb.append('/').append(group.material.transparency());
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private void rebuildInner(Group group) {
|
||||
final VertexFormat format = group.layer.getVertexFormat();
|
||||
int totalVerts = 0;
|
||||
for (int i = 0, n = group.instTemplates.size(); i < n; i++) {
|
||||
totalVerts += group.instTemplates.get(i).vertexCount;
|
||||
}
|
||||
final int bytes = format.getVertexSize() * totalVerts;
|
||||
group.scratch = MeshBuffer.ensureCapacity(group.scratch, bytes, false);
|
||||
group.scratch.clear();
|
||||
final long base = memAddress0(group.scratch);
|
||||
long ptr = base;
|
||||
for (int i = 0, n = group.count; i < n; i++) {
|
||||
group.instMatrices.getElements(i * 16, matScratch, 0, 16);
|
||||
scratchMat.set(matScratch);
|
||||
final int light = group.instLights.getInt(i);
|
||||
final int color = group.instColors.getInt(i);
|
||||
final TemplateBuffer template = group.instTemplates.get(i);
|
||||
ptr = VertexTransform.writeInstance(ptr, format, template, scratchMat, scratchVec, color, light, group.instTexMatrices.get(i));
|
||||
}
|
||||
group.scratch.position((int) (ptr - base));
|
||||
group.scratch.flip();
|
||||
group.builtVertexCount = totalVerts;
|
||||
group.mesh.upload(format, group.layer.getDrawMode(), group.scratch, group.builtVertexCount, true);
|
||||
group.meshBytes = bytes;
|
||||
group.builtHash = group.hashAcc;
|
||||
group.builtCount = group.count;
|
||||
}
|
||||
|
||||
private void draw(Group group) {
|
||||
retainedDraws++;
|
||||
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);
|
||||
group.mesh.render();
|
||||
}
|
||||
|
||||
private void saveMV() {
|
||||
if (!mvSaved) {
|
||||
mvSaved = true;
|
||||
savedMV.set(GLStateManager.getModelViewMatrix());
|
||||
}
|
||||
}
|
||||
|
||||
private void restoreMV() {
|
||||
if (mvSaved) {
|
||||
mvSaved = false;
|
||||
GLStateManager.setModelViewMatrix(savedMV);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.gtnewhorizons.angelica.rendering.tesr;
|
||||
|
||||
public final class TemplateBuffer {
|
||||
|
||||
public final int[] data;
|
||||
final int[] work;
|
||||
public final int vertexCount;
|
||||
public final int drawMode;
|
||||
|
||||
public TemplateBuffer(int[] data, int vertexCount, int drawMode) {
|
||||
this.data = data;
|
||||
this.work = data.clone();
|
||||
this.vertexCount = vertexCount;
|
||||
this.drawMode = drawMode;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.gtnewhorizons.angelica.rendering.tesr;
|
||||
|
||||
import org.joml.Matrix4f;
|
||||
|
||||
public final class TesrAnchorMath {
|
||||
|
||||
public static final int ANCHOR_GRID = 16;
|
||||
public static final double REANCHOR_DISTANCE = 512.0;
|
||||
private static final float HASH_QUANT = 4096f;
|
||||
|
||||
private TesrAnchorMath() {}
|
||||
|
||||
public static long anchorCoord(double cam) {
|
||||
return (long) Math.floor(cam / ANCHOR_GRID) * ANCHOR_GRID;
|
||||
}
|
||||
|
||||
public static boolean shouldReanchor(double camX, double camY, double camZ, long anchorX, long anchorY, long anchorZ) {
|
||||
final double dx = camX - anchorX;
|
||||
final double dy = camY - anchorY;
|
||||
final double dz = camZ - anchorZ;
|
||||
return dx * dx + dy * dy + dz * dz > REANCHOR_DISTANCE * REANCHOR_DISTANCE;
|
||||
}
|
||||
|
||||
public static void toAnchorRelative(Matrix4f m, double camX, double camY, double camZ, long anchorX, long anchorY, long anchorZ) {
|
||||
m.m30(m.m30() + (float) (camX - anchorX));
|
||||
m.m31(m.m31() + (float) (camY - anchorY));
|
||||
m.m32(m.m32() + (float) (camZ - anchorZ));
|
||||
}
|
||||
|
||||
public static long instanceHash(int templateIdentity, Matrix4f mA, int packedLight, int colorABGR) {
|
||||
long h = templateIdentity * 0x9E3779B97F4A7C15L;
|
||||
h = mix(h, quantize(mA.m00()));
|
||||
h = mix(h, quantize(mA.m01()));
|
||||
h = mix(h, quantize(mA.m02()));
|
||||
h = mix(h, quantize(mA.m10()));
|
||||
h = mix(h, quantize(mA.m11()));
|
||||
h = mix(h, quantize(mA.m12()));
|
||||
h = mix(h, quantize(mA.m20()));
|
||||
h = mix(h, quantize(mA.m21()));
|
||||
h = mix(h, quantize(mA.m22()));
|
||||
h = mix(h, quantize(mA.m30()));
|
||||
h = mix(h, quantize(mA.m31()));
|
||||
h = mix(h, quantize(mA.m32()));
|
||||
h = mix(h, packedLight);
|
||||
h = mix(h, colorABGR);
|
||||
return avalanche(h);
|
||||
}
|
||||
|
||||
public static long texMatrixHash(Matrix4f t) {
|
||||
long h = 0x2545F4914F6CDD1DL;
|
||||
h = mix(h, quantize(t.m00()));
|
||||
h = mix(h, quantize(t.m01()));
|
||||
h = mix(h, quantize(t.m10()));
|
||||
h = mix(h, quantize(t.m11()));
|
||||
h = mix(h, quantize(t.m30()));
|
||||
h = mix(h, quantize(t.m31()));
|
||||
return avalanche(h);
|
||||
}
|
||||
|
||||
private static int quantize(float v) {
|
||||
return Math.round(v * HASH_QUANT);
|
||||
}
|
||||
|
||||
private static long mix(long h, int v) {
|
||||
h ^= v;
|
||||
h *= 0xFF51AFD7ED558CCDL;
|
||||
return Long.rotateLeft(h, 31);
|
||||
}
|
||||
|
||||
private static long avalanche(long h) {
|
||||
h ^= h >>> 33;
|
||||
h *= 0xFF51AFD7ED558CCDL;
|
||||
h ^= h >>> 29;
|
||||
h *= 0xC4CEB9FE1A85EC53L;
|
||||
h ^= h >>> 32;
|
||||
return h;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.gtnewhorizons.angelica.rendering.tesr;
|
||||
|
||||
public final class TesrAttribution {
|
||||
private TesrAttribution() {}
|
||||
|
||||
public static Class<?> currentRenderable;
|
||||
}
|
||||
@@ -0,0 +1,481 @@
|
||||
package com.gtnewhorizons.angelica.rendering.tesr;
|
||||
|
||||
import com.gtnewhorizon.gtnhlib.client.renderer.MatrixHelper;
|
||||
import com.gtnewhorizon.gtnhlib.client.renderer.cel.api.util.ColorABGR;
|
||||
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
|
||||
import com.gtnewhorizons.angelica.api.tesr.TesrMaterial;
|
||||
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.ffp.ShaderManager;
|
||||
import com.gtnewhorizons.angelica.glsm.hooks.GLSMConfig;
|
||||
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
|
||||
import com.gtnewhorizons.angelica.glsm.states.Color4;
|
||||
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
|
||||
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
|
||||
import net.coderbot.batchedentityrendering.impl.AngelicaBufferSource;
|
||||
import net.coderbot.batchedentityrendering.impl.SegmentedBufferBuilder;
|
||||
import net.coderbot.batchedentityrendering.impl.TransparencyType;
|
||||
import net.coderbot.iris.Iris;
|
||||
import net.coderbot.iris.layer.GbufferPrograms;
|
||||
import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline;
|
||||
import net.coderbot.iris.pipeline.FixedFunctionWorldRenderingPipeline;
|
||||
import net.coderbot.iris.pipeline.WorldRenderingPhase;
|
||||
import net.coderbot.iris.pipeline.WorldRenderingPipeline;
|
||||
import net.coderbot.iris.uniforms.CapturedRenderingState;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.renderer.EntityRenderer;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import org.joml.Matrix4f;
|
||||
import org.joml.Vector3f;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
import org.lwjgl.opengl.GL13;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0;
|
||||
|
||||
public final class TesrBatchRenderer {
|
||||
|
||||
public static final TesrBatchRenderer INSTANCE = new TesrBatchRenderer();
|
||||
|
||||
public static final int PASS_MAIN_0 = 0;
|
||||
public static final int PASS_MAIN_1 = 1;
|
||||
public static final int PASS_SHADOW = 2;
|
||||
private static final int PASS_COUNT = 3;
|
||||
|
||||
private static final long SWEEP_INTERVAL_MS = 5_000L;
|
||||
|
||||
private static final Tracy.ZoneId Z_TESR_OPAQUE = Tracy.zoneId("tesrOpaque", Tracy.COLOR_CLIENT);
|
||||
private static final Tracy.ZoneId Z_TESR_BATCH = Tracy.zoneId("tesrBatch", Tracy.COLOR_CLIENT);
|
||||
private static final Tracy.ZoneId Z_TESR_INSTANCED = Tracy.zoneId("tesrInstanced", Tracy.COLOR_CLIENT);
|
||||
private static final Tracy.ZoneId Z_TESR_TEXT = Tracy.zoneId("tesrText", Tracy.COLOR_CLIENT);
|
||||
private static final Tracy.ZoneId Z_TESR_DEFERRED = Tracy.zoneId("tesrDeferred", Tracy.COLOR_CLIENT);
|
||||
|
||||
private final AngelicaBufferSource bufferSource = new AngelicaBufferSource();
|
||||
private final RetainedTesrGroups[] retained = new RetainedTesrGroups[PASS_COUNT];
|
||||
final InstancedTemplateRenderer instancedRenderer = new InstancedTemplateRenderer();
|
||||
private int activePass = -1;
|
||||
private long lastSweepMs;
|
||||
private boolean deferredFlushPending;
|
||||
private RetainedTesrGroups pendingDeferredHook;
|
||||
|
||||
private final Matrix4f modelView = new Matrix4f();
|
||||
private final Matrix4f identity = new Matrix4f();
|
||||
private final Vector3f scratchVec = new Vector3f();
|
||||
|
||||
private TesrBatchRenderer() {
|
||||
for (int i = 0; i < PASS_COUNT; i++) {
|
||||
retained[i] = new RetainedTesrGroups(bufferSource);
|
||||
}
|
||||
}
|
||||
|
||||
public void beginPass(int passKey, Matrix4f baseMV, double camX, double camY, double camZ) {
|
||||
if (deferredFlushPending) {
|
||||
discardDeferred();
|
||||
}
|
||||
activePass = passKey;
|
||||
retained[passKey].beginPass(baseMV, camX, camY, camZ, instancedCapable() ? instancedRenderer : null, deferredPipeline());
|
||||
if (passKey == PASS_MAIN_0) {
|
||||
final long now = System.currentTimeMillis();
|
||||
if (now - lastSweepMs >= SWEEP_INTERVAL_MS) {
|
||||
lastSweepMs = now;
|
||||
for (int i = 0; i < PASS_COUNT; i++) {
|
||||
retained[i].sweep(now);
|
||||
}
|
||||
instancedRenderer.sweep(now);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static boolean instancedCapable() {
|
||||
if (!ShaderManager.getInstance().isEnabled()) return false;
|
||||
if (!Iris.enabled) return true;
|
||||
final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable();
|
||||
if (pipeline == null || pipeline instanceof FixedFunctionWorldRenderingPipeline) return true;
|
||||
return pipeline instanceof DeferredWorldRenderingPipeline deferred && deferred.supportsTesrInstancing();
|
||||
}
|
||||
|
||||
static DeferredWorldRenderingPipeline deferredPipeline() {
|
||||
if (!Iris.enabled) return null;
|
||||
return Iris.getPipelineManager().getPipelineNullable() instanceof DeferredWorldRenderingPipeline deferred
|
||||
? deferred : null;
|
||||
}
|
||||
|
||||
private void discardDeferred() {
|
||||
deferredFlushPending = false;
|
||||
pendingDeferredHook = null;
|
||||
bufferSource.discard();
|
||||
BatchingFontRenderer.discardDeferredText();
|
||||
}
|
||||
|
||||
public void clearRetained() {
|
||||
discardDeferred();
|
||||
for (int i = 0; i < PASS_COUNT; i++) {
|
||||
retained[i].clear();
|
||||
}
|
||||
instancedRenderer.clear();
|
||||
immediateMesh.delete();
|
||||
immediateScratch = null;
|
||||
bufferSource.freeBuffers();
|
||||
AngelicaTesrMeshCache.INSTANCE.clear();
|
||||
}
|
||||
|
||||
public boolean hasActivePass() {
|
||||
return activePass >= 0;
|
||||
}
|
||||
|
||||
public void queue(TemplateBuffer template, ResourceLocation texture, TesrMaterial material) {
|
||||
modelView.set(GLStateManager.getModelViewMatrix());
|
||||
final int packedLight = currentPackedLight(material);
|
||||
final int colorABGR = resolveColor(material);
|
||||
if (activePass >= 0) {
|
||||
final RenderLayer layer = layerFor(texture, material);
|
||||
final int blockEntityId = CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity();
|
||||
retained[activePass].queue(template, layer, material, modelView, packedLight, colorABGR, blockEntityId, captureTextureMatrix(), false);
|
||||
} else {
|
||||
drawImmediate(template, texture, material, packedLight, colorABGR);
|
||||
}
|
||||
}
|
||||
|
||||
private static Matrix4f captureTextureMatrix() {
|
||||
final Matrix4f texMatrix = GLStateManager.getTextures().getTextureUnitMatrix(0);
|
||||
return MatrixHelper.isIdentity(texMatrix) ? null : texMatrix;
|
||||
}
|
||||
|
||||
static final class LayerKey {
|
||||
ResourceLocation texture;
|
||||
TesrMaterial.Transparency transparency;
|
||||
boolean noCull;
|
||||
boolean unlit;
|
||||
boolean noDepthWrite;
|
||||
boolean depthOnly;
|
||||
float cutoutAlpha;
|
||||
boolean depthEqual;
|
||||
TesrMaterial.SpecialRender special;
|
||||
TesrShader shader;
|
||||
boolean noPass;
|
||||
|
||||
LayerKey set(ResourceLocation texture, TesrMaterial.Transparency transparency, boolean noCull, boolean unlit, boolean noDepthWrite, boolean depthOnly, float cutoutAlpha, boolean depthEqual, TesrMaterial.SpecialRender special, TesrShader shader, boolean noPass) {
|
||||
this.texture = texture;
|
||||
this.transparency = transparency;
|
||||
this.noCull = noCull;
|
||||
this.unlit = unlit;
|
||||
this.noDepthWrite = noDepthWrite;
|
||||
this.depthOnly = depthOnly;
|
||||
this.cutoutAlpha = cutoutAlpha;
|
||||
this.depthEqual = depthEqual;
|
||||
this.special = special;
|
||||
this.shader = shader;
|
||||
this.noPass = noPass;
|
||||
return this;
|
||||
}
|
||||
|
||||
LayerKey copy() {
|
||||
return new LayerKey().set(texture, transparency, noCull, unlit, noDepthWrite, depthOnly, cutoutAlpha, depthEqual, special, shader, noPass);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (!(o instanceof LayerKey other)) return false;
|
||||
return Objects.equals(texture, other.texture) && transparency == other.transparency
|
||||
&& noCull == other.noCull && unlit == other.unlit && noDepthWrite == other.noDepthWrite
|
||||
&& depthOnly == other.depthOnly
|
||||
&& Float.floatToIntBits(cutoutAlpha) == Float.floatToIntBits(other.cutoutAlpha)
|
||||
&& depthEqual == other.depthEqual && special == other.special && shader == other.shader && noPass == other.noPass;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int h = Objects.hashCode(texture);
|
||||
h = h * 31 + Objects.hashCode(transparency);
|
||||
h = h * 31 + (noCull ? 1 : 0);
|
||||
h = h * 31 + (unlit ? 1 : 0);
|
||||
h = h * 31 + (noDepthWrite ? 1 : 0);
|
||||
h = h * 31 + (depthOnly ? 1 : 0);
|
||||
h = h * 31 + Float.floatToIntBits(cutoutAlpha);
|
||||
h = h * 31 + (depthEqual ? 1 : 0);
|
||||
h = h * 31 + Objects.hashCode(special);
|
||||
h = h * 31 + System.identityHashCode(shader);
|
||||
h = h * 31 + (noPass ? 1 : 0);
|
||||
return h;
|
||||
}
|
||||
}
|
||||
|
||||
private final Object2ObjectOpenHashMap<LayerKey, RenderLayer> layers = new Object2ObjectOpenHashMap<>();
|
||||
private final LayerKey scratchKey = new LayerKey();
|
||||
private ResourceLocation lastLayerTexture;
|
||||
private TesrMaterial lastLayerMaterial;
|
||||
private RenderLayer lastLayer;
|
||||
private ResourceLocation lastImmediateTexture;
|
||||
private TesrMaterial lastImmediateMaterial;
|
||||
private RenderLayer lastImmediateLayer;
|
||||
|
||||
private RenderLayer layerFor(ResourceLocation texture, TesrMaterial material) {
|
||||
if (texture == lastLayerTexture && material == lastLayerMaterial) {
|
||||
return lastLayer;
|
||||
}
|
||||
final RenderLayer layer = layerLookup(texture, material, false);
|
||||
lastLayerTexture = texture;
|
||||
lastLayerMaterial = material;
|
||||
lastLayer = layer;
|
||||
return layer;
|
||||
}
|
||||
|
||||
private RenderLayer noPassLayerFor(ResourceLocation texture, TesrMaterial material) {
|
||||
if (texture == lastImmediateTexture && material == lastImmediateMaterial) {
|
||||
return lastImmediateLayer;
|
||||
}
|
||||
final RenderLayer layer = layerLookup(texture, material, true);
|
||||
lastImmediateTexture = texture;
|
||||
lastImmediateMaterial = material;
|
||||
lastImmediateLayer = layer;
|
||||
return layer;
|
||||
}
|
||||
|
||||
private RenderLayer layerLookup(ResourceLocation texture, TesrMaterial material, boolean noPass) {
|
||||
final LayerKey key = scratchKey.set(texture, material.transparency(), material.isNoCull(), material.isUnlit(), material.isNoDepthWrite(), material.isDepthOnly(), material.cutoutAlpha(), material.isDepthEqual(), material.special(), material.shader(), noPass);
|
||||
RenderLayer layer = layers.get(key);
|
||||
if (layer == null) {
|
||||
layer = noPass ? RenderLayer.tesrNoPass(texture, material) : RenderLayer.tesr(texture, material);
|
||||
layers.put(key.copy(), layer);
|
||||
}
|
||||
return layer;
|
||||
}
|
||||
|
||||
private static int currentPackedLight(TesrMaterial material) {
|
||||
if (material.hasLightmap()) {
|
||||
return ((int) material.lightmapY() << 16) | ((int) material.lightmapX() & 0xFFFF);
|
||||
}
|
||||
return ((int) GLSMConfig.lastBrightnessY << 16) | ((int) GLSMConfig.lastBrightnessX & 0xFFFF);
|
||||
}
|
||||
|
||||
private static int resolveColor(TesrMaterial material) {
|
||||
if (material.hasColor()) {
|
||||
return ColorABGR.pack(material.colorRed(), material.colorGreen(), material.colorBlue(), material.colorAlpha());
|
||||
}
|
||||
final Color4 color = GLStateManager.getColor();
|
||||
return ColorABGR.pack(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());
|
||||
}
|
||||
|
||||
public void flush() {
|
||||
final RetainedTesrGroups hook = activePass >= 0 ? retained[activePass] : null;
|
||||
if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_OPAQUE);
|
||||
try {
|
||||
bufferSource.endBatchWithType(TransparencyType.OPAQUE, hook);
|
||||
} finally {
|
||||
if (Tracy.ENABLED) Tracy.endZone();
|
||||
}
|
||||
if (activePass == PASS_MAIN_0 && deferredPipeline() != null) {
|
||||
bufferSource.pauseBatch();
|
||||
pendingDeferredHook = hook;
|
||||
deferredFlushPending = true;
|
||||
activePass = -1;
|
||||
return;
|
||||
}
|
||||
if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_BATCH);
|
||||
try {
|
||||
bufferSource.endBatch(hook);
|
||||
} finally {
|
||||
if (Tracy.ENABLED) Tracy.endZone();
|
||||
}
|
||||
if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_INSTANCED);
|
||||
try {
|
||||
instancedRenderer.endFrame();
|
||||
} finally {
|
||||
if (Tracy.ENABLED) Tracy.endZone();
|
||||
}
|
||||
if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_TEXT);
|
||||
try {
|
||||
BatchingFontRenderer.flushDeferredText();
|
||||
} finally {
|
||||
if (Tracy.ENABLED) Tracy.endZone();
|
||||
}
|
||||
activePass = -1;
|
||||
}
|
||||
|
||||
public void flushAfterDeferred() {
|
||||
if (!deferredFlushPending) return;
|
||||
deferredFlushPending = false;
|
||||
final RetainedTesrGroups hook = pendingDeferredHook;
|
||||
pendingDeferredHook = null;
|
||||
if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_DEFERRED);
|
||||
try {
|
||||
final EntityRenderer entityRenderer = Minecraft.getMinecraft().entityRenderer;
|
||||
final boolean savedDepthMask = GLStateManager.getDepthState().isEnabled();
|
||||
final boolean savedBlend = GLStateManager.getBlendMode().isEnabled();
|
||||
final int savedSrcRgb = GLStateManager.getBlendState().getSrcRgb();
|
||||
final int savedDstRgb = GLStateManager.getBlendState().getDstRgb();
|
||||
final int savedSrcAlpha = GLStateManager.getBlendState().getSrcAlpha();
|
||||
final int savedDstAlpha = GLStateManager.getBlendState().getDstAlpha();
|
||||
final boolean savedAlphaTest = GLStateManager.getAlphaTest().isEnabled();
|
||||
final int savedAlphaFunc = GLStateManager.getAlphaState().getFunction();
|
||||
final float savedAlphaRef = GLStateManager.getAlphaState().getReference();
|
||||
|
||||
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.beginBlockEntities();
|
||||
try {
|
||||
bufferSource.endBatch(hook);
|
||||
instancedRenderer.endFrame();
|
||||
AngelicaBufferSource.rebindPass();
|
||||
BatchingFontRenderer.flushDeferredText();
|
||||
} finally {
|
||||
if (wrap) GbufferPrograms.endBlockEntities();
|
||||
entityRenderer.disableLightmap(0);
|
||||
GLStateManager.glDepthMask(savedDepthMask);
|
||||
if (savedBlend) GLStateManager.enableBlend(); else GLStateManager.disableBlend();
|
||||
GLStateManager.tryBlendFuncSeparate(savedSrcRgb, savedDstRgb, savedSrcAlpha, savedDstAlpha);
|
||||
if (savedAlphaTest) GLStateManager.enableAlphaTest(); else GLStateManager.disableAlphaTest();
|
||||
GLStateManager.glAlphaFunc(savedAlphaFunc, savedAlphaRef);
|
||||
}
|
||||
} finally {
|
||||
if (Tracy.ENABLED) Tracy.endZone();
|
||||
}
|
||||
}
|
||||
|
||||
private long lastRebuilds, lastRetainedDraws, lastStreamed, lastInstInstances;
|
||||
private long lastSummaryNanos;
|
||||
|
||||
public String getDebugSummaryLine() {
|
||||
long rebuilds = 0, retainedDraws = 0, streamed = 0, instInstances = 0, retainedBytes = 0;
|
||||
int groupCount = 0, streamingCount = 0;
|
||||
for (int i = 0; i < PASS_COUNT; i++) {
|
||||
final RetainedTesrGroups r = retained[i];
|
||||
rebuilds += r.rebuilds;
|
||||
retainedDraws += r.retainedDraws;
|
||||
streamed += r.streamedInstances;
|
||||
instInstances += r.instancedInstances;
|
||||
retainedBytes += r.retainedBytes();
|
||||
groupCount += r.groupCount();
|
||||
streamingCount += r.streamingGroupCount();
|
||||
}
|
||||
final long now = System.nanoTime();
|
||||
final long elapsed = now - lastSummaryNanos;
|
||||
final String line = String.format("TESR: %d grp (%d strm), reb %d/s, drw %d/s, inst %d/s, stream %d/s, mem %.1fMB",
|
||||
groupCount, streamingCount,
|
||||
perSecond(rebuilds - lastRebuilds, elapsed),
|
||||
perSecond(retainedDraws - lastRetainedDraws, elapsed),
|
||||
perSecond(instInstances - lastInstInstances, elapsed),
|
||||
perSecond(streamed - lastStreamed, elapsed),
|
||||
(retainedBytes + bufferSource.allocatedBytes() + instancedRenderer.meshBytes()) / 1048576.0);
|
||||
lastSummaryNanos = now;
|
||||
lastRebuilds = rebuilds;
|
||||
lastRetainedDraws = retainedDraws;
|
||||
lastStreamed = streamed;
|
||||
lastInstInstances = instInstances;
|
||||
return line;
|
||||
}
|
||||
|
||||
private static long perSecond(long delta, long elapsedNanos) {
|
||||
return elapsedNanos <= 0 ? 0 : delta * 1_000_000_000L / elapsedNanos;
|
||||
}
|
||||
|
||||
public List<String> getDebugDetailStrings() {
|
||||
long retainedBytes = 0;
|
||||
for (int i = 0; i < PASS_COUNT; i++) {
|
||||
retainedBytes += retained[i].retainedBytes();
|
||||
}
|
||||
final String mem = String.format("TESR mem: ret %.1fMB, seg %.1fMB, tmpl %d/%.1fMB, cache %d",
|
||||
retainedBytes / 1048576.0, bufferSource.allocatedBytes() / 1048576.0,
|
||||
instancedRenderer.meshCount(), instancedRenderer.meshBytes() / 1048576.0,
|
||||
AngelicaTesrMeshCache.INSTANCE.size());
|
||||
final String attribution = rebuildAttributionLine();
|
||||
return attribution == null ? Arrays.asList(mem) : Arrays.asList(mem, attribution);
|
||||
}
|
||||
|
||||
private final ObjectArrayList<RetainedTesrGroups.Group> rebuilders = new ObjectArrayList<>();
|
||||
|
||||
private String rebuildAttributionLine() {
|
||||
rebuilders.clear();
|
||||
for (int i = 0; i < PASS_COUNT; i++) {
|
||||
retained[i].collectRebuilders(rebuilders);
|
||||
}
|
||||
if (rebuilders.isEmpty()) return null;
|
||||
rebuilders.sort((a, b) -> Integer.compare(b.rebuildsWindow, a.rebuildsWindow));
|
||||
final StringBuilder sb = new StringBuilder("TESR reb:");
|
||||
final int shown = Math.min(3, rebuilders.size());
|
||||
for (int i = 0; i < shown; i++) {
|
||||
final RetainedTesrGroups.Group group = rebuilders.get(i);
|
||||
if (i > 0) sb.append(',');
|
||||
sb.append(' ').append(group.rebuildsWindow).append("x ").append(RetainedTesrGroups.attribution(group)).append(' ').append(group.builtVertexCount).append('v');
|
||||
}
|
||||
if (rebuilders.size() > shown) {
|
||||
sb.append(" +").append(rebuilders.size() - shown);
|
||||
}
|
||||
for (int i = 0, n = rebuilders.size(); i < n; i++) {
|
||||
rebuilders.get(i).rebuildsWindow = 0;
|
||||
}
|
||||
rebuilders.clear();
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public long statRebuilds() { return sumStat(0); }
|
||||
public long statRetainedDraws() { return sumStat(1); }
|
||||
public long statInstancedDraws() { return sumStat(2); }
|
||||
public long statInstancedInstances() { return sumStat(3); }
|
||||
public long statStreamedInstances() { return sumStat(4); }
|
||||
public long statVolatilePromotions() { return sumStat(5); }
|
||||
|
||||
private long sumStat(int which) {
|
||||
long v = 0;
|
||||
for (int i = 0; i < PASS_COUNT; i++) {
|
||||
final RetainedTesrGroups r = retained[i];
|
||||
v += switch (which) {
|
||||
case 0 -> r.rebuilds;
|
||||
case 1 -> r.retainedDraws;
|
||||
case 2 -> r.instancedDraws;
|
||||
case 3 -> r.instancedInstances;
|
||||
case 4 -> r.streamedInstances;
|
||||
default -> r.streamPromotions;
|
||||
};
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
public long statRetainedBytes() {
|
||||
long v = 0;
|
||||
for (int i = 0; i < PASS_COUNT; i++) {
|
||||
v += retained[i].retainedBytes();
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
public long statBufferSourceBytes() {
|
||||
return bufferSource.allocatedBytes();
|
||||
}
|
||||
|
||||
private final MeshBuffer immediateMesh = new MeshBuffer();
|
||||
private ByteBuffer immediateScratch;
|
||||
|
||||
private void drawImmediate(TemplateBuffer template, ResourceLocation texture, TesrMaterial material, int packedLight, int colorABGR) {
|
||||
final int vertexCount = template.vertexCount;
|
||||
if (vertexCount == 0) return;
|
||||
final VertexFormat format = SegmentedBufferBuilder.FORMAT;
|
||||
final int bytes = format.getVertexSize() * vertexCount;
|
||||
immediateScratch = MeshBuffer.ensureCapacity(immediateScratch, bytes, false);
|
||||
immediateScratch.clear();
|
||||
final long addr = memAddress0(immediateScratch);
|
||||
final long end = VertexTransform.writeInstance(addr, format, template, identity, scratchVec, colorABGR, packedLight, null);
|
||||
immediateScratch.position((int) (end - addr));
|
||||
immediateScratch.flip();
|
||||
final RenderLayer layer = noPassLayerFor(texture, material);
|
||||
GLStateManager.glPushAttrib(AngelicaBufferSource.SAVED_STATE_BITS);
|
||||
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
|
||||
layer.startDrawing();
|
||||
immediateMesh.upload(format, template.drawMode, immediateScratch, vertexCount);
|
||||
immediateMesh.render();
|
||||
layer.endDrawing();
|
||||
GLStateManager.glPopAttrib();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.gtnewhorizons.angelica.rendering.tesr;
|
||||
|
||||
import com.gtnewhorizons.angelica.api.tesr.TesrMeshProvider;
|
||||
import com.gtnewhorizons.angelica.glsm.GLStateManager;
|
||||
import it.unimi.dsi.fastutil.ints.Int2IntMap;
|
||||
import it.unimi.dsi.fastutil.objects.Reference2ObjectMap;
|
||||
import net.coderbot.iris.block_rendering.BlockRenderingSettings;
|
||||
import net.coderbot.iris.uniforms.CapturedRenderingState;
|
||||
import net.minecraft.block.Block;
|
||||
import net.minecraft.tileentity.TileEntity;
|
||||
|
||||
public final class TesrProviderDispatch {
|
||||
|
||||
private TesrProviderDispatch() {}
|
||||
|
||||
public static int resolveBlockEntityId(TileEntity te) {
|
||||
if (te == null) return 0;
|
||||
final Block block = te.getBlockType();
|
||||
if (block == null) return 0;
|
||||
final Reference2ObjectMap<Block, Int2IntMap> matches = BlockRenderingSettings.INSTANCE.getBlockMetaMatches();
|
||||
if (matches == null) return 0;
|
||||
final Int2IntMap metaMap = matches.get(block);
|
||||
if (metaMap == null) return 0;
|
||||
return Math.max(0, metaMap.get(te.getBlockMetadata()));
|
||||
}
|
||||
|
||||
public static boolean tryRender(Object renderer, TileEntity te, double x, double y, double z) {
|
||||
if (!(renderer instanceof TesrMeshProvider provider)) return false;
|
||||
final Object key = provider.angelica$meshKey(te);
|
||||
if (key == null) return false;
|
||||
|
||||
CapturedRenderingState.INSTANCE.setCurrentBlockEntity(resolveBlockEntityId(te));
|
||||
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);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package com.gtnewhorizons.angelica.rendering.tesr;
|
||||
|
||||
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat;
|
||||
import com.gtnewhorizons.angelica.api.tesr.TesrMaterial;
|
||||
import com.gtnewhorizons.angelica.api.tesr.TesrMeshBuilder;
|
||||
import com.gtnewhorizons.angelica.api.tesr.TesrMeshSink;
|
||||
import com.gtnewhorizons.angelica.glsm.GLStateManager;
|
||||
import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap;
|
||||
import net.minecraft.client.model.ModelChest;
|
||||
import net.minecraft.client.model.ModelRenderer;
|
||||
import net.minecraft.client.model.ModelSign;
|
||||
import net.minecraft.client.model.ModelSkeletonHead;
|
||||
import net.minecraft.client.renderer.Tessellator;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/** Cached-mesh entry points for the vanilla chest/sign/skull TESR mixins. */
|
||||
public final class VanillaModelMeshes {
|
||||
|
||||
private static final float MODEL_SCALE = 0.0625f;
|
||||
private static final float LID_CLOSED_EPS = 1.0e-4f;
|
||||
private static final TesrMaterial WHITE = TesrMaterial.builder().color(1f, 1f, 1f, 1f).build();
|
||||
private static final ResourceLocation SIGN_TEXTURE = new ResourceLocation("textures/entity/sign.png");
|
||||
|
||||
private static final class ChestKeys {
|
||||
final Object closed = new Object();
|
||||
final Object base = new Object();
|
||||
final Object lid = new Object();
|
||||
final Object knob = new Object();
|
||||
}
|
||||
|
||||
private static final Reference2ObjectOpenHashMap<ResourceLocation, ChestKeys> SINGLE_CHEST_KEYS = new Reference2ObjectOpenHashMap<>();
|
||||
private static final Reference2ObjectOpenHashMap<ResourceLocation, ChestKeys> DOUBLE_CHEST_KEYS = new Reference2ObjectOpenHashMap<>();
|
||||
private static final Object KEY_SIGN_STANDING = new Object();
|
||||
private static final Object KEY_SIGN_WALL = new Object();
|
||||
|
||||
private record SkullKey(ModelSkeletonHead model, ResourceLocation texture) {}
|
||||
|
||||
private static final Map<SkullKey, Object> SKULL_KEYS = new HashMap<>();
|
||||
|
||||
private static final Builder BUILDER = new Builder();
|
||||
|
||||
private VanillaModelMeshes() {}
|
||||
|
||||
public static void renderChest(ModelChest model, ResourceLocation texture, boolean isDouble) {
|
||||
final float lidAngle = model.chestLid.rotateAngleX;
|
||||
final ChestKeys keys = chestKeys(texture, isDouble);
|
||||
if (Math.abs(lidAngle) <= LID_CLOSED_EPS) {
|
||||
BUILDER.set(texture, MODEL_SCALE, model.chestLid, model.chestKnob, model.chestBelow);
|
||||
AngelicaTesrMeshCache.INSTANCE.renderCached(keys.closed, BUILDER);
|
||||
return;
|
||||
}
|
||||
BUILDER.set(texture, MODEL_SCALE, model.chestBelow, null, null);
|
||||
AngelicaTesrMeshCache.INSTANCE.renderCached(keys.base, BUILDER);
|
||||
renderRotatedPart(keys.lid, texture, model.chestLid, lidAngle);
|
||||
renderRotatedPart(keys.knob, texture, model.chestKnob, lidAngle);
|
||||
}
|
||||
|
||||
private static ChestKeys chestKeys(ResourceLocation texture, boolean isDouble) {
|
||||
final Reference2ObjectOpenHashMap<ResourceLocation, ChestKeys> keys = isDouble ? DOUBLE_CHEST_KEYS : SINGLE_CHEST_KEYS;
|
||||
ChestKeys k = keys.get(texture);
|
||||
if (k == null) {
|
||||
k = new ChestKeys();
|
||||
keys.put(texture, k);
|
||||
}
|
||||
return k;
|
||||
}
|
||||
|
||||
private static void renderRotatedPart(Object key, ResourceLocation texture, ModelRenderer part, float angleX) {
|
||||
GLStateManager.glPushMatrix();
|
||||
GLStateManager.glTranslatef(part.offsetX + part.rotationPointX * MODEL_SCALE, part.offsetY + part.rotationPointY * MODEL_SCALE, part.offsetZ + part.rotationPointZ * MODEL_SCALE);
|
||||
GLStateManager.glRotatef(angleX * (180f / (float) Math.PI), 1.0f, 0.0f, 0.0f);
|
||||
BUILDER.setLocal(texture, MODEL_SCALE, part);
|
||||
AngelicaTesrMeshCache.INSTANCE.renderCached(key, BUILDER);
|
||||
GLStateManager.glPopMatrix();
|
||||
}
|
||||
|
||||
public static void renderSign(ModelSign model) {
|
||||
final boolean standing = model.signStick.showModel;
|
||||
BUILDER.set(SIGN_TEXTURE, MODEL_SCALE, model.signBoard, standing ? model.signStick : null, null);
|
||||
AngelicaTesrMeshCache.INSTANCE.renderCached(standing ? KEY_SIGN_STANDING : KEY_SIGN_WALL, BUILDER);
|
||||
}
|
||||
|
||||
public static boolean renderSkull(ModelSkeletonHead model, ResourceLocation texture, float yawDegrees, float pitchDegrees, float scale) {
|
||||
if (texture == null) {
|
||||
return false;
|
||||
}
|
||||
final Object key = SKULL_KEYS.computeIfAbsent(new SkullKey(model, texture), k -> new Object());
|
||||
GLStateManager.glPushMatrix();
|
||||
if (yawDegrees != 0.0f) {
|
||||
GLStateManager.glRotatef(yawDegrees, 0.0f, 1.0f, 0.0f);
|
||||
}
|
||||
if (pitchDegrees != 0.0f) {
|
||||
GLStateManager.glRotatef(pitchDegrees, 1.0f, 0.0f, 0.0f);
|
||||
}
|
||||
BUILDER.set(texture, scale, model.skeletonHead, null, null);
|
||||
AngelicaTesrMeshCache.INSTANCE.renderCached(key, BUILDER);
|
||||
GLStateManager.glPopMatrix();
|
||||
return true;
|
||||
}
|
||||
|
||||
private static final class Builder implements TesrMeshBuilder {
|
||||
private ResourceLocation texture;
|
||||
private float scale;
|
||||
private ModelRenderer part0, part1, part2;
|
||||
private boolean partLocal;
|
||||
|
||||
void set(ResourceLocation texture, float scale, ModelRenderer part0, ModelRenderer part1, ModelRenderer part2) {
|
||||
this.texture = texture;
|
||||
this.scale = scale;
|
||||
this.part0 = part0;
|
||||
this.part1 = part1;
|
||||
this.part2 = part2;
|
||||
this.partLocal = false;
|
||||
}
|
||||
|
||||
void setLocal(ResourceLocation texture, float scale, ModelRenderer part) {
|
||||
set(texture, scale, part, null, null);
|
||||
this.partLocal = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void angelica$build(TesrMeshSink sink) {
|
||||
final Tessellator t = sink.angelica$bucket(DefaultVertexFormat.POSITION_TEXTURE_NORMAL, texture, WHITE);
|
||||
if (partLocal) {
|
||||
ModelPartMesher.emitPartLocal(t, part0, scale);
|
||||
return;
|
||||
}
|
||||
ModelPartMesher.emitPart(t, part0, scale);
|
||||
if (part1 != null) ModelPartMesher.emitPart(t, part1, scale);
|
||||
if (part2 != null) ModelPartMesher.emitPart(t, part2, scale);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package com.gtnewhorizons.angelica.rendering.tesr;
|
||||
|
||||
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
|
||||
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormatElement;
|
||||
import net.coderbot.iris.vertices.NormI8;
|
||||
import org.joml.Matrix4fc;
|
||||
import org.joml.Vector3f;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt;
|
||||
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.COLOR_INDEX;
|
||||
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.DEFAULT_COLOR;
|
||||
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.DEFAULT_LIGHTMAP;
|
||||
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.LIGHT_INDEX;
|
||||
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.NORMAL_INDEX;
|
||||
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.TEX_X_INDEX;
|
||||
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.TEX_Y_INDEX;
|
||||
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.VERTEX_SIZE;
|
||||
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.X_INDEX;
|
||||
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.Y_INDEX;
|
||||
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.Z_INDEX;
|
||||
|
||||
public final class VertexTransform {
|
||||
|
||||
private VertexTransform() {}
|
||||
|
||||
private static final int PACKED_UP = NormI8.pack(0f, 1f, 0f, 0f);
|
||||
|
||||
public static int[] decode(long srcAddr, VertexFormat srcFormat, int vertexCount, int drawMode) {
|
||||
final int[] out = decode(srcAddr, srcFormat, vertexCount);
|
||||
seedMissingNormals(out, vertexCount, drawMode);
|
||||
return out;
|
||||
}
|
||||
|
||||
static void seedMissingNormals(int[] out, int vertexCount, int drawMode) {
|
||||
final int prim = switch (drawMode) {
|
||||
case GL11.GL_QUADS -> 4;
|
||||
case GL11.GL_TRIANGLES -> 3;
|
||||
default -> 0;
|
||||
};
|
||||
if (prim != 0) {
|
||||
outer:
|
||||
for (int p = 0; p + prim <= vertexCount; p += prim) {
|
||||
for (int v = p; v < p + prim; v++) {
|
||||
if (out[v * VERTEX_SIZE | NORMAL_INDEX] != 0) continue outer;
|
||||
}
|
||||
final int packed = packedFaceNormal(out, p, prim);
|
||||
for (int v = p; v < p + prim; v++) {
|
||||
out[v * VERTEX_SIZE | NORMAL_INDEX] = packed;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (int v = 0; v < vertexCount; v++) {
|
||||
if (out[v * VERTEX_SIZE | NORMAL_INDEX] == 0) {
|
||||
out[v * VERTEX_SIZE | NORMAL_INDEX] = PACKED_UP;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static int packedFaceNormal(int[] out, int firstVertex, int prim) {
|
||||
final int b0 = firstVertex * VERTEX_SIZE;
|
||||
final int b1 = (firstVertex + 1) * VERTEX_SIZE;
|
||||
final int b2 = (firstVertex + 2) * VERTEX_SIZE;
|
||||
final float e1x, e1y, e1z, e2x, e2y, e2z;
|
||||
if (prim == 4) {
|
||||
final int b3 = (firstVertex + 3) * VERTEX_SIZE;
|
||||
e1x = Float.intBitsToFloat(out[b2 | X_INDEX]) - Float.intBitsToFloat(out[b0 | X_INDEX]);
|
||||
e1y = Float.intBitsToFloat(out[b2 | Y_INDEX]) - Float.intBitsToFloat(out[b0 | Y_INDEX]);
|
||||
e1z = Float.intBitsToFloat(out[b2 | Z_INDEX]) - Float.intBitsToFloat(out[b0 | Z_INDEX]);
|
||||
e2x = Float.intBitsToFloat(out[b3 | X_INDEX]) - Float.intBitsToFloat(out[b1 | X_INDEX]);
|
||||
e2y = Float.intBitsToFloat(out[b3 | Y_INDEX]) - Float.intBitsToFloat(out[b1 | Y_INDEX]);
|
||||
e2z = Float.intBitsToFloat(out[b3 | Z_INDEX]) - Float.intBitsToFloat(out[b1 | Z_INDEX]);
|
||||
} else {
|
||||
final float x0 = Float.intBitsToFloat(out[b0 | X_INDEX]);
|
||||
final float y0 = Float.intBitsToFloat(out[b0 | Y_INDEX]);
|
||||
final float z0 = Float.intBitsToFloat(out[b0 | Z_INDEX]);
|
||||
e1x = Float.intBitsToFloat(out[b1 | X_INDEX]) - x0;
|
||||
e1y = Float.intBitsToFloat(out[b1 | Y_INDEX]) - y0;
|
||||
e1z = Float.intBitsToFloat(out[b1 | Z_INDEX]) - z0;
|
||||
e2x = Float.intBitsToFloat(out[b2 | X_INDEX]) - x0;
|
||||
e2y = Float.intBitsToFloat(out[b2 | Y_INDEX]) - y0;
|
||||
e2z = Float.intBitsToFloat(out[b2 | Z_INDEX]) - z0;
|
||||
}
|
||||
final float nx = e1y * e2z - e1z * e2y;
|
||||
final float ny = e1z * e2x - e1x * e2z;
|
||||
final float nz = e1x * e2y - e1y * e2x;
|
||||
final float lenSq = nx * nx + ny * ny + nz * nz;
|
||||
if (lenSq < 1.0e-12f) return PACKED_UP;
|
||||
final float invLen = (float) (1.0 / Math.sqrt(lenSq));
|
||||
return NormI8.pack(nx * invLen, ny * invLen, nz * invLen, 0f);
|
||||
}
|
||||
|
||||
public static int[] decode(long srcAddr, VertexFormat srcFormat, int vertexCount) {
|
||||
final VertexFormatElement[] elems = srcFormat.elementsArray;
|
||||
final int n = elems.length;
|
||||
final int[] offsets = new int[n];
|
||||
int off = 0;
|
||||
for (int i = 0; i < n; i++) {
|
||||
offsets[i] = off;
|
||||
off += elems[i].getByteSize();
|
||||
}
|
||||
final int stride = srcFormat.getVertexSize();
|
||||
final int[] out = new int[vertexCount * VERTEX_SIZE];
|
||||
for (int v = 0; v < vertexCount; v++) {
|
||||
final long base = srcAddr + (long) v * stride;
|
||||
final int vbase = v * VERTEX_SIZE;
|
||||
out[vbase | COLOR_INDEX] = DEFAULT_COLOR;
|
||||
out[vbase | LIGHT_INDEX] = DEFAULT_LIGHTMAP;
|
||||
for (int i = 0; i < n; i++) {
|
||||
final long p = base + offsets[i];
|
||||
switch (elems[i].getUsage()) {
|
||||
case POSITION -> {
|
||||
out[vbase | X_INDEX] = memGetInt(p);
|
||||
out[vbase | Y_INDEX] = memGetInt(p + 4);
|
||||
out[vbase | Z_INDEX] = memGetInt(p + 8);
|
||||
}
|
||||
case PRIMARY_UV -> {
|
||||
out[vbase | TEX_X_INDEX] = memGetInt(p);
|
||||
out[vbase | TEX_Y_INDEX] = memGetInt(p + 4);
|
||||
}
|
||||
case NORMAL -> out[vbase | NORMAL_INDEX] = memGetInt(p);
|
||||
case COLOR -> out[vbase | COLOR_INDEX] = memGetInt(p);
|
||||
case SECONDARY_UV -> out[vbase | LIGHT_INDEX] = memGetInt(p);
|
||||
default -> {}
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
public static long writeInstance(long destPtr, VertexFormat destFormat, TemplateBuffer template, Matrix4fc mv, Vector3f scratch, int colorABGR, int packedLight, Matrix4fc texMatrix) {
|
||||
final int[] src = template.data;
|
||||
final int[] work = template.work;
|
||||
final int vertexCount = template.vertexCount;
|
||||
for (int v = 0; v < vertexCount; v++) {
|
||||
final int vbase = v * VERTEX_SIZE;
|
||||
work[vbase | COLOR_INDEX] = mulColor(src[vbase | COLOR_INDEX], colorABGR);
|
||||
work[vbase | LIGHT_INDEX] = packedLight;
|
||||
if (texMatrix != null) {
|
||||
final float u = Float.intBitsToFloat(src[vbase | TEX_X_INDEX]);
|
||||
final float t = Float.intBitsToFloat(src[vbase | TEX_Y_INDEX]);
|
||||
work[vbase | TEX_X_INDEX] = Float.floatToRawIntBits(texMatrix.m00() * u + texMatrix.m10() * t + texMatrix.m30());
|
||||
work[vbase | TEX_Y_INDEX] = Float.floatToRawIntBits(texMatrix.m01() * u + texMatrix.m11() * t + texMatrix.m31());
|
||||
} else {
|
||||
work[vbase | TEX_X_INDEX] = src[vbase | TEX_X_INDEX];
|
||||
work[vbase | TEX_Y_INDEX] = src[vbase | TEX_Y_INDEX];
|
||||
}
|
||||
}
|
||||
return destFormat.writeToBuffer0(destPtr, work, vertexCount * VERTEX_SIZE, mv, scratch);
|
||||
}
|
||||
|
||||
static int mulColor(int a, int b) {
|
||||
if (a == -1) return b;
|
||||
if (b == -1) return a;
|
||||
return mul8(a, b, 0) | mul8(a, b, 8) | mul8(a, b, 16) | mul8(a, b, 24);
|
||||
}
|
||||
|
||||
private static int mul8(int a, int b, int shift) {
|
||||
final int t = ((a >>> shift) & 0xFF) * ((b >>> shift) & 0xFF) + 0x80;
|
||||
return (((t + (t >> 8)) >> 8) & 0xFF) << shift;
|
||||
}
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
package com.gtnewhorizons.angelica.rendering.voxelization;
|
||||
|
||||
import com.gtnewhorizons.angelica.glsm.backend.BackendManager;
|
||||
import com.gtnewhorizons.angelica.sdlgpu.SDLGPURenderBackend;
|
||||
import net.coderbot.iris.pipeline.transform.RwImageStoreExtractor;
|
||||
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexFormat;
|
||||
import org.embeddedt.embeddium.impl.gl.buffer.GlBuffer;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion;
|
||||
|
||||
public final class SdlShadowVoxelizationSink implements ShadowVoxelizer.Sink {
|
||||
|
||||
private static final Logger LOG = LogManager.getLogger("Angelica");
|
||||
private static final int SSBO_BINDING = RwImageStoreExtractor.VG_VBUF_SSBO_BINDING;
|
||||
|
||||
private static int encodersThisFrame;
|
||||
private static int dispatchesThisFrame;
|
||||
private static int regionsThisFrame;
|
||||
|
||||
private boolean warnedBindFailure;
|
||||
private boolean warnedBeginFailure;
|
||||
private long pass;
|
||||
private int pendingVertexBuffer;
|
||||
private float pendingX;
|
||||
private float pendingY;
|
||||
private float pendingZ;
|
||||
|
||||
private static SDLGPURenderBackend sdl() {
|
||||
return (SDLGPURenderBackend) BackendManager.RENDER_BACKEND;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean region(RenderRegion region, GlVertexFormat format, float offsetX, float offsetY, float offsetZ) {
|
||||
final RenderRegion.DeviceResources resources = region.getResources(format);
|
||||
if (resources == null) return false;
|
||||
final GlBuffer vertexBuffer = resources.getVertexBuffer();
|
||||
if (vertexBuffer == null || vertexBuffer.handle() == 0) return false;
|
||||
pendingVertexBuffer = vertexBuffer.handle();
|
||||
pendingX = offsetX;
|
||||
pendingY = offsetY;
|
||||
pendingZ = offsetZ;
|
||||
regionsThisFrame++;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean range(int vertexOffset, int vertexCount) {
|
||||
if (pendingVertexBuffer != 0) {
|
||||
if (!sdl().bindVoxelizationRegion(SSBO_BINDING, pendingVertexBuffer, pass, pendingX, pendingY, pendingZ)) {
|
||||
if (!warnedBindFailure) {
|
||||
warnedBindFailure = true;
|
||||
LOG.warn("shadow voxelization: could not bind region vertex buffer {} at SSBO slot {}", pendingVertexBuffer, SSBO_BINDING);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
pendingVertexBuffer = 0;
|
||||
}
|
||||
if (pass == 0) {
|
||||
pass = sdl().beginVoxelizationBatch(SSBO_BINDING);
|
||||
if (pass != 0) encodersThisFrame++;
|
||||
if (pass == 0) {
|
||||
if (!warnedBeginFailure) {
|
||||
warnedBeginFailure = true;
|
||||
LOG.warn("shadow voxelization: compute encoder refused; no voxel writes this pass");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
sdl().voxelizeRange(pass, vertexOffset, vertexCount);
|
||||
dispatchesThisFrame++;
|
||||
return true;
|
||||
}
|
||||
|
||||
public static int takeEncoders() { final int n = encodersThisFrame; encodersThisFrame = 0; return n; }
|
||||
|
||||
public static int takeDispatches() { final int n = dispatchesThisFrame; dispatchesThisFrame = 0; return n; }
|
||||
|
||||
public static int takeRegions() { final int n = regionsThisFrame; regionsThisFrame = 0; return n; }
|
||||
|
||||
@Override
|
||||
public void finish() {
|
||||
if (pass != 0) {
|
||||
sdl().endVoxelizationBatch(pass);
|
||||
pass = 0;
|
||||
}
|
||||
pendingVertexBuffer = 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package com.gtnewhorizons.angelica.rendering.voxelization;
|
||||
|
||||
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexFormat;
|
||||
import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.LocalSectionIndex;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.ChunkPrimitiveType;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataStorage;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataUnsafe;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.lists.ChunkRenderList;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.lists.ChunkRenderListIterable;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.multidraw.BatchAssembler;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion;
|
||||
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
|
||||
import org.embeddedt.embeddium.impl.render.viewport.CameraTransform;
|
||||
|
||||
import java.util.Iterator;
|
||||
|
||||
public final class ShadowVoxelizer {
|
||||
|
||||
public interface Sink {
|
||||
/** @return false to skip this region */
|
||||
boolean region(RenderRegion region, GlVertexFormat format, float offsetX, float offsetY, float offsetZ);
|
||||
|
||||
/** @return false to skip the rest of this region; later regions are still attempted */
|
||||
boolean range(int vertexOffset, int vertexCount);
|
||||
|
||||
void finish();
|
||||
}
|
||||
|
||||
public void walkPass(ChunkRenderListIterable renderLists, TerrainRenderPass renderPass, GlVertexFormat format, CameraTransform camera, CameraTransform occlusionCamera, boolean useBlockFaceCulling, Sink sink) {
|
||||
try {
|
||||
final Iterator<ChunkRenderList> it = renderLists.iterator(renderPass.isReverseOrder());
|
||||
while (it.hasNext()) {
|
||||
walkRegion(it.next(), renderPass, format, camera, occlusionCamera, useBlockFaceCulling, sink);
|
||||
}
|
||||
} finally {
|
||||
sink.finish();
|
||||
}
|
||||
}
|
||||
|
||||
private static void walkRegion(ChunkRenderList list, TerrainRenderPass renderPass, GlVertexFormat format, CameraTransform camera, CameraTransform occlusionCamera, boolean useBlockFaceCulling, Sink sink) {
|
||||
final RenderRegion region = list.getRegion();
|
||||
final SectionRenderDataStorage storage = region.getStorage(renderPass);
|
||||
if (storage == null) return;
|
||||
|
||||
final int sectionCount = list.getSectionsWithGeometryCount();
|
||||
if (sectionCount == 0) return;
|
||||
|
||||
final byte[] sections = list.getSectionsWithGeometry();
|
||||
final SectionRenderDataUnsafe.Strategy layout = storage.getStorageStrategy();
|
||||
final ChunkPrimitiveType primitiveType = storage.getPrimitiveType();
|
||||
final int regionChunkX = region.getChunkX();
|
||||
final int regionChunkY = region.getChunkY();
|
||||
final int regionChunkZ = region.getChunkZ();
|
||||
boolean bound = false;
|
||||
|
||||
for (int i = 0; i < sectionCount; i++) {
|
||||
final int sectionIndex = sections[i] & 0xFF;
|
||||
final long pMeshData = storage.getDataPointer(sectionIndex);
|
||||
int slices = useBlockFaceCulling
|
||||
? BatchAssembler.getVisibleFaces(occlusionCamera.intX, occlusionCamera.intY, occlusionCamera.intZ,
|
||||
regionChunkX + LocalSectionIndex.unpackX(sectionIndex),
|
||||
regionChunkY + LocalSectionIndex.unpackY(sectionIndex),
|
||||
regionChunkZ + LocalSectionIndex.unpackZ(sectionIndex))
|
||||
: ModelQuadFacing.ALL;
|
||||
slices &= SectionRenderDataUnsafe.getSliceMask(pMeshData);
|
||||
slices &= 0x7F;
|
||||
if (slices == 0) continue;
|
||||
|
||||
final long runs = BatchAssembler.packRuns(slices);
|
||||
final int runCount = BatchAssembler.runCount(runs);
|
||||
for (int run = 0; run < runCount; run++) {
|
||||
final int startVertex = layout.getVertexOffset(pMeshData, BatchAssembler.runFirst(runs, run));
|
||||
final int endVertex = layout.getRunVertexEnd(pMeshData, BatchAssembler.runLast(runs, run), primitiveType);
|
||||
final int vertexCount = endVertex - startVertex;
|
||||
if (vertexCount <= 0) continue;
|
||||
|
||||
if (!bound) {
|
||||
if (!sink.region(region, format,
|
||||
cameraRelative(region.getOriginX(), camera.intX, camera.fracX),
|
||||
cameraRelative(region.getOriginY(), camera.intY, camera.fracY),
|
||||
cameraRelative(region.getOriginZ(), camera.intZ, camera.fracZ))) {
|
||||
return;
|
||||
}
|
||||
bound = true;
|
||||
}
|
||||
if (!sink.range(startVertex, vertexCount)) return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static float cameraRelative(int originBlock, int cameraBlock, float cameraFrac) {
|
||||
return (originBlock - cameraBlock) - cameraFrac;
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,8 @@ import java.awt.image.BufferedImage;
|
||||
import java.io.InputStream;
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
import static org.joml.Math.clamp;
|
||||
|
||||
/**
|
||||
* Maybe overcomplicated, but it's required to bridge the gap between the modern glint texture and white texture 1.7.10
|
||||
* has. Some shaders are able to render the glint just fine as they seem to have some amount of support for older
|
||||
@@ -159,8 +161,6 @@ public final class ShaderGlint {
|
||||
}
|
||||
|
||||
private static int clamp8(float v) {
|
||||
final int i = Math.round(v * 255.0F);
|
||||
if (i < 0) return 0;
|
||||
return Math.min(i, 255);
|
||||
return clamp(0, 255, Math.round(v * 255.0F));
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,8 @@ import it.unimi.dsi.fastutil.ints.IntArrayFIFOQueue;
|
||||
import org.embeddedt.embeddium.api.util.ColorARGB;
|
||||
import org.embeddedt.embeddium.impl.texture.MipmapHelper;
|
||||
|
||||
import static org.joml.Math.clamp;
|
||||
|
||||
/**
|
||||
* Mipmap downsampling for atlas sprites, replacing vanilla's {@code TextureUtil.generateMipmapData}.
|
||||
*/
|
||||
@@ -185,11 +187,7 @@ public final class MipmapGenerator {
|
||||
}
|
||||
|
||||
private static float scaledAlpha(int color, float alphaFactor) {
|
||||
return clamp01(ColorARGB.unpackAlpha(color) * alphaFactor);
|
||||
}
|
||||
|
||||
private static float clamp01(float value) {
|
||||
return value < 0.0f ? 0.0f : Math.min(value, 1.0f);
|
||||
return clamp(0.0f, 1.0f, ColorARGB.unpackAlpha(color) * alphaFactor);
|
||||
}
|
||||
|
||||
static void scaleAlphaToCoverage(int[] image, int width, float desiredCoverage, float alphaRef, int border) {
|
||||
@@ -221,7 +219,7 @@ public final class MipmapGenerator {
|
||||
final int color = image[i];
|
||||
final int rawAlpha = ColorARGB.unpackAlpha(color);
|
||||
final float bias = rawAlpha > 0 ? ALPHA_BIAS : 0.0f;
|
||||
final int alpha = (int) Math.floor(clamp01(rawAlpha / 255.0f * bestScale + bias) * 255.0f);
|
||||
final int alpha = (int) Math.floor(clamp(0.0f, 1.0f, rawAlpha / 255.0f * bestScale + bias) * 255.0f);
|
||||
image[i] = ColorARGB.withAlpha(color, alpha);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
package com.gtnewhorizons.angelica.utils;
|
||||
|
||||
public class Mipmaps {
|
||||
|
||||
private static final float[] VALS = new float[256];
|
||||
|
||||
public static float get(int i) {
|
||||
return VALS[i & 0xFF];
|
||||
}
|
||||
|
||||
public static int getColorComponent(int one, int two, int three, int four, int bits) {
|
||||
final float f = Mipmaps.get(one >> bits);
|
||||
final float g = Mipmaps.get(two >> bits);
|
||||
final float h = Mipmaps.get(three >> bits);
|
||||
final float i = Mipmaps.get(four >> bits);
|
||||
final float j = (float) Math.pow((f + g + h + i) * 0.25, 0.45454545454545453);
|
||||
return (int) (j * 255.0);
|
||||
}
|
||||
|
||||
static {
|
||||
for (int i = 0; i < VALS.length; ++i) {
|
||||
VALS[i] = (float) Math.pow((float) i / 255.0F, 2.2);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -101,7 +101,7 @@ public class ColorizeWorld {
|
||||
return null;
|
||||
} else {
|
||||
if (fogBlendRadius > 0) {
|
||||
map = new ColorMapBase.Blended(map, fogBlendRadius);
|
||||
map = new ColorMapBase.Blended(new ColorMapBase.BlockCached(map), fogBlendRadius);
|
||||
}
|
||||
map = new ColorMapBase.Cached(map);
|
||||
map = new ColorMapBase.Smoothed(map, 3000.0f);
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.prupe.mcpatcher.mal.biome;
|
||||
|
||||
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
@@ -199,6 +201,66 @@ abstract public class ColorMapBase {
|
||||
}
|
||||
}
|
||||
|
||||
public static final class BlockCached implements IColorMap {
|
||||
|
||||
private static final int MAX_ENTRIES = 4096;
|
||||
|
||||
private final IColorMap parent;
|
||||
private final Long2ObjectOpenHashMap<float[]> cache = new Long2ObjectOpenHashMap<>();
|
||||
private IBlockAccess lastBlockAccess;
|
||||
|
||||
public BlockCached(IColorMap parent) {
|
||||
this.parent = parent;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return parent.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isHeightDependent() {
|
||||
return parent.isHeightDependent();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getColorMultiplier() {
|
||||
return parent.getColorMultiplier();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getColorMultiplier(IBlockAccess blockAccess, int i, int j, int k) {
|
||||
return ColorUtils.float3ToInt(getColorMultiplierF(blockAccess, i, j, k));
|
||||
}
|
||||
|
||||
@Override
|
||||
public float[] getColorMultiplierF(IBlockAccess blockAccess, int i, int j, int k) {
|
||||
if (blockAccess != lastBlockAccess) {
|
||||
cache.clear();
|
||||
lastBlockAccess = blockAccess;
|
||||
}
|
||||
final long key = (((long) i & 0x3FFFFFFL) << 38) | (((long) k & 0x3FFFFFFL) << 12) | ((long) j & 0xFFFL);
|
||||
float[] color = cache.get(key);
|
||||
if (color == null) {
|
||||
final float[] src = parent.getColorMultiplierF(blockAccess, i, j, k);
|
||||
color = new float[] { src[0], src[1], src[2] };
|
||||
if (cache.size() >= MAX_ENTRIES) cache.clear();
|
||||
cache.put(key, color);
|
||||
}
|
||||
return color;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void claimResources(Collection<ResourceLocation> resources) {
|
||||
parent.claimResources(resources);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IColorMap copy() {
|
||||
return new BlockCached(parent.copy());
|
||||
}
|
||||
}
|
||||
|
||||
public static final class Smoothed implements IColorMap {
|
||||
|
||||
private final IColorMap parent;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package com.prupe.mcpatcher.mal.biome;
|
||||
|
||||
import net.minecraft.util.MathHelper;
|
||||
import org.joml.Math;
|
||||
|
||||
public class ColorUtils {
|
||||
|
||||
@@ -28,6 +28,6 @@ public class ColorUtils {
|
||||
}
|
||||
|
||||
public static float clamp(float f) {
|
||||
return MathHelper.clamp_float(f, 0.0f, 1.0f);
|
||||
return Math.clamp(0.0f, 1.0f, f);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package jss.notfine.gui;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.gtnewhorizons.angelica.config.AngelicaConfig;
|
||||
import com.gtnewhorizons.angelica.config.SystemProperties;
|
||||
import com.gtnewhorizons.angelica.glsm.GLStateManager;
|
||||
import jss.notfine.config.NotFineConfig;
|
||||
import jss.notfine.core.Settings;
|
||||
@@ -68,7 +69,7 @@ public class NotFineGameOptionPages {
|
||||
.setControl(TickBoxControl::new)
|
||||
.setBinding((opts, value) -> {
|
||||
opts.enableVsync = value;
|
||||
Display.setVSyncEnabled(opts.enableVsync);
|
||||
GLStateManager.setVSyncEnabled(opts.enableVsync);
|
||||
}, opts -> opts.enableVsync)
|
||||
.setImpact(OptionImpact.VARIES)
|
||||
.build())
|
||||
@@ -413,14 +414,6 @@ public class NotFineGameOptionPages {
|
||||
.setBinding((opts, value) -> opts.performance.useNoErrorGLContext = value, opts -> opts.performance.useNoErrorGLContext)
|
||||
.setFlags(OptionFlag.REQUIRES_GAME_RESTART)
|
||||
.build())
|
||||
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
|
||||
.setName(I18n.format("sodium.options.use_gl_state_cache.name"))
|
||||
.setTooltip(I18n.format("sodium.options.use_gl_state_cache.tooltip"))
|
||||
.setControl(TickBoxControl::new)
|
||||
.setImpact(OptionImpact.EXTREME)
|
||||
.setBinding((opts, value) -> GLStateManager.BYPASS_CACHE = !value, opts -> !GLStateManager.BYPASS_CACHE)
|
||||
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
|
||||
.build())
|
||||
.build());
|
||||
|
||||
return new OptionPage(I18n.format("options.button.other"), ImmutableList.copyOf(groups));
|
||||
|
||||
@@ -2,7 +2,7 @@ package kroppeb.stareval.function;
|
||||
|
||||
import kroppeb.stareval.expression.ConstantExpression;
|
||||
import kroppeb.stareval.function.TypedFunction.Parameter;
|
||||
import net.coderbot.iris.gl.uniform.UniformType;
|
||||
import com.gtnewhorizons.angelica.glsm.shader.UniformType;
|
||||
import net.coderbot.iris.parsing.MatrixType;
|
||||
import net.coderbot.iris.parsing.VectorType;
|
||||
|
||||
|
||||
@@ -17,7 +17,11 @@ import com.cardinalstar.cubicchunks.api.compat.CubicChunksVideoSettings;
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.gtnewhorizons.angelica.compat.ModStatus;
|
||||
import com.gtnewhorizons.angelica.config.AngelicaConfig;
|
||||
import com.gtnewhorizons.angelica.rendering.celeritas.MultiDrawModeResolver;
|
||||
import com.gtnewhorizons.angelica.rendering.culling.GpuCulling;
|
||||
import com.gtnewhorizons.angelica.config.GpuCullingMode;
|
||||
import com.gtnewhorizons.angelica.glsm.GLStateManager;
|
||||
import com.gtnewhorizons.angelica.glsm.RenderSystem;
|
||||
import cpw.mods.fml.common.Optional.Method;
|
||||
import com.gtnewhorizons.angelica.glsm.streaming.StreamingUploader;
|
||||
import jss.notfine.core.Settings;
|
||||
@@ -140,7 +144,7 @@ public class SodiumGameOptionPages {
|
||||
.setControl(TickBoxControl::new)
|
||||
.setBinding((opts, value) -> {
|
||||
opts.enableVsync = value;
|
||||
Display.setVSyncEnabled(opts.enableVsync);
|
||||
GLStateManager.setVSyncEnabled(opts.enableVsync);
|
||||
}, opts -> opts.enableVsync)
|
||||
.setImpact(OptionImpact.VARIES)
|
||||
.build())
|
||||
@@ -300,8 +304,7 @@ public class SodiumGameOptionPages {
|
||||
.setName(I18n.format("sodium.options.multidraw_mode.name"))
|
||||
.setTooltip(I18n.format("sodium.options.multidraw_mode.tooltip"))
|
||||
.setControl(o -> {
|
||||
boolean indirectSupported = GLStateManager.capabilities != null && (GLStateManager.capabilities.OpenGL43 || GLStateManager.capabilities.GL_ARB_multi_draw_indirect);
|
||||
MultiDrawMode[] allowed = indirectSupported ? MultiDrawMode.values() : new MultiDrawMode[]{MultiDrawMode.DIRECT, MultiDrawMode.INDIVIDUAL};
|
||||
MultiDrawMode[] allowed = MultiDrawModeResolver.indirectSupported() ? MultiDrawMode.values() : new MultiDrawMode[]{MultiDrawMode.DIRECT, MultiDrawMode.INDIVIDUAL};
|
||||
return new CyclingControl<>(o, MultiDrawMode.class, allowed);
|
||||
})
|
||||
.setBinding((opts, value) -> opts.advanced.multiDrawMode = value, opts -> opts.advanced.multiDrawMode)
|
||||
@@ -373,6 +376,14 @@ public class SodiumGameOptionPages {
|
||||
.setBinding((opts, value) -> opts.performance.useEntityCulling = value, opts -> opts.performance.useEntityCulling)
|
||||
.build()
|
||||
)
|
||||
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
|
||||
.setName(I18n.format("sodium.options.section_gated_tesr_culling.name"))
|
||||
.setTooltip(I18n.format("sodium.options.section_gated_tesr_culling.tooltip"))
|
||||
.setControl(TickBoxControl::new)
|
||||
.setImpact(OptionImpact.MEDIUM)
|
||||
.setBinding((opts, value) -> opts.performance.sectionGatedTesrCulling = value, opts -> opts.performance.sectionGatedTesrCulling)
|
||||
.build()
|
||||
)
|
||||
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
|
||||
.setName(I18n.format("sodium.options.use_particle_culling.name"))
|
||||
.setTooltip(I18n.format("sodium.options.use_particle_culling.tooltip"))
|
||||
@@ -439,6 +450,25 @@ public class SodiumGameOptionPages {
|
||||
)
|
||||
.build());
|
||||
|
||||
final OptionImpl<AngelicaConfig, GpuCullingMode> gpuCullingMode =
|
||||
OptionImpl.createBuilder(GpuCullingMode.class, angelicaOpts)
|
||||
.setName(I18n.format("options.angelica.gpuCullingMode"))
|
||||
.setTooltip(I18n.format("options.angelica.gpuCullingMode.tooltip"))
|
||||
.setControl(o -> new CyclingControl<>(o, GpuCullingMode.class, new GpuCullingMode[]{
|
||||
GpuCullingMode.CPU_ONLY, GpuCullingMode.COMPUTE}))
|
||||
.setBinding((opts, value) -> {
|
||||
AngelicaConfig.gpuCullingMode = value;
|
||||
AngelicaConfig.applyGpuCullingMode();
|
||||
}, opts -> AngelicaConfig.gpuCullingMode)
|
||||
.setImpact(OptionImpact.HIGH)
|
||||
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
|
||||
.setEnabled(true)
|
||||
.build();
|
||||
gpuCullingMode.iris$dynamicallyEnable(GpuCulling::isAvailable);
|
||||
groups.add(OptionGroup.createBuilder()
|
||||
.add(gpuCullingMode)
|
||||
.build());
|
||||
|
||||
return new OptionPage(I18n.format("sodium.options.pages.advanced"), ImmutableList.copyOf(groups));
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,6 @@ import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonSyntaxException;
|
||||
import com.gtnewhorizons.angelica.AngelicaMod;
|
||||
import com.gtnewhorizons.angelica.config.AngelicaConfig;
|
||||
import com.gtnewhorizons.angelica.glsm.GLStateManager;
|
||||
import com.gtnewhorizons.angelica.glsm.streaming.StreamingUploader;
|
||||
import com.gtnewhorizons.angelica.proxy.ClientProxy;
|
||||
@@ -72,9 +71,6 @@ public class SodiumGameOptions {
|
||||
}
|
||||
|
||||
public static boolean needsForcedSpritePadding() {
|
||||
if (!AngelicaConfig.enableCeleritas) {
|
||||
return false;
|
||||
}
|
||||
final TextureFilterMode mode = filteringPossible()
|
||||
? resolveFilterMode(ClientProxy.options().quality.textureFilterMode)
|
||||
: TextureFilterMode.NONE;
|
||||
@@ -148,14 +144,14 @@ public class SodiumGameOptions {
|
||||
config.quality.textureFilterMode = TextureFilterMode.RGSS;
|
||||
}
|
||||
|
||||
// Clamp render-ahead to 0 if GL 3.2 fences aren't available
|
||||
if (GLStateManager.capabilities == null || !GLStateManager.capabilities.OpenGL32) {
|
||||
config.performance.cpuRenderAheadLimit = 0;
|
||||
}
|
||||
|
||||
// Downgrade INDIRECT if hardware doesn't support it
|
||||
if (config.advanced.multiDrawMode == MultiDrawMode.INDIRECT && (GLStateManager.capabilities == null || (!GLStateManager.capabilities.OpenGL43 && !GLStateManager.capabilities.GL_ARB_multi_draw_indirect))) {
|
||||
config.advanced.multiDrawMode = MultiDrawMode.DIRECT;
|
||||
if (GLStateManager.capabilities != null) {
|
||||
if (!GLStateManager.capabilities.OpenGL32) {
|
||||
config.performance.cpuRenderAheadLimit = 0;
|
||||
}
|
||||
if (config.advanced.multiDrawMode == MultiDrawMode.INDIRECT
|
||||
&& !GLStateManager.capabilities.OpenGL43 && !GLStateManager.capabilities.GL_ARB_multi_draw_indirect) {
|
||||
config.advanced.multiDrawMode = MultiDrawMode.DIRECT;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -218,6 +214,7 @@ public class SodiumGameOptions {
|
||||
|
||||
public boolean animateOnlyVisibleTextures = true;
|
||||
public boolean useEntityCulling = true;
|
||||
public boolean sectionGatedTesrCulling = true;
|
||||
public boolean useFogOcclusion = true;
|
||||
public boolean useBlockFaceCulling = true;
|
||||
public boolean useCompactVertexFormat = true;
|
||||
|
||||
@@ -0,0 +1,335 @@
|
||||
package net.coderbot.batchedentityrendering.impl;
|
||||
|
||||
import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
|
||||
import com.gtnewhorizons.angelica.glsm.GLStateManager;
|
||||
import it.unimi.dsi.fastutil.objects.Object2IntLinkedOpenHashMap;
|
||||
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
|
||||
import net.coderbot.batchedentityrendering.impl.ordering.SimpleRenderOrderManager;
|
||||
import net.coderbot.iris.Iris;
|
||||
import net.coderbot.iris.pipeline.WorldRenderingPipeline;
|
||||
import net.coderbot.iris.uniforms.CapturedRenderingState;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
import org.lwjgl.opengl.GL13;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** Collects geometry into per-RenderLayer buffers during a pass and draws it all at endBatch, one state bracket per layer. Based on Iris's FullyBufferedMultiBufferSource */
|
||||
public class AngelicaBufferSource implements Groupable {
|
||||
public static final int SAVED_STATE_BITS = GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT | GL11.GL_CURRENT_BIT | GL11.GL_LIGHTING_BIT | GL11.GL_TEXTURE_BIT;
|
||||
|
||||
private static final int NUM_BUFFERS = 32;
|
||||
|
||||
public enum GroupIdKind { BLOCK_ENTITY, ENTITY }
|
||||
|
||||
public interface LayerDrawHook {
|
||||
boolean hasDraws(RenderLayer layer);
|
||||
void drawLayer(RenderLayer layer);
|
||||
}
|
||||
|
||||
private static final Comparator<BufferSegment> OPAQUE_ORDER = Comparator.comparingInt(BufferSegment::getBlockEntityId);
|
||||
|
||||
private final SimpleRenderOrderManager renderOrderManager = new SimpleRenderOrderManager();
|
||||
private final SegmentedBufferBuilder[] builders = new SegmentedBufferBuilder[NUM_BUFFERS];
|
||||
private final Object2IntLinkedOpenHashMap<RenderLayer> affinities = new Object2IntLinkedOpenHashMap<>(NUM_BUFFERS);
|
||||
private final Map<RenderLayer, List<BufferSegment>> typeToSegment = new Object2ObjectOpenHashMap<>();
|
||||
|
||||
private boolean prepared;
|
||||
private final List<RenderLayer> order = new ArrayList<>();
|
||||
private boolean stateSaved;
|
||||
private boolean anyIdSet;
|
||||
private GroupIdKind idKind = GroupIdKind.BLOCK_ENTITY;
|
||||
|
||||
public AngelicaBufferSource() {
|
||||
for (int i = 0; i < builders.length; i++) {
|
||||
builders[i] = new SegmentedBufferBuilder();
|
||||
}
|
||||
affinities.defaultReturnValue(-1);
|
||||
}
|
||||
|
||||
public SegmentedBufferBuilder getBuffer(RenderLayer type, int blockEntityId) {
|
||||
renderOrderManager.begin(type);
|
||||
int affinity = affinities.getAndMoveToLast(type);
|
||||
if (affinity == -1) {
|
||||
if (affinities.size() < builders.length) {
|
||||
affinity = affinities.size();
|
||||
} else {
|
||||
affinity = affinities.removeFirstInt();
|
||||
}
|
||||
affinities.put(type, affinity);
|
||||
}
|
||||
final SegmentedBufferBuilder builder = builders[affinity];
|
||||
builder.begin(type, blockEntityId);
|
||||
return builder;
|
||||
}
|
||||
|
||||
public void declareUse(RenderLayer type) {
|
||||
renderOrderManager.begin(type);
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
for (SegmentedBufferBuilder builder : builders) {
|
||||
if (!builder.isEmpty()) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void ensurePrepared() {
|
||||
if (prepared) return;
|
||||
prepared = true;
|
||||
clearSegmentLists();
|
||||
for (SegmentedBufferBuilder builder : builders) {
|
||||
final List<BufferSegment> builderSegments = builder.getSegments();
|
||||
for (int i = 0, n = builderSegments.size(); i < n; i++) {
|
||||
final BufferSegment segment = builderSegments.get(i);
|
||||
typeToSegment.computeIfAbsent(segment.getRenderType(), t -> new ArrayList<>()).add(segment);
|
||||
}
|
||||
}
|
||||
order.clear();
|
||||
final List<RenderLayer> renderOrder = renderOrderManager.getRenderOrder();
|
||||
for (int i = 0, n = renderOrder.size(); i < n; i++) {
|
||||
order.add(renderOrder.get(i));
|
||||
}
|
||||
renderOrderManager.reset();
|
||||
for (int i = 0, n = order.size(); i < n; i++) {
|
||||
final RenderLayer layer = order.get(i);
|
||||
if (getTransparencyType(layer) != TransparencyType.OPAQUE) continue;
|
||||
final List<BufferSegment> segments = typeToSegment.get(layer);
|
||||
if (segments != null) {
|
||||
segments.sort(OPAQUE_ORDER);
|
||||
}
|
||||
}
|
||||
affinities.clear();
|
||||
stateSaved = false;
|
||||
anyIdSet = false;
|
||||
}
|
||||
|
||||
List<RenderLayer> prepare() {
|
||||
ensurePrepared();
|
||||
return new ArrayList<>(order);
|
||||
}
|
||||
|
||||
List<BufferSegment> segmentsFor(RenderLayer layer) {
|
||||
return typeToSegment.get(layer);
|
||||
}
|
||||
|
||||
public void endBatchWithType(TransparencyType type, LayerDrawHook hook) {
|
||||
ensurePrepared();
|
||||
int keep = 0;
|
||||
for (int i = 0, n = order.size(); i < n; i++) {
|
||||
final RenderLayer layer = order.get(i);
|
||||
if (getTransparencyType(layer) != type) {
|
||||
order.set(keep++, layer);
|
||||
continue;
|
||||
}
|
||||
drawLayer(layer, hook);
|
||||
}
|
||||
for (int i = order.size() - 1; i >= keep; i--) {
|
||||
order.remove(i);
|
||||
}
|
||||
}
|
||||
|
||||
public void endBatch(LayerDrawHook hook) {
|
||||
ensurePrepared();
|
||||
for (int i = 0, n = order.size(); i < n; i++) {
|
||||
drawLayer(order.get(i), hook);
|
||||
}
|
||||
order.clear();
|
||||
finish();
|
||||
}
|
||||
|
||||
public void pauseBatch() {
|
||||
releaseAttribState();
|
||||
clearCurrentId();
|
||||
}
|
||||
|
||||
public void discard() {
|
||||
order.clear();
|
||||
finish();
|
||||
}
|
||||
|
||||
private void releaseAttribState() {
|
||||
if (stateSaved) {
|
||||
GLStateManager.glPopAttrib();
|
||||
stateSaved = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void clearCurrentId() {
|
||||
if (!anyIdSet) return;
|
||||
if (idKind == GroupIdKind.ENTITY) {
|
||||
CapturedRenderingState.INSTANCE.setCurrentEntity(-1);
|
||||
CapturedRenderingState.INSTANCE.setCurrentEntityColor(0f, 0f, 0f, 0f);
|
||||
} else {
|
||||
CapturedRenderingState.INSTANCE.setCurrentBlockEntity(0);
|
||||
}
|
||||
anyIdSet = false;
|
||||
}
|
||||
|
||||
private void drawLayer(RenderLayer layer, LayerDrawHook hook) {
|
||||
final List<BufferSegment> segments = typeToSegment.get(layer);
|
||||
final boolean hasDynamic = segments != null && !segments.isEmpty();
|
||||
final boolean hasRetained = hook != null && hook.hasDraws(layer);
|
||||
if (!hasDynamic && !hasRetained) return;
|
||||
if (!stateSaved) {
|
||||
stateSaved = true;
|
||||
GLStateManager.glPushAttrib(SAVED_STATE_BITS);
|
||||
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
|
||||
}
|
||||
layer.startDrawing();
|
||||
if (hasDynamic) {
|
||||
anyIdSet = true;
|
||||
GLStateManager.glPushMatrix();
|
||||
GLStateManager.glLoadIdentity();
|
||||
SegmentedBufferBuilder.LayerBuffer bound = null;
|
||||
final boolean entityKind = idKind == GroupIdKind.ENTITY;
|
||||
int currentId = Integer.MIN_VALUE;
|
||||
int currentColor = 0;
|
||||
boolean colorSet = false;
|
||||
for (int i = 0, n = segments.size(); i < n; i++) {
|
||||
final BufferSegment segment = segments.get(i);
|
||||
if (entityKind && (!colorSet || segment.getEntityColor() != currentColor)) {
|
||||
colorSet = true;
|
||||
currentColor = segment.getEntityColor();
|
||||
setEntityColor(currentColor);
|
||||
}
|
||||
if (segment.getBlockEntityId() != currentId) {
|
||||
currentId = segment.getBlockEntityId();
|
||||
applyIdAndRebind(currentId);
|
||||
}
|
||||
final SegmentedBufferBuilder.LayerBuffer owner = segment.getOwner();
|
||||
if (owner != bound) {
|
||||
if (bound != null) bound.finishDraw();
|
||||
bound = owner;
|
||||
bound.uploadForDraw();
|
||||
bound.setupDraw();
|
||||
}
|
||||
bound.draw(segment.getFirstVertex(), segment.getVertexCount());
|
||||
}
|
||||
if (bound != null) bound.finishDraw();
|
||||
GLStateManager.glPopMatrix();
|
||||
}
|
||||
if (hasRetained) {
|
||||
anyIdSet = true;
|
||||
hook.drawLayer(layer);
|
||||
}
|
||||
layer.endDrawing();
|
||||
}
|
||||
|
||||
private void clearSegmentLists() {
|
||||
for (List<BufferSegment> segments : typeToSegment.values()) {
|
||||
segments.clear();
|
||||
}
|
||||
}
|
||||
|
||||
private void finish() {
|
||||
releaseAttribState();
|
||||
clearCurrentId();
|
||||
clearSegmentLists();
|
||||
final long now = System.currentTimeMillis();
|
||||
final long maxIdle = getTargetClearTime();
|
||||
for (SegmentedBufferBuilder builder : builders) {
|
||||
builder.resetAndReclaim(now, maxIdle);
|
||||
}
|
||||
prepared = false;
|
||||
}
|
||||
|
||||
public void freeBuffers() {
|
||||
for (SegmentedBufferBuilder builder : builders) {
|
||||
builder.freeAll();
|
||||
}
|
||||
typeToSegment.clear();
|
||||
order.clear();
|
||||
affinities.clear();
|
||||
renderOrderManager.reset();
|
||||
prepared = false;
|
||||
}
|
||||
|
||||
public long allocatedBytes() {
|
||||
long bytes = 0;
|
||||
for (SegmentedBufferBuilder builder : builders) {
|
||||
bytes += builder.allocatedBytes();
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
private long getTargetClearTime() {
|
||||
final long sizeInMiB = allocatedBytes() / 1024L / 1024L;
|
||||
if (sizeInMiB > 5000) {
|
||||
return 1_000;
|
||||
} else if (sizeInMiB > 1000) {
|
||||
return 5_000;
|
||||
}
|
||||
return 10_000;
|
||||
}
|
||||
|
||||
public void setIdKind(GroupIdKind kind) {
|
||||
this.idKind = kind;
|
||||
}
|
||||
|
||||
public void applyIdAndRebind(int id) {
|
||||
anyIdSet = true;
|
||||
if (idKind == GroupIdKind.ENTITY) {
|
||||
CapturedRenderingState.INSTANCE.setCurrentEntity(id);
|
||||
rebindPass();
|
||||
} else {
|
||||
setBlockEntityAndRebind(id);
|
||||
}
|
||||
}
|
||||
|
||||
public void applyIdNoRebind(int id) {
|
||||
anyIdSet = true;
|
||||
if (idKind == GroupIdKind.ENTITY) {
|
||||
CapturedRenderingState.INSTANCE.setCurrentEntity(id);
|
||||
} else {
|
||||
CapturedRenderingState.INSTANCE.setCurrentBlockEntity(id);
|
||||
}
|
||||
}
|
||||
|
||||
public static void setEntityColor(int packed) {
|
||||
CapturedRenderingState.INSTANCE.setCurrentEntityColor(
|
||||
((packed >>> 16) & 0xFF) / 255f, ((packed >>> 8) & 0xFF) / 255f,
|
||||
(packed & 0xFF) / 255f, (packed >>> 24) / 255f);
|
||||
}
|
||||
|
||||
public static void setBlockEntityAndRebind(int blockEntityId) {
|
||||
CapturedRenderingState.INSTANCE.setCurrentBlockEntity(blockEntityId);
|
||||
rebindPass();
|
||||
}
|
||||
|
||||
public static void rebindPass() {
|
||||
if (Iris.enabled) {
|
||||
final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable();
|
||||
if (pipeline != null) {
|
||||
pipeline.rebindCurrentPass();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static TransparencyType getTransparencyType(RenderLayer type) {
|
||||
while (type instanceof WrappableRenderType wrappable) {
|
||||
type = wrappable.unwrap();
|
||||
}
|
||||
if (type instanceof BlendingStateHolder holder) {
|
||||
return holder.getTransparencyType();
|
||||
}
|
||||
return TransparencyType.GENERAL_TRANSPARENT;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void startGroup() {
|
||||
renderOrderManager.startGroup();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean maybeStartGroup() {
|
||||
return renderOrderManager.maybeStartGroup();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void endGroup() {
|
||||
renderOrderManager.endGroup();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package net.coderbot.batchedentityrendering.impl;
|
||||
|
||||
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat;
|
||||
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
|
||||
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormatElement;
|
||||
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags;
|
||||
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.writers.IVertexAttributeWriter;
|
||||
import net.minecraft.client.renderer.Tessellator;
|
||||
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetFloat;
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutFloat;
|
||||
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.LIGHT_INDEX;
|
||||
|
||||
public final class BatchVertexFormats {
|
||||
public static final VertexFormatElement LIGHT_FLOAT_ELEMENT = new VertexFormatElement(1, VertexFormatElement.Type.FLOAT, VertexFormatElement.Usage.SECONDARY_UV, 2, VertexFlags.BRIGHTNESS_BIT, new FloatLightVertexAttributeWriter());
|
||||
public static final VertexFormat POSITION_COLOR_TEXTURE_LIGHTF_NORMAL = new VertexFormat(DefaultVertexFormat.POSITION_ELEMENT, DefaultVertexFormat.COLOR_ELEMENT, DefaultVertexFormat.TEXTURE_ELEMENT, LIGHT_FLOAT_ELEMENT, DefaultVertexFormat.NORMAL_ELEMENT);
|
||||
|
||||
private BatchVertexFormats() {}
|
||||
|
||||
private static final class FloatLightVertexAttributeWriter implements IVertexAttributeWriter {
|
||||
@Override
|
||||
public int writeAttribute(long pointer, int[] data, int index) {
|
||||
final int light = data[index | LIGHT_INDEX];
|
||||
memPutFloat(pointer, light & 0xFFFF);
|
||||
memPutFloat(pointer + 4, light >>> 16);
|
||||
return 8;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int writeAttribute(long pointer, Tessellator tessellator) {
|
||||
final int light = tessellator.brightness;
|
||||
memPutFloat(pointer, light & 0xFFFF);
|
||||
memPutFloat(pointer + 4, light >>> 16);
|
||||
return 8;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int readAttribute(long pointer, Tessellator tessellator) {
|
||||
tessellator.brightness = (((int) memGetFloat(pointer + 4)) << 16) | (((int) memGetFloat(pointer)) & 0xFFFF);
|
||||
return 8;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,25 +1,45 @@
|
||||
package net.coderbot.batchedentityrendering.impl;
|
||||
|
||||
import com.gtnewhorizons.angelica.compat.toremove.RenderLayer;
|
||||
import lombok.Getter;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
|
||||
|
||||
public class BufferSegment {
|
||||
private final ByteBuffer slice;
|
||||
@Getter
|
||||
private final RenderLayer type;
|
||||
private final int blockEntityId;
|
||||
private final int entityColor;
|
||||
private final int firstVertex;
|
||||
private final int vertexCount;
|
||||
private final SegmentedBufferBuilder.LayerBuffer owner;
|
||||
|
||||
public BufferSegment(ByteBuffer slice, RenderLayer type) {
|
||||
this.slice = slice;
|
||||
public BufferSegment(RenderLayer type, int blockEntityId, int entityColor, int firstVertex, int vertexCount, SegmentedBufferBuilder.LayerBuffer owner) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public ByteBuffer getSlice() {
|
||||
return slice;
|
||||
this.blockEntityId = blockEntityId;
|
||||
this.entityColor = entityColor;
|
||||
this.firstVertex = firstVertex;
|
||||
this.vertexCount = vertexCount;
|
||||
this.owner = owner;
|
||||
}
|
||||
|
||||
public RenderLayer getRenderType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public int getBlockEntityId() {
|
||||
return blockEntityId;
|
||||
}
|
||||
|
||||
public int getEntityColor() {
|
||||
return entityColor;
|
||||
}
|
||||
|
||||
public int getFirstVertex() {
|
||||
return firstVertex;
|
||||
}
|
||||
|
||||
public int getVertexCount() {
|
||||
return vertexCount;
|
||||
}
|
||||
|
||||
public SegmentedBufferBuilder.LayerBuffer getOwner() {
|
||||
return owner;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
package net.coderbot.batchedentityrendering.impl;
|
||||
|
||||
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadView;
|
||||
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
|
||||
import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
|
||||
import com.gtnewhorizons.angelica.rendering.tesr.TemplateBuffer;
|
||||
import com.gtnewhorizons.angelica.rendering.tesr.MeshBuffer;
|
||||
import com.gtnewhorizons.angelica.rendering.tesr.VertexTransform;
|
||||
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
|
||||
import net.coderbot.iris.uniforms.CapturedRenderingState;
|
||||
import org.joml.Matrix4fc;
|
||||
import org.joml.Vector3f;
|
||||
import org.joml.Vector4fc;
|
||||
import org.lwjgl.BufferUtils;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0;
|
||||
|
||||
public class SegmentedBufferBuilder {
|
||||
|
||||
public static final VertexFormat FORMAT = BatchVertexFormats.POSITION_COLOR_TEXTURE_LIGHTF_NORMAL;
|
||||
|
||||
static final class LayerBuffer {
|
||||
final RenderLayer layer;
|
||||
ByteBuffer buffer;
|
||||
final MeshBuffer mesh = new MeshBuffer();
|
||||
int vertexCount;
|
||||
boolean uploaded;
|
||||
long lastUsedMs;
|
||||
|
||||
LayerBuffer(RenderLayer layer) {
|
||||
this.layer = layer;
|
||||
this.buffer = BufferUtils.createByteBuffer(Math.max(layer.getExpectedBufferSize(), 4096));
|
||||
}
|
||||
|
||||
void ensureCapacity(int bytes) {
|
||||
buffer = MeshBuffer.ensureCapacity(buffer, bytes, true);
|
||||
}
|
||||
|
||||
void uploadForDraw() {
|
||||
if (uploaded) return;
|
||||
uploaded = true;
|
||||
final ByteBuffer view = buffer.duplicate();
|
||||
view.flip();
|
||||
mesh.upload(layer.getVertexFormat(), layer.getDrawMode(), view, vertexCount);
|
||||
}
|
||||
|
||||
void setupDraw() {
|
||||
mesh.bind();
|
||||
}
|
||||
|
||||
void draw(int firstVertex, int count) {
|
||||
mesh.draw(firstVertex, count);
|
||||
}
|
||||
|
||||
void finishDraw() {
|
||||
mesh.unbind();
|
||||
}
|
||||
|
||||
void reset() {
|
||||
buffer.clear();
|
||||
vertexCount = 0;
|
||||
uploaded = false;
|
||||
}
|
||||
}
|
||||
|
||||
private final Map<RenderLayer, LayerBuffer> layerBuffers = new Object2ObjectOpenHashMap<>();
|
||||
private final List<LayerBuffer> bufferList = new ArrayList<>();
|
||||
private final List<BufferSegment> segments = new ArrayList<>();
|
||||
private LayerBuffer current;
|
||||
private RenderLayer currentType;
|
||||
private int currentBlockEntityId;
|
||||
private int currentEntityColor;
|
||||
private int segmentStartVertex;
|
||||
private long allocatedBytes;
|
||||
|
||||
public void begin(RenderLayer type, int blockEntityId) {
|
||||
final int entityColor = packEntityColor(CapturedRenderingState.INSTANCE.getCurrentEntityColor());
|
||||
if (type == currentType && blockEntityId == currentBlockEntityId && entityColor == currentEntityColor && current != null) {
|
||||
return;
|
||||
}
|
||||
endSegment();
|
||||
LayerBuffer buffer = layerBuffers.get(type);
|
||||
if (buffer == null) {
|
||||
buffer = new LayerBuffer(type);
|
||||
layerBuffers.put(type, buffer);
|
||||
bufferList.add(buffer);
|
||||
allocatedBytes += buffer.buffer.capacity();
|
||||
}
|
||||
current = buffer;
|
||||
currentType = type;
|
||||
currentBlockEntityId = blockEntityId;
|
||||
currentEntityColor = entityColor;
|
||||
segmentStartVertex = current.vertexCount;
|
||||
}
|
||||
|
||||
public static int packEntityColor(Vector4fc c) {
|
||||
return ((int) (c.w() * 255f + 0.5f) << 24) | ((int) (c.x() * 255f + 0.5f) << 16) | ((int) (c.y() * 255f + 0.5f) << 8) | (int) (c.z() * 255f + 0.5f);
|
||||
}
|
||||
|
||||
public void addQuad(ModelQuadView quad) {
|
||||
if (current == null) {
|
||||
throw new IllegalStateException("addQuad() without begin()");
|
||||
}
|
||||
final VertexFormat format = currentType.getVertexFormat();
|
||||
ensureCurrentCapacity(format.getVertexSize() * 4);
|
||||
format.writeQuad(quad, current.buffer);
|
||||
current.vertexCount += 4;
|
||||
}
|
||||
|
||||
public void addTemplateInstance(TemplateBuffer template, Matrix4fc mv, Vector3f scratch, int colorABGR, int packedLight, Matrix4fc texMatrix) {
|
||||
if (current == null) {
|
||||
throw new IllegalStateException("addTemplateInstance() without begin()");
|
||||
}
|
||||
final VertexFormat format = currentType.getVertexFormat();
|
||||
ensureCurrentCapacity(format.getVertexSize() * template.vertexCount);
|
||||
final ByteBuffer buffer = current.buffer;
|
||||
final long ptr = memAddress0(buffer) + buffer.position();
|
||||
final long end = VertexTransform.writeInstance(ptr, format, template, mv, scratch, colorABGR, packedLight, texMatrix);
|
||||
buffer.position(buffer.position() + (int) (end - ptr));
|
||||
current.vertexCount += template.vertexCount;
|
||||
}
|
||||
|
||||
private void ensureCurrentCapacity(int bytes) {
|
||||
final int before = current.buffer.capacity();
|
||||
current.ensureCapacity(bytes);
|
||||
allocatedBytes += current.buffer.capacity() - before;
|
||||
}
|
||||
|
||||
private void endSegment() {
|
||||
if (current != null && current.vertexCount > segmentStartVertex) {
|
||||
segments.add(new BufferSegment(currentType, currentBlockEntityId, currentEntityColor, segmentStartVertex,
|
||||
current.vertexCount - segmentStartVertex, current));
|
||||
}
|
||||
segmentStartVertex = current == null ? 0 : current.vertexCount;
|
||||
}
|
||||
|
||||
public List<BufferSegment> getSegments() {
|
||||
endSegment();
|
||||
currentType = null;
|
||||
current = null;
|
||||
return segments;
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
for (int i = 0, n = bufferList.size(); i < n; i++) {
|
||||
if (bufferList.get(i).vertexCount != 0) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public int getVertexCount() {
|
||||
int total = 0;
|
||||
for (int i = 0, n = bufferList.size(); i < n; i++) {
|
||||
total += bufferList.get(i).vertexCount;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
public void reset() {
|
||||
for (int i = 0, n = bufferList.size(); i < n; i++) {
|
||||
bufferList.get(i).reset();
|
||||
}
|
||||
segments.clear();
|
||||
currentType = null;
|
||||
current = null;
|
||||
currentBlockEntityId = 0;
|
||||
segmentStartVertex = 0;
|
||||
}
|
||||
|
||||
public void resetAndReclaim(long nowMs, long maxIdleMs) {
|
||||
for (int i = bufferList.size() - 1; i >= 0; i--) {
|
||||
final LayerBuffer lb = bufferList.get(i);
|
||||
if (lb.vertexCount > 0) {
|
||||
lb.lastUsedMs = nowMs;
|
||||
}
|
||||
lb.reset();
|
||||
if (nowMs - lb.lastUsedMs > maxIdleMs) {
|
||||
allocatedBytes -= lb.buffer.capacity();
|
||||
lb.mesh.delete();
|
||||
layerBuffers.remove(lb.layer);
|
||||
bufferList.remove(i);
|
||||
}
|
||||
}
|
||||
segments.clear();
|
||||
currentType = null;
|
||||
current = null;
|
||||
currentBlockEntityId = 0;
|
||||
segmentStartVertex = 0;
|
||||
}
|
||||
|
||||
public void freeAll() {
|
||||
for (int i = 0, n = bufferList.size(); i < n; i++) {
|
||||
bufferList.get(i).mesh.delete();
|
||||
}
|
||||
layerBuffers.clear();
|
||||
bufferList.clear();
|
||||
segments.clear();
|
||||
currentType = null;
|
||||
current = null;
|
||||
currentBlockEntityId = 0;
|
||||
segmentStartVertex = 0;
|
||||
allocatedBytes = 0;
|
||||
}
|
||||
|
||||
public long allocatedBytes() {
|
||||
return allocatedBytes;
|
||||
}
|
||||
|
||||
public int bufferCount() {
|
||||
return layerBuffers.size();
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
package net.coderbot.batchedentityrendering.impl;
|
||||
|
||||
import com.gtnewhorizons.angelica.compat.toremove.RenderLayer;
|
||||
import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
|
||||
|
||||
public interface WrappableRenderType {
|
||||
/**
|
||||
|
||||
Loaded 100 of 647 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user