Vertex pulling #48

Manually merged
embeddedt merged 8 commits from vertex-pulling into stonecutter 2026-10-30 15:00:42 -04:00
28 changed files with 989 additions and 71 deletions
Showing only changes of commit 956a6c6442 - Show all commits

No files matched your search

@@ -13,10 +13,12 @@ import org.apache.logging.log4j.Logger;
import org.lwjgl.opengl.APPLEVertexArrayObject; import org.lwjgl.opengl.APPLEVertexArrayObject;
import org.lwjgl.opengl.ARBBufferStorage; import org.lwjgl.opengl.ARBBufferStorage;
import org.lwjgl.opengl.ARBInstancedArrays; import org.lwjgl.opengl.ARBInstancedArrays;
import org.lwjgl.opengl.ARBTextureBufferObject;
import org.lwjgl.opengl.ARBTimerQuery; import org.lwjgl.opengl.ARBTimerQuery;
import org.lwjgl.opengl.ARBVertexArrayObject; import org.lwjgl.opengl.ARBVertexArrayObject;
import org.lwjgl.opengl.ContextCapabilities; import org.lwjgl.opengl.ContextCapabilities;
import org.lwjgl.opengl.EXTGpuShader4; import org.lwjgl.opengl.EXTGpuShader4;
import org.lwjgl.opengl.EXTTextureBufferObject;
import org.lwjgl.opengl.EXTTimerQuery; import org.lwjgl.opengl.EXTTimerQuery;
import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13; import org.lwjgl.opengl.GL13;
@@ -255,6 +257,9 @@ public record LWJGL2Service(
case ARB_texture_storage -> caps.GL_ARB_texture_storage; case ARB_texture_storage -> caps.GL_ARB_texture_storage;
case ARB_base_instance -> caps.GL_ARB_base_instance; case ARB_base_instance -> caps.GL_ARB_base_instance;
case ARB_compatibility -> caps.GL_ARB_compatibility; case ARB_compatibility -> caps.GL_ARB_compatibility;
case ARB_texture_buffer_object -> caps.GL_ARB_texture_buffer_object;
case EXT_texture_buffer_object -> caps.GL_EXT_texture_buffer_object;
case EXT_gpu_shader4 -> caps.GL_EXT_gpu_shader4;
}; };
} }
@@ -753,6 +758,21 @@ public record LWJGL2Service(
GL11.glTexParameteri(target, pname, param); GL11.glTexParameteri(target, pname, param);
} }
@Override
public void glTexBuffer(int target, int internalFormat, int buffer) {
GL31.glTexBuffer(target, internalFormat, buffer);
}
@Override
public void glTexBufferARB(int target, int internalFormat, int buffer) {
ARBTextureBufferObject.glTexBufferARB(target, internalFormat, buffer);
}
@Override
public void glTexBufferEXT(int target, int internalFormat, int buffer) {
EXTTextureBufferObject.glTexBufferEXT(target, internalFormat, buffer);
}
// ===================== FRAMEBUFFER OPERATIONS ===================== // ===================== FRAMEBUFFER OPERATIONS =====================
@Override @Override
@@ -79,6 +79,9 @@ public record LWJGL3Service(
case ARB_texture_storage -> caps.GL_ARB_texture_storage; case ARB_texture_storage -> caps.GL_ARB_texture_storage;
case ARB_base_instance -> caps.GL_ARB_base_instance; case ARB_base_instance -> caps.GL_ARB_base_instance;
case ARB_compatibility -> caps.GL_ARB_compatibility; case ARB_compatibility -> caps.GL_ARB_compatibility;
case ARB_texture_buffer_object -> caps.GL_ARB_texture_buffer_object;
case EXT_texture_buffer_object -> caps.GL_EXT_texture_buffer_object;
case EXT_gpu_shader4 -> caps.GL_EXT_gpu_shader4;
}; };
} }
@@ -650,6 +653,21 @@ public record LWJGL3Service(
GL11C.glTexParameteri(target, pname, param); GL11C.glTexParameteri(target, pname, param);
} }
@Override
public void glTexBuffer(int target, int internalFormat, int buffer) {
GL31C.glTexBuffer(target, internalFormat, buffer);
}
@Override
public void glTexBufferARB(int target, int internalFormat, int buffer) {
ARBTextureBufferObject.glTexBufferARB(target, internalFormat, buffer);
}
@Override
public void glTexBufferEXT(int target, int internalFormat, int buffer) {
EXTTextureBufferObject.glTexBufferEXT(target, internalFormat, buffer);
}
// ===================== FRAMEBUFFER OPERATIONS ===================== // ===================== FRAMEBUFFER OPERATIONS =====================
@Override @Override
@@ -20,5 +20,8 @@ public enum GLExtension {
ARB_copy_buffer, ARB_copy_buffer,
ARB_texture_storage, ARB_texture_storage,
ARB_base_instance, ARB_base_instance,
ARB_compatibility ARB_compatibility,
ARB_texture_buffer_object,
EXT_texture_buffer_object,
EXT_gpu_shader4
} }
@@ -138,6 +138,9 @@ public interface LWJGLService {
void glPixelStorei(int pname, int param); void glPixelStorei(int pname, int param);
void glTexImage2D(int target, int level, int internalFormat, int width, int height, int border, int format, int type, ByteBuffer pixels); void glTexImage2D(int target, int level, int internalFormat, int width, int height, int border, int format, int type, ByteBuffer pixels);
void glTexParameteri(int target, int pname, int param); void glTexParameteri(int target, int pname, int param);
void glTexBuffer(int target, int internalFormat, int buffer);
void glTexBufferARB(int target, int internalFormat, int buffer);
void glTexBufferEXT(int target, int internalFormat, int buffer);
// ===================== FRAMEBUFFER OPERATIONS ===================== // ===================== FRAMEBUFFER OPERATIONS =====================
@@ -2,12 +2,24 @@ package org.embeddedt.embeddium.impl.gl.functions;
import org.embeddedt.embeddium.impl.gl.device.RenderDevice; import org.embeddedt.embeddium.impl.gl.device.RenderDevice;
/**
* @param maxTextureBufferTexels the number of texels a texture buffer may address, or 0 if texture buffers are unsupported
*/
public record DeviceFunctions(BufferCopyFunctions bufferCopyFunctions, public record DeviceFunctions(BufferCopyFunctions bufferCopyFunctions,
BufferMapRangeFunctions bufferMapRangeFunctions) { BufferMapRangeFunctions bufferMapRangeFunctions,
TextureBufferFunctions textureBufferFunctions,
int maxTextureBufferTexels) {
public DeviceFunctions(RenderDevice device) { public DeviceFunctions(RenderDevice device) {
this( this(
BufferCopyFunctions.pickBest(device), BufferCopyFunctions.pickBest(device),
BufferMapRangeFunctions.pickBest(device) BufferMapRangeFunctions.pickBest(device),
TextureBufferFunctions.pickBest(device)
); );
} }
private DeviceFunctions(BufferCopyFunctions bufferCopyFunctions,
BufferMapRangeFunctions bufferMapRangeFunctions,
TextureBufferFunctions textureBufferFunctions) {
this(bufferCopyFunctions, bufferMapRangeFunctions, textureBufferFunctions, textureBufferFunctions.queryMaxTexels());
}
} }
@@ -0,0 +1,65 @@
package org.embeddedt.embeddium.impl.gl.functions;
import org.embeddedt.embeddium.impl.gl.buffer.GlBuffer;
import org.embeddedt.embeddium.impl.gl.device.RenderDevice;
import org.taumc.celeritas.lwjgl.GL31;
import org.taumc.celeritas.lwjgl.GLExtension;
import static org.taumc.celeritas.lwjgl.LWJGLServiceProvider.LWJGL;
public enum TextureBufferFunctions {
CORE {
@Override
public void texBuffer(int target, int internalFormat, GlBuffer buffer) {
LWJGL.glTexBuffer(target, internalFormat, buffer.handle());
}
},
ARB {
@Override
public void texBuffer(int target, int internalFormat, GlBuffer buffer) {
LWJGL.glTexBufferARB(target, internalFormat, buffer.handle());
}
},
EXT {
@Override
public void texBuffer(int target, int internalFormat, GlBuffer buffer) {
LWJGL.glTexBufferEXT(target, internalFormat, buffer.handle());
}
},
NONE {
@Override
public void texBuffer(int target, int internalFormat, GlBuffer buffer) {
throw new UnsupportedOperationException("Texture buffers are not supported");
}
};
public abstract void texBuffer(int target, int internalFormat, GlBuffer buffer);
public boolean isSupported() {
return this != NONE;
}
/**
* {@return the number of texels a texture buffer may address, or 0 if texture buffers are unsupported}
*/
int queryMaxTexels() {
return this.isSupported() ? LWJGL.glGetInteger(GL31.GL_MAX_TEXTURE_BUFFER_SIZE) : 0;
}
public static TextureBufferFunctions pickBest(RenderDevice device) {
// Below GL 3.2 the terrain shaders are GLSL 1.20, which can only sample texture buffers through EXT_gpu_shader4
if (!LWJGL.isOpenGLVersionSupported(3, 2) && !LWJGL.isExtensionSupported(GLExtension.EXT_gpu_shader4)) {
return NONE;
}
if (LWJGL.isOpenGLVersionSupported(3, 1)) {
return CORE;
} else if (LWJGL.isExtensionSupported(GLExtension.ARB_texture_buffer_object)) {
return ARB;
} else if (LWJGL.isExtensionSupported(GLExtension.EXT_texture_buffer_object)) {
return EXT;
} else {
return NONE;
}
}
}
@@ -0,0 +1,39 @@
package org.embeddedt.embeddium.impl.gl.texture;
import org.embeddedt.embeddium.impl.gl.GlObject;
import org.embeddedt.embeddium.impl.gl.buffer.GlBuffer;
import org.embeddedt.embeddium.impl.gl.functions.TextureBufferFunctions;
import org.taumc.celeritas.lwjgl.GL30;
import org.taumc.celeritas.lwjgl.GL31;
import static org.taumc.celeritas.lwjgl.LWJGLServiceProvider.LWJGL;
/**
* A texture buffer exposing a buffer object to shaders as an array of 32-bit unsigned integers.
*/
public class GlBufferTexture extends GlObject {
private GlBuffer attachedBuffer;
public GlBufferTexture() {
this.setHandle(LWJGL.glGenTextures());
}
/**
* Binds this texture to the active texture unit, attaching the given buffer if it is not already attached. Buffers
* 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) {
LWJGL.glBindTexture(GL31.GL_TEXTURE_BUFFER, this.handle());
if (this.attachedBuffer != buffer) {
functions.texBuffer(GL31.GL_TEXTURE_BUFFER, GL30.GL_R32UI, buffer);
this.attachedBuffer = buffer;
}
}
@Override
protected void destroyInternal() {
LWJGL.glDeleteTextures(this.handle());
this.attachedBuffer = null;
}
}
@@ -3,6 +3,7 @@ package org.embeddedt.embeddium.impl.render.chunk;
import it.unimi.dsi.fastutil.objects.Reference2ReferenceMap; import it.unimi.dsi.fastutil.objects.Reference2ReferenceMap;
import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap; import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap;
import org.embeddedt.embeddium.impl.gl.array.GlVertexArray; import org.embeddedt.embeddium.impl.gl.array.GlVertexArray;
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexAttributeFormat;
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexFormat; 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;
@@ -16,9 +17,15 @@ import org.embeddedt.embeddium.impl.render.chunk.lists.ChunkRenderList;
import org.embeddedt.embeddium.impl.render.chunk.multidraw.BatchAssembler; import org.embeddedt.embeddium.impl.render.chunk.multidraw.BatchAssembler;
import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion; import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion;
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.terrain.TerrainRenderPass; 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.viewport.CameraTransform; import org.embeddedt.embeddium.impl.render.viewport.CameraTransform;
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 {
@@ -26,6 +33,20 @@ public abstract class DefaultChunkRenderer extends ShaderChunkRenderer {
private final BatchAssembler.TessellationProvider tessellationProvider = this::prepareTessellation; private final BatchAssembler.TessellationProvider tessellationProvider = this::prepareTessellation;
/**
* The texture unit that pulled passes read vertex data from. Loaders bind their own textures to low units, so this
* stays clear of them.
*/
private static final int VERTEX_DATA_TEXTURE_UNIT = 15;
/**
* 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.
*/
private static final GlVertexFormat PLACEHOLDER_ATTRIBUTE_FORMAT = GlVertexFormat.builder(4)
.addElement("celeritas_Placeholder", 0, GlVertexAttributeFormat.UNSIGNED_BYTE, 4, true, false)
.build();
private TerrainRenderPass currentRenderPass; private TerrainRenderPass currentRenderPass;
private GlVertexFormat currentVertexFormat; private GlVertexFormat currentVertexFormat;
@@ -78,10 +99,22 @@ public abstract class DefaultChunkRenderer extends ShaderChunkRenderer {
Iterator<ChunkRenderList> iterator = renderLists.iterator(renderPass.isReverseOrder()); Iterator<ChunkRenderList> iterator = renderLists.iterator(renderPass.isReverseOrder());
this.currentRenderPass = renderPass; this.currentRenderPass = renderPass;
this.currentVertexFormat = ChunkVertexLayout.requireAttributes(this.renderPassConfiguration.getVertexTypeForPass(this.currentRenderPass).getLayout());
boolean pulled = renderPass.vertexFetchMode() == VertexFetchMode.PULLED;
if (pulled) {
this.currentVertexFormat = PLACEHOLDER_ATTRIBUTE_FORMAT;
LWJGL.glActiveTexture(GL13.GL_TEXTURE0 + VERTEX_DATA_TEXTURE_UNIT);
} else {
this.currentVertexFormat = ChunkVertexLayout.requireAttributes(renderPass.vertexType().getLayout());
}
this.configureShaderInterface(shader); this.configureShaderInterface(shader);
if (pulled) {
shader.setTextureSlot(ChunkShaderTextureSlot.VERTEX_DATA, VERTEX_DATA_TEXTURE_UNIT);
}
long timestamp = System.nanoTime(); long timestamp = System.nanoTime();
useBlockFaceCulling = useBlockFaceCulling && !renderPass.isSorted(); useBlockFaceCulling = useBlockFaceCulling && !renderPass.isSorted();
@@ -118,12 +151,22 @@ public abstract class DefaultChunkRenderer extends ShaderChunkRenderer {
.ensureCapacity(commandList, batch.getIndexBufferSize()); .ensureCapacity(commandList, batch.getIndexBufferSize());
} }
if (pulled) {
region.getResources().bindVertexDataTexture(this.device.getDeviceFunctions());
}
setModelMatrixUniforms(shader, region, camera); setModelMatrixUniforms(shader, region, camera);
shader.setSectionAges(timestamp, region.getSectionLoadTimes()); shader.setSectionAges(timestamp, region.getSectionLoadTimes());
batch.execute(commandList, cached.getTessellation(), primitiveType); batch.execute(commandList, cached.getTessellation(), primitiveType);
} }
} }
if (pulled) {
// The game caches the active unit, so it has to be put back.
// TODO: don't assume unit 0 was active before the pass
LWJGL.glActiveTexture(GL13.GL_TEXTURE0);
}
this.currentVertexFormat = null; this.currentVertexFormat = null;
this.currentRenderPass = null; this.currentRenderPass = null;
@@ -12,6 +12,8 @@ import org.embeddedt.embeddium.impl.render.chunk.shader.*;
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexType; import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexType;
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.VertexFetchGenerator;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.VertexFetchMode;
import org.embeddedt.embeddium.impl.render.shader.ShaderLoader; import org.embeddedt.embeddium.impl.render.shader.ShaderLoader;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -62,22 +64,27 @@ public abstract class ShaderChunkRenderer implements ChunkRenderer {
protected GlProgram<ChunkShaderInterface> createShader(String path, ChunkShaderOptions options) { protected GlProgram<ChunkShaderInterface> createShader(String path, ChunkShaderOptions options) {
ShaderConstants constants = options.constants(); ShaderConstants constants = options.constants();
var pass = options.pass();
var generatedSources = VertexFetchGenerator.sources(pass.vertexType().getLayout(),
pass.primitiveType().getVerticesPerPrimitive(), pass.vertexFetchMode(), this.enableLegacyGLPatches);
List<GlShader> loadedShaders = new ArrayList<>(); List<GlShader> loadedShaders = new ArrayList<>();
loadedShaders.add(ShaderLoader.loadShader(ShaderType.VERTEX, loadedShaders.add(ShaderLoader.loadShader(ShaderType.VERTEX,
"sodium:" + path + ".vsh", constants)); "sodium:" + path + ".vsh", constants, generatedSources));
loadedShaders.add(ShaderLoader.loadShader(ShaderType.FRAGMENT, loadedShaders.add(ShaderLoader.loadShader(ShaderType.FRAGMENT,
"sodium:" + path + ".fsh", constants)); "sodium:" + path + ".fsh", constants, generatedSources));
try { try {
var builder = GlProgram.builder("sodium:chunk_shader"); var builder = GlProgram.builder("sodium:chunk_shader");
loadedShaders.forEach(builder::attachShader); loadedShaders.forEach(builder::attachShader);
if (pass.vertexFetchMode() == VertexFetchMode.ATTRIBUTES) {
int i = 0; int i = 0;
for (var attr : ChunkVertexLayout.requireAttributes(options.pass().vertexType().getLayout()).getAttributes()) { for (var attr : ChunkVertexLayout.requireAttributes(pass.vertexType().getLayout()).getAttributes()) {
builder.bindAttribute(attr.getName(), i++); builder.bindAttribute(attr.getName(), i++);
} }
}
if (!this.enableLegacyGLPatches) { if (!this.enableLegacyGLPatches) {
builder.bindFragmentData("fragColor", ChunkShaderBindingPoints.FRAG_COLOR); builder.bindFragmentData("fragColor", ChunkShaderBindingPoints.FRAG_COLOR);
} }
@@ -7,7 +7,9 @@ import org.embeddedt.embeddium.impl.gl.arena.GlBufferArena;
import org.embeddedt.embeddium.impl.gl.arena.staging.StagingBuffer; import org.embeddedt.embeddium.impl.gl.arena.staging.StagingBuffer;
import org.embeddedt.embeddium.impl.gl.buffer.GlBuffer; import org.embeddedt.embeddium.impl.gl.buffer.GlBuffer;
import org.embeddedt.embeddium.impl.gl.device.CommandList; import org.embeddedt.embeddium.impl.gl.device.CommandList;
import org.embeddedt.embeddium.impl.gl.functions.DeviceFunctions;
import org.embeddedt.embeddium.impl.gl.tessellation.GlTessellation; import org.embeddedt.embeddium.impl.gl.tessellation.GlTessellation;
import org.embeddedt.embeddium.impl.gl.texture.GlBufferTexture;
import org.embeddedt.embeddium.impl.render.chunk.RenderPassConfiguration; import org.embeddedt.embeddium.impl.render.chunk.RenderPassConfiguration;
import org.embeddedt.embeddium.impl.render.chunk.RenderSection; import org.embeddedt.embeddium.impl.render.chunk.RenderSection;
import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataStorage; import org.embeddedt.embeddium.impl.render.chunk.data.SectionRenderDataStorage;
@@ -309,6 +311,7 @@ public class RenderRegion {
private final GlBufferArena geometryArena; private final GlBufferArena geometryArena;
private final StagingBuffer stagingBuffer; private final StagingBuffer stagingBuffer;
private GlBufferArena indexArena; private GlBufferArena indexArena;
private GlBufferTexture vertexDataTexture;
private final Map<TerrainRenderPass.TessellationKey, GlTessellation> tessellations = new Object2ReferenceOpenHashMap<>(); private final Map<TerrainRenderPass.TessellationKey, GlTessellation> tessellations = new Object2ReferenceOpenHashMap<>();
public DeviceResources(CommandList commandList, StagingBuffer stagingBuffer, int commonVertexStride) { public DeviceResources(CommandList commandList, StagingBuffer stagingBuffer, int commonVertexStride) {
@@ -340,6 +343,24 @@ public class RenderRegion {
return this.geometryArena.getBufferObject(); return this.geometryArena.getBufferObject();
} }
/**
* Binds a texture buffer over the geometry arena to the active texture unit, for passes that pull vertex data.
*/
public void bindVertexDataTexture(DeviceFunctions functions) {
long texels = this.geometryArena.getDeviceAllocatedMemoryL() / 4;
if (texels > functions.maxTextureBufferTexels()) {
throw new IllegalStateException("Geometry arena of " + texels + " texels exceeds the device's texture buffer limit of "
+ functions.maxTextureBufferTexels());
}
if (this.vertexDataTexture == null) {
this.vertexDataTexture = new GlBufferTexture();
}
this.vertexDataTexture.bind(functions.textureBufferFunctions(), this.geometryArena.getBufferObject());
}
public GlBuffer getIndexBuffer() { public GlBuffer getIndexBuffer() {
if (this.indexArena == null) { if (this.indexArena == null) {
throw new IllegalStateException("Attempted to retrieve index buffer for a non-indexed region"); throw new IllegalStateException("Attempted to retrieve index buffer for a non-indexed region");
@@ -349,6 +370,10 @@ public class RenderRegion {
public void delete(CommandList commandList) { public void delete(CommandList commandList) {
this.deleteTessellations(commandList); this.deleteTessellations(commandList);
if (this.vertexDataTexture != null) {
this.vertexDataTexture.delete();
this.vertexDataTexture = null;
}
this.geometryArena.delete(commandList); this.geometryArena.delete(commandList);
if (this.indexArena != null) { if (this.indexArena != null) {
this.indexArena.delete(commandList); this.indexArena.delete(commandList);
@@ -2,6 +2,7 @@ package org.embeddedt.embeddium.impl.render.chunk.shader;
import org.embeddedt.embeddium.impl.gl.shader.ShaderConstants; import org.embeddedt.embeddium.impl.gl.shader.ShaderConstants;
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.VertexFetchMode;
import java.util.List; import java.util.List;
@@ -21,6 +22,10 @@ public record ChunkShaderOptions(List<ChunkShaderComponent.Factory<?>> component
constants.add("CELERITAS_NO_LIGHTMAP"); constants.add("CELERITAS_NO_LIGHTMAP");
} }
if (this.pass.vertexFetchMode() == VertexFetchMode.PULLED) {
constants.add("USE_VERTEX_PULLING");
}
constants.addAll(pass.extraDefines()); constants.addAll(pass.extraDefines());
var vertexType = pass.vertexType(); var vertexType = pass.vertexType();
@@ -2,7 +2,8 @@ package org.embeddedt.embeddium.impl.render.chunk.shader;
public enum ChunkShaderTextureSlot { public enum ChunkShaderTextureSlot {
BLOCK, BLOCK,
LIGHT; LIGHT,
VERTEX_DATA;
public static final ChunkShaderTextureSlot[] VALUES = ChunkShaderTextureSlot.values(); public static final ChunkShaderTextureSlot[] VALUES = ChunkShaderTextureSlot.values();
} }
@@ -8,6 +8,7 @@ import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformMatrix4f;
import org.embeddedt.embeddium.impl.gl.tessellation.GlPrimitiveType; import org.embeddedt.embeddium.impl.gl.tessellation.GlPrimitiveType;
import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.QuadPrimitiveType; import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.QuadPrimitiveType;
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.VertexFetchMode;
import org.joml.Matrix4fc; import org.joml.Matrix4fc;
import org.taumc.celeritas.lwjgl.MemoryStack; import org.taumc.celeritas.lwjgl.MemoryStack;
import static org.taumc.celeritas.lwjgl.LWJGLServiceProvider.LWJGL; import static org.taumc.celeritas.lwjgl.LWJGLServiceProvider.LWJGL;
@@ -47,6 +48,9 @@ public class DefaultChunkShaderInterface implements ChunkShaderInterface {
if (!options.pass().hasNoLightmap()) { if (!options.pass().hasNoLightmap()) {
this.uniformTextures.put(ChunkShaderTextureSlot.LIGHT, context.bindUniform("u_LightTex", GlUniformInt::new)); this.uniformTextures.put(ChunkShaderTextureSlot.LIGHT, context.bindUniform("u_LightTex", GlUniformInt::new));
} }
if (options.pass().vertexFetchMode() == VertexFetchMode.PULLED) {
this.uniformTextures.put(ChunkShaderTextureSlot.VERTEX_DATA, context.bindUniform("u_VertexData", GlUniformInt::new));
}
this.components = options.components().stream().map(c -> c.create(context, environment)).toList(); this.components = options.components().stream().map(c -> c.create(context, environment)).toList();
} }
@@ -9,6 +9,7 @@ import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.ChunkPrimitiveT
import org.embeddedt.embeddium.impl.render.chunk.terrain.material.Material; import org.embeddedt.embeddium.impl.render.chunk.terrain.material.Material;
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.ChunkVertexType; import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexType;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.VertexFetchMode;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.Map; import java.util.Map;
@@ -56,8 +57,9 @@ public class TerrainRenderPass {
private final @NotNull ChunkPrimitiveType primitiveType; private final @NotNull ChunkPrimitiveType primitiveType;
private final @NotNull ChunkVertexType vertexType; private final @NotNull ChunkVertexType vertexType;
private final @NotNull VertexFetchMode vertexFetchMode;
public record TessellationKey(ChunkVertexLayout vertexLayout, ChunkPrimitiveType primitiveType, boolean sorted) {} public record TessellationKey(ChunkVertexLayout vertexLayout, VertexFetchMode vertexFetchMode, ChunkPrimitiveType primitiveType, boolean sorted) {}
@Getter @Getter
@EqualsAndHashCode.Exclude @EqualsAndHashCode.Exclude
@@ -89,7 +91,8 @@ public class TerrainRenderPass {
this.hasNoLightmap = hasNoLightmap; this.hasNoLightmap = hasNoLightmap;
this.primitiveType = primitiveType; this.primitiveType = primitiveType;
this.vertexType = vertexType; this.vertexType = vertexType;
this.tessellationKey = new TessellationKey(vertexType.getLayout(), primitiveType, useTranslucencySorting); this.vertexFetchMode = VertexFetchMode.select(vertexType.getLayout());
this.tessellationKey = new TessellationKey(vertexType.getLayout(), this.vertexFetchMode, primitiveType, useTranslucencySorting);
this.extraDefines = Map.copyOf(extraDefines); this.extraDefines = Map.copyOf(extraDefines);
} }
@@ -125,6 +128,10 @@ public class TerrainRenderPass {
return this.vertexType; return this.vertexType;
} }
public VertexFetchMode vertexFetchMode() {
return this.vertexFetchMode;
}
public Map<String, String> extraDefines() { public Map<String, String> extraDefines() {
return this.extraDefines; return this.extraDefines;
} }
@@ -1,58 +1,99 @@
package org.embeddedt.embeddium.impl.render.chunk.vertex.format; package org.embeddedt.embeddium.impl.render.chunk.vertex.format;
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexAttribute;
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexFormat; import org.embeddedt.embeddium.impl.gl.attribute.GlVertexFormat;
import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.ChunkPrimitiveType; import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.ChunkPrimitiveType;
import org.jetbrains.annotations.Nullable;
import java.util.Objects;
/** /**
* Describes how the shader fetches a vertex type's data, and how much space one primitive takes in the geometry buffer. * Describes how a vertex type's data is laid out in the geometry buffer. Each primitive is stored as one record: an
* optional header holding per-primitive elements, followed by its vertices.
* <p>
* Only layouts without a header can be fetched through vertex attributes. Any layout can be pulled by the vertex
* shader, see {@link VertexFetchGenerator}.
*/ */
public sealed interface ChunkVertexLayout permits ChunkVertexLayout.Attributes, ChunkVertexLayout.Pulled { public record ChunkVertexLayout(GlVertexFormat vertex, @Nullable Header header) {
/**
* @param verticesPerRecord the number of vertices that follow each header
*/
public record Header(GlVertexFormat format, int verticesPerRecord) {
public Header {
Objects.requireNonNull(format);
if (verticesPerRecord <= 0) {
throw new IllegalArgumentException("Records must contain at least one vertex");
}
}
}
public ChunkVertexLayout {
Objects.requireNonNull(vertex);
validateWordAligned(vertex);
if (header != null) {
validateWordAligned(header.format());
}
}
public static ChunkVertexLayout of(GlVertexFormat vertex) {
return new ChunkVertexLayout(vertex, null);
}
public static ChunkVertexLayout withHeader(GlVertexFormat vertex, GlVertexFormat header, int verticesPerRecord) {
return new ChunkVertexLayout(vertex, new Header(header, verticesPerRecord));
}
/**
* Pulled records are fetched as 32-bit words, so no component may straddle a word boundary.
*/
private static void validateWordAligned(GlVertexFormat format) {
if (format.getStride() % 4 != 0) {
throw new IllegalArgumentException("Stride of " + format + " is not a multiple of 4 bytes");
}
for (GlVertexAttribute attribute : format.getAttributes()) {
int componentSize = attribute.getFormat().size();
if (attribute.getPointer() % componentSize != 0) {
throw new IllegalArgumentException("Attribute " + attribute.getName() + " at offset " + attribute.getPointer()
+ " is not aligned to its " + componentSize + "-byte components");
}
}
}
/** /**
* {@return the number of bytes one primitive of the given type occupies in the geometry buffer} * {@return the number of bytes one primitive of the given type occupies in the geometry buffer}
*/ */
int bytesPerPrimitive(ChunkPrimitiveType primitiveType); public int bytesPerPrimitive(ChunkPrimitiveType primitiveType) {
int vertices = primitiveType.getVerticesPerPrimitive();
if (this.header == null) {
return this.vertex.getStride() * vertices;
}
if (vertices != this.header.verticesPerRecord()) {
throw new IllegalArgumentException("Layout holds " + this.header.verticesPerRecord() + " vertices per record, but "
+ primitiveType + " has " + vertices);
}
return this.header.format().getStride() + this.vertex.getStride() * vertices;
}
public boolean supportsAttributeFetch() {
return this.header == null;
}
/** /**
* {@return the attribute format of the given layout} * {@return the attribute format of the given layout}
* @throws UnsupportedOperationException if the layout is not fetched through vertex attributes * @throws UnsupportedOperationException if the layout cannot be fetched through vertex attributes
*/ */
static GlVertexFormat requireAttributes(ChunkVertexLayout layout) { public static GlVertexFormat requireAttributes(ChunkVertexLayout layout) {
if (layout instanceof Attributes attributes) { if (layout.supportsAttributeFetch()) {
return attributes.format(); return layout.vertex();
} }
throw new UnsupportedOperationException("Vertex pulling is not supported: " + layout); throw new UnsupportedOperationException("Layout must be pulled by the vertex shader: " + layout);
}
/**
* Vertices fetched through vertex attributes.
*/
record Attributes(GlVertexFormat format) implements ChunkVertexLayout {
@Override
public int bytesPerPrimitive(ChunkPrimitiveType primitiveType) {
return this.format.getStride() * primitiveType.getVerticesPerPrimitive();
}
}
/**
* One record per primitive, read by the vertex shader from a texture buffer using {@code gl_VertexID}. The layout
* within the record is defined by the vertex type's GLSL decoder.
*/
record Pulled(int verticesPerRecord, int bytesPerRecord) implements ChunkVertexLayout {
public Pulled {
if (bytesPerRecord % 4 != 0) {
throw new IllegalArgumentException("Records are fetched as 32-bit words, but are " + bytesPerRecord + " bytes");
}
}
@Override
public int bytesPerPrimitive(ChunkPrimitiveType primitiveType) {
if (primitiveType.getVerticesPerPrimitive() != this.verticesPerRecord) {
throw new IllegalArgumentException("Layout holds " + this.verticesPerRecord + " vertices per record, but "
+ primitiveType + " has " + primitiveType.getVerticesPerPrimitive());
}
return this.bytesPerRecord;
}
} }
} }
@@ -0,0 +1,293 @@
package org.embeddedt.embeddium.impl.render.chunk.vertex.format;
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexAttribute;
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexAttributeFormat;
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
/**
* Generates the GLSL that supplies a vertex type's inputs to {@code chunk_vertex.glsl}.
* <p>
* With attribute fetch, the inputs are declared as {@code in} variables. When pulled, they are declared as globals of the
* same names and types, and {@code _vert_fetch()} fills them from the {@code u_VertexData} texture buffer, converting each
* component the way attribute fetch would for the same {@link GlVertexAttribute}.
*/
public final class VertexFetchGenerator {
public static final String IMPORT_NAME = "sodium:generated/vertex_fetch.glsl";
/**
* The inputs read by {@code chunk_vertex.glsl}, which must change in step with it. Other attributes are left for
* external shaders to declare themselves.
*/
public static final Set<String> CHUNK_VERTEX_INPUTS = Set.of("a_PosId", "a_Color", "a_TexCoord", "a_LightCoord", "a_RdhFactor");
public enum Scope {
HEADER,
VERTEX
}
public enum Conversion {
UINT,
SINT,
FLOAT_BITS,
UNORM,
SNORM,
UINT_TO_FLOAT,
SINT_TO_FLOAT
}
/**
* One component of an element, held in bits {@code [shift, shift + bits)} of a 32-bit word. The word index is
* relative to the start of the header or vertex the component belongs to.
*/
public record Component(Scope scope, int word, int shift, int bits, Conversion conversion) {}
public record Element(String name, String glslType, List<Component> components) {}
private VertexFetchGenerator() {}
public static Map<String, String> sources(ChunkVertexLayout layout, int verticesPerPrimitive, VertexFetchMode mode, boolean legacyGlsl) {
return Map.of(IMPORT_NAME, generate(layout, verticesPerPrimitive, mode, legacyGlsl));
}
public static List<Element> plan(ChunkVertexLayout layout) {
var elements = new ArrayList<Element>();
if (layout.header() != null) {
addElements(elements, layout.header().format(), Scope.HEADER);
}
addElements(elements, layout.vertex(), Scope.VERTEX);
return elements;
}
private static void addElements(List<Element> elements, GlVertexFormat format, Scope scope) {
for (GlVertexAttribute attribute : format.getAttributes()) {
if (!CHUNK_VERTEX_INPUTS.contains(attribute.getName())) {
continue;
}
Conversion conversion = conversionOf(attribute);
int componentSize = attribute.getFormat().size();
var components = new ArrayList<Component>(attribute.getCount());
for (int i = 0; i < attribute.getCount(); i++) {
int offset = attribute.getPointer() + (i * componentSize);
components.add(new Component(scope, offset / 4, (offset % 4) * 8, componentSize * 8, conversion));
}
elements.add(new Element(attribute.getName(), glslType(conversion, attribute.getCount()), components));
}
}
private static Conversion conversionOf(GlVertexAttribute attribute) {
GlVertexAttributeFormat format = attribute.getFormat();
if (format.equals(GlVertexAttributeFormat.FLOAT)) {
if (attribute.isIntType()) {
throw new IllegalArgumentException("Float attribute " + attribute.getName() + " cannot be an integer type");
}
return Conversion.FLOAT_BITS;
}
boolean signed = format.equals(GlVertexAttributeFormat.BYTE) || format.equals(GlVertexAttributeFormat.SHORT);
if (attribute.isIntType()) {
return signed ? Conversion.SINT : Conversion.UINT;
} else if (attribute.isNormalized()) {
return signed ? Conversion.SNORM : Conversion.UNORM;
} else {
return signed ? Conversion.SINT_TO_FLOAT : Conversion.UINT_TO_FLOAT;
}
}
private static String glslType(Conversion conversion, int count) {
String scalar = switch (conversion) {
case UINT -> "uint";
case SINT -> "int";
default -> "float";
};
if (count == 1) {
return scalar;
}
String prefix = switch (conversion) {
case UINT -> "u";
case SINT -> "i";
default -> "";
};
return prefix + "vec" + count;
}
public static String generate(ChunkVertexLayout layout, int verticesPerPrimitive, VertexFetchMode mode, boolean legacyGlsl) {
if (mode == VertexFetchMode.ATTRIBUTES && !layout.supportsAttributeFetch()) {
throw new IllegalArgumentException("Layout cannot be fetched through vertex attributes: " + layout);
}
int verticesPerRecord = layout.header() != null ? layout.header().verticesPerRecord() : verticesPerPrimitive;
List<Element> elements = plan(layout);
var out = new StringBuilder();
for (Element element : elements) {
out.append("#define VERT_HAS_").append(element.name()).append('\n');
}
out.append('\n');
String storage = mode == VertexFetchMode.ATTRIBUTES ? "in " : "";
for (Element element : elements) {
out.append(storage).append(element.glslType()).append(' ').append(element.name()).append(";\n");
}
out.append("\nint _vert_corner;\n\n");
if (mode == VertexFetchMode.ATTRIBUTES) {
out.append("void _vert_fetch() {\n");
out.append(" _vert_corner = gl_VertexID % ").append(verticesPerRecord).append(";\n");
out.append("}\n");
return out.toString();
}
boolean needsFloatHelper = legacyGlsl && elements.stream()
.flatMap(e -> e.components().stream())
.anyMatch(c -> c.conversion() == Conversion.FLOAT_BITS);
out.append("uniform usamplerBuffer u_VertexData;\n\n");
if (needsFloatHelper) {
appendFloatHelper(out);
}
int vertexWords = layout.vertex().getStride() / 4;
out.append("void _vert_fetch() {\n");
out.append(" _vert_corner = gl_VertexID % ").append(verticesPerRecord).append(";\n");
if (layout.header() != null) {
int headerWords = layout.header().format().getStride() / 4;
int recordWords = headerWords + (verticesPerRecord * vertexWords);
out.append(" int _vf_record = (gl_VertexID / ").append(verticesPerRecord).append(") * ").append(recordWords).append(";\n");
out.append(" int _vf_vertex = _vf_record + ").append(headerWords).append(" + (_vert_corner * ").append(vertexWords).append(");\n");
} else {
out.append(" int _vf_vertex = gl_VertexID * ").append(vertexWords).append(";\n");
}
String fetch = legacyGlsl ? "texelFetchBuffer" : "texelFetch";
for (Scope scope : Scope.values()) {
var words = new TreeSet<Integer>();
for (Element element : elements) {
for (Component component : element.components()) {
if (component.scope() == scope) {
words.add(component.word());
}
}
}
for (int word : words) {
out.append(" uint ").append(wordName(scope, word)).append(" = ").append(fetch).append("(u_VertexData, ")
.append(scope == Scope.HEADER ? "_vf_record" : "_vf_vertex").append(" + ").append(word).append(").r;\n");
}
}
for (Element element : elements) {
out.append(" ").append(element.name()).append(" = ");
if (element.components().size() == 1) {
out.append(componentExpression(element.components().get(0), legacyGlsl));
} else {
out.append(element.glslType()).append('(');
for (int i = 0; i < element.components().size(); i++) {
if (i > 0) {
out.append(", ");
}
out.append(componentExpression(element.components().get(i), legacyGlsl));
}
out.append(')');
}
out.append(";\n");
}
out.append("}\n");
return out.toString();
}
/**
* Decodes IEEE 754 single-precision bits using only integer and float arithmetic, for GLSL without
* {@code uintBitsToFloat}. Exact for normal numbers; denormals become zero, and infinities and NaNs are not handled.
*/
private static void appendFloatHelper(StringBuilder out) {
out.append("float _vf_bits_to_float(uint b) {\n");
out.append(" uint e = (b >> 23u) & 0xFFu;\n");
out.append(" if (e == 0u) return 0.0;\n");
out.append(" float f = (1.0 + float(b & 0x7FFFFFu) / 8388608.0) * exp2(float(int(e) - 127));\n");
out.append(" return (b >> 31u) != 0u ? -f : f;\n");
out.append("}\n\n");
}
private static String wordName(Scope scope, int word) {
return (scope == Scope.HEADER ? "_vf_h" : "_vf_v") + word;
}
private static String componentExpression(Component component, boolean legacyGlsl) {
String word = wordName(component.scope(), component.word());
int bits = component.bits();
String unsigned;
if (bits == 32) {
unsigned = word;
} else if (component.shift() == 0) {
unsigned = "(" + word + " & " + mask(bits) + ")";
} else {
unsigned = "((" + word + " >> " + component.shift() + "u) & " + mask(bits) + ")";
}
return switch (component.conversion()) {
case UINT -> unsigned;
case SINT -> signedExpression(component, word);
case FLOAT_BITS -> (legacyGlsl ? "_vf_bits_to_float(" : "uintBitsToFloat(") + word + ")";
case UNORM -> "(float(" + unsigned + ") / " + ((1L << bits) - 1) + ".0)";
case SNORM -> "max(float(" + signedExpression(component, word) + ") / " + ((1L << (bits - 1)) - 1) + ".0, -1.0)";
case UINT_TO_FLOAT -> "float(" + unsigned + ")";
case SINT_TO_FLOAT -> "float(" + signedExpression(component, word) + ")";
};
}
/**
* Moves the component to the top of the word, then sign-extends it with an arithmetic right shift.
*/
private static String signedExpression(Component component, String word) {
int bits = component.bits();
if (bits == 32) {
return "int(" + word + ")";
}
int leftShift = 32 - component.shift() - bits;
String raised = leftShift == 0 ? word : "(" + word + " << " + leftShift + "u)";
return "(int(" + raised + ") >> " + (32 - bits) + ")";
}
private static String mask(int bits) {
return "0x" + Long.toHexString((1L << bits) - 1).toUpperCase() + "u";
}
}
@@ -0,0 +1,35 @@
package org.embeddedt.embeddium.impl.render.chunk.vertex.format;
import org.embeddedt.embeddium.impl.gl.device.RenderDevice;
/**
* How the vertex shader obtains vertex data.
*/
public enum VertexFetchMode {
/**
* Vertex data is bound as vertex attributes.
*/
ATTRIBUTES,
/**
* The vertex shader reads vertex data from a texture buffer over the region's geometry buffer.
*/
PULLED;
private static final boolean PREFER_PULLING = Boolean.getBoolean("celeritas.preferVertexPulling");
public static VertexFetchMode select(ChunkVertexLayout layout) {
if (!layout.supportsAttributeFetch()) {
if (!isPullingSupported()) {
throw new UnsupportedOperationException("Layout must be pulled by the vertex shader, which this device does not support: " + layout);
}
return PULLED;
}
return PREFER_PULLING && isPullingSupported() ? PULLED : ATTRIBUTES;
}
private static boolean isPullingSupported() {
return RenderDevice.INSTANCE.getDeviceFunctions().textureBufferFunctions().isSupported();
}
}
@@ -22,7 +22,7 @@ public class CompactChunkVertex implements ChunkVertexType {
public static final int STRIDE = 24; public static final int STRIDE = 24;
public static final ChunkVertexLayout LAYOUT = new ChunkVertexLayout.Attributes(VERTEX_FORMAT); public static final ChunkVertexLayout LAYOUT = ChunkVertexLayout.of(VERTEX_FORMAT);
private static final int POSITION_BITS = 21; private static final int POSITION_BITS = 21;
private static final int POSITION_LOW_BITS = 5; private static final int POSITION_LOW_BITS = 5;
@@ -23,7 +23,7 @@ public class VanillaLikeChunkVertex implements ChunkVertexType {
.addElement("a_RdhFactor", 28, GlVertexAttributeFormat.BYTE, 4, true, false) .addElement("a_RdhFactor", 28, GlVertexAttributeFormat.BYTE, 4, true, false)
.build(); .build();
public static final ChunkVertexLayout LAYOUT = new ChunkVertexLayout.Attributes(VERTEX_FORMAT); public static final ChunkVertexLayout LAYOUT = ChunkVertexLayout.of(VERTEX_FORMAT);
@Override @Override
public float getPositionScale() { public float getPositionScale() {
@@ -8,6 +8,8 @@ import org.embeddedt.embeddium.impl.gl.shader.ShaderConstants;
import org.embeddedt.embeddium.impl.gl.shader.ShaderParser; import org.embeddedt.embeddium.impl.gl.shader.ShaderParser;
import org.embeddedt.embeddium.impl.gl.shader.ShaderType; import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
import java.util.Map;
import java.util.function.Function;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import static org.taumc.celeritas.lwjgl.LWJGLServiceProvider.LWJGL; import static org.taumc.celeritas.lwjgl.LWJGLServiceProvider.LWJGL;
@@ -24,7 +26,22 @@ public class ShaderLoader {
* @return An OpenGL shader object compiled with the given user defines * @return An OpenGL shader object compiled with the given user defines
*/ */
public static GlShader loadShader(ShaderType type, String name, ShaderConstants constants) { public static GlShader loadShader(ShaderType type, String name, ShaderConstants constants) {
return new GlShader(type, name, downgradeIfNeeded(type, ShaderParser.parseShader(getShaderSource(name), ShaderLoader::getShaderSource, constants))); return loadShader(type, name, constants, Map.of());
}
/**
* Like {@link #loadShader(ShaderType, String, ShaderConstants)}, but imports of names in {@code generatedSources}
* resolve to the given source instead of the classpath.
*/
public static GlShader loadShader(ShaderType type, String name, ShaderConstants constants, Map<String, String> generatedSources) {
return new GlShader(type, name, downgradeIfNeeded(type, ShaderParser.parseShader(getShaderSource(name), sourceProvider(generatedSources), constants)));
}
public static Function<String, String> sourceProvider(Map<String, String> generatedSources) {
return name -> {
String generated = generatedSources.get(name);
return generated != null ? generated : getShaderSource(name);
};
} }
private static final Pattern VERSION_DIRECTIVE = Pattern.compile("^#version.*$", Pattern.MULTILINE); private static final Pattern VERSION_DIRECTIVE = Pattern.compile("^#version.*$", Pattern.MULTILINE);
@@ -76,7 +76,7 @@ void main() {
v_RdhFactor.rgb *= lightColor.rgb; v_RdhFactor.rgb *= lightColor.rgb;
#endif #endif
int corner = gl_VertexID & 3; int corner = _vert_corner;
v_QuadCoord = vec2(corner >= 2 ? 1.0 : 0.0, v_QuadCoord = vec2(corner >= 2 ? 1.0 : 0.0,
corner == 1 || corner == 2 ? 1.0 : 0.0); corner == 1 || corner == 2 ? 1.0 : 0.0);
v_TexCoord = _vert_tex_diffuse_coord; v_TexCoord = _vert_tex_diffuse_coord;
@@ -30,13 +30,17 @@ vec3 _get_draw_translation(uint pos) {
return _get_relative_chunk_coord(pos) * vec3(16.0); return _get_relative_chunk_coord(pos) * vec3(16.0);
} }
#ifdef USE_VERTEX_COMPRESSION #import <sodium:generated/vertex_fetch.glsl>
in uvec4 a_PosId;
in vec4 a_Color;
in uvec2 a_TexCoord;
in uint a_LightCoord;
in vec4 a_RdhFactor;
vec4 _get_rdh_factor() {
#ifdef VERT_HAS_a_RdhFactor
return a_RdhFactor;
#else
return vec4(0.0);
#endif
}
#ifdef USE_VERTEX_COMPRESSION
#if !defined(VERT_POS_SCALE) #if !defined(VERT_POS_SCALE)
#error "VERT_POS_SCALE not defined" #error "VERT_POS_SCALE not defined"
#elif !defined(VERT_POS_OFFSET) #elif !defined(VERT_POS_OFFSET)
@@ -46,6 +50,8 @@ in vec4 a_RdhFactor;
#endif #endif
void _vert_init() { void _vert_init() {
_vert_fetch();
uint packed_draw_params = (a_LightCoord & 0xFFFFu); uint packed_draw_params = (a_LightCoord & 0xFFFFu);
uvec3 position = (a_PosId.xyz << 5u) | ((uvec3(a_PosId.w) >> uvec3(0u, 5u, 10u)) & uvec3(0x1Fu)); uvec3 position = (a_PosId.xyz << 5u) | ((uvec3(a_PosId.w) >> uvec3(0u, 5u, 10u)) & uvec3(0x1Fu));
@@ -54,7 +60,7 @@ void _vert_init() {
_vert_position = (vec3(position) * VERT_POS_SCALE + VERT_POS_OFFSET); _vert_position = (vec3(position) * VERT_POS_SCALE + VERT_POS_OFFSET);
_vert_tex_diffuse_coord = (vec2(tex_coord) * VERT_TEX_SCALE); _vert_tex_diffuse_coord = (vec2(tex_coord) * VERT_TEX_SCALE);
_vert_color = a_Color; _vert_color = a_Color;
_vert_rdh_factor = a_RdhFactor; _vert_rdh_factor = _get_rdh_factor();
_material_params = (packed_draw_params) & 0xFu; _material_params = (packed_draw_params) & 0xFu;
_draw_id = (packed_draw_params >> 8) & 0xFFu; _draw_id = (packed_draw_params >> 8) & 0xFFu;
@@ -63,17 +69,13 @@ void _vert_init() {
#else #else
in vec3 a_PosId;
in vec4 a_Color;
in vec2 a_TexCoord;
in uint a_LightCoord;
in vec4 a_RdhFactor;
void _vert_init() { void _vert_init() {
_vert_fetch();
_vert_position = a_PosId; _vert_position = a_PosId;
_vert_tex_diffuse_coord = a_TexCoord; _vert_tex_diffuse_coord = a_TexCoord;
_vert_color = a_Color; _vert_color = a_Color;
_vert_rdh_factor = a_RdhFactor; _vert_rdh_factor = _get_rdh_factor();
uint packed_draw_params = (a_LightCoord & 0xFFFFu); uint packed_draw_params = (a_LightCoord & 0xFFFFu);
// Vertex Material // Vertex Material
@@ -0,0 +1,220 @@
package org.embeddedt.embeddium.impl.render.chunk.vertex.format;
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexAttribute;
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexAttributeFormat;
import org.embeddedt.embeddium.impl.gl.attribute.GlVertexFormat;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.VertexFetchGenerator.Component;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.VertexFetchGenerator.Element;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.VertexFetchGenerator.Scope;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.impl.CompactChunkVertex;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.impl.VanillaLikeChunkVertex;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Random;
import static org.junit.jupiter.api.Assertions.*;
class VertexFetchGeneratorTest {
/**
* A layout with a header, using every conversion the generator supports.
*/
private static final ChunkVertexLayout HEADER_LAYOUT = ChunkVertexLayout.withHeader(
GlVertexFormat.builder(12)
.addElement("a_PosId", 0, GlVertexAttributeFormat.FLOAT, 2, false, false)
.addElement("a_TexCoord", 8, GlVertexAttributeFormat.SHORT, 2, false, false)
.build(),
GlVertexFormat.builder(12)
.addElement("a_Color", 0, GlVertexAttributeFormat.UNSIGNED_SHORT, 2, true, false)
.addElement("a_RdhFactor", 4, GlVertexAttributeFormat.SHORT, 2, true, false)
.addElement("a_LightCoord", 8, GlVertexAttributeFormat.BYTE, 4, false, true)
.build(),
4);
@Test
void compactPlanMatchesAttributeFetch() {
assertPlanMatchesAttributeFetch(CompactChunkVertex.LAYOUT, 4);
}
@Test
void vanillaLikePlanMatchesAttributeFetch() {
assertPlanMatchesAttributeFetch(VanillaLikeChunkVertex.LAYOUT, 4);
}
@Test
void headerPlanMatchesAttributeFetch() {
assertPlanMatchesAttributeFetch(HEADER_LAYOUT, 4);
}
@Test
void rejectsComponentsStraddlingWords() {
assertThrows(IllegalArgumentException.class, () -> ChunkVertexLayout.of(GlVertexFormat.builder(8)
.addElement("a_PosId", 1, GlVertexAttributeFormat.UNSIGNED_SHORT, 2, false, true)
.build()));
}
@Test
void rejectsStridesThatAreNotWords() {
assertThrows(IllegalArgumentException.class, () -> ChunkVertexLayout.of(GlVertexFormat.builder(6)
.addElement("a_PosId", 0, GlVertexAttributeFormat.UNSIGNED_SHORT, 2, false, true)
.build()));
}
@Test
void headerLayoutsCannotUseAttributes() {
assertFalse(HEADER_LAYOUT.supportsAttributeFetch());
assertThrows(IllegalArgumentException.class,
() -> VertexFetchGenerator.generate(HEADER_LAYOUT, 4, VertexFetchMode.ATTRIBUTES, false));
}
@Test
void legacyPullingDecodesFloatsWithoutBitCasts() {
String source = VertexFetchGenerator.generate(VanillaLikeChunkVertex.LAYOUT, 4, VertexFetchMode.PULLED, true);
assertTrue(source.contains("texelFetchBuffer("));
assertTrue(source.contains("_vf_bits_to_float("));
assertFalse(source.contains("uintBitsToFloat"));
}
/**
* Mirrors the arithmetic of the generated {@code _vf_bits_to_float}, which must be exact for normal floats.
*/
@Test
void legacyFloatDecodeIsExactForNormals() {
var random = new Random(5678);
for (int i = 0; i < 1_000_000; i++) {
int bits = random.nextInt();
int exponent = (bits >>> 23) & 0xFF;
if (exponent == 0 || exponent == 0xFF) {
continue;
}
float magnitude = (1.0f + (float) (bits & 0x7FFFFF) / 8388608.0f) * Math.scalb(1.0f, exponent - 127);
float decoded = (bits >>> 31) != 0 ? -magnitude : magnitude;
assertEquals(Float.intBitsToFloat(bits), decoded);
}
}
@Test
void compactPulledSourceIsUnchanged() throws IOException {
assertEquals(readResource("compact_pulled.glsl"),
VertexFetchGenerator.generate(CompactChunkVertex.LAYOUT, 4, VertexFetchMode.PULLED, false));
}
@Test
void compactAttributeSourceIsUnchanged() throws IOException {
assertEquals(readResource("compact_attributes.glsl"),
VertexFetchGenerator.generate(CompactChunkVertex.LAYOUT, 4, VertexFetchMode.ATTRIBUTES, false));
}
/**
* Fills records with random bytes, then checks that every component the plan extracts from 32-bit words equals what
* attribute fetch reads from the attribute's own offset and type.
*/
private static void assertPlanMatchesAttributeFetch(ChunkVertexLayout layout, int verticesPerPrimitive) {
var header = layout.header();
int headerStride = header != null ? header.format().getStride() : 0;
int vertices = header != null ? header.verticesPerRecord() : verticesPerPrimitive;
int vertexStride = layout.vertex().getStride();
var random = new Random(1234);
var record = ByteBuffer.allocate(headerStride + vertices * vertexStride).order(ByteOrder.LITTLE_ENDIAN);
List<Element> plan = VertexFetchGenerator.plan(layout);
assertFalse(plan.isEmpty());
for (int iteration = 0; iteration < 1000; iteration++) {
random.nextBytes(record.array());
for (int corner = 0; corner < vertices; corner++) {
int vertexBase = headerStride + corner * vertexStride;
for (Element element : plan) {
boolean inHeader = element.components().get(0).scope() == Scope.HEADER;
GlVertexAttribute attribute = (inHeader ? header.format() : layout.vertex()).getAttribute(element.name());
int base = inHeader ? 0 : vertexBase;
for (int i = 0; i < element.components().size(); i++) {
Component component = element.components().get(i);
int word = record.getInt(base + component.word() * 4);
double expected = attributeFetch(record, base + attribute.getPointer() + i * attribute.getFormat().size(), attribute);
double actual = interpret(component, word);
assertEquals(expected, actual, "component " + i + " of " + element.name());
}
}
}
}
}
private static double attributeFetch(ByteBuffer record, int offset, GlVertexAttribute attribute) {
GlVertexAttributeFormat format = attribute.getFormat();
if (format.equals(GlVertexAttributeFormat.FLOAT)) {
return record.getFloat(offset);
}
long value;
int bits = format.size() * 8;
boolean signed = format.equals(GlVertexAttributeFormat.BYTE) || format.equals(GlVertexAttributeFormat.SHORT);
if (format.equals(GlVertexAttributeFormat.UNSIGNED_BYTE)) {
value = Byte.toUnsignedLong(record.get(offset));
} else if (format.equals(GlVertexAttributeFormat.BYTE)) {
value = record.get(offset);
} else if (format.equals(GlVertexAttributeFormat.UNSIGNED_SHORT)) {
value = Short.toUnsignedLong(record.getShort(offset));
} else if (format.equals(GlVertexAttributeFormat.SHORT)) {
value = record.getShort(offset);
} else if (format.equals(GlVertexAttributeFormat.UNSIGNED_INT)) {
value = Integer.toUnsignedLong(record.getInt(offset));
} else {
throw new IllegalArgumentException("Unhandled format " + format);
}
if (attribute.isIntType() || !attribute.isNormalized()) {
return attribute.isIntType() ? value : (float) value;
}
if (signed) {
return Math.max((float) value / (float) ((1L << (bits - 1)) - 1), -1.0f);
} else {
return (float) value / (float) ((1L << bits) - 1);
}
}
/**
* Evaluates a planned component the way the generated GLSL does.
*/
private static double interpret(Component component, int word) {
int bits = component.bits();
long unsigned = bits == 32 ? Integer.toUnsignedLong(word) : (word >>> component.shift()) & ((1L << bits) - 1);
long signed = bits == 32 ? word : (word << (32 - component.shift() - bits)) >> (32 - bits);
return switch (component.conversion()) {
case UINT -> unsigned;
case SINT -> signed;
case FLOAT_BITS -> Float.intBitsToFloat(word);
case UNORM -> (float) unsigned / (float) ((1L << bits) - 1);
case SNORM -> Math.max((float) signed / (float) ((1L << (bits - 1)) - 1), -1.0f);
case UINT_TO_FLOAT -> (float) unsigned;
case SINT_TO_FLOAT -> (float) signed;
};
}
private static String readResource(String name) throws IOException {
try (InputStream in = VertexFetchGeneratorTest.class.getResourceAsStream(name)) {
assertNotNull(in, "missing test resource " + name);
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
}
}
}
@@ -0,0 +1,17 @@
#define VERT_HAS_a_PosId
#define VERT_HAS_a_Color
#define VERT_HAS_a_TexCoord
#define VERT_HAS_a_LightCoord
#define VERT_HAS_a_RdhFactor
in uvec4 a_PosId;
in vec4 a_Color;
in uvec2 a_TexCoord;
in uint a_LightCoord;
in vec4 a_RdhFactor;
int _vert_corner;
void _vert_fetch() {
_vert_corner = gl_VertexID % 4;
}
@@ -0,0 +1,31 @@
#define VERT_HAS_a_PosId
#define VERT_HAS_a_Color
#define VERT_HAS_a_TexCoord
#define VERT_HAS_a_LightCoord
#define VERT_HAS_a_RdhFactor
uvec4 a_PosId;
vec4 a_Color;
uvec2 a_TexCoord;
uint a_LightCoord;
vec4 a_RdhFactor;
int _vert_corner;
uniform usamplerBuffer u_VertexData;
void _vert_fetch() {
_vert_corner = gl_VertexID % 4;
int _vf_vertex = gl_VertexID * 6;
uint _vf_v0 = texelFetch(u_VertexData, _vf_vertex + 0).r;
uint _vf_v1 = texelFetch(u_VertexData, _vf_vertex + 1).r;
uint _vf_v2 = texelFetch(u_VertexData, _vf_vertex + 2).r;
uint _vf_v3 = texelFetch(u_VertexData, _vf_vertex + 3).r;
uint _vf_v4 = texelFetch(u_VertexData, _vf_vertex + 4).r;
uint _vf_v5 = texelFetch(u_VertexData, _vf_vertex + 5).r;
a_PosId = uvec4((_vf_v0 & 0xFFFFu), ((_vf_v0 >> 16u) & 0xFFFFu), (_vf_v1 & 0xFFFFu), ((_vf_v1 >> 16u) & 0xFFFFu));
a_Color = vec4((float((_vf_v2 & 0xFFu)) / 255.0), (float(((_vf_v2 >> 8u) & 0xFFu)) / 255.0), (float(((_vf_v2 >> 16u) & 0xFFu)) / 255.0), (float(((_vf_v2 >> 24u) & 0xFFu)) / 255.0));
a_TexCoord = uvec2((_vf_v3 & 0xFFFFu), ((_vf_v3 >> 16u) & 0xFFFFu));
a_LightCoord = _vf_v4;
a_RdhFactor = vec4(max(float((int((_vf_v5 << 24u)) >> 24)) / 127.0, -1.0), max(float((int((_vf_v5 << 16u)) >> 24)) / 127.0, -1.0), max(float((int((_vf_v5 << 8u)) >> 24)) / 127.0, -1.0), max(float((int(_vf_v5) >> 24)) / 127.0, -1.0));
}
@@ -11,6 +11,7 @@ import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkFogMode;
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderOptions; import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderOptions;
import org.embeddedt.embeddium.impl.render.chunk.terrain.TerrainRenderPass; 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 net.irisshaders.iris.Iris; import net.irisshaders.iris.Iris;
import net.irisshaders.iris.gl.blending.BlendModeOverride; import net.irisshaders.iris.gl.blending.BlendModeOverride;
import net.irisshaders.iris.gl.blending.BufferBlendOverride; import net.irisshaders.iris.gl.blending.BufferBlendOverride;
@@ -91,7 +92,11 @@ public class IrisChunkProgramOverrides {
createdShaders.values().forEach(builder::attachShader); createdShaders.values().forEach(builder::attachShader);
int i = 0; int i = 0;
var vertexType = configuration.getVertexTypeForPass(pass.toTerrainPass(configuration)); var terrainPass = pass.toTerrainPass(configuration);
if (terrainPass.vertexFetchMode() != VertexFetchMode.ATTRIBUTES) {
throw new UnsupportedOperationException("Vertex pulling is not supported with shader packs");
}
var vertexType = configuration.getVertexTypeForPass(terrainPass);
for (var attr : ChunkVertexLayout.requireAttributes(vertexType.getLayout()).getAttributes()) { for (var attr : ChunkVertexLayout.requireAttributes(vertexType.getLayout()).getAttributes()) {
builder.bindAttribute(attr.getName(), i++); builder.bindAttribute(attr.getName(), i++);
} }
@@ -24,7 +24,7 @@ public class XHFPModelVertexType implements ChunkVertexType {
.addElement("at_midBlock", GlVertexFormat.NEXT_ALIGNED_POINTER, GlVertexAttributeFormat.BYTE, 4, false, false) .addElement("at_midBlock", GlVertexFormat.NEXT_ALIGNED_POINTER, GlVertexAttributeFormat.BYTE, 4, false, false)
.build(); .build();
public static final ChunkVertexLayout LAYOUT = new ChunkVertexLayout.Attributes(VERTEX_FORMAT); public static final ChunkVertexLayout LAYOUT = ChunkVertexLayout.of(VERTEX_FORMAT);
private static final int TEXTURE_MAX_VALUE = 32768; private static final int TEXTURE_MAX_VALUE = 32768;
@@ -10,7 +10,10 @@ import net.irisshaders.iris.shaderpack.preprocessor.JcppProcessor;
import org.apache.commons.lang3.mutable.MutableObject; import org.apache.commons.lang3.mutable.MutableObject;
import org.embeddedt.embeddium.impl.gl.shader.ShaderConstants; import org.embeddedt.embeddium.impl.gl.shader.ShaderConstants;
import org.embeddedt.embeddium.impl.gl.shader.ShaderType; import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.QuadPrimitiveType;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkMeshFormats; import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkMeshFormats;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.VertexFetchGenerator;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.VertexFetchMode;
import org.embeddedt.embeddium.impl.render.shader.ShaderLoader; import org.embeddedt.embeddium.impl.render.shader.ShaderLoader;
import org.taumc.glsl.ShaderParser; import org.taumc.glsl.ShaderParser;
import org.taumc.glsl.ShaderPrinter; import org.taumc.glsl.ShaderPrinter;
@@ -246,7 +249,9 @@ public class ShaderTransformer {
private static String computeCeleritasHeader(SodiumParameters parameters) { private static String computeCeleritasHeader(SodiumParameters parameters) {
var defines = parameters.vertexType.getDefines(); var defines = parameters.vertexType.getDefines();
String chunkVertexHeader = org.embeddedt.embeddium.impl.gl.shader.ShaderParser.parseShader(ShaderLoader.getShaderSource("sodium:include/chunk_vertex.glsl"), ShaderLoader::getShaderSource, var generatedSources = VertexFetchGenerator.sources(parameters.vertexType.getLayout(),
QuadPrimitiveType.TRIANGULATED.getVerticesPerPrimitive(), VertexFetchMode.ATTRIBUTES, false);
String chunkVertexHeader = org.embeddedt.embeddium.impl.gl.shader.ShaderParser.parseShader(ShaderLoader.getShaderSource("sodium:include/chunk_vertex.glsl"), ShaderLoader.sourceProvider(generatedSources),
ShaderConstants.builder().addAll(defines).build()); ShaderConstants.builder().addAll(defines).build());
return "\n\n" + chunkVertexHeader + "\n\n"; return "\n\n" + chunkVertexHeader + "\n\n";
} }