Improve terrain fog quality and refactor cloud rendering #52

Merged
embeddedt merged 8 commits from rdh/celeritas:sky-fog into stonecutter 2026-11-19 21:51:49 -05:00
53 changed files with 1633 additions and 728 deletions

No files matched your search

@@ -1,6 +1,7 @@
package org.embeddedt.embeddium.impl.render.chunk.draw.bench; package org.embeddedt.embeddium.impl.render.chunk.draw.bench;
import org.embeddedt.embeddium.impl.gl.device.RenderDevice; import org.embeddedt.embeddium.impl.gl.device.RenderDevice;
import org.embeddedt.embeddium.impl.gl.state.GlStateService;
import org.embeddedt.embeddium.impl.render.chunk.ChunkRenderMatrices; import org.embeddedt.embeddium.impl.render.chunk.ChunkRenderMatrices;
import org.embeddedt.embeddium.impl.render.chunk.DefaultChunkRenderer; import org.embeddedt.embeddium.impl.render.chunk.DefaultChunkRenderer;
import org.embeddedt.embeddium.impl.render.chunk.bench.voxel.BenchRenderPasses; import org.embeddedt.embeddium.impl.render.chunk.bench.voxel.BenchRenderPasses;
@@ -132,7 +133,7 @@ public class TerrainDrawBench {
this.height = this.width * 9 / 16; this.height = this.width * 9 / 16;
this.matrices = createMatrices(this.renderDistance); this.matrices = createMatrices(this.renderDistance);
this.renderer = new DefaultChunkRenderer(RenderDevice.INSTANCE, BenchRenderPasses.configuration(), NO_FOG) { this.renderer = new DefaultChunkRenderer(RenderDevice.INSTANCE, BenchRenderPasses.configuration(), NO_FOG, GlStateService.UNCACHED) {
@Override @Override
protected void configureShaderInterface(ChunkShaderInterface shader) { protected void configureShaderInterface(ChunkShaderInterface shader) {
shader.setTextureSlot(ChunkShaderTextureSlot.BLOCK, 0); shader.setTextureSlot(ChunkShaderTextureSlot.BLOCK, 0);
@@ -0,0 +1,36 @@
package org.embeddedt.embeddium.impl.gl.state;
import org.taumc.celeritas.lwjgl.GL13;
import static org.taumc.celeritas.lwjgl.LWJGLServiceProvider.LWJGL;
public interface GlStateService {
/**
* For renderers that don't cache texture state. These leave unit 0 active, so it is taken to be the previous unit.
*/
GlStateService UNCACHED = new GlStateService() {
@Override
public int activateTextureUnit(int unit) {
LWJGL.glActiveTexture(unit);
return GL13.GL_TEXTURE0;
}
@Override
public void bindTexture(int unit, int target, int texture) {
LWJGL.glActiveTexture(GL13.GL_TEXTURE0 + unit);
LWJGL.glBindTexture(target, texture);
LWJGL.glActiveTexture(GL13.GL_TEXTURE0);
}
};
/**
* @param unit the unit, as {@code GL_TEXTURE0 + n}
* @return the unit that was active before, in the same form
*/
int activateTextureUnit(int unit);
/**
* @param unit the unit, as an index
*/
void bindTexture(int unit, int target, int texture);
}
@@ -23,10 +23,14 @@ public class GlBufferTexture extends GlObject {
* are compared by identity, because a deleted buffer's name may be reused by the buffer that replaces it. * are compared by identity, because a deleted buffer's name may be reused by the buffer that replaces it.
*/ */
public void bind(TextureBufferFunctions functions, GlBuffer buffer) { public void bind(TextureBufferFunctions functions, GlBuffer buffer) {
this.bind(functions, buffer, GL30.GL_R32UI);
}
public void bind(TextureBufferFunctions functions, GlBuffer buffer, int internalFormat) {
LWJGL.glBindTexture(GL31.GL_TEXTURE_BUFFER, this.handle()); LWJGL.glBindTexture(GL31.GL_TEXTURE_BUFFER, this.handle());
if (this.attachedBuffer != buffer) { if (this.attachedBuffer != buffer) {
functions.texBuffer(GL31.GL_TEXTURE_BUFFER, GL30.GL_R32UI, buffer); functions.texBuffer(GL31.GL_TEXTURE_BUFFER, internalFormat, buffer);
this.attachedBuffer = buffer; this.attachedBuffer = buffer;
} }
} }
@@ -99,6 +99,8 @@ public class SodiumGameOptions implements OptionStorage<SodiumGameOptions> {
public int chunkFadeInDuration = 0; public int chunkFadeInDuration = 0;
public boolean useSkyFog = false;
public boolean useRgssTextureFiltering = false; public boolean useRgssTextureFiltering = false;
public int legacyBiomeBlendRadius = 0; public int legacyBiomeBlendRadius = 0;
@@ -37,6 +37,14 @@ public class CommonOptionPages {
.setBinding((opts, value) -> opts.quality.chunkFadeInDuration = value, opts -> opts.quality.chunkFadeInDuration) .setBinding((opts, value) -> opts.quality.chunkFadeInDuration = value, opts -> opts.quality.chunkFadeInDuration)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD) .setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build()) .build())
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setId(StandardOptions.Option.SKY_FOG.cast())
.setName(TextComponent.translatable("celeritas.options.sky_fog.name"))
.setTooltip(TextComponent.translatable("celeritas.options.sky_fog.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.LOW)
.setBinding((opts, value) -> opts.quality.useSkyFog = value, opts -> opts.quality.useSkyFog)
.build())
.build(); .build();
} }
@@ -8,6 +8,7 @@ import org.embeddedt.embeddium.impl.gl.attribute.GlVertexFormat;
import org.embeddedt.embeddium.impl.gl.debug.GLDebug; import org.embeddedt.embeddium.impl.gl.debug.GLDebug;
import org.embeddedt.embeddium.impl.gl.device.CommandList; import org.embeddedt.embeddium.impl.gl.device.CommandList;
import org.embeddedt.embeddium.impl.gl.device.RenderDevice; import org.embeddedt.embeddium.impl.gl.device.RenderDevice;
import org.embeddedt.embeddium.impl.gl.state.GlStateService;
import org.embeddedt.embeddium.impl.gl.tessellation.*; import org.embeddedt.embeddium.impl.gl.tessellation.*;
import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.ChunkPrimitiveType; 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.SectionRenderDataStorage;
@@ -23,10 +24,9 @@ import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexLayout; import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexLayout;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.VertexFetchMode; import org.embeddedt.embeddium.impl.render.chunk.vertex.format.VertexFetchMode;
import org.embeddedt.embeddium.impl.render.viewport.CameraTransform; import org.embeddedt.embeddium.impl.render.viewport.CameraTransform;
import org.taumc.celeritas.lwjgl.GL11;
import org.taumc.celeritas.lwjgl.GL13; import org.taumc.celeritas.lwjgl.GL13;
import static org.taumc.celeritas.lwjgl.LWJGLServiceProvider.LWJGL;
import java.util.Iterator; import java.util.Iterator;
public abstract class DefaultChunkRenderer extends ShaderChunkRenderer { public abstract class DefaultChunkRenderer extends ShaderChunkRenderer {
@@ -40,6 +40,8 @@ public abstract class DefaultChunkRenderer extends ShaderChunkRenderer {
*/ */
public static final int VERTEX_DATA_TEXTURE_UNIT = 15; public static final int VERTEX_DATA_TEXTURE_UNIT = 15;
public static final int SKY_TEXTURE_UNIT = 14;
/** /**
* Stands in for vertex attributes in pulled passes. Compatibility profiles leave a draw undefined when attribute * Stands in for vertex attributes in pulled passes. Compatibility profiles leave a draw undefined when attribute
* array 0 is disabled, and pulled shaders don't declare any attributes. * array 0 is disabled, and pulled shaders don't declare any attributes.
@@ -48,12 +50,16 @@ public abstract class DefaultChunkRenderer extends ShaderChunkRenderer {
.addElement("celeritas_Placeholder", 0, GlVertexAttributeFormat.UNSIGNED_BYTE, 4, true, false) .addElement("celeritas_Placeholder", 0, GlVertexAttributeFormat.UNSIGNED_BYTE, 4, true, false)
.build(); .build();
private final GlStateService glState;
private TerrainRenderPass currentRenderPass; private TerrainRenderPass currentRenderPass;
private GlVertexFormat currentVertexFormat; private GlVertexFormat currentVertexFormat;
public DefaultChunkRenderer(RenderDevice device, RenderPassConfiguration<?> renderPassConfiguration, FogService fogService) { public DefaultChunkRenderer(RenderDevice device, RenderPassConfiguration<?> renderPassConfiguration, FogService fogService, GlStateService glState) {
super(device, renderPassConfiguration, fogService); super(device, renderPassConfiguration, fogService);
this.glState = glState;
this.sharedIndexBuffers = new Reference2ReferenceOpenHashMap<>(); this.sharedIndexBuffers = new Reference2ReferenceOpenHashMap<>();
} }
@@ -118,11 +124,13 @@ public abstract class DefaultChunkRenderer extends ShaderChunkRenderer {
boolean pulled = renderPass.vertexFetchMode() == VertexFetchMode.PULLED; boolean pulled = renderPass.vertexFetchMode() == VertexFetchMode.PULLED;
this.bindSkyTexture();
int previousActiveTexture = 0; int previousActiveTexture = 0;
if (pulled) { if (pulled) {
this.currentVertexFormat = PLACEHOLDER_ATTRIBUTE_FORMAT; this.currentVertexFormat = PLACEHOLDER_ATTRIBUTE_FORMAT;
previousActiveTexture = this.activateTextureUnit(GL13.GL_TEXTURE0 + VERTEX_DATA_TEXTURE_UNIT); previousActiveTexture = this.glState.activateTextureUnit(GL13.GL_TEXTURE0 + VERTEX_DATA_TEXTURE_UNIT);
} else { } else {
this.currentVertexFormat = ChunkVertexLayout.requireAttributes(renderPass.vertexType().getLayout()); this.currentVertexFormat = ChunkVertexLayout.requireAttributes(renderPass.vertexType().getLayout());
} }
@@ -170,7 +178,7 @@ public abstract class DefaultChunkRenderer extends ShaderChunkRenderer {
} }
if (pulled) { if (pulled) {
this.activateTextureUnit(previousActiveTexture); this.glState.activateTextureUnit(previousActiveTexture);
} }
this.currentVertexFormat = null; this.currentVertexFormat = null;
@@ -203,16 +211,12 @@ public abstract class DefaultChunkRenderer extends ShaderChunkRenderer {
return cached; return cached;
} }
/** private void bindSkyTexture() {
* Makes the given texture unit active. Platforms whose renderer caches the active unit must update that cache. int skyTexture = this.environment.fogService().getSkyTexture();
*
* @param unit the unit, as {@code GL_TEXTURE0 + n} if (skyTexture != 0) {
* @return the unit that was active before, in the same form this.glState.bindTexture(SKY_TEXTURE_UNIT, GL11.GL_TEXTURE_2D, skyTexture);
*/ }
protected int activateTextureUnit(int unit) {
LWJGL.glActiveTexture(unit);
// TODO: don't assume unit 0 was active before the pass
return GL13.GL_TEXTURE0;
} }
private static void setModelMatrixUniforms(ChunkShaderInterface shader, RenderRegion region, CameraTransform camera) { private static void setModelMatrixUniforms(ChunkShaderInterface shader, RenderRegion region, CameraTransform camera) {
@@ -14,5 +14,21 @@ public interface FogService {
int getFogShapeIndex(); int getFogShapeIndex();
float getFogCutoff(); float getFogCutoff();
float[] getFogColor(); float[] getFogColor();
ChunkShaderComponent.Factory<?> getFogMode(); ChunkShaderComponent.Factory<?> getFogMode();
/**
* {@return the GL handle for a viewport-sized texture with the sky, or 0 when not available}
*/
default int getSkyTexture() {
return 0;
}
default float getSkyFogEdgeStart() {
return this.getFogStart();
}
default float getSkyFogEdgeEnd() {
return this.getFogEnd();
}
} }
@@ -0,0 +1,69 @@
package org.embeddedt.embeddium.impl.render.chunk.fog;
import org.embeddedt.embeddium.impl.gl.state.GlStateService;
import org.embeddedt.embeddium.impl.render.ShaderModBridge;
import org.embeddedt.embeddium.impl.render.chunk.DefaultChunkRenderer;
import org.taumc.celeritas.lwjgl.GL11;
import org.taumc.celeritas.lwjgl.GL13;
import static org.taumc.celeritas.lwjgl.LWJGLServiceProvider.LWJGL;
public final class SkyTextureCopy {
private final GlStateService glState;
private int texture, width, height;
private boolean valid;
public SkyTextureCopy(GlStateService glState) {
this.glState = glState;
}
public static boolean shouldProvide(boolean optionEnabled) {
return optionEnabled && !ShaderModBridge.areShadersEnabled();
}
public int getTexture() {
return this.valid ? this.texture : 0;
}
public void invalidate() {
this.valid = false;
}
/**
* Copies from the bound read framebuffer.
*/
public void copy(int width, int height) {
if (this.texture == 0) {
this.texture = LWJGL.glGenTextures();
}
// The texture calls below act on the active unit's binding
this.glState.bindTexture(DefaultChunkRenderer.SKY_TEXTURE_UNIT, GL11.GL_TEXTURE_2D, this.texture);
int previous = this.glState.activateTextureUnit(GL13.GL_TEXTURE0 + DefaultChunkRenderer.SKY_TEXTURE_UNIT);
if (this.width != width || this.height != height) {
this.width = width;
this.height = height;
LWJGL.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, width, height, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, null);
// texelFetch ignores filtering, but the default mipmapped min filter would leave the texture incomplete
LWJGL.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST);
LWJGL.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);
}
LWJGL.glCopyTexSubImage2D(GL11.GL_TEXTURE_2D, 0, 0, 0, 0, 0, width, height);
this.glState.activateTextureUnit(previous);
this.valid = true;
}
public void delete() {
if (this.texture != 0) {
LWJGL.glDeleteTextures(this.texture);
this.texture = 0;
this.width = 0;
this.height = 0;
}
this.valid = false;
}
}
@@ -12,7 +12,8 @@ public enum ChunkFogMode implements ChunkShaderComponent.Factory<ChunkShaderFogC
NONE(ChunkShaderFogComponent.None::new, List.of()), NONE(ChunkShaderFogComponent.None::new, List.of()),
EXP(ChunkShaderFogComponent.Exp::new, List.of("USE_FOG", "USE_FOG_EXP")), EXP(ChunkShaderFogComponent.Exp::new, List.of("USE_FOG", "USE_FOG_EXP")),
EXP2(ChunkShaderFogComponent.Exp2::new, List.of("USE_FOG", "USE_FOG_EXP2")), EXP2(ChunkShaderFogComponent.Exp2::new, List.of("USE_FOG", "USE_FOG_EXP2")),
SMOOTH(ChunkShaderFogComponent.Smooth::new, List.of("USE_FOG", "USE_FOG_SMOOTH")); SMOOTH(ChunkShaderFogComponent.Smooth::new, List.of("USE_FOG", "USE_FOG_SMOOTH")),
SMOOTH_SKY(ChunkShaderFogComponent.SmoothSky::new, List.of("USE_FOG", "USE_FOG_SMOOTH", "USE_SKY_FOG"));
private final BiFunction<ShaderBindingContext, ChunkShaderEnvironment, ChunkShaderFogComponent> factory; private final BiFunction<ShaderBindingContext, ChunkShaderEnvironment, ChunkShaderFogComponent> factory;
private final List<String> defines; private final List<String> defines;
@@ -5,6 +5,7 @@ import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformFloat;
import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformFloat4v; import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformFloat4v;
import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformInt; import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformInt;
import org.embeddedt.embeddium.impl.render.chunk.fog.FogService; import org.embeddedt.embeddium.impl.render.chunk.fog.FogService;
import org.embeddedt.embeddium.impl.render.chunk.DefaultChunkRenderer;
/** /**
* These shader implementations try to remain compatible with the deprecated fixed function pipeline by manually * These shader implementations try to remain compatible with the deprecated fixed function pipeline by manually
@@ -81,7 +82,7 @@ public abstract class ChunkShaderFogComponent implements ChunkShaderComponent {
super(environment.fogService()); super(environment.fogService());
this.uFogColor = context.bindUniform("u_FogColor", GlUniformFloat4v::new); this.uFogColor = context.bindUniform("u_FogColor", GlUniformFloat4v::new);
this.uFogShape = context.bindUniform("u_FogShape", GlUniformInt::new); this.uFogShape = context.bindUniformIfPresent("u_FogShape", GlUniformInt::new);
this.uFogStart = context.bindUniform("u_FogStart", GlUniformFloat::new); this.uFogStart = context.bindUniform("u_FogStart", GlUniformFloat::new);
this.uFogEnd = context.bindUniform("u_FogEnd", GlUniformFloat::new); this.uFogEnd = context.bindUniform("u_FogEnd", GlUniformFloat::new);
} }
@@ -89,11 +90,55 @@ public abstract class ChunkShaderFogComponent implements ChunkShaderComponent {
@Override @Override
public void setup() { public void setup() {
this.uFogColor.set(this.fogService.getFogColor()); this.uFogColor.set(this.fogService.getFogColor());
if (this.uFogShape != null) {
this.uFogShape.set(this.fogService.getFogShapeIndex()); this.uFogShape.set(this.fogService.getFogShapeIndex());
}
this.uFogStart.set(this.fogService.getFogStart()); this.uFogStart.set(this.fogService.getFogStart());
this.uFogEnd.set(this.fogService.getFogEnd()); this.uFogEnd.set(this.fogService.getFogEnd());
} }
} }
public static class SmoothSky extends Smooth {
private final SkyUniforms skyFog;
public SmoothSky(ShaderBindingContext context, ChunkShaderEnvironment environment) {
super(context, environment);
this.skyFog = new SkyUniforms(context, environment.fogService());
}
@Override
public void setup() {
super.setup();
this.skyFog.setup();
}
}
public static final class SkyUniforms {
private final FogService fogService;
private final GlUniformInt sampler;
private final GlUniformFloat edgeStart, edgeEnd;
public SkyUniforms(ShaderBindingContext context, FogService fogService) {
this.fogService = fogService;
this.sampler = context.bindUniformIfPresent("u_SkyTex", GlUniformInt::new);
this.edgeStart = context.bindUniformIfPresent("u_SkyFogEdgeStart", GlUniformFloat::new);
this.edgeEnd = context.bindUniformIfPresent("u_SkyFogEdgeEnd", GlUniformFloat::new);
}
public void setup() {
if (this.sampler != null) {
this.sampler.setInt(DefaultChunkRenderer.SKY_TEXTURE_UNIT);
}
if (this.edgeStart != null) {
this.edgeStart.setFloat(this.fogService.getSkyFogEdgeStart());
}
if (this.edgeEnd != null) {
this.edgeEnd.setFloat(this.fogService.getSkyFogEdgeEnd());
}
}
}
} }
@@ -0,0 +1,20 @@
package org.embeddedt.embeddium.impl.render.clouds;
import org.joml.Matrix4fc;
/**
* What the platform knows about the clouds for one frame.
*
* @param modelView the camera rotation, without translation
* @param cloudHeight the height of the bottom of the clouds
* @param ticks the game time in ticks, including the partial tick
* @param red the cloud color
* @param range how far clouds are drawn, in blocks
* @param fogEnd the distance at which clouds have faded out completely
*/
public record CloudFrame(Matrix4fc modelView, Matrix4fc projection,
double cameraX, double cameraY, double cameraZ,
float cloudHeight, double ticks,
float red, float green, float blue,
boolean fancy, float range, float fogEnd) {
}
@@ -0,0 +1,15 @@
package org.embeddedt.embeddium.impl.render.clouds;
/**
* Sets up the GL state clouds are drawn with. Platforms implement this so they can use their own render state objects
* and keep their state caches in sync.
*/
public interface CloudRenderState {
/**
* Sets up blending and depth testing and writing. Fancy clouds are drawn with back face culling, fast clouds
* without.
*/
void setup(boolean fancy);
void restore();
}
@@ -0,0 +1,414 @@
package org.embeddedt.embeddium.impl.render.clouds;
import org.embeddedt.embeddium.impl.gl.array.GlVertexArray;
import org.embeddedt.embeddium.impl.gl.buffer.GlBufferTarget;
import org.embeddedt.embeddium.impl.gl.buffer.GlBufferUsage;
import org.embeddedt.embeddium.impl.gl.buffer.GlMutableBuffer;
import org.embeddedt.embeddium.impl.gl.device.CommandList;
import org.embeddedt.embeddium.impl.gl.device.RenderDevice;
import org.embeddedt.embeddium.impl.gl.shader.GlProgram;
import org.embeddedt.embeddium.impl.gl.shader.GlShader;
import org.embeddedt.embeddium.impl.gl.shader.ShaderBindingContext;
import org.embeddedt.embeddium.impl.gl.shader.ShaderConstants;
import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformFloat;
import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformFloat3v;
import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformFloat4v;
import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformInt;
import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformMatrix4f;
import org.embeddedt.embeddium.impl.gl.state.GlStateService;
import org.embeddedt.embeddium.impl.gl.texture.GlBufferTexture;
import org.embeddedt.embeddium.impl.render.chunk.SharedQuadIndexBuffer;
import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.QuadPrimitiveType;
import org.embeddedt.embeddium.impl.render.shader.ShaderLoader;
import org.taumc.celeritas.lwjgl.GL11;
import org.taumc.celeritas.lwjgl.GL12;
import org.taumc.celeritas.lwjgl.GL13;
import org.taumc.celeritas.lwjgl.GL30;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import static org.taumc.celeritas.lwjgl.LWJGLServiceProvider.LWJGL;
/**
* Draws clouds without vertex data, like vanilla since 1.21.6. The visible faces are written to a buffer texture, and
* the vertex shader builds each vertex from {@code gl_VertexID}. The face format matches vanilla's, so shader packs can
* generate the same vertices. Unlike vanilla, each cell is tinted by its pixel in the clouds texture.
*/
public final class CloudRenderer {
public static final int FACES_TEXTURE_UNIT = 3;
public static final int COLORS_TEXTURE_UNIT = 4;
private static final int DIRECTION_DOWN = 0;
private static final int DIRECTION_UP = 1;
private static final int DIRECTION_NORTH = 2;
private static final int DIRECTION_SOUTH = 3;
private static final int DIRECTION_WEST = 4;
private static final int DIRECTION_EAST = 5;
private static final int FLAG_INSIDE_FACE = 1 << 4;
private static final int FLAG_USE_TOP_COLOR = 1 << 5;
// A 256 px clouds texture makes 12 block cells
private static final float TEXTURE_SIZE_IN_BLOCKS = 3072.0f;
private static final float CLOUD_THICKNESS = 4.0f;
private static final float CLOUD_ALPHA = 0.8f;
private static final double BLOCKS_PER_TICK = 0.03;
private static final int BYTES_PER_FACE = 3 * Short.BYTES;
private enum CameraPosition {
ABOVE_CLOUDS,
INSIDE_CLOUDS,
BELOW_CLOUDS
}
private final GlStateService glState;
private final CloudTexture texture;
private final float cellSizeX, cellSizeZ;
private final GlProgram<ShaderInterface> program;
private final GlMutableBuffer faceBuffer;
private final GlBufferTexture faceTexture;
private final SharedQuadIndexBuffer indexBuffer;
private final GlVertexArray vertexArray;
private final int colorTexture;
private ByteBuffer faceData = ByteBuffer.allocateDirect(1024 * BYTES_PER_FACE).order(ByteOrder.nativeOrder());
private int faceCount;
private boolean needsRebuild = true;
private int prevCellX, prevCellZ, prevRadius;
private CameraPosition prevCameraPosition;
private boolean prevFancy;
private int centerCellX, centerCellZ;
private float offsetX, offsetY, offsetZ;
public CloudRenderer(CommandList commandList, GlStateService glState, CloudTexture texture) {
this.glState = glState;
this.texture = texture;
this.cellSizeX = TEXTURE_SIZE_IN_BLOCKS / texture.width;
this.cellSizeZ = TEXTURE_SIZE_IN_BLOCKS / texture.height;
this.program = createProgram();
this.faceBuffer = commandList.createMutableBuffer();
this.faceTexture = new GlBufferTexture();
this.indexBuffer = new SharedQuadIndexBuffer(commandList, QuadPrimitiveType.TRIANGULATED);
this.vertexArray = new GlVertexArray();
this.colorTexture = this.createColorTexture();
}
/**
* Updates the faces for the frame.
*
* @return whether there is anything to draw
*/
public boolean prepare(CommandList commandList, CloudFrame frame) {
double textureWidthBlocks = this.texture.width * this.cellSizeX;
double textureHeightBlocks = this.texture.height * this.cellSizeZ;
double cloudX = frame.cameraX() + frame.ticks() * BLOCKS_PER_TICK;
double cloudZ = frame.cameraZ() + 3.96;
cloudX -= Math.floor(cloudX / textureWidthBlocks) * textureWidthBlocks;
cloudZ -= Math.floor(cloudZ / textureHeightBlocks) * textureHeightBlocks;
int cellX = (int) Math.floor(cloudX / this.cellSizeX);
int cellZ = (int) Math.floor(cloudZ / this.cellSizeZ);
float relativeBottomY = frame.cloudHeight() - (float) frame.cameraY() + 0.33f;
float relativeTopY = relativeBottomY + CLOUD_THICKNESS;
CameraPosition cameraPosition;
float verticalDistance;
if (relativeTopY < 0.0f) {
cameraPosition = CameraPosition.ABOVE_CLOUDS;
verticalDistance = -relativeTopY;
} else if (relativeBottomY > 0.0f) {
cameraPosition = CameraPosition.BELOW_CLOUDS;
verticalDistance = relativeBottomY;
} else {
cameraPosition = CameraPosition.INSIDE_CLOUDS;
verticalDistance = 0.0f;
}
// Every cloud has faded out, such as underwater far below them
if (verticalDistance >= frame.fogEnd()) {
return false;
}
float cellSize = Math.min(this.cellSizeX, this.cellSizeZ);
int maxRadius = (int) Math.ceil(frame.range() / cellSize);
// Cells past the fade end are invisible. Rounding up keeps a fade end that changes gradually, like water fog
// while the player's eyes adjust, from rebuilding the faces every frame.
int fadeRadius = ((int) Math.ceil(frame.fogEnd() / cellSize) + 1 + 15) & ~15;
int radius = Math.min(maxRadius, fadeRadius);
if (this.needsRebuild || cellX != this.prevCellX || cellZ != this.prevCellZ || radius != this.prevRadius
|| cameraPosition != this.prevCameraPosition || frame.fancy() != this.prevFancy) {
this.needsRebuild = false;
this.prevCellX = cellX;
this.prevCellZ = cellZ;
this.prevRadius = radius;
this.prevCameraPosition = cameraPosition;
this.prevFancy = frame.fancy();
this.buildFaces(cameraPosition, cellX, cellZ, frame.fancy(), radius);
this.faceData.flip();
commandList.uploadData(this.faceBuffer, this.faceData, GlBufferUsage.DYNAMIC_DRAW);
this.indexBuffer.ensureCapacity(commandList, this.faceCount * 6);
}
this.centerCellX = cellX;
this.centerCellZ = cellZ;
this.offsetX = -(float) (cloudX - cellX * this.cellSizeX);
this.offsetY = relativeBottomY;
this.offsetZ = -(float) (cloudZ - cellZ * this.cellSizeZ);
return this.faceCount != 0;
}
/**
* Draws the faces from {@link #prepare} with our own program.
*/
public void render(CommandList commandList, CloudRenderState state, CloudFrame frame) {
state.setup(frame.fancy());
this.program.bind();
this.program.getInterface().setup(this, frame);
this.bindTextures();
this.draw(commandList);
this.program.unbind();
state.restore();
}
/**
* Binds the faces to {@link #FACES_TEXTURE_UNIT} and the cell colors to {@link #COLORS_TEXTURE_UNIT}.
*/
public void bindTextures() {
this.glState.bindTexture(COLORS_TEXTURE_UNIT, GL11.GL_TEXTURE_2D, this.colorTexture);
int previous = this.glState.activateTextureUnit(GL13.GL_TEXTURE0 + FACES_TEXTURE_UNIT);
this.faceTexture.bind(RenderDevice.INSTANCE.getDeviceFunctions().textureBufferFunctions(), this.faceBuffer, GL30.GL_R16I);
this.glState.activateTextureUnit(previous);
}
/**
* Draws the faces with the bound program.
*/
public void draw(CommandList commandList) {
commandList.bindVertexArray(this.vertexArray);
commandList.bindBuffer(GlBufferTarget.ELEMENT_BUFFER, this.indexBuffer.getBufferObject());
LWJGL.glDrawElementsBaseVertex(GL11.GL_TRIANGLES, this.faceCount * 6, GL11.GL_UNSIGNED_INT, 0L, 0);
commandList.unbindVertexArray();
}
public int getCenterCellX() {
return this.centerCellX;
}
public int getCenterCellZ() {
return this.centerCellZ;
}
public float getOffsetX() {
return this.offsetX;
}
public float getOffsetY() {
return this.offsetY;
}
public float getOffsetZ() {
return this.offsetZ;
}
public float getCellSizeX() {
return this.cellSizeX;
}
public float getCellSizeZ() {
return this.cellSizeZ;
}
public float getCellHeight() {
return CLOUD_THICKNESS;
}
public static float getAlpha() {
return CLOUD_ALPHA;
}
public void delete(CommandList commandList) {
this.program.delete();
commandList.deleteBuffer(this.faceBuffer);
this.faceTexture.delete();
this.indexBuffer.delete(commandList);
commandList.deleteVertexArray(this.vertexArray);
LWJGL.glDeleteTextures(this.colorTexture);
}
private void buildFaces(CameraPosition cameraPosition, int centerCellX, int centerCellZ, boolean fancy, int radius) {
this.faceData.clear();
this.faceCount = 0;
// Rings of cells around the camera, so the faces are drawn front to back
for (int ring = 0; ring <= 2 * radius; ring++) {
for (int x = -ring; x <= ring; x++) {
int z = ring - Math.abs(x);
if (z > radius || x * x + z * z > radius * radius) {
continue;
}
if (z != 0) {
this.buildCell(cameraPosition, centerCellX, centerCellZ, fancy, x, -z);
}
this.buildCell(cameraPosition, centerCellX, centerCellZ, fancy, x, z);
}
}
}
private void buildCell(CameraPosition cameraPosition, int centerCellX, int centerCellZ, boolean fancy, int x, int z) {
int cell = this.texture.cell(centerCellX + x, centerCellZ + z);
if (cell == 0) {
return;
}
if (!fancy) {
this.addFace(x, z, DIRECTION_DOWN, FLAG_USE_TOP_COLOR);
return;
}
if (cameraPosition != CameraPosition.BELOW_CLOUDS) {
this.addFace(x, z, DIRECTION_UP, 0);
}
if (cameraPosition != CameraPosition.ABOVE_CLOUDS) {
this.addFace(x, z, DIRECTION_DOWN, 0);
}
// Only the sides that face the camera
if ((cell & CloudTexture.OPEN_NORTH) != 0 && z > 0) {
this.addFace(x, z, DIRECTION_NORTH, 0);
}
if ((cell & CloudTexture.OPEN_SOUTH) != 0 && z < 0) {
this.addFace(x, z, DIRECTION_SOUTH, 0);
}
if ((cell & CloudTexture.OPEN_WEST) != 0 && x > 0) {
this.addFace(x, z, DIRECTION_WEST, 0);
}
if ((cell & CloudTexture.OPEN_EAST) != 0 && x < 0) {
this.addFace(x, z, DIRECTION_EAST, 0);
}
// Seen from inside the clouds
if (Math.abs(x) <= 1 && Math.abs(z) <= 1) {
for (int direction = DIRECTION_DOWN; direction <= DIRECTION_EAST; direction++) {
this.addFace(x, z, direction, FLAG_INSIDE_FACE);
}
}
}
private void addFace(int x, int z, int direction, int flags) {
if (this.faceData.remaining() < BYTES_PER_FACE) {
ByteBuffer grown = ByteBuffer.allocateDirect(this.faceData.capacity() * 2).order(ByteOrder.nativeOrder());
this.faceData.flip();
grown.put(this.faceData);
this.faceData = grown;
}
// The low bits of the cell position are stored with the flags, as vanilla does
int directionAndFlags = direction | flags | ((x & 1) << 7) | ((z & 1) << 6);
this.faceData.putShort((short) (x >> 1));
this.faceData.putShort((short) (z >> 1));
this.faceData.putShort((short) directionAndFlags);
this.faceCount++;
}
private int createColorTexture() {
int texture = LWJGL.glGenTextures();
ByteBuffer pixels = ByteBuffer.allocateDirect(this.texture.pixels.length * 4).order(ByteOrder.LITTLE_ENDIAN);
// ABGR as little endian ints is RGBA in memory
pixels.asIntBuffer().put(this.texture.pixels);
this.glState.bindTexture(COLORS_TEXTURE_UNIT, GL11.GL_TEXTURE_2D, texture);
int previous = this.glState.activateTextureUnit(GL13.GL_TEXTURE0 + COLORS_TEXTURE_UNIT);
LWJGL.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 4);
LWJGL.glPixelStorei(GL11.GL_UNPACK_ROW_LENGTH, 0);
LWJGL.glPixelStorei(GL11.GL_UNPACK_SKIP_ROWS, 0);
LWJGL.glPixelStorei(GL11.GL_UNPACK_SKIP_PIXELS, 0);
LWJGL.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, this.texture.width, this.texture.height, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, pixels);
LWJGL.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST);
LWJGL.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);
LWJGL.glTexParameteri(GL11.GL_TEXTURE_2D, GL12.GL_TEXTURE_MAX_LEVEL, 0);
this.glState.activateTextureUnit(previous);
return texture;
}
private static GlProgram<ShaderInterface> createProgram() {
ShaderConstants constants = ShaderConstants.builder().build();
GlShader vertexShader = ShaderLoader.loadShader(ShaderType.VERTEX, "sodium:clouds/clouds.vsh", constants);
GlShader fragmentShader = ShaderLoader.loadShader(ShaderType.FRAGMENT, "sodium:clouds/clouds.fsh", constants);
try {
return GlProgram.builder("celeritas:clouds")
.attachShader(vertexShader)
.attachShader(fragmentShader)
.bindFragmentData("fragColor", 0)
.link(ShaderInterface::new);
} finally {
vertexShader.delete();
fragmentShader.delete();
}
}
private static final class ShaderInterface {
private final GlUniformMatrix4f modelViewMatrix, projectionMatrix;
private final GlUniformFloat4v colorModulator;
private final GlUniformFloat3v cloudOffset, cellSize;
private final GlUniformInt centerCellX, centerCellZ;
private final GlUniformFloat fogEnd;
private final GlUniformInt facesSampler, colorsSampler;
private ShaderInterface(ShaderBindingContext context) {
this.modelViewMatrix = context.bindUniform("ModelViewMat", GlUniformMatrix4f::new);
this.projectionMatrix = context.bindUniform("ProjMat", GlUniformMatrix4f::new);
this.colorModulator = context.bindUniform("ColorModulator", GlUniformFloat4v::new);
this.cloudOffset = context.bindUniform("CloudOffset", GlUniformFloat3v::new);
this.cellSize = context.bindUniform("CellSize", GlUniformFloat3v::new);
this.centerCellX = context.bindUniform("CenterCellX", GlUniformInt::new);
this.centerCellZ = context.bindUniform("CenterCellZ", GlUniformInt::new);
this.fogEnd = context.bindUniform("FogEnd", GlUniformFloat::new);
this.facesSampler = context.bindUniform("CloudFaces", GlUniformInt::new);
this.colorsSampler = context.bindUniform("CloudColors", GlUniformInt::new);
}
private void setup(CloudRenderer renderer, CloudFrame frame) {
this.modelViewMatrix.set(frame.modelView());
this.projectionMatrix.set(frame.projection());
this.colorModulator.set(new float[] { frame.red(), frame.green(), frame.blue(), CLOUD_ALPHA });
this.cloudOffset.set(renderer.offsetX, renderer.offsetY, renderer.offsetZ);
this.cellSize.set(renderer.cellSizeX, CLOUD_THICKNESS, renderer.cellSizeZ);
this.centerCellX.setInt(renderer.centerCellX);
this.centerCellZ.setInt(renderer.centerCellZ);
this.fogEnd.setFloat(frame.fogEnd());
this.facesSampler.setInt(FACES_TEXTURE_UNIT);
this.colorsSampler.setInt(COLORS_TEXTURE_UNIT);
}
}
}
@@ -0,0 +1,78 @@
package org.embeddedt.embeddium.impl.render.clouds;
/**
* The cells of the clouds texture, one per pixel.
*/
public final class CloudTexture {
static final int OPEN_NORTH = 1;
static final int OPEN_SOUTH = 2;
static final int OPEN_WEST = 4;
static final int OPEN_EAST = 8;
static final int FILLED = 16;
final int width, height;
final int[] pixels;
final byte[] cells;
/**
* @param pixels the pixels in rows along X, packed as ABGR (as {@code NativeImage#getPixelRGBA} returns them)
*/
public CloudTexture(int width, int height, int[] pixels) {
if (pixels.length != width * height) {
throw new IllegalArgumentException("Expected " + (width * height) + " pixels, got " + pixels.length);
}
this.width = width;
this.height = height;
this.pixels = pixels;
this.cells = new byte[pixels.length];
for (int z = 0; z < height; z++) {
for (int x = 0; x < width; x++) {
int pixel = this.pixel(x, z);
if (!isFilled(pixel)) {
continue;
}
// A side is open where the neighbor differs. Between two filled cells of different colors, only the
// side of the cell to the south or east is open, so the boundary is drawn once.
int flags = FILLED;
int north = this.pixel(x, z - 1);
int south = this.pixel(x, z + 1);
int west = this.pixel(x - 1, z);
int east = this.pixel(x + 1, z);
if (north != pixel) {
flags |= OPEN_NORTH;
}
if (!isFilled(south) && south != pixel) {
flags |= OPEN_SOUTH;
}
if (west != pixel) {
flags |= OPEN_WEST;
}
if (!isFilled(east) && east != pixel) {
flags |= OPEN_EAST;
}
this.cells[x + z * width] = (byte) flags;
}
}
}
int cell(int x, int z) {
return this.cells[Math.floorMod(x, this.width) + Math.floorMod(z, this.height) * this.width];
}
private int pixel(int x, int z) {
return this.pixels[Math.floorMod(x, this.width) + Math.floorMod(z, this.height) * this.width];
}
private static boolean isFilled(int abgr) {
return (abgr >>> 24) > 1;
}
}
@@ -75,6 +75,7 @@ public final class StandardOptions {
public static final OptionIdentifier<Void> USE_FASTER_CLOUDS = OptionIdentifier.create(EMBEDDIUM_MOD_ID, "use_faster_clouds"); public static final OptionIdentifier<Void> USE_FASTER_CLOUDS = OptionIdentifier.create(EMBEDDIUM_MOD_ID, "use_faster_clouds");
public static final OptionIdentifier<Void> ASYNC_GRAPH_SEARCH = OptionIdentifier.create(EMBEDDIUM_MOD_ID, "async_graph_search"); public static final OptionIdentifier<Void> ASYNC_GRAPH_SEARCH = OptionIdentifier.create(EMBEDDIUM_MOD_ID, "async_graph_search");
public static final OptionIdentifier<Void> CHUNK_FADE_IN_DURATION = OptionIdentifier.create(EMBEDDIUM_MOD_ID, "chunk_fade_in_duration"); public static final OptionIdentifier<Void> CHUNK_FADE_IN_DURATION = OptionIdentifier.create(EMBEDDIUM_MOD_ID, "chunk_fade_in_duration");
public static final OptionIdentifier<Void> SKY_FOG = OptionIdentifier.create(EMBEDDIUM_MOD_ID, "sky_fog");
public static final OptionIdentifier<Void> RGSS_TEXTURE_FILTERING = OptionIdentifier.create(EMBEDDIUM_MOD_ID, "rgss_texture_filtering"); public static final OptionIdentifier<Void> RGSS_TEXTURE_FILTERING = OptionIdentifier.create(EMBEDDIUM_MOD_ID, "rgss_texture_filtering");
public static final OptionIdentifier<Void> RASTER_OCCLUSION_CULLING = OptionIdentifier.create(EMBEDDIUM_MOD_ID, "raster_occlusion_culling"); public static final OptionIdentifier<Void> RASTER_OCCLUSION_CULLING = OptionIdentifier.create(EMBEDDIUM_MOD_ID, "raster_occlusion_culling");
} }
@@ -30,25 +30,6 @@ in float v_FragDistance;
uniform sampler2D u_BlockTex; // The block texture uniform sampler2D u_BlockTex; // The block texture
uniform int u_FogShape;
uniform vec4 u_FogColor; // The color of the shader fog
#ifdef USE_FOG_SMOOTH
uniform float u_FogStart; // The starting position of the shader fog
uniform float u_FogEnd; // The ending position of the shader fog
#endif
#ifdef USE_FOG_POSTMODERN
uniform float u_RenderDistFogStart;
uniform float u_RenderDistFogEnd;
uniform float u_EnvFogStart;
uniform float u_EnvFogEnd;
#endif
#if defined(USE_FOG_EXP) || defined(USE_FOG_EXP2)
uniform float u_FogDensity; // The density of the shader fog
#endif
#ifndef LEGACY #ifndef LEGACY
out vec4 fragColor; // The output fragment for the color framebuffer out vec4 fragColor; // The output fragment for the color framebuffer
#else #else
@@ -78,14 +59,14 @@ void main() {
#if defined(CHUNK_FADE_IN_DURATION_MS) && CHUNK_FADE_IN_DURATION_MS > 0 #if defined(CHUNK_FADE_IN_DURATION_MS) && CHUNK_FADE_IN_DURATION_MS > 0
// Make chunk fade in over a short duration // Make chunk fade in over a short duration
diffuseColor = vec4(mix(u_FogColor.rgb, diffuseColor.rgb, (clamp(v_ChunkAgeMs, 0, CHUNK_FADE_IN_DURATION_MS) / CHUNK_FADE_IN_DURATION_MS)), diffuseColor.a); diffuseColor = vec4(mix(_fogBackground(u_FogColor), diffuseColor.rgb, (clamp(v_ChunkAgeMs, 0, CHUNK_FADE_IN_DURATION_MS) / CHUNK_FADE_IN_DURATION_MS)), diffuseColor.a);
#endif #endif
#if defined(USE_FOG_POSTMODERN) #if defined(USE_FOG_POSTMODERN)
float fogValue = max(_linearFogValue(v_CylindricalFragDistance, u_RenderDistFogStart, u_RenderDistFogEnd), fragColor = _blendFog(diffuseColor,
_linearFogValue(v_SphericalFragDistance, u_EnvFogStart, u_EnvFogEnd)); _linearFogValue(v_SphericalFragDistance, u_EnvFogStart, u_EnvFogEnd),
_linearFogValue(v_CylindricalFragDistance, u_RenderDistFogStart, u_RenderDistFogEnd),
fragColor = vec4(mix(diffuseColor.rgb, u_FogColor.rgb, fogValue * u_FogColor.a), diffuseColor.a); u_FogColor);
#else // Legacy fog #else // Legacy fog
float fragDistance; float fragDistance;
if (u_FogShape == FOG_SHAPE_PLANAR) { if (u_FogShape == FOG_SHAPE_PLANAR) {
@@ -34,8 +34,6 @@ out float v_CylindricalFragDistance;
out float v_FragDistance; out float v_FragDistance;
#endif #endif
uniform int u_FogShape;
uniform vec3 u_RegionOffset; uniform vec3 u_RegionOffset;
#if defined(USE_FOG) && defined(CHUNK_FADE_IN_DURATION_MS) && CHUNK_FADE_IN_DURATION_MS > 0 #if defined(USE_FOG) && defined(CHUNK_FADE_IN_DURATION_MS) && CHUNK_FADE_IN_DURATION_MS > 0
@@ -1,11 +1,5 @@
#version 150 #version 150
#import <sodium:include/fog.glsl>
uniform mat4 ProjMat;
uniform vec4 ColorModulator;
uniform vec4 FogColor;
uniform float FogStart;
uniform float FogEnd; uniform float FogEnd;
in vec4 vertexColor; in vec4 vertexColor;
@@ -13,14 +7,20 @@ in float vertexDistance;
out vec4 fragColor; out vec4 fragColor;
// Custom cloud fog algorithm by Balint, for use in Sodium
void main() { void main() {
vec4 color = vertexColor * ColorModulator; vec4 color = vertexColor;
if (color.a < 0.1) { if (color.a < 0.1) {
discard; discard;
} }
fragColor = _linearFog(color, vertexDistance, FogColor, FogStart, FogEnd); // Clouds fade out over their own range instead of using terrain fog, like vanilla since 1.21.6
} color.a *= 1.0 - clamp(vertexDistance / FogEnd, 0.0, 1.0);
// Faded out clouds must not write depth
if (color.a < 1.0 / 255.0) {
discard;
}
fragColor = color;
}
@@ -1,19 +1,67 @@
#version 150 #version 150
in vec3 Position; const int FLAG_MASK_DIR = 7;
in vec4 Color; const int FLAG_INSIDE_FACE = 1 << 4;
const int FLAG_USE_TOP_COLOR = 1 << 5;
const int FLAG_EXTRA_Z = 1 << 6;
const int FLAG_EXTRA_X = 1 << 7;
uniform mat4 ModelViewMat; uniform mat4 ModelViewMat;
uniform mat4 ProjMat; uniform mat4 ProjMat;
uniform int FogShape; uniform vec4 ColorModulator;
uniform vec3 CloudOffset;
uniform vec3 CellSize;
uniform int CenterCellX;
uniform int CenterCellZ;
uniform isamplerBuffer CloudFaces;
uniform sampler2D CloudColors;
out float vertexDistance; out float vertexDistance;
out vec4 vertexColor; out vec4 vertexColor;
// Custom cloud fog algorithm by Balint, for use in Sodium const vec3[] vertices = vec3[](
// Bottom face
vec3(1, 0, 0), vec3(1, 0, 1), vec3(0, 0, 1), vec3(0, 0, 0),
// Top face
vec3(0, 1, 0), vec3(0, 1, 1), vec3(1, 1, 1), vec3(1, 1, 0),
// North face
vec3(0, 0, 0), vec3(0, 1, 0), vec3(1, 1, 0), vec3(1, 0, 0),
// South face
vec3(1, 0, 1), vec3(1, 1, 1), vec3(0, 1, 1), vec3(0, 0, 1),
// West face
vec3(0, 0, 1), vec3(0, 1, 1), vec3(0, 1, 0), vec3(0, 0, 0),
// East face
vec3(1, 0, 0), vec3(1, 1, 0), vec3(1, 1, 1), vec3(1, 0, 1)
);
const float[] faceShades = float[](0.7, 1.0, 0.8, 0.8, 0.9, 0.9);
int wrap(int value, int size) {
return value - size * int(floor(float(value) / float(size)));
}
void main() { void main() {
gl_Position = ProjMat * ModelViewMat * vec4(Position, 1.0); int quadVertex = gl_VertexID % 4;
vec4 pos = ModelViewMat * vec4(Position.x, 0.0, Position.z, 1.0); int index = (gl_VertexID / 4) * 3;
vertexDistance = length(pos.xyz);
vertexColor = Color; int cellX = texelFetch(CloudFaces, index).r;
int cellZ = texelFetch(CloudFaces, index + 1).r;
int dirAndFlags = texelFetch(CloudFaces, index + 2).r;
int direction = dirAndFlags & FLAG_MASK_DIR;
bool isInsideFace = (dirAndFlags & FLAG_INSIDE_FACE) == FLAG_INSIDE_FACE;
bool useTopColor = (dirAndFlags & FLAG_USE_TOP_COLOR) == FLAG_USE_TOP_COLOR;
cellX = (cellX << 1) | ((dirAndFlags & FLAG_EXTRA_X) >> 7);
cellZ = (cellZ << 1) | ((dirAndFlags & FLAG_EXTRA_Z) >> 6);
vec3 faceVertex = vertices[(direction * 4) + (isInsideFace ? 3 - quadVertex : quadVertex)];
vec3 pos = (faceVertex * CellSize) + (vec3(cellX, 0, cellZ) * CellSize) + CloudOffset;
gl_Position = ProjMat * ModelViewMat * vec4(pos, 1.0);
ivec2 textureSize = textureSize(CloudColors, 0);
ivec2 texel = ivec2(wrap(CenterCellX + cellX, textureSize.x), wrap(CenterCellZ + cellZ, textureSize.y));
float shade = useTopColor ? faceShades[1] : faceShades[direction];
vertexDistance = length(pos);
vertexColor = texelFetch(CloudColors, texel, 0) * vec4(vec3(shade), 1.0) * ColorModulator;
} }
@@ -2,19 +2,40 @@ const int FOG_SHAPE_SPHERICAL = 0;
const int FOG_SHAPE_CYLINDRICAL = 1; const int FOG_SHAPE_CYLINDRICAL = 1;
const int FOG_SHAPE_PLANAR = 2; const int FOG_SHAPE_PLANAR = 2;
vec4 _linearFog(vec4 fragColor, float fragDistance, vec4 fogColor, float fogStart, float fogEnd) { uniform int u_FogShape;
#ifdef USE_FOG uniform vec4 u_FogColor;
if (fragDistance <= fogStart) {
return fragColor;
}
float factor = fragDistance < fogEnd ? smoothstep(fogStart, fogEnd, fragDistance) : 1.0; // alpha value of fog is used as a weight
vec3 blended = mix(fragColor.rgb, fogColor.rgb, factor * fogColor.a);
return vec4(blended, fragColor.a); // alpha value of fragment cannot be modified #ifdef USE_FOG_SMOOTH
uniform float u_FogStart;
uniform float u_FogEnd;
#endif
#ifdef USE_FOG_POSTMODERN
uniform float u_RenderDistFogStart;
uniform float u_RenderDistFogEnd;
uniform float u_EnvFogStart;
uniform float u_EnvFogEnd;
#endif
#if defined(USE_FOG_EXP) || defined(USE_FOG_EXP2)
uniform float u_FogDensity;
#endif
#if defined(USE_SKY_FOG) && defined(FRAGMENT_SHADER)
#define CELERITAS_SKY_FOG
uniform sampler2D u_SkyTex;
uniform float u_SkyFogEdgeStart;
uniform float u_SkyFogEdgeEnd;
vec3 _skyColor() {
#ifdef LEGACY
return texelFetch2D(u_SkyTex, ivec2(gl_FragCoord.xy), 0).rgb;
#else #else
return fragColor; return texelFetch(u_SkyTex, ivec2(gl_FragCoord.xy), 0).rgb;
#endif #endif
} }
#endif
float _linearFogValue(float fragDistance, float fogStart, float fogEnd) { float _linearFogValue(float fragDistance, float fogStart, float fogEnd) {
#ifdef USE_FOG #ifdef USE_FOG
@@ -30,6 +51,51 @@ float _linearFogValue(float fragDistance, float fogStart, float fogEnd) {
#endif #endif
} }
vec3 _fogBackground(vec4 fogColor) {
#ifdef CELERITAS_SKY_FOG
return _skyColor();
#else
return fogColor.rgb;
#endif
}
// environment: fog from the surroundings (water, weather, blindness), which fades toward the fog color.
// edge: fog hiding the render distance limit, which with sky fog fades toward the sky behind the fragment.
vec4 _blendFog(vec4 fragColor, float environment, float edge, vec4 fogColor) {
float fogValue = max(environment, edge);
if (fogValue <= 0.0) {
return fragColor;
}
vec3 target = fogColor.rgb;
#ifdef CELERITAS_SKY_FOG
// The dominant fog picks the color. Nearly opaque environmental fog also turns into the sky, so that fully
// fogged terrain matches the background.
float skyWeight = edge >= environment ? 1.0 : edge / environment;
skyWeight = max(skyWeight, smoothstep(0.9, 1.0, environment));
target = mix(target, _skyColor(), skyWeight);
#endif
return vec4(mix(fragColor.rgb, target, fogValue * fogColor.a), fragColor.a);
}
// Single-range fog. With sky fog, the render distance edge comes from u_SkyFogEdge* and fades into the sky separately.
vec4 _linearFog(vec4 fragColor, float fragDistance, vec4 fogColor, float fogStart, float fogEnd) {
#ifdef USE_FOG
float environment = _linearFogValue(fragDistance, fogStart, fogEnd);
#ifdef CELERITAS_SKY_FOG
float edge = _linearFogValue(fragDistance, u_SkyFogEdgeStart, u_SkyFogEdgeEnd);
#else
float edge = environment;
#endif
return _blendFog(fragColor, environment, edge, fogColor);
#else
return fragColor;
#endif
}
vec4 _exp2Fog(vec4 fragColor, float fragDistance, vec4 fogColor, float fogDensity) { vec4 _exp2Fog(vec4 fragColor, float fragDistance, vec4 fogColor, float fogDensity) {
#ifdef USE_FOG #ifdef USE_FOG
float dist = fragDistance * fogDensity; float dist = fragDistance * fogDensity;
@@ -10,6 +10,7 @@ import org.taumc.celeritas.api.options.control.SliderControl;
import org.taumc.celeritas.api.options.control.TickBoxControl; import org.taumc.celeritas.api.options.control.TickBoxControl;
import org.embeddedt.embeddium.impl.gui.SodiumGameOptions; import org.embeddedt.embeddium.impl.gui.SodiumGameOptions;
import org.embeddedt.embeddium.impl.gui.framework.TextComponent; import org.embeddedt.embeddium.impl.gui.framework.TextComponent;
import org.embeddedt.embeddium.impl.gui.options.CommonOptionPages;
import org.lwjgl.opengl.Display; import org.lwjgl.opengl.Display;
import org.taumc.celeritas.CeleritasVintage; import org.taumc.celeritas.CeleritasVintage;
import org.taumc.celeritas.api.options.structure.OptionFlag; import org.taumc.celeritas.api.options.structure.OptionFlag;
@@ -221,6 +222,14 @@ public class SodiumGameOptionPages {
.setBinding((opts, value) -> opts.quality.chunkFadeInDuration = value, opts -> opts.quality.chunkFadeInDuration) .setBinding((opts, value) -> opts.quality.chunkFadeInDuration = value, opts -> opts.quality.chunkFadeInDuration)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD) .setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build()) .build())
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setId(StandardOptions.Option.SKY_FOG.cast())
.setName(TextComponent.translatable("celeritas.options.sky_fog.name"))
.setTooltip(TextComponent.translatable("celeritas.options.sky_fog.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.LOW)
.setBinding((opts, value) -> opts.quality.useSkyFog = value, opts -> opts.quality.useSkyFog)
.build())
.add(OptionImpl.createBuilder(boolean.class, vanillaOpts) .add(OptionImpl.createBuilder(boolean.class, vanillaOpts)
.setId(StandardOptions.Option.ENTITY_SHADOWS.cast()) .setId(StandardOptions.Option.ENTITY_SHADOWS.cast())
.setName(TextComponent.translatable("options.entityShadows")) .setName(TextComponent.translatable("options.entityShadows"))
@@ -58,6 +58,13 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Vin
return Minecraft.getMinecraft().gameSettings.renderDistanceChunks; return Minecraft.getMinecraft().gameSettings.renderDistanceChunks;
} }
@Override
protected void unloadWorld() {
super.unloadWorld();
GLStateManagerFogService.INSTANCE.deleteSkyTexture();
}
@Override @Override
protected ChunkRenderMatrices createChunkRenderMatrices() { protected ChunkRenderMatrices createChunkRenderMatrices() {
return new ChunkRenderMatrices(ActiveRenderInfoAccessor.getProjectionMatrix(), ActiveRenderInfoAccessor.getModelViewMatrix()); return new ChunkRenderMatrices(ActiveRenderInfoAccessor.getProjectionMatrix(), ActiveRenderInfoAccessor.getModelViewMatrix());
@@ -0,0 +1,37 @@
package org.taumc.celeritas.impl.render.terrain;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.OpenGlHelper;
import org.embeddedt.embeddium.impl.gl.state.GlStateService;
import org.lwjgl.opengl.GL11;
import org.taumc.celeritas.mixin.core.GlStateManagerAccessor;
public final class GLStateManagerGlStateService implements GlStateService {
public static final GLStateManagerGlStateService INSTANCE = new GLStateManagerGlStateService();
// GlStateManager.textureState only covers 2D textures on these units
private static final int CACHED_TEXTURE_UNITS = 8;
private GLStateManagerGlStateService() {
}
@Override
public int activateTextureUnit(int unit) {
int previous = OpenGlHelper.defaultTexUnit + GlStateManagerAccessor.celeritas$getActiveTextureUnit();
GlStateManager.setActiveTexture(unit);
return previous;
}
@Override
public void bindTexture(int unit, int target, int texture) {
int previous = this.activateTextureUnit(OpenGlHelper.defaultTexUnit + unit);
if (target == GL11.GL_TEXTURE_2D && unit < CACHED_TEXTURE_UNITS) {
GlStateManager.bindTexture(texture);
} else {
GL11.glBindTexture(target, texture);
}
this.activateTextureUnit(previous);
}
}
@@ -162,7 +162,7 @@ public class VintageRenderSectionManager extends RenderSectionManager {
private static class ChunkRenderer extends DefaultChunkRenderer { private static class ChunkRenderer extends DefaultChunkRenderer {
public ChunkRenderer(RenderDevice device, RenderPassConfiguration<?> renderPassConfiguration) { public ChunkRenderer(RenderDevice device, RenderPassConfiguration<?> renderPassConfiguration) {
super(device, renderPassConfiguration, GLStateManagerFogService.INSTANCE); super(device, renderPassConfiguration, GLStateManagerFogService.INSTANCE, GLStateManagerGlStateService.INSTANCE);
} }
@Override @Override
@@ -3,7 +3,11 @@ package org.taumc.celeritas.impl.render.terrain.fog;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.EntityRenderer; import net.minecraft.client.renderer.EntityRenderer;
import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.shader.Framebuffer;
import org.embeddedt.embeddium.impl.render.chunk.fog.FogService; import org.embeddedt.embeddium.impl.render.chunk.fog.FogService;
import org.embeddedt.embeddium.impl.render.chunk.fog.SkyTextureCopy;
import org.taumc.celeritas.impl.render.terrain.GLStateManagerGlStateService;
import org.taumc.celeritas.CeleritasVintage;
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkFogMode; import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkFogMode;
public class GLStateManagerFogService implements FogService { public class GLStateManagerFogService implements FogService {
@@ -42,9 +46,50 @@ public class GLStateManagerFogService implements FogService {
@Override @Override
public ChunkFogMode getFogMode() { public ChunkFogMode getFogMode() {
ChunkFogMode mode = this.getGlFogMode();
return mode == ChunkFogMode.SMOOTH && this.getSkyTexture() != 0 ? ChunkFogMode.SMOOTH_SKY : mode;
}
private ChunkFogMode getGlFogMode() {
if (!GlStateManager.fogState.fog.currentState) { if (!GlStateManager.fogState.fog.currentState) {
return ChunkFogMode.NONE; return ChunkFogMode.NONE;
} }
return ChunkFogMode.fromGLMode(GlStateManager.fogState.mode); return ChunkFogMode.fromGLMode(GlStateManager.fogState.mode);
} }
private final SkyTextureCopy skyTexture = new SkyTextureCopy(GLStateManagerGlStateService.INSTANCE);
@Override
public int getSkyTexture() {
return this.skyTexture.getTexture();
}
public void captureSkyTexture() {
if (!SkyTextureCopy.shouldProvide(CeleritasVintage.options().quality.useSkyFog)) {
this.skyTexture.delete();
return;
}
// Sized to the display even when FBOs are disabled
Framebuffer framebuffer = Minecraft.getMinecraft().getFramebuffer();
this.skyTexture.copy(framebuffer.framebufferWidth, framebuffer.framebufferHeight);
}
public void invalidateSkyTexture() {
this.skyTexture.invalidate();
}
public void deleteSkyTexture() {
this.skyTexture.delete();
}
@Override
public float getSkyFogEdgeStart() {
return this.getSkyFogEdgeEnd() * 0.75F;
}
@Override
public float getSkyFogEdgeEnd() {
return Minecraft.getMinecraft().gameSettings.renderDistanceChunks * 16.0F;
}
} }
@@ -0,0 +1,16 @@
package org.taumc.celeritas.mixin.core;
import net.minecraft.client.renderer.GlStateManager;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
@Mixin(GlStateManager.class)
public interface GlStateManagerAccessor {
/**
* {@return the cached active texture unit, as an index rather than {@code GL_TEXTURE0 + n}}
*/
@Accessor("activeTextureUnit")
static int celeritas$getActiveTextureUnit() {
throw new AssertionError();
}
}
@@ -0,0 +1,16 @@
package org.taumc.celeritas.mixin.features.render.sky;
import net.minecraft.client.renderer.EntityRenderer;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.taumc.celeritas.impl.render.terrain.fog.GLStateManagerFogService;
@Mixin(EntityRenderer.class)
public class SkyFogEntityRendererMixin {
@Inject(method = "renderWorldPass", at = { @At("HEAD"), @At("RETURN") })
private void celeritas$invalidateSkyTexture(CallbackInfo ci) {
GLStateManagerFogService.INSTANCE.invalidateSkyTexture();
}
}
@@ -0,0 +1,16 @@
package org.taumc.celeritas.mixin.features.render.sky;
import net.minecraft.client.renderer.RenderGlobal;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.taumc.celeritas.impl.render.terrain.fog.GLStateManagerFogService;
@Mixin(RenderGlobal.class)
public class SkyFogRenderGlobalMixin {
@Inject(method = "renderSky(FI)V", at = @At("RETURN"))
private void celeritas$captureSkyTexture(CallbackInfo ci) {
GLStateManagerFogService.INSTANCE.captureSkyTexture();
}
}
@@ -17,6 +17,8 @@ celeritas.options.async_graph_search.name=Async Occlusion Culling
celeritas.options.async_graph_search.tooltip=Performs occlusion/frustum culling asynchronously, up to one frame behind the current camera position. This can improve frametimes, particularly at higher render distances, but at the cost of chunks popping into view if the camera is turned too aggressively. celeritas.options.async_graph_search.tooltip=Performs occlusion/frustum culling asynchronously, up to one frame behind the current camera position. This can improve frametimes, particularly at higher render distances, but at the cost of chunks popping into view if the camera is turned too aggressively.
celeritas.options.chunk_fade_in_duration.name=Chunk Fade-In Duration celeritas.options.chunk_fade_in_duration.name=Chunk Fade-In Duration
celeritas.options.chunk_fade_in_duration.value=%s ms celeritas.options.chunk_fade_in_duration.value=%s ms
celeritas.options.sky_fog.name=Sky Fog
celeritas.options.sky_fog.tooltip=Makes distant terrain fade into the sky behind it instead of a single fog color. This removes miscolored terrain at the edge of the render distance during sunrise and sunset, in the End, and with custom skies. Has no effect while a shader pack is active.
celeritas.options.chunk_fade_in_duration.tooltip=Controls how long it takes for newly loaded chunks to fully appear. Longer durations create a smoother transition between unloaded and loaded chunks, reducing visual popping, but may make distant terrain appear to 'fade in' more slowly. celeritas.options.chunk_fade_in_duration.tooltip=Controls how long it takes for newly loaded chunks to fully appear. Longer durations create a smoother transition between unloaded and loaded chunks, reducing visual popping, but may make distant terrain appear to 'fade in' more slowly.
celeritas.options.raster_occlusion_culling.name=Rasterized Occlusion Culling celeritas.options.raster_occlusion_culling.name=Rasterized Occlusion Culling
celeritas.options.raster_occlusion_culling.tooltip=Rasterizes nearby terrain into a small software coverage buffer and uses it to skip chunks hidden behind solid terrain, such as a valley behind a hill. This can substantially reduce the amount of terrain drawn. This helps most when the GPU is the bottleneck.\n\nChanging this rebuilds all chunks. celeritas.options.raster_occlusion_culling.tooltip=Rasterizes nearby terrain into a small software coverage buffer and uses it to skip chunks hidden behind solid terrain, such as a valley behind a hill. This can substantially reduce the amount of terrain drawn. This helps most when the GPU is the bottleneck.\n\nChanging this rebuilds all chunks.
@@ -2,6 +2,7 @@ package org.taumc.celeritas.impl.render.terrain;
import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.Chunk;
import org.embeddedt.embeddium.impl.gl.state.GlStateService;
import org.embeddedt.embeddium.impl.gl.device.CommandList; import org.embeddedt.embeddium.impl.gl.device.CommandList;
import org.embeddedt.embeddium.impl.gl.device.RenderDevice; import org.embeddedt.embeddium.impl.gl.device.RenderDevice;
import org.embeddedt.embeddium.impl.render.chunk.*; import org.embeddedt.embeddium.impl.render.chunk.*;
@@ -109,7 +110,7 @@ public class ArchaicRenderSectionManager extends RenderSectionManager {
private static class ChunkRenderer extends DefaultChunkRenderer { private static class ChunkRenderer extends DefaultChunkRenderer {
public ChunkRenderer(RenderDevice device, RenderPassConfiguration<?> renderPassConfiguration) { public ChunkRenderer(RenderDevice device, RenderPassConfiguration<?> renderPassConfiguration) {
super(device, renderPassConfiguration, GLStateManagerFogService.INSTANCE); super(device, renderPassConfiguration, GLStateManagerFogService.INSTANCE, GlStateService.UNCACHED);
} }
@Override @Override
@@ -0,0 +1,37 @@
package org.embeddedt.embeddium.impl.gl.compat;
import com.mojang.blaze3d.platform.GlStateManager;
import org.embeddedt.embeddium.impl.gl.state.GlStateService;
import org.embeddedt.embeddium.impl.mixin.core.GlStateManagerAccessor;
import org.lwjgl.opengl.GL11C;
import org.lwjgl.opengl.GL13C;
public final class ModernGlStateService implements GlStateService {
public static final ModernGlStateService INSTANCE = new ModernGlStateService();
// GlStateManager.TEXTURES only covers 2D textures on these units. Iris enlarges it.
private static final int CACHED_TEXTURE_UNITS = GlStateManagerAccessor.celeritas$getTextures().length;
private ModernGlStateService() {
}
@Override
public int activateTextureUnit(int unit) {
int previous = GL13C.GL_TEXTURE0 + GlStateManagerAccessor.celeritas$getActiveTexture();
GlStateManager._activeTexture(unit);
return previous;
}
@Override
public void bindTexture(int unit, int target, int texture) {
int previous = this.activateTextureUnit(GL13C.GL_TEXTURE0 + unit);
if (target == GL11C.GL_TEXTURE_2D && unit < CACHED_TEXTURE_UNITS) {
GlStateManager._bindTexture(texture);
} else {
GL11C.glBindTexture(target, texture);
}
this.activateTextureUnit(previous);
}
}
@@ -13,4 +13,9 @@ public interface GlStateManagerAccessor {
static int celeritas$getActiveTexture() { static int celeritas$getActiveTexture() {
throw new AssertionError(); throw new AssertionError();
} }
@Accessor("TEXTURES")
static GlStateManager.TextureState[] celeritas$getTextures() {
throw new AssertionError();
}
} }
@@ -1,21 +1,19 @@
package org.embeddedt.embeddium.impl.modern.render.chunk; package org.embeddedt.embeddium.impl.modern.render.chunk;
import com.mojang.blaze3d.platform.GlStateManager;
import org.embeddedt.embeddium.impl.Celeritas; import org.embeddedt.embeddium.impl.Celeritas;
import org.embeddedt.embeddium.impl.gl.compat.FogHelper; import org.embeddedt.embeddium.impl.gl.compat.FogHelper;
import org.embeddedt.embeddium.impl.gl.compat.ModernGlStateService;
import org.embeddedt.embeddium.impl.gl.device.RenderDevice; import org.embeddedt.embeddium.impl.gl.device.RenderDevice;
import org.embeddedt.embeddium.impl.mixin.core.GlStateManagerAccessor;
import org.embeddedt.embeddium.impl.render.chunk.DefaultChunkRenderer; import org.embeddedt.embeddium.impl.render.chunk.DefaultChunkRenderer;
import org.embeddedt.embeddium.impl.render.chunk.RenderPassConfiguration; import org.embeddedt.embeddium.impl.render.chunk.RenderPassConfiguration;
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderInterface; import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderInterface;
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderTextureSlot; import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderTextureSlot;
import org.lwjgl.opengl.GL13C;
public class ModernChunkRenderer extends DefaultChunkRenderer { public class ModernChunkRenderer extends DefaultChunkRenderer {
public static final int ATLAS_EDGE_MASK_TEXTURE_UNIT = 3; public static final int ATLAS_EDGE_MASK_TEXTURE_UNIT = 3;
public ModernChunkRenderer(RenderDevice device, RenderPassConfiguration<?> renderPassConfiguration) { public ModernChunkRenderer(RenderDevice device, RenderPassConfiguration<?> renderPassConfiguration) {
super(device, renderPassConfiguration, FogHelper.INSTANCE); super(device, renderPassConfiguration, FogHelper.INSTANCE, ModernGlStateService.INSTANCE);
} }
/* /*
@@ -43,13 +41,6 @@ public class ModernChunkRenderer extends DefaultChunkRenderer {
} }
//?} //?}
@Override
protected int activateTextureUnit(int unit) {
int previous = GL13C.GL_TEXTURE0 + GlStateManagerAccessor.celeritas$getActiveTexture();
GlStateManager._activeTexture(unit);
return previous;
}
@Override @Override
protected void configureShaderInterface(ChunkShaderInterface shader) { protected void configureShaderInterface(ChunkShaderInterface shader) {
shader.setTextureSlot(ChunkShaderTextureSlot.BLOCK, 0); shader.setTextureSlot(ChunkShaderTextureSlot.BLOCK, 0);
@@ -25,6 +25,7 @@ import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.AABB;
import org.embeddedt.embeddium.impl.Celeritas; import org.embeddedt.embeddium.impl.Celeritas;
import org.embeddedt.embeddium.impl.gl.compat.FogHelper;
import org.embeddedt.embeddium.impl.gl.device.CommandList; import org.embeddedt.embeddium.impl.gl.device.CommandList;
import org.embeddedt.embeddium.impl.model.color.BlendedColorProvider; import org.embeddedt.embeddium.impl.model.color.BlendedColorProvider;
//? if <1.21.11 //? if <1.21.11
@@ -131,6 +132,13 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<ClientLevel,
BlendedColorProvider.checkBlendingEnabled(); BlendedColorProvider.checkBlendingEnabled();
} }
@Override
protected void unloadWorld() {
super.unloadWorld();
FogHelper.INSTANCE.deleteSkyTexture();
}
@Override @Override
public void setupTerrain(Viewport viewport, CameraState cameraState, int frame, boolean spectator, boolean updateChunksImmediately) { public void setupTerrain(Viewport viewport, CameraState cameraState, int frame, boolean spectator, boolean updateChunksImmediately) {
super.setupTerrain(viewport, cameraState, frame, spectator, updateChunksImmediately); super.setupTerrain(viewport, cameraState, frame, spectator, updateChunksImmediately);
@@ -2,7 +2,10 @@ package org.embeddedt.embeddium.impl.gl.compat;
//? if >=1.17 //? if >=1.17
import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.Minecraft;
import org.embeddedt.embeddium.impl.Celeritas;
import org.embeddedt.embeddium.impl.render.chunk.fog.FogService; import org.embeddedt.embeddium.impl.render.chunk.fog.FogService;
import org.embeddedt.embeddium.impl.render.chunk.fog.SkyTextureCopy;
import org.lwjgl.opengl.GL20; import org.lwjgl.opengl.GL20;
import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.platform.GlStateManager;
@@ -79,6 +82,11 @@ public class FogHelper implements FogService {
} }
public ChunkFogMode getFogMode() { public ChunkFogMode getFogMode() {
ChunkFogMode mode = this.getVanillaFogMode();
return mode == ChunkFogMode.SMOOTH && this.getSkyTexture() != 0 ? ChunkFogMode.SMOOTH_SKY : mode;
}
private ChunkFogMode getVanillaFogMode() {
//? if <1.17 { //? if <1.17 {
/*int mode = GlStateManager.FOG.mode; /*int mode = GlStateManager.FOG.mode;
@@ -98,4 +106,49 @@ public class FogHelper implements FogService {
*///?} else *///?} else
return ChunkFogMode.SMOOTH; return ChunkFogMode.SMOOTH;
} }
private final SkyTextureCopy skyTexture = new SkyTextureCopy(ModernGlStateService.INSTANCE);
@Override
public int getSkyTexture() {
return this.skyTexture.getTexture();
}
public void captureSkyTexture() {
if (!SkyTextureCopy.shouldProvide(Celeritas.options().quality.useSkyFog)) {
this.skyTexture.delete();
return;
}
var target = Minecraft.getInstance().getMainRenderTarget();
this.skyTexture.copy(target.width, target.height);
}
public void invalidateSkyTexture() {
this.skyTexture.invalidate();
}
public void deleteSkyTexture() {
this.skyTexture.delete();
}
@Override
public float getSkyFogEdgeStart() {
float end = this.getSkyFogEdgeEnd();
//? if >=1.18 {
return end - Mth.clamp(end / 10.0F, 4.0F, 64.0F);
//?} else {
/*return end * 0.75F;
*///?}
}
@Override
public float getSkyFogEdgeEnd() {
float renderDistance = Minecraft.getInstance().gameRenderer.getRenderDistance();
//? if >=1.18 {
return Math.max(renderDistance, 32.0F);
//?} else {
/*return Math.max(renderDistance - 16.0F, 32.0F);
*///?}
}
} }
@@ -0,0 +1,34 @@
package org.embeddedt.embeddium.impl.mixin.features.render.world.clouds;
//? if >=1.17 && <1.21.6 {
import com.llamalad7.mixinextras.injector.ModifyReturnValue;
import net.minecraft.client.CloudStatus;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GameRenderer;
import org.embeddedt.embeddium.impl.Celeritas;
import org.embeddedt.embeddium.impl.render.immediate.ModernCloudRenderer;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
/**
* Pushes the far plane out to the cloud range, as vanilla does since 1.21.6, so that clouds past the terrain
* render distance aren't clipped.
*/
@Mixin(GameRenderer.class)
public class GameRendererMixin {
@Shadow
@Final
private Minecraft minecraft;
@ModifyReturnValue(method = "getDepthFar", at = @At("RETURN"))
private float celeritas$extendDepthFarForClouds(float depthFar) {
if (!Celeritas.options().performance.useFasterClouds || this.minecraft.options.getCloudsType() == CloudStatus.OFF) {
return depthFar;
}
return Math.max(depthFar, ModernCloudRenderer.getCloudRange());
}
}
//?}
@@ -5,7 +5,7 @@ import com.mojang.blaze3d.vertex.PoseStack;
import org.embeddedt.embeddium.api.math.JomlHelper; import org.embeddedt.embeddium.api.math.JomlHelper;
import org.embeddedt.embeddium.impl.Celeritas; import org.embeddedt.embeddium.impl.Celeritas;
import org.embeddedt.embeddium.impl.gui.SodiumGameOptions; import org.embeddedt.embeddium.impl.gui.SodiumGameOptions;
import org.embeddedt.embeddium.impl.render.immediate.CloudRenderer; import org.embeddedt.embeddium.impl.render.immediate.ModernCloudRenderer;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.renderer.LevelRenderer; import net.minecraft.client.renderer.LevelRenderer;
@@ -32,7 +32,7 @@ public class WorldRendererMixin {
private Minecraft minecraft; private Minecraft minecraft;
@Unique @Unique
private CloudRenderer cloudRenderer; private ModernCloudRenderer cloudRenderer;
/** /**
* @author jellysquid3 * @author jellysquid3
@@ -41,7 +41,7 @@ public class WorldRendererMixin {
@Inject(method = "renderClouds", at = @At(value = "INVOKE", target = "Ljava/lang/Float;isNaN(F)Z", ordinal = 0), cancellable = true) @Inject(method = "renderClouds", at = @At(value = "INVOKE", target = "Ljava/lang/Float;isNaN(F)Z", ordinal = 0), cancellable = true)
public void renderCloudsFast(PoseStack matrices, /*? if >=1.20.6 {*/ /*Matrix4f modelViewMatrix, *//*?}*/ Matrix4f projectionMatrix, float tickDelta, double x, double y, double z, CallbackInfo ci) { public void renderCloudsFast(PoseStack matrices, /*? if >=1.20.6 {*/ /*Matrix4f modelViewMatrix, *//*?}*/ Matrix4f projectionMatrix, float tickDelta, double x, double y, double z, CallbackInfo ci) {
if (this.cloudRenderer == null) { if (this.cloudRenderer == null) {
this.cloudRenderer = new CloudRenderer(this.minecraft.getResourceManager()); this.cloudRenderer = new ModernCloudRenderer(this.minecraft.getResourceManager());
} }
boolean renderFasterClouds = Celeritas.options().performance.useFasterClouds; boolean renderFasterClouds = Celeritas.options().performance.useFasterClouds;
@@ -0,0 +1,21 @@
package org.embeddedt.embeddium.impl.mixin.features.render.world.sky;
import net.minecraft.client.renderer.LevelRenderer;
import org.embeddedt.embeddium.impl.gl.compat.FogHelper;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(LevelRenderer.class)
public class SkyFogLevelRendererMixin {
@Inject(method = "renderLevel", at = { @At("HEAD"), @At("RETURN") })
private void celeritas$invalidateSkyTexture(CallbackInfo ci) {
FogHelper.INSTANCE.invalidateSkyTexture();
}
@Inject(method = "renderSky", at = @At("RETURN"))
private void celeritas$captureSkyTexture(CallbackInfo ci) {
FogHelper.INSTANCE.captureSkyTexture();
}
}
@@ -1,501 +0,0 @@
package org.embeddedt.embeddium.impl.render.immediate;
//? if >=1.17 {
import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.platform.NativeImage;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.*;
import net.minecraft.client.renderer.RenderType;
import org.embeddedt.embeddium.api.util.ColorABGR;
import org.embeddedt.embeddium.api.util.ColorARGB;
import org.embeddedt.embeddium.api.util.ColorMixer;
import org.embeddedt.embeddium.api.util.NormI8;
import org.embeddedt.embeddium.api.vertex.buffer.VertexBufferWriter;
import net.minecraft.client.CloudStatus;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.resources.Resource;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.server.packs.resources.ResourceProvider;
import net.minecraft.util.Mth;
import net.minecraft.world.phys.Vec3;
import org.embeddedt.embeddium.api.render.clouds.ModifyCloudRenderingEvent;
import org.embeddedt.embeddium.api.vertex.format.common.LineVertex;
import org.embeddedt.embeddium.impl.render.ShaderModBridge;
import org.embeddedt.embeddium.impl.render.CeleritasWorldRenderer;
import org.embeddedt.embeddium.impl.util.ResourceLocationUtil;
import org.jetbrains.annotations.Nullable;
import org.joml.Matrix4f;
import org.joml.Vector3f;
import org.lwjgl.opengl.GL30C;
import org.lwjgl.system.MemoryStack;
import java.io.IOException;
import java.io.InputStream;
public class CloudRenderer {
private static final ResourceLocation CLOUDS_TEXTURE_ID = ResourceLocationUtil.make("textures/environment/clouds.png");
private static final int CLOUD_COLOR_NEG_Y = ColorABGR.pack(0.7F, 0.7F, 0.7F, 1.0f);
private static final int CLOUD_COLOR_POS_Y = ColorABGR.pack(1.0f, 1.0f, 1.0f, 1.0f);
private static final int CLOUD_COLOR_NEG_X = ColorABGR.pack(0.9F, 0.9F, 0.9F, 1.0f);
private static final int CLOUD_COLOR_POS_X = ColorABGR.pack(0.9F, 0.9F, 0.9F, 1.0f);
private static final int CLOUD_COLOR_NEG_Z = ColorABGR.pack(0.8F, 0.8F, 0.8F, 1.0f);
private static final int CLOUD_COLOR_POS_Z = ColorABGR.pack(0.8F, 0.8F, 0.8F, 1.0f);
private static final int DIR_NEG_Y = 1 << 0;
private static final int DIR_POS_Y = 1 << 1;
private static final int DIR_NEG_X = 1 << 2;
private static final int DIR_POS_X = 1 << 3;
private static final int DIR_NEG_Z = 1 << 4;
private static final int DIR_POS_Z = 1 << 5;
private static final int NORMAL_NEG_Y = NormI8.pack(0f, -1f, 0f);
private static final int NORMAL_POS_Y = NormI8.pack(0f, 1f, 0f);
private static final int NORMAL_NEG_Z = NormI8.pack(0f, 0f, -1f);
private static final int NORMAL_POS_Z = NormI8.pack(0f, 0f, 1f);
private static final int NORMAL_NEG_X = NormI8.pack(-1f, 0f, 0f);
private static final int NORMAL_POS_X = NormI8.pack(1f, 0f, 0f);
// 256x256 px cloud.png is 12x12 units
// 3072 / 256 = 12
// 3072 / 1024 = 3
private static final int MAX_SINGLE_CLOUD_SIZE = 3072;
// 256x256 px cloud.png starts fog 8x from cloud render distance
// 2048 / 256 = 8
// 2048 / 1024 = 2
private static final int CLOUD_PIXELS_TO_FOG_DISTANCE = 2048;
// 256x256 px cloud.png results in a minimum render distance of 32
// 256 / 8 = 32
// 1024 / 8 = 128
private static final float CLOUD_PIXELS_TO_MINIMUM_RENDER_DISTANCE = 0.125F;
// 256x256 px cloud.png results in render distance multiplier of 2
// 256 / 128 = 2
// 1024 / 128 = 8
private static final float CLOUD_PIXELS_TO_MAXIMUM_RENDER_DISTANCE = 0.0078125F;
private VertexBuffer vertexBuffer;
private CloudEdges edges;
private CloudShader shader;
private int prevCenterCellX, prevCenterCellY, cachedRenderDistance;
private float cloudSizeX, cloudSizeZ, fogDistanceMultiplier;
private int cloudDistanceMinimum, cloudDistanceMaximum;
private CloudStatus cloudRenderMode;
private boolean hasCloudGeometry;
public CloudRenderer(ResourceProvider factory) {
this.reloadTextures(factory);
}
private static int fireModifyCloudRenderDistanceEvent(int distance) {
var event = new ModifyCloudRenderingEvent(distance);
ModifyCloudRenderingEvent.BUS.post(event);
return event.getCloudRenderDistance();
}
private void drawVertexBuffer() {
//? if <1.19 {
/*BufferUploader.reset();
this.vertexBuffer.bindVertexArray();
this.vertexBuffer.bind();
this.vertexBuffer.getFormat().setupBufferState();
*///?}
this.vertexBuffer.draw();
//? if <1.19 {
/*this.vertexBuffer.getFormat().clearBufferState();
VertexBuffer.unbind();
VertexBuffer.unbindVertexArray();
*///?}
}
public void render(@Nullable ClientLevel world, LocalPlayer player, Matrix4f modelViewMatrix, Matrix4f projectionMatrix, float ticks, float tickDelta, double cameraX, double cameraY, double cameraZ) {
if (world == null) {
return;
}
float cloudHeight = world.effects().getCloudHeight();
// Vanilla uses NaN height as a way to disable cloud rendering
if (Float.isNaN(cloudHeight)) {
return;
}
Vec3 color = world.getCloudColor(tickDelta);
double cloudTime = (ticks + tickDelta) * 0.03F;
double cloudCenterX = (cameraX + cloudTime);
double cloudCenterZ = (cameraZ) + 3.96D;
int renderDistance = CeleritasWorldRenderer.instance().getEffectiveRenderDistance();
// This insanity (as opposed to just wrapping the call) is necessary to preserve the original assignment for mixin compat
renderDistance = fireModifyCloudRenderDistanceEvent(renderDistance);
int cloudDistance = Math.max(this.cloudDistanceMinimum, (renderDistance * this.cloudDistanceMaximum) + 9);
int centerCellX = (int) (Math.floor(cloudCenterX / this.cloudSizeX));
int centerCellZ = (int) (Math.floor(cloudCenterZ / this.cloudSizeZ));
if (this.vertexBuffer == null || this.prevCenterCellX != centerCellX || this.prevCenterCellY != centerCellZ || this.cachedRenderDistance != renderDistance || cloudRenderMode != Minecraft.getInstance().options.getCloudsType()) {
//? if <1.21 {
BufferBuilder bufferBuilder = Tesselator.getInstance().getBuilder();
bufferBuilder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR_NORMAL);
//?} else {
//BufferBuilder bufferBuilder = Tesselator.getInstance().begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR_NORMAL);
//?}
this.cloudRenderMode = Minecraft.getInstance().options.getCloudsType();
this.rebuildGeometry(bufferBuilder, cloudDistance, centerCellX, centerCellZ);
if (this.vertexBuffer == null) {
this.vertexBuffer = new VertexBuffer(/*? if >=1.20 {*/VertexBuffer.Usage.DYNAMIC /*?}*/);
}
this.vertexBuffer.bind();
//? if <1.21 {
//? if <1.19
//bufferBuilder.end();
this.vertexBuffer.upload(bufferBuilder /*? if >=1.19 {*/ .end() /*?}*/);
this.hasCloudGeometry = true;
//?} else {
/*MeshData meshData = bufferBuilder.build();
if(meshData != null) {
this.vertexBuffer.upload(meshData);
this.hasCloudGeometry = true;
} else {
this.hasCloudGeometry = false;
}
*///?}
VertexBuffer.unbind();
this.prevCenterCellX = centerCellX;
this.prevCenterCellY = centerCellZ;
this.cachedRenderDistance = renderDistance;
}
// Skip render path if there is no cloud geometry
if (!this.hasCloudGeometry) {
return;
}
float translateX = (float) (cloudCenterX - (centerCellX * this.cloudSizeX));
float translateZ = (float) (cloudCenterZ - (centerCellZ * this.cloudSizeZ));
RenderSystem.enableDepthTest();
this.vertexBuffer.bind();
boolean insideClouds = cameraY < cloudHeight + 4.5f && cameraY > cloudHeight - 0.5f;
boolean fastClouds = cloudRenderMode == CloudStatus.FAST;
if (insideClouds || fastClouds) {
RenderSystem.disableCull();
} else {
RenderSystem.enableCull();
}
modelViewMatrix = new Matrix4f(modelViewMatrix);
modelViewMatrix.translate(-translateX, cloudHeight - (float) cameraY + 0.33F, -translateZ);
// PASS 1: Set up depth buffer
//? if <1.21 {
RenderSystem.disableBlend();
RenderSystem.depthMask(true);
RenderSystem.colorMask(false, false, false, false);
//?} else {
//RenderType.cloudsDepthOnly().setupRenderState();
//?}
this.shader.prepareForDraw(modelViewMatrix, projectionMatrix, (float) color.x, (float) color.y, (float) color.z, 0.8f);
this.drawVertexBuffer();
this.shader.clear();
//? if >=1.21
//RenderType.cloudsDepthOnly().clearRenderState();
// PASS 2: Render geometry
//? if <1.21 {
RenderSystem.enableBlend();
RenderSystem.blendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA);
RenderSystem.depthMask(false);
RenderSystem.enableDepthTest();
RenderSystem.depthFunc(GL30C.GL_EQUAL);
RenderSystem.colorMask(true, true, true, true);
//?} else {
//RenderType.clouds().setupRenderState();
//?}
this.shader.prepareForDraw(modelViewMatrix, projectionMatrix, (float) color.x, (float) color.y, (float) color.z, 0.8f);
this.drawVertexBuffer();
this.shader.clear();
//? if >=1.21
//RenderType.clouds().clearRenderState();
VertexBuffer.unbind();
//? if <1.21 {
RenderSystem.disableBlend();
RenderSystem.depthFunc(GL30C.GL_LEQUAL);
RenderSystem.enableCull();
//?}
RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f);
}
private void rebuildGeometry(BufferBuilder bufferBuilder, int cloudDistance, int centerCellX, int centerCellZ) {
var writer = VertexBufferWriter.of(bufferBuilder);
boolean fastClouds = cloudRenderMode == CloudStatus.FAST;
for (int offsetX = -cloudDistance; offsetX < cloudDistance; offsetX++) {
for (int offsetZ = -cloudDistance; offsetZ < cloudDistance; offsetZ++) {
int connectedEdges = this.edges.getEdges(centerCellX + offsetX, centerCellZ + offsetZ);
if (connectedEdges == 0) {
continue;
}
int texel = this.edges.getColor(centerCellX + offsetX, centerCellZ + offsetZ);
float x = offsetX * this.cloudSizeX;
float z = offsetZ * this.cloudSizeZ;
try (MemoryStack stack = MemoryStack.stackPush()) {
final long buffer = stack.nmalloc((fastClouds ? 4 : (6 * 4)) * LineVertex.STRIDE);
long ptr = buffer;
int count = 0;
// -Y
if ((connectedEdges & DIR_NEG_Y) != 0) {
int mixedColor = ColorMixer.mul(texel, fastClouds ? CLOUD_COLOR_POS_Y : CLOUD_COLOR_NEG_Y);
ptr = writeVertex(ptr, x + this.cloudSizeX, 0.0f, z + this.cloudSizeZ, mixedColor, NORMAL_NEG_Y);
ptr = writeVertex(ptr, x + 0.0f, 0.0f, z + this.cloudSizeZ, mixedColor, NORMAL_NEG_Y);
ptr = writeVertex(ptr, x + 0.0f, 0.0f, z + 0.0f, mixedColor, NORMAL_NEG_Y);
ptr = writeVertex(ptr, x + this.cloudSizeX, 0.0f, z + 0.0f, mixedColor, NORMAL_NEG_Y);
count += 4;
}
// Only emit -Y geometry to emulate vanilla fast clouds
if (fastClouds) {
writer.push(stack, buffer, count, LineVertex.FORMAT);
continue;
}
// +Y
if ((connectedEdges & DIR_POS_Y) != 0) {
int mixedColor = ColorMixer.mul(texel, CLOUD_COLOR_POS_Y);
ptr = writeVertex(ptr, x + 0.0f, 4.0f, z + this.cloudSizeZ, mixedColor, NORMAL_POS_Y);
ptr = writeVertex(ptr, x + this.cloudSizeX, 4.0f, z + this.cloudSizeZ, mixedColor, NORMAL_POS_Y);
ptr = writeVertex(ptr, x + this.cloudSizeX, 4.0f, z + 0.0f, mixedColor, NORMAL_POS_Y);
ptr = writeVertex(ptr, x + 0.0f, 4.0f, z + 0.0f, mixedColor, NORMAL_POS_Y);
count += 4;
}
// -X
if ((connectedEdges & DIR_NEG_X) != 0) {
int mixedColor = ColorMixer.mul(texel, CLOUD_COLOR_NEG_X);
ptr = writeVertex(ptr, x + 0.0f, 0.0f, z + this.cloudSizeZ, mixedColor, NORMAL_NEG_X);
ptr = writeVertex(ptr, x + 0.0f, 4.0f, z + this.cloudSizeZ, mixedColor, NORMAL_NEG_X);
ptr = writeVertex(ptr, x + 0.0f, 4.0f, z + 0.0f, mixedColor, NORMAL_NEG_X);
ptr = writeVertex(ptr, x + 0.0f, 0.0f, z + 0.0f, mixedColor, NORMAL_NEG_X);
count += 4;
}
// +X
if ((connectedEdges & DIR_POS_X) != 0) {
int mixedColor = ColorMixer.mul(texel, CLOUD_COLOR_POS_X);
ptr = writeVertex(ptr, x + this.cloudSizeX, 4.0f, z + this.cloudSizeZ, mixedColor, NORMAL_POS_X);
ptr = writeVertex(ptr, x + this.cloudSizeX, 0.0f, z + this.cloudSizeZ, mixedColor, NORMAL_POS_X);
ptr = writeVertex(ptr, x + this.cloudSizeX, 0.0f, z + 0.0f, mixedColor, NORMAL_POS_X);
ptr = writeVertex(ptr, x + this.cloudSizeX, 4.0f, z + 0.0f, mixedColor, NORMAL_POS_X);
count += 4;
}
// -Z
if ((connectedEdges & DIR_NEG_Z) != 0) {
int mixedColor = ColorMixer.mul(texel, CLOUD_COLOR_NEG_Z);
ptr = writeVertex(ptr, x + this.cloudSizeX, 4.0f, z + 0.0f, mixedColor, NORMAL_NEG_Z);
ptr = writeVertex(ptr, x + this.cloudSizeX, 0.0f, z + 0.0f, mixedColor, NORMAL_NEG_Z);
ptr = writeVertex(ptr, x + 0.0f, 0.0f, z + 0.0f, mixedColor, NORMAL_NEG_Z);
ptr = writeVertex(ptr, x + 0.0f, 4.0f, z + 0.0f, mixedColor, NORMAL_NEG_Z);
count += 4;
}
// +Z
if ((connectedEdges & DIR_POS_Z) != 0) {
int mixedColor = ColorMixer.mul(texel, CLOUD_COLOR_POS_Z);
ptr = writeVertex(ptr, x + this.cloudSizeX, 0.0f, z + this.cloudSizeZ, mixedColor, NORMAL_POS_Z);
ptr = writeVertex(ptr, x + this.cloudSizeX, 4.0f, z + this.cloudSizeZ, mixedColor, NORMAL_POS_Z);
ptr = writeVertex(ptr, x + 0.0f, 4.0f, z + this.cloudSizeZ, mixedColor, NORMAL_POS_Z);
ptr = writeVertex(ptr, x + 0.0f, 0.0f, z + this.cloudSizeZ, mixedColor, NORMAL_POS_Z);
count += 4;
}
if (count > 0) {
writer.push(stack, buffer, count, LineVertex.FORMAT);
}
}
}
}
}
private static long writeVertex(long buffer, float x, float y, float z, int color, int normal) {
LineVertex.put(buffer, x, y, z, color, normal);
return buffer + LineVertex.STRIDE;
}
public void reloadTextures(ResourceProvider factory) {
this.destroy();
this.edges = createCloudEdges();
// FIXME this ugly code is needed because Iris, as usual, duplicates the original code and assumes the old sizes
// If shaders are on we assume the vanilla size so that the hardcoded values will actually match up with our code.
// This will be removed when Iris support is dropped.
boolean shaderMod = ShaderModBridge.areShadersEnabled();
float width = shaderMod ? 256 : this.edges.width;
float height = shaderMod ? 256 : this.edges.height;
this.cloudSizeX = MAX_SINGLE_CLOUD_SIZE / width;
this.cloudSizeZ = MAX_SINGLE_CLOUD_SIZE / height;
this.fogDistanceMultiplier = CLOUD_PIXELS_TO_FOG_DISTANCE / width;
this.cloudDistanceMinimum = (int) (width * CLOUD_PIXELS_TO_MINIMUM_RENDER_DISTANCE);
this.cloudDistanceMaximum = (int) (width * CLOUD_PIXELS_TO_MAXIMUM_RENDER_DISTANCE);
this.shader = new CloudShader();
}
public void destroy() {
if (this.shader != null) {
this.shader.close();
this.shader = null;
}
if (this.vertexBuffer != null) {
this.vertexBuffer.close();
this.vertexBuffer = null;
}
}
private static CloudEdges createCloudEdges() {
ResourceManager resourceManager = Minecraft.getInstance().getResourceManager();
try {
//? if >=1.19 {
Resource resource = resourceManager.getResource(CLOUDS_TEXTURE_ID)
.orElseThrow();
try (InputStream inputStream = resource.open()){
//?} else {
/*Resource resource = resourceManager.getResource(CLOUDS_TEXTURE_ID);
try (InputStream inputStream = resource.getInputStream()){
*///?}
try (NativeImage nativeImage = NativeImage.read(inputStream)) {
return new CloudEdges(nativeImage);
}
}
} catch (IOException ex) {
throw new RuntimeException("Failed to load texture data", ex);
}
}
private static class CloudEdges {
private final byte[] edges;
private final int[] colors;
private final int width, height;
public CloudEdges(NativeImage texture) {
int width = texture.getWidth();
int height = texture.getHeight();
this.edges = new byte[width * height];
this.colors = new int[width * height];
this.width = width;
this.height = height;
for (int x = 0; x < width; x++) {
for (int z = 0; z < height; z++) {
int index = index(x, z, width, height);
int cell = texture.getPixelRGBA(x, z);
this.colors[index] = cell;
int edges = 0;
if (isOpaqueCell(cell)) {
edges |= DIR_NEG_Y | DIR_POS_Y;
int negX = texture.getPixelRGBA(wrap(x - 1, width), wrap(z, height));
if (cell != negX) {
edges |= DIR_NEG_X;
}
int posX = texture.getPixelRGBA(wrap(x + 1, width), wrap(z, height));
if (!isOpaqueCell(posX) && cell != posX) {
edges |= DIR_POS_X;
}
int negZ = texture.getPixelRGBA(wrap(x, width), wrap(z - 1, height));
if (cell != negZ) {
edges |= DIR_NEG_Z;
}
int posZ = texture.getPixelRGBA(wrap(x, width), wrap(z + 1, height));
if (!isOpaqueCell(posZ) && cell != posZ) {
edges |= DIR_POS_Z;
}
}
this.edges[index] = (byte) edges;
}
}
}
private static boolean isOpaqueCell(int color) {
return ColorARGB.unpackAlpha(color) > 1;
}
public int getEdges(int x, int z) {
return this.edges[index(x, z, this.width, this.height)];
}
public int getColor(int x, int z) {
return this.colors[index(x, z, this.width, this.height)];
}
private static int index(int posX, int posZ, int width, int height) {
return (wrap(posX, width) * height) + wrap(posZ, height);
}
private static int wrap(int pos, int dim) {
return Math.floorMod(pos, dim);
}
}
}
//?}
@@ -1,79 +0,0 @@
package org.embeddedt.embeddium.impl.render.immediate;
import org.embeddedt.embeddium.impl.gl.shader.*;
import org.embeddedt.embeddium.impl.gl.shader.uniform.*;
import org.embeddedt.embeddium.impl.gl.compat.FogHelper;
import org.embeddedt.embeddium.impl.render.shader.ShaderLoader;
import org.joml.Matrix4f;
public class CloudShader implements AutoCloseable {
private static final int ATTRIBUTE_POSITION = 0;
private static final int ATTRIBUTE_COLOR = 1;
private static final int FRAG_COLOR = 0;
private final GlProgram<CloudShaderInterface> program;
private static final ShaderConstants CLOUD_CONSTANTS = ShaderConstants.builder().add("USE_FOG").build();
public CloudShader() {
this.program = createShader();
}
private GlProgram<CloudShaderInterface> createShader() {
GlShader vertShader = ShaderLoader.loadShader(ShaderType.VERTEX, "sodium:clouds/clouds.vsh", CLOUD_CONSTANTS);
GlShader fragShader = ShaderLoader.loadShader(ShaderType.FRAGMENT, "sodium:clouds/clouds.fsh", CLOUD_CONSTANTS);
try {
return GlProgram.builder("celeritas:cloud_shader")
.attachShader(vertShader)
.attachShader(fragShader)
.bindAttribute("Position", ATTRIBUTE_POSITION)
.bindAttribute("Color", ATTRIBUTE_COLOR)
.bindFragmentData("fragColor", FRAG_COLOR)
.link(CloudShaderInterface::new);
} finally {
vertShader.delete();
fragShader.delete();
}
}
public void prepareForDraw(Matrix4f modelViewMatrix, Matrix4f projectionMatrix, float r, float g, float b, float a) {
this.program.bind();
this.program.getInterface().setupState(modelViewMatrix, projectionMatrix, r, g, b, a);
}
public void clear() {
this.program.unbind();
}
@Override
public void close() {
this.program.delete();
}
static class CloudShaderInterface {
private final GlUniformMatrix4f uniformModelViewMatrix;
private final GlUniformMatrix4f uniformProjectionMatrix;
private final GlUniformFloat uniformFogStart, uniformFogEnd;
private final GlUniformFloat4v uniformFogColor, uniformMainColor;
public CloudShaderInterface(ShaderBindingContext context) {
this.uniformModelViewMatrix = context.bindUniform("ModelViewMat", GlUniformMatrix4f::new);
this.uniformProjectionMatrix = context.bindUniform("ProjMat", GlUniformMatrix4f::new);
this.uniformFogStart = context.bindUniform("FogStart", GlUniformFloat::new);
this.uniformFogEnd = context.bindUniform("FogEnd", GlUniformFloat::new);
this.uniformFogColor = context.bindUniform("FogColor", GlUniformFloat4v::new);
this.uniformMainColor = context.bindUniform("ColorModulator", GlUniformFloat4v::new);
}
public void setupState(Matrix4f modelViewMatrix, Matrix4f projectionMatrix, float r, float g, float b, float a) {
this.uniformModelViewMatrix.set(modelViewMatrix);
this.uniformProjectionMatrix.set(projectionMatrix);
this.uniformFogStart.set(FogHelper.INSTANCE.getFogStart());
this.uniformFogEnd.set(FogHelper.INSTANCE.getFogEnd());
this.uniformFogColor.set(FogHelper.INSTANCE.getFogColor());
this.uniformMainColor.set(new float[] { r, g, b, a });
}
}
}
@@ -0,0 +1,204 @@
package org.embeddedt.embeddium.impl.render.immediate;
//? if >=1.17 {
import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.platform.NativeImage;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.CloudStatus;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.resources.Resource;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.server.packs.resources.ResourceProvider;
import net.minecraft.world.phys.Vec3;
import org.embeddedt.embeddium.api.render.clouds.ModifyCloudRenderingEvent;
import org.embeddedt.embeddium.impl.gl.compat.FogHelper;
import org.embeddedt.embeddium.impl.gl.compat.ModernGlStateService;
import org.embeddedt.embeddium.impl.gl.device.CommandList;
import org.embeddedt.embeddium.impl.gl.device.RenderDevice;
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkFogMode;
import org.embeddedt.embeddium.impl.render.clouds.CloudFrame;
import org.embeddedt.embeddium.impl.render.clouds.CloudRenderState;
import org.embeddedt.embeddium.impl.render.clouds.CloudRenderer;
import org.embeddedt.embeddium.impl.render.clouds.CloudTexture;
import org.embeddedt.embeddium.impl.util.ResourceLocationUtil;
import org.jetbrains.annotations.Nullable;
import org.joml.Matrix4f;
import org.lwjgl.opengl.GL30C;
import java.io.IOException;
import java.io.InputStream;
public class ModernCloudRenderer {
private static final ResourceLocation CLOUDS_TEXTURE_ID = ResourceLocationUtil.make("textures/environment/clouds.png");
// Vanilla's default cloud range since 1.21.6
private static final int CLOUD_RANGE_CHUNKS = 128;
private static final CloudRenderState RENDER_STATE = new CloudRenderState() {
@Override
public void setup(boolean fancy) {
//? if <1.21 {
RenderSystem.enableBlend();
RenderSystem.blendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA);
RenderSystem.enableDepthTest();
RenderSystem.depthFunc(GL30C.GL_LEQUAL);
RenderSystem.depthMask(true);
RenderSystem.colorMask(true, true, true, true);
//?} else {
//RenderType.clouds().setupRenderState();
//?}
if (fancy) {
RenderSystem.enableCull();
} else {
RenderSystem.disableCull();
}
}
@Override
public void restore() {
//? if <1.21 {
RenderSystem.disableBlend();
//?} else
//RenderType.clouds().clearRenderState();
RenderSystem.enableCull();
}
};
private CloudTexture texture;
private @Nullable CloudRenderer renderer;
public ModernCloudRenderer(ResourceProvider factory) {
this.reloadTextures(factory);
}
private static int fireModifyCloudRenderDistanceEvent(int distance) {
var event = new ModifyCloudRenderingEvent(distance);
ModifyCloudRenderingEvent.BUS.post(event);
return event.getCloudRenderDistance();
}
public static float getCloudRange() {
return fireModifyCloudRenderDistanceEvent(CLOUD_RANGE_CHUNKS) * 16.0f;
}
public void render(@Nullable ClientLevel world, LocalPlayer player, Matrix4f modelViewMatrix, Matrix4f projectionMatrix, float ticks, float tickDelta, double cameraX, double cameraY, double cameraZ) {
if (world == null) {
return;
}
float cloudHeight = world.effects().getCloudHeight();
// Vanilla uses NaN height as a way to disable cloud rendering
if (Float.isNaN(cloudHeight)) {
return;
}
float range = getCloudRange();
float fogEnd = getFogEnd(range);
if (fogEnd <= 0.0f) {
return;
}
Vec3 color = world.getCloudColor(tickDelta);
boolean fancy = Minecraft.getInstance().options.getCloudsType() == CloudStatus.FANCY;
CloudFrame frame = new CloudFrame(modelViewMatrix, projectionMatrix, cameraX, cameraY, cameraZ, cloudHeight,
ticks + tickDelta, (float) color.x, (float) color.y, (float) color.z, fancy, range, fogEnd);
RenderDevice.enterManagedCode();
try (CommandList commandList = RenderDevice.INSTANCE.createCommandList()) {
if (this.renderer == null) {
this.renderer = new CloudRenderer(commandList, ModernGlStateService.INSTANCE, this.texture);
}
if (this.renderer.prepare(commandList, frame)) {
this.draw(commandList, this.renderer, frame);
}
} finally {
exitManagedCode();
}
}
private void draw(CommandList commandList, CloudRenderer renderer, CloudFrame frame) {
renderer.render(commandList, RENDER_STATE, frame);
}
/**
* Like vanilla since 1.21.6, clouds fade out over their own range, unless environmental fog (water, blindness, etc.)
* is closer.
*/
private static float getFogEnd(float cloudRange) {
FogHelper fog = FogHelper.INSTANCE;
if (fog.getFogMode() != ChunkFogMode.NONE && fog.getFogEnd() < fog.getSkyFogEdgeEnd()) {
return Math.min(cloudRange, fog.getFogEnd());
}
return cloudRange;
}
public void reloadTextures(ResourceProvider factory) {
this.destroy();
this.texture = loadTexture();
}
public void destroy() {
if (this.renderer == null) {
return;
}
RenderDevice.enterManagedCode();
try (CommandList commandList = RenderDevice.INSTANCE.createCommandList()) {
this.renderer.delete(commandList);
} finally {
exitManagedCode();
}
this.renderer = null;
}
private static void exitManagedCode() {
RenderDevice.exitManagedCode();
com.mojang.blaze3d.vertex.BufferUploader.reset();
}
private static CloudTexture loadTexture() {
ResourceManager resourceManager = Minecraft.getInstance().getResourceManager();
try {
//? if >=1.19 {
Resource resource = resourceManager.getResource(CLOUDS_TEXTURE_ID)
.orElseThrow();
try (InputStream inputStream = resource.open()){
//?} else {
/*Resource resource = resourceManager.getResource(CLOUDS_TEXTURE_ID);
try (InputStream inputStream = resource.getInputStream()){
*///?}
try (NativeImage image = NativeImage.read(inputStream)) {
int width = image.getWidth();
int height = image.getHeight();
int[] pixels = new int[width * height];
for (int z = 0; z < height; z++) {
for (int x = 0; x < width; x++) {
pixels[x + z * width] = image.getPixelRGBA(x, z);
}
}
return new CloudTexture(width, height, pixels);
}
}
} catch (IOException ex) {
throw new RuntimeException("Failed to load texture data", ex);
}
}
}
//?}
@@ -1,13 +1,24 @@
package org.embeddedt.embeddium.impl.gl.compat; package org.embeddedt.embeddium.impl.gl.compat;
import com.mojang.blaze3d.opengl.GlStateManager;
import com.mojang.blaze3d.opengl.GlTexture;
import com.mojang.blaze3d.pipeline.RenderTarget;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.fog.FogData; import net.minecraft.client.renderer.fog.FogData;
import org.embeddedt.embeddium.impl.Celeritas;
import org.embeddedt.embeddium.impl.gl.shader.ShaderBindingContext; import org.embeddedt.embeddium.impl.gl.shader.ShaderBindingContext;
import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformFloat; import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformFloat;
import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformFloat4v; import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformFloat4v;
import org.embeddedt.embeddium.impl.render.chunk.fog.FogService; import org.embeddedt.embeddium.impl.render.chunk.fog.FogService;
import org.embeddedt.embeddium.impl.render.chunk.fog.SkyTextureCopy;
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderComponent; import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderComponent;
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderEnvironment; import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderEnvironment;
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderFogComponent;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL30;
import org.jetbrains.annotations.Nullable;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
@@ -52,26 +63,66 @@ public class FogHelper implements FogService {
@Override @Override
public ChunkShaderComponent.Factory<?> getFogMode() { public ChunkShaderComponent.Factory<?> getFogMode() {
return PostmodernFogComponent.FACTORY; return this.getSkyTexture() != 0 ? PostmodernFogComponent.SKY_FACTORY : PostmodernFogComponent.FACTORY;
}
private final SkyTextureCopy skyTexture = new SkyTextureCopy(ModernGlStateService.INSTANCE);
private int skyReadFramebuffer;
@Override
public int getSkyTexture() {
return this.skyTexture.getTexture();
}
public void captureSkyTexture() {
RenderTarget target = Minecraft.getInstance().getMainRenderTarget();
if (!SkyTextureCopy.shouldProvide(Celeritas.options().quality.useSkyFog) || !(target.getColorTexture() instanceof GlTexture color)) {
this.skyTexture.delete();
return;
}
// Blaze3D only binds framebuffers inside its own passes, so read the main target through one of our own
if (this.skyReadFramebuffer == 0) {
this.skyReadFramebuffer = GlStateManager.glGenFramebuffers();
}
GlStateManager._glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, this.skyReadFramebuffer);
GlStateManager._glFramebufferTexture2D(GL30.GL_READ_FRAMEBUFFER, GL30.GL_COLOR_ATTACHMENT0, GL11.GL_TEXTURE_2D, color.glId(), 0);
this.skyTexture.copy(target.width, target.height);
}
public void invalidateSkyTexture() {
this.skyTexture.invalidate();
}
public void deleteSkyTexture() {
this.skyTexture.delete();
} }
private static class PostmodernFogComponent implements ChunkShaderComponent { private static class PostmodernFogComponent implements ChunkShaderComponent {
private static final ChunkShaderComponent.Factory<PostmodernFogComponent> FACTORY = new ChunkShaderComponent.Factory<>() { private static final ChunkShaderComponent.Factory<PostmodernFogComponent> FACTORY = new Factory(false);
private static final ChunkShaderComponent.Factory<PostmodernFogComponent> SKY_FACTORY = new Factory(true);
private record Factory(boolean skyFog) implements ChunkShaderComponent.Factory<PostmodernFogComponent> {
@Override @Override
public PostmodernFogComponent create(ShaderBindingContext context, ChunkShaderEnvironment environment) { public PostmodernFogComponent create(ShaderBindingContext context, ChunkShaderEnvironment environment) {
return new PostmodernFogComponent(context); return new PostmodernFogComponent(context, this.skyFog ? new ChunkShaderFogComponent.SkyUniforms(context, environment.fogService()) : null);
} }
@Override @Override
public Collection<String> getDefines() { public Collection<String> getDefines() {
return List.of("USE_FOG", "USE_FOG_POSTMODERN"); return this.skyFog ? List.of("USE_FOG", "USE_FOG_POSTMODERN", "USE_SKY_FOG") : List.of("USE_FOG", "USE_FOG_POSTMODERN");
}
} }
};
private final GlUniformFloat4v uFogColor; private final GlUniformFloat4v uFogColor;
private final GlUniformFloat uRenderDistFogStart, uRenderDistFogEnd, uEnvFogStart, uEnvFogEnd; private final GlUniformFloat uRenderDistFogStart, uRenderDistFogEnd, uEnvFogStart, uEnvFogEnd;
public PostmodernFogComponent(ShaderBindingContext context) { private final ChunkShaderFogComponent.@Nullable SkyUniforms skyFog;
public PostmodernFogComponent(ShaderBindingContext context, ChunkShaderFogComponent.@Nullable SkyUniforms skyFog) {
this.skyFog = skyFog;
this.uFogColor = context.bindUniform("u_FogColor", GlUniformFloat4v::new); this.uFogColor = context.bindUniform("u_FogColor", GlUniformFloat4v::new);
this.uRenderDistFogStart = context.bindUniform("u_RenderDistFogStart", GlUniformFloat::new); this.uRenderDistFogStart = context.bindUniform("u_RenderDistFogStart", GlUniformFloat::new);
this.uRenderDistFogEnd = context.bindUniform("u_RenderDistFogEnd", GlUniformFloat::new); this.uRenderDistFogEnd = context.bindUniform("u_RenderDistFogEnd", GlUniformFloat::new);
@@ -87,6 +138,10 @@ public class FogHelper implements FogService {
this.uRenderDistFogEnd.set(data.renderDistanceEnd); this.uRenderDistFogEnd.set(data.renderDistanceEnd);
this.uEnvFogStart.set(data.environmentalStart); this.uEnvFogStart.set(data.environmentalStart);
this.uEnvFogEnd.set(data.environmentalEnd); this.uEnvFogEnd.set(data.environmentalEnd);
if (this.skyFog != null) {
this.skyFog.setup();
}
} }
} }
} }
@@ -163,7 +163,18 @@ public abstract class LevelRendererMixin implements WorldRendererExtended {
return new ChunkSectionsToRender(blocksAtlas, new EnumMap<>(ChunkSectionLayer.class), 0, new GpuBufferSlice[0]); return new ChunkSectionsToRender(blocksAtlas, new EnumMap<>(ChunkSectionLayer.class), 0, new GpuBufferSlice[0]);
} }
@Redirect(method = "lambda$addMainPass$0", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/chunk/ChunkSectionsToRender;renderGroup(Lnet/minecraft/client/renderer/chunk/ChunkSectionLayerGroup;Lcom/mojang/blaze3d/textures/GpuSampler;)V")) @Inject(method = "renderLevel", at = { @At("HEAD"), @At("RETURN") })
private void invalidateSkyTexture(CallbackInfo ci) {
FogHelper.INSTANCE.invalidateSkyTexture();
}
// Runs after the clear and sky passes
@Inject(method = "lambda$addMainPass$0", at = @At("HEAD"))
private void captureSkyTexture(CallbackInfo ci) {
FogHelper.INSTANCE.captureSkyTexture();
}
@Redirect(method = "lambda$addMainPass$0", at =@At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/chunk/ChunkSectionsToRender;renderGroup(Lnet/minecraft/client/renderer/chunk/ChunkSectionLayerGroup;Lcom/mojang/blaze3d/textures/GpuSampler;)V"))
private void renderChunksWithCeleritas(ChunkSectionsToRender sectionsToRender, ChunkSectionLayerGroup group, GpuSampler terrainSampler) { private void renderChunksWithCeleritas(ChunkSectionsToRender sectionsToRender, ChunkSectionLayerGroup group, GpuSampler terrainSampler) {
RenderDevice.enterManagedCode(); RenderDevice.enterManagedCode();
var cameraPos = this.levelRenderState.cameraRenderState.pos; var cameraPos = this.levelRenderState.cameraRenderState.pos;
@@ -17,6 +17,8 @@
"celeritas.options.async_graph_search.tooltip": "Performs occlusion/frustum culling asynchronously, up to one frame behind the current camera position. This can improve frametimes, particularly at higher render distances, but at the cost of chunks popping into view if the camera is turned too aggressively.", "celeritas.options.async_graph_search.tooltip": "Performs occlusion/frustum culling asynchronously, up to one frame behind the current camera position. This can improve frametimes, particularly at higher render distances, but at the cost of chunks popping into view if the camera is turned too aggressively.",
"celeritas.options.chunk_fade_in_duration.name": "Chunk Fade-In Duration", "celeritas.options.chunk_fade_in_duration.name": "Chunk Fade-In Duration",
"celeritas.options.chunk_fade_in_duration.value": "%s ms", "celeritas.options.chunk_fade_in_duration.value": "%s ms",
"celeritas.options.sky_fog.name": "Sky Fog",
"celeritas.options.sky_fog.tooltip": "Makes distant terrain and clouds fade into the sky behind them instead of a single fog color. This removes miscolored terrain at the edge of the render distance during sunrise and sunset, in the End, and with custom skies. Has no effect while a shader pack is active.",
"celeritas.options.rgss_texture_filtering.name": "RGSS Texture Filtering", "celeritas.options.rgss_texture_filtering.name": "RGSS Texture Filtering",
"celeritas.options.rgss_texture_filtering.tooltip": "Smooths block textures in the distance by supersampling them, which reduces shimmering and jagged texel edges. Requires mipmaps, and has no effect while a shader pack is active.", "celeritas.options.rgss_texture_filtering.tooltip": "Smooths block textures in the distance by supersampling them, which reduces shimmering and jagged texel edges. Requires mipmaps, and has no effect while a shader pack is active.",
"celeritas.options.chunk_fade_in_duration.tooltip": "Controls how long it takes for newly loaded chunks to fully appear. Longer durations create a smoother transition between unloaded and loaded chunks, reducing visual popping, but may make distant terrain appear to 'fade in' more slowly.", "celeritas.options.chunk_fade_in_duration.tooltip": "Controls how long it takes for newly loaded chunks to fully appear. Longer durations create a smoother transition between unloaded and loaded chunks, reducing visual popping, but may make distant terrain appear to 'fade in' more slowly.",
@@ -692,18 +692,27 @@ public class IrisRenderingPipeline implements WorldRenderingPipeline, ShaderRend
private PendingGbufferProgram createShader(String name, Optional<ProgramSource> source, ShaderKey key) { private PendingGbufferProgram createShader(String name, Optional<ProgramSource> source, ShaderKey key) {
if (source.isEmpty()) { if (source.isEmpty()) {
//? if >=26.1 { // Synthesized programs can't generate clouds, so the clouds are drawn without the pack.
/*// Synthesized programs can't generate 26.1's clouds, so vanilla's draws them. if (generatesClouds(key)) {
if (key == ShaderKey.CLOUDS) {
return null; return null;
} }
*///?}
return createFallbackShader(name, key); return createFallbackShader(name, key);
} }
return createShader(name, source.get(), key.getProgram(), key.getAlphaTest(), key.getVertexFormat(), return createShader(name, source.get(), key.getProgram(), key.getAlphaTest(), key.getVertexFormat(),
key.isIntensity(), key.shouldIgnoreLightmap(), key.isGlint(), key.isText()); key.isIntensity(), key.shouldIgnoreLightmap(), key.isGlint(), key.isText(), generatesClouds(key));
}
/**
* Whether the key's program generates its vertices from cloud faces, as vanilla's clouds do on 26.1 and
* Celeritas's do before that.
*/
private static boolean generatesClouds(ShaderKey key) {
//? if >=26.1 {
/*return key.getProgram() == ProgramId.Clouds;
*///?} else
return key == ShaderKey.CLOUDS_SODIUM;
} }
@Override @Override
@@ -712,7 +721,8 @@ public class IrisRenderingPipeline implements WorldRenderingPipeline, ShaderRend
} }
private PendingGbufferProgram createShader(String name, ProgramSource source, ProgramId programId, AlphaTest fallbackAlpha, private PendingGbufferProgram createShader(String name, ProgramSource source, ProgramId programId, AlphaTest fallbackAlpha,
VertexFormat vertexFormat, boolean isIntensity, boolean isFullbright, boolean isGlint, boolean isText) { VertexFormat vertexFormat, boolean isIntensity, boolean isFullbright, boolean isGlint, boolean isText,
boolean generatesClouds) {
GlFramebuffer beforeTranslucent = renderTargets.createGbufferFramebuffer(flippedAfterPrepare, source.getDirectives().getDrawBuffers()); GlFramebuffer beforeTranslucent = renderTargets.createGbufferFramebuffer(flippedAfterPrepare, source.getDirectives().getDrawBuffers());
GlFramebuffer afterTranslucent = renderTargets.createGbufferFramebuffer(flippedAfterTranslucent, source.getDirectives().getDrawBuffers()); GlFramebuffer afterTranslucent = renderTargets.createGbufferFramebuffer(flippedAfterTranslucent, source.getDirectives().getDrawBuffers());
boolean isLines = programId == ProgramId.Line && resolver.has(ProgramId.Line); boolean isLines = programId == ProgramId.Line && resolver.has(ProgramId.Line);
@@ -723,7 +733,7 @@ public class IrisRenderingPipeline implements WorldRenderingPipeline, ShaderRend
() -> isBeforeTranslucent ? flippedAfterPrepare : flippedAfterTranslucent; () -> isBeforeTranslucent ? flippedAfterPrepare : flippedAfterTranslucent;
return ShaderCreator.create(this, name, source, programId, beforeTranslucent, afterTranslucent, return ShaderCreator.create(this, name, source, programId, beforeTranslucent, afterTranslucent,
fallbackAlpha, vertexFormat, inputs, flipped, isIntensity, false, isLines, programId == ProgramId.Clouds, customUniforms); fallbackAlpha, vertexFormat, inputs, flipped, isIntensity, false, isLines, generatesClouds, customUniforms);
} }
private PendingGbufferProgram createFallbackShader(String name, ShaderKey key) { private PendingGbufferProgram createFallbackShader(String name, ShaderKey key) {
@@ -3,10 +3,12 @@ package net.irisshaders.iris.pipeline.foss_transform;
import org.taumc.glsl.Transformer; import org.taumc.glsl.Transformer;
/** /**
* Generates the vertices of 26.1's clouds in a shader pack's vertex shader. Vanilla draws clouds without vertex data, * Generates the vertices of clouds in a shader pack's vertex shader. 26.1's vanilla clouds and Celeritas's clouds before
* building each vertex from {@code gl_VertexID}, the cloud cells in the {@code CloudFaces} texel buffer and the * that are drawn without vertex data, building each vertex from {@code gl_VertexID}, the cloud cells in the
* {@code CloudInfo} block, as its {@code rendertype_clouds} shader does. This feeds the results to the pack's shader in * {@code CloudFaces} texel buffer and the cloud info, as vanilla's {@code rendertype_clouds} shader does. This feeds the
* place of the position, color, normal and texture coordinate attributes. * results to the pack's shader in place of the position, color, normal and texture coordinate attributes.
* <p>
* Before 26.1, the cloud info is plain uniforms, and each cell is also tinted by its pixel in the clouds texture.
*/ */
public final class CloudVertices { public final class CloudVertices {
/** /**
@@ -14,6 +16,16 @@ public final class CloudVertices {
*/ */
public static final String CLOUD_FACES_SAMPLER = "iris_CloudFaces"; public static final String CLOUD_FACES_SAMPLER = "iris_CloudFaces";
//? if <26.1 {
/**
* The name of the clouds texture sampler, which must be bound to Celeritas's cloud colors texture.
*/
public static final String CLOUD_COLORS_SAMPLER = "iris_CloudColors";
private static final String CELL_COLOR = " * iris_cloudCellColor(cellX, cellZ)";
//?} else
//private static final String CELL_COLOR = "";
private CloudVertices() { private CloudVertices() {
} }
@@ -30,7 +42,15 @@ public final class CloudVertices {
translationUnit.rename(attribute[0], attribute[1]); translationUnit.rename(attribute[0], attribute[1]);
} }
translationUnit.injectVariable(VanillaUniformBlocks.CLOUD_INFO.getDeclaration()); //? if >=26.1 {
/*translationUnit.injectVariable(VanillaUniformBlocks.CLOUD_INFO.getDeclaration());
*///?} else {
translationUnit.injectVariable("uniform vec4 iris_CloudColor;");
translationUnit.injectVariable("uniform vec3 iris_CloudOffset;");
translationUnit.injectVariable("uniform vec3 iris_CloudCellSize;");
translationUnit.injectVariable("uniform ivec2 iris_CloudCenterCell;");
translationUnit.injectVariable("uniform sampler2D " + CLOUD_COLORS_SAMPLER + ";");
//?}
translationUnit.injectVariable("uniform isamplerBuffer " + CLOUD_FACES_SAMPLER + ";"); translationUnit.injectVariable("uniform isamplerBuffer " + CLOUD_FACES_SAMPLER + ";");
translationUnit.injectVariable("vec3 iris_cloudPosition;"); translationUnit.injectVariable("vec3 iris_cloudPosition;");
translationUnit.injectVariable("vec4 iris_cloudColor;"); translationUnit.injectVariable("vec4 iris_cloudColor;");
@@ -68,8 +88,20 @@ public final class CloudVertices {
vec3 faceVertex = vertices[(direction * 4) + (isInsideFace ? 3 - quadVertex : quadVertex)]; vec3 faceVertex = vertices[(direction * 4) + (isInsideFace ? 3 - quadVertex : quadVertex)];
iris_cloudPosition = (faceVertex + vec3(cellX, 0, cellZ)) * iris_CloudCellSize + iris_CloudOffset; iris_cloudPosition = (faceVertex + vec3(cellX, 0, cellZ)) * iris_CloudCellSize + iris_CloudOffset;
iris_cloudNormal = isInsideFace ? -normals[direction] : normals[direction]; iris_cloudNormal = isInsideFace ? -normals[direction] : normals[direction];
iris_cloudColor = (useTopColor ? faceColors[1] : faceColors[direction]) * iris_CloudColor; iris_cloudColor = (useTopColor ? faceColors[1] : faceColors[direction]) * iris_CloudColor""" + CELL_COLOR + """
;
}"""); }""");
//? if <26.1 {
// injectFunction inserts each function before the previously injected one, so this ends up ahead of
// iris_generateCloudVertex, which calls it.
translationUnit.injectFunction("""
vec4 iris_cloudCellColor(int cellX, int cellZ) {
ivec2 size = textureSize(iris_CloudColors, 0);
ivec2 cell = iris_CloudCenterCell + ivec2(cellX, cellZ);
cell -= size * ivec2(floor(vec2(cell) / vec2(size)));
return texelFetch(iris_CloudColors, cell, 0);
}""");
//?}
translationUnit.prependMain("iris_generateCloudVertex();"); translationUnit.prependMain("iris_generateCloudVertex();");
} }
} }
@@ -209,8 +209,13 @@ public class VanillaTransformer {
translationUnit.injectVariable( translationUnit.injectVariable(
"uniform mat4 iris_ProjMat;"); "uniform mat4 iris_ProjMat;");
//? if >=26.1 //? if >=26.1 {
//patchVanillaBlocks(translationUnit, parameters); /*patchVanillaBlocks(translationUnit, parameters);
*///?} else {
if (parameters.isClouds() && parameters.type == ShaderType.VERTEX) {
CloudVertices.patch(translationUnit);
}
//?}
} }
public static void patchVanillaCore(Transformer translationUnit, VanillaParameters parameters) { public static void patchVanillaCore(Transformer translationUnit, VanillaParameters parameters) {
@@ -285,8 +290,13 @@ public class VanillaTransformer {
addIfNotExistsType(translationUnit, "iris_UV2", "in vec2"); addIfNotExistsType(translationUnit, "iris_UV2", "in vec2");
} }
//? if >=26.1 //? if >=26.1 {
//patchVanillaBlocks(translationUnit, parameters); /*patchVanillaBlocks(translationUnit, parameters);
*///?} else {
if (parameters.isClouds() && parameters.type == ShaderType.VERTEX) {
CloudVertices.patch(translationUnit);
}
//?}
} }
//? if >=26.1 { //? if >=26.1 {
@@ -71,6 +71,10 @@ public final class GbufferProgram {
private final int fogColorLocation; private final int fogColorLocation;
private final int light0DirectionLocation; private final int light0DirectionLocation;
private final int light1DirectionLocation; private final int light1DirectionLocation;
private final int cloudColorLocation;
private final int cloudOffsetLocation;
private final int cloudCellSizeLocation;
private final int cloudCenterCellLocation;
private final Matrix4f scratchMatrix = new Matrix4f(); private final Matrix4f scratchMatrix = new Matrix4f();
private final Matrix3f scratchNormalMatrix = new Matrix3f(); private final Matrix3f scratchNormalMatrix = new Matrix3f();
@@ -127,6 +131,10 @@ public final class GbufferProgram {
this.fogColorLocation = GlStateManager._glGetUniformLocation(id, "iris_FogColor"); this.fogColorLocation = GlStateManager._glGetUniformLocation(id, "iris_FogColor");
this.light0DirectionLocation = GlStateManager._glGetUniformLocation(id, "iris_Light0_Direction"); this.light0DirectionLocation = GlStateManager._glGetUniformLocation(id, "iris_Light0_Direction");
this.light1DirectionLocation = GlStateManager._glGetUniformLocation(id, "iris_Light1_Direction"); this.light1DirectionLocation = GlStateManager._glGetUniformLocation(id, "iris_Light1_Direction");
this.cloudColorLocation = GlStateManager._glGetUniformLocation(id, "iris_CloudColor");
this.cloudOffsetLocation = GlStateManager._glGetUniformLocation(id, "iris_CloudOffset");
this.cloudCellSizeLocation = GlStateManager._glGetUniformLocation(id, "iris_CloudCellSize");
this.cloudCenterCellLocation = GlStateManager._glGetUniformLocation(id, "iris_CloudCenterCell");
//?} else { //?} else {
/*for (VanillaUniformBlocks block : BLOCKS) { /*for (VanillaUniformBlocks block : BLOCKS) {
int index = IrisRenderSystem.getUniformBlockIndex(id, block.getBlockName()); int index = IrisRenderSystem.getUniformBlockIndex(id, block.getBlockName());
@@ -218,6 +226,13 @@ public final class GbufferProgram {
uploadFloat(glintAlphaLocation, state.glintAlpha); uploadFloat(glintAlphaLocation, state.glintAlpha);
uploadFloat(fogStartLocation, state.fogStart); uploadFloat(fogStartLocation, state.fogStart);
uploadFloat(fogEndLocation, state.fogEnd); uploadFloat(fogEndLocation, state.fogEnd);
uploadVector(cloudColorLocation, state.cloudColor);
uploadVector(cloudOffsetLocation, state.cloudOffset);
uploadVector(cloudCellSizeLocation, state.cloudCellSize);
if (cloudCenterCellLocation != -1) {
GL20C.glUniform2i(cloudCenterCellLocation, state.cloudCenterCellX, state.cloudCenterCellZ);
}
} }
private void uploadMatrix(int location, Matrix4f matrix) { private void uploadMatrix(int location, Matrix4f matrix) {
@@ -49,7 +49,7 @@ public class ShaderCreator {
GlFramebuffer writingToBeforeTranslucent, GlFramebuffer writingToAfterTranslucent, GlFramebuffer writingToBeforeTranslucent, GlFramebuffer writingToAfterTranslucent,
AlphaTest fallbackAlpha, VertexFormat vertexFormat, ShaderAttributeInputs inputs, AlphaTest fallbackAlpha, VertexFormat vertexFormat, ShaderAttributeInputs inputs,
Supplier<ImmutableSet<Integer>> flipped, boolean isIntensity, boolean isShadowPass, Supplier<ImmutableSet<Integer>> flipped, boolean isIntensity, boolean isShadowPass,
boolean isLines, boolean isClouds, CustomUniforms customUniforms) { boolean isLines, boolean generatesClouds, CustomUniforms customUniforms) {
AlphaTest alpha = source.getDirectives().getAlphaTestOverride().orElse(fallbackAlpha); AlphaTest alpha = source.getDirectives().getAlphaTestOverride().orElse(fallbackAlpha);
BlendModeOverride blendModeOverride = source.getDirectives().getBlendModeOverride().orElse(programId.getBlendModeOverride()); BlendModeOverride blendModeOverride = source.getDirectives().getBlendModeOverride().orElse(programId.getBlendModeOverride());
@@ -63,18 +63,16 @@ public class ShaderCreator {
CompletableFuture<Map<ShaderType, String>> transformed = CompletableFuture.supplyAsync(() -> { CompletableFuture<Map<ShaderType, String>> transformed = CompletableFuture.supplyAsync(() -> {
Preconditions.checkArgument(source.isValid()); Preconditions.checkArgument(source.isValid());
return TransformPatcherBridge.patchVanilla(name, source.getSourcesMap(), alpha, isLines, isClouds, true, inputs, parent.getTextureMap()); return TransformPatcherBridge.patchVanilla(name, source.getSourcesMap(), alpha, isLines, generatesClouds, true, inputs, parent.getTextureMap());
}, TransformPatcherBridge.EXECUTOR); }, TransformPatcherBridge.EXECUTOR);
//? if >=26.1 {
/*boolean generatesClouds = isClouds;
*///?} else
boolean generatesClouds = false;
ImmutableSet<Integer> reservedTextureUnits = generatesClouds ? IrisSamplers.CLOUDS_RESERVED_TEXTURE_UNITS : IrisSamplers.WORLD_RESERVED_TEXTURE_UNITS; ImmutableSet<Integer> reservedTextureUnits = generatesClouds ? IrisSamplers.CLOUDS_RESERVED_TEXTURE_UNITS : IrisSamplers.WORLD_RESERVED_TEXTURE_UNITS;
return new PendingGbufferProgram(name, attributeLocations(vertexFormat), reservedTextureUnits, transformed, (builder, sources) -> { return new PendingGbufferProgram(name, attributeLocations(vertexFormat), reservedTextureUnits, transformed, (builder, sources) -> {
if (generatesClouds) { if (generatesClouds) {
builder.addExternalSampler(IrisSamplers.CLOUD_FACES_TEXTURE_UNIT, CloudVertices.CLOUD_FACES_SAMPLER); builder.addExternalSampler(IrisSamplers.CLOUD_FACES_TEXTURE_UNIT, CloudVertices.CLOUD_FACES_SAMPLER);
//? if <26.1
builder.addExternalSampler(IrisSamplers.CLOUD_COLORS_TEXTURE_UNIT, CloudVertices.CLOUD_COLORS_SAMPLER);
} }
CommonUniforms.addDynamicUniforms(builder, FogMode.PER_VERTEX); CommonUniforms.addDynamicUniforms(builder, FogMode.PER_VERTEX);
@@ -28,6 +28,12 @@ public final class VanillaDrawState {
public float glintAlpha = 1.0F; public float glintAlpha = 1.0F;
public float fogStart; public float fogStart;
public float fogEnd = 1.0F; public float fogEnd = 1.0F;
// What clouds programs generate their vertices from, as the cloud info uniforms
public final Vector4f cloudColor = new Vector4f(1.0F);
public final Vector3f cloudOffset = new Vector3f();
public final Vector3f cloudCellSize = new Vector3f();
public int cloudCenterCellX;
public int cloudCenterCellZ;
//?} else { //?} else {
/*// The program vanilla set up the draw for, whose uniform block bindings hold vanilla's values. /*// The program vanilla set up the draw for, whose uniform block bindings hold vanilla's values.
public GlProgram vanillaProgram; public GlProgram vanillaProgram;
@@ -32,9 +32,15 @@ public class IrisSamplers {
public static final int LIGHTMAP_TEXTURE_UNIT = 2; public static final int LIGHTMAP_TEXTURE_UNIT = 2;
public static final ImmutableSet<Integer> WORLD_RESERVED_TEXTURE_UNITS = ImmutableSet.of(0, 1, 2); public static final ImmutableSet<Integer> WORLD_RESERVED_TEXTURE_UNITS = ImmutableSet.of(0, 1, 2);
// Holds the buffer of cloud faces 26.1 generates cloud vertices from, in clouds programs only. // Holds the buffer of cloud faces that clouds programs generate their vertices from.
public static final int CLOUD_FACES_TEXTURE_UNIT = 3; public static final int CLOUD_FACES_TEXTURE_UNIT = 3;
public static final ImmutableSet<Integer> CLOUDS_RESERVED_TEXTURE_UNITS = ImmutableSet.of(0, 1, 2, CLOUD_FACES_TEXTURE_UNIT); //? if >=26.1 {
/*public static final ImmutableSet<Integer> CLOUDS_RESERVED_TEXTURE_UNITS = ImmutableSet.of(0, 1, 2, CLOUD_FACES_TEXTURE_UNIT);
*///?} else {
// Celeritas's clouds also tint each cell by its pixel in the clouds texture
public static final int CLOUD_COLORS_TEXTURE_UNIT = 4;
public static final ImmutableSet<Integer> CLOUDS_RESERVED_TEXTURE_UNITS = ImmutableSet.of(0, 1, 2, CLOUD_FACES_TEXTURE_UNIT, CLOUD_COLORS_TEXTURE_UNIT);
//?}
/** /**
* Terrain programs that pull vertex data also reserve the unit Celeritas binds it to. * Terrain programs that pull vertex data also reserve the unit Celeritas binds it to.
@@ -1,52 +1,82 @@
package net.irisshaders.iris.compat.sodium.mixin.clouds; package net.irisshaders.iris.compat.sodium.mixin.clouds;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation; import com.mojang.blaze3d.systems.RenderSystem;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import com.mojang.blaze3d.vertex.VertexBuffer;
import org.embeddedt.embeddium.impl.render.immediate.CloudRenderer;
import net.irisshaders.iris.Iris; import net.irisshaders.iris.Iris;
import net.irisshaders.iris.pipeline.ShaderRenderingPipeline; import net.irisshaders.iris.pipeline.ShaderRenderingPipeline;
import net.irisshaders.iris.pipeline.WorldRenderingPipeline; import net.irisshaders.iris.pipeline.WorldRenderingPipeline;
import net.irisshaders.iris.pipeline.programs.GbufferProgram;
import net.irisshaders.iris.pipeline.programs.ShaderKey; import net.irisshaders.iris.pipeline.programs.ShaderKey;
import org.embeddedt.embeddium.impl.render.immediate.CloudShader; import net.irisshaders.iris.pipeline.programs.VanillaDrawState;
import org.joml.Matrix4f; import net.minecraft.client.Minecraft;
import org.embeddedt.embeddium.impl.gl.device.CommandList;
import org.embeddedt.embeddium.impl.render.clouds.CloudFrame;
import org.embeddedt.embeddium.impl.render.clouds.CloudRenderState;
import org.embeddedt.embeddium.impl.render.clouds.CloudRenderer;
import org.embeddedt.embeddium.impl.render.immediate.ModernCloudRenderer;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(CloudRenderer.class) @Mixin(ModernCloudRenderer.class)
public abstract class MixinCloudRenderer { public abstract class MixinCloudRenderer {
@Shadow private VertexBuffer vertexBuffer; @Shadow
@Final
private static CloudRenderState RENDER_STATE;
@Unique
private static final VanillaDrawState iris$drawState = new VanillaDrawState();
/** /**
* @author embeddedt * @author embeddedt
* @reason draw the clouds using the Iris shader if present * @reason draw the clouds with the shader pack's program, which generates the vertices from the same faces
*/ */
@WrapOperation(method = "render", at = @At(value = "INVOKE", target = "Lorg/embeddedt/embeddium/impl/render/immediate/CloudShader;prepareForDraw(Lorg/joml/Matrix4f;Lorg/joml/Matrix4f;FFFF)V")) @Inject(method = "draw", at = @At("HEAD"), cancellable = true)
private void drawWithIrisShader(CloudShader instance, Matrix4f modelViewMatrix, Matrix4f projectionMatrix, float r, float g, float b, float a, Operation<Void> original) { private void iris$drawWithShaderPack(CommandList commandList, CloudRenderer renderer, CloudFrame frame, CallbackInfo ci) {
WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable(); WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable();
if (pipeline instanceof ShaderRenderingPipeline) { if (!(pipeline instanceof ShaderRenderingPipeline shaderPipeline)) {
var irisShader = ((ShaderRenderingPipeline) pipeline).getShaderMap().getShader(ShaderKey.CLOUDS_SODIUM); return;
this.vertexBuffer.drawWithShader(modelViewMatrix, projectionMatrix, irisShader);
} else {
original.call(instance, modelViewMatrix, projectionMatrix, r, g, b, a);
}
} }
/** GbufferProgram program = shaderPipeline.getShaderMap().getProgram(ShaderKey.CLOUDS_SODIUM);
* @author embeddedt
* @reason suppress the vanilla cloud rendering if Iris shader is active // Without a clouds program from the pack, our own draws them
*/ if (program == null) {
@Inject(method = "drawVertexBuffer", at = @At("HEAD"), cancellable = true) return;
private void drawWithIrisShader(CallbackInfo ci) { }
WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable();
VanillaDrawState state = iris$drawState;
state.modelView.set(frame.modelView());
state.projection.set(frame.projection());
state.textureMatrix.identity();
state.chunkOffset.zero();
// The cloud color is applied through the cloud info, so the pack mustn't apply it again
state.colorModulator.set(1.0F);
float[] fogColor = RenderSystem.getShaderFogColor();
state.fogColor.set(fogColor[0], fogColor[1], fogColor[2], fogColor[3]);
state.fogStart = RenderSystem.getShaderFogStart();
state.fogEnd = RenderSystem.getShaderFogEnd();
state.albedoTexture = RenderSystem.getShaderTexture(0);
state.overlayTexture = RenderSystem.getShaderTexture(1);
state.lightmapTexture = RenderSystem.getShaderTexture(2);
state.cloudColor.set(frame.red(), frame.green(), frame.blue(), CloudRenderer.getAlpha());
state.cloudOffset.set(renderer.getOffsetX(), renderer.getOffsetY(), renderer.getOffsetZ());
state.cloudCellSize.set(renderer.getCellSizeX(), renderer.getCellHeight(), renderer.getCellSizeZ());
state.cloudCenterCellX = renderer.getCenterCellX();
state.cloudCenterCellZ = renderer.getCenterCellZ();
RENDER_STATE.setup(frame.fancy());
program.bind(state);
renderer.bindTextures();
renderer.draw(commandList);
program.unbind();
Minecraft.getInstance().getMainRenderTarget().bindWrite(false);
RENDER_STATE.restore();
if (pipeline instanceof ShaderRenderingPipeline) {
ci.cancel(); ci.cancel();
} }
}
} }
@@ -5,6 +5,7 @@ import net.minecraft.block.Block;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World; import net.minecraft.world.World;
import net.minecraft.world.chunk.WorldChunk; import net.minecraft.world.chunk.WorldChunk;
import org.embeddedt.embeddium.impl.gl.state.GlStateService;
import org.embeddedt.embeddium.impl.gl.device.CommandList; import org.embeddedt.embeddium.impl.gl.device.CommandList;
import org.embeddedt.embeddium.impl.gl.device.RenderDevice; import org.embeddedt.embeddium.impl.gl.device.RenderDevice;
import org.embeddedt.embeddium.impl.render.chunk.*; import org.embeddedt.embeddium.impl.render.chunk.*;
@@ -177,7 +178,7 @@ public class PrimitiveRenderSectionManager extends RenderSectionManager {
private static class ChunkRenderer extends DefaultChunkRenderer { private static class ChunkRenderer extends DefaultChunkRenderer {
public ChunkRenderer(RenderDevice device, RenderPassConfiguration<?> renderPassConfiguration) { public ChunkRenderer(RenderDevice device, RenderPassConfiguration<?> renderPassConfiguration) {
super(device, renderPassConfiguration, GLStateManagerFogService.INSTANCE); super(device, renderPassConfiguration, GLStateManagerFogService.INSTANCE, GlStateService.UNCACHED);
} }
@Override @Override