Update Celeritas (#2087)

This commit is contained in:
Jason Mitchell authored and GitHub committed 2026-09-09 08:31:31 -07:00
1 parent 2845c9e078
commit 3b4ebcf611
165 files changed
+6776 -3036

No files matched your search

@@ -1,368 +0,0 @@
package com.gtnewhorizons.angelica.client.rendering;
import com.gtnewhorizon.gtnhlib.client.opengl.UniversalVAO;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.mitchej123.glsm.GLStateManagerService;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import java.nio.IntBuffer;
public class AngelicaGLStateManagerService implements GLStateManagerService {
private IntBuffer intArrayBuffer = BufferUtils.createIntBuffer(16);
private IntBuffer getIntArrayBuffer(int size) {
if (intArrayBuffer.capacity() < size) {
intArrayBuffer = BufferUtils.createIntBuffer(size);
}
intArrayBuffer.clear();
return intArrayBuffer;
}
@Override
public int getPriority() {
return 100;
}
// ===================== QUERY OPERATIONS =====================
@Override
public int glGetInteger(int pname) {
return GLStateManager.glGetInteger(pname);
}
@Override
public String glGetString(int pname) {
return GLStateManager.glGetString(pname);
}
// ===================== FRAMEBUFFER OPERATIONS =====================
@Override
public int glGenFramebuffers() {
return GLStateManager.glGenFramebuffers();
}
@Override
public void glDeleteFramebuffers(int framebuffer) {
GLStateManager.glDeleteFramebuffers(framebuffer);
}
@Override
public void glBindFramebuffer(int target, int framebuffer) {
GLStateManager.glBindFramebuffer(target, framebuffer);
}
@Override
public int glCheckFramebufferStatus(int target) {
return GLStateManager.glCheckFramebufferStatus(target);
}
@Override
public void glFramebufferTexture2D(int target, int attachment, int textarget, int texture, int level) {
GLStateManager.glFramebufferTexture2D(target, attachment, textarget, texture, level);
}
// ===================== SHADER OPERATIONS =====================
@Override
public int glCreateShader(int type) {
return GLStateManager.glCreateShader(type);
}
@Override
public void glCompileShader(int shader) {
GLStateManager.glCompileShader(shader);
}
@Override
public int glGetShaderi(int shader, int pname) {
return GLStateManager.glGetShaderi(shader, pname);
}
@Override
public String glGetShaderInfoLog(int shader, int maxLength) {
return GLStateManager.glGetShaderInfoLog(shader, maxLength);
}
@Override
public void glDeleteShader(int shader) {
GLStateManager.glDeleteShader(shader);
}
@Override
public int glCreateProgram() {
return GLStateManager.glCreateProgram();
}
@Override
public void glAttachShader(int program, int shader) {
GLStateManager.glAttachShader(program, shader);
}
@Override
public void glLinkProgram(int program) {
GLStateManager.glLinkProgram(program);
}
@Override
public int glGetProgrami(int program, int pname) {
return GLStateManager.glGetProgrami(program, pname);
}
@Override
public void glUseProgram(int program) {
GLStateManager.glUseProgram(program);
}
@Override
public void glDeleteProgram(int program) {
GLStateManager.glDeleteProgram(program);
}
// ===================== UNIFORM/ATTRIBUTE OPERATIONS =====================
@Override
public int glGetUniformLocation(int program, CharSequence name) {
return GLStateManager.glGetUniformLocation(program, name);
}
@Override
public void glUniform1i(int location, int value) {
GLStateManager.glUniform1i(location, value);
}
@Override
public int glGetAttribLocation(int program, CharSequence name) {
return GLStateManager.glGetAttribLocation(program, name);
}
@Override
public void glBindAttribLocation(int program, int index, CharSequence name) {
GLStateManager.glBindAttribLocation(program, index, name);
}
// ===================== VAO OPERATIONS =====================
@Override
public int glGenVertexArrays() {
return UniversalVAO.genVertexArrays();
}
@Override
public void glBindVertexArray(int array) {
GLStateManager.glBindVertexArray(array);
}
@Override
public void glDeleteVertexArrays(int array) {
GLStateManager.glDeleteVertexArrays(array);
}
// ===================== BUFFER OPERATIONS =====================
@Override
public int glGenBuffers() {
return GLStateManager.glGenBuffers();
}
@Override
public void glBindBuffer(int target, int buffer) {
GLStateManager.glBindBuffer(target, buffer);
}
@Override
public void glDeleteBuffers(int buffer) {
GLStateManager.glDeleteBuffers(buffer);
}
// ===================== TEXTURE OPERATIONS =====================
@Override
public int glGenTextures() {
return GLStateManager.glGenTextures();
}
@Override
public void glGenTextures(int[] textures) {
final IntBuffer buffer = getIntArrayBuffer(textures.length);
GLStateManager.glGenTextures(buffer);
buffer.get(textures);
}
@Override
public void glDeleteTextures(int texture) {
GLStateManager.glDeleteTextures(texture);
}
@Override
public void glDeleteTextures(int[] textures) {
final IntBuffer buffer = getIntArrayBuffer(textures.length);
buffer.put(textures);
buffer.flip();
GLStateManager.glDeleteTextures(buffer);
}
@Override
public void glActiveTexture(int texture) {
GLStateManager.glActiveTexture(texture);
}
@Override
public int glGetTexLevelParameteri(int target, int level, int pname) {
return GLStateManager.glGetTexLevelParameteri(target, level, pname);
}
@Override
public int glGetTexLevelParameter(int target, int level, int pname) {
return GLStateManager.glGetTexLevelParameteri(target, level, pname);
}
@Override
public void glCopyTexSubImage2D(int target, int level, int xoffset, int yoffset, int x, int y, int width, int height) {
GLStateManager.glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height);
}
@Override
public void glPixelStorei(int pname, int param) {
GLStateManager.glPixelStorei(pname, param);
}
// ===================== STATE OPERATIONS =====================
@Override
public void enableCullFace() {
GLStateManager.enableCull();
}
@Override
public void disableCullFace() {
GLStateManager.disableCull();
}
@Override
public void enableBlend() {
GLStateManager.enableBlend();
}
@Override
public void disableBlend() {
GLStateManager.disableBlend();
}
@Override
public void glBlendFuncSeparate(int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) {
GLStateManager.tryBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha);
}
@Override
public void enableDepthTest() {
GLStateManager.enableDepthTest();
}
@Override
public void disableDepthTest() {
GLStateManager.disableDepthTest();
}
@Override
public void glDepthFunc(int func) {
GLStateManager.glDepthFunc(func);
}
@Override
public void glDepthMask(boolean flag) {
GLStateManager.glDepthMask(flag);
}
@Override
public void glViewport(int x, int y, int width, int height) {
GLStateManager.glViewport(x, y, width, height);
}
@Override
public void glColorMask(boolean red, boolean green, boolean blue, boolean alpha) {
GLStateManager.glColorMask(red, green, blue, alpha);
}
@Override
public void glClearColor(float red, float green, float blue, float alpha) {
GLStateManager.glClearColor(red, green, blue, alpha);
}
@Override
public void glClear(int mask) {
GLStateManager.glClear(mask);
}
// ===================== MOJANG ADDITIONS =====================
@Override
public void clear(int mask, boolean checkError) {
GLStateManager.glClear(mask);
}
@Override
public void bindTexture(int texture) {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texture);
}
@Override
public int getActiveTexture() {
return GLStateManager.getActiveTextureUnit() + GL13.GL_TEXTURE0;
}
@Override
public int getActiveTextureAccessor() {
return GLStateManager.getActiveTextureUnit();
}
@Override
public int getBoundTexture(int internalUnit) {
return GLStateManager.getBoundTextureForServerState(internalUnit);
}
@Override
public int getActiveBoundTexture() {
return GLStateManager.getBoundTextureForServerState();
}
@Override
public int getViewportWidth() {
return GLStateManager.getViewportState().width;
}
@Override
public int getViewportHeight() {
return GLStateManager.getViewportState().height;
}
@Override
public boolean getDepthStateMask() {
return GLStateManager.getDepthState().isEnabled();
}
@Override
public boolean isBlendEnabled() {
return GLStateManager.getBlendMode().isEnabled();
}
@Override
public void setBoundTexture(int unit, int texture) {
final int currentUnit = GLStateManager.getActiveTextureUnit();
if (currentUnit != unit) {
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + unit);
}
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texture);
if (currentUnit != unit) {
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + currentUnit);
}
}
@Override
public int getTextureBinding(int unit) {
return GLStateManager.getBoundTextureForServerState(unit);
}
}
@@ -1,243 +0,0 @@
package com.gtnewhorizons.angelica.client.rendering;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.mitchej123.glsm.RenderSystemService;
import org.joml.Matrix4f;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import java.nio.FloatBuffer;
public class AngelicaRenderSystemService implements RenderSystemService {
// Shader state (Mojang-specific, tracked here)
private final int[] shaderTextures = new int[16];
private final float[] shaderColor = {1f, 1f, 1f, 1f};
private final float[] shaderFogColor = {0f, 0f, 0f, 1f};
private float shaderFogStart = 0f;
private float shaderFogEnd = 0f;
private int fogShape = 0;
private float shaderLineWidth = 1f;
private final Matrix4f projectionMatrix = new Matrix4f();
private final FloatBuffer projectionMatrixBuffer = BufferUtils.createFloatBuffer(16);
@Override
public int getPriority() {
return 100;
}
// ===================== TEXTURE OPERATIONS =====================
@Override
public void glActiveTexture(int texture) {
GLStateManager.glActiveTexture(texture);
}
@Override
public void bindTexture(int texture) {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texture);
}
// ===================== STATE OPERATIONS =====================
@Override
public void enableCullFace() {
GLStateManager.enableCull();
}
@Override
public void disableCullFace() {
GLStateManager.disableCull();
}
@Override
public void enableBlend() {
GLStateManager.enableBlend();
}
@Override
public void disableBlend() {
GLStateManager.disableBlend();
}
@Override
public void defaultBlendFunc() {
GLStateManager.defaultBlendFunc();
}
@Override
public void blendFuncSeparate(int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) {
GLStateManager.tryBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha);
}
@Override
public void setUnknownBlendState() {
// No-op: Angelica tracks blend state accurately
}
@Override
public void enableDepthTest() {
GLStateManager.enableDepthTest();
}
@Override
public void disableDepthTest() {
GLStateManager.disableDepthTest();
}
@Override
public void depthFunc(int depthFunc) {
GLStateManager.glDepthFunc(depthFunc);
}
@Override
public void depthMask(boolean flag) {
GLStateManager.glDepthMask(flag);
}
@Override
public void glViewport(int x, int y, int width, int height) {
GLStateManager.glViewport(x, y, width, height);
}
@Override
public void glClearColor(float red, float green, float blue, float alpha) {
GLStateManager.glClearColor(red, green, blue, alpha);
}
@Override
public void clear(int mask, boolean checkError) {
GLStateManager.glClear(mask);
}
// ===================== UNIFORM OPERATIONS =====================
@Override
public void glUniform1i(int location, int value) {
GLStateManager.glUniform1i(location, value);
}
@Override
public void glUniformMatrix3(int location, boolean transpose, FloatBuffer value) {
GLStateManager.glUniformMatrix3(location, transpose, value);
}
@Override
public void glUniformMatrix4(int location, boolean transpose, FloatBuffer value) {
GLStateManager.glUniformMatrix4(location, transpose, value);
}
// ===================== THREAD ASSERTIONS =====================
@Override
public void assertOnRenderThread() {
// No-op: 1.7.10 is single-threaded for rendering
}
@Override
public void assertOnRenderThreadOrInit() {
// No-op: 1.7.10 is single-threaded for rendering
}
// ===================== SHADER STATE =====================
@Override
public void setShaderTexture(int shaderTexture, int textureId) {
if (shaderTexture >= 0 && shaderTexture < 16) {
shaderTextures[shaderTexture] = textureId;
}
}
@Override
public int getShaderTexture(int shaderTexture) {
return (shaderTexture >= 0 && shaderTexture < 16) ? shaderTextures[shaderTexture] : 0;
}
@Override
public void setShaderColor(float red, float green, float blue, float alpha) {
shaderColor[0] = red;
shaderColor[1] = green;
shaderColor[2] = blue;
shaderColor[3] = alpha;
}
@Override
public float[] getShaderColor() {
return shaderColor.clone();
}
@Override
public void setShaderLineWidth(float lineWidth) {
shaderLineWidth = lineWidth;
}
@Override
public float getShaderLineWidth() {
return shaderLineWidth;
}
// ===================== FOG STATE =====================
@Override
public void setShaderFogColor(float red, float green, float blue, float alpha) {
shaderFogColor[0] = red;
shaderFogColor[1] = green;
shaderFogColor[2] = blue;
shaderFogColor[3] = alpha;
}
@Override
public float[] getShaderFogColor() {
return shaderFogColor.clone();
}
@Override
public void setShaderFogStart(float start) {
shaderFogStart = start;
}
@Override
public float getShaderFogStart() {
return shaderFogStart;
}
@Override
public void setShaderFogEnd(float end) {
shaderFogEnd = end;
}
@Override
public float getShaderFogEnd() {
return shaderFogEnd;
}
@Override
public void setFogShape(int shape) {
fogShape = shape;
}
@Override
public int getFogShape() {
return fogShape;
}
// ===================== PROJECTION MATRIX =====================
@Override
public Matrix4f getProjectionMatrix() {
return new Matrix4f(projectionMatrix);
}
@Override
public void setProjectionMatrixOrth(Matrix4f m) {
projectionMatrix.set(m);
GLStateManager.glMatrixMode(GL11.GL_PROJECTION);
projectionMatrix.get(projectionMatrixBuffer);
projectionMatrixBuffer.rewind();
GLStateManager.glLoadMatrix(projectionMatrixBuffer);
}
@Override
public void setProjectionMatrixOrigin(Matrix4f m) {
setProjectionMatrixOrth(m);
}
}
@@ -7,6 +7,7 @@ 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.client.gui.GuiMainMenu;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.EnumChatFormatting;
@@ -27,7 +28,6 @@ public final class FlybyRunner {
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 }
@@ -123,6 +123,14 @@ public final class FlybyRunner {
if (event.phase != TickEvent.Phase.END || this.state == State.IDLE || this.state == State.DONE) return;
final Minecraft mc = Minecraft.getMinecraft();
if (this.state == State.EXITING) {
if (++this.tick >= EXIT_TICKS) {
this.state = State.DONE;
this.exitGame(mc);
}
return;
}
final EntityClientPlayerMP player = mc.thePlayer;
if (player == null || mc.theWorld == null) return;
@@ -152,13 +160,6 @@ public final class FlybyRunner {
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 -> { }
}
}
@@ -383,9 +384,9 @@ public final class FlybyRunner {
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);
if (world.getWorldTime() % 24000L != SystemProperties.FLYBY_TIME_OF_DAY) {
LOGGER.info("Flyby: freezing time at {}", SystemProperties.FLYBY_TIME_OF_DAY);
world.setWorldTime(SystemProperties.FLYBY_TIME_OF_DAY);
}
}
}
@@ -419,6 +420,16 @@ public final class FlybyRunner {
this.state = this.exitWhenDone ? State.EXITING : State.DONE;
}
private void exitGame(Minecraft mc) {
LOGGER.info("Flyby complete, shutting down.");
if (mc.theWorld != null) {
mc.theWorld.sendQuittingDisconnectingPacket();
mc.loadWorld(null);
mc.displayGuiScreen(new GuiMainMenu());
}
mc.shutdown();
}
private void restorePauseOnLostFocus(Minecraft mc) {
if (!this.pauseOnLostFocusOverridden) return;
mc.gameSettings.pauseOnLostFocus = this.pauseOnLostFocusSaved;
@@ -10,12 +10,11 @@ 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.glsm.loading.Lwjgl3ifyExclusions;
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;
import cpw.mods.fml.relauncher.FMLRelaunchLog;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin;
@@ -33,8 +32,6 @@ import org.apache.logging.log4j.core.config.LoggerConfig;
import org.spongepowered.asm.launch.GlobalProperties;
import org.spongepowered.asm.service.mojang.MixinServiceLaunchWrapper;
import javax.swing.JOptionPane;
import java.awt.GraphicsEnvironment;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@@ -57,7 +54,7 @@ public final class AngelicaClientTweaker implements IFMLLoadingPlugin, IEarlyMix
final boolean rfbLoaded = Launch.blackboard.getOrDefault("angelica.rfbPluginLoaded", Boolean.FALSE) == Boolean.TRUE;
if (rfbLoaded) {
addLwjgl3ifyExclusions();
Lwjgl3ifyExclusions.apply();
} else {
// Fucking java 8 and non RFB
try {
@@ -86,7 +83,9 @@ public final class AngelicaClientTweaker implements IFMLLoadingPlugin, IEarlyMix
} catch (ConfigException e) {
throw new RuntimeException(e);
}
verifyDependencies();
DependencyVerifier.verifyOrHalt(AngelicaTweaker.class, "Angelica",
DependencyVerifier.gtnhLibChecks("Angelica"), LOGGER,
(title, message) -> MissingDependencySdl.showFatal(title, message));
if (SystemProperties.USE_SDL_GPU) {
if (SDLGPUGate.isSDLGPUAvailable()) {
@@ -109,56 +108,6 @@ public final class AngelicaClientTweaker implements IFMLLoadingPlugin, IEarlyMix
}
}
private static void addLwjgl3ifyExclusions() {
final var handle = SharedConfig.getRfbTransformers().stream()
.filter(transformer -> transformer.id().equals("lwjgl3ify:redirect"))
.findFirst()
.orElse(null);
if (handle != null) {
for (String exclusion : EcosystemNarrowRules.LWJGL3IFY_EXCLUSIONS_SHARED) {
handle.exclusions().add(exclusion);
}
handle.exclusions().add("com.gtnewhorizons.angelica.sdlgpu");
}
}
private static void verifyDependencies() {
try {
DependencyVerifier.verify(AngelicaTweaker.class, List.of(
new DependencyVerifier.Check(
"/it/unimi/dsi/fastutil/ints/Int2ObjectMap.class",
"Missing dependency: Angelica requires GTNHLib! Download: https://modrinth.com/mod/gtnhlib"),
new DependencyVerifier.Check(
"/com/gtnewhorizon/gtnhlib/client/renderer/VertexCallbackManager.class",
"GTNHLib is outdated: Angelica requires GTNHLib 0.10.0 or newer! Download: https://modrinth.com/mod/gtnhlib"),
new DependencyVerifier.Check(
"/it/unimi/dsi/fastutil/objects/ObjectBooleanBiConsumer.class",
"GTNHLib is outdated: Angelica requires GTNHLib 0.11.19 or newer (fastutil 8.5.18+)! Download: https://modrinth.com/mod/gtnhlib")
));
} catch (RuntimeException ex) {
fatalDependencyError(ex.getMessage());
}
}
private static void fatalDependencyError(String message) {
final String title = "Angelica - Missing Dependency";
System.err.println("FATAL: " + message);
try {
LOGGER.fatal(message);
} catch (Throwable ignored) {}
final int lwjgl3ifyMajor = ((Integer) Launch.blackboard.getOrDefault("lwjgl3ify:major-version", Integer.MIN_VALUE));
try {
if (lwjgl3ifyMajor >= 3) {
MissingDependencySdl.showFatal(title, message);
} else if (!GraphicsEnvironment.isHeadless()) {
JOptionPane.showMessageDialog(null, message, title, JOptionPane.ERROR_MESSAGE);
}
} catch (Throwable ignored) {}
Runtime.getRuntime().halt(1);
}
@Override
public String[] getASMTransformerClass() {
if (transformerClasses == null) {
@@ -1,48 +1,15 @@
package com.gtnewhorizons.angelica.loading.fml.transformers;
import com.gtnewhorizons.angelica.loading.shared.AngelicaClassDump;
import com.gtnewhorizons.angelica.glsm.loading.ModRedirector;
import com.gtnewhorizons.angelica.loading.shared.transformers.AngelicaRedirector;
import net.minecraft.launchwrapper.IClassTransformer;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.tree.ClassNode;
/** IClassTransformer wrapper for {@link AngelicaRedirector} */
public class AngelicaRedirectorTransformer implements IClassTransformer {
private final AngelicaRedirector inner;
private final String[] exclusions;
public AngelicaRedirectorTransformer() {
inner = new AngelicaRedirector();
exclusions = inner.getTransformerExclusions();
}
private final ModRedirector inner = AngelicaRedirector.create();
@Override
public byte[] transform(final String className, String transformedName, byte[] basicClass) {
if (basicClass == null) return null;
// Ignore classes that are excluded from transformation - Doesn't fully work without the
// TransformerExclusions due to some nested classes
for (String exclusion : exclusions) {
if (transformedName.startsWith(exclusion)) return basicClass;
}
if (!inner.shouldTransform(basicClass)) {
return basicClass;
}
final ClassReader cr = new ClassReader(basicClass);
final ClassNode cn = new ClassNode();
cr.accept(cn, 0);
final boolean changed = inner.transformClassNode(transformedName, cn);
if (changed) {
final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
cn.accept(cw);
final byte[] bytes = cw.toByteArray();
AngelicaClassDump.dumpClass(transformedName, basicClass, bytes, this);
return bytes;
}
return basicClass;
return inner.transform(transformedName, basicClass, this);
}
}
@@ -18,13 +18,10 @@ import net.minecraft.launchwrapper.IClassTransformer;
*/
public class EarlyRedirectorTransformer implements IClassTransformer {
private final EarlyRedirectorCore impl = new EarlyRedirectorCore(
"com.gtnewhorizons.angelica.lwjgl3.",
"com.gtnewhorizons.angelica.transform"
);
private final EarlyRedirectorCore impl = new EarlyRedirectorCore("com.gtnewhorizons.angelica.transform");
@Override
public byte[] transform(String name, String transformedName, byte[] basicClass) {
return impl.transform(transformedName, basicClass);
return impl.transform(transformedName, basicClass, this);
}
}
@@ -1,79 +1,11 @@
package com.gtnewhorizons.angelica.loading.rfb.transformers;
import com.gtnewhorizons.angelica.loading.shared.AngelicaClassDump;
import com.gtnewhorizons.angelica.glsm.loading.RfbModRedirector;
import com.gtnewhorizons.angelica.loading.shared.transformers.AngelicaRedirector;
import com.gtnewhorizons.retrofuturabootstrap.api.ClassNodeHandle;
import com.gtnewhorizons.retrofuturabootstrap.api.ExtensibleClassLoader;
import com.gtnewhorizons.retrofuturabootstrap.api.RfbClassTransformer;
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} */
public class RFBAngelicaRedirector implements RfbClassTransformer {
private final AngelicaRedirector inner;
public class RFBAngelicaRedirector extends RfbModRedirector {
public RFBAngelicaRedirector() {
inner = new AngelicaRedirector();
}
@Pattern("[a-z0-9-]+")
@Override
public @NotNull String id() {
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"};
}
@Override
public @NotNull String @Nullable [] sortBefore() {
return new String[] {"lwjgl3ify:redirect"};
}
@Override
public @NotNull String @Nullable [] additionalExclusions() {
return inner.getTransformerExclusions();
}
@Override
public boolean shouldTransformClass(@NotNull ExtensibleClassLoader classLoader,
@NotNull RfbClassTransformer.Context context, @Nullable Manifest manifest, @NotNull String className,
@NotNull ClassNodeHandle classNode) {
if (!classNode.isPresent()) {
return false;
}
return inner.shouldTransform(classNode.getOriginalBytes());
}
@Override
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(), isLwjgl3Aware(manifest));
if (changed) {
classNode.computeMaxs();
AngelicaClassDump.dumpRFBClass(className, classNode, this);
}
return changed;
}
@Override
public void transformClass(@NotNull ExtensibleClassLoader classLoader, @NotNull RfbClassTransformer.Context context,
@Nullable Manifest manifest, @NotNull String className, @NotNull ClassNodeHandle classNode) {
transformClassIfNeeded(classLoader, context, manifest, className, classNode);
super("redirector", AngelicaRedirector.create());
}
}
@@ -1,24 +1,18 @@
package com.gtnewhorizons.angelica.loading.shared;
import com.gtnewhorizon.gtnhlib.asm.ASMUtil;
import com.gtnewhorizons.angelica.config.SystemProperties;
import com.gtnewhorizons.angelica.glsm.loading.ClassDump;
import com.gtnewhorizons.retrofuturabootstrap.api.ClassNodeHandle;
public class AngelicaClassDump {
public static final ClassDump INSTANCE = new ClassDump(SystemProperties.DUMP_CLASS);
public static void dumpClass(String className, byte[] originalBytes, byte[] transformedBytes, Object transformer) {
if (SystemProperties.DUMP_CLASS) {
ASMUtil.saveAsRawClassFile(originalBytes, className + "_PRE", transformer);
ASMUtil.saveAsRawClassFile(transformedBytes, className + "_POST", transformer);
}
INSTANCE.dumpClass(className, originalBytes, transformedBytes, transformer);
}
public static void dumpRFBClass(String className, ClassNodeHandle classNode, Object transformer) {
if (SystemProperties.DUMP_CLASS) {
final byte[] originalBytes = classNode.getOriginalBytes();
final byte[] transformedBytes = classNode.computeBytes();
ASMUtil.saveAsRawClassFile(originalBytes, className + "_PRE", transformer);
ASMUtil.saveAsRawClassFile(transformedBytes, className + "_POST", transformer);
}
INSTANCE.dumpRFBClass(className, classNode, transformer);
}
}
@@ -1,45 +1,13 @@
package com.gtnewhorizons.angelica.loading.shared.transformers;
import com.gtnewhorizons.angelica.glsm.redirect.GLSMRedirector;
import org.objectweb.asm.tree.ClassNode;
import com.gtnewhorizons.angelica.glsm.loading.ModRedirector;
import com.gtnewhorizons.angelica.loading.shared.AngelicaClassDump;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Mod-level wrapper around {@link GLSMRedirector}. Adds mod-specific transformer exclusions and delegates all redirect logic to GLSM.
* <p>
* THIS CLASS MIGHT BE LOADED ON A DIFFERENT CLASS LOADER,
* IT SHOULD NOT CALL ANY CODE FROM THE MAIN MOD
*/
public final class AngelicaRedirector {
private final GLSMRedirector core = new GLSMRedirector();
private final String[] allExclusions;
public AngelicaRedirector() {
final List<String> exclusions = new ArrayList<>(Arrays.asList(core.getCoreExclusions()));
exclusions.add("com.gtnewhorizons.angelica.lwjgl3.");
exclusions.add("com.gtnewhorizons.angelica.transform");
allExclusions = exclusions.toArray(new String[0]);
public static ModRedirector create() {
return new ModRedirector(AngelicaClassDump.INSTANCE, "com.gtnewhorizons.angelica.transform");
}
public String[] getTransformerExclusions() {
return allExclusions;
}
public boolean shouldTransform(byte[] basicClass) {
return core.shouldTransform(basicClass);
}
/** @return Was the class changed? */
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);
}
private AngelicaRedirector() {}
}
@@ -103,12 +103,6 @@ public enum Mixins implements IMixins {
)
),
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)
@@ -367,7 +361,6 @@ public enum Mixins implements IMixins {
"celeritas.terrain.MixinChunkProviderClient"
, "celeritas.terrain.MixinMinecraft_ChunkUpdates"
, "celeritas.terrain.MixinRenderGlobal"
, "celeritas.terrain.MixinRenderListManager"
, "celeritas.terrain.MixinRenderSectionManager"
, "celeritas.terrain.MixinWorldClient"
, "celeritas.frustum.MixinClippingHelper"
@@ -391,7 +384,6 @@ public enum Mixins implements IMixins {
, "celeritas.terrain.MixinWorld_AwaitingDescriptor"
, "celeritas.terrain.MixinRenderRegion"
, "celeritas.terrain.MixinSectionRenderDataStorage"
, "celeritas.terrain.MixinDefaultChunkRenderer"
, "celeritas.terrain.MixinDefaultChunkShaderInterface"
)
),
@@ -1,5 +0,0 @@
package com.gtnewhorizons.angelica.mixins.interfaces;
public interface RenderListManagerAccessor {
boolean angelica$hasOcclusionFutureInFlight();
}
@@ -2,13 +2,10 @@ 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();
}
@@ -4,7 +4,6 @@ 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;
@@ -22,20 +21,18 @@ 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 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 long lastSectionsUploaded, lastBytesUploaded, lastIndexBufferGrowths;
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);
@@ -61,7 +58,7 @@ public final class TracyFramePlots {
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_BATCH_REBUILDS = Tracy.plotHandle("draw.batchRebuilds");
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");
@@ -175,20 +172,17 @@ public final class TracyFramePlots {
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_GL_SECTION_META_BYTES, TerrainDrawStats.takeSectionMetaBytes());
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_DRAW_BATCH_REBUILDS, TerrainDrawStats.takeBatchRebuilds());
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;
Tracy.plotInt(P_CULL_REGIONS_DRAWN, TerrainDrawStats.takeCullRegionsDrawn());
Tracy.plotInt(P_CULL_MAX_REGION_COMMANDS, TerrainDrawStats.takeCullMaxRegionCommands());
Tracy.plotInt(P_CULL_COMMANDS_SUBMITTED, TerrainDrawStats.takeCullCommandsSubmitted());
final ShaderManager ffp = ShaderManager.getInstance();
Tracy.plotInt(P_FFP_PRE_DRAW_CALLS, ffp.statLastFramePreDrawCalls());
@@ -231,6 +225,7 @@ public final class TracyFramePlots {
lastSectionsUploaded = delta(P_MESH_UPLOADED_SECTIONS, RenderRegionManager.getSectionsUploaded(), lastSectionsUploaded);
lastBytesUploaded = delta(P_MESH_UPLOADED_BYTES, RenderRegionManager.getBytesUploaded(), lastBytesUploaded);
lastIndexBufferGrowths = delta(P_DRAW_INDEX_BUFFER_GROWTHS, SharedQuadIndexBuffer.getGrowths(), lastIndexBufferGrowths);
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());
@@ -1,16 +1,27 @@
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.rendering.culling.GpuTerrainCuller;
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 com.gtnewhorizons.angelica.rendering.voxelization.SdlShadowVoxelizationSink;
import com.gtnewhorizons.angelica.rendering.voxelization.ShadowVoxelizer;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gl.program.ComputeProgram;
import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline;
import net.coderbot.iris.pipeline.WorldRenderingPipeline;
import net.coderbot.iris.shadows.ShadowRenderingState;
import org.embeddedt.embeddium.impl.gl.device.CommandList;
import org.embeddedt.embeddium.impl.gl.device.DirectMultiDrawBatch;
import org.embeddedt.embeddium.impl.gl.device.IndirectMultiDrawBatch;
import org.embeddedt.embeddium.impl.gl.device.MultiDrawBatch;
import org.embeddedt.embeddium.impl.gl.device.RenderDevice;
import org.embeddedt.embeddium.impl.gl.shader.GlProgram;
import org.embeddedt.embeddium.impl.gl.shader.GlShader;
@@ -19,15 +30,15 @@ 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.ChunkRenderMatrices;
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.lists.ChunkRenderListIterable;
import org.embeddedt.embeddium.impl.render.chunk.multidraw.BatchAssembler;
import org.embeddedt.embeddium.impl.render.chunk.multidraw.CachedBatch;
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;
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderBindingPoints;
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderInterface;
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderOptions;
@@ -36,7 +47,9 @@ import org.embeddedt.embeddium.impl.render.chunk.shader.DefaultChunkShaderInterf
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.jetbrains.annotations.Nullable;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL20;
import java.util.ArrayList;
import java.util.List;
@@ -44,20 +57,26 @@ 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;
private final GpuTerrainCuller culler;
private final ReusableCachedBatch gpuBatch = new ReusableCachedBatch();
private static final ShadowVoxelizer shadowVoxelizer = new ShadowVoxelizer();
private static final SdlShadowVoxelizationSink shadowVoxelSink = new SdlShadowVoxelizationSink();
private static int loggedVoxelizationSkips;
private static MultiDrawMode installedBatchMode;
public AngelicaChunkRenderer(RenderDevice device, RenderPassConfiguration<?> renderPassConfiguration) {
super(device, renderPassConfiguration, createEmitter());
super(device, renderPassConfiguration);
installBatchFactory();
this.culler = createCuller();
final IrisShaderProvider provider = IrisShaderProviderHolder.getProvider();
if (provider != null) {
@@ -65,10 +84,18 @@ class AngelicaChunkRenderer extends DefaultChunkRenderer {
}
}
private static MultiDrawEmitter createEmitter() {
private static void installBatchFactory() {
final MultiDrawMode configured = ClientProxy.options().advanced.multiDrawMode;
final MultiDrawMode mode = MultiDrawModeResolver.resolve();
if (BackendManager.RENDER_BACKEND.isIndirectRequired() && mode != MultiDrawMode.INDIRECT) {
throw new IllegalStateException(
"Indirect multi-draw was required by the backend but resolved mode is " + mode);
}
if (mode == installedBatchMode) return;
installedBatchMode = mode;
if (mode != configured) {
if (mode == MultiDrawMode.INDIRECT) {
AngelicaMod.LOGGER.info("Backend requires indirect draw; {} -> INDIRECT", configured);
@@ -77,22 +104,40 @@ class AngelicaChunkRenderer extends DefaultChunkRenderer {
}
}
if (BackendManager.RENDER_BACKEND.isIndirectRequired() && mode != MultiDrawMode.INDIRECT) {
throw new IllegalStateException("Indirect multi-draw was required by the backend but resolved mode is " + mode);
}
BatchAssembler.setBatchFactory(switch (mode) {
case DIRECT -> DirectMultiDrawBatch::new;
case INDIRECT -> IndirectMultiDrawBatch::new;
case INDIVIDUAL -> IndividualDrawBatch::new;
});
}
private enum VoxelizationSkip {
NO_RENDER_LISTS("pass has no render lists"),
NO_DEFERRED_PIPELINE("no deferred pipeline"),
NO_VOXELIZATION_COMPUTE("pack declares no shadow voxelization");
private final String message;
VoxelizationSkip(String message) {
this.message = message;
}
}
private static void logVoxelizationSkipOnce(VoxelizationSkip reason) {
final int bit = 1 << reason.ordinal();
if ((loggedVoxelizationSkips & bit) != 0) return;
loggedVoxelizationSkips |= bit;
AngelicaMod.LOGGER.info("shadow voxelization skipped: {}", reason.message);
}
private static GpuTerrainCuller createCuller() {
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());
return new GpuTerrainCuller(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();
case INDIVIDUAL -> new IndividualDrawEmitter();
};
return null;
}
private static GlShader loadShader(ShaderType type, String path, ShaderConstants constants) {
@@ -102,7 +147,6 @@ class AngelicaChunkRenderer extends DefaultChunkRenderer {
@Override
protected void begin(TerrainRenderPass pass) {
this.regionIndex = 0;
if (Tracy.ENABLED) Tracy.beginZone(Z_CHUNK_BEGIN);
try {
final IrisShaderProvider provider = IrisShaderProviderHolder.getProvider();
@@ -181,6 +225,10 @@ class AngelicaChunkRenderer extends DefaultChunkRenderer {
public void delete(CommandList commandList) {
super.delete(commandList);
if (culler != null) {
culler.delete();
}
unbindRgssSampler();
RenderSystem.destroySampler(rgssSampler);
rgssSampler = 0;
@@ -210,48 +258,116 @@ 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);
public void render(ChunkRenderMatrices matrices, CommandList commandList, ChunkRenderListIterable renderLists,
TerrainRenderPass renderPass, CameraTransform occlusionCamera, CameraTransform camera) {
if (culler != null) {
culler.beginRenderPass(matrices, renderLists, renderPass, occlusionCamera, camera, useBlockFaceCulling());
}
try {
regionIndex++;
super.drawRegion(shader, commandList, region, camera, timestamp);
voxelizeShadowTerrain(matrices, renderLists, renderPass, occlusionCamera, camera);
super.render(matrices, commandList, renderLists, renderPass, occlusionCamera, camera);
} finally {
if (Tracy.ENABLED) Tracy.endZone();
if (culler != null) {
culler.endPass();
}
}
}
@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);
protected @Nullable CachedBatch getRegionBatch(CommandList commandList, RenderRegion region,
SectionRenderDataStorage storage, ChunkRenderList renderList,
CameraTransform occlusionCamera, TerrainRenderPass renderPass,
boolean useBlockFaceCulling,
SectionRenderDataStorage.BatchCacheParams cacheParams) {
if (culler != null && culler.isComputeActiveThisPass()) {
final MultiDrawBatch batch = culler.batchForRegion(region);
if (batch == null) return null;
return this.gpuBatch.wrap(batch, prepareTessellation(commandList, region, renderPass));
}
if (!Tracy.ENABLED) {
return super.getRegionBatch(commandList, region, storage, renderList, occlusionCamera, renderPass,
useBlockFaceCulling, cacheParams);
}
final long batchesCreatedBefore = BatchAssembler.getCachedBatchesCreated();
Tracy.beginZone(Z_CHUNK_ASSEMBLE_REGION);
try {
final CachedBatch cached = super.getRegionBatch(commandList, region, storage, renderList, occlusionCamera,
renderPass, useBlockFaceCulling, cacheParams);
if (BatchAssembler.getCachedBatchesCreated() != batchesCreatedBefore) TerrainDrawStats.recordRebuild();
final MultiDrawBatch batch = cached != null ? cached.getBatch() : null;
if (batch != null && !batch.isEmpty()) TerrainDrawStats.recordBatch(batch.size());
return cached;
} finally {
Tracy.endZone();
}
}
@Override
protected void executeBatch(CommandList commandList, MultiDrawBatch batch, GlTessellation tessellation, GlPrimitiveType primitiveType) {
TerrainDrawStats.beginExecuteZone();
try {
super.executeBatch(commandList, batch, tessellation, primitiveType);
} finally {
TerrainDrawStats.endExecuteZone();
}
}
private static final class ReusableCachedBatch extends CachedBatch {
private static final byte[] NO_SECTIONS = new byte[0];
private MultiDrawBatch batch;
private GlTessellation tessellation;
ReusableCachedBatch() {
super(null, null, NO_SECTIONS, 0, 0, 0, 0, 0, 0, 0);
}
CachedBatch wrap(MultiDrawBatch batch, GlTessellation tessellation) {
this.batch = batch;
this.tessellation = tessellation;
return this;
}
@Override
public MultiDrawBatch getBatch() {
return this.batch;
}
@Override
public GlTessellation getTessellation() {
return this.tessellation;
}
}
private void voxelizeShadowTerrain(ChunkRenderMatrices matrices, ChunkRenderListIterable renderLists, TerrainRenderPass renderPass, CameraTransform occlusionCamera, CameraTransform camera) {
if (!BackendManager.RENDER_BACKEND.isSDLGPU()) return;
if (!ShadowRenderingState.areShadowsCurrentlyBeingRendered()) return;
if (!renderLists.hasPass(renderPass)) {
logVoxelizationSkipOnce(VoxelizationSkip.NO_RENDER_LISTS);
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();
final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable();
if (!(pipeline instanceof DeferredWorldRenderingPipeline deferred)) {
logVoxelizationSkipOnce(VoxelizationSkip.NO_DEFERRED_PIPELINE);
return;
}
final ComputeProgram voxelCompute = deferred.getShadowVoxelizationCompute();
if (voxelCompute == null) {
logVoxelizationSkipOnce(VoxelizationSkip.NO_VOXELIZATION_COMPUTE);
return;
}
}
@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);
}
final int prevProgram = GLStateManager.glGetInteger(GL20.GL_CURRENT_PROGRAM);
voxelCompute.use();
deferred.prepareShadowVoxelizationCompute(matrices.modelView());
try {
super.executeBatch(commandList, tessellation, primitiveType);
shadowVoxelizer.walkPass(renderLists, renderPass, renderPass.vertexType().getVertexFormat(), camera, occlusionCamera, useBlockFaceCulling(), shadowVoxelSink);
} finally {
if (Tracy.ENABLED) Tracy.endZone();
if (prevProgram != 0) GLStateManager.glUseProgram(prevProgram);
}
}
@@ -5,7 +5,6 @@ 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;
@@ -50,6 +49,7 @@ public class AngelicaRenderSectionManager extends RenderSectionManager {
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_DRAW_REGION_BUFFERS = Tracy.plotHandle("draw.regionBuffers");
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);
@@ -91,27 +91,12 @@ public class AngelicaRenderSectionManager extends RenderSectionManager {
this.cameraPosition.set(x, y, z);
}
private boolean isChunkNotLoaded(int chunkX, int chunkZ) {
return this.world.getChunkFromChunkCoords(chunkX, chunkZ).isEmpty();
}
@Override
public void onSectionAdded(int x, int y, int z) {
super.onSectionAdded(x, y, z);
// If chunk isn't actually loaded (EmptyChunk placeholder), make sections opaque for main pass.
// This prevents BFS from traversing through chunks we haven't received from the server.
if (isChunkNotLoaded(x, z)) {
renderListManager.updateVisibilityData(x, y, z, 0L);
}
}
@Override
public void update(Viewport positionedViewport, int frame, boolean spectator) {
if (isInShadowPass() && !needsUpdate()) {
if (isInShadowPass()) {
return;
}
if (!isInShadowPass() && !initialCameraSectionReady) {
if (!initialCameraSectionReady) {
var origin = positionedViewport.getChunkCoord();
long key = PositionUtil.packSection(origin.x(), origin.y(), origin.z());
if (!((RenderSectionManagerAccessor) this).angelica$getSectionByPosition().containsKey(key)) {
@@ -132,6 +117,11 @@ public class AngelicaRenderSectionManager extends RenderSectionManager {
return true;
}
@Override
protected boolean useRasterOcclusionCulling() {
return false;
}
@Override
protected boolean useFogOcclusion() {
return ClientProxy.options().performance.useFogOcclusion && !IrisShaderProviderHolder.isActive();
@@ -267,14 +257,15 @@ 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;
@Override
public boolean canSubmitShadowGraphSearch() {
return super.canSubmitShadowGraphSearch() && this.shadowRenderListManager.isNeedsUpdate()
&& !this.shadowRenderListManager.hasOcclusionFutureInFlight();
}
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;
@Override
public boolean submitShadowGraphSearch(Viewport viewport, int frame) {
return super.submitShadowGraphSearch(viewport, frame);
}
public boolean isShadowGraphDirty() {
@@ -361,5 +352,6 @@ public class AngelicaRenderSectionManager extends RenderSectionManager {
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);
Tracy.plotInt(P_DRAW_REGION_BUFFERS, mem.bufferCount);
}
}
@@ -248,12 +248,19 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
@Override
protected void renderBlockEntityList(List<TileEntity> list, TileEntityRenderContext context) {
for (int i = 0; i < list.size(); i++) {
final TileEntity te = list.get(i);
collectVisibleBlockEntities(list);
}
private int collectVisibleBlockEntities(List<TileEntity> 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;
}
private CameraState lastMainCameraState;
@@ -290,7 +297,7 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
collectTileEntitiesForShadow();
}
} else if (IrisShaderProviderHolder.isActive()) {
IrisShaderProviderHolder.getProvider().preSubmitShadowGraph(frame, spectator);
IrisShaderProviderHolder.getProvider().preSubmitShadowGraph(frame);
}
}
@@ -393,7 +400,7 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
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.teFrustum = viewport != null && ClientProxy.options().performance.sectionGatedTesrCulling && viewport.getFrustum() instanceof SimpleFrustum simpleFrustum ? simpleFrustum.getFrustumIntersection() : null;
this.teCullEpoch++;
this.teCamX = TileEntityRendererDispatcher.staticPlayerX;
this.teCamY = TileEntityRendererDispatcher.staticPlayerY;
@@ -470,15 +477,7 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
}
}
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;
return collectVisibleBlockEntities(blockEntities);
}
int count = 0;
@@ -0,0 +1,32 @@
package com.gtnewhorizons.angelica.rendering.celeritas;
import static org.taumc.celeritas.lwjgl.LWJGLServiceProvider.LWJGL;
import static org.taumc.celeritas.lwjgl.LWJGLServiceProvider.POINTER_SIZE;
import org.embeddedt.embeddium.impl.gl.device.CommandList;
import org.embeddedt.embeddium.impl.gl.device.DirectMultiDrawBatch;
import org.embeddedt.embeddium.impl.gl.device.DrawCommandList;
import org.embeddedt.embeddium.impl.gl.tessellation.GlIndexType;
import org.embeddedt.embeddium.impl.gl.tessellation.GlPrimitiveType;
import org.embeddedt.embeddium.impl.gl.tessellation.GlTessellation;
public class IndividualDrawBatch extends DirectMultiDrawBatch {
public IndividualDrawBatch(int capacity) {
super(capacity);
}
@Override
public void execute(CommandList commandList, GlTessellation tessellation, GlPrimitiveType primitiveType) {
try (DrawCommandList ignored = commandList.beginTessellating(tessellation)) {
final int mode = primitiveType.getId();
final int type = GlIndexType.UNSIGNED_INT.getFormatId();
final int commands = this.size();
for (int i = 0; i < commands; i++) {
final int count = LWJGL.memGetInt(this.pElementCount + (long) i * Integer.BYTES);
LWJGL.glDrawElementsBaseVertex(mode, count, type, LWJGL.memGetAddress(this.pElementPointer + (long) i * POINTER_SIZE), LWJGL.memGetInt(this.pBaseVertex + (long) i * Integer.BYTES));
}
}
}
}
@@ -1,44 +0,0 @@
package com.gtnewhorizons.angelica.rendering.celeritas;
import static com.mitchej123.lwjgl.LWJGLServiceProvider.LWJGL;
import static com.mitchej123.lwjgl.LWJGLServiceProvider.POINTER_SIZE;
import org.embeddedt.embeddium.impl.gl.device.CommandList;
import org.embeddedt.embeddium.impl.gl.device.DrawCommandList;
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.render.chunk.multidraw.DrawCommandSink;
import org.embeddedt.embeddium.impl.render.chunk.multidraw.MultiDrawEmitter;
public record IndividualDrawEmitter(MultiDrawBatch batch) implements MultiDrawEmitter {
public IndividualDrawEmitter() {
this(new MultiDrawBatch(MAX_COMMAND_COUNT));
}
@Override
public DrawCommandSink getCommandSink() {
return this.batch;
}
@Override
public void executeBatch(CommandList commandList, GlTessellation tessellation, GlPrimitiveType primitiveType) {
try (DrawCommandList ignored = commandList.beginTessellating(tessellation)) {
final int mode = primitiveType.getId();
final int type = GlIndexType.UNSIGNED_INT.getFormatId();
for (int i = 0; i < batch.size; i++) {
final int count = LWJGL.memGetInt(batch.pElementCount + (long) i * Integer.BYTES);
if (count > 0) {
LWJGL.glDrawElementsBaseVertex(mode, count, type, LWJGL.memGetAddress(batch.pElementPointer + (long) i * POINTER_SIZE), LWJGL.memGetInt(batch.pBaseVertex + (long) i * Integer.BYTES));
}
}
}
}
@Override
public void delete() {
this.batch.delete();
}
}
@@ -1,17 +1,55 @@
package com.gtnewhorizons.angelica.rendering.celeritas;
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
public final class TerrainDrawStats {
private static final Tracy.ZoneId Z_EXECUTE_BATCH = Tracy.zoneId("chunkExecuteBatch", Tracy.COLOR_TERRAIN);
private static int commandsSubmitted;
private static int regionsDrawn;
private static int batchRebuilds;
private static int cullCommandsSubmitted;
private static int cullRegionsDrawn;
private static int cullMaxRegionCommands;
private static long sectionMetaBytes;
private TerrainDrawStats() {
}
public static void beginExecuteZone() {
if (Tracy.ENABLED) Tracy.beginZone(Z_EXECUTE_BATCH);
}
public static void endExecuteZone() {
if (Tracy.ENABLED) Tracy.endZone();
}
public static void recordBatch(int commandCount) {
commandsSubmitted += commandCount;
regionsDrawn++;
}
public static void recordRebuild() {
batchRebuilds++;
}
public static void recordCullRegion(int commandCount) {
cullCommandsSubmitted += commandCount;
cullRegionsDrawn++;
if (commandCount > cullMaxRegionCommands) cullMaxRegionCommands = commandCount;
}
public static void recordSectionMetaBytes(int bytes) {
sectionMetaBytes += bytes;
}
public static int takeBatchRebuilds() {
final int n = batchRebuilds;
batchRebuilds = 0;
return n;
}
public static int takeCommandsSubmitted() {
final int n = commandsSubmitted;
commandsSubmitted = 0;
@@ -23,4 +61,28 @@ public final class TerrainDrawStats {
regionsDrawn = 0;
return n;
}
public static int takeCullCommandsSubmitted() {
final int n = cullCommandsSubmitted;
cullCommandsSubmitted = 0;
return n;
}
public static int takeCullRegionsDrawn() {
final int n = cullRegionsDrawn;
cullRegionsDrawn = 0;
return n;
}
public static int takeCullMaxRegionCommands() {
final int n = cullMaxRegionCommands;
cullMaxRegionCommands = 0;
return n;
}
public static long takeSectionMetaBytes() {
final long n = sectionMetaBytes;
sectionMetaBytes = 0;
return n;
}
}
@@ -28,5 +28,5 @@ public interface IrisShaderProvider {
/** Block render layer overrides from shader pack */
@Nullable Map<Block, BlockRenderLayer> getBlockTypeIds();
default void preSubmitShadowGraph(int frame, boolean spectator) {}
default void preSubmitShadowGraph(int frame) {}
}
@@ -19,9 +19,6 @@ import org.embeddedt.embeddium.impl.render.chunk.terrain.material.Material;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexEncoder;
import org.joml.Vector3f;
/**
* Writes Iris-extended vertices. Delegates base 28 bytes to VANILLA_LIKE encoder.
*/
public class IrisExtendedChunkVertexEncoder implements ContextAwareChunkVertexEncoder {
// Offsets derived from format definition
private static final int MID_TEX_OFFSET = IrisExtendedChunkVertexType.VERTEX_FORMAT.getAttribute("mc_midTexCoord").getPointer();
@@ -101,6 +98,11 @@ public class IrisExtendedChunkVertexEncoder implements ContextAwareChunkVertexEn
}
}
@Override
public boolean supportsBilinearCorrection() {
return false;
}
@Override
public long write(long ptr, Material material, Vertex vertex, int sectionIndex) {
uSum += vertex.u;
@@ -109,6 +111,7 @@ public class IrisExtendedChunkVertexEncoder implements ContextAwareChunkVertexEn
final BlockRenderContext ctx = context;
vertex.rdhFactor = 0;
baseEncoder.write(ptr, material, vertex, sectionIndex);
// Per-vertex: mc_Entity (packed blockId + renderType), midBlock, lightValue
@@ -6,22 +6,15 @@ import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkMeshFormats;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexEncoder;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexType;
/**
* VANILLA_LIKE (28 bytes) + Iris extensions (20 bytes) = 48 bytes total.
*
* Iris extensions:
* mc_midTexCoord ushort[2] - quad center UV (average of 4 vertices)
* at_tangent byte[4] - tangent vector, normalized
* iris_Normal byte[3]+1 - face normal, normalized
* mc_Entity uint - packed as ((blockId + 1) << 1) | (renderType & 1)
* at_midBlock byte[4] - (xyz offset from block center, lightValue)
*/
import java.util.stream.Collectors;
public class IrisExtendedChunkVertexType implements ChunkVertexType {
public static final ChunkVertexType BASE_TYPE = ChunkMeshFormats.VANILLA_LIKE;
public static final int STRIDE = 48;
public static final GlVertexFormat VERTEX_FORMAT = GlVertexFormat.builder(STRIDE)
.addAllElements(BASE_TYPE.getVertexFormat())
.addElements(BASE_TYPE.getVertexFormat().getAttributes().stream()
.filter(a -> !a.getName().equals("a_RdhFactor")).collect(Collectors.toList()))
.addElement("mc_midTexCoord", GlVertexFormat.NEXT_ALIGNED_POINTER, GlVertexAttributeFormat.UNSIGNED_SHORT, 2, false, false)
.addElement("at_tangent", GlVertexFormat.NEXT_ALIGNED_POINTER, GlVertexAttributeFormat.BYTE, 4, true, false)
.addElement("iris_Normal", GlVertexFormat.NEXT_ALIGNED_POINTER, GlVertexAttributeFormat.BYTE, 3, true, false)
@@ -0,0 +1,46 @@
package com.gtnewhorizons.angelica.rendering.culling;
import org.embeddedt.embeddium.impl.gl.device.CommandList;
import org.embeddedt.embeddium.impl.gl.device.MultiDrawBatch;
import org.embeddedt.embeddium.impl.gl.tessellation.GlPrimitiveType;
import org.embeddedt.embeddium.impl.gl.tessellation.GlTessellation;
public final class GpuCulledMultiDrawBatch extends MultiDrawBatch {
private final GpuTerrainCuller culler;
private int drawStart;
GpuCulledMultiDrawBatch(GpuTerrainCuller culler) {
super(MAX_COMMAND_COUNT);
this.culler = culler;
}
void prepare(int drawStart, int drawCount, int maxElementCount) {
this.drawStart = drawStart;
this.size = drawCount;
this.maxElementCount = maxElementCount;
}
@Override
public void appendDrawCommand(int baseVertex, int elementCount, long elementPointer) {
throw new UnsupportedOperationException("GPU-culled batches build their commands on the GPU");
}
@Override
public void mergeIntoLastCommand(int additionalElementCount) {
throw new UnsupportedOperationException("GPU-culled batches build their commands on the GPU");
}
@Override
public void upload(CommandList commandList) {
}
@Override
public void delete() {
}
@Override
public void execute(CommandList commandList, GlTessellation tessellation, GlPrimitiveType primitiveType) {
this.culler.drawRegionRange(commandList, tessellation, primitiveType, this.drawStart, this.size);
}
}
@@ -1,382 +0,0 @@
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,543 @@
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 com.gtnewhorizons.angelica.mixins.interfaces.SectionRenderDataStorageRegionAccessor;
import com.gtnewhorizons.angelica.rendering.celeritas.AngelicaRenderPassConfiguration;
import com.gtnewhorizons.angelica.rendering.celeritas.TerrainDrawStats;
import lombok.Getter;
import net.coderbot.iris.pipeline.ShadowRenderer;
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.model.quad.properties.ModelQuadFacing;
import org.embeddedt.embeddium.impl.render.chunk.ChunkRenderMatrices;
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 org.joml.Matrix4f;
import org.joml.Matrix4fc;
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;
import java.util.Arrays;
public final class GpuTerrainCuller {
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 long[] EMPTY_RANGES = new long[0];
private static final int[] EMPTY_STAMPS = new int[0];
private static final class PassState {
int entryBase;
int entryCount;
int indexPointerMask;
int maxElementCount;
boolean dispatched;
int stamp;
long[] regionRanges = EMPTY_RANGES;
int[] regionStamps = EMPTY_STAMPS;
void reset(int mask, int base) {
entryBase = base;
entryCount = 0;
indexPointerMask = mask;
maxElementCount = 0;
dispatched = false;
stamp++;
if (stamp == 0) {
Arrays.fill(regionStamps, 0);
stamp = 1;
}
}
void putRange(int regionId, long packed) {
if (regionId >= regionStamps.length) {
final int cap = Math.max(regionId + 1, Math.max(regionStamps.length * 2, 64));
regionRanges = Arrays.copyOf(regionRanges, cap);
regionStamps = Arrays.copyOf(regionStamps, cap);
}
regionRanges[regionId] = packed;
regionStamps[regionId] = stamp;
}
long getRange(int regionId) {
if (regionId >= regionStamps.length || regionStamps[regionId] != stamp) return -1L;
return regionRanges[regionId];
}
void releaseRanges() {
regionRanges = EMPTY_RANGES;
regionStamps = EMPTY_STAMPS;
}
}
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 boolean indirectBufferBound;
private ByteBuffer frustumUboBytes;
private final GpuCulledMultiDrawBatch batch = new GpuCulledMultiDrawBatch(this);
private ByteBuffer uboBytes;
private Matrix4f mvp;
private Matrix4f mvNoTranslation;
private int passOutputBase;
private ChunkPrimitiveType walkPrimitiveType;
private final SectionMetaBuffer.Sink uploadSectionMetaSink;
public GpuTerrainCuller(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) TerrainDrawStats.recordSectionMetaBytes(bytes);
return true;
};
}
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;
}
void beginCombinedPasses(int firstMask, int secondMask) {
beginCullPass(firstMask);
secondPass.reset(secondMask, 0);
}
void startSecondPass() {
primaryPass.entryCount = totalAppendedEntries - primaryPass.entryBase;
secondPass.entryBase = totalAppendedEntries;
this.buildPass = secondPass;
this.current = secondPass;
}
void finishCombinedBuild() {
secondPass.entryCount = totalAppendedEntries - secondPass.entryBase;
this.secondPrepared = true;
this.buildPass = primaryPass;
this.current = primaryPass;
}
boolean selectPreparedSecondPass() {
if (!secondPrepared || !computeActiveThisPass) return false;
this.current = secondPass;
this.currentDrawStart = 0;
this.currentDrawCount = 0;
return true;
}
void reserveSections(int count) {
if (count > 0) ensureStagingCapacity(totalAppendedEntries + count);
}
void 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 off = totalAppendedEntries * ENTRY_BYTES;
visibleStaging.putInt(off + 0, slot);
visibleStaging.putInt(off + 4, (outputBase << 8) | (facingMask & 0xFF));
totalAppendedEntries++;
buildPass.entryCount = totalAppendedEntries - buildPass.entryBase;
}
void recordRegion(RenderRegion region, int drawStart, int drawCount, int maxElementCount) {
if (drawCount <= 0) return;
buildPass.putRange(region.getId(), (((long) drawStart) << 32) | (drawCount & 0xFFFFFFFFL));
if (maxElementCount > buildPass.maxElementCount) buildPass.maxElementCount = maxElementCount;
}
private void prepareRegion(RenderRegion region) {
final long packed = current.getRange(region.getId());
if (packed < 0L) {
currentDrawStart = 0;
currentDrawCount = 0;
} else {
currentDrawStart = (int) (packed >>> 32);
currentDrawCount = (int) (packed & 0xFFFFFFFFL);
}
}
void syncSectionMetaIfDirty() {
culler.ensureReady();
sectionMeta.syncIfDirty(uploadSectionMetaSink);
}
public void endPass() {
if (indirectBufferBound) {
GLStateManager.glBindBuffer(GL40.GL_DRAW_INDIRECT_BUFFER, 0);
indirectBufferBound = false;
}
currentDrawStart = 0;
currentDrawCount = 0;
if (current == secondPass) secondPrepared = false;
}
private void dispatchPreparedPasses() {
if (!computeActiveThisPass || totalAppendedEntries == 0) return;
if (!needsDispatch(primaryPass) && (!secondPrepared || !needsDispatch(secondPass))) return;
if (!culler.ensureReady()) return;
if (frustumUboBytes == null) {
LOG.warn("GpuTerrainCuller: 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);
GLStateManager.glBufferData(GL43.GL_SHADER_STORAGE_BUFFER, (long) newCap * GpuDrivenChunkCuller.FACINGS_PER_SECTION * GpuDrivenChunkCuller.INDIRECT_COMMAND_BYTES, 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;
}
public void beginRenderPass(ChunkRenderMatrices matrices, ChunkRenderListIterable renderLists, TerrainRenderPass renderPass, CameraTransform occlusionCamera, CameraTransform camera, boolean useBlockFaceCulling) {
if (renderPass == AngelicaRenderPassConfiguration.CUTOUT_MIPPED_PASS && renderLists.hasPass(renderPass)
&& selectPreparedSecondPass()) {
return;
}
if (!renderLists.hasPass(renderPass)) return;
final boolean combined = renderPass == AngelicaRenderPassConfiguration.SOLID_PASS && AngelicaRenderPassConfiguration.CUTOUT_MIPPED_PASS != null && renderLists.hasPass(AngelicaRenderPassConfiguration.CUTOUT_MIPPED_PASS);
final int indexPointerMask = renderPass.isSorted() ? 0xFFFFFFFF : 0;
if (combined) {
beginCombinedPasses(0, 0);
} else {
beginCullPass(indexPointerMask);
}
passOutputBase = 0;
walkPrimitiveType = null;
if (!computeActiveThisPass) {
return;
}
if (uboBytes == null) {
uboBytes = FrustumExtractor.allocateUboByteBuffer();
}
final boolean shadow = ShadowRenderer.ACTIVE;
final Matrix4fc proj = matrices.projection();
final Matrix4fc mv = matrices.modelView();
if (mvp == null) mvp = new Matrix4f();
if (mvNoTranslation == null) mvNoTranslation = new Matrix4f();
mvNoTranslation.set(mv).setTranslation(0f, 0f, 0f);
proj.mul(mvNoTranslation, mvp);
final float camX = (float) camera.intX + camera.fracX;
final float camY = (float) camera.intY + camera.fracY;
final float camZ = (float) camera.intZ + camera.fracZ;
FrustumExtractor.writeStd140(mvp, 0, 0, uboBytes);
FrustumExtractor.patchCameraWorld(camX, camY, camZ, uboBytes);
FrustumExtractor.patchBypassFrustum(shadow, uboBytes);
frustumUboBytes = uboBytes;
syncSectionMetaIfDirty();
walkPass(renderLists, renderPass, occlusionCamera, useBlockFaceCulling);
if (combined) {
startSecondPass();
walkPass(renderLists, AngelicaRenderPassConfiguration.CUTOUT_MIPPED_PASS, occlusionCamera, useBlockFaceCulling);
finishCombinedBuild();
}
if (walkPrimitiveType != null) {
FrustumExtractor.patchPrimitiveRatio(walkPrimitiveType.getVerticesPerPrimitive(), walkPrimitiveType.getIndexBufferElementsPerPrimitive(), uboBytes);
}
}
private void walkPass(ChunkRenderListIterable renderLists, TerrainRenderPass renderPass, CameraTransform occlusionCamera, boolean useBlockFaceCulling) {
if (renderPass.isSorted()) {
walkSortedPass(renderLists, renderPass);
} else {
walkMergedPass(renderLists, renderPass, occlusionCamera, useBlockFaceCulling);
}
}
private void walkMergedPass(ChunkRenderListIterable renderLists, TerrainRenderPass renderPass, CameraTransform occlusionCamera, boolean useBlockFaceCulling) {
final boolean reverse = renderPass.isReverseOrder();
final int step = reverse ? -1 : 1;
final long stride = SectionRenderDataUnsafe.Strategy.COMPACT.getStride();
final int cameraX = occlusionCamera.intX;
final int cameraY = occlusionCamera.intY;
final int cameraZ = occlusionCamera.intZ;
final int n = renderLists.getNumRegions();
for (int regionIndex = 0; regionIndex < n; regionIndex++) {
final ChunkRenderList list = renderLists.getRegion(reverse ? n - 1 - regionIndex : regionIndex);
final RenderRegion region = list.getRegion();
final SectionRenderDataStorage storage = region.getStorage(renderPass);
if (storage == null) continue;
final byte[] sections = list.getSectionsWithGeometry();
final int sectionCount = list.getSectionsWithGeometryCount();
if (sectionCount == 0) continue;
final SectionRenderDataStorageRegionAccessor accessor = (SectionRenderDataStorageRegionAccessor) storage;
final ChunkPrimitiveType primitiveType = storage.getPrimitiveType();
trackPrimitiveType(primitiveType);
final int[] slotCache = accessor.angelica$getSlotCache();
if (slotCache == null) continue;
reserveSections(sectionCount);
final long pBase = storage.getRowBasePointer();
final int regionOriginX = region.getChunkX();
final int regionOriginY = region.getChunkY();
final int regionOriginZ = region.getChunkZ();
final int uniformMask = useBlockFaceCulling ? BatchAssembler.uniformCullMask(region, occlusionCamera) : ModelQuadFacing.ALL;
final int regionDrawStart = passOutputBase;
int regionDrawCount = 0;
int regionMaxElems = 0;
int cursor = reverse ? sectionCount - 1 : 0;
for (int i = 0; i < sectionCount; i++, cursor += step) {
final int sectionIndex = sections[cursor] & 0xFF;
int slices = uniformMask != BatchAssembler.MASK_NOT_UNIFORM ? uniformMask : BatchAssembler.getVisibleFaces(cameraX, cameraY, cameraZ, regionOriginX + LocalSectionIndex.unpackX(sectionIndex), regionOriginY + LocalSectionIndex.unpackY(sectionIndex), regionOriginZ + LocalSectionIndex.unpackZ(sectionIndex));
slices &= storage.getSliceMask(sectionIndex);
if (slices == 0) continue;
final int slot = slotCache[sectionIndex];
if (slot < 0) continue;
final long pMeshData = pBase + (sectionIndex * stride);
final long runs = BatchAssembler.packRuns(slices & 0x7F);
final int sectionDraws = BatchAssembler.runCount(runs);
appendSection(slot, slices, passOutputBase);
passOutputBase += sectionDraws;
regionDrawCount += sectionDraws;
int maxElems = 0;
for (int run = 0; run < sectionDraws; run++) {
final int startVertex = SectionRenderDataUnsafe.Strategy.COMPACT.getVertexOffset(pMeshData, BatchAssembler.runFirst(runs, run));
final int endVertex = SectionRenderDataUnsafe.Strategy.COMPACT.getRunVertexEnd(pMeshData, BatchAssembler.runLast(runs, run), primitiveType);
final int ec = SectionRenderDataUnsafe.elementsForVertices(endVertex - startVertex, primitiveType);
if (ec > maxElems) maxElems = ec;
}
if (maxElems > regionMaxElems) regionMaxElems = maxElems;
}
if (regionDrawCount > 0) {
recordRegion(region, regionDrawStart, regionDrawCount, regionMaxElems);
}
}
}
private void walkSortedPass(ChunkRenderListIterable renderLists, TerrainRenderPass renderPass) {
final boolean reverse = renderPass.isReverseOrder();
final int step = reverse ? -1 : 1;
final long stride = SectionRenderDataUnsafe.Strategy.FULL.getStride();
final int n = renderLists.getNumRegions();
for (int regionIndex = 0; regionIndex < n; regionIndex++) {
final ChunkRenderList list = renderLists.getRegion(reverse ? n - 1 - regionIndex : regionIndex);
final RenderRegion region = list.getRegion();
final SectionRenderDataStorage storage = region.getStorage(renderPass);
if (storage == null) continue;
final byte[] sections = list.getSectionsWithGeometry();
final int sectionCount = list.getSectionsWithGeometryCount();
if (sectionCount == 0) continue;
final SectionRenderDataStorageRegionAccessor accessor = (SectionRenderDataStorageRegionAccessor) storage;
final ChunkPrimitiveType primitiveType = storage.getPrimitiveType();
trackPrimitiveType(primitiveType);
final int[] slotCache = accessor.angelica$getSlotCache();
if (slotCache == null) continue;
reserveSections(sectionCount);
final long pBase = storage.getRowBasePointer();
final int regionDrawStart = passOutputBase;
int regionDrawCount = 0;
int regionMaxElems = 0;
int cursor = reverse ? sectionCount - 1 : 0;
for (int i = 0; i < sectionCount; i++, cursor += step) {
final int sectionIndex = sections[cursor] & 0xFF;
final int slices = ModelQuadFacing.ALL & storage.getSliceMask(sectionIndex);
if (slices == 0) continue;
final int slot = slotCache[sectionIndex];
if (slot < 0) continue;
final long pMeshData = pBase + (sectionIndex * stride);
final int sectionDraws = Integer.bitCount(slices);
appendSection(slot, slices, passOutputBase);
passOutputBase += sectionDraws;
regionDrawCount += sectionDraws;
int maxElems = 0;
for (int f = 0; f < ModelQuadFacing.COUNT; f++) {
final int ec = SectionRenderDataUnsafe.Strategy.FULL.getElementCount(pMeshData, f, primitiveType);
if (ec > maxElems) maxElems = ec;
}
if (maxElems > regionMaxElems) regionMaxElems = maxElems;
}
if (regionDrawCount > 0) {
recordRegion(region, regionDrawStart, regionDrawCount, regionMaxElems);
}
}
}
private void trackPrimitiveType(ChunkPrimitiveType primitiveType) {
if (walkPrimitiveType == null) {
walkPrimitiveType = primitiveType;
} else if (walkPrimitiveType.getVerticesPerPrimitive() != primitiveType.getVerticesPerPrimitive() || walkPrimitiveType.getIndexBufferElementsPerPrimitive() != primitiveType.getIndexBufferElementsPerPrimitive()) {
throw new IllegalStateException("Batched cull dispatch spans passes with differing primitive ratios: " + walkPrimitiveType + " vs " + primitiveType);
}
}
public GpuCulledMultiDrawBatch batchForRegion(RenderRegion region) {
prepareRegion(region);
if (currentDrawCount == 0) return null;
batch.prepare(currentDrawStart, currentDrawCount, current.maxElementCount);
return batch;
}
void drawRegionRange(CommandList commandList, GlTessellation tessellation, GlPrimitiveType primitiveType, int drawStart, int drawCount) {
if (drawCount == 0) return;
dispatchPreparedPasses();
if (!current.dispatched) return;
if (Tracy.ENABLED) {
TerrainDrawStats.recordCullRegion(drawCount);
}
if (!indirectBufferBound) {
GLStateManager.glBindBuffer(GL40.GL_DRAW_INDIRECT_BUFFER, indirectSsboGlId);
indirectBufferBound = true;
}
final long offsetBytes = (long) drawStart * GpuDrivenChunkCuller.INDIRECT_COMMAND_BYTES;
try (DrawCommandList ignored = commandList.beginTessellating(tessellation)) {
GLStateManager.glMultiDrawElementsIndirect(primitiveType.getId(), GL11.GL_UNSIGNED_INT, offsetBytes, drawCount, 0);
}
}
public void delete() {
if (indirectBufferBound) {
GLStateManager.glBindBuffer(GL40.GL_DRAW_INDIRECT_BUFFER, 0);
indirectBufferBound = false;
}
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;
frustumUboBytes = null;
uboBytes = null;
primaryPass.releaseRanges();
secondPass.releaseRanges();
}
}
@@ -40,7 +40,7 @@ public final class SectionMetaBuffer {
}
public synchronized int update(int passIndex, int regionOriginX, int regionOriginY, int regionOriginZ, int localSectionIndex,
long dataPtr, SectionRenderDataUnsafe.Strategy layout, ChunkPrimitiveType primitiveType) {
long dataPtr, int sliceMask, 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);
@@ -51,7 +51,7 @@ public final class SectionMetaBuffer {
slot = allocateSlot();
keyToSlot.put(key, slot);
}
writeSlot(slot, sectionOriginX, sectionOriginY, sectionOriginZ, dataPtr, layout, primitiveType);
writeSlot(slot, sectionOriginX, sectionOriginY, sectionOriginZ, dataPtr, sliceMask, layout, primitiveType);
dirty = true;
return slot;
}
@@ -97,12 +97,12 @@ public final class SectionMetaBuffer {
capacity = newCapacity;
}
private void writeSlot(int slot, int sectionOriginX, int sectionOriginY, int sectionOriginZ, long dataPtr, SectionRenderDataUnsafe.Strategy layout, ChunkPrimitiveType primitiveType) {
private void writeSlot(int slot, int sectionOriginX, int sectionOriginY, int sectionOriginZ, long dataPtr, int sliceMask, 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));
mirror.putInt(base + OFFSET_SLICE_MASK, sliceMask);
for (int facing = 0; facing < FACING_COUNT; facing++) {
mirror.putInt(base + OFFSET_POSTS + facing * 4, layout.getVertexOffset(dataPtr, facing));
}
@@ -32,7 +32,7 @@ public final class SdlShadowVoxelizationSink implements ShadowVoxelizer.Sink {
@Override
public boolean region(RenderRegion region, GlVertexFormat format, float offsetX, float offsetY, float offsetZ) {
final RenderRegion.DeviceResources resources = region.getResources(format);
final RenderRegion.DeviceResources resources = region.getResources();
if (resources == null) return false;
final GlBuffer vertexBuffer = resources.getVertexBuffer();
if (vertexBuffer == null || vertexBuffer.handle() == 0) return false;
@@ -13,8 +13,6 @@ 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 {
@@ -29,16 +27,23 @@ public final class ShadowVoxelizer {
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);
final boolean reverse = renderPass.isReverseOrder();
final int n = renderLists.getNumRegions();
if (renderPass.isSorted()) {
for (int i = 0; i < n; i++) {
walkRegionFull(renderLists.getRegion(reverse ? n - 1 - i : i), renderPass, format, camera, sink);
}
} else {
for (int i = 0; i < n; i++) {
walkRegionCompact(renderLists.getRegion(reverse ? n - 1 - i : i), 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) {
private static void walkRegionCompact(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;
@@ -47,7 +52,8 @@ public final class ShadowVoxelizer {
if (sectionCount == 0) return;
final byte[] sections = list.getSectionsWithGeometry();
final SectionRenderDataUnsafe.Strategy layout = storage.getStorageStrategy();
final long pBase = storage.getRowBasePointer();
final long stride = SectionRenderDataUnsafe.Strategy.COMPACT.getStride();
final ChunkPrimitiveType primitiveType = storage.getPrimitiveType();
final int regionChunkX = region.getChunkX();
final int regionChunkY = region.getChunkY();
@@ -56,32 +62,27 @@ public final class ShadowVoxelizer {
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 &= storage.getSliceMask(sectionIndex);
slices &= 0x7F;
if (slices == 0) continue;
final long pMeshData = pBase + sectionIndex * stride;
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 startVertex = SectionRenderDataUnsafe.Strategy.COMPACT.getVertexOffset(pMeshData, BatchAssembler.runFirst(runs, run));
final int endVertex = SectionRenderDataUnsafe.Strategy.COMPACT.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;
}
if (!bindRegion(region, format, camera, sink)) return;
bound = true;
}
if (!sink.range(startVertex, vertexCount)) return;
@@ -89,6 +90,50 @@ public final class ShadowVoxelizer {
}
}
private static void walkRegionFull(ChunkRenderList list, TerrainRenderPass renderPass, GlVertexFormat format, CameraTransform camera, 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 long pBase = storage.getRowBasePointer();
final long stride = SectionRenderDataUnsafe.Strategy.FULL.getStride();
final ChunkPrimitiveType primitiveType = storage.getPrimitiveType();
boolean bound = false;
for (int i = 0; i < sectionCount; i++) {
final int sectionIndex = sections[i] & 0xFF;
final int slices = ModelQuadFacing.ALL & storage.getSliceMask(sectionIndex);
if (slices == 0) continue;
final long pMeshData = pBase + sectionIndex * stride;
final long runs = BatchAssembler.packRuns(slices);
final int runCount = BatchAssembler.runCount(runs);
for (int run = 0; run < runCount; run++) {
final int startVertex = SectionRenderDataUnsafe.Strategy.FULL.getVertexOffset(pMeshData, BatchAssembler.runFirst(runs, run));
final int endVertex = SectionRenderDataUnsafe.Strategy.FULL.getRunVertexEnd(pMeshData, BatchAssembler.runLast(runs, run), primitiveType);
final int vertexCount = endVertex - startVertex;
if (vertexCount <= 0) continue;
if (!bound) {
if (!bindRegion(region, format, camera, sink)) return;
bound = true;
}
if (!sink.range(startVertex, vertexCount)) return;
}
}
}
private static boolean bindRegion(RenderRegion region, GlVertexFormat format, CameraTransform camera, Sink sink) {
return 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));
}
private static float cameraRelative(int originBlock, int cameraBlock, float cameraFrac) {
return (originBlock - cameraBlock) - cameraFrac;
}
@@ -67,9 +67,9 @@ public class IrisCeleritasShaderProvider implements IrisShaderProvider {
}
@Override
public void preSubmitShadowGraph(int frame, boolean spectator) {
public void preSubmitShadowGraph(int frame) {
final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable();
if (pipeline != null) pipeline.preSubmitShadowGraph(frame, spectator);
if (pipeline != null) pipeline.preSubmitShadowGraph(frame);
}
public void deleteShaders() {
@@ -1908,8 +1908,8 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
}
@Override
public void preSubmitShadowGraph(int frame, boolean spectator) {
if (shadowRenderer != null) shadowRenderer.preSubmitGraphUpdate(frame, spectator);
public void preSubmitShadowGraph(int frame) {
if (shadowRenderer != null) shadowRenderer.preSubmitGraphUpdate(frame);
}
@Override
@@ -127,15 +127,41 @@ public class ShadowRenderer {
private final CelestialUniforms celestialUniforms;
private static final class MemoizedBoxCuller {
private BoxCuller culler;
private double lastDistance;
BoxCuller get(double distance) {
if (culler == null) {
culler = new BoxCuller(distance);
lastDistance = distance;
} else if (lastDistance != distance) {
culler.setMaxDistance(distance);
lastDistance = distance;
}
return culler;
}
}
private static final class FrustumCaches {
final AdvancedShadowCullingFrustum advancedFrustum = new AdvancedShadowCullingFrustum();
BoxCuller boxCuller;
final MemoizedBoxCuller boxCuller = new MemoizedBoxCuller();
final MemoizedBoxCuller advancedBoxCuller = new MemoizedBoxCuller();
final MemoizedBoxCuller safeZoneDistanceCuller = new MemoizedBoxCuller();
SafeZoneCullingFrustum safeZoneFrustum;
BoxCullingFrustum boxCullingFrustum;
BoxCuller advancedBoxCuller;
double lastBoxCullerDistance = -1;
double lastAdvancedBoxCullerDistance = -1;
String distanceInfo = "(unavailable)";
String cullingInfo = "(unavailable)";
int infoBranch = -1;
double infoDistance = Double.NaN;
int infoRenderDistanceBlocks = -1;
boolean infoHasSafeZone;
boolean infoPackSetter;
}
private static final int INFO_BRANCH_DISTANCE_ONLY = 0;
private static final int INFO_BRANCH_ADVANCED = 1;
private static final long SHADOW_RELAY_MAX_AGE_NANOS = 250_000_000L;
public static boolean SHADOW_TERRAIN_RELAID = true;
@@ -145,7 +171,7 @@ public class ShadowRenderer {
private final FrustumCaches entityFrustumCaches = new FrustumCaches();
private float lastGraphShadowAngle = Float.NaN;
private float relayShadowAngle = Float.NaN;
private FrustumHolder preSubmitFrustumHolder = new FrustumHolder();
private FrustumHolder preSubmitFrustumHolder = new FrustumHolder("preSubmit");
private final FrustumCaches preSubmitFrustumCaches = new FrustumCaches();
private boolean preSubmitActive;
private float preSubmittedShadowAngle = Float.NaN;
@@ -159,29 +185,28 @@ public class ShadowRenderer {
AngelicaConfig.shadowGraphHorizonScale);
}
public void preSubmitGraphUpdate(int frame, boolean spectator) {
public void preSubmitGraphUpdate(int frame) {
final AngelicaRenderSectionManager rsm = CeleritasWorldRenderer.getInstance().getRenderSectionManager();
final float currentShadowAngle = getShadowAngle();
if (ShadowGraphGate.shouldMarkDirty(lastGraphShadowAngle, currentShadowAngle, shadowAngleDelta())) {
rsm.markShadowGraphDirty();
lastGraphShadowAngle = currentShadowAngle;
}
if (!rsm.isShadowGraphDirty()) return;
if (!rsm.canSubmitShadowGraphSearch()) return;
preSubmitFrustumHolder = createShadowFrustum(renderDistanceMultiplier, preSubmitFrustumHolder, preSubmitFrustumCaches);
if (!(preSubmitFrustumHolder.getFrustum() instanceof ViewportProvider provider)) return;
final Vector3d entityPos = Camera.INSTANCE.getEntityPos();
preSubmitFrustumHolder.getFrustum().setPosition(entityPos.x, entityPos.y, entityPos.z);
if (rsm.preSubmitShadowGraphUpdate(provider.sodium$createViewport(), frame, spectator)) {
if (rsm.submitShadowGraphSearch(provider.sodium$createViewport(), frame)) {
preSubmittedShadowAngle = lastGraphShadowAngle;
preSubmitActive = true;
}
}
private long lastRelayNanos;
private final Vector3f shadowLightVectorCache = new Vector3f();
private BoxCuller cachedTileEntityCuller;
private double lastTileEntityCullerDistance = -1;
private final MemoizedBoxCuller tileEntityCuller = new MemoizedBoxCuller();
private final boolean shouldRenderDH;
private final float nearPlane, farPlane;
private final BooleanSupplier packUsesShadowtex1;
@@ -214,8 +239,8 @@ public class ShadowRenderer {
debugStringOverall = "half plane = " + halfPlaneLength + " meters @ " + resolution + "x" + resolution;
this.terrainFrustumHolder = new FrustumHolder();
this.entityFrustumHolder = new FrustumHolder();
this.terrainFrustumHolder = new FrustumHolder("terrain");
this.entityFrustumHolder = new FrustumHolder("entity");
this.fov = shadowDirectives.getFov();
this.targets = shadowRenderTargets;
@@ -390,117 +415,122 @@ public class ShadowRenderer {
private FrustumHolder createShadowFrustum(float renderMultiplier, FrustumHolder holder, FrustumCaches caches) {
// TODO: Cull entities / block entities with Advanced Frustum Culling even if voxelization is detected.
String distanceInfo;
String cullingInfo;
final int renderDistanceBlocks = Minecraft.getMinecraft().gameSettings.renderDistanceChunks * 16;
if ((packCullingState == ShadowCullState.DISTANCE || packHasVoxelization) && packCullingState != ShadowCullState.ADVANCED && packCullingState != ShadowCullState.SAFE_ZONE) {
double distance = halfPlaneLength * renderMultiplier;
final double distance = halfPlaneLength * renderMultiplier;
final boolean packSetter = packCullingState == ShadowCullState.DISTANCE;
final boolean capped = distance <= 0 || distance > renderDistanceBlocks;
String reason;
if (infoInputsChanged(caches, INFO_BRANCH_DISTANCE_ONLY, distance, renderDistanceBlocks, false, packSetter)) {
final String reason = packSetter ? "(set by shader pack)" : "(voxelization detected)";
if (packCullingState == ShadowCullState.DISTANCE) {
reason = "(set by shader pack)";
} else /*if (packHasVoxelization)*/ {
reason = "(voxelization detected)";
if (capped) {
caches.distanceInfo = renderDistanceBlocks + " blocks (capped by normal render distance)";
caches.cullingInfo = "disabled " + reason;
} else {
caches.distanceInfo = distance + " blocks (set by shader pack)";
caches.cullingInfo = "distance only " + reason;
}
}
if (distance <= 0 || distance > Minecraft.getMinecraft().gameSettings.renderDistanceChunks * 16) {
distanceInfo = Minecraft.getMinecraft().gameSettings.renderDistanceChunks * 16
+ " blocks (capped by normal render distance)";
cullingInfo = "disabled " + reason;
return holder.setInfo(NON_CULLING_FRUSTUM, distanceInfo, cullingInfo);
} else {
distanceInfo = distance + " blocks (set by shader pack)";
cullingInfo = "distance only " + reason;
holder.setInfo(getOrCreateBoxCullingFrustum(distance, caches), distanceInfo, cullingInfo);
if (capped) {
return applyInfo(holder, NON_CULLING_FRUSTUM, caches);
}
return applyInfo(holder, getOrCreateBoxCullingFrustum(distance, caches), caches);
} else {
BoxCuller boxCuller;
boolean hasSafeZone = packCullingState == ShadowCullState.SAFE_ZONE;
final boolean hasSafeZone = packCullingState == ShadowCullState.SAFE_ZONE;
if (hasSafeZone && renderMultiplier < 0) renderMultiplier = 1.0f;
final boolean userSetter = renderMultiplier < 0;
double distance = (hasSafeZone ? voxelDistance : halfPlaneLength) * renderMultiplier;
String setter = "(set by shader pack)";
if (renderMultiplier < 0) {
if (userSetter) {
// TODO: GUI
distance = IrisVideoSettings.shadowDistance * 16; // can be zero :(
setter = "(set by user)";
}
if (distance >= Minecraft.getMinecraft().gameSettings.renderDistanceChunks * 16 && !hasSafeZone) {
distanceInfo = Minecraft.getMinecraft().gameSettings.renderDistanceChunks * 16
+ " blocks (capped by normal render distance)";
boxCuller = null;
} else {
distanceInfo = distance + " blocks " + setter;
final boolean capped = distance >= renderDistanceBlocks && !hasSafeZone;
final boolean cullEverything = !capped && distance == 0.0 && !hasSafeZone;
if (distance == 0.0 && !hasSafeZone) {
cullingInfo = "no shadows rendered";
return holder.setInfo(CULL_EVERYTHING_FRUSTUM, distanceInfo, cullingInfo);
if (infoInputsChanged(caches, INFO_BRANCH_ADVANCED, distance, renderDistanceBlocks, hasSafeZone, !userSetter)) {
if (capped) {
caches.distanceInfo = renderDistanceBlocks + " blocks (capped by normal render distance)";
} else {
caches.distanceInfo = distance + " blocks " + (userSetter ? "(set by user)" : "(set by shader pack)");
}
boxCuller = getOrCreateAdvancedBoxCuller(distance, caches);
if (cullEverything) {
caches.cullingInfo = "no shadows rendered";
} else {
caches.cullingInfo = hasSafeZone ? "Safe Zone Frustum Culling enabled" : "Advanced Occlusion Culling enabled";
}
}
cullingInfo = (hasSafeZone ? "Safe Zone" : "Advanced") + " Frustum Culling enabled";
if (cullEverything) {
return applyInfo(holder, CULL_EVERYTHING_FRUSTUM, caches);
}
final BoxCuller boxCuller = capped ? null : caches.advancedBoxCuller.get(distance);
final Vector4f shadowLightPosition = celestialUniforms.getShadowLightPositionInWorldSpace();
shadowLightVectorCache.set(shadowLightPosition.x(), shadowLightPosition.y(), shadowLightPosition.z());
shadowLightVectorCache.normalize();
Matrix4fc projView = ((shouldRenderDH && DHCompat.hasRenderingEnabled()) ? DHCompat.getProjection() : RenderingState.INSTANCE.getProjectionMatrix());
final Matrix4fc projView = ((shouldRenderDH && DHCompat.hasRenderingEnabled()) ? DHCompat.getProjection() : RenderingState.INSTANCE.getProjectionMatrix());
if (hasSafeZone) {
BoxCuller distanceCuller = new BoxCuller(halfPlaneLength * renderMultiplier);
SafeZoneCullingFrustum safeZoneFrustum = new SafeZoneCullingFrustum(
RenderingState.INSTANCE.getModelViewMatrix(), projView,
shadowLightVectorCache, boxCuller, distanceCuller);
return holder.setInfo(safeZoneFrustum, distanceInfo, cullingInfo);
if (caches.safeZoneFrustum == null) {
caches.safeZoneFrustum = new SafeZoneCullingFrustum();
}
caches.safeZoneFrustum.init(RenderingState.INSTANCE.getModelViewMatrix(), projView, shadowLightVectorCache,
boxCuller, caches.safeZoneDistanceCuller.get(halfPlaneLength * renderMultiplier));
return applyInfo(holder, caches.safeZoneFrustum, caches);
} else {
caches.advancedFrustum.init(RenderingState.INSTANCE.getModelViewMatrix(), projView, shadowLightVectorCache, boxCuller);
return holder.setInfo(caches.advancedFrustum, distanceInfo, cullingInfo);
return applyInfo(holder, caches.advancedFrustum, caches);
}
}
}
private static boolean infoInputsChanged(FrustumCaches caches, int branch, double distance, int renderDistanceBlocks, boolean hasSafeZone, boolean packSetter) {
if (caches.infoBranch == branch && caches.infoDistance == distance
&& caches.infoRenderDistanceBlocks == renderDistanceBlocks
&& caches.infoHasSafeZone == hasSafeZone && caches.infoPackSetter == packSetter) {
return false;
}
caches.infoBranch = branch;
caches.infoDistance = distance;
caches.infoRenderDistanceBlocks = renderDistanceBlocks;
caches.infoHasSafeZone = hasSafeZone;
caches.infoPackSetter = packSetter;
return true;
}
private static FrustumHolder applyInfo(FrustumHolder holder, Frustrum frustum, FrustumCaches caches) {
final boolean changed = !caches.cullingInfo.equals(holder.getCullingInfo())
|| !caches.distanceInfo.equals(holder.getDistanceInfo());
holder.setInfo(frustum, caches.distanceInfo, caches.cullingInfo);
if (changed) {
Iris.logger.info("Shadow culling ({}): {}, {}", holder.getRole(), caches.cullingInfo, caches.distanceInfo);
}
return holder;
}
private static BoxCullingFrustum getOrCreateBoxCullingFrustum(double distance, FrustumCaches caches) {
if (caches.boxCuller == null) {
caches.boxCuller = new BoxCuller(distance);
caches.boxCullingFrustum = new BoxCullingFrustum(caches.boxCuller);
caches.lastBoxCullerDistance = distance;
} else if (caches.lastBoxCullerDistance != distance) {
caches.boxCuller.setMaxDistance(distance);
caches.lastBoxCullerDistance = distance;
final BoxCuller culler = caches.boxCuller.get(distance);
if (caches.boxCullingFrustum == null) {
caches.boxCullingFrustum = new BoxCullingFrustum(culler);
}
return caches.boxCullingFrustum;
}
private static BoxCuller getOrCreateAdvancedBoxCuller(double distance, FrustumCaches caches) {
if (caches.advancedBoxCuller == null) {
caches.advancedBoxCuller = new BoxCuller(distance);
caches.lastAdvancedBoxCullerDistance = distance;
} else if (caches.lastAdvancedBoxCullerDistance != distance) {
caches.advancedBoxCuller.setMaxDistance(distance);
caches.lastAdvancedBoxCullerDistance = distance;
}
return caches.advancedBoxCuller;
}
private BoxCuller getOrCreateTileEntityCuller(double distance) {
if (cachedTileEntityCuller == null) {
cachedTileEntityCuller = new BoxCuller(distance);
lastTileEntityCullerDistance = distance;
} else if (lastTileEntityCullerDistance != distance) {
cachedTileEntityCuller.setMaxDistance(distance);
lastTileEntityCullerDistance = distance;
}
return cachedTileEntityCuller;
}
private void setupGlState(Matrix4f projMatrix) {
GLStateManager.glViewport(0, 0, resolution, resolution);
@@ -780,7 +810,7 @@ public class ShadowRenderer {
BoxCuller culler = null;
if (hasEntityFrustum) {
double distance = halfPlaneLength * (renderDistanceMultiplier * entityShadowDistanceMultiplier);
culler = getOrCreateTileEntityCuller(distance);
culler = tileEntityCuller.get(distance);
culler.setPosition(cameraX, cameraY, cameraZ);
}
@@ -22,7 +22,7 @@ import java.util.OptionalInt;
public interface WorldRenderingPipeline {
void beginLevelRendering();
void renderShadows(EntityRenderer levelRenderer, Camera camera);
default void preSubmitShadowGraph(int frame, boolean spectator) {}
default void preSubmitShadowGraph(int frame) {}
void addDebugText(List<String> messages);
OptionalInt getForcedShadowRenderDistanceChunksForDisplay();
@@ -96,4 +96,10 @@ public class BoxCuller {
return maxZ < this.minRelZ || minZ > this.maxRelZ;
}
public boolean isFullyInsideViewRelative(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
return minX >= this.minRelX && maxX <= this.maxRelX
&& minY >= this.minRelY && maxY <= this.maxRelY
&& minZ >= this.minRelZ && maxZ <= this.maxRelZ;
}
}
@@ -24,6 +24,11 @@ public class CullEverythingFrustum extends Frustrum implements ViewportProvider,
return false;
}
@Override
public int intersectAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
return OUTSIDE;
}
@Override
public Viewport sodium$createViewport() {
return new Viewport(this, position.set(xPosition, yPosition, zPosition));
@@ -3,10 +3,15 @@ package net.coderbot.iris.shadows.frustum;
import net.minecraft.client.renderer.culling.Frustrum;
public class FrustumHolder {
private final String role;
private Frustrum frustum;
private String distanceInfo = "(unavailable)";
private String cullingInfo = "(unavailable)";
public FrustumHolder(String role) {
this.role = role;
}
public FrustumHolder setInfo(Frustrum frustum, String distanceInfo, String cullingInfo) {
this.frustum = frustum;
this.distanceInfo = distanceInfo;
@@ -14,6 +19,10 @@ public class FrustumHolder {
return this;
}
public String getRole() {
return role;
}
public Frustrum getFrustum() {
return frustum;
}
@@ -9,6 +9,7 @@ import net.minecraft.util.AxisAlignedBB;
import org.embeddedt.embeddium.impl.render.viewport.Viewport;
import org.embeddedt.embeddium.impl.render.viewport.ViewportProvider;
import org.embeddedt.embeddium.impl.render.viewport.frustum.Frustum;
import org.embeddedt.embeddium.impl.render.viewport.frustum.ShadowSearchFrustum;
import org.joml.Math;
import org.joml.Matrix4f;
import org.joml.Matrix4fc;
@@ -37,7 +38,7 @@ import org.joml.Vector4f;
* cost of slightly more computations.</p>
*/
@Optional.Interface(modid = "distanthorizons", iface = "com.seibel.distanthorizons.api.interfaces.override.rendering.IDhApiShadowCullingFrustum")
public class AdvancedShadowCullingFrustum extends Frustrum implements ViewportProvider, Frustum, IDhApiShadowCullingFrustum {
public class AdvancedShadowCullingFrustum extends Frustrum implements ViewportProvider, Frustum, ShadowSearchFrustum, IDhApiShadowCullingFrustum {
private static final int MAX_CLIPPING_PLANES = 13;
/**
@@ -279,11 +280,47 @@ public class AdvancedShadowCullingFrustum extends Frustrum implements ViewportPr
return checkCornerVisibility(minX, minY, minZ, maxX, maxY, maxZ);
}
@Override
public int intersectAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
if (boxCuller != null && boxCuller.isCulledViewRelative(minX, minY, minZ, maxX, maxY, maxZ)) {
return OUTSIDE;
}
final int result = intersectCorners(minX, minY, minZ, maxX, maxY, maxZ);
if (result == FULLY_INSIDE && boxCuller != null
&& !boxCuller.isFullyInsideViewRelative(minX, minY, minZ, maxX, maxY, maxZ)) {
return PARTIALLY_INSIDE;
}
return result;
}
@Override
public Viewport sodium$createViewport() {
return new Viewport(this, position.set(xPosition, yPosition, zPosition));
}
@Override
public boolean supportsOcclusionSearch() {
return true;
}
@Override
public float shadowLightX() {
return this.shadowLightVectorFromOrigin.x();
}
@Override
public float shadowLightY() {
return this.shadowLightVectorFromOrigin.y();
}
@Override
public float shadowLightZ() {
return this.shadowLightVectorFromOrigin.z();
}
protected boolean isVisible(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) {
return this.checkCornerVisibility((float)(minX - xPosition), (float)(minY - yPosition), (float)(minZ - zPosition),
(float)(maxX - xPosition), (float)(maxY - yPosition), (float)(maxZ - zPosition));
@@ -306,6 +343,29 @@ public class AdvancedShadowCullingFrustum extends Frustrum implements ViewportPr
return true;
}
protected int intersectCorners(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
boolean inside = true;
for (int i = 0; i < planeCount; ++i) {
final Vector4f plane = this.planes[i];
final float px = plane.x();
final float py = plane.y();
final float pz = plane.z();
final float pw = plane.w();
if (Math.fma(px, px < 0 ? minX : maxX, Math.fma(py, py < 0 ? minY : maxY, pz * (pz < 0 ? minZ : maxZ))) < -pw) {
return OUTSIDE;
}
if (Math.fma(px, px < 0 ? maxX : minX, Math.fma(py, py < 0 ? maxY : minY, pz * (pz < 0 ? maxZ : minZ))) < -pw) {
inside = false;
}
}
return inside ? FULLY_INSIDE : PARTIALLY_INSIDE;
}
@Optional.Method(modid = "distanthorizons")
@Override
public void update(int worldMinBlockY, int worldMaxBlockY, DhApiMat4f worldViewProjection) {
@@ -7,14 +7,18 @@ import org.joml.Matrix4fc;
import org.joml.Vector3f;
public class SafeZoneCullingFrustum extends AdvancedShadowCullingFrustum {
private final BoxCuller distanceCuller;
private BoxCuller distanceCuller;
public SafeZoneCullingFrustum(Matrix4fc playerView, Matrix4fc playerProjection, Vector3f shadowLightVector, BoxCuller voxelCuller, BoxCuller distanceCuller) {
super();
init(playerView, playerProjection, shadowLightVector, voxelCuller);
public void init(Matrix4fc playerView, Matrix4fc playerProjection, Vector3f shadowLightVector, BoxCuller voxelCuller, BoxCuller distanceCuller) {
super.init(playerView, playerProjection, shadowLightVector, voxelCuller);
this.distanceCuller = distanceCuller;
}
@Override
public boolean supportsOcclusionSearch() {
return false;
}
@Override
public void setPosition(double cameraX, double cameraY, double cameraZ) {
if (this.distanceCuller != null) {
@@ -53,4 +57,51 @@ public class SafeZoneCullingFrustum extends AdvancedShadowCullingFrustum {
return checkCornerVisibility(minX, minY, minZ, maxX, maxY, maxZ);
}
@Override
public int intersectAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
int distanceResult = FULLY_INSIDE;
if (distanceCuller != null) {
distanceResult = intersectCuller(distanceCuller, minX, minY, minZ, maxX, maxY, maxZ);
if (distanceResult == OUTSIDE) {
return OUTSIDE;
}
}
int safeZoneResult = OUTSIDE;
if (boxCuller != null) {
safeZoneResult = intersectCuller(boxCuller, minX, minY, minZ, maxX, maxY, maxZ);
if (safeZoneResult == FULLY_INSIDE && distanceResult == FULLY_INSIDE) {
return FULLY_INSIDE;
}
}
if (distanceResult == PARTIALLY_INSIDE && safeZoneResult == PARTIALLY_INSIDE) {
return PARTIALLY_INSIDE;
}
final int frustumResult = intersectCorners(minX, minY, minZ, maxX, maxY, maxZ);
if (safeZoneResult == OUTSIDE && frustumResult == OUTSIDE) {
return OUTSIDE;
}
if (frustumResult == FULLY_INSIDE && distanceResult == FULLY_INSIDE) {
return FULLY_INSIDE;
}
return PARTIALLY_INSIDE;
}
private static int intersectCuller(BoxCuller culler, float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
if (culler.isCulledViewRelative(minX, minY, minZ, maxX, maxY, maxZ)) {
return OUTSIDE;
}
return culler.isFullyInsideViewRelative(minX, minY, minZ, maxX, maxY, maxZ) ? FULLY_INSIDE : PARTIALLY_INSIDE;
}
}
@@ -38,6 +38,15 @@ public class BoxCullingFrustum extends Frustrum implements ViewportProvider, Fru
return !boxCuller.isCulledViewRelative(minX, minY, minZ, maxX, maxY, maxZ);
}
@Override
public int intersectAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
if (boxCuller.isCulledViewRelative(minX, minY, minZ, maxX, maxY, maxZ)) {
return OUTSIDE;
}
return boxCuller.isFullyInsideViewRelative(minX, minY, minZ, maxX, maxY, maxZ) ? FULLY_INSIDE : PARTIALLY_INSIDE;
}
@Override
public Viewport sodium$createViewport() {
return new Viewport(this, position.set(xPosition, yPosition, zPosition));
@@ -24,6 +24,11 @@ public class NonCullingFrustum extends Frustrum implements ViewportProvider, Fru
return true;
}
@Override
public int intersectAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
return FULLY_INSIDE;
}
@Override
public Viewport sodium$createViewport() {
return new Viewport(this, position.set(xPosition, yPosition, zPosition));