Vertex pulling #48

Manually merged
embeddedt merged 8 commits from vertex-pulling into stonecutter 2026-10-30 15:00:42 -04:00
4 changed files with 96 additions and 79 deletions
Showing only changes of commit e47c9ef588 - Show all commits

No files matched your search

@@ -13,7 +13,7 @@ import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexType;
public class XHFPModelVertexType implements ChunkVertexType { public class XHFPModelVertexType implements ChunkVertexType {
public static final ChunkVertexType BASE_VERTEX_TYPE = ChunkMeshFormats.VANILLA_LIKE; public static final ChunkVertexType BASE_VERTEX_TYPE = ChunkMeshFormats.VANILLA_LIKE;
public static final int HEADER_STRIDE = 20; public static final int HEADER_STRIDE = 8;
public static final int VERTEX_STRIDE = 28; public static final int VERTEX_STRIDE = 28;
/** /**
@@ -23,11 +23,8 @@ public class XHFPModelVertexType implements ChunkVertexType {
public static final String BLOCK_INFO = "celeritas_BlockInfo"; public static final String BLOCK_INFO = "celeritas_BlockInfo";
public static final GlVertexFormat HEADER_FORMAT = GlVertexFormat.builder(HEADER_STRIDE) public static final GlVertexFormat HEADER_FORMAT = GlVertexFormat.builder(HEADER_STRIDE)
.addElement("mc_midTexCoord", 0, GlVertexAttributeFormat.UNSIGNED_SHORT, 2, false, false) .addElement("mc_Entity", 0, GlVertexAttributeFormat.SHORT, 2, false, false)
.addElement("at_tangent", 4, GlVertexAttributeFormat.BYTE, 4, true, false) .addElement(BLOCK_INFO, 4, GlVertexAttributeFormat.UNSIGNED_INT, 1, false, true)
.addElement("iris_Normal", 8, GlVertexAttributeFormat.BYTE, 3, true, false)
.addElement("mc_Entity", 12, GlVertexAttributeFormat.SHORT, 2, false, false)
.addElement(BLOCK_INFO, 16, GlVertexAttributeFormat.UNSIGNED_INT, 1, false, true)
.build(); .build();
public static final GlVertexFormat VERTEX_FORMAT = GlVertexFormat.builder(VERTEX_STRIDE) public static final GlVertexFormat VERTEX_FORMAT = GlVertexFormat.builder(VERTEX_STRIDE)
@@ -36,16 +33,6 @@ public class XHFPModelVertexType implements ChunkVertexType {
public static final ChunkVertexLayout LAYOUT = ChunkVertexLayout.withHeader(VERTEX_FORMAT, HEADER_FORMAT, 4); public static final ChunkVertexLayout LAYOUT = ChunkVertexLayout.withHeader(VERTEX_FORMAT, HEADER_FORMAT, 4);
private static final int TEXTURE_MAX_VALUE = 32768;
public static final float MID_TEX_SCALE = 1.0f / TEXTURE_MAX_VALUE;
public static int encodeTexture(float u, float v) {
return ((Math.round(u * TEXTURE_MAX_VALUE) & 0xFFFF) << 0) |
((Math.round(v * TEXTURE_MAX_VALUE) & 0xFFFF) << 16);
}
@Override @Override
public float getTextureScale() { public float getTextureScale() {
return 1f; return 1f;
@@ -15,11 +15,8 @@ import org.embeddedt.embeddium.impl.modern.render.chunk.compile.pipeline.BlockRe
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.ChunkVertexEncoder; import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexEncoder;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.impl.VanillaLikeChunkVertex; import org.embeddedt.embeddium.impl.render.chunk.vertex.format.impl.VanillaLikeChunkVertex;
import net.irisshaders.iris.vertices.NormI8;
import net.irisshaders.iris.vertices.NormalHelper;
import org.embeddedt.embeddium.impl.render.texture.TextureAtlasExtended; import org.embeddedt.embeddium.impl.render.texture.TextureAtlasExtended;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.joml.Vector3f;
import org.lwjgl.system.MemoryUtil; import org.lwjgl.system.MemoryUtil;
import org.taumc.celeritas.shaders.CeleritasShaders; import org.taumc.celeritas.shaders.CeleritasShaders;
@@ -31,8 +28,6 @@ import static net.irisshaders.iris.compat.sodium.impl.vertex_format.terrain_xhfp
public class XHFPTerrainVertex implements ChunkVertexEncoder, ContextAwareChunkVertexEncoder { public class XHFPTerrainVertex implements ChunkVertexEncoder, ContextAwareChunkVertexEncoder {
private final QuadViewTerrain.QuadViewTerrainUnsafe quad = new QuadViewTerrain.QuadViewTerrainUnsafe();
private final Vector3f normal = new Vector3f();
private static final BlockState AIR = Blocks.AIR.defaultBlockState(); private static final BlockState AIR = Blocks.AIR.defaultBlockState();
@@ -54,10 +49,7 @@ public class XHFPTerrainVertex implements ChunkVertexEncoder, ContextAwareChunkV
private final FallbackTextureMaterials fallbackMaterials = WorldRenderingSettings.INSTANCE.getFallbackTextureMaterialMapping(); private final FallbackTextureMaterials fallbackMaterials = WorldRenderingSettings.INSTANCE.getFallbackTextureMaterialMapping();
private static final int MID_TEX_OFFSET = XHFPModelVertexType.HEADER_FORMAT.getAttribute("mc_midTexCoord").getPointer();
private static final int MC_ENTITY_OFFSET = XHFPModelVertexType.HEADER_FORMAT.getAttribute("mc_Entity").getPointer(); private static final int MC_ENTITY_OFFSET = XHFPModelVertexType.HEADER_FORMAT.getAttribute("mc_Entity").getPointer();
private static final int NORMAL_OFFSET = XHFPModelVertexType.HEADER_FORMAT.getAttribute("iris_Normal").getPointer();
private static final int TANGENT_OFFSET = XHFPModelVertexType.HEADER_FORMAT.getAttribute("at_tangent").getPointer();
private static final int BLOCK_INFO_OFFSET = XHFPModelVertexType.HEADER_FORMAT.getAttribute(XHFPModelVertexType.BLOCK_INFO).getPointer(); private static final int BLOCK_INFO_OFFSET = XHFPModelVertexType.HEADER_FORMAT.getAttribute(XHFPModelVertexType.BLOCK_INFO).getPointer();
private static final ClassValue<AtomicBoolean> GET_APPEARANCE_CRASHED = new ClassValue<>() { private static final ClassValue<AtomicBoolean> GET_APPEARANCE_CRASHED = new ClassValue<>() {
@@ -163,8 +155,6 @@ public class XHFPTerrainVertex implements ChunkVertexEncoder, ContextAwareChunkV
float midU = uSum / vertices.length; float midU = uSum / vertices.length;
float midV = vSum / vertices.length; float midV = vSum / vertices.length;
MemoryUtil.memPutInt(ptr + MID_TEX_OFFSET, XHFPModelVertexType.encodeTexture(midU, midV));
short blockId = this.blockId; short blockId = this.blockId;
if (blockId == -1 && fallbackMaterials != null) { if (blockId == -1 && fallbackMaterials != null) {
@@ -186,14 +176,6 @@ public class XHFPTerrainVertex implements ChunkVertexEncoder, ContextAwareChunkV
| (ignoreMidBlock ? 0 : 1 << 12) | (ignoreMidBlock ? 0 : 1 << 12)
| ((lightValue & 0xFF) << 16)); | ((lightValue & 0xFF) << 16));
// Implementation based on the algorithm found here:
// https://github.com/IrisShaders/ShaderDoc/blob/master/vertex-format-extensions.md#surface-normal-vector
quad.setup(vertexPtr - VERTEX_STRIDE, VERTEX_STRIDE);
NormalHelper.computeFaceNormal(normal, quad);
MemoryUtil.memPutInt(ptr + NORMAL_OFFSET, NormI8.pack(normal));
MemoryUtil.memPutInt(ptr + TANGENT_OFFSET, NormalHelper.computeTangent(normal.x, normal.y, normal.z, quad));
return vertexPtr; return vertexPtr;
} }
} }
@@ -15,6 +15,7 @@ import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.QuadPrimitiveTy
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.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.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;
@@ -295,7 +296,10 @@ public class ShaderTransformer {
QuadPrimitiveType.TRIANGULATED.getVerticesPerPrimitive(), parameters.vertexFetchMode, false, vertexInputTypes); QuadPrimitiveType.TRIANGULATED.getVerticesPerPrimitive(), parameters.vertexFetchMode, false, vertexInputTypes);
String chunkVertexHeader = org.embeddedt.embeddium.impl.gl.shader.ShaderParser.parseShader(ShaderLoader.getShaderSource("sodium:include/chunk_vertex.glsl"), ShaderLoader.sourceProvider(generatedSources), 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"; String quadInputFunctions = parameters.vertexFetchMode == VertexFetchMode.PULLED
? String.join("\n\n", QUAD_INPUT_FUNCTIONS) + "\n\n"
: "";
return "\n\n" + chunkVertexHeader + "\n\n" + quadInputFunctions;
} }
private static void patchVanillaCore(Transformer translationUnit, VanillaParameters parameters) { private static void patchVanillaCore(Transformer translationUnit, VanillaParameters parameters) {
@@ -321,46 +325,6 @@ public class ShaderTransformer {
} }
} }
public static void replaceMidTexCoord(Transformer translationUnit, float textureScale) {
int type = translationUnit.findType("mc_midTexCoord");
if (type != 0) {
translationUnit.removeVariable("mc_midTexCoord");
}
translationUnit.replaceExpression("mc_midTexCoord", "iris_MidTex");
String declaration;
String value;
switch (type) {
case GLSLLexer.FLOAT -> {
declaration = "float iris_MidTex;";
value = "(mc_midTexCoord.x * " + textureScale + ")";
}
case GLSLLexer.VEC2 -> {
declaration = "vec2 iris_MidTex;";
value = "(mc_midTexCoord.xy * " + textureScale + ")";
}
case GLSLLexer.VEC3 -> {
declaration = "vec3 iris_MidTex;";
value = "vec3(mc_midTexCoord.xy * " + textureScale + ", 0.0)";
}
case GLSLLexer.VEC4 -> {
declaration = "vec4 iris_MidTex;";
value = "vec4(mc_midTexCoord.xy * " + textureScale + ", 0.0, 1.0)";
}
default -> {
return;
}
}
// Assigned in main rather than initialized, since pulled vertex data is only available once _vert_init has run
translationUnit.injectVariable(declaration);
translationUnit.prependMain("iris_MidTex = " + value + ";");
translationUnit.injectVariable("in vec2 mc_midTexCoord;"); //TODO why is this inserted oddly?
}
/** /**
* XHFP doesn't store {@code at_midBlock}: it is derived from the block's position within its section, which the vertex * XHFP doesn't store {@code at_midBlock}: it is derived from the block's position within its section, which the vertex
* position is relative to, and stored in 1/64ths of a block with the block's light emission in {@code w}. * position is relative to, and stored in 1/64ths of a block with the block's light emission in {@code w}.
@@ -389,6 +353,92 @@ public class ShaderTransformer {
translationUnit.prependMain("at_midBlock = " + declaredType.adapt("iris_ComputeMidBlock()", VertexFetchGenerator.GlslType.parse("vec4")) + ";"); translationUnit.prependMain("at_midBlock = " + declaredType.adapt("iris_ComputeMidBlock()", VertexFetchGenerator.GlslType.parse("vec4")) + ";");
} }
/**
* Inputs that are constant across a quad and that pulled formats can compute from its corners, with the GLSL
* computing each.
*/
private static final Map<String, Map.Entry<VertexFetchGenerator.GlslType, String>> QUAD_INPUTS = Map.of(
"iris_Normal", Map.entry(VertexFetchGenerator.GlslType.parse("vec3"), "iris_ComputeFaceNormal()"),
"at_tangent", Map.entry(VertexFetchGenerator.GlslType.parse("vec4"), "iris_ComputeTangent()"),
"mc_midTexCoord", Map.entry(VertexFetchGenerator.GlslType.parse("vec2"), "iris_ComputeMidTexCoord()"));
/**
* Mirror NormalHelper#computeFaceNormal and NormalHelper#computeTangent, including leaving zero-length vectors as they
* are. Ordered so each function follows the ones it calls, which is why they go in the header rather than being
* injected: the transformer doesn't keep injected functions in order.
*/
private static final List<String> QUAD_INPUT_FUNCTIONS = List.of(
String.join("\n",
"vec3 iris_NormalizeOrZero(vec3 v) {",
" float lengthSquared = dot(v, v);",
" return lengthSquared == 0.0 ? v : v * inversesqrt(lengthSquared);",
"}"),
String.join("\n",
"vec3 iris_ComputeFaceNormal() {",
" vec3 p0 = _vert_corner_position(0);",
" vec3 p1 = _vert_corner_position(1);",
" vec3 p2 = _vert_corner_position(2);",
" vec3 p3 = _vert_corner_position(3);",
" return iris_NormalizeOrZero(cross(p2 - p0, p3 - p1));",
"}"),
String.join("\n",
"vec4 iris_ComputeTangent() {",
" vec3 normal = iris_ComputeFaceNormal();",
" vec3 p0 = _vert_corner_position(0);",
" vec2 t0 = _vert_corner_tex_coord(0);",
" vec3 edge1 = _vert_corner_position(1) - p0;",
" vec3 edge2 = _vert_corner_position(2) - p0;",
" vec2 delta1 = _vert_corner_tex_coord(1) - t0;",
" vec2 delta2 = _vert_corner_tex_coord(2) - t0;",
" float denom = delta1.x * delta2.y - delta2.x * delta1.y;",
" float f = denom == 0.0 ? 1.0 : 1.0 / denom;",
" vec3 tangent = iris_NormalizeOrZero(f * (delta2.y * edge1 - delta1.y * edge2));",
" vec3 bitangent = iris_NormalizeOrZero(f * (-delta2.x * edge1 + delta1.x * edge2));",
" return vec4(tangent, dot(bitangent, cross(tangent, normal)) < 0.0 ? -1.0 : 1.0);",
"}"),
String.join("\n",
"vec2 iris_ComputeMidTexCoord() {",
" vec2 sum = _vert_corner_tex_coord(0) + _vert_corner_tex_coord(1) + _vert_corner_tex_coord(2) + _vert_corner_tex_coord(3);",
" return sum * 0.25;",
"}"));
/**
* Pulled formats can read every corner of a quad, so inputs that are constant across it are computed rather than
* stored when the layout lacks them. Must run after {@link #patchMultiTexCoord3}, which can declare
* {@code mc_midTexCoord}, and before {@code _vert_init()} is prepended to main.
*/
public static void replaceQuadInputs(Transformer translationUnit, SodiumParameters parameters) {
if (parameters.vertexFetchMode != VertexFetchMode.PULLED) {
return;
}
var layout = parameters.vertexType.getLayout();
Set<String> storedNames = new HashSet<>();
layout.vertex().getAttributes().forEach(attribute -> storedNames.add(attribute.getName()));
if (layout.header() != null) {
layout.header().format().getAttributes().forEach(attribute -> storedNames.add(attribute.getName()));
}
for (var entry : QUAD_INPUTS.entrySet()) {
String name = entry.getKey();
if (storedNames.contains(name)) {
continue;
}
var declaredType = findInputType(translationUnit, name);
if (declaredType == null) {
continue;
}
translationUnit.removeVariable(name);
translationUnit.injectVariable(declaredType + " " + name + ";");
translationUnit.prependMain(name + " = " + declaredType.adapt(entry.getValue().getValue(), entry.getValue().getKey()) + ";");
}
}
private static VertexFetchGenerator.GlslType findInputType(Transformer translationUnit, String name) { private static VertexFetchGenerator.GlslType findInputType(Transformer translationUnit, String name) {
for (int qualifier : new int[] { GLSLLexer.IN, GLSLLexer.ATTRIBUTE }) { for (int qualifier : new int[] { GLSLLexer.IN, GLSLLexer.ATTRIBUTE }) {
var declaration = translationUnit.findQualifiers(qualifier).get(name); var declaration = translationUnit.findQualifiers(qualifier).get(name);
@@ -1,6 +1,5 @@
package net.irisshaders.iris.pipeline.foss_transform; package net.irisshaders.iris.pipeline.foss_transform;
import net.irisshaders.iris.compat.sodium.impl.vertex_format.terrain_xhfp.XHFPModelVertexType;
import net.irisshaders.iris.pipeline.transform.parameter.SodiumParameters; import net.irisshaders.iris.pipeline.transform.parameter.SodiumParameters;
import org.embeddedt.embeddium.impl.gl.shader.ShaderType; import org.embeddedt.embeddium.impl.gl.shader.ShaderType;
import org.taumc.glsl.Transformer; import org.taumc.glsl.Transformer;
@@ -28,8 +27,8 @@ public class SodiumTransformer {
translationUnit.rename("vaUV2", "_vert_tex_light_coord"); translationUnit.rename("vaUV2", "_vert_tex_light_coord");
translationUnit.replaceExpression("textureMatrix", "mat4(1.0f)"); translationUnit.replaceExpression("textureMatrix", "mat4(1.0f)");
replaceMidTexCoord(translationUnit, XHFPModelVertexType.MID_TEX_SCALE);
replaceMidBlock(translationUnit, parameters); replaceMidBlock(translationUnit, parameters);
replaceQuadInputs(translationUnit, parameters);
injectVertInit(translationUnit, parameters); injectVertInit(translationUnit, parameters);
} }
@@ -38,8 +37,6 @@ public class SodiumTransformer {
public static void patchSodium(Transformer translationUnit, SodiumParameters parameters) { public static void patchSodium(Transformer translationUnit, SodiumParameters parameters) {
commonPatch(translationUnit, parameters, false); commonPatch(translationUnit, parameters, false);
replaceMidTexCoord(translationUnit, XHFPModelVertexType.MID_TEX_SCALE);
translationUnit.replaceExpression("gl_TextureMatrix[0]", "mat4(1.0f)"); translationUnit.replaceExpression("gl_TextureMatrix[0]", "mat4(1.0f)");
translationUnit.replaceExpression("gl_TextureMatrix[1]", "iris_LightmapTextureMatrix"); translationUnit.replaceExpression("gl_TextureMatrix[1]", "iris_LightmapTextureMatrix");
translationUnit.injectFunction("uniform mat4 iris_LightmapTextureMatrix;"); translationUnit.injectFunction("uniform mat4 iris_LightmapTextureMatrix;");
@@ -100,6 +97,7 @@ public class SodiumTransformer {
translationUnit.replaceExpression("gl_Vertex", "getVertexPosition()"); translationUnit.replaceExpression("gl_Vertex", "getVertexPosition()");
replaceMidBlock(translationUnit, parameters); replaceMidBlock(translationUnit, parameters);
replaceQuadInputs(translationUnit, parameters);
// inject here so that _vert_position is available to the above. (injections // inject here so that _vert_position is available to the above. (injections
// inject in reverse order if performed piece-wise but in correct order if // inject in reverse order if performed piece-wise but in correct order if